1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
5 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Copyright : Written by and Copyright (C) 2001-2020 the
8 * Privoxy team. https://www.privoxy.org/
10 * Based on the Internet Junkbuster originally written
11 * by and Copyright (C) 1997 Anonymous Coders and
12 * Junkbusters Corporation. http://www.junkbusters.com
14 * This program is free software; you can redistribute it
15 * and/or modify it under the terms of the GNU General
16 * Public License as published by the Free Software
17 * Foundation; either version 2 of the License, or (at
18 * your option) any later version.
20 * This program is distributed in the hope that it will
21 * be useful, but WITHOUT ANY WARRANTY; without even the
22 * implied warranty of MERCHANTABILITY or FITNESS FOR A
23 * PARTICULAR PURPOSE. See the GNU General Public
24 * License for more details.
26 * The GNU General Public License should be included with
27 * this file. If not, you can view it at
28 * http://www.gnu.org/copyleft/gpl.html
29 * or write to the Free Software Foundation, Inc., 59
30 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 *********************************************************************/
39 #include <sys/types.h>
49 * Convince GNU's libc to provide a strptime prototype.
58 #define GZIP_IDENTIFIER_1 0x1f
59 #define GZIP_IDENTIFIER_2 0x8b
61 #define GZIP_FLAG_CHECKSUM 0x02
62 #define GZIP_FLAG_EXTRA_FIELDS 0x04
63 #define GZIP_FLAG_FILE_NAME 0x08
64 #define GZIP_FLAG_COMMENT 0x10
65 #define GZIP_FLAG_RESERVED_BITS 0xe0
68 #include <brotli/decode.h>
71 #if !defined(_WIN32) && !defined(__OS2__)
77 #ifdef FEATURE_PTHREAD
79 /* jcc.h is for mutex semapores only */
80 #endif /* def FEATURE_PTHREAD */
85 #include "jbsockets.h"
95 static char *get_header_line(struct iob *iob);
96 static jb_err scan_headers(struct client_state *csp);
97 static jb_err header_tagger(struct client_state *csp, char *header);
98 static jb_err parse_header_time(const char *header_time, time_t *result);
99 static jb_err parse_time_header(const char *header, time_t *result);
101 static jb_err crumble (struct client_state *csp, char **header);
102 static jb_err filter_header (struct client_state *csp, char **header);
103 static jb_err client_connection (struct client_state *csp, char **header);
104 static jb_err client_referrer (struct client_state *csp, char **header);
105 static jb_err client_uagent (struct client_state *csp, char **header);
106 static jb_err client_ua (struct client_state *csp, char **header);
107 static jb_err client_from (struct client_state *csp, char **header);
108 static jb_err client_send_cookie (struct client_state *csp, char **header);
109 static jb_err client_x_forwarded (struct client_state *csp, char **header);
110 static jb_err client_accept_encoding (struct client_state *csp, char **header);
111 static jb_err client_te (struct client_state *csp, char **header);
112 static jb_err client_max_forwards (struct client_state *csp, char **header);
113 static jb_err client_host (struct client_state *csp, char **header);
114 static jb_err client_if_modified_since (struct client_state *csp, char **header);
115 static jb_err client_accept_language (struct client_state *csp, char **header);
116 static jb_err client_if_none_match (struct client_state *csp, char **header);
117 static jb_err crunch_client_header (struct client_state *csp, char **header);
118 static jb_err client_x_filter (struct client_state *csp, char **header);
119 static jb_err client_range (struct client_state *csp, char **header);
120 static jb_err client_expect (struct client_state *csp, char **header);
121 static jb_err server_set_cookie (struct client_state *csp, char **header);
122 static jb_err server_connection (struct client_state *csp, char **header);
123 static jb_err server_content_type (struct client_state *csp, char **header);
124 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
125 static jb_err server_content_md5 (struct client_state *csp, char **header);
126 static jb_err server_content_encoding (struct client_state *csp, char **header);
127 static jb_err server_transfer_coding (struct client_state *csp, char **header);
128 static jb_err server_http (struct client_state *csp, char **header);
129 static jb_err crunch_server_header (struct client_state *csp, char **header);
130 static jb_err server_last_modified (struct client_state *csp, char **header);
131 static jb_err server_content_disposition(struct client_state *csp, char **header);
133 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
136 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
137 static jb_err server_save_content_length(struct client_state *csp, char **header);
138 static jb_err server_keep_alive(struct client_state *csp, char **header);
139 static jb_err server_proxy_connection(struct client_state *csp, char **header);
140 static jb_err client_keep_alive(struct client_state *csp, char **header);
141 static jb_err client_save_content_length(struct client_state *csp, char **header);
142 static jb_err client_proxy_connection(struct client_state *csp, char **header);
143 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
145 static jb_err client_host_adder (struct client_state *csp);
146 static jb_err client_xtra_adder (struct client_state *csp);
147 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
148 static jb_err client_connection_header_adder(struct client_state *csp);
149 static jb_err server_connection_adder(struct client_state *csp);
150 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
151 static jb_err server_proxy_connection_adder(struct client_state *csp);
152 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
153 static jb_err proxy_authentication(struct client_state *csp, char **header);
155 static jb_err create_forged_referrer(char **header, const char *hostport);
156 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
157 static jb_err handle_conditional_hide_referrer_parameter(char **header,
158 const char *host, const int parameter_conditional_block);
159 static void create_content_length_header(unsigned long long content_length,
160 char *header, size_t buffer_length);
163 * List of functions to run on a list of headers.
167 /** The header prefix to match */
170 /** The length of the prefix to match */
173 /** The function to apply to this line */
174 const parser_func_ptr parser;
177 static const struct parsers client_patterns[] = {
178 { "referer:", 8, client_referrer },
179 { "user-agent:", 11, client_uagent },
180 { "ua-", 3, client_ua },
181 { "from:", 5, client_from },
182 { "cookie:", 7, client_send_cookie },
183 { "x-forwarded-for:", 16, client_x_forwarded },
184 { "Accept-Encoding:", 16, client_accept_encoding },
185 { "TE:", 3, client_te },
186 { "Host:", 5, client_host },
187 { "if-modified-since:", 18, client_if_modified_since },
188 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
189 { "Keep-Alive:", 11, client_keep_alive },
190 { "Content-Length:", 15, client_save_content_length },
191 { "Proxy-Connection:", 17, client_proxy_connection },
193 { "Keep-Alive:", 11, crumble },
194 { "Proxy-Connection:", 17, crumble },
196 { "connection:", 11, client_connection },
197 { "max-forwards:", 13, client_max_forwards },
198 { "Accept-Language:", 16, client_accept_language },
199 { "if-none-match:", 14, client_if_none_match },
200 { "Range:", 6, client_range },
201 { "Request-Range:", 14, client_range },
202 { "If-Range:", 9, client_range },
203 { "X-Filter:", 9, client_x_filter },
204 { "Proxy-Authorization:", 20, proxy_authentication },
206 { "Transfer-Encoding:", 18, client_transfer_encoding },
208 { "Expect:", 7, client_expect },
209 { "*", 0, crunch_client_header },
210 { "*", 0, filter_header },
214 static const struct parsers server_patterns[] = {
215 { "HTTP/", 5, server_http },
216 { "set-cookie:", 11, server_set_cookie },
217 { "connection:", 11, server_connection },
218 { "Content-Type:", 13, server_content_type },
219 { "Content-MD5:", 12, server_content_md5 },
220 { "Content-Encoding:", 17, server_content_encoding },
221 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
222 { "Content-Length:", 15, server_save_content_length },
223 { "Keep-Alive:", 11, server_keep_alive },
224 { "Proxy-Connection:", 17, server_proxy_connection },
226 { "Keep-Alive:", 11, crumble },
227 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
228 { "Transfer-Encoding:", 18, server_transfer_coding },
229 { "content-disposition:", 20, server_content_disposition },
230 { "Last-Modified:", 14, server_last_modified },
231 { "Proxy-Authenticate:", 19, proxy_authentication },
232 { "*", 0, crunch_server_header },
233 { "*", 0, filter_header },
237 static const add_header_func_ptr add_client_headers[] = {
239 client_x_forwarded_for_adder,
241 client_connection_header_adder,
245 static const add_header_func_ptr add_server_headers[] = {
246 server_connection_adder,
247 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
248 server_proxy_connection_adder,
249 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
253 /*********************************************************************
255 * Function : flush_iob
257 * Description : Write any pending "buffered" content.
260 * 1 : fd = file descriptor of the socket to read
261 * 2 : iob = The I/O buffer to flush, usually csp->iob.
262 * 3 : delay = Number of milliseconds to delay the writes
264 * Returns : On success, the number of bytes written are returned (zero
265 * indicates nothing was written). On error, -1 is returned,
266 * and errno is set appropriately. If count is zero and the
267 * file descriptor refers to a regular file, 0 will be
268 * returned without causing any other effect. For a special
269 * file, the results are not portable.
271 *********************************************************************/
272 long flush_iob(jb_socket fd, struct iob *iob, unsigned int delay)
274 long len = iob->eod - iob->cur;
281 if (write_socket_delayed(fd, iob->cur, (size_t)len, delay))
285 iob->eod = iob->cur = iob->buf;
291 /*********************************************************************
293 * Function : add_to_iob
295 * Description : Add content to the buffer, expanding the
296 * buffer if necessary.
299 * 1 : iob = Destination buffer.
300 * 2 : buffer_limit = Limit to which the destination may grow
301 * 3 : src = holds the content to be added
302 * 4 : n = number of bytes to be added
304 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
305 * or buffer limit reached.
307 *********************************************************************/
308 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
310 size_t used, offset, need;
313 if (n <= 0) return JB_ERR_OK;
315 used = (size_t)(iob->eod - iob->buf);
316 offset = (size_t)(iob->cur - iob->buf);
317 need = used + (size_t)n + 1;
320 * If the buffer can't hold the new data, extend it first.
321 * Use the next power of two if possible, else use the actual need.
323 if (need > buffer_limit)
325 log_error(LOG_LEVEL_INFO,
326 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
328 return JB_ERR_MEMORY;
331 if (need > iob->size)
333 size_t want = iob->size ? iob->size : 512;
340 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
344 else if (NULL != (p = (char *)realloc(iob->buf, need)))
350 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
351 return JB_ERR_MEMORY;
354 /* Update the iob pointers */
355 iob->cur = p + offset;
360 /* copy the new data into the iob buffer */
361 memcpy(iob->eod, src, (size_t)n);
363 /* point to the end of the data */
366 /* null terminate == cheap insurance */
374 /*********************************************************************
376 * Function : clear_iob
378 * Description : Frees the memory allocated for an I/O buffer and
379 * resets the structure.
382 * 1 : iob = I/O buffer to clear.
386 *********************************************************************/
387 void clear_iob(struct iob *iob)
390 memset(iob, '\0', sizeof(*iob));
395 #ifdef FEATURE_BROTLI
396 /*********************************************************************
398 * Function : decompress_iob_with_brotli
400 * Description : Decompress buffered page using Brotli.
403 * 1 : csp = Current client state (buffers, headers, etc...)
405 * Returns : JB_ERR_OK on success,
406 * JB_ERR_MEMORY if out-of-memory limit reached, and
407 * JB_ERR_COMPRESS if error decompressing buffer.
409 *********************************************************************/
410 static jb_err decompress_iob_with_brotli(struct client_state *csp)
412 BrotliDecoderResult result;
413 char *decoded_buffer;
415 size_t decoded_buffer_size;
417 enum { MAX_COMPRESSION_FACTOR = 15 };
419 encoded_size = (size_t)(csp->iob->eod - csp->iob->cur);
421 * The BrotliDecoderDecompress() api is a bit unfortunate
422 * and requires the caller to reserve enough memory for
423 * the decompressed content. Hopefully reserving
424 * MAX_COMPRESSION_FACTOR times the original size is
425 * sufficient. If not, BrotliDecoderDecompress() will fail.
427 decoded_buffer_size = encoded_size * MAX_COMPRESSION_FACTOR;
429 if (decoded_buffer_size > csp->config->buffer_limit)
431 log_error(LOG_LEVEL_ERROR,
432 "Buffer limit reached before decompressing iob with Brotli");
433 return JB_ERR_MEMORY;
436 decoded_buffer = malloc(decoded_buffer_size);
437 if (decoded_buffer == NULL)
439 log_error(LOG_LEVEL_ERROR,
440 "Failed to allocate %d bytes for Brotli decompression",
441 decoded_buffer_size);
442 return JB_ERR_MEMORY;
445 decoded_size = decoded_buffer_size;
446 result = BrotliDecoderDecompress(encoded_size,
447 (const uint8_t *)csp->iob->cur, &decoded_size,
448 (uint8_t *)decoded_buffer);
449 if (result == BROTLI_DECODER_RESULT_SUCCESS)
452 * Update the iob, since the decompression was successful.
454 freez(csp->iob->buf);
455 csp->iob->buf = decoded_buffer;
456 csp->iob->cur = csp->iob->buf;
457 csp->iob->eod = csp->iob->cur + decoded_size;
458 csp->iob->size = decoded_buffer_size;
460 log_error(LOG_LEVEL_RE_FILTER,
461 "Decompression successful. Old size: %d, new size: %d.",
462 encoded_size, decoded_size);
468 log_error(LOG_LEVEL_ERROR, "Failed to decompress buffer with Brotli");
469 freez(decoded_buffer);
471 return JB_ERR_COMPRESS;
476 /*********************************************************************
478 * Function : decompress_iob
480 * Description : Decompress buffered page, expanding the
481 * buffer as necessary. csp->iob->cur
482 * should point to the the beginning of the
483 * compressed data block.
486 * 1 : csp = Current client state (buffers, headers, etc...)
488 * Returns : JB_ERR_OK on success,
489 * JB_ERR_MEMORY if out-of-memory limit reached, and
490 * JB_ERR_COMPRESS if error decompressing buffer.
492 *********************************************************************/
493 jb_err decompress_iob(struct client_state *csp)
495 char *buf; /* new, uncompressed buffer */
496 char *cur; /* Current iob position (to keep the original
497 * iob->cur unmodified if we return early) */
498 size_t bufsize; /* allocated size of the new buffer */
499 size_t old_size; /* Content size before decompression */
500 size_t skip_size; /* Number of bytes at the beginning of the iob
501 that we should NOT decompress. */
502 int status; /* return status of the inflate() call */
503 z_stream zstr; /* used by calls to zlib */
506 assert(csp->iob->cur - csp->iob->buf >= 0);
507 assert(csp->iob->eod - csp->iob->cur >= 0);
509 assert(csp->iob->cur - csp->iob->buf > 0);
510 assert(csp->iob->eod - csp->iob->cur > 0);
513 bufsize = csp->iob->size;
514 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
515 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
519 if (bufsize < (size_t)10)
522 * This is to protect the parsing of gzipped data,
523 * but it should(?) be valid for deflated data also.
525 log_error(LOG_LEVEL_ERROR,
526 "Insufficient data to start decompression. Bytes in buffer: %d",
527 csp->iob->eod - csp->iob->cur);
528 return JB_ERR_COMPRESS;
531 #ifdef FEATURE_BROTLI
532 if (csp->content_type & CT_BROTLI)
534 return decompress_iob_with_brotli(csp);
538 if (csp->content_type & CT_GZIP)
541 * Our task is slightly complicated by the facts that data
542 * compressed by gzip does not include a zlib header, and
543 * that there is no easily accessible interface in zlib to
544 * handle a gzip header. We strip off the gzip header by
545 * hand, and later inform zlib not to expect a header.
549 * Strip off the gzip header. Please see RFC 1952 for more
550 * explanation of the appropriate fields.
552 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
553 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
554 || (*cur++ != Z_DEFLATED))
556 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
557 return JB_ERR_COMPRESS;
562 if (flags & GZIP_FLAG_RESERVED_BITS)
564 /* The gzip header has reserved bits set; bail out. */
565 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
566 return JB_ERR_COMPRESS;
570 * Skip mtime (4 bytes), extra flags (1 byte)
571 * and OS type (1 byte).
575 /* Skip extra fields if necessary. */
576 if (flags & GZIP_FLAG_EXTRA_FIELDS)
579 * Skip a given number of bytes, specified
580 * as a 16-bit little-endian value.
582 * XXX: this code is untested and should probably be removed.
586 skip_bytes += *cur++ << 8;
589 * The number of bytes to skip should be positive
590 * and we'd like to stay in the buffer.
592 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
594 log_error(LOG_LEVEL_ERROR,
595 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
597 return JB_ERR_COMPRESS;
599 log_error(LOG_LEVEL_INFO,
600 "Skipping %d bytes for gzip compression. Does this sound right?",
605 /* Skip the filename if necessary. */
606 if (flags & GZIP_FLAG_FILE_NAME)
608 /* A null-terminated string is supposed to follow. */
609 while (*cur++ && (cur < csp->iob->eod));
612 /* Skip the comment if necessary. */
613 if (flags & GZIP_FLAG_COMMENT)
615 /* A null-terminated string is supposed to follow. */
616 while (*cur++ && (cur < csp->iob->eod));
619 /* Skip the CRC if necessary. */
620 if (flags & GZIP_FLAG_CHECKSUM)
625 if (cur >= csp->iob->eod)
628 * If the current position pointer reached or passed
629 * the buffer end, we were obviously tricked to skip
632 log_error(LOG_LEVEL_ERROR,
633 "Malformed gzip header detected. Aborting decompression.");
634 return JB_ERR_COMPRESS;
638 else if (csp->content_type & CT_DEFLATE)
641 * In theory (that is, according to RFC 1950), deflate-compressed
642 * data should begin with a two-byte zlib header and have an
643 * adler32 checksum at the end. It seems that in practice only
644 * the raw compressed data is sent. Note that this means that
645 * we are not RFC 1950-compliant here, but the advantage is that
646 * this actually works. :)
648 * We add a dummy null byte to tell zlib where the data ends,
649 * and later inform it not to expect a header.
651 * Fortunately, add_to_iob() has thoughtfully null-terminated
652 * the buffer; we can just increment the end pointer to include
659 log_error(LOG_LEVEL_ERROR,
660 "Unable to determine compression format for decompression");
661 return JB_ERR_COMPRESS;
664 /* Set up the fields required by zlib. */
665 zstr.next_in = (Bytef *)cur;
666 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
667 zstr.zalloc = Z_NULL;
669 zstr.opaque = Z_NULL;
672 * Passing -MAX_WBITS to inflateInit2 tells the library
673 * that there is no zlib header.
675 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
677 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
678 return JB_ERR_COMPRESS;
682 * Next, we allocate new storage for the inflated data.
683 * We don't modify the existing iob yet, so in case there
684 * is error in decompression we can recover gracefully.
686 buf = zalloc(bufsize);
689 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
690 return JB_ERR_MEMORY;
693 assert(bufsize >= skip_size);
694 memcpy(buf, csp->iob->buf, skip_size);
695 zstr.avail_out = (uInt)(bufsize - skip_size);
696 zstr.next_out = (Bytef *)buf + skip_size;
698 /* Try to decompress the whole stream in one shot. */
699 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
701 /* We need to allocate more memory for the output buffer. */
703 char *tmpbuf; /* used for realloc'ing the buffer */
704 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
706 if (0 == zstr.avail_in)
709 * If zlib wants more data then there's a problem, because
710 * the complete compressed file should have been buffered.
712 log_error(LOG_LEVEL_ERROR,
713 "Unexpected end of compressed iob. Using what we got so far.");
718 * If we reached the buffer limit and still didn't have enough
719 * memory, just give up. Due to the ceiling enforced by the next
720 * if block we could actually check for equality here, but as it
721 * can be easily mistaken for a bug we don't.
723 if (bufsize >= csp->config->buffer_limit)
725 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
727 return JB_ERR_MEMORY;
730 /* Try doubling the buffer size each time. */
733 /* Don't exceed the buffer limit. */
734 if (bufsize > csp->config->buffer_limit)
736 bufsize = csp->config->buffer_limit;
739 /* Try to allocate the new buffer. */
740 tmpbuf = realloc(buf, bufsize);
743 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
745 return JB_ERR_MEMORY;
749 char *oldnext_out = (char *)zstr.next_out;
752 * Update the fields for inflate() to use the new
753 * buffer, which may be in a location different from
756 zstr.avail_out += (uInt)(bufsize - oldbufsize);
757 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
760 * Compare with an uglier method of calculating these values
761 * that doesn't require the extra oldbufsize variable.
763 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
764 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
770 if (Z_STREAM_ERROR == inflateEnd(&zstr))
772 log_error(LOG_LEVEL_ERROR,
773 "Inconsistent stream state after decompression: %s", zstr.msg);
775 * XXX: Intentionally no return.
777 * According to zlib.h, Z_STREAM_ERROR is returned
778 * "if the stream state was inconsistent".
780 * I assume in this case inflate()'s status
781 * would also be something different than Z_STREAM_END
782 * so this check should be redundant, but lets see.
786 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
789 * We failed to decompress the stream and it's
790 * not simply because of missing data.
792 log_error(LOG_LEVEL_ERROR,
793 "Unexpected error while decompressing to the buffer (iob): %s",
795 return JB_ERR_COMPRESS;
799 * Finally, we can actually update the iob, since the
800 * decompression was successful. First, free the old
803 freez(csp->iob->buf);
805 /* Now, update the iob to use the new buffer. */
807 csp->iob->cur = csp->iob->buf + skip_size;
808 csp->iob->eod = (char *)zstr.next_out;
809 csp->iob->size = bufsize;
812 * Make sure the new uncompressed iob obeys some minimal
813 * consistency conditions.
815 if ((csp->iob->buf <= csp->iob->cur)
816 && (csp->iob->cur <= csp->iob->eod)
817 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
819 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
820 if (new_size > (size_t)0)
822 log_error(LOG_LEVEL_RE_FILTER,
823 "Decompression successful. Old size: %d, new size: %d.",
828 /* zlib thinks this is OK, so let's do the same. */
829 log_error(LOG_LEVEL_RE_FILTER,
830 "Decompression didn't result in any content.");
835 /* It seems that zlib did something weird. */
836 log_error(LOG_LEVEL_ERROR,
837 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
838 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
839 csp->iob->eod, csp->iob->buf + csp->iob->size);
840 return JB_ERR_COMPRESS;
846 #endif /* defined(FEATURE_ZLIB) */
849 /*********************************************************************
851 * Function : normalize_lws
853 * Description : Reduces unquoted linear whitespace in headers to
854 * a single space in accordance with RFC 7230 3.2.4.
855 * This simplifies parsing and filtering later on.
858 * 1 : header = A header with linear whitespace to reduce.
862 *********************************************************************/
863 static void normalize_lws(char *header)
869 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
873 while (privoxy_isspace(*q))
877 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
883 log_error(LOG_LEVEL_HEADER,
884 "Converting tab to space in '%s'", header);
889 char *end_of_token = strstr(p+1, "\"");
891 if (NULL != end_of_token)
893 /* Don't mess with quoted text. */
898 log_error(LOG_LEVEL_HEADER,
899 "Ignoring single quote in '%s'", header);
905 p = strchr(header, ':');
906 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
909 * There's still space before the colon.
917 /*********************************************************************
919 * Function : get_header
921 * Description : This (odd) routine will parse the csp->iob
922 * to get the next complete header.
925 * 1 : iob = The I/O buffer to parse, usually csp->iob.
927 * Returns : Any one of the following:
929 * 1) a pointer to a dynamically allocated string that contains a header line
930 * 2) NULL indicating that the end of the header was reached
931 * 3) "" indicating that the end of the iob was reached before finding
932 * a complete header line.
934 *********************************************************************/
935 char *get_header(struct iob *iob)
939 header = get_header_line(iob);
941 if ((header == NULL) || (*header == '\0'))
944 * No complete header read yet, tell the client.
949 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
952 * Header spans multiple lines, append the next one.
954 char *continued_header;
956 continued_header = get_header_line(iob);
957 if ((continued_header == NULL) || (*continued_header == '\0'))
960 * No complete header read yet, return what we got.
961 * XXX: Should "unread" header instead.
963 log_error(LOG_LEVEL_INFO,
964 "Failed to read a multi-line header properly: '%s'",
969 if (JB_ERR_OK != string_join(&header, continued_header))
971 log_error(LOG_LEVEL_FATAL,
972 "Out of memory while appending multiple headers.");
976 /* XXX: remove before next stable release. */
977 log_error(LOG_LEVEL_HEADER,
978 "Merged multiple header lines to: '%s'",
983 normalize_lws(header);
990 /*********************************************************************
992 * Function : get_header_line
994 * Description : This (odd) routine will parse the csp->iob
995 * to get the next header line.
998 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1000 * Returns : Any one of the following:
1002 * 1) a pointer to a dynamically allocated string that contains a header line
1003 * 2) NULL indicating that the end of the header was reached
1004 * 3) "" indicating that the end of the iob was reached before finding
1005 * a complete header line.
1007 *********************************************************************/
1008 static char *get_header_line(struct iob *iob)
1012 if ((iob->cur == NULL)
1013 || ((p = strchr(iob->cur, '\n')) == NULL))
1015 return(""); /* couldn't find a complete header */
1020 ret = strdup(iob->cur);
1023 /* FIXME No way to handle error properly */
1024 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1026 assert(ret != NULL);
1030 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1032 /* is this a blank line (i.e. the end of the header) ? */
1044 /*********************************************************************
1046 * Function : get_header_value
1048 * Description : Get the value of a given header from a chained list
1049 * of header lines or return NULL if no such header is
1050 * present in the list.
1053 * 1 : header_list = pointer to list
1054 * 2 : header_name = string with name of header to look for.
1055 * Trailing colon required, capitalization
1058 * Returns : NULL if not found, else value of header
1060 *********************************************************************/
1061 char *get_header_value(const struct list *header_list, const char *header_name)
1063 struct list_entry *cur_entry;
1067 assert(header_list);
1068 assert(header_name);
1069 length = strlen(header_name);
1071 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1075 if (!strncmpic(cur_entry->str, header_name, length))
1078 * Found: return pointer to start of value
1080 ret = cur_entry->str + length;
1081 while (*ret && privoxy_isspace(*ret)) ret++;
1095 /*********************************************************************
1097 * Function : scan_headers
1099 * Description : Scans headers, applies tags and updates action bits.
1102 * 1 : csp = Current client state (buffers, headers, etc...)
1104 * Returns : JB_ERR_OK
1106 *********************************************************************/
1107 static jb_err scan_headers(struct client_state *csp)
1109 struct list_entry *h; /* Header */
1110 jb_err err = JB_ERR_OK;
1112 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1114 /* Header crunch()ed in previous run? -> ignore */
1115 if (h->str == NULL) continue;
1116 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1117 err = header_tagger(csp, h->str);
1124 /*********************************************************************
1126 * Function : enforce_header_order
1128 * Description : Enforces a given header order.
1131 * 1 : headers = List of headers to order.
1132 * 2 : ordered_headers = List of ordered header names.
1136 *********************************************************************/
1137 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1139 struct list_entry *sorted_header;
1140 struct list new_headers[1];
1141 struct list_entry *header;
1143 init_list(new_headers);
1145 /* The request line is always the first "header" */
1147 assert(NULL != headers->first->str);
1148 enlist(new_headers, headers->first->str);
1149 freez(headers->first->str)
1151 /* Enlist the specified headers in the given order */
1153 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1154 sorted_header = sorted_header->next)
1156 const size_t sorted_header_length = strlen(sorted_header->str);
1157 for (header = headers->first; header != NULL; header = header->next)
1159 /* Header enlisted in previous run? -> ignore */
1160 if (header->str == NULL) continue;
1162 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1163 && (header->str[sorted_header_length] == ':'))
1165 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1166 if (JB_ERR_OK != enlist(new_headers, header->str))
1168 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1175 /* Enlist the rest of the headers behind the ordered ones */
1176 for (header = headers->first; header != NULL; header = header->next)
1178 /* Header enlisted in previous run? -> ignore */
1179 if (header->str == NULL) continue;
1181 log_error(LOG_LEVEL_HEADER,
1182 "Enlisting left-over header %s", header->str);
1183 if (JB_ERR_OK != enlist(new_headers, header->str))
1185 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1190 list_remove_all(headers);
1191 list_duplicate(headers, new_headers);
1192 list_remove_all(new_headers);
1198 /*********************************************************************
1202 * Description : add, delete or modify lines in the HTTP header streams.
1203 * On entry, it receives a linked list of headers space
1204 * that was allocated dynamically (both the list nodes
1205 * and the header contents).
1207 * As a side effect it frees the space used by the original
1211 * 1 : csp = Current client state (buffers, headers, etc...)
1212 * 2 : filter_server_headers = Boolean to switch between
1213 * server and header filtering.
1215 * Returns : JB_ERR_OK in case off success, or
1216 * JB_ERR_MEMORY on some out-of-memory errors, or
1217 * JB_ERR_PARSE in case of fatal parse errors.
1219 *********************************************************************/
1220 jb_err sed(struct client_state *csp, int filter_server_headers)
1222 /* XXX: use more descriptive names. */
1223 struct list_entry *p;
1224 const struct parsers *v;
1225 const add_header_func_ptr *f;
1226 jb_err err = JB_ERR_OK;
1230 if (filter_server_headers)
1232 v = server_patterns;
1233 f = add_server_headers;
1234 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1238 v = client_patterns;
1239 f = add_client_headers;
1240 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1243 while (v->str != NULL)
1245 for (p = csp->headers->first; p != NULL; p = p->next)
1247 /* Header crunch()ed in previous run? -> ignore */
1248 if (p->str == NULL) continue;
1250 /* Does the current parser handle this header? */
1251 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1252 (v->len == CHECK_EVERY_HEADER_REMAINING))
1254 err = v->parser(csp, &(p->str));
1255 if (err != JB_ERR_OK)
1264 /* place additional headers on the csp->headers list */
1265 while ((err == JB_ERR_OK) && (*f))
1271 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1273 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1280 #ifdef FEATURE_HTTPS_INSPECTION
1281 /*********************************************************************
1283 * Function : sed_https
1285 * Description : add, delete or modify lines in the HTTPS client
1286 * header streams. Wrapper around sed().
1289 * 1 : csp = Current client state (buffers, headers, etc...)
1291 * Returns : JB_ERR_OK in case off success, or
1292 * JB_ERR_MEMORY on some out-of-memory errors, or
1293 * JB_ERR_PARSE in case of fatal parse errors.
1295 *********************************************************************/
1296 jb_err sed_https(struct client_state *csp)
1299 struct list headers;
1302 * Temporarily replace csp->headers with csp->https_headers
1303 * to trick sed() into filtering the https headers.
1305 headers.first = csp->headers->first;
1306 headers.last = csp->headers->last;
1307 csp->headers->first = csp->https_headers->first;
1308 csp->headers->last = csp->https_headers->last;
1311 * Start with fresh tags. Already existing tags may
1312 * be set again. This is necessary to overrule
1313 * URL-based patterns.
1315 destroy_list(csp->tags);
1318 * We want client header filters and taggers
1319 * so temporarily remove the flag.
1321 csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1322 err = sed(csp, FILTER_CLIENT_HEADERS);
1323 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1326 * Update the last header which may have changed
1327 * due to header additions,
1329 csp->https_headers->last = csp->headers->last;
1331 csp->headers->first = headers.first;
1332 csp->headers->last = headers.last;
1336 #endif /* def FEATURE_HTTPS_INSPECTION */
1339 /*********************************************************************
1341 * Function : update_server_headers
1343 * Description : Updates server headers after the body has been modified.
1346 * 1 : csp = Current client state (buffers, headers, etc...)
1348 * Returns : JB_ERR_OK in case off success, or
1349 * JB_ERR_MEMORY on out-of-memory error.
1351 *********************************************************************/
1352 jb_err update_server_headers(struct client_state *csp)
1354 jb_err err = JB_ERR_OK;
1356 static const struct parsers server_patterns_light[] = {
1357 { "Content-Length:", 15, server_adjust_content_length },
1358 { "Transfer-Encoding:", 18, server_transfer_coding },
1360 { "Content-Encoding:", 17, server_adjust_content_encoding },
1361 #endif /* def FEATURE_ZLIB */
1365 if (strncmpic(csp->http->cmd, "HEAD", 4))
1367 const struct parsers *v;
1368 struct list_entry *p;
1370 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1372 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1374 /* Header crunch()ed in previous run? -> ignore */
1375 if (p->str == NULL) continue;
1377 /* Does the current parser handle this header? */
1378 if (strncmpic(p->str, v->str, v->len) == 0)
1380 err = v->parser(csp, (char **)&(p->str));
1386 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1387 if ((JB_ERR_OK == err)
1388 && (csp->flags & CSP_FLAG_MODIFIED)
1389 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1390 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1394 create_content_length_header(csp->content_length, header, sizeof(header));
1395 err = enlist(csp->headers, header);
1396 if (JB_ERR_OK == err)
1398 log_error(LOG_LEVEL_HEADER,
1399 "Content modified with no Content-Length header set. "
1400 "Created: %s.", header);
1401 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1404 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1406 #ifdef FEATURE_COMPRESSION
1407 if ((JB_ERR_OK == err)
1408 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1410 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1411 if (JB_ERR_OK == err)
1413 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1422 /*********************************************************************
1424 * Function : header_tagger
1426 * Description : Executes all text substitutions from applying
1427 * tag actions and saves the result as tag.
1429 * XXX: Shares enough code with filter_header() and
1430 * pcrs_filter_response() to warrant some helper functions.
1433 * 1 : csp = Current client state (buffers, headers, etc...)
1434 * 2 : header = Header that is used as tagger input
1436 * Returns : JB_ERR_OK on success and always succeeds
1438 *********************************************************************/
1439 static jb_err header_tagger(struct client_state *csp, char *header)
1441 enum filter_type wanted_filter_type;
1442 int multi_action_index;
1445 struct re_filterfile_spec *b;
1446 struct list_entry *tag_name;
1448 const size_t header_length = strlen(header);
1450 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1452 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1453 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1457 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1458 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1461 if (list_is_empty(csp->action->multi[multi_action_index])
1462 || filters_available(csp) == FALSE)
1464 /* Return early if no taggers apply or if none are available. */
1468 /* Execute all applying taggers */
1469 for (tag_name = csp->action->multi[multi_action_index]->first;
1470 NULL != tag_name; tag_name = tag_name->next)
1472 char *modified_tag = NULL;
1474 size_t size = header_length;
1477 b = get_filter(csp, tag_name->str, wanted_filter_type);
1483 joblist = b->joblist;
1485 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1487 if (NULL == joblist)
1489 log_error(LOG_LEVEL_RE_FILTER,
1490 "Tagger %s has empty joblist. Nothing to do.", b->name);
1494 /* execute their pcrs_joblist on the header. */
1495 for (job = joblist; NULL != job; job = job->next)
1497 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1501 /* Success, continue with the modified version. */
1510 /* Tagger doesn't match */
1513 /* Regex failure, log it but continue anyway. */
1514 assert(NULL != header);
1515 log_error(LOG_LEVEL_ERROR,
1516 "Problems with tagger \'%s\' and header \'%s\': %s",
1517 b->name, *header, pcrs_strerror(hits));
1519 freez(modified_tag);
1523 if (b->dynamic) pcrs_free_joblist(joblist);
1525 /* If this tagger matched */
1531 * There is no technical limitation which makes
1532 * it impossible to use empty tags, but I assume
1533 * no one would do it intentionally.
1536 log_error(LOG_LEVEL_INFO,
1537 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1541 if (!list_contains_item(csp->tags, tag))
1543 if (JB_ERR_OK != enlist(csp->tags, tag))
1545 log_error(LOG_LEVEL_ERROR,
1546 "Insufficient memory to add tag \'%s\', "
1547 "based on tagger \'%s\' and header \'%s\'",
1548 tag, b->name, *header);
1552 char *action_message;
1554 * update the action bits right away, to make
1555 * tagging based on tags set by earlier taggers
1556 * of the same kind possible.
1558 if (update_action_bits_for_tag(csp, tag))
1560 action_message = "Action bits updated accordingly.";
1564 action_message = "No action bits update necessary.";
1567 log_error(LOG_LEVEL_HEADER,
1568 "Tagger \'%s\' added tag \'%s\'. %s",
1569 b->name, tag, action_message);
1574 /* XXX: Is this log-worthy? */
1575 log_error(LOG_LEVEL_HEADER,
1576 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1586 /* here begins the family of parser functions that reformat header lines */
1588 /*********************************************************************
1590 * Function : filter_header
1592 * Description : Executes all text substitutions from all applying
1593 * +(server|client)-header-filter actions on the header.
1594 * Most of the code was copied from pcrs_filter_response,
1595 * including the rather short variable names
1598 * 1 : csp = Current client state (buffers, headers, etc...)
1599 * 2 : header = On input, pointer to header to modify.
1600 * On output, pointer to the modified header, or NULL
1601 * to remove the header. This function frees the
1602 * original string if necessary.
1604 * Returns : JB_ERR_OK on success and always succeeds
1606 *********************************************************************/
1607 static jb_err filter_header(struct client_state *csp, char **header)
1611 size_t size = strlen(*header);
1613 char *newheader = NULL;
1616 struct re_filterfile_spec *b;
1617 struct list_entry *filtername;
1619 enum filter_type wanted_filter_type;
1620 int multi_action_index;
1622 if (csp->flags & CSP_FLAG_NO_FILTERING)
1627 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1629 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1630 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1634 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1635 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1638 if (list_is_empty(csp->action->multi[multi_action_index])
1639 || filters_available(csp) == FALSE)
1641 /* Return early if no filters apply or if none are available. */
1645 /* Execute all applying header filters */
1646 for (filtername = csp->action->multi[multi_action_index]->first;
1647 filtername != NULL; filtername = filtername->next)
1649 int current_hits = 0;
1652 b = get_filter(csp, filtername->str, wanted_filter_type);
1658 joblist = b->joblist;
1660 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1662 if (NULL == joblist)
1664 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1668 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1669 *header, size, b->name);
1671 /* Apply all jobs from the joblist */
1672 for (job = joblist; NULL != job; job = job->next)
1674 matches = pcrs_execute(job, *header, size, &newheader, &size);
1677 current_hits += matches;
1678 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1680 *header = newheader;
1682 else if (0 == matches)
1684 /* Filter doesn't change header */
1690 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1691 *header, b->name, pcrs_strerror(matches));
1692 if (newheader != NULL)
1694 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1700 if (b->dynamic) pcrs_free_joblist(joblist);
1702 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1703 hits += current_hits;
1707 * Additionally checking for hits is important because if
1708 * the continue hack is triggered, server headers can
1709 * arrive empty to separate multiple heads from each other.
1711 if ((0 == size) && hits)
1713 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1721 /*********************************************************************
1723 * Function : server_connection
1725 * Description : Makes sure a proper "Connection:" header is
1726 * set and signals connection_header_adder to
1730 * 1 : csp = Current client state (buffers, headers, etc...)
1731 * 2 : header = On input, pointer to header to modify.
1732 * On output, pointer to the modified header, or NULL
1733 * to remove the header. This function frees the
1734 * original string if necessary.
1736 * Returns : JB_ERR_OK on success.
1738 *********************************************************************/
1739 static jb_err server_connection(struct client_state *csp, char **header)
1741 if (!strcmpic(*header, "Connection: keep-alive")
1742 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1743 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1747 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1748 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1750 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1753 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1755 log_error(LOG_LEVEL_HEADER,
1756 "Keeping the server header '%s' around.", *header);
1759 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1761 char *old_header = *header;
1763 *header = strdup_or_die("Connection: close");
1764 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1769 /* Signal server_connection_adder() to return early. */
1770 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1776 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1777 /*********************************************************************
1779 * Function : server_keep_alive
1781 * Description : Stores the server's keep alive timeout.
1784 * 1 : csp = Current client state (buffers, headers, etc...)
1785 * 2 : header = On input, pointer to header to modify.
1786 * On output, pointer to the modified header, or NULL
1787 * to remove the header. This function frees the
1788 * original string if necessary.
1790 * Returns : JB_ERR_OK.
1792 *********************************************************************/
1793 static jb_err server_keep_alive(struct client_state *csp, char **header)
1795 unsigned int keep_alive_timeout;
1796 const char *timeout_position = strstr(*header, "timeout=");
1798 if ((NULL == timeout_position)
1799 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1801 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1805 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1807 log_error(LOG_LEVEL_HEADER,
1808 "Reducing keep-alive timeout from %u to %u.",
1809 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1810 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1814 /* XXX: Is this log worthy? */
1815 log_error(LOG_LEVEL_HEADER,
1816 "Server keep-alive timeout is %u. Sticking with %u.",
1817 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1819 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1828 /*********************************************************************
1830 * Function : server_proxy_connection
1832 * Description : Figures out whether or not we should add a
1833 * Proxy-Connection header.
1836 * 1 : csp = Current client state (buffers, headers, etc...)
1837 * 2 : header = On input, pointer to header to modify.
1838 * On output, pointer to the modified header, or NULL
1839 * to remove the header. This function frees the
1840 * original string if necessary.
1842 * Returns : JB_ERR_OK.
1844 *********************************************************************/
1845 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1847 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1852 /*********************************************************************
1854 * Function : proxy_authentication
1856 * Description : Removes headers that are relevant for proxy
1857 * authentication unless forwarding them has
1858 * been explicitly requested.
1861 * 1 : csp = Current client state (buffers, headers, etc...)
1862 * 2 : header = On input, pointer to header to modify.
1863 * On output, pointer to the modified header, or NULL
1864 * to remove the header. This function frees the
1865 * original string if necessary.
1867 * Returns : JB_ERR_OK.
1869 *********************************************************************/
1870 static jb_err proxy_authentication(struct client_state *csp, char **header)
1872 if ((csp->config->feature_flags &
1873 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1874 log_error(LOG_LEVEL_HEADER,
1875 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1882 /*********************************************************************
1884 * Function : client_keep_alive
1886 * Description : Stores the client's keep alive timeout.
1889 * 1 : csp = Current client state (buffers, headers, etc...)
1890 * 2 : header = On input, pointer to header to modify.
1891 * On output, pointer to the modified header, or NULL
1892 * to remove the header. This function frees the
1893 * original string if necessary.
1895 * Returns : JB_ERR_OK.
1897 *********************************************************************/
1898 static jb_err client_keep_alive(struct client_state *csp, char **header)
1900 unsigned int keep_alive_timeout;
1901 char *timeout_position;
1903 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1905 log_error(LOG_LEVEL_HEADER,
1906 "keep-alive support is disabled. Crunching: %s.", *header);
1911 /* Check for parameter-less format "Keep-Alive: 100" */
1912 timeout_position = strstr(*header, ": ");
1913 if ((NULL == timeout_position)
1914 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1916 /* Assume parameter format "Keep-Alive: timeout=100" */
1917 timeout_position = strstr(*header, "timeout=");
1918 if ((NULL == timeout_position)
1919 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1921 log_error(LOG_LEVEL_HEADER,
1922 "Couldn't parse: '%s'. Using default timeout %u",
1923 *header, csp->config->keep_alive_timeout);
1930 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1932 log_error(LOG_LEVEL_HEADER,
1933 "Reducing keep-alive timeout from %u to %u.",
1934 csp->config->keep_alive_timeout, keep_alive_timeout);
1935 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1939 /* XXX: Is this log worthy? */
1940 log_error(LOG_LEVEL_HEADER,
1941 "Client keep-alive timeout is %u. Sticking with %u.",
1942 keep_alive_timeout, csp->config->keep_alive_timeout);
1950 /*********************************************************************
1952 * Function : get_content_length
1954 * Description : Gets the content length specified in a
1955 * Content-Length header.
1958 * 1 : header_value = The Content-Length header value.
1959 * 2 : length = Storage to return the value.
1961 * Returns : JB_ERR_OK on success, or
1962 * JB_ERR_PARSE if no value is recognized.
1964 *********************************************************************/
1965 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1968 #if SIZEOF_LONG_LONG < 8
1969 #error sizeof(unsigned long long) too small
1971 if (1 != sscanf(header_value, "%I64u", length))
1973 if (1 != sscanf(header_value, "%llu", length))
1976 return JB_ERR_PARSE;
1983 /*********************************************************************
1985 * Function : client_save_content_length
1987 * Description : Save the Content-Length sent by the client.
1990 * 1 : csp = Current client state (buffers, headers, etc...)
1991 * 2 : header = On input, pointer to header to modify.
1992 * On output, pointer to the modified header, or NULL
1993 * to remove the header. This function frees the
1994 * original string if necessary.
1996 * Returns : JB_ERR_OK on success, or
1997 * JB_ERR_MEMORY on out-of-memory error.
1999 *********************************************************************/
2000 static jb_err client_save_content_length(struct client_state *csp, char **header)
2002 unsigned long long content_length = 0;
2003 const char *header_value;
2005 assert(*(*header+14) == ':');
2007 header_value = *header + 15;
2008 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2010 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2015 csp->expected_client_content_length = content_length;
2020 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2024 /*********************************************************************
2026 * Function : client_connection
2028 * Description : Makes sure a proper "Connection:" header is
2029 * set and signals connection_header_adder
2033 * 1 : csp = Current client state (buffers, headers, etc...)
2034 * 2 : header = On input, pointer to header to modify.
2035 * On output, pointer to the modified header, or NULL
2036 * to remove the header. This function frees the
2037 * original string if necessary.
2039 * Returns : JB_ERR_OK on success.
2041 *********************************************************************/
2042 static jb_err client_connection(struct client_state *csp, char **header)
2044 static const char connection_close[] = "Connection: close";
2046 if (!strcmpic(*header, connection_close))
2048 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2049 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2050 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2052 if (!strcmpic(csp->http->version, "HTTP/1.1"))
2054 log_error(LOG_LEVEL_HEADER,
2055 "Removing \'%s\' to imply keep-alive.", *header);
2058 * While we imply keep-alive to the server,
2059 * we have to remember that the client didn't.
2061 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2065 char *old_header = *header;
2067 *header = strdup_or_die("Connection: keep-alive");
2068 log_error(LOG_LEVEL_HEADER,
2069 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2075 log_error(LOG_LEVEL_HEADER,
2076 "Keeping the client header '%s' around. "
2077 "The connection will not be kept alive.",
2079 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2082 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2083 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2085 log_error(LOG_LEVEL_HEADER,
2086 "Keeping the client header '%s' around. "
2087 "The server connection will be kept alive if possible.",
2089 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2090 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2094 char *old_header = *header;
2096 *header = strdup_or_die(connection_close);
2097 log_error(LOG_LEVEL_HEADER,
2098 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2102 /* Signal client_connection_header_adder() to return early. */
2103 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2109 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2110 /*********************************************************************
2112 * Function : client_proxy_connection
2114 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
2115 * appropriate and removes the Proxy-Connection
2119 * 1 : csp = Current client state (buffers, headers, etc...)
2120 * 2 : header = On input, pointer to header to modify.
2121 * On output, pointer to the modified header, or NULL
2122 * to remove the header. This function frees the
2123 * original string if necessary.
2125 * Returns : JB_ERR_OK
2127 *********************************************************************/
2128 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2130 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2131 && (csp->http->ssl == 0)
2132 && (NULL == strstr(*header, "close")))
2134 log_error(LOG_LEVEL_HEADER,
2135 "The client connection can be kept alive due to: %s", *header);
2136 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2138 crumble(csp, header);
2142 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2145 /*********************************************************************
2147 * Function : client_transfer_encoding
2149 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2150 * the request body is "chunked"
2152 * XXX: Currently not called through sed() as we
2153 * need the flag earlier on. Should be fixed.
2156 * 1 : csp = Current client state (buffers, headers, etc...)
2157 * 2 : header = On input, pointer to header to modify.
2158 * On output, pointer to the modified header, or NULL
2159 * to remove the header. This function frees the
2160 * original string if necessary.
2162 * Returns : JB_ERR_OK on success, or
2164 *********************************************************************/
2165 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2167 if (strstr(*header, "chunked"))
2169 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2170 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2177 /*********************************************************************
2179 * Function : client_expect
2181 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2182 * if the Expect header value is unsupported.
2184 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2185 * MAY and a RFC 2616 (obsolete) MUST.
2188 * 1 : csp = Current client state (buffers, headers, etc...)
2189 * 2 : header = On input, pointer to header to modify.
2190 * On output, pointer to the modified header, or NULL
2191 * to remove the header. This function frees the
2192 * original string if necessary.
2194 * Returns : JB_ERR_OK on success, or
2196 *********************************************************************/
2197 jb_err client_expect(struct client_state *csp, char **header)
2199 if (0 != strcmpic(*header, "Expect: 100-continue"))
2201 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2202 log_error(LOG_LEVEL_HEADER,
2203 "Unsupported client expectaction: %s", *header);
2211 /*********************************************************************
2213 * Function : crumble
2215 * Description : This is called if a header matches a pattern to "crunch"
2218 * 1 : csp = Current client state (buffers, headers, etc...)
2219 * 2 : header = On input, pointer to header to modify.
2220 * On output, pointer to the modified header, or NULL
2221 * to remove the header. This function frees the
2222 * original string if necessary.
2224 * Returns : JB_ERR_OK on success, or
2225 * JB_ERR_MEMORY on out-of-memory error.
2227 *********************************************************************/
2228 static jb_err crumble(struct client_state *csp, char **header)
2231 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2237 /*********************************************************************
2239 * Function : crunch_server_header
2241 * Description : Crunch server header if it matches a string supplied by the
2242 * user. Called from `sed'.
2245 * 1 : csp = Current client state (buffers, headers, etc...)
2246 * 2 : header = On input, pointer to header to modify.
2247 * On output, pointer to the modified header, or NULL
2248 * to remove the header. This function frees the
2249 * original string if necessary.
2251 * Returns : JB_ERR_OK on success and always succeeds
2253 *********************************************************************/
2254 static jb_err crunch_server_header(struct client_state *csp, char **header)
2256 const char *crunch_pattern;
2258 /* Do we feel like crunching? */
2259 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2261 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2263 /* Is the current header the lucky one? */
2264 if (strstr(*header, crunch_pattern))
2266 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2275 /*********************************************************************
2277 * Function : server_content_type
2279 * Description : Set the content-type for filterable types (text/.*,
2280 * .*xml.*, .*script.* and image/gif) unless filtering has been
2281 * forbidden (CT_TABOO) while parsing earlier headers.
2282 * NOTE: Since text/plain is commonly used by web servers
2283 * for files whose correct type is unknown, we don't
2284 * set CT_TEXT for it.
2287 * 1 : csp = Current client state (buffers, headers, etc...)
2288 * 2 : header = On input, pointer to header to modify.
2289 * On output, pointer to the modified header, or NULL
2290 * to remove the header. This function frees the
2291 * original string if necessary.
2293 * Returns : JB_ERR_OK on success, or
2294 * JB_ERR_MEMORY on out-of-memory error.
2296 *********************************************************************/
2297 static jb_err server_content_type(struct client_state *csp, char **header)
2299 /* Remove header if it isn't the first Content-Type header */
2300 if ((csp->content_type & CT_DECLARED))
2302 if (content_filters_enabled(csp->action))
2305 * Making sure the client interprets the content the same way
2306 * Privoxy did is only relevant if Privoxy modified it.
2308 * Checking for this is "hard" as it's not yet known when
2309 * this function is called, thus go shopping and and just
2310 * check if Privoxy could filter it.
2312 * The main thing is that we don't mess with the headers
2313 * unless the user signalled that it's acceptable.
2315 log_error(LOG_LEVEL_HEADER,
2316 "Multiple Content-Type headers detected. "
2317 "Removing and ignoring: %s",
2325 * Signal that the Content-Type has been set.
2327 csp->content_type |= CT_DECLARED;
2329 if (!(csp->content_type & CT_TABOO))
2332 * XXX: The assumption that text/plain is a sign of
2333 * binary data seems to be somewhat unreasonable nowadays
2334 * and should be dropped after 3.0.8 is out.
2336 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2337 || strstr(*header, "xml")
2338 || strstr(*header, "script"))
2340 csp->content_type |= CT_TEXT;
2342 else if (strstr(*header, "image/gif"))
2344 csp->content_type |= CT_GIF;
2349 * Are we messing with the content type?
2351 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2354 * Make sure the user doesn't accidentally
2355 * change the content type of binary documents.
2357 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2361 *header = strdup_or_die("Content-Type: ");
2363 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2364 if (JB_ERR_OK != err)
2366 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2367 return JB_ERR_MEMORY;
2369 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2373 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2374 "It doesn't look like a content type that should be filtered. "
2375 "Enable force-text-mode if you know what you're doing.", *header);
2383 /*********************************************************************
2385 * Function : server_transfer_coding
2387 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2388 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2389 * - Remove header if body was chunked but has been
2390 * de-chunked for filtering.
2393 * 1 : csp = Current client state (buffers, headers, etc...)
2394 * 2 : header = On input, pointer to header to modify.
2395 * On output, pointer to the modified header, or NULL
2396 * to remove the header. This function frees the
2397 * original string if necessary.
2399 * Returns : JB_ERR_OK on success, or
2400 * JB_ERR_MEMORY on out-of-memory error.
2402 *********************************************************************/
2403 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2406 * Turn off pcrs and gif filtering if body compressed
2408 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2412 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2414 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2415 csp->http->cmd, *header);
2416 #endif /* def FEATURE_ZLIB */
2417 csp->content_type = CT_TABOO;
2421 * Raise flag if body chunked
2423 if (strstr(*header, "chunked"))
2425 csp->flags |= CSP_FLAG_CHUNKED;
2428 * If the body was modified, it has been de-chunked first
2429 * and the header must be removed.
2431 * FIXME: If there is more than one transfer encoding,
2432 * only the "chunked" part should be removed here.
2434 if (csp->flags & CSP_FLAG_MODIFIED)
2436 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2445 /*********************************************************************
2447 * Function : server_content_encoding
2449 * Description : Used to check if the content is compressed, and if
2450 * FEATURE_ZLIB is disabled, filtering is disabled as
2453 * If FEATURE_ZLIB is enabled and the compression type
2454 * supported, the content is marked for decompression.
2456 * XXX: Doesn't properly deal with multiple or with
2457 * unsupported but unknown encodings.
2458 * Is case-sensitive but shouldn't be.
2461 * 1 : csp = Current client state (buffers, headers, etc...)
2462 * 2 : header = On input, pointer to header to modify.
2463 * On output, pointer to the modified header, or NULL
2464 * to remove the header. This function frees the
2465 * original string if necessary.
2467 * Returns : JB_ERR_OK on success, or
2468 * JB_ERR_MEMORY on out-of-memory error.
2470 *********************************************************************/
2471 static jb_err server_content_encoding(struct client_state *csp, char **header)
2474 if (strstr(*header, "sdch"))
2477 * Shared Dictionary Compression over HTTP isn't supported,
2478 * filtering it anyway is pretty much guaranteed to mess up
2481 csp->content_type |= CT_TABOO;
2484 * Log a warning if the user expects the content to be filtered.
2486 if (content_filters_enabled(csp->action))
2488 log_error(LOG_LEVEL_INFO,
2489 "SDCH-compressed content detected, content filtering disabled. "
2490 "Consider suppressing SDCH offers made by the client.");
2493 else if (strstr(*header, "gzip"))
2495 /* Mark for gzip decompression */
2496 csp->content_type |= CT_GZIP;
2498 else if (strstr(*header, "deflate"))
2500 /* Mark for zlib decompression */
2501 csp->content_type |= CT_DEFLATE;
2503 else if (strstr(*header, "br"))
2505 #ifdef FEATURE_BROTLI
2506 /* Mark for Brotli decompression */
2507 csp->content_type |= CT_BROTLI;
2509 csp->content_type |= CT_TABOO;
2512 else if (strstr(*header, "compress"))
2515 * We can't decompress this; therefore we can't filter
2518 csp->content_type |= CT_TABOO;
2520 #else /* !defined(FEATURE_ZLIB) */
2522 * XXX: Using a black list here isn't the right approach.
2524 * In case of SDCH, building with zlib support isn't
2527 if (strstr(*header, "gzip") ||
2528 strstr(*header, "compress") ||
2529 strstr(*header, "deflate") ||
2530 strstr(*header, "sdch"))
2533 * Body is compressed, turn off pcrs and gif filtering.
2535 csp->content_type |= CT_TABOO;
2538 * Log a warning if the user expects the content to be filtered.
2540 if (content_filters_enabled(csp->action))
2542 log_error(LOG_LEVEL_INFO,
2543 "Compressed content detected, content filtering disabled. "
2544 "Consider recompiling Privoxy with zlib support or "
2545 "enable the prevent-compression action.");
2548 #endif /* defined(FEATURE_ZLIB) */
2556 /*********************************************************************
2558 * Function : server_adjust_content_encoding
2560 * Description : Remove the Content-Encoding header if the
2561 * decompression was successful and the content
2562 * has been modified.
2565 * 1 : csp = Current client state (buffers, headers, etc...)
2566 * 2 : header = On input, pointer to header to modify.
2567 * On output, pointer to the modified header, or NULL
2568 * to remove the header. This function frees the
2569 * original string if necessary.
2571 * Returns : JB_ERR_OK on success, or
2572 * JB_ERR_MEMORY on out-of-memory error.
2574 *********************************************************************/
2575 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2577 if ((csp->flags & CSP_FLAG_MODIFIED)
2578 && ((csp->content_type & (CT_GZIP | CT_DEFLATE))
2579 #ifdef FEATURE_BROTLI
2580 || (csp->content_type & CT_BROTLI)
2586 * We successfully decompressed the content,
2587 * and have to clean the header now, so the
2588 * client no longer expects compressed data.
2590 * XXX: There is a difference between cleaning
2591 * and removing it completely.
2593 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2600 #endif /* defined(FEATURE_ZLIB) */
2603 /*********************************************************************
2605 * Function : server_adjust_content_length
2607 * Description : Adjust Content-Length header if we modified
2611 * 1 : csp = Current client state (buffers, headers, etc...)
2612 * 2 : header = On input, pointer to header to modify.
2613 * On output, pointer to the modified header, or NULL
2614 * to remove the header. This function frees the
2615 * original string if necessary.
2617 * Returns : JB_ERR_OK on success, or
2618 * JB_ERR_MEMORY on out-of-memory error.
2620 *********************************************************************/
2621 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2623 /* Regenerate header if the content was modified. */
2624 if (csp->flags & CSP_FLAG_MODIFIED)
2626 const size_t header_length = 50;
2628 *header = malloc(header_length);
2629 if (*header == NULL)
2631 return JB_ERR_MEMORY;
2633 create_content_length_header(csp->content_length, *header, header_length);
2634 log_error(LOG_LEVEL_HEADER,
2635 "Adjusted Content-Length to %llu", csp->content_length);
2642 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2643 /*********************************************************************
2645 * Function : server_save_content_length
2647 * Description : Save the Content-Length sent by the server.
2650 * 1 : csp = Current client state (buffers, headers, etc...)
2651 * 2 : header = On input, pointer to header to modify.
2652 * On output, pointer to the modified header, or NULL
2653 * to remove the header. This function frees the
2654 * original string if necessary.
2656 * Returns : JB_ERR_OK on success, or
2657 * JB_ERR_MEMORY on out-of-memory error.
2659 *********************************************************************/
2660 static jb_err server_save_content_length(struct client_state *csp, char **header)
2662 unsigned long long content_length = 0;
2663 const char *header_value;
2665 assert(*(*header+14) == ':');
2667 header_value = *header + 15;
2668 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2670 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2675 csp->expected_content_length = content_length;
2676 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2677 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2682 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2685 /*********************************************************************
2687 * Function : server_content_md5
2689 * Description : Crumble any Content-MD5 headers if the document was
2690 * modified. FIXME: Should we re-compute instead?
2693 * 1 : csp = Current client state (buffers, headers, etc...)
2694 * 2 : header = On input, pointer to header to modify.
2695 * On output, pointer to the modified header, or NULL
2696 * to remove the header. This function frees the
2697 * original string if necessary.
2699 * Returns : JB_ERR_OK on success, or
2700 * JB_ERR_MEMORY on out-of-memory error.
2702 *********************************************************************/
2703 static jb_err server_content_md5(struct client_state *csp, char **header)
2705 if (csp->flags & CSP_FLAG_MODIFIED)
2707 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2715 /*********************************************************************
2717 * Function : server_content_disposition
2719 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2720 * Called from `sed'.
2723 * 1 : csp = Current client state (buffers, headers, etc...)
2724 * 2 : header = On input, pointer to header to modify.
2725 * On output, pointer to the modified header, or NULL
2726 * to remove the header. This function frees the
2727 * original string if necessary.
2729 * Returns : JB_ERR_OK on success, or
2730 * JB_ERR_MEMORY on out-of-memory error.
2732 *********************************************************************/
2733 static jb_err server_content_disposition(struct client_state *csp, char **header)
2738 * Are we messing with the Content-Disposition header?
2740 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2746 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2748 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2751 * Blocking content-disposition header
2753 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2760 * Replacing Content-Disposition header
2763 *header = strdup("Content-Disposition: ");
2764 string_append(header, newval);
2766 if (*header != NULL)
2768 log_error(LOG_LEVEL_HEADER,
2769 "Content-Disposition header crunched and replaced with: %s", *header);
2772 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2776 /*********************************************************************
2778 * Function : server_last_modified
2780 * Description : Changes Last-Modified header to the actual date
2781 * to help hide-if-modified-since.
2782 * Called from `sed'.
2785 * 1 : csp = Current client state (buffers, headers, etc...)
2786 * 2 : header = On input, pointer to header to modify.
2787 * On output, pointer to the modified header, or NULL
2788 * to remove the header. This function frees the
2789 * original string if necessary.
2791 * Returns : JB_ERR_OK on success, or
2792 * JB_ERR_MEMORY on out-of-memory error.
2794 *********************************************************************/
2795 static jb_err server_last_modified(struct client_state *csp, char **header)
2798 time_t last_modified;
2802 * Are we messing with the Last-Modified header?
2804 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2810 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2812 if (0 == strcmpic(newval, "block"))
2815 * Blocking Last-Modified header. Useless but why not.
2817 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2821 else if (0 == strcmpic(newval, "reset-to-request-time"))
2824 * Setting Last-Modified Header to now.
2827 get_http_time(0, buf, sizeof(buf));
2829 *header = strdup("Last-Modified: ");
2830 string_append(header, buf);
2832 if (*header == NULL)
2834 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2838 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2841 else if (0 == strcmpic(newval, "randomize"))
2843 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2845 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2847 log_error(LOG_LEVEL_HEADER,
2848 "Couldn't parse time in %s (crunching!)", *header);
2854 struct tm *timeptr = NULL;
2859 rtime = (long int)difftime(now, last_modified);
2862 long int days, hours, minutes, seconds;
2863 const int negative_delta = (rtime < 0);
2868 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2870 rtime = pick_from_range(rtime);
2875 last_modified += rtime;
2876 timeptr = privoxy_gmtime_r(&last_modified, &gmt);
2877 if ((NULL == timeptr) || !strftime(newheader,
2878 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2880 log_error(LOG_LEVEL_ERROR,
2881 "Randomizing '%s' failed. Crunching the header without replacement.",
2887 *header = strdup("Last-Modified: ");
2888 string_append(header, newheader);
2890 if (*header == NULL)
2892 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2893 return JB_ERR_MEMORY;
2896 days = rtime / (3600 * 24);
2897 hours = rtime / 3600 % 24;
2898 minutes = rtime / 60 % 60;
2899 seconds = rtime % 60;
2901 log_error(LOG_LEVEL_HEADER,
2902 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2903 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2904 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2908 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2917 /*********************************************************************
2919 * Function : client_accept_encoding
2921 * Description : Rewrite the client's Accept-Encoding header so that
2922 * if doesn't allow compression, if the action applies.
2923 * Note: For HTTP/1.0 the absence of the header is enough.
2926 * 1 : csp = Current client state (buffers, headers, etc...)
2927 * 2 : header = On input, pointer to header to modify.
2928 * On output, pointer to the modified header, or NULL
2929 * to remove the header. This function frees the
2930 * original string if necessary.
2932 * Returns : JB_ERR_OK on success, or
2933 * JB_ERR_MEMORY on out-of-memory error.
2935 *********************************************************************/
2936 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2938 #ifdef FEATURE_COMPRESSION
2939 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2940 && strstr(*header, "deflate"))
2942 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2945 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2947 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2955 /*********************************************************************
2957 * Function : client_te
2959 * Description : Rewrite the client's TE header so that
2960 * if doesn't allow compression, if the action applies.
2963 * 1 : csp = Current client state (buffers, headers, etc...)
2964 * 2 : header = On input, pointer to header to modify.
2965 * On output, pointer to the modified header, or NULL
2966 * to remove the header. This function frees the
2967 * original string if necessary.
2969 * Returns : JB_ERR_OK on success, or
2970 * JB_ERR_MEMORY on out-of-memory error.
2972 *********************************************************************/
2973 static jb_err client_te(struct client_state *csp, char **header)
2975 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2978 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2985 /*********************************************************************
2987 * Function : client_referrer
2989 * Description : Handle the "referer" config setting properly.
2990 * Called from `sed'.
2993 * 1 : csp = Current client state (buffers, headers, etc...)
2994 * 2 : header = On input, pointer to header to modify.
2995 * On output, pointer to the modified header, or NULL
2996 * to remove the header. This function frees the
2997 * original string if necessary.
2999 * Returns : JB_ERR_OK on success, or
3000 * JB_ERR_MEMORY on out-of-memory error.
3002 *********************************************************************/
3003 static jb_err client_referrer(struct client_state *csp, char **header)
3005 const char *parameter;
3006 /* booleans for parameters we have to check multiple times */
3007 int parameter_conditional_block;
3008 int parameter_conditional_forge;
3010 #ifdef FEATURE_FORCE_LOAD
3012 * Since the referrer can include the prefix even
3013 * if the request itself is non-forced, we must
3014 * clean it unconditionally.
3016 * XXX: strclean is too broad
3018 strclean(*header, FORCE_PREFIX);
3019 #endif /* def FEATURE_FORCE_LOAD */
3021 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3023 /* Nothing left to do */
3027 parameter = csp->action->string[ACTION_STRING_REFERER];
3028 assert(parameter != NULL);
3029 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3030 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3032 if (!parameter_conditional_block && !parameter_conditional_forge)
3035 * As conditional-block and conditional-forge are the only
3036 * parameters that rely on the original referrer, we can
3037 * remove it now for all the others.
3042 if (0 == strcmpic(parameter, "block"))
3044 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3047 else if (parameter_conditional_block || parameter_conditional_forge)
3049 return handle_conditional_hide_referrer_parameter(header,
3050 csp->http->hostport, parameter_conditional_block);
3052 else if (0 == strcmpic(parameter, "forge"))
3054 return create_forged_referrer(header, csp->http->hostport);
3058 /* interpret parameter as user-supplied referer to fake */
3059 return create_fake_referrer(header, parameter);
3064 /*********************************************************************
3066 * Function : client_accept_language
3068 * Description : Handle the "Accept-Language" config setting properly.
3069 * Called from `sed'.
3072 * 1 : csp = Current client state (buffers, headers, etc...)
3073 * 2 : header = On input, pointer to header to modify.
3074 * On output, pointer to the modified header, or NULL
3075 * to remove the header. This function frees the
3076 * original string if necessary.
3078 * Returns : JB_ERR_OK on success, or
3079 * JB_ERR_MEMORY on out-of-memory error.
3081 *********************************************************************/
3082 static jb_err client_accept_language(struct client_state *csp, char **header)
3087 * Are we messing with the Accept-Language?
3089 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3091 /*I don't think so*/
3095 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3097 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3100 * Blocking Accept-Language header
3102 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3109 * Replacing Accept-Language header
3112 *header = strdup("Accept-Language: ");
3113 string_append(header, newval);
3115 if (*header == NULL)
3117 log_error(LOG_LEVEL_ERROR,
3118 "Insufficient memory. Accept-Language header crunched without replacement.");
3122 log_error(LOG_LEVEL_HEADER,
3123 "Accept-Language header crunched and replaced with: %s", *header);
3126 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3130 /*********************************************************************
3132 * Function : crunch_client_header
3134 * Description : Crunch client header if it matches a string supplied by the
3135 * user. 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 and always succeeds
3146 *********************************************************************/
3147 static jb_err crunch_client_header(struct client_state *csp, char **header)
3149 const char *crunch_pattern;
3151 /* Do we feel like crunching? */
3152 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3154 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3156 /* Is the current header the lucky one? */
3157 if (strstr(*header, crunch_pattern))
3159 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3167 /*********************************************************************
3169 * Function : client_uagent
3171 * Description : Handle the "user-agent" config setting properly
3172 * and remember its original value to enable browser
3173 * bug workarounds. Called from `sed'.
3176 * 1 : csp = Current client state (buffers, headers, etc...)
3177 * 2 : header = On input, pointer to header to modify.
3178 * On output, pointer to the modified header, or NULL
3179 * to remove the header. This function frees the
3180 * original string if necessary.
3182 * Returns : JB_ERR_OK on success, or
3183 * JB_ERR_MEMORY on out-of-memory error.
3185 *********************************************************************/
3186 static jb_err client_uagent(struct client_state *csp, char **header)
3190 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3195 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3202 *header = strdup("User-Agent: ");
3203 string_append(header, newval);
3205 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3207 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3211 /*********************************************************************
3213 * Function : client_ua
3215 * Description : Handle "ua-" headers properly. Called from `sed'.
3218 * 1 : csp = Current client state (buffers, headers, etc...)
3219 * 2 : header = On input, pointer to header to modify.
3220 * On output, pointer to the modified header, or NULL
3221 * to remove the header. This function frees the
3222 * original string if necessary.
3224 * Returns : JB_ERR_OK on success, or
3225 * JB_ERR_MEMORY on out-of-memory error.
3227 *********************************************************************/
3228 static jb_err client_ua(struct client_state *csp, char **header)
3230 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3232 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3240 /*********************************************************************
3242 * Function : client_from
3244 * Description : Handle the "from" config setting properly.
3245 * Called from `sed'.
3248 * 1 : csp = Current client state (buffers, headers, etc...)
3249 * 2 : header = On input, pointer to header to modify.
3250 * On output, pointer to the modified header, or NULL
3251 * to remove the header. This function frees the
3252 * original string if necessary.
3254 * Returns : JB_ERR_OK on success, or
3255 * JB_ERR_MEMORY on out-of-memory error.
3257 *********************************************************************/
3258 static jb_err client_from(struct client_state *csp, char **header)
3262 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3269 newval = csp->action->string[ACTION_STRING_FROM];
3272 * Are we blocking the e-mail address?
3274 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3276 log_error(LOG_LEVEL_HEADER, "crunched From!");
3280 log_error(LOG_LEVEL_HEADER, " modified");
3282 *header = strdup("From: ");
3283 string_append(header, newval);
3285 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3289 /*********************************************************************
3291 * Function : client_send_cookie
3293 * Description : Crunches the "cookie" header if necessary.
3294 * Called from `sed'.
3296 * XXX: Stupid name, doesn't send squat.
3299 * 1 : csp = Current client state (buffers, headers, etc...)
3300 * 2 : header = On input, pointer to header to modify.
3301 * On output, pointer to the modified header, or NULL
3302 * to remove the header. This function frees the
3303 * original string if necessary.
3305 * Returns : JB_ERR_OK on success, or
3306 * JB_ERR_MEMORY on out-of-memory error.
3308 *********************************************************************/
3309 static jb_err client_send_cookie(struct client_state *csp, char **header)
3311 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3313 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3321 /*********************************************************************
3323 * Function : client_x_forwarded
3325 * Description : Handle the "x-forwarded-for" config setting properly,
3326 * also used in the add_client_headers list. Called from `sed'.
3329 * 1 : csp = Current client state (buffers, headers, etc...)
3330 * 2 : header = On input, pointer to header to modify.
3331 * On output, pointer to the modified header, or NULL
3332 * to remove the header. This function frees the
3333 * original string if necessary.
3335 * Returns : JB_ERR_OK on success, or
3336 * JB_ERR_MEMORY on out-of-memory error.
3338 *********************************************************************/
3339 jb_err client_x_forwarded(struct client_state *csp, char **header)
3341 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3343 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3345 if (0 == strcmpic(parameter, "block"))
3348 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3350 else if (0 == strcmpic(parameter, "add"))
3352 string_append(header, ", ");
3353 string_append(header, csp->ip_addr_str);
3355 if (*header == NULL)
3357 return JB_ERR_MEMORY;
3359 log_error(LOG_LEVEL_HEADER,
3360 "Appended client IP address to %s", *header);
3361 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3365 log_error(LOG_LEVEL_FATAL,
3366 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3374 /*********************************************************************
3376 * Function : client_max_forwards
3378 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3379 * from the value of the Max-Forwards header field.
3382 * 1 : csp = Current client state (buffers, headers, etc...)
3383 * 2 : header = On input, pointer to header to modify.
3384 * On output, pointer to the modified header, or NULL
3385 * to remove the header. This function frees the
3386 * original string if necessary.
3388 * Returns : JB_ERR_OK on success, or
3389 * JB_ERR_MEMORY on out-of-memory error.
3391 *********************************************************************/
3392 static jb_err client_max_forwards(struct client_state *csp, char **header)
3396 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3397 (0 == strcmpic(csp->http->gpc, "options")))
3399 assert(*(*header+12) == ':');
3400 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3402 if (max_forwards > 0)
3404 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3405 log_error(LOG_LEVEL_HEADER,
3406 "Max-Forwards value for %s request reduced to %d.",
3407 csp->http->gpc, max_forwards);
3409 else if (max_forwards < 0)
3411 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3417 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3426 /*********************************************************************
3428 * Function : client_host
3430 * Description : If the request URI did not contain host and
3431 * port information, parse and evaluate the Host
3435 * 1 : csp = Current client state (buffers, headers, etc...)
3436 * 2 : header = On input, pointer to header to modify.
3437 * On output, pointer to the modified header, or NULL
3438 * to remove the header. This function frees the
3439 * original string if necessary.
3441 * Returns : JB_ERR_OK on success, or
3442 * JB_ERR_MEMORY on out-of-memory error.
3444 *********************************************************************/
3445 static jb_err client_host(struct client_state *csp, char **header)
3449 if (strlen(*header) < 7)
3451 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3456 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3457 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3460 p = strdup_or_die((*header)+6);
3462 q = strdup_or_die(p);
3464 freez(csp->http->hostport);
3465 csp->http->hostport = p;
3466 freez(csp->http->host);
3467 csp->http->host = q;
3468 q = strchr(csp->http->host, ':');
3471 /* Terminate hostname and evaluate port string */
3473 csp->http->port = atoi(q);
3477 csp->http->port = csp->http->ssl ? 443 : 80;
3480 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3481 csp->http->hostport, csp->http->host, csp->http->port);
3484 /* Signal client_host_adder() to return right away */
3485 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3491 /*********************************************************************
3493 * Function : client_if_modified_since
3495 * Description : Remove or modify the If-Modified-Since header.
3498 * 1 : csp = Current client state (buffers, headers, etc...)
3499 * 2 : header = On input, pointer to header to modify.
3500 * On output, pointer to the modified header, or NULL
3501 * to remove the header. This function frees the
3502 * original string if necessary.
3504 * Returns : JB_ERR_OK on success, or
3505 * JB_ERR_MEMORY on out-of-memory error.
3507 *********************************************************************/
3508 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3512 struct tm *timeptr = NULL;
3517 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3520 * The client got an error message because of a temporary problem,
3521 * the problem is gone and the client now tries to revalidate our
3522 * error message on the real server. The revalidation would always
3523 * end with the transmission of the whole document and there is
3524 * no need to expose the bogus If-Modified-Since header.
3526 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3529 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3531 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3533 if ((0 == strcmpic(newval, "block")))
3535 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3538 else /* add random value */
3540 if (JB_ERR_OK != parse_time_header(*header, &tm))
3542 log_error(LOG_LEVEL_HEADER,
3543 "Couldn't parse time in %s (crunching!)", *header);
3548 long int hours, minutes, seconds;
3549 long int rtime = strtol(newval, &endptr, 0);
3550 const int negative_range = (rtime < 0);
3554 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3555 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3561 rtime = pick_from_range(rtime);
3565 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3568 tm += rtime * (negative_range ? -1 : 1);
3569 timeptr = privoxy_gmtime_r(&tm, &gmt);
3570 if ((NULL == timeptr) || !strftime(newheader,
3571 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3573 log_error(LOG_LEVEL_ERROR,
3574 "Randomizing '%s' failed. Crunching the header without replacement.",
3580 *header = strdup("If-Modified-Since: ");
3581 string_append(header, newheader);
3583 if (*header == NULL)
3585 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3586 return JB_ERR_MEMORY;
3589 hours = rtime / 3600;
3590 minutes = rtime / 60 % 60;
3591 seconds = rtime % 60;
3593 log_error(LOG_LEVEL_HEADER,
3594 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3595 *header, (negative_range) ? "subtracted" : "added", hours,
3596 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3597 seconds, (seconds == 1) ? ")" : "s)");
3606 /*********************************************************************
3608 * Function : client_if_none_match
3610 * Description : Remove the If-None-Match header.
3613 * 1 : csp = Current client state (buffers, headers, etc...)
3614 * 2 : header = On input, pointer to header to modify.
3615 * On output, pointer to the modified header, or NULL
3616 * to remove the header. This function frees the
3617 * original string if necessary.
3619 * Returns : JB_ERR_OK on success, or
3620 * JB_ERR_MEMORY on out-of-memory error.
3622 *********************************************************************/
3623 static jb_err client_if_none_match(struct client_state *csp, char **header)
3625 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3627 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3635 /*********************************************************************
3637 * Function : client_x_filter
3639 * Description : Disables filtering if the client set "X-Filter: No".
3640 * Called from `sed'.
3643 * 1 : csp = Current client state (buffers, headers, etc...)
3644 * 2 : header = On input, pointer to header to modify.
3645 * On output, pointer to the modified header, or NULL
3646 * to remove the header. This function frees the
3647 * original string if necessary.
3649 * Returns : JB_ERR_OK on success
3651 *********************************************************************/
3652 jb_err client_x_filter(struct client_state *csp, char **header)
3654 if (0 == strcmpic(*header, "X-Filter: No"))
3656 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3658 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3662 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3664 log_error(LOG_LEVEL_HEADER,
3665 "force-text-mode overruled the client's request to fetch without filtering!");
3669 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3670 csp->flags |= CSP_FLAG_NO_FILTERING;
3671 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3673 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3681 /*********************************************************************
3683 * Function : client_range
3685 * Description : Removes Range, Request-Range and If-Range headers if
3686 * content filtering is enabled and the range doesn't
3689 * If the client's version of the document has been
3690 * altered by Privoxy, the server could interpret the
3691 * range differently than the client intended in which
3692 * case the user could end up with corrupted content.
3694 * If the range starts at byte 0 this isn't an issue
3695 * so the header can pass. Partial requests like this
3696 * are used to render preview images for videos without
3697 * downloading the whole video.
3699 * While HTTP doesn't require that range requests are
3700 * honoured and the client could simply abort the download
3701 * after receiving a sufficient amount of data, various
3702 * clients don't handle complete responses to range
3703 * requests gracefully and emit misleading error messages
3707 * 1 : csp = Current client state (buffers, headers, etc...)
3708 * 2 : header = On input, pointer to header to modify.
3709 * On output, pointer to the modified header, or NULL
3710 * to remove the header. This function frees the
3711 * original string if necessary.
3713 * Returns : JB_ERR_OK
3715 *********************************************************************/
3716 static jb_err client_range(struct client_state *csp, char **header)
3718 if (content_filters_enabled(csp->action)
3719 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3721 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3722 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3729 /* the following functions add headers directly to the header list */
3731 /*********************************************************************
3733 * Function : client_host_adder
3735 * Description : Adds the Host: header field if it is missing.
3736 * Called from `sed'.
3739 * 1 : csp = Current client state (buffers, headers, etc...)
3741 * Returns : JB_ERR_OK on success, or
3742 * JB_ERR_MEMORY on out-of-memory error.
3744 *********************************************************************/
3745 static jb_err client_host_adder(struct client_state *csp)
3750 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3752 /* Header already set by the client, nothing to do. */
3756 if (!csp->http->hostport || !*(csp->http->hostport))
3758 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3759 return JB_ERR_PARSE;
3763 * remove 'user:pass@' from 'proto://user:pass@host'
3765 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3771 p = csp->http->hostport;
3774 /* XXX: Just add it, we already made sure that it will be unique */
3775 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3776 err = enlist_unique_header(csp->headers, "Host", p);
3782 /*********************************************************************
3784 * Function : client_xtra_adder
3786 * Description : Used in the add_client_headers list. Called from `sed'.
3789 * 1 : csp = Current client state (buffers, headers, etc...)
3791 * Returns : JB_ERR_OK on success, or
3792 * JB_ERR_MEMORY on out-of-memory error.
3794 *********************************************************************/
3795 static jb_err client_xtra_adder(struct client_state *csp)
3797 struct list_entry *lst;
3800 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3801 lst ; lst = lst->next)
3803 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3804 err = enlist(csp->headers, lst->str);
3816 /*********************************************************************
3818 * Function : client_x_forwarded_for_adder
3820 * Description : Used in the add_client_headers list. Called from `sed'.
3823 * 1 : csp = Current client state (buffers, headers, etc...)
3825 * Returns : JB_ERR_OK on success, or
3826 * JB_ERR_MEMORY on out-of-memory error.
3828 *********************************************************************/
3829 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3831 char *header = NULL;
3834 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3835 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3836 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3839 * If we aren't adding X-Forwarded-For headers,
3840 * or we already appended an existing X-Forwarded-For
3841 * header, there's nothing left to do here.
3846 header = strdup("X-Forwarded-For: ");
3847 string_append(&header, csp->ip_addr_str);
3851 return JB_ERR_MEMORY;
3854 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3855 err = enlist(csp->headers, header);
3862 /*********************************************************************
3864 * Function : server_connection_adder
3866 * Description : Adds an appropriate "Connection:" header to csp->headers
3867 * unless the header was already present. Called from `sed'.
3870 * 1 : csp = Current client state (buffers, headers, etc...)
3872 * Returns : JB_ERR_OK on success, or
3873 * JB_ERR_MEMORY on out-of-memory error.
3875 *********************************************************************/
3876 static jb_err server_connection_adder(struct client_state *csp)
3878 const unsigned int flags = csp->flags;
3879 const char *response_status_line = csp->headers->first->str;
3880 static const char connection_close[] = "Connection: close";
3882 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3883 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3889 * XXX: if we downgraded the response, this check will fail.
3891 if ((csp->config->feature_flags &
3892 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3893 && (NULL != response_status_line)
3894 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3895 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3896 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3900 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3901 "without Connection header implies keep-alive.");
3902 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3906 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3908 return enlist(csp->headers, connection_close);
3912 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3913 /*********************************************************************
3915 * Function : server_proxy_connection_adder
3917 * Description : Adds a "Proxy-Connection: keep-alive" header to
3918 * csp->headers when appropriate.
3921 * 1 : csp = Current client state (buffers, headers, etc...)
3923 * Returns : JB_ERR_OK on success, or
3924 * JB_ERR_MEMORY on out-of-memory error.
3926 *********************************************************************/
3927 static jb_err server_proxy_connection_adder(struct client_state *csp)
3929 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3930 jb_err err = JB_ERR_OK;
3932 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3933 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3934 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3935 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3936 || (csp->flags & CSP_FLAG_CHUNKED)))
3938 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3939 err = enlist(csp->headers, proxy_connection_header);
3944 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3947 /*********************************************************************
3949 * Function : client_connection_header_adder
3951 * Description : Adds a proper "Connection:" header to csp->headers
3952 * unless the header was already present or it's a
3953 * CONNECT request. Called from `sed'.
3956 * 1 : csp = Current client state (buffers, headers, etc...)
3958 * Returns : JB_ERR_OK on success, or
3959 * JB_ERR_MEMORY on out-of-memory error.
3961 *********************************************************************/
3962 static jb_err client_connection_header_adder(struct client_state *csp)
3964 static const char connection_close[] = "Connection: close";
3966 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3967 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3973 * In case of CONNECT requests "Connection: close" is implied,
3974 * but actually setting the header has been reported to cause
3975 * problems with some forwarding proxies that close the
3976 * connection prematurely.
3978 if (csp->http->ssl != 0)
3983 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3984 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3985 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3986 && !strcmpic(csp->http->version, "HTTP/1.1"))
3988 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3991 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3993 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3995 return enlist(csp->headers, connection_close);
3999 /*********************************************************************
4001 * Function : server_http
4003 * Description : - Save the HTTP Status into csp->http->status
4004 * - Set CT_TABOO to prevent filtering if the answer
4005 * is a partial range (HTTP status 206)
4006 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4008 * - Normalize the HTTP-version.
4011 * 1 : csp = Current client state (buffers, headers, etc...)
4012 * 2 : header = On input, pointer to header to modify.
4013 * On output, pointer to the modified header, or NULL
4014 * to remove the header. This function frees the
4015 * original string if necessary.
4017 * Returns : JB_ERR_OK on success, or
4018 * JB_ERR_PARSE on fatal parse errors.
4020 *********************************************************************/
4021 static jb_err server_http(struct client_state *csp, char **header)
4023 char *reason_phrase = NULL;
4024 char *new_response_line;
4027 unsigned int major_version;
4028 unsigned int minor_version;
4030 /* Get the reason phrase which start after the second whitespace */
4031 p = strchr(*header, ' ');
4035 reason_phrase = strchr(p, ' ');
4038 if (reason_phrase != NULL)
4044 log_error(LOG_LEVEL_ERROR,
4045 "Response line lacks reason phrase: %s", *header);
4049 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
4050 &minor_version, &(csp->http->status)))
4052 log_error(LOG_LEVEL_ERROR,
4053 "Failed to parse the response line: %s", *header);
4054 return JB_ERR_PARSE;
4057 if (csp->http->status == 206)
4059 csp->content_type = CT_TABOO;
4062 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
4065 * According to RFC 7230 2.6 intermediaries MUST send
4066 * their own HTTP-version in forwarded messages.
4068 log_error(LOG_LEVEL_ERROR,
4069 "Unsupported HTTP version. Downgrading to 1.1.");
4074 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
4076 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
4080 /* Rebuild response line. */
4081 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
4082 new_response_line = malloc_or_die(length);
4084 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
4085 major_version, minor_version, csp->http->status, reason_phrase);
4087 if (0 != strcmp(*header, new_response_line))
4089 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
4090 *header, new_response_line);
4094 *header = new_response_line;
4099 /*********************************************************************
4101 * Function : add_cooky_expiry_date
4103 * Description : Adds a cookie expiry date to a string.
4106 * 1 : cookie = On input, pointer to cookie to modify.
4107 * On output, pointer to the modified header.
4108 * The original string is freed.
4109 * 2 : lifetime = Seconds the cookie should be valid
4113 *********************************************************************/
4114 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
4117 struct tm *timeptr = NULL;
4118 time_t expiry_date = time(NULL) + lifetime;
4121 timeptr = privoxy_gmtime_r(&expiry_date, &gmt);
4122 if (NULL == timeptr)
4124 log_error(LOG_LEVEL_FATAL,
4125 "Failed to get the time in add_cooky_expiry_date()");
4127 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
4128 if (JB_ERR_OK != string_append(cookie, tmp))
4130 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
4135 /*********************************************************************
4137 * Function : server_set_cookie
4139 * Description : Handle the server "cookie" header properly.
4140 * Crunch, accept or rewrite it to a session cookie.
4141 * Called from `sed'.
4144 * 1 : csp = Current client state (buffers, headers, etc...)
4145 * 2 : header = On input, pointer to header to modify.
4146 * On output, pointer to the modified header, or NULL
4147 * to remove the header. This function frees the
4148 * original string if necessary.
4150 * Returns : JB_ERR_OK on success, or
4151 * JB_ERR_MEMORY on out-of-memory error.
4153 *********************************************************************/
4154 static jb_err server_set_cookie(struct client_state *csp, char **header)
4156 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4158 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4161 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4162 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4166 long cookie_lifetime = 0;
4169 NO_EXPIRY_DATE_SPECIFIED,
4170 EXPIRY_DATE_ACCEPTABLE,
4171 EXPIRY_DATE_UNACCEPTABLE
4172 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4174 /* A variable to store the tag we're working on */
4177 /* Skip "Set-Cookie:" (11 characters) in header */
4178 cur_tag = *header + 11;
4180 /* skip whitespace between "Set-Cookie:" and value */
4181 while (*cur_tag && privoxy_isspace(*cur_tag))
4188 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4190 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4192 cookie_lifetime = strtol(param, NULL, 0);
4193 if (cookie_lifetime < 0)
4195 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4197 cookie_lifetime *= 60;
4200 /* Loop through each tag in the cookie */
4204 char *next_tag = strchr(cur_tag, ';');
4205 if (next_tag != NULL)
4207 /* Skip the ';' character itself */
4210 /* skip whitespace ";" and start of tag */
4211 while (*next_tag && privoxy_isspace(*next_tag))
4218 /* "Next tag" is the end of the string */
4219 next_tag = cur_tag + strlen(cur_tag);
4223 * Check the expiration date to see
4224 * if the cookie is still valid, if yes,
4225 * rewrite it to a session cookie.
4227 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4229 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4231 if ((expiration_date[0] == '"')
4232 && (expiration_date[1] != '\0'))
4235 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4236 * that the expiration date isn't supposed to be quoted,
4237 * but some servers do it anyway.
4242 /* Did we detect the date properly? */
4243 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4246 * Nope, treat it as if it was still valid.
4248 * XXX: Should we remove the whole cookie instead?
4250 log_error(LOG_LEVEL_ERROR,
4251 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4252 string_move(cur_tag, next_tag);
4253 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4258 * Yes. Check if the cookie is still valid.
4260 * If the cookie is already expired it's probably
4261 * a delete cookie and even if it isn't, the browser
4262 * will discard it anyway.
4266 * XXX: timegm() isn't available on some AmigaOS
4267 * versions and our replacement doesn't work.
4269 * Our options are to either:
4271 * - disable session-cookies-only completely if timegm
4274 * - to simply remove all expired tags, like it has
4275 * been done until Privoxy 3.0.6 and to live with
4276 * the consequence that it can cause login/logout
4277 * problems on servers that don't validate their
4278 * input properly, or
4280 * - to replace it with mktime in which
4281 * case there is a slight chance of valid cookies
4282 * passing as already expired.
4284 * This is the way it's currently done and it's not
4285 * as bad as it sounds. If the missing GMT offset is
4286 * enough to change the result of the expiration check
4287 * the cookie will be only valid for a few hours
4288 * anyway, which in many cases will be shorter
4289 * than a browser session.
4291 if (cookie_time < now)
4293 log_error(LOG_LEVEL_HEADER,
4294 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4295 /* Just in case some clown sets more then one expiration date */
4297 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4299 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4301 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4302 "Its lifetime is below the limit.", *header);
4303 /* Just in case some clown sets more then one expiration date */
4305 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4310 * Still valid, delete expiration date by copying
4311 * the rest of the string over it.
4313 string_move(cur_tag, next_tag);
4315 /* That changed the header, need to issue a log message */
4316 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4319 * Note that the next tag has now been moved to *cur_tag,
4320 * so we do not need to update the cur_tag pointer.
4328 /* Move on to next cookie tag */
4333 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4335 assert(NULL != *header);
4336 if (cookie_lifetime != 0)
4338 add_cookie_expiry_date(header, cookie_lifetime);
4339 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4341 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4343 log_error(LOG_LEVEL_HEADER,
4344 "Cookie rewritten to a temporary one: %s", *header);
4353 #ifdef FEATURE_FORCE_LOAD
4354 /*********************************************************************
4356 * Function : strclean
4358 * Description : In-Situ-Eliminate all occurrences of substring in
4362 * 1 : string = string to clean
4363 * 2 : substring = substring to eliminate
4365 * Returns : Number of eliminations
4367 *********************************************************************/
4368 int strclean(char *string, const char *substring)
4374 len = strlen(substring);
4376 while((pos = strstr(string, substring)) != NULL)
4383 while (*p++ != '\0');
4390 #endif /* def FEATURE_FORCE_LOAD */
4393 /*********************************************************************
4395 * Function : parse_header_time
4397 * Description : Parses time formats used in HTTP header strings
4398 * to get the numerical respresentation.
4401 * 1 : header_time = HTTP header time as string.
4402 * 2 : result = storage for header_time in seconds
4404 * Returns : JB_ERR_OK if the time format was recognized, or
4405 * JB_ERR_PARSE otherwise.
4407 *********************************************************************/
4408 static jb_err parse_header_time(const char *header_time, time_t *result)
4412 * Checking for two-digit years first in an
4413 * attempt to work around GNU libc's strptime()
4414 * reporting negative year values when using %Y.
4416 static const char time_formats[][22] = {
4417 /* Tue, 02-Jun-37 20:00:00 */
4418 "%a, %d-%b-%y %H:%M:%S",
4419 /* Tue, 02 Jun 2037 20:00:00 */
4420 "%a, %d %b %Y %H:%M:%S",
4421 /* Tue, 02-Jun-2037 20:00:00 */
4422 "%a, %d-%b-%Y %H:%M:%S",
4423 /* Tuesday, 02-Jun-2037 20:00:00 */
4424 "%A, %d-%b-%Y %H:%M:%S",
4425 /* Tuesday Jun 02 20:00:00 2037 */
4426 "%A %b %d %H:%M:%S %Y"
4430 for (i = 0; i < SZ(time_formats); i++)
4433 * Zero out gmt to prevent time zone offsets.
4434 * Documented to be required for GNU libc.
4436 memset(&gmt, 0, sizeof(gmt));
4438 if (NULL != strptime(header_time, time_formats[i], &gmt))
4440 /* Sanity check for GNU libc. */
4441 if (gmt.tm_year < 0)
4443 log_error(LOG_LEVEL_HEADER,
4444 "Failed to parse '%s' using '%s'. Moving on.",
4445 header_time, time_formats[i]);
4448 *result = timegm(&gmt);
4450 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4452 * Verify that parsing the date recreated from the first
4453 * parse operation gets the previous result. If it doesn't,
4454 * either strptime() or strftime() are malfunctioning.
4456 * We could string-compare the recreated date with the original
4457 * header date, but this leads to false positives as strptime()
4458 * may let %a accept all day formats while strftime() will only
4462 char recreated_date[100];
4467 tm = privoxy_gmtime_r(result, &storage);
4468 if (!strftime(recreated_date, sizeof(recreated_date),
4469 time_formats[i], tm))
4471 log_error(LOG_LEVEL_ERROR, "Failed to recreate date '%s' with '%s'.",
4472 header_time, time_formats[i]);
4475 memset(&gmt, 0, sizeof(gmt));
4476 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4478 log_error(LOG_LEVEL_ERROR,
4479 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4480 recreated_date, time_formats[i], header_time);
4483 result2 = timegm(&gmt);
4484 if (*result != result2)
4486 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4487 "Format: '%s'. In: '%s', out: '%s'. %d != %d. Rejecting.",
4488 time_formats[i], header_time, recreated_date, *result, result2);
4498 return JB_ERR_PARSE;
4502 /*********************************************************************
4504 * Function : parse_time_header
4506 * Description : Parses the time in an HTTP time header to get
4507 * the numerical respresentation.
4510 * 1 : header = HTTP header with a time value
4511 * 2 : result = storage for header_time in seconds
4513 * Returns : JB_ERR_OK if the time format was recognized, or
4514 * JB_ERR_PARSE otherwise.
4516 *********************************************************************/
4517 static jb_err parse_time_header(const char *header, time_t *result)
4519 const char *header_time;
4521 header_time = strchr(header, ':');
4524 * Currently this can't happen as all callers are called
4525 * through sed() which requires a header name followed by
4528 assert(header_time != NULL);
4531 if (*header_time == ' ')
4536 return parse_header_time(header_time, result);
4541 /*********************************************************************
4543 * Function : get_destination_from_headers
4545 * Description : Parse the "Host:" header to get the request's destination.
4546 * Only needed if the client's request was forcefully
4547 * redirected into Privoxy.
4549 * Code mainly copied from client_host() which is currently
4550 * run too late for this purpose.
4553 * 1 : headers = List of headers (one of them hopefully being
4554 * the "Host:" header)
4555 * 2 : http = storage for the result (host, port and hostport).
4557 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4558 * JB_ERR_PARSE if the host header couldn't be found,
4559 * JB_ERR_OK otherwise.
4561 *********************************************************************/
4562 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4568 host = get_header_value(headers, "Host:");
4572 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4573 return JB_ERR_PARSE;
4576 p = strdup_or_die(host);
4578 q = strdup_or_die(p);
4580 freez(http->hostport);
4584 q = strchr(http->host, ':');
4587 /* Terminate hostname and evaluate port string */
4589 http->port = atoi(q);
4596 /* Rebuild request URL */
4598 http->url = strdup("http://");
4599 string_append(&http->url, http->hostport);
4600 string_append(&http->url, http->path);
4601 if (http->url == NULL)
4603 return JB_ERR_MEMORY;
4606 log_error(LOG_LEVEL_HEADER,
4607 "Destination extracted from \"Host\" header. New request URL: %s",
4611 * Regenerate request line in "proxy format"
4612 * to make rewrites more convenient.
4614 assert(http->cmd != NULL);
4616 http->cmd = strdup_or_die(http->gpc);
4617 string_append(&http->cmd, " ");
4618 string_append(&http->cmd, http->url);
4619 string_append(&http->cmd, " ");
4620 string_append(&http->cmd, http->version);
4621 if (http->cmd == NULL)
4623 return JB_ERR_MEMORY;
4631 #ifdef FEATURE_HTTPS_INSPECTION
4632 /*********************************************************************
4634 * Function : get_destination_from_https_headers
4636 * Description : Parse the previously encrypted "Host:" header to
4637 * get the request's destination.
4640 * 1 : headers = List of headers (one of them hopefully being
4641 * the "Host:" header)
4642 * 2 : http = storage for the result (host, port and hostport).
4644 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4645 * JB_ERR_PARSE if the host header couldn't be found,
4646 * JB_ERR_OK otherwise.
4648 *********************************************************************/
4649 jb_err get_destination_from_https_headers(const struct list *headers, struct http_request *http)
4655 host = get_header_value(headers, "Host:");
4659 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4660 return JB_ERR_PARSE;
4663 p = strdup_or_die(host);
4665 q = strdup_or_die(p);
4667 freez(http->hostport);
4671 q = strchr(http->host, ':');
4674 /* Terminate hostname and evaluate port string */
4676 http->port = atoi(q);
4683 /* Rebuild request URL */
4685 http->url = strdup_or_die(http->path);
4687 log_error(LOG_LEVEL_HEADER,
4688 "Destination extracted from \"Host\" header. New request URL: %s",
4692 * Regenerate request line in "proxy format"
4693 * to make rewrites more convenient.
4695 assert(http->cmd != NULL);
4697 http->cmd = strdup_or_die(http->gpc);
4698 string_append(&http->cmd, " ");
4699 string_append(&http->cmd, http->url);
4700 string_append(&http->cmd, " ");
4701 string_append(&http->cmd, http->version);
4702 if (http->cmd == NULL)
4704 return JB_ERR_MEMORY;
4710 #endif /* def FEATURE_HTTPS_INSPECTION */
4713 /*********************************************************************
4715 * Function : create_forged_referrer
4717 * Description : Helper for client_referrer to forge a referer as
4718 * 'http://hostname[:port]/' to fool stupid
4719 * checks for in-site links
4722 * 1 : header = Pointer to header pointer
4723 * 2 : hostport = Host and optionally port as string
4725 * Returns : JB_ERR_OK in case of success, or
4726 * JB_ERR_MEMORY in case of memory problems.
4728 *********************************************************************/
4729 static jb_err create_forged_referrer(char **header, const char *hostport)
4731 assert(NULL == *header);
4733 *header = strdup("Referer: http://");
4734 string_append(header, hostport);
4735 string_append(header, "/");
4737 if (NULL == *header)
4739 return JB_ERR_MEMORY;
4742 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4749 /*********************************************************************
4751 * Function : create_fake_referrer
4753 * Description : Helper for client_referrer to create a fake referrer
4754 * based on a string supplied by the user.
4757 * 1 : header = Pointer to header pointer
4758 * 2 : hosthost = Referrer to fake
4760 * Returns : JB_ERR_OK in case of success, or
4761 * JB_ERR_MEMORY in case of memory problems.
4763 *********************************************************************/
4764 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4766 assert(NULL == *header);
4768 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4770 log_error(LOG_LEVEL_HEADER,
4771 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4773 *header = strdup("Referer: ");
4774 string_append(header, fake_referrer);
4776 if (NULL == *header)
4778 return JB_ERR_MEMORY;
4781 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4788 /*********************************************************************
4790 * Function : handle_conditional_hide_referrer_parameter
4792 * Description : Helper for client_referrer to crunch or forge
4793 * the referrer header if the host has changed.
4796 * 1 : header = Pointer to header pointer
4797 * 2 : host = The target host (may include the port)
4798 * 3 : parameter_conditional_block = Boolean to signal
4799 * if we're in conditional-block mode. If not set,
4800 * we're in conditional-forge mode.
4802 * Returns : JB_ERR_OK in case of success, or
4803 * JB_ERR_MEMORY in case of memory problems.
4805 *********************************************************************/
4806 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4807 const char *host, const int parameter_conditional_block)
4809 char *referer = strdup_or_die(*header);
4810 const size_t hostlength = strlen(host);
4811 const char *referer_url = NULL;
4813 /* referer begins with 'Referer: http[s]://' */
4814 if ((hostlength+17) < strlen(referer))
4817 * Shorten referer to make sure the referer is blocked
4818 * if www.example.org/www.example.com-shall-see-the-referer/
4819 * links to www.example.com/
4821 referer[hostlength+17] = '\0';
4823 referer_url = strstr(referer, "http://");
4824 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4826 /* Host has changed, Referer is invalid or a https URL. */
4827 if (parameter_conditional_block)
4829 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4836 return create_forged_referrer(header, host);
4846 /*********************************************************************
4848 * Function : create_content_length_header
4850 * Description : Creates a Content-Length header.
4853 * 1 : content_length = The content length to be used in the header.
4854 * 2 : header = Allocated space to safe the header.
4855 * 3 : buffer_length = The length of the allocated space.
4859 *********************************************************************/
4860 static void create_content_length_header(unsigned long long content_length,
4861 char *header, size_t buffer_length)
4864 #if SIZEOF_LONG_LONG < 8
4865 #error sizeof(unsigned long long) too small
4867 snprintf(header, buffer_length, "Content-Length: %I64u", content_length);
4869 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4874 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4875 /*********************************************************************
4877 * Function : get_expected_content_length
4879 * Description : Figures out the content length from a list of headers.
4882 * 1 : headers = List of headers
4884 * Returns : Number of bytes to expect
4886 *********************************************************************/
4887 unsigned long long get_expected_content_length(struct list *headers)
4889 const char *content_length_header;
4890 unsigned long long content_length = 0;
4892 content_length_header = get_header_value(headers, "Content-Length:");
4893 if (content_length_header != NULL)
4895 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4897 log_error(LOG_LEVEL_ERROR,
4898 "Failed to get the Content-Length in %s", content_length_header);
4899 /* XXX: The header will be removed later on */
4904 return content_length;