1 const char parsers_rcs[] = "$Id: parsers.c,v 1.312 2017/06/08 13:13:26 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
8 * Copyright : Written by and Copyright (C) 2001-2016 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
40 #include <sys/types.h>
50 * Convince GNU's libc to provide a strptime prototype.
59 #define GZIP_IDENTIFIER_1 0x1f
60 #define GZIP_IDENTIFIER_2 0x8b
62 #define GZIP_FLAG_CHECKSUM 0x02
63 #define GZIP_FLAG_EXTRA_FIELDS 0x04
64 #define GZIP_FLAG_FILE_NAME 0x08
65 #define GZIP_FLAG_COMMENT 0x10
66 #define GZIP_FLAG_RESERVED_BITS 0xe0
69 #if !defined(_WIN32) && !defined(__OS2__)
75 #ifdef FEATURE_PTHREAD
77 /* jcc.h is for mutex semapores only */
78 #endif /* def FEATURE_PTHREAD */
83 #include "jbsockets.h"
93 const char parsers_h_rcs[] = PARSERS_H_VERSION;
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_socket
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.
263 * Returns : On success, the number of bytes written are returned (zero
264 * indicates nothing was written). On error, -1 is returned,
265 * and errno is set appropriately. If count is zero and the
266 * file descriptor refers to a regular file, 0 will be
267 * returned without causing any other effect. For a special
268 * file, the results are not portable.
270 *********************************************************************/
271 long flush_socket(jb_socket fd, struct iob *iob)
273 long len = iob->eod - iob->cur;
280 if (write_socket(fd, iob->cur, (size_t)len))
284 iob->eod = iob->cur = iob->buf;
290 /*********************************************************************
292 * Function : add_to_iob
294 * Description : Add content to the buffer, expanding the
295 * buffer if necessary.
298 * 1 : iob = Destination buffer.
299 * 2 : buffer_limit = Limit to which the destination may grow
300 * 3 : src = holds the content to be added
301 * 4 : n = number of bytes to be added
303 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
304 * or buffer limit reached.
306 *********************************************************************/
307 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
309 size_t used, offset, need;
312 if (n <= 0) return JB_ERR_OK;
314 used = (size_t)(iob->eod - iob->buf);
315 offset = (size_t)(iob->cur - iob->buf);
316 need = used + (size_t)n + 1;
319 * If the buffer can't hold the new data, extend it first.
320 * Use the next power of two if possible, else use the actual need.
322 if (need > buffer_limit)
324 log_error(LOG_LEVEL_INFO,
325 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
327 return JB_ERR_MEMORY;
330 if (need > iob->size)
332 size_t want = iob->size ? iob->size : 512;
339 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
343 else if (NULL != (p = (char *)realloc(iob->buf, need)))
349 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
350 return JB_ERR_MEMORY;
353 /* Update the iob pointers */
354 iob->cur = p + offset;
359 /* copy the new data into the iob buffer */
360 memcpy(iob->eod, src, (size_t)n);
362 /* point to the end of the data */
365 /* null terminate == cheap insurance */
373 /*********************************************************************
375 * Function : clear_iob
377 * Description : Frees the memory allocated for an I/O buffer and
378 * resets the structure.
381 * 1 : iob = I/O buffer to clear.
383 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
384 * or buffer limit reached.
386 *********************************************************************/
387 void clear_iob(struct iob *iob)
390 memset(iob, '\0', sizeof(*iob));
395 /*********************************************************************
397 * Function : decompress_iob
399 * Description : Decompress buffered page, expanding the
400 * buffer as necessary. csp->iob->cur
401 * should point to the the beginning of the
402 * compressed data block.
405 * 1 : csp = Current client state (buffers, headers, etc...)
407 * Returns : JB_ERR_OK on success,
408 * JB_ERR_MEMORY if out-of-memory limit reached, and
409 * JB_ERR_COMPRESS if error decompressing buffer.
411 *********************************************************************/
412 jb_err decompress_iob(struct client_state *csp)
414 char *buf; /* new, uncompressed buffer */
415 char *cur; /* Current iob position (to keep the original
416 * iob->cur unmodified if we return early) */
417 size_t bufsize; /* allocated size of the new buffer */
418 size_t old_size; /* Content size before decompression */
419 size_t skip_size; /* Number of bytes at the beginning of the iob
420 that we should NOT decompress. */
421 int status; /* return status of the inflate() call */
422 z_stream zstr; /* used by calls to zlib */
425 assert(csp->iob->cur - csp->iob->buf >= 0);
426 assert(csp->iob->eod - csp->iob->cur >= 0);
428 assert(csp->iob->cur - csp->iob->buf > 0);
429 assert(csp->iob->eod - csp->iob->cur > 0);
432 bufsize = csp->iob->size;
433 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
434 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
438 if (bufsize < (size_t)10)
441 * This is to protect the parsing of gzipped data,
442 * but it should(?) be valid for deflated data also.
444 log_error(LOG_LEVEL_ERROR,
445 "Insufficient data to start decompression. Bytes in buffer: %d",
446 csp->iob->eod - csp->iob->cur);
447 return JB_ERR_COMPRESS;
450 if (csp->content_type & CT_GZIP)
453 * Our task is slightly complicated by the facts that data
454 * compressed by gzip does not include a zlib header, and
455 * that there is no easily accessible interface in zlib to
456 * handle a gzip header. We strip off the gzip header by
457 * hand, and later inform zlib not to expect a header.
461 * Strip off the gzip header. Please see RFC 1952 for more
462 * explanation of the appropriate fields.
464 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
465 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
466 || (*cur++ != Z_DEFLATED))
468 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
469 return JB_ERR_COMPRESS;
474 if (flags & GZIP_FLAG_RESERVED_BITS)
476 /* The gzip header has reserved bits set; bail out. */
477 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
478 return JB_ERR_COMPRESS;
482 * Skip mtime (4 bytes), extra flags (1 byte)
483 * and OS type (1 byte).
487 /* Skip extra fields if necessary. */
488 if (flags & GZIP_FLAG_EXTRA_FIELDS)
491 * Skip a given number of bytes, specified
492 * as a 16-bit little-endian value.
494 * XXX: this code is untested and should probably be removed.
498 skip_bytes += *cur++ << 8;
501 * The number of bytes to skip should be positive
502 * and we'd like to stay in the buffer.
504 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
506 log_error(LOG_LEVEL_ERROR,
507 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
509 return JB_ERR_COMPRESS;
511 log_error(LOG_LEVEL_INFO,
512 "Skipping %d bytes for gzip compression. Does this sound right?",
517 /* Skip the filename if necessary. */
518 if (flags & GZIP_FLAG_FILE_NAME)
520 /* A null-terminated string is supposed to follow. */
521 while (*cur++ && (cur < csp->iob->eod));
524 /* Skip the comment if necessary. */
525 if (flags & GZIP_FLAG_COMMENT)
527 /* A null-terminated string is supposed to follow. */
528 while (*cur++ && (cur < csp->iob->eod));
531 /* Skip the CRC if necessary. */
532 if (flags & GZIP_FLAG_CHECKSUM)
537 if (cur >= csp->iob->eod)
540 * If the current position pointer reached or passed
541 * the buffer end, we were obviously tricked to skip
544 log_error(LOG_LEVEL_ERROR,
545 "Malformed gzip header detected. Aborting decompression.");
546 return JB_ERR_COMPRESS;
550 else if (csp->content_type & CT_DEFLATE)
553 * In theory (that is, according to RFC 1950), deflate-compressed
554 * data should begin with a two-byte zlib header and have an
555 * adler32 checksum at the end. It seems that in practice only
556 * the raw compressed data is sent. Note that this means that
557 * we are not RFC 1950-compliant here, but the advantage is that
558 * this actually works. :)
560 * We add a dummy null byte to tell zlib where the data ends,
561 * and later inform it not to expect a header.
563 * Fortunately, add_to_iob() has thoughtfully null-terminated
564 * the buffer; we can just increment the end pointer to include
571 log_error(LOG_LEVEL_ERROR,
572 "Unable to determine compression format for decompression");
573 return JB_ERR_COMPRESS;
576 /* Set up the fields required by zlib. */
577 zstr.next_in = (Bytef *)cur;
578 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
579 zstr.zalloc = Z_NULL;
581 zstr.opaque = Z_NULL;
584 * Passing -MAX_WBITS to inflateInit2 tells the library
585 * that there is no zlib header.
587 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
589 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
590 return JB_ERR_COMPRESS;
594 * Next, we allocate new storage for the inflated data.
595 * We don't modify the existing iob yet, so in case there
596 * is error in decompression we can recover gracefully.
598 buf = zalloc(bufsize);
601 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
602 return JB_ERR_MEMORY;
605 assert(bufsize >= skip_size);
606 memcpy(buf, csp->iob->buf, skip_size);
607 zstr.avail_out = (uInt)(bufsize - skip_size);
608 zstr.next_out = (Bytef *)buf + skip_size;
610 /* Try to decompress the whole stream in one shot. */
611 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
613 /* We need to allocate more memory for the output buffer. */
615 char *tmpbuf; /* used for realloc'ing the buffer */
616 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
618 if (0 == zstr.avail_in)
621 * If zlib wants more data then there's a problem, because
622 * the complete compressed file should have been buffered.
624 log_error(LOG_LEVEL_ERROR,
625 "Unexpected end of compressed iob. Using what we got so far.");
630 * If we reached the buffer limit and still didn't have enough
631 * memory, just give up. Due to the ceiling enforced by the next
632 * if block we could actually check for equality here, but as it
633 * can be easily mistaken for a bug we don't.
635 if (bufsize >= csp->config->buffer_limit)
637 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
638 return JB_ERR_MEMORY;
641 /* Try doubling the buffer size each time. */
644 /* Don't exceed the buffer limit. */
645 if (bufsize > csp->config->buffer_limit)
647 bufsize = csp->config->buffer_limit;
650 /* Try to allocate the new buffer. */
651 tmpbuf = realloc(buf, bufsize);
654 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
656 return JB_ERR_MEMORY;
660 char *oldnext_out = (char *)zstr.next_out;
663 * Update the fields for inflate() to use the new
664 * buffer, which may be in a location different from
667 zstr.avail_out += (uInt)(bufsize - oldbufsize);
668 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
671 * Compare with an uglier method of calculating these values
672 * that doesn't require the extra oldbufsize variable.
674 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
675 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
681 if (Z_STREAM_ERROR == inflateEnd(&zstr))
683 log_error(LOG_LEVEL_ERROR,
684 "Inconsistent stream state after decompression: %s", zstr.msg);
686 * XXX: Intentionally no return.
688 * According to zlib.h, Z_STREAM_ERROR is returned
689 * "if the stream state was inconsistent".
691 * I assume in this case inflate()'s status
692 * would also be something different than Z_STREAM_END
693 * so this check should be redundant, but lets see.
697 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
700 * We failed to decompress the stream and it's
701 * not simply because of missing data.
703 log_error(LOG_LEVEL_ERROR,
704 "Unexpected error while decompressing to the buffer (iob): %s",
706 return JB_ERR_COMPRESS;
710 * Finally, we can actually update the iob, since the
711 * decompression was successful. First, free the old
714 freez(csp->iob->buf);
716 /* Now, update the iob to use the new buffer. */
718 csp->iob->cur = csp->iob->buf + skip_size;
719 csp->iob->eod = (char *)zstr.next_out;
720 csp->iob->size = bufsize;
723 * Make sure the new uncompressed iob obeys some minimal
724 * consistency conditions.
726 if ((csp->iob->buf <= csp->iob->cur)
727 && (csp->iob->cur <= csp->iob->eod)
728 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
730 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
731 if (new_size > (size_t)0)
733 log_error(LOG_LEVEL_RE_FILTER,
734 "Decompression successful. Old size: %d, new size: %d.",
739 /* zlib thinks this is OK, so lets do the same. */
740 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
745 /* It seems that zlib did something weird. */
746 log_error(LOG_LEVEL_ERROR,
747 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
748 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
749 csp->iob->eod, csp->iob->buf + csp->iob->size);
750 return JB_ERR_COMPRESS;
756 #endif /* defined(FEATURE_ZLIB) */
759 /*********************************************************************
761 * Function : normalize_lws
763 * Description : Reduces unquoted linear whitespace in headers to
764 * a single space in accordance with RFC 7230 3.2.4.
765 * This simplifies parsing and filtering later on.
768 * 1 : header = A header with linear whitespace to reduce.
772 *********************************************************************/
773 static void normalize_lws(char *header)
779 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
783 while (privoxy_isspace(*q))
787 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
793 log_error(LOG_LEVEL_HEADER,
794 "Converting tab to space in '%s'", header);
799 char *end_of_token = strstr(p+1, "\"");
801 if (NULL != end_of_token)
803 /* Don't mess with quoted text. */
808 log_error(LOG_LEVEL_HEADER,
809 "Ignoring single quote in '%s'", header);
815 p = strchr(header, ':');
816 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
819 * There's still space before the colon.
827 /*********************************************************************
829 * Function : get_header
831 * Description : This (odd) routine will parse the csp->iob
832 * to get the next complete header.
835 * 1 : iob = The I/O buffer to parse, usually csp->iob.
837 * Returns : Any one of the following:
839 * 1) a pointer to a dynamically allocated string that contains a header line
840 * 2) NULL indicating that the end of the header was reached
841 * 3) "" indicating that the end of the iob was reached before finding
842 * a complete header line.
844 *********************************************************************/
845 char *get_header(struct iob *iob)
849 header = get_header_line(iob);
851 if ((header == NULL) || (*header == '\0'))
854 * No complete header read yet, tell the client.
859 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
862 * Header spans multiple lines, append the next one.
864 char *continued_header;
866 continued_header = get_header_line(iob);
867 if ((continued_header == NULL) || (*continued_header == '\0'))
870 * No complete header read yet, return what we got.
871 * XXX: Should "unread" header instead.
873 log_error(LOG_LEVEL_INFO,
874 "Failed to read a multi-line header properly: '%s'",
879 if (JB_ERR_OK != string_join(&header, continued_header))
881 log_error(LOG_LEVEL_FATAL,
882 "Out of memory while appending multiple headers.");
886 /* XXX: remove before next stable release. */
887 log_error(LOG_LEVEL_HEADER,
888 "Merged multiple header lines to: '%s'",
893 normalize_lws(header);
900 /*********************************************************************
902 * Function : get_header_line
904 * Description : This (odd) routine will parse the csp->iob
905 * to get the next header line.
908 * 1 : iob = The I/O buffer to parse, usually csp->iob.
910 * Returns : Any one of the following:
912 * 1) a pointer to a dynamically allocated string that contains a header line
913 * 2) NULL indicating that the end of the header was reached
914 * 3) "" indicating that the end of the iob was reached before finding
915 * a complete header line.
917 *********************************************************************/
918 static char *get_header_line(struct iob *iob)
922 if ((iob->cur == NULL)
923 || ((p = strchr(iob->cur, '\n')) == NULL))
925 return(""); /* couldn't find a complete header */
930 ret = strdup(iob->cur);
933 /* FIXME No way to handle error properly */
934 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
940 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
942 /* is this a blank line (i.e. the end of the header) ? */
954 /*********************************************************************
956 * Function : get_header_value
958 * Description : Get the value of a given header from a chained list
959 * of header lines or return NULL if no such header is
960 * present in the list.
963 * 1 : header_list = pointer to list
964 * 2 : header_name = string with name of header to look for.
965 * Trailing colon required, capitalization
968 * Returns : NULL if not found, else value of header
970 *********************************************************************/
971 char *get_header_value(const struct list *header_list, const char *header_name)
973 struct list_entry *cur_entry;
979 length = strlen(header_name);
981 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
985 if (!strncmpic(cur_entry->str, header_name, length))
988 * Found: return pointer to start of value
990 ret = cur_entry->str + length;
991 while (*ret && privoxy_isspace(*ret)) ret++;
1005 /*********************************************************************
1007 * Function : scan_headers
1009 * Description : Scans headers, applies tags and updates action bits.
1012 * 1 : csp = Current client state (buffers, headers, etc...)
1014 * Returns : JB_ERR_OK
1016 *********************************************************************/
1017 static jb_err scan_headers(struct client_state *csp)
1019 struct list_entry *h; /* Header */
1020 jb_err err = JB_ERR_OK;
1022 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1024 /* Header crunch()ed in previous run? -> ignore */
1025 if (h->str == NULL) continue;
1026 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1027 err = header_tagger(csp, h->str);
1034 /*********************************************************************
1036 * Function : enforce_header_order
1038 * Description : Enforces a given header order.
1041 * 1 : headers = List of headers to order.
1042 * 2 : ordered_headers = List of ordered header names.
1046 *********************************************************************/
1047 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1049 struct list_entry *sorted_header;
1050 struct list new_headers[1];
1051 struct list_entry *header;
1053 init_list(new_headers);
1055 /* The request line is always the first "header" */
1057 assert(NULL != headers->first->str);
1058 enlist(new_headers, headers->first->str);
1059 freez(headers->first->str)
1061 /* Enlist the specified headers in the given order */
1063 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1064 sorted_header = sorted_header->next)
1066 const size_t sorted_header_length = strlen(sorted_header->str);
1067 for (header = headers->first; header != NULL; header = header->next)
1069 /* Header enlisted in previous run? -> ignore */
1070 if (header->str == NULL) continue;
1072 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1073 && (header->str[sorted_header_length] == ':'))
1075 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1076 if (JB_ERR_OK != enlist(new_headers, header->str))
1078 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1085 /* Enlist the rest of the headers behind the ordered ones */
1086 for (header = headers->first; header != NULL; header = header->next)
1088 /* Header enlisted in previous run? -> ignore */
1089 if (header->str == NULL) continue;
1091 log_error(LOG_LEVEL_HEADER,
1092 "Enlisting left-over header %s", header->str);
1093 if (JB_ERR_OK != enlist(new_headers, header->str))
1095 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1100 list_remove_all(headers);
1101 list_duplicate(headers, new_headers);
1102 list_remove_all(new_headers);
1108 /*********************************************************************
1112 * Description : add, delete or modify lines in the HTTP header streams.
1113 * On entry, it receives a linked list of headers space
1114 * that was allocated dynamically (both the list nodes
1115 * and the header contents).
1117 * As a side effect it frees the space used by the original
1121 * 1 : csp = Current client state (buffers, headers, etc...)
1122 * 2 : filter_server_headers = Boolean to switch between
1123 * server and header filtering.
1125 * Returns : JB_ERR_OK in case off success, or
1126 * JB_ERR_MEMORY on some out-of-memory errors, or
1127 * JB_ERR_PARSE in case of fatal parse errors.
1129 *********************************************************************/
1130 jb_err sed(struct client_state *csp, int filter_server_headers)
1132 /* XXX: use more descriptive names. */
1133 struct list_entry *p;
1134 const struct parsers *v;
1135 const add_header_func_ptr *f;
1136 jb_err err = JB_ERR_OK;
1140 if (filter_server_headers)
1142 v = server_patterns;
1143 f = add_server_headers;
1144 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1148 v = client_patterns;
1149 f = add_client_headers;
1150 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1153 while (v->str != NULL)
1155 for (p = csp->headers->first; p != NULL; p = p->next)
1157 /* Header crunch()ed in previous run? -> ignore */
1158 if (p->str == NULL) continue;
1160 /* Does the current parser handle this header? */
1161 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1162 (v->len == CHECK_EVERY_HEADER_REMAINING))
1164 err = v->parser(csp, &(p->str));
1165 if (err != JB_ERR_OK)
1174 /* place additional headers on the csp->headers list */
1175 while ((err == JB_ERR_OK) && (*f))
1181 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1183 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1190 /*********************************************************************
1192 * Function : update_server_headers
1194 * Description : Updates server headers after the body has been modified.
1197 * 1 : csp = Current client state (buffers, headers, etc...)
1199 * Returns : JB_ERR_OK in case off success, or
1200 * JB_ERR_MEMORY on out-of-memory error.
1202 *********************************************************************/
1203 jb_err update_server_headers(struct client_state *csp)
1205 jb_err err = JB_ERR_OK;
1207 static const struct parsers server_patterns_light[] = {
1208 { "Content-Length:", 15, server_adjust_content_length },
1209 { "Transfer-Encoding:", 18, server_transfer_coding },
1211 { "Content-Encoding:", 17, server_adjust_content_encoding },
1212 #endif /* def FEATURE_ZLIB */
1216 if (strncmpic(csp->http->cmd, "HEAD", 4))
1218 const struct parsers *v;
1219 struct list_entry *p;
1221 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1223 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1225 /* Header crunch()ed in previous run? -> ignore */
1226 if (p->str == NULL) continue;
1228 /* Does the current parser handle this header? */
1229 if (strncmpic(p->str, v->str, v->len) == 0)
1231 err = v->parser(csp, (char **)&(p->str));
1237 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1238 if ((JB_ERR_OK == err)
1239 && (csp->flags & CSP_FLAG_MODIFIED)
1240 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1241 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1245 create_content_length_header(csp->content_length, header, sizeof(header));
1246 err = enlist(csp->headers, header);
1247 if (JB_ERR_OK == err)
1249 log_error(LOG_LEVEL_HEADER,
1250 "Content modified with no Content-Length header set. "
1251 "Created: %s.", header);
1252 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1255 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1257 #ifdef FEATURE_COMPRESSION
1258 if ((JB_ERR_OK == err)
1259 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1261 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1262 if (JB_ERR_OK == err)
1264 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1273 /*********************************************************************
1275 * Function : header_tagger
1277 * Description : Executes all text substitutions from applying
1278 * tag actions and saves the result as tag.
1280 * XXX: Shares enough code with filter_header() and
1281 * pcrs_filter_response() to warrant some helper functions.
1284 * 1 : csp = Current client state (buffers, headers, etc...)
1285 * 2 : header = Header that is used as tagger input
1287 * Returns : JB_ERR_OK on success and always succeeds
1289 *********************************************************************/
1290 static jb_err header_tagger(struct client_state *csp, char *header)
1292 enum filter_type wanted_filter_type;
1293 int multi_action_index;
1296 struct re_filterfile_spec *b;
1297 struct list_entry *tag_name;
1299 const size_t header_length = strlen(header);
1301 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1303 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1304 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1308 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1309 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1312 if (list_is_empty(csp->action->multi[multi_action_index])
1313 || filters_available(csp) == FALSE)
1315 /* Return early if no taggers apply or if none are available. */
1319 /* Execute all applying taggers */
1320 for (tag_name = csp->action->multi[multi_action_index]->first;
1321 NULL != tag_name; tag_name = tag_name->next)
1323 char *modified_tag = NULL;
1325 size_t size = header_length;
1328 b = get_filter(csp, tag_name->str, wanted_filter_type);
1334 joblist = b->joblist;
1336 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1338 if (NULL == joblist)
1340 log_error(LOG_LEVEL_RE_FILTER,
1341 "Tagger %s has empty joblist. Nothing to do.", b->name);
1345 /* execute their pcrs_joblist on the header. */
1346 for (job = joblist; NULL != job; job = job->next)
1348 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1352 /* Success, continue with the modified version. */
1361 /* Tagger doesn't match */
1364 /* Regex failure, log it but continue anyway. */
1365 assert(NULL != header);
1366 log_error(LOG_LEVEL_ERROR,
1367 "Problems with tagger \'%s\' and header \'%s\': %s",
1368 b->name, *header, pcrs_strerror(hits));
1370 freez(modified_tag);
1374 if (b->dynamic) pcrs_free_joblist(joblist);
1376 /* If this tagger matched */
1382 * There is no technical limitation which makes
1383 * it impossible to use empty tags, but I assume
1384 * no one would do it intentionally.
1387 log_error(LOG_LEVEL_INFO,
1388 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1392 if (!list_contains_item(csp->tags, tag))
1394 if (JB_ERR_OK != enlist(csp->tags, tag))
1396 log_error(LOG_LEVEL_ERROR,
1397 "Insufficient memory to add tag \'%s\', "
1398 "based on tagger \'%s\' and header \'%s\'",
1399 tag, b->name, *header);
1403 char *action_message;
1405 * update the action bits right away, to make
1406 * tagging based on tags set by earlier taggers
1407 * of the same kind possible.
1409 if (update_action_bits_for_tag(csp, tag))
1411 action_message = "Action bits updated accordingly.";
1415 action_message = "No action bits update necessary.";
1418 log_error(LOG_LEVEL_HEADER,
1419 "Tagger \'%s\' added tag \'%s\'. %s",
1420 b->name, tag, action_message);
1425 /* XXX: Is this log-worthy? */
1426 log_error(LOG_LEVEL_HEADER,
1427 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1437 /* here begins the family of parser functions that reformat header lines */
1439 /*********************************************************************
1441 * Function : filter_header
1443 * Description : Executes all text substitutions from all applying
1444 * +(server|client)-header-filter actions on the header.
1445 * Most of the code was copied from pcrs_filter_response,
1446 * including the rather short variable names
1449 * 1 : csp = Current client state (buffers, headers, etc...)
1450 * 2 : header = On input, pointer to header to modify.
1451 * On output, pointer to the modified header, or NULL
1452 * to remove the header. This function frees the
1453 * original string if necessary.
1455 * Returns : JB_ERR_OK on success and always succeeds
1457 *********************************************************************/
1458 static jb_err filter_header(struct client_state *csp, char **header)
1462 size_t size = strlen(*header);
1464 char *newheader = NULL;
1467 struct re_filterfile_spec *b;
1468 struct list_entry *filtername;
1470 enum filter_type wanted_filter_type;
1471 int multi_action_index;
1473 if (csp->flags & CSP_FLAG_NO_FILTERING)
1478 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1480 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1481 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1485 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1486 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1489 if (list_is_empty(csp->action->multi[multi_action_index])
1490 || filters_available(csp) == FALSE)
1492 /* Return early if no filters apply or if none are available. */
1496 /* Execute all applying header filters */
1497 for (filtername = csp->action->multi[multi_action_index]->first;
1498 filtername != NULL; filtername = filtername->next)
1500 int current_hits = 0;
1503 b = get_filter(csp, filtername->str, wanted_filter_type);
1509 joblist = b->joblist;
1511 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1513 if (NULL == joblist)
1515 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1519 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1520 *header, size, b->name);
1522 /* Apply all jobs from the joblist */
1523 for (job = joblist; NULL != job; job = job->next)
1525 matches = pcrs_execute(job, *header, size, &newheader, &size);
1528 current_hits += matches;
1529 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1531 *header = newheader;
1533 else if (0 == matches)
1535 /* Filter doesn't change header */
1541 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1542 *header, b->name, pcrs_strerror(matches));
1543 if (newheader != NULL)
1545 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1551 if (b->dynamic) pcrs_free_joblist(joblist);
1553 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1554 hits += current_hits;
1558 * Additionally checking for hits is important because if
1559 * the continue hack is triggered, server headers can
1560 * arrive empty to separate multiple heads from each other.
1562 if ((0 == size) && hits)
1564 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1572 /*********************************************************************
1574 * Function : server_connection
1576 * Description : Makes sure a proper "Connection:" header is
1577 * set and signals connection_header_adder to
1581 * 1 : csp = Current client state (buffers, headers, etc...)
1582 * 2 : header = On input, pointer to header to modify.
1583 * On output, pointer to the modified header, or NULL
1584 * to remove the header. This function frees the
1585 * original string if necessary.
1587 * Returns : JB_ERR_OK on success.
1589 *********************************************************************/
1590 static jb_err server_connection(struct client_state *csp, char **header)
1592 if (!strcmpic(*header, "Connection: keep-alive")
1593 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1594 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1598 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1599 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1601 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1604 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1606 log_error(LOG_LEVEL_HEADER,
1607 "Keeping the server header '%s' around.", *header);
1610 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1612 char *old_header = *header;
1614 *header = strdup_or_die("Connection: close");
1615 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1620 /* Signal server_connection_adder() to return early. */
1621 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1627 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1628 /*********************************************************************
1630 * Function : server_keep_alive
1632 * Description : Stores the server's keep alive timeout.
1635 * 1 : csp = Current client state (buffers, headers, etc...)
1636 * 2 : header = On input, pointer to header to modify.
1637 * On output, pointer to the modified header, or NULL
1638 * to remove the header. This function frees the
1639 * original string if necessary.
1641 * Returns : JB_ERR_OK.
1643 *********************************************************************/
1644 static jb_err server_keep_alive(struct client_state *csp, char **header)
1646 unsigned int keep_alive_timeout;
1647 const char *timeout_position = strstr(*header, "timeout=");
1649 if ((NULL == timeout_position)
1650 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1652 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1656 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1658 log_error(LOG_LEVEL_HEADER,
1659 "Reducing keep-alive timeout from %u to %u.",
1660 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1661 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1665 /* XXX: Is this log worthy? */
1666 log_error(LOG_LEVEL_HEADER,
1667 "Server keep-alive timeout is %u. Sticking with %u.",
1668 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1670 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1679 /*********************************************************************
1681 * Function : server_proxy_connection
1683 * Description : Figures out whether or not we should add a
1684 * Proxy-Connection header.
1687 * 1 : csp = Current client state (buffers, headers, etc...)
1688 * 2 : header = On input, pointer to header to modify.
1689 * On output, pointer to the modified header, or NULL
1690 * to remove the header. This function frees the
1691 * original string if necessary.
1693 * Returns : JB_ERR_OK.
1695 *********************************************************************/
1696 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1698 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1703 /*********************************************************************
1705 * Function : proxy_authentication
1707 * Description : Removes headers that are relevant for proxy
1708 * authentication unless forwarding them has
1709 * been explicitly requested.
1712 * 1 : csp = Current client state (buffers, headers, etc...)
1713 * 2 : header = On input, pointer to header to modify.
1714 * On output, pointer to the modified header, or NULL
1715 * to remove the header. This function frees the
1716 * original string if necessary.
1718 * Returns : JB_ERR_OK.
1720 *********************************************************************/
1721 static jb_err proxy_authentication(struct client_state *csp, char **header)
1723 if ((csp->config->feature_flags &
1724 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1725 log_error(LOG_LEVEL_HEADER,
1726 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1733 /*********************************************************************
1735 * Function : client_keep_alive
1737 * Description : Stores the client's keep alive timeout.
1740 * 1 : csp = Current client state (buffers, headers, etc...)
1741 * 2 : header = On input, pointer to header to modify.
1742 * On output, pointer to the modified header, or NULL
1743 * to remove the header. This function frees the
1744 * original string if necessary.
1746 * Returns : JB_ERR_OK.
1748 *********************************************************************/
1749 static jb_err client_keep_alive(struct client_state *csp, char **header)
1751 unsigned int keep_alive_timeout;
1752 char *timeout_position;
1754 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1756 log_error(LOG_LEVEL_HEADER,
1757 "keep-alive support is disabled. Crunching: %s.", *header);
1762 /* Check for parameter-less format "Keep-Alive: 100" */
1763 timeout_position = strstr(*header, ": ");
1764 if ((NULL == timeout_position)
1765 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1767 /* Assume parameter format "Keep-Alive: timeout=100" */
1768 timeout_position = strstr(*header, "timeout=");
1769 if ((NULL == timeout_position)
1770 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1772 log_error(LOG_LEVEL_HEADER,
1773 "Couldn't parse: '%s'. Using default timeout %u",
1774 *header, csp->config->keep_alive_timeout);
1781 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1783 log_error(LOG_LEVEL_HEADER,
1784 "Reducing keep-alive timeout from %u to %u.",
1785 csp->config->keep_alive_timeout, keep_alive_timeout);
1786 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1790 /* XXX: Is this log worthy? */
1791 log_error(LOG_LEVEL_HEADER,
1792 "Client keep-alive timeout is %u. Sticking with %u.",
1793 keep_alive_timeout, csp->config->keep_alive_timeout);
1801 /*********************************************************************
1803 * Function : get_content_length
1805 * Description : Gets the content length specified in a
1806 * Content-Length header.
1809 * 1 : header_value = The Content-Length header value.
1810 * 2 : length = Storage to return the value.
1812 * Returns : JB_ERR_OK on success, or
1813 * JB_ERR_PARSE if no value is recognized.
1815 *********************************************************************/
1816 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1819 #if SIZEOF_LONG_LONG < 8
1820 #error sizeof(unsigned long long) too small
1822 if (1 != sscanf(header_value, "%I64u", length))
1824 if (1 != sscanf(header_value, "%llu", length))
1827 return JB_ERR_PARSE;
1834 /*********************************************************************
1836 * Function : client_save_content_length
1838 * Description : Save the Content-Length sent by the client.
1841 * 1 : csp = Current client state (buffers, headers, etc...)
1842 * 2 : header = On input, pointer to header to modify.
1843 * On output, pointer to the modified header, or NULL
1844 * to remove the header. This function frees the
1845 * original string if necessary.
1847 * Returns : JB_ERR_OK on success, or
1848 * JB_ERR_MEMORY on out-of-memory error.
1850 *********************************************************************/
1851 static jb_err client_save_content_length(struct client_state *csp, char **header)
1853 unsigned long long content_length = 0;
1854 const char *header_value;
1856 assert(*(*header+14) == ':');
1858 header_value = *header + 15;
1859 if (JB_ERR_OK != get_content_length(header_value, &content_length))
1861 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1866 csp->expected_client_content_length = content_length;
1871 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1875 /*********************************************************************
1877 * Function : client_connection
1879 * Description : Makes sure a proper "Connection:" header is
1880 * set and signals connection_header_adder
1884 * 1 : csp = Current client state (buffers, headers, etc...)
1885 * 2 : header = On input, pointer to header to modify.
1886 * On output, pointer to the modified header, or NULL
1887 * to remove the header. This function frees the
1888 * original string if necessary.
1890 * Returns : JB_ERR_OK on success.
1892 *********************************************************************/
1893 static jb_err client_connection(struct client_state *csp, char **header)
1895 static const char connection_close[] = "Connection: close";
1897 if (!strcmpic(*header, connection_close))
1899 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1900 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1901 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1903 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1905 log_error(LOG_LEVEL_HEADER,
1906 "Removing \'%s\' to imply keep-alive.", *header);
1909 * While we imply keep-alive to the server,
1910 * we have to remember that the client didn't.
1912 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1916 char *old_header = *header;
1918 *header = strdup_or_die("Connection: keep-alive");
1919 log_error(LOG_LEVEL_HEADER,
1920 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1926 log_error(LOG_LEVEL_HEADER,
1927 "Keeping the client header '%s' around. "
1928 "The connection will not be kept alive.",
1930 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1933 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1934 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1936 log_error(LOG_LEVEL_HEADER,
1937 "Keeping the client header '%s' around. "
1938 "The server connection will be kept alive if possible.",
1940 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1941 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1945 char *old_header = *header;
1947 *header = strdup_or_die(connection_close);
1948 log_error(LOG_LEVEL_HEADER,
1949 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1953 /* Signal client_connection_header_adder() to return early. */
1954 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1960 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1961 /*********************************************************************
1963 * Function : client_proxy_connection
1965 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
1966 * appropriate and removes the Proxy-Connection
1970 * 1 : csp = Current client state (buffers, headers, etc...)
1971 * 2 : header = On input, pointer to header to modify.
1972 * On output, pointer to the modified header, or NULL
1973 * to remove the header. This function frees the
1974 * original string if necessary.
1976 * Returns : JB_ERR_OK
1978 *********************************************************************/
1979 static jb_err client_proxy_connection(struct client_state *csp, char **header)
1981 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1982 && (csp->http->ssl == 0)
1983 && (NULL == strstr(*header, "close")))
1985 log_error(LOG_LEVEL_HEADER,
1986 "The client connection can be kept alive due to: %s", *header);
1987 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1989 crumble(csp, header);
1993 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1996 /*********************************************************************
1998 * Function : client_transfer_encoding
2000 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2001 * the request body is "chunked"
2003 * XXX: Currently not called through sed() as we
2004 * need the flag earlier on. Should be fixed.
2007 * 1 : csp = Current client state (buffers, headers, etc...)
2008 * 2 : header = On input, pointer to header to modify.
2009 * On output, pointer to the modified header, or NULL
2010 * to remove the header. This function frees the
2011 * original string if necessary.
2013 * Returns : JB_ERR_OK on success, or
2015 *********************************************************************/
2016 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2018 if (strstr(*header, "chunked"))
2020 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2021 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2028 /*********************************************************************
2030 * Function : client_expect
2032 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2033 * if the Expect header value is unsupported.
2035 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2036 * MAY and a RFC 2616 (obsolete) MUST.
2039 * 1 : csp = Current client state (buffers, headers, etc...)
2040 * 2 : header = On input, pointer to header to modify.
2041 * On output, pointer to the modified header, or NULL
2042 * to remove the header. This function frees the
2043 * original string if necessary.
2045 * Returns : JB_ERR_OK on success, or
2047 *********************************************************************/
2048 jb_err client_expect(struct client_state *csp, char **header)
2050 if (0 != strcmpic(*header, "Expect: 100-continue"))
2052 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2053 log_error(LOG_LEVEL_HEADER,
2054 "Unsupported client expectaction: %s", *header);
2062 /*********************************************************************
2064 * Function : crumble
2066 * Description : This is called if a header matches a pattern to "crunch"
2069 * 1 : csp = Current client state (buffers, headers, etc...)
2070 * 2 : header = On input, pointer to header to modify.
2071 * On output, pointer to the modified header, or NULL
2072 * to remove the header. This function frees the
2073 * original string if necessary.
2075 * Returns : JB_ERR_OK on success, or
2076 * JB_ERR_MEMORY on out-of-memory error.
2078 *********************************************************************/
2079 static jb_err crumble(struct client_state *csp, char **header)
2082 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2088 /*********************************************************************
2090 * Function : crunch_server_header
2092 * Description : Crunch server header if it matches a string supplied by the
2093 * user. Called from `sed'.
2096 * 1 : csp = Current client state (buffers, headers, etc...)
2097 * 2 : header = On input, pointer to header to modify.
2098 * On output, pointer to the modified header, or NULL
2099 * to remove the header. This function frees the
2100 * original string if necessary.
2102 * Returns : JB_ERR_OK on success and always succeeds
2104 *********************************************************************/
2105 static jb_err crunch_server_header(struct client_state *csp, char **header)
2107 const char *crunch_pattern;
2109 /* Do we feel like crunching? */
2110 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2112 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2114 /* Is the current header the lucky one? */
2115 if (strstr(*header, crunch_pattern))
2117 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2126 /*********************************************************************
2128 * Function : server_content_type
2130 * Description : Set the content-type for filterable types (text/.*,
2131 * .*xml.*, .*script.* and image/gif) unless filtering has been
2132 * forbidden (CT_TABOO) while parsing earlier headers.
2133 * NOTE: Since text/plain is commonly used by web servers
2134 * for files whose correct type is unknown, we don't
2135 * set CT_TEXT for it.
2138 * 1 : csp = Current client state (buffers, headers, etc...)
2139 * 2 : header = On input, pointer to header to modify.
2140 * On output, pointer to the modified header, or NULL
2141 * to remove the header. This function frees the
2142 * original string if necessary.
2144 * Returns : JB_ERR_OK on success, or
2145 * JB_ERR_MEMORY on out-of-memory error.
2147 *********************************************************************/
2148 static jb_err server_content_type(struct client_state *csp, char **header)
2150 /* Remove header if it isn't the first Content-Type header */
2151 if ((csp->content_type & CT_DECLARED))
2153 if (content_filters_enabled(csp->action))
2156 * Making sure the client interprets the content the same way
2157 * Privoxy did is only relevant if Privoxy modified it.
2159 * Checking for this is "hard" as it's not yet known when
2160 * this function is called, thus go shopping and and just
2161 * check if Privoxy could filter it.
2163 * The main thing is that we don't mess with the headers
2164 * unless the user signalled that it's acceptable.
2166 log_error(LOG_LEVEL_HEADER,
2167 "Multiple Content-Type headers detected. "
2168 "Removing and ignoring: %s",
2176 * Signal that the Content-Type has been set.
2178 csp->content_type |= CT_DECLARED;
2180 if (!(csp->content_type & CT_TABOO))
2183 * XXX: The assumption that text/plain is a sign of
2184 * binary data seems to be somewhat unreasonable nowadays
2185 * and should be dropped after 3.0.8 is out.
2187 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2188 || strstr(*header, "xml")
2189 || strstr(*header, "script"))
2191 csp->content_type |= CT_TEXT;
2193 else if (strstr(*header, "image/gif"))
2195 csp->content_type |= CT_GIF;
2200 * Are we messing with the content type?
2202 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2205 * Make sure the user doesn't accidentally
2206 * change the content type of binary documents.
2208 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2212 *header = strdup_or_die("Content-Type: ");
2214 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2215 if (JB_ERR_OK != err)
2217 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2218 return JB_ERR_MEMORY;
2220 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2224 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2225 "It doesn't look like a content type that should be filtered. "
2226 "Enable force-text-mode if you know what you're doing.", *header);
2234 /*********************************************************************
2236 * Function : server_transfer_coding
2238 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2239 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2240 * - Remove header if body was chunked but has been
2241 * de-chunked for filtering.
2244 * 1 : csp = Current client state (buffers, headers, etc...)
2245 * 2 : header = On input, pointer to header to modify.
2246 * On output, pointer to the modified header, or NULL
2247 * to remove the header. This function frees the
2248 * original string if necessary.
2250 * Returns : JB_ERR_OK on success, or
2251 * JB_ERR_MEMORY on out-of-memory error.
2253 *********************************************************************/
2254 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2257 * Turn off pcrs and gif filtering if body compressed
2259 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2263 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2265 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2266 csp->http->cmd, *header);
2267 #endif /* def FEATURE_ZLIB */
2268 csp->content_type = CT_TABOO;
2272 * Raise flag if body chunked
2274 if (strstr(*header, "chunked"))
2276 csp->flags |= CSP_FLAG_CHUNKED;
2279 * If the body was modified, it has been de-chunked first
2280 * and the header must be removed.
2282 * FIXME: If there is more than one transfer encoding,
2283 * only the "chunked" part should be removed here.
2285 if (csp->flags & CSP_FLAG_MODIFIED)
2287 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2296 /*********************************************************************
2298 * Function : server_content_encoding
2300 * Description : Used to check if the content is compressed, and if
2301 * FEATURE_ZLIB is disabled, filtering is disabled as
2304 * If FEATURE_ZLIB is enabled and the compression type
2305 * supported, the content is marked for decompression.
2307 * XXX: Doesn't properly deal with multiple or with
2308 * unsupported but unknown encodings.
2309 * Is case-sensitive but shouldn't be.
2312 * 1 : csp = Current client state (buffers, headers, etc...)
2313 * 2 : header = On input, pointer to header to modify.
2314 * On output, pointer to the modified header, or NULL
2315 * to remove the header. This function frees the
2316 * original string if necessary.
2318 * Returns : JB_ERR_OK on success, or
2319 * JB_ERR_MEMORY on out-of-memory error.
2321 *********************************************************************/
2322 static jb_err server_content_encoding(struct client_state *csp, char **header)
2325 if (strstr(*header, "sdch"))
2328 * Shared Dictionary Compression over HTTP isn't supported,
2329 * filtering it anyway is pretty much guaranteed to mess up
2332 csp->content_type |= CT_TABOO;
2335 * Log a warning if the user expects the content to be filtered.
2337 if (content_filters_enabled(csp->action))
2339 log_error(LOG_LEVEL_INFO,
2340 "SDCH-compressed content detected, content filtering disabled. "
2341 "Consider suppressing SDCH offers made by the client.");
2344 else if (strstr(*header, "gzip"))
2346 /* Mark for gzip decompression */
2347 csp->content_type |= CT_GZIP;
2349 else if (strstr(*header, "deflate"))
2351 /* Mark for zlib decompression */
2352 csp->content_type |= CT_DEFLATE;
2354 else if (strstr(*header, "compress"))
2357 * We can't decompress this; therefore we can't filter
2360 csp->content_type |= CT_TABOO;
2362 #else /* !defined(FEATURE_ZLIB) */
2364 * XXX: Using a black list here isn't the right approach.
2366 * In case of SDCH, building with zlib support isn't
2369 if (strstr(*header, "gzip") ||
2370 strstr(*header, "compress") ||
2371 strstr(*header, "deflate") ||
2372 strstr(*header, "sdch"))
2375 * Body is compressed, turn off pcrs and gif filtering.
2377 csp->content_type |= CT_TABOO;
2380 * Log a warning if the user expects the content to be filtered.
2382 if (content_filters_enabled(csp->action))
2384 log_error(LOG_LEVEL_INFO,
2385 "Compressed content detected, content filtering disabled. "
2386 "Consider recompiling Privoxy with zlib support or "
2387 "enable the prevent-compression action.");
2390 #endif /* defined(FEATURE_ZLIB) */
2398 /*********************************************************************
2400 * Function : server_adjust_content_encoding
2402 * Description : Remove the Content-Encoding header if the
2403 * decompression was successful and the content
2407 * 1 : csp = Current client state (buffers, headers, etc...)
2408 * 2 : header = On input, pointer to header to modify.
2409 * On output, pointer to the modified header, or NULL
2410 * to remove the header. This function frees the
2411 * original string if necessary.
2413 * Returns : JB_ERR_OK on success, or
2414 * JB_ERR_MEMORY on out-of-memory error.
2416 *********************************************************************/
2417 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2419 if ((csp->flags & CSP_FLAG_MODIFIED)
2420 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2423 * We successfully decompressed the content,
2424 * and have to clean the header now, so the
2425 * client no longer expects compressed data.
2427 * XXX: There is a difference between cleaning
2428 * and removing it completely.
2430 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2437 #endif /* defined(FEATURE_ZLIB) */
2440 /*********************************************************************
2442 * Function : server_adjust_content_length
2444 * Description : Adjust Content-Length header if we modified
2448 * 1 : csp = Current client state (buffers, headers, etc...)
2449 * 2 : header = On input, pointer to header to modify.
2450 * On output, pointer to the modified header, or NULL
2451 * to remove the header. This function frees the
2452 * original string if necessary.
2454 * Returns : JB_ERR_OK on success, or
2455 * JB_ERR_MEMORY on out-of-memory error.
2457 *********************************************************************/
2458 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2460 /* Regenerate header if the content was modified. */
2461 if (csp->flags & CSP_FLAG_MODIFIED)
2463 const size_t header_length = 50;
2465 *header = malloc(header_length);
2466 if (*header == NULL)
2468 return JB_ERR_MEMORY;
2470 create_content_length_header(csp->content_length, *header, header_length);
2471 log_error(LOG_LEVEL_HEADER,
2472 "Adjusted Content-Length to %llu", csp->content_length);
2479 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2480 /*********************************************************************
2482 * Function : server_save_content_length
2484 * Description : Save the Content-Length sent by the server.
2487 * 1 : csp = Current client state (buffers, headers, etc...)
2488 * 2 : header = On input, pointer to header to modify.
2489 * On output, pointer to the modified header, or NULL
2490 * to remove the header. This function frees the
2491 * original string if necessary.
2493 * Returns : JB_ERR_OK on success, or
2494 * JB_ERR_MEMORY on out-of-memory error.
2496 *********************************************************************/
2497 static jb_err server_save_content_length(struct client_state *csp, char **header)
2499 unsigned long long content_length = 0;
2500 const char *header_value;
2502 assert(*(*header+14) == ':');
2504 header_value = *header + 15;
2505 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2507 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2512 csp->expected_content_length = content_length;
2513 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2514 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2519 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2522 /*********************************************************************
2524 * Function : server_content_md5
2526 * Description : Crumble any Content-MD5 headers if the document was
2527 * modified. FIXME: Should we re-compute instead?
2530 * 1 : csp = Current client state (buffers, headers, etc...)
2531 * 2 : header = On input, pointer to header to modify.
2532 * On output, pointer to the modified header, or NULL
2533 * to remove the header. This function frees the
2534 * original string if necessary.
2536 * Returns : JB_ERR_OK on success, or
2537 * JB_ERR_MEMORY on out-of-memory error.
2539 *********************************************************************/
2540 static jb_err server_content_md5(struct client_state *csp, char **header)
2542 if (csp->flags & CSP_FLAG_MODIFIED)
2544 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2552 /*********************************************************************
2554 * Function : server_content_disposition
2556 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2557 * Called from `sed'.
2560 * 1 : csp = Current client state (buffers, headers, etc...)
2561 * 2 : header = On input, pointer to header to modify.
2562 * On output, pointer to the modified header, or NULL
2563 * to remove the header. This function frees the
2564 * original string if necessary.
2566 * Returns : JB_ERR_OK on success, or
2567 * JB_ERR_MEMORY on out-of-memory error.
2569 *********************************************************************/
2570 static jb_err server_content_disposition(struct client_state *csp, char **header)
2575 * Are we messing with the Content-Disposition header?
2577 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2583 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2585 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2588 * Blocking content-disposition header
2590 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2597 * Replacing Content-Disposition header
2600 *header = strdup("Content-Disposition: ");
2601 string_append(header, newval);
2603 if (*header != NULL)
2605 log_error(LOG_LEVEL_HEADER,
2606 "Content-Disposition header crunched and replaced with: %s", *header);
2609 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2613 /*********************************************************************
2615 * Function : server_last_modified
2617 * Description : Changes Last-Modified header to the actual date
2618 * to help hide-if-modified-since.
2619 * Called from `sed'.
2622 * 1 : csp = Current client state (buffers, headers, etc...)
2623 * 2 : header = On input, pointer to header to modify.
2624 * On output, pointer to the modified header, or NULL
2625 * to remove the header. This function frees the
2626 * original string if necessary.
2628 * Returns : JB_ERR_OK on success, or
2629 * JB_ERR_MEMORY on out-of-memory error.
2631 *********************************************************************/
2632 static jb_err server_last_modified(struct client_state *csp, char **header)
2635 time_t last_modified;
2639 * Are we messing with the Last-Modified header?
2641 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2647 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2649 if (0 == strcmpic(newval, "block"))
2652 * Blocking Last-Modified header. Useless but why not.
2654 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2658 else if (0 == strcmpic(newval, "reset-to-request-time"))
2661 * Setting Last-Modified Header to now.
2664 get_http_time(0, buf, sizeof(buf));
2666 *header = strdup("Last-Modified: ");
2667 string_append(header, buf);
2669 if (*header == NULL)
2671 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2675 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2678 else if (0 == strcmpic(newval, "randomize"))
2680 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2682 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2684 log_error(LOG_LEVEL_HEADER,
2685 "Couldn't parse time in %s (crunching!)", *header);
2691 struct tm *timeptr = NULL;
2693 #ifdef HAVE_GMTIME_R
2697 rtime = (long int)difftime(now, last_modified);
2700 long int days, hours, minutes, seconds;
2701 const int negative_delta = (rtime < 0);
2706 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2708 rtime = pick_from_range(rtime);
2713 last_modified += rtime;
2714 #ifdef HAVE_GMTIME_R
2715 timeptr = gmtime_r(&last_modified, &gmt);
2716 #elif defined(MUTEX_LOCKS_AVAILABLE)
2717 privoxy_mutex_lock(&gmtime_mutex);
2718 timeptr = gmtime(&last_modified);
2719 privoxy_mutex_unlock(&gmtime_mutex);
2721 timeptr = gmtime(&last_modified);
2723 if ((NULL == timeptr) || !strftime(newheader,
2724 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2726 log_error(LOG_LEVEL_ERROR,
2727 "Randomizing '%s' failed. Crunching the header without replacement.",
2734 *header = strdup("Last-Modified: ");
2735 string_append(header, newheader);
2737 if (*header == NULL)
2739 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2740 return JB_ERR_MEMORY;
2743 days = rtime / (3600 * 24);
2744 hours = rtime / 3600 % 24;
2745 minutes = rtime / 60 % 60;
2746 seconds = rtime % 60;
2748 log_error(LOG_LEVEL_HEADER,
2749 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2750 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2751 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2755 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2764 /*********************************************************************
2766 * Function : client_accept_encoding
2768 * Description : Rewrite the client's Accept-Encoding header so that
2769 * if doesn't allow compression, if the action applies.
2770 * Note: For HTTP/1.0 the absence of the header is enough.
2773 * 1 : csp = Current client state (buffers, headers, etc...)
2774 * 2 : header = On input, pointer to header to modify.
2775 * On output, pointer to the modified header, or NULL
2776 * to remove the header. This function frees the
2777 * original string if necessary.
2779 * Returns : JB_ERR_OK on success, or
2780 * JB_ERR_MEMORY on out-of-memory error.
2782 *********************************************************************/
2783 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2785 #ifdef FEATURE_COMPRESSION
2786 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2787 && strstr(*header, "deflate"))
2789 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2792 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2794 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2802 /*********************************************************************
2804 * Function : client_te
2806 * Description : Rewrite the client's TE header so that
2807 * if doesn't allow compression, if the action applies.
2810 * 1 : csp = Current client state (buffers, headers, etc...)
2811 * 2 : header = On input, pointer to header to modify.
2812 * On output, pointer to the modified header, or NULL
2813 * to remove the header. This function frees the
2814 * original string if necessary.
2816 * Returns : JB_ERR_OK on success, or
2817 * JB_ERR_MEMORY on out-of-memory error.
2819 *********************************************************************/
2820 static jb_err client_te(struct client_state *csp, char **header)
2822 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2825 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2832 /*********************************************************************
2834 * Function : client_referrer
2836 * Description : Handle the "referer" config setting properly.
2837 * Called from `sed'.
2840 * 1 : csp = Current client state (buffers, headers, etc...)
2841 * 2 : header = On input, pointer to header to modify.
2842 * On output, pointer to the modified header, or NULL
2843 * to remove the header. This function frees the
2844 * original string if necessary.
2846 * Returns : JB_ERR_OK on success, or
2847 * JB_ERR_MEMORY on out-of-memory error.
2849 *********************************************************************/
2850 static jb_err client_referrer(struct client_state *csp, char **header)
2852 const char *parameter;
2853 /* booleans for parameters we have to check multiple times */
2854 int parameter_conditional_block;
2855 int parameter_conditional_forge;
2857 #ifdef FEATURE_FORCE_LOAD
2859 * Since the referrer can include the prefix even
2860 * if the request itself is non-forced, we must
2861 * clean it unconditionally.
2863 * XXX: strclean is too broad
2865 strclean(*header, FORCE_PREFIX);
2866 #endif /* def FEATURE_FORCE_LOAD */
2868 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2870 /* Nothing left to do */
2874 parameter = csp->action->string[ACTION_STRING_REFERER];
2875 assert(parameter != NULL);
2876 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2877 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2879 if (!parameter_conditional_block && !parameter_conditional_forge)
2882 * As conditional-block and conditional-forge are the only
2883 * parameters that rely on the original referrer, we can
2884 * remove it now for all the others.
2889 if (0 == strcmpic(parameter, "block"))
2891 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2894 else if (parameter_conditional_block || parameter_conditional_forge)
2896 return handle_conditional_hide_referrer_parameter(header,
2897 csp->http->hostport, parameter_conditional_block);
2899 else if (0 == strcmpic(parameter, "forge"))
2901 return create_forged_referrer(header, csp->http->hostport);
2905 /* interpret parameter as user-supplied referer to fake */
2906 return create_fake_referrer(header, parameter);
2911 /*********************************************************************
2913 * Function : client_accept_language
2915 * Description : Handle the "Accept-Language" config setting properly.
2916 * Called from `sed'.
2919 * 1 : csp = Current client state (buffers, headers, etc...)
2920 * 2 : header = On input, pointer to header to modify.
2921 * On output, pointer to the modified header, or NULL
2922 * to remove the header. This function frees the
2923 * original string if necessary.
2925 * Returns : JB_ERR_OK on success, or
2926 * JB_ERR_MEMORY on out-of-memory error.
2928 *********************************************************************/
2929 static jb_err client_accept_language(struct client_state *csp, char **header)
2934 * Are we messing with the Accept-Language?
2936 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2938 /*I don't think so*/
2942 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2944 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2947 * Blocking Accept-Language header
2949 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2956 * Replacing Accept-Language header
2959 *header = strdup("Accept-Language: ");
2960 string_append(header, newval);
2962 if (*header == NULL)
2964 log_error(LOG_LEVEL_ERROR,
2965 "Insufficient memory. Accept-Language header crunched without replacement.");
2969 log_error(LOG_LEVEL_HEADER,
2970 "Accept-Language header crunched and replaced with: %s", *header);
2973 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2977 /*********************************************************************
2979 * Function : crunch_client_header
2981 * Description : Crunch client header if it matches a string supplied by the
2982 * user. Called from `sed'.
2985 * 1 : csp = Current client state (buffers, headers, etc...)
2986 * 2 : header = On input, pointer to header to modify.
2987 * On output, pointer to the modified header, or NULL
2988 * to remove the header. This function frees the
2989 * original string if necessary.
2991 * Returns : JB_ERR_OK on success and always succeeds
2993 *********************************************************************/
2994 static jb_err crunch_client_header(struct client_state *csp, char **header)
2996 const char *crunch_pattern;
2998 /* Do we feel like crunching? */
2999 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3001 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3003 /* Is the current header the lucky one? */
3004 if (strstr(*header, crunch_pattern))
3006 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3014 /*********************************************************************
3016 * Function : client_uagent
3018 * Description : Handle the "user-agent" config setting properly
3019 * and remember its original value to enable browser
3020 * bug workarounds. Called from `sed'.
3023 * 1 : csp = Current client state (buffers, headers, etc...)
3024 * 2 : header = On input, pointer to header to modify.
3025 * On output, pointer to the modified header, or NULL
3026 * to remove the header. This function frees the
3027 * original string if necessary.
3029 * Returns : JB_ERR_OK on success, or
3030 * JB_ERR_MEMORY on out-of-memory error.
3032 *********************************************************************/
3033 static jb_err client_uagent(struct client_state *csp, char **header)
3037 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3042 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3049 *header = strdup("User-Agent: ");
3050 string_append(header, newval);
3052 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3054 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3058 /*********************************************************************
3060 * Function : client_ua
3062 * Description : Handle "ua-" headers properly. Called from `sed'.
3065 * 1 : csp = Current client state (buffers, headers, etc...)
3066 * 2 : header = On input, pointer to header to modify.
3067 * On output, pointer to the modified header, or NULL
3068 * to remove the header. This function frees the
3069 * original string if necessary.
3071 * Returns : JB_ERR_OK on success, or
3072 * JB_ERR_MEMORY on out-of-memory error.
3074 *********************************************************************/
3075 static jb_err client_ua(struct client_state *csp, char **header)
3077 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3079 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3087 /*********************************************************************
3089 * Function : client_from
3091 * Description : Handle the "from" config setting properly.
3092 * Called from `sed'.
3095 * 1 : csp = Current client state (buffers, headers, etc...)
3096 * 2 : header = On input, pointer to header to modify.
3097 * On output, pointer to the modified header, or NULL
3098 * to remove the header. This function frees the
3099 * original string if necessary.
3101 * Returns : JB_ERR_OK on success, or
3102 * JB_ERR_MEMORY on out-of-memory error.
3104 *********************************************************************/
3105 static jb_err client_from(struct client_state *csp, char **header)
3109 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3116 newval = csp->action->string[ACTION_STRING_FROM];
3119 * Are we blocking the e-mail address?
3121 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3123 log_error(LOG_LEVEL_HEADER, "crunched From!");
3127 log_error(LOG_LEVEL_HEADER, " modified");
3129 *header = strdup("From: ");
3130 string_append(header, newval);
3132 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3136 /*********************************************************************
3138 * Function : client_send_cookie
3140 * Description : Crunches the "cookie" header if necessary.
3141 * Called from `sed'.
3143 * XXX: Stupid name, doesn't send squat.
3146 * 1 : csp = Current client state (buffers, headers, etc...)
3147 * 2 : header = On input, pointer to header to modify.
3148 * On output, pointer to the modified header, or NULL
3149 * to remove the header. This function frees the
3150 * original string if necessary.
3152 * Returns : JB_ERR_OK on success, or
3153 * JB_ERR_MEMORY on out-of-memory error.
3155 *********************************************************************/
3156 static jb_err client_send_cookie(struct client_state *csp, char **header)
3158 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3160 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3168 /*********************************************************************
3170 * Function : client_x_forwarded
3172 * Description : Handle the "x-forwarded-for" config setting properly,
3173 * also used in the add_client_headers list. 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 jb_err client_x_forwarded(struct client_state *csp, char **header)
3188 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3190 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3192 if (0 == strcmpic(parameter, "block"))
3195 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3197 else if (0 == strcmpic(parameter, "add"))
3199 string_append(header, ", ");
3200 string_append(header, csp->ip_addr_str);
3202 if (*header == NULL)
3204 return JB_ERR_MEMORY;
3206 log_error(LOG_LEVEL_HEADER,
3207 "Appended client IP address to %s", *header);
3208 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3212 log_error(LOG_LEVEL_FATAL,
3213 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3221 /*********************************************************************
3223 * Function : client_max_forwards
3225 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3226 * from the value of the Max-Forwards header field.
3229 * 1 : csp = Current client state (buffers, headers, etc...)
3230 * 2 : header = On input, pointer to header to modify.
3231 * On output, pointer to the modified header, or NULL
3232 * to remove the header. This function frees the
3233 * original string if necessary.
3235 * Returns : JB_ERR_OK on success, or
3236 * JB_ERR_MEMORY on out-of-memory error.
3238 *********************************************************************/
3239 static jb_err client_max_forwards(struct client_state *csp, char **header)
3243 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3244 (0 == strcmpic(csp->http->gpc, "options")))
3246 assert(*(*header+12) == ':');
3247 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3249 if (max_forwards > 0)
3251 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3252 log_error(LOG_LEVEL_HEADER,
3253 "Max-Forwards value for %s request reduced to %d.",
3254 csp->http->gpc, max_forwards);
3256 else if (max_forwards < 0)
3258 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3264 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3273 /*********************************************************************
3275 * Function : client_host
3277 * Description : If the request URI did not contain host and
3278 * port information, parse and evaluate the Host
3282 * 1 : csp = Current client state (buffers, headers, etc...)
3283 * 2 : header = On input, pointer to header to modify.
3284 * On output, pointer to the modified header, or NULL
3285 * to remove the header. This function frees the
3286 * original string if necessary.
3288 * Returns : JB_ERR_OK on success, or
3289 * JB_ERR_MEMORY on out-of-memory error.
3291 *********************************************************************/
3292 static jb_err client_host(struct client_state *csp, char **header)
3296 if (strlen(*header) < 7)
3298 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3303 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3304 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3307 p = strdup_or_die((*header)+6);
3309 q = strdup_or_die(p);
3311 freez(csp->http->hostport);
3312 csp->http->hostport = p;
3313 freez(csp->http->host);
3314 csp->http->host = q;
3315 q = strchr(csp->http->host, ':');
3318 /* Terminate hostname and evaluate port string */
3320 csp->http->port = atoi(q);
3324 csp->http->port = csp->http->ssl ? 443 : 80;
3327 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3328 csp->http->hostport, csp->http->host, csp->http->port);
3331 /* Signal client_host_adder() to return right away */
3332 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3338 /*********************************************************************
3340 * Function : client_if_modified_since
3342 * Description : Remove or modify the If-Modified-Since header.
3345 * 1 : csp = Current client state (buffers, headers, etc...)
3346 * 2 : header = On input, pointer to header to modify.
3347 * On output, pointer to the modified header, or NULL
3348 * to remove the header. This function frees the
3349 * original string if necessary.
3351 * Returns : JB_ERR_OK on success, or
3352 * JB_ERR_MEMORY on out-of-memory error.
3354 *********************************************************************/
3355 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3358 #ifdef HAVE_GMTIME_R
3361 struct tm *timeptr = NULL;
3366 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3369 * The client got an error message because of a temporary problem,
3370 * the problem is gone and the client now tries to revalidate our
3371 * error message on the real server. The revalidation would always
3372 * end with the transmission of the whole document and there is
3373 * no need to expose the bogus If-Modified-Since header.
3375 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3378 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3380 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3382 if ((0 == strcmpic(newval, "block")))
3384 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3387 else /* add random value */
3389 if (JB_ERR_OK != parse_time_header(*header, &tm))
3391 log_error(LOG_LEVEL_HEADER,
3392 "Couldn't parse time in %s (crunching!)", *header);
3397 long int hours, minutes, seconds;
3398 long int rtime = strtol(newval, &endptr, 0);
3399 const int negative_range = (rtime < 0);
3403 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3404 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3410 rtime = pick_from_range(rtime);
3414 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3417 tm += rtime * (negative_range ? -1 : 1);
3418 #ifdef HAVE_GMTIME_R
3419 timeptr = gmtime_r(&tm, &gmt);
3420 #elif defined(MUTEX_LOCKS_AVAILABLE)
3421 privoxy_mutex_lock(&gmtime_mutex);
3422 timeptr = gmtime(&tm);
3423 privoxy_mutex_unlock(&gmtime_mutex);
3425 timeptr = gmtime(&tm);
3427 if ((NULL == timeptr) || !strftime(newheader,
3428 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3430 log_error(LOG_LEVEL_ERROR,
3431 "Randomizing '%s' failed. Crunching the header without replacement.",
3438 *header = strdup("If-Modified-Since: ");
3439 string_append(header, newheader);
3441 if (*header == NULL)
3443 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3444 return JB_ERR_MEMORY;
3447 hours = rtime / 3600;
3448 minutes = rtime / 60 % 60;
3449 seconds = rtime % 60;
3451 log_error(LOG_LEVEL_HEADER,
3452 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3453 *header, (negative_range) ? "subtracted" : "added", hours,
3454 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3455 seconds, (seconds == 1) ? ")" : "s)");
3464 /*********************************************************************
3466 * Function : client_if_none_match
3468 * Description : Remove the If-None-Match header.
3471 * 1 : csp = Current client state (buffers, headers, etc...)
3472 * 2 : header = On input, pointer to header to modify.
3473 * On output, pointer to the modified header, or NULL
3474 * to remove the header. This function frees the
3475 * original string if necessary.
3477 * Returns : JB_ERR_OK on success, or
3478 * JB_ERR_MEMORY on out-of-memory error.
3480 *********************************************************************/
3481 static jb_err client_if_none_match(struct client_state *csp, char **header)
3483 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3485 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3493 /*********************************************************************
3495 * Function : client_x_filter
3497 * Description : Disables filtering if the client set "X-Filter: No".
3498 * Called from `sed'.
3501 * 1 : csp = Current client state (buffers, headers, etc...)
3502 * 2 : header = On input, pointer to header to modify.
3503 * On output, pointer to the modified header, or NULL
3504 * to remove the header. This function frees the
3505 * original string if necessary.
3507 * Returns : JB_ERR_OK on success
3509 *********************************************************************/
3510 jb_err client_x_filter(struct client_state *csp, char **header)
3512 if (0 == strcmpic(*header, "X-Filter: No"))
3514 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3516 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3520 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3522 log_error(LOG_LEVEL_HEADER,
3523 "force-text-mode overruled the client's request to fetch without filtering!");
3527 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3528 csp->flags |= CSP_FLAG_NO_FILTERING;
3529 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3531 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3539 /*********************************************************************
3541 * Function : client_range
3543 * Description : Removes Range, Request-Range and If-Range headers if
3544 * content filtering is enabled and the range doesn't
3547 * If the client's version of the document has been
3548 * altered by Privoxy, the server could interpret the
3549 * range differently than the client intended in which
3550 * case the user could end up with corrupted content.
3552 * If the range starts at byte 0 this isn't an issue
3553 * so the header can pass. Partial requests like this
3554 * are used to render preview images for videos without
3555 * downloading the whole video.
3557 * While HTTP doesn't require that range requests are
3558 * honoured and the client could simply abort the download
3559 * after receiving a sufficient amount of data, various
3560 * clients don't handle complete responses to range
3561 * requests gracefully and emit misleading error messages
3565 * 1 : csp = Current client state (buffers, headers, etc...)
3566 * 2 : header = On input, pointer to header to modify.
3567 * On output, pointer to the modified header, or NULL
3568 * to remove the header. This function frees the
3569 * original string if necessary.
3571 * Returns : JB_ERR_OK
3573 *********************************************************************/
3574 static jb_err client_range(struct client_state *csp, char **header)
3576 if (content_filters_enabled(csp->action)
3577 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3579 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3580 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3587 /* the following functions add headers directly to the header list */
3589 /*********************************************************************
3591 * Function : client_host_adder
3593 * Description : Adds the Host: header field if it is missing.
3594 * Called from `sed'.
3597 * 1 : csp = Current client state (buffers, headers, etc...)
3599 * Returns : JB_ERR_OK on success, or
3600 * JB_ERR_MEMORY on out-of-memory error.
3602 *********************************************************************/
3603 static jb_err client_host_adder(struct client_state *csp)
3608 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3610 /* Header already set by the client, nothing to do. */
3614 if (!csp->http->hostport || !*(csp->http->hostport))
3616 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3617 return JB_ERR_PARSE;
3621 * remove 'user:pass@' from 'proto://user:pass@host'
3623 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3629 p = csp->http->hostport;
3632 /* XXX: Just add it, we already made sure that it will be unique */
3633 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3634 err = enlist_unique_header(csp->headers, "Host", p);
3640 /*********************************************************************
3642 * Function : client_xtra_adder
3644 * Description : Used in the add_client_headers list. Called from `sed'.
3647 * 1 : csp = Current client state (buffers, headers, etc...)
3649 * Returns : JB_ERR_OK on success, or
3650 * JB_ERR_MEMORY on out-of-memory error.
3652 *********************************************************************/
3653 static jb_err client_xtra_adder(struct client_state *csp)
3655 struct list_entry *lst;
3658 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3659 lst ; lst = lst->next)
3661 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3662 err = enlist(csp->headers, lst->str);
3674 /*********************************************************************
3676 * Function : client_x_forwarded_for_adder
3678 * Description : Used in the add_client_headers list. Called from `sed'.
3681 * 1 : csp = Current client state (buffers, headers, etc...)
3683 * Returns : JB_ERR_OK on success, or
3684 * JB_ERR_MEMORY on out-of-memory error.
3686 *********************************************************************/
3687 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3689 char *header = NULL;
3692 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3693 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3694 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3697 * If we aren't adding X-Forwarded-For headers,
3698 * or we already appended an existing X-Forwarded-For
3699 * header, there's nothing left to do here.
3704 header = strdup("X-Forwarded-For: ");
3705 string_append(&header, csp->ip_addr_str);
3709 return JB_ERR_MEMORY;
3712 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3713 err = enlist(csp->headers, header);
3720 /*********************************************************************
3722 * Function : server_connection_adder
3724 * Description : Adds an appropriate "Connection:" header to csp->headers
3725 * unless the header was already present. Called from `sed'.
3728 * 1 : csp = Current client state (buffers, headers, etc...)
3730 * Returns : JB_ERR_OK on success, or
3731 * JB_ERR_MEMORY on out-of-memory error.
3733 *********************************************************************/
3734 static jb_err server_connection_adder(struct client_state *csp)
3736 const unsigned int flags = csp->flags;
3737 const char *response_status_line = csp->headers->first->str;
3738 static const char connection_close[] = "Connection: close";
3740 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3741 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3747 * XXX: if we downgraded the response, this check will fail.
3749 if ((csp->config->feature_flags &
3750 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3751 && (NULL != response_status_line)
3752 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3753 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3754 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3758 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3759 "without Connection header implies keep-alive.");
3760 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3764 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3766 return enlist(csp->headers, connection_close);
3770 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3771 /*********************************************************************
3773 * Function : server_proxy_connection_adder
3775 * Description : Adds a "Proxy-Connection: keep-alive" header to
3776 * csp->headers when appropriate.
3779 * 1 : csp = Current client state (buffers, headers, etc...)
3781 * Returns : JB_ERR_OK on success, or
3782 * JB_ERR_MEMORY on out-of-memory error.
3784 *********************************************************************/
3785 static jb_err server_proxy_connection_adder(struct client_state *csp)
3787 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3788 jb_err err = JB_ERR_OK;
3790 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3791 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3792 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3793 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3794 || (csp->flags & CSP_FLAG_CHUNKED)))
3796 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3797 err = enlist(csp->headers, proxy_connection_header);
3802 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3805 /*********************************************************************
3807 * Function : client_connection_header_adder
3809 * Description : Adds a proper "Connection:" header to csp->headers
3810 * unless the header was already present or it's a
3811 * CONNECT request. Called from `sed'.
3814 * 1 : csp = Current client state (buffers, headers, etc...)
3816 * Returns : JB_ERR_OK on success, or
3817 * JB_ERR_MEMORY on out-of-memory error.
3819 *********************************************************************/
3820 static jb_err client_connection_header_adder(struct client_state *csp)
3822 static const char connection_close[] = "Connection: close";
3824 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3825 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3831 * In case of CONNECT requests "Connection: close" is implied,
3832 * but actually setting the header has been reported to cause
3833 * problems with some forwarding proxies that close the
3834 * connection prematurely.
3836 if (csp->http->ssl != 0)
3841 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3842 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3843 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3844 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3846 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3849 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3851 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3853 return enlist(csp->headers, connection_close);
3857 /*********************************************************************
3859 * Function : server_http
3861 * Description : - Save the HTTP Status into csp->http->status
3862 * - Set CT_TABOO to prevent filtering if the answer
3863 * is a partial range (HTTP status 206)
3864 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3866 * - Normalize the HTTP-version.
3869 * 1 : csp = Current client state (buffers, headers, etc...)
3870 * 2 : header = On input, pointer to header to modify.
3871 * On output, pointer to the modified header, or NULL
3872 * to remove the header. This function frees the
3873 * original string if necessary.
3875 * Returns : JB_ERR_OK on success, or
3876 * JB_ERR_PARSE on fatal parse errors.
3878 *********************************************************************/
3879 static jb_err server_http(struct client_state *csp, char **header)
3881 char *reason_phrase = NULL;
3882 char *new_response_line;
3885 unsigned int major_version;
3886 unsigned int minor_version;
3888 /* Get the reason phrase which start after the second whitespace */
3889 p = strchr(*header, ' ');
3893 reason_phrase = strchr(p, ' ');
3896 if (reason_phrase != NULL)
3902 log_error(LOG_LEVEL_ERROR,
3903 "Response line lacks reason phrase: %s", *header);
3907 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
3908 &minor_version, &(csp->http->status)))
3910 log_error(LOG_LEVEL_ERROR,
3911 "Failed to parse the response line: %s", *header);
3912 return JB_ERR_PARSE;
3915 if (csp->http->status == 206)
3917 csp->content_type = CT_TABOO;
3920 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
3923 * According to RFC 7230 2.6 intermediaries MUST send
3924 * their own HTTP-version in forwarded messages.
3926 log_error(LOG_LEVEL_ERROR,
3927 "Unsupported HTTP version. Downgrading to 1.1.");
3932 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
3934 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
3938 /* Rebuild response line. */
3939 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
3940 new_response_line = malloc_or_die(length);
3942 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
3943 major_version, minor_version, csp->http->status, reason_phrase);
3945 if (0 != strcmp(*header, new_response_line))
3947 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
3948 *header, new_response_line);
3952 *header = new_response_line;
3957 /*********************************************************************
3959 * Function : add_cooky_expiry_date
3961 * Description : Adds a cookie expiry date to a string.
3964 * 1 : cookie = On input, pointer to cookie to modify.
3965 * On output, pointer to the modified header.
3966 * The original string is freed.
3967 * 2 : lifetime = Seconds the cookie should be valid
3971 *********************************************************************/
3972 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
3975 struct tm *timeptr = NULL;
3976 time_t expiry_date = time(NULL) + lifetime;
3977 #ifdef HAVE_GMTIME_R
3980 timeptr = gmtime_r(&expiry_date, &gmt);
3981 #elif defined(MUTEX_LOCKS_AVAILABLE)
3982 privoxy_mutex_lock(&gmtime_mutex);
3983 timeptr = gmtime(&expiry_date);
3984 privoxy_mutex_unlock(&gmtime_mutex);
3986 timeptr = gmtime(&expiry_date);
3989 if (NULL == timeptr)
3991 log_error(LOG_LEVEL_FATAL,
3992 "Failed to get the time in add_cooky_expiry_date()");
3994 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
3995 if (JB_ERR_OK != string_append(cookie, tmp))
3997 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
4002 /*********************************************************************
4004 * Function : server_set_cookie
4006 * Description : Handle the server "cookie" header properly.
4007 * Crunch, accept or rewrite it to a session cookie.
4008 * Called from `sed'.
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_MEMORY on out-of-memory error.
4020 *********************************************************************/
4021 static jb_err server_set_cookie(struct client_state *csp, char **header)
4023 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4025 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4028 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4029 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4033 long cookie_lifetime = 0;
4036 NO_EXPIRY_DATE_SPECIFIED,
4037 EXPIRY_DATE_ACCEPTABLE,
4038 EXPIRY_DATE_UNACCEPTABLE
4039 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4041 /* A variable to store the tag we're working on */
4044 /* Skip "Set-Cookie:" (11 characters) in header */
4045 cur_tag = *header + 11;
4047 /* skip whitespace between "Set-Cookie:" and value */
4048 while (*cur_tag && privoxy_isspace(*cur_tag))
4055 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4057 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4059 cookie_lifetime = strtol(param, NULL, 0);
4060 if (cookie_lifetime < 0)
4062 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4064 cookie_lifetime *= 60;
4067 /* Loop through each tag in the cookie */
4071 char *next_tag = strchr(cur_tag, ';');
4072 if (next_tag != NULL)
4074 /* Skip the ';' character itself */
4077 /* skip whitespace ";" and start of tag */
4078 while (*next_tag && privoxy_isspace(*next_tag))
4085 /* "Next tag" is the end of the string */
4086 next_tag = cur_tag + strlen(cur_tag);
4090 * Check the expiration date to see
4091 * if the cookie is still valid, if yes,
4092 * rewrite it to a session cookie.
4094 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4096 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4098 if ((expiration_date[0] == '"')
4099 && (expiration_date[1] != '\0'))
4102 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4103 * that the expiration date isn't supposed to be quoted,
4104 * but some servers do it anyway.
4109 /* Did we detect the date properly? */
4110 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4113 * Nope, treat it as if it was still valid.
4115 * XXX: Should we remove the whole cookie instead?
4117 log_error(LOG_LEVEL_ERROR,
4118 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4119 string_move(cur_tag, next_tag);
4120 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4125 * Yes. Check if the cookie is still valid.
4127 * If the cookie is already expired it's probably
4128 * a delete cookie and even if it isn't, the browser
4129 * will discard it anyway.
4133 * XXX: timegm() isn't available on some AmigaOS
4134 * versions and our replacement doesn't work.
4136 * Our options are to either:
4138 * - disable session-cookies-only completely if timegm
4141 * - to simply remove all expired tags, like it has
4142 * been done until Privoxy 3.0.6 and to live with
4143 * the consequence that it can cause login/logout
4144 * problems on servers that don't validate their
4145 * input properly, or
4147 * - to replace it with mktime in which
4148 * case there is a slight chance of valid cookies
4149 * passing as already expired.
4151 * This is the way it's currently done and it's not
4152 * as bad as it sounds. If the missing GMT offset is
4153 * enough to change the result of the expiration check
4154 * the cookie will be only valid for a few hours
4155 * anyway, which in many cases will be shorter
4156 * than a browser session.
4158 if (cookie_time < now)
4160 log_error(LOG_LEVEL_HEADER,
4161 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4162 /* Just in case some clown sets more then one expiration date */
4164 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4166 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4168 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4169 "Its lifetime is below the limit.", *header);
4170 /* Just in case some clown sets more then one expiration date */
4172 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4177 * Still valid, delete expiration date by copying
4178 * the rest of the string over it.
4180 string_move(cur_tag, next_tag);
4182 /* That changed the header, need to issue a log message */
4183 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4186 * Note that the next tag has now been moved to *cur_tag,
4187 * so we do not need to update the cur_tag pointer.
4195 /* Move on to next cookie tag */
4200 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4202 assert(NULL != *header);
4203 if (cookie_lifetime != 0)
4205 add_cookie_expiry_date(header, cookie_lifetime);
4206 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4208 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4210 log_error(LOG_LEVEL_HEADER,
4211 "Cookie rewritten to a temporary one: %s", *header);
4220 #ifdef FEATURE_FORCE_LOAD
4221 /*********************************************************************
4223 * Function : strclean
4225 * Description : In-Situ-Eliminate all occurrences of substring in
4229 * 1 : string = string to clean
4230 * 2 : substring = substring to eliminate
4232 * Returns : Number of eliminations
4234 *********************************************************************/
4235 int strclean(char *string, const char *substring)
4241 len = strlen(substring);
4243 while((pos = strstr(string, substring)) != NULL)
4250 while (*p++ != '\0');
4257 #endif /* def FEATURE_FORCE_LOAD */
4260 /*********************************************************************
4262 * Function : parse_header_time
4264 * Description : Parses time formats used in HTTP header strings
4265 * to get the numerical respresentation.
4268 * 1 : header_time = HTTP header time as string.
4269 * 2 : result = storage for header_time in seconds
4271 * Returns : JB_ERR_OK if the time format was recognized, or
4272 * JB_ERR_PARSE otherwise.
4274 *********************************************************************/
4275 static jb_err parse_header_time(const char *header_time, time_t *result)
4279 * Checking for two-digit years first in an
4280 * attempt to work around GNU libc's strptime()
4281 * reporting negative year values when using %Y.
4283 static const char time_formats[][22] = {
4284 /* Tue, 02-Jun-37 20:00:00 */
4285 "%a, %d-%b-%y %H:%M:%S",
4286 /* Tue, 02 Jun 2037 20:00:00 */
4287 "%a, %d %b %Y %H:%M:%S",
4288 /* Tue, 02-Jun-2037 20:00:00 */
4289 "%a, %d-%b-%Y %H:%M:%S",
4290 /* Tuesday, 02-Jun-2037 20:00:00 */
4291 "%A, %d-%b-%Y %H:%M:%S",
4292 /* Tuesday Jun 02 20:00:00 2037 */
4293 "%A %b %d %H:%M:%S %Y"
4297 for (i = 0; i < SZ(time_formats); i++)
4300 * Zero out gmt to prevent time zone offsets.
4301 * Documented to be required for GNU libc.
4303 memset(&gmt, 0, sizeof(gmt));
4305 if (NULL != strptime(header_time, time_formats[i], &gmt))
4307 /* Sanity check for GNU libc. */
4308 if (gmt.tm_year < 0)
4310 log_error(LOG_LEVEL_HEADER,
4311 "Failed to parse '%s' using '%s'. Moving on.",
4312 header_time, time_formats[i]);
4315 *result = timegm(&gmt);
4317 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4319 * Verify that parsing the date recreated from the first
4320 * parse operation gets the previous result. If it doesn't,
4321 * either strptime() or strftime() are malfunctioning.
4323 * We could string-compare the recreated date with the original
4324 * header date, but this leads to false positives as strptime()
4325 * may let %a accept all day formats while strftime() will only
4329 char recreated_date[100];
4333 tm = gmtime(result);
4334 if (!strftime(recreated_date, sizeof(recreated_date),
4335 time_formats[i], tm))
4337 log_error(LOG_LEVEL_ERROR, "Failed to recreate date '%s' with '%s'.",
4338 header_time, time_formats[i]);
4341 memset(&gmt, 0, sizeof(gmt));
4342 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4344 log_error(LOG_LEVEL_ERROR,
4345 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4346 recreated_date, time_formats[i], header_time);
4349 result2 = timegm(&gmt);
4350 if (*result != result2)
4352 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4353 "Format: '%s'. In: '%s', out: '%s'. %d != %d. Rejecting.",
4354 time_formats[i], header_time, recreated_date, *result, result2);
4364 return JB_ERR_PARSE;
4368 /*********************************************************************
4370 * Function : parse_time_header
4372 * Description : Parses the time in an HTTP time header to get
4373 * the numerical respresentation.
4376 * 1 : header = HTTP header with a time value
4377 * 2 : result = storage for header_time in seconds
4379 * Returns : JB_ERR_OK if the time format was recognized, or
4380 * JB_ERR_PARSE otherwise.
4382 *********************************************************************/
4383 static jb_err parse_time_header(const char *header, time_t *result)
4385 const char *header_time;
4387 header_time = strchr(header, ':');
4390 * Currently this can't happen as all callers are called
4391 * through sed() which requires a header name followed by
4394 assert(header_time != NULL);
4397 if (*header_time == ' ')
4402 return parse_header_time(header_time, result);
4407 /*********************************************************************
4409 * Function : get_destination_from_headers
4411 * Description : Parse the "Host:" header to get the request's destination.
4412 * Only needed if the client's request was forcefully
4413 * redirected into Privoxy.
4415 * Code mainly copied from client_host() which is currently
4416 * run too late for this purpose.
4419 * 1 : headers = List of headers (one of them hopefully being
4420 * the "Host:" header)
4421 * 2 : http = storage for the result (host, port and hostport).
4423 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4424 * JB_ERR_PARSE if the host header couldn't be found,
4425 * JB_ERR_OK otherwise.
4427 *********************************************************************/
4428 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4436 host = get_header_value(headers, "Host:");
4440 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4441 return JB_ERR_PARSE;
4444 p = strdup_or_die(host);