1 const char parsers_rcs[] = "$Id: parsers.c,v 1.307 2016/01/17 14:31:47 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 */
424 assert(csp->iob->cur - csp->iob->buf > 0);
425 assert(csp->iob->eod - csp->iob->cur > 0);
427 bufsize = csp->iob->size;
428 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
429 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
433 if (bufsize < (size_t)10)
436 * This is to protect the parsing of gzipped data,
437 * but it should(?) be valid for deflated data also.
439 log_error(LOG_LEVEL_ERROR,
440 "Insufficient data to start decompression. Bytes in buffer: %d",
441 csp->iob->eod - csp->iob->cur);
442 return JB_ERR_COMPRESS;
445 if (csp->content_type & CT_GZIP)
448 * Our task is slightly complicated by the facts that data
449 * compressed by gzip does not include a zlib header, and
450 * that there is no easily accessible interface in zlib to
451 * handle a gzip header. We strip off the gzip header by
452 * hand, and later inform zlib not to expect a header.
456 * Strip off the gzip header. Please see RFC 1952 for more
457 * explanation of the appropriate fields.
459 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
460 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
461 || (*cur++ != Z_DEFLATED))
463 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
464 return JB_ERR_COMPRESS;
469 if (flags & GZIP_FLAG_RESERVED_BITS)
471 /* The gzip header has reserved bits set; bail out. */
472 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
473 return JB_ERR_COMPRESS;
477 * Skip mtime (4 bytes), extra flags (1 byte)
478 * and OS type (1 byte).
482 /* Skip extra fields if necessary. */
483 if (flags & GZIP_FLAG_EXTRA_FIELDS)
486 * Skip a given number of bytes, specified
487 * as a 16-bit little-endian value.
489 * XXX: this code is untested and should probably be removed.
493 skip_bytes += *cur++ << 8;
496 * The number of bytes to skip should be positive
497 * and we'd like to stay in the buffer.
499 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
501 log_error(LOG_LEVEL_ERROR,
502 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
504 return JB_ERR_COMPRESS;
506 log_error(LOG_LEVEL_INFO,
507 "Skipping %d bytes for gzip compression. Does this sound right?",
512 /* Skip the filename if necessary. */
513 if (flags & GZIP_FLAG_FILE_NAME)
515 /* A null-terminated string is supposed to follow. */
516 while (*cur++ && (cur < csp->iob->eod));
519 /* Skip the comment if necessary. */
520 if (flags & GZIP_FLAG_COMMENT)
522 /* A null-terminated string is supposed to follow. */
523 while (*cur++ && (cur < csp->iob->eod));
526 /* Skip the CRC if necessary. */
527 if (flags & GZIP_FLAG_CHECKSUM)
532 if (cur >= csp->iob->eod)
535 * If the current position pointer reached or passed
536 * the buffer end, we were obviously tricked to skip
539 log_error(LOG_LEVEL_ERROR,
540 "Malformed gzip header detected. Aborting decompression.");
541 return JB_ERR_COMPRESS;
545 else if (csp->content_type & CT_DEFLATE)
548 * In theory (that is, according to RFC 1950), deflate-compressed
549 * data should begin with a two-byte zlib header and have an
550 * adler32 checksum at the end. It seems that in practice only
551 * the raw compressed data is sent. Note that this means that
552 * we are not RFC 1950-compliant here, but the advantage is that
553 * this actually works. :)
555 * We add a dummy null byte to tell zlib where the data ends,
556 * and later inform it not to expect a header.
558 * Fortunately, add_to_iob() has thoughtfully null-terminated
559 * the buffer; we can just increment the end pointer to include
566 log_error(LOG_LEVEL_ERROR,
567 "Unable to determine compression format for decompression");
568 return JB_ERR_COMPRESS;
571 /* Set up the fields required by zlib. */
572 zstr.next_in = (Bytef *)cur;
573 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
574 zstr.zalloc = Z_NULL;
576 zstr.opaque = Z_NULL;
579 * Passing -MAX_WBITS to inflateInit2 tells the library
580 * that there is no zlib header.
582 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
584 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
585 return JB_ERR_COMPRESS;
589 * Next, we allocate new storage for the inflated data.
590 * We don't modify the existing iob yet, so in case there
591 * is error in decompression we can recover gracefully.
593 buf = zalloc(bufsize);
596 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
597 return JB_ERR_MEMORY;
600 assert(bufsize >= skip_size);
601 memcpy(buf, csp->iob->buf, skip_size);
602 zstr.avail_out = (uInt)(bufsize - skip_size);
603 zstr.next_out = (Bytef *)buf + skip_size;
605 /* Try to decompress the whole stream in one shot. */
606 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
608 /* We need to allocate more memory for the output buffer. */
610 char *tmpbuf; /* used for realloc'ing the buffer */
611 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
613 if (0 == zstr.avail_in)
616 * If zlib wants more data then there's a problem, because
617 * the complete compressed file should have been buffered.
619 log_error(LOG_LEVEL_ERROR,
620 "Unexpected end of compressed iob. Using what we got so far.");
625 * If we reached the buffer limit and still didn't have enough
626 * memory, just give up. Due to the ceiling enforced by the next
627 * if block we could actually check for equality here, but as it
628 * can be easily mistaken for a bug we don't.
630 if (bufsize >= csp->config->buffer_limit)
632 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
633 return JB_ERR_MEMORY;
636 /* Try doubling the buffer size each time. */
639 /* Don't exceed the buffer limit. */
640 if (bufsize > csp->config->buffer_limit)
642 bufsize = csp->config->buffer_limit;
645 /* Try to allocate the new buffer. */
646 tmpbuf = realloc(buf, bufsize);
649 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
651 return JB_ERR_MEMORY;
655 char *oldnext_out = (char *)zstr.next_out;
658 * Update the fields for inflate() to use the new
659 * buffer, which may be in a location different from
662 zstr.avail_out += (uInt)(bufsize - oldbufsize);
663 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
666 * Compare with an uglier method of calculating these values
667 * that doesn't require the extra oldbufsize variable.
669 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
670 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
676 if (Z_STREAM_ERROR == inflateEnd(&zstr))
678 log_error(LOG_LEVEL_ERROR,
679 "Inconsistent stream state after decompression: %s", zstr.msg);
681 * XXX: Intentionally no return.
683 * According to zlib.h, Z_STREAM_ERROR is returned
684 * "if the stream state was inconsistent".
686 * I assume in this case inflate()'s status
687 * would also be something different than Z_STREAM_END
688 * so this check should be redundant, but lets see.
692 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
695 * We failed to decompress the stream and it's
696 * not simply because of missing data.
698 log_error(LOG_LEVEL_ERROR,
699 "Unexpected error while decompressing to the buffer (iob): %s",
701 return JB_ERR_COMPRESS;
705 * Finally, we can actually update the iob, since the
706 * decompression was successful. First, free the old
709 freez(csp->iob->buf);
711 /* Now, update the iob to use the new buffer. */
713 csp->iob->cur = csp->iob->buf + skip_size;
714 csp->iob->eod = (char *)zstr.next_out;
715 csp->iob->size = bufsize;
718 * Make sure the new uncompressed iob obeys some minimal
719 * consistency conditions.
721 if ((csp->iob->buf < csp->iob->cur)
722 && (csp->iob->cur <= csp->iob->eod)
723 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
725 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
726 if (new_size > (size_t)0)
728 log_error(LOG_LEVEL_RE_FILTER,
729 "Decompression successful. Old size: %d, new size: %d.",
734 /* zlib thinks this is OK, so lets do the same. */
735 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
740 /* It seems that zlib did something weird. */
741 log_error(LOG_LEVEL_ERROR,
742 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
743 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
744 csp->iob->eod, csp->iob->buf + csp->iob->size);
745 return JB_ERR_COMPRESS;
751 #endif /* defined(FEATURE_ZLIB) */
754 /*********************************************************************
756 * Function : normalize_lws
758 * Description : Reduces unquoted linear whitespace in headers to
759 * a single space in accordance with RFC 7230 3.2.4.
760 * This simplifies parsing and filtering later on.
763 * 1 : header = A header with linear whitespace to reduce.
767 *********************************************************************/
768 static void normalize_lws(char *header)
774 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
778 while (privoxy_isspace(*q))
782 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
788 log_error(LOG_LEVEL_HEADER,
789 "Converting tab to space in '%s'", header);
794 char *end_of_token = strstr(p+1, "\"");
796 if (NULL != end_of_token)
798 /* Don't mess with quoted text. */
803 log_error(LOG_LEVEL_HEADER,
804 "Ignoring single quote in '%s'", header);
810 p = strchr(header, ':');
811 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
814 * There's still space before the colon.
822 /*********************************************************************
824 * Function : get_header
826 * Description : This (odd) routine will parse the csp->iob
827 * to get the next complete header.
830 * 1 : iob = The I/O buffer to parse, usually csp->iob.
832 * Returns : Any one of the following:
834 * 1) a pointer to a dynamically allocated string that contains a header line
835 * 2) NULL indicating that the end of the header was reached
836 * 3) "" indicating that the end of the iob was reached before finding
837 * a complete header line.
839 *********************************************************************/
840 char *get_header(struct iob *iob)
844 header = get_header_line(iob);
846 if ((header == NULL) || (*header == '\0'))
849 * No complete header read yet, tell the client.
854 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
857 * Header spans multiple lines, append the next one.
859 char *continued_header;
861 continued_header = get_header_line(iob);
862 if ((continued_header == NULL) || (*continued_header == '\0'))
865 * No complete header read yet, return what we got.
866 * XXX: Should "unread" header instead.
868 log_error(LOG_LEVEL_INFO,
869 "Failed to read a multi-line header properly: '%s'",
874 if (JB_ERR_OK != string_join(&header, continued_header))
876 log_error(LOG_LEVEL_FATAL,
877 "Out of memory while appending multiple headers.");
881 /* XXX: remove before next stable release. */
882 log_error(LOG_LEVEL_HEADER,
883 "Merged multiple header lines to: '%s'",
888 normalize_lws(header);
895 /*********************************************************************
897 * Function : get_header_line
899 * Description : This (odd) routine will parse the csp->iob
900 * to get the next header line.
903 * 1 : iob = The I/O buffer to parse, usually csp->iob.
905 * Returns : Any one of the following:
907 * 1) a pointer to a dynamically allocated string that contains a header line
908 * 2) NULL indicating that the end of the header was reached
909 * 3) "" indicating that the end of the iob was reached before finding
910 * a complete header line.
912 *********************************************************************/
913 static char *get_header_line(struct iob *iob)
917 if ((iob->cur == NULL)
918 || ((p = strchr(iob->cur, '\n')) == NULL))
920 return(""); /* couldn't find a complete header */
925 ret = strdup(iob->cur);
928 /* FIXME No way to handle error properly */
929 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
935 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
937 /* is this a blank line (i.e. the end of the header) ? */
949 /*********************************************************************
951 * Function : get_header_value
953 * Description : Get the value of a given header from a chained list
954 * of header lines or return NULL if no such header is
955 * present in the list.
958 * 1 : header_list = pointer to list
959 * 2 : header_name = string with name of header to look for.
960 * Trailing colon required, capitalization
963 * Returns : NULL if not found, else value of header
965 *********************************************************************/
966 char *get_header_value(const struct list *header_list, const char *header_name)
968 struct list_entry *cur_entry;
974 length = strlen(header_name);
976 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
980 if (!strncmpic(cur_entry->str, header_name, length))
983 * Found: return pointer to start of value
985 ret = cur_entry->str + length;
986 while (*ret && privoxy_isspace(*ret)) ret++;
1000 /*********************************************************************
1002 * Function : scan_headers
1004 * Description : Scans headers, applies tags and updates action bits.
1007 * 1 : csp = Current client state (buffers, headers, etc...)
1009 * Returns : JB_ERR_OK
1011 *********************************************************************/
1012 static jb_err scan_headers(struct client_state *csp)
1014 struct list_entry *h; /* Header */
1015 jb_err err = JB_ERR_OK;
1017 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1019 /* Header crunch()ed in previous run? -> ignore */
1020 if (h->str == NULL) continue;
1021 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1022 err = header_tagger(csp, h->str);
1029 /*********************************************************************
1031 * Function : enforce_header_order
1033 * Description : Enforces a given header order.
1036 * 1 : headers = List of headers to order.
1037 * 2 : ordered_headers = List of ordered header names.
1041 *********************************************************************/
1042 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1044 struct list_entry *sorted_header;
1045 struct list new_headers[1];
1046 struct list_entry *header;
1048 init_list(new_headers);
1050 /* The request line is always the first "header" */
1052 assert(NULL != headers->first->str);
1053 enlist(new_headers, headers->first->str);
1054 freez(headers->first->str)
1056 /* Enlist the specified headers in the given order */
1058 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1059 sorted_header = sorted_header->next)
1061 const size_t sorted_header_length = strlen(sorted_header->str);
1062 for (header = headers->first; header != NULL; header = header->next)
1064 /* Header enlisted in previous run? -> ignore */
1065 if (header->str == NULL) continue;
1067 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1068 && (header->str[sorted_header_length] == ':'))
1070 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1071 if (JB_ERR_OK != enlist(new_headers, header->str))
1073 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1080 /* Enlist the rest of the headers behind the ordered ones */
1081 for (header = headers->first; header != NULL; header = header->next)
1083 /* Header enlisted in previous run? -> ignore */
1084 if (header->str == NULL) continue;
1086 log_error(LOG_LEVEL_HEADER,
1087 "Enlisting left-over header %s", header->str);
1088 if (JB_ERR_OK != enlist(new_headers, header->str))
1090 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1095 list_remove_all(headers);
1096 list_duplicate(headers, new_headers);
1097 list_remove_all(new_headers);
1103 /*********************************************************************
1107 * Description : add, delete or modify lines in the HTTP header streams.
1108 * On entry, it receives a linked list of headers space
1109 * that was allocated dynamically (both the list nodes
1110 * and the header contents).
1112 * As a side effect it frees the space used by the original
1116 * 1 : csp = Current client state (buffers, headers, etc...)
1117 * 2 : filter_server_headers = Boolean to switch between
1118 * server and header filtering.
1120 * Returns : JB_ERR_OK in case off success, or
1121 * JB_ERR_MEMORY on some out-of-memory errors, or
1122 * JB_ERR_PARSE in case of fatal parse errors.
1124 *********************************************************************/
1125 jb_err sed(struct client_state *csp, int filter_server_headers)
1127 /* XXX: use more descriptive names. */
1128 struct list_entry *p;
1129 const struct parsers *v;
1130 const add_header_func_ptr *f;
1131 jb_err err = JB_ERR_OK;
1135 if (filter_server_headers)
1137 v = server_patterns;
1138 f = add_server_headers;
1139 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1143 v = client_patterns;
1144 f = add_client_headers;
1145 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1148 while (v->str != NULL)
1150 for (p = csp->headers->first; p != NULL; p = p->next)
1152 /* Header crunch()ed in previous run? -> ignore */
1153 if (p->str == NULL) continue;
1155 /* Does the current parser handle this header? */
1156 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1157 (v->len == CHECK_EVERY_HEADER_REMAINING))
1159 err = v->parser(csp, &(p->str));
1160 if (err != JB_ERR_OK)
1169 /* place additional headers on the csp->headers list */
1170 while ((err == JB_ERR_OK) && (*f))
1176 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1178 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1185 /*********************************************************************
1187 * Function : update_server_headers
1189 * Description : Updates server headers after the body has been modified.
1192 * 1 : csp = Current client state (buffers, headers, etc...)
1194 * Returns : JB_ERR_OK in case off success, or
1195 * JB_ERR_MEMORY on out-of-memory error.
1197 *********************************************************************/
1198 jb_err update_server_headers(struct client_state *csp)
1200 jb_err err = JB_ERR_OK;
1202 static const struct parsers server_patterns_light[] = {
1203 { "Content-Length:", 15, server_adjust_content_length },
1204 { "Transfer-Encoding:", 18, server_transfer_coding },
1206 { "Content-Encoding:", 17, server_adjust_content_encoding },
1207 #endif /* def FEATURE_ZLIB */
1211 if (strncmpic(csp->http->cmd, "HEAD", 4))
1213 const struct parsers *v;
1214 struct list_entry *p;
1216 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1218 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1220 /* Header crunch()ed in previous run? -> ignore */
1221 if (p->str == NULL) continue;
1223 /* Does the current parser handle this header? */
1224 if (strncmpic(p->str, v->str, v->len) == 0)
1226 err = v->parser(csp, (char **)&(p->str));
1232 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1233 if ((JB_ERR_OK == err)
1234 && (csp->flags & CSP_FLAG_MODIFIED)
1235 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1236 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1240 create_content_length_header(csp->content_length, header, sizeof(header));
1241 err = enlist(csp->headers, header);
1242 if (JB_ERR_OK == err)
1244 log_error(LOG_LEVEL_HEADER,
1245 "Content modified with no Content-Length header set. "
1246 "Created: %s.", header);
1247 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1250 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1252 #ifdef FEATURE_COMPRESSION
1253 if ((JB_ERR_OK == err)
1254 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1256 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1257 if (JB_ERR_OK == err)
1259 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1268 /*********************************************************************
1270 * Function : header_tagger
1272 * Description : Executes all text substitutions from applying
1273 * tag actions and saves the result as tag.
1275 * XXX: Shares enough code with filter_header() and
1276 * pcrs_filter_response() to warrant some helper functions.
1279 * 1 : csp = Current client state (buffers, headers, etc...)
1280 * 2 : header = Header that is used as tagger input
1282 * Returns : JB_ERR_OK on success and always succeeds
1284 *********************************************************************/
1285 static jb_err header_tagger(struct client_state *csp, char *header)
1287 enum filter_type wanted_filter_type;
1288 int multi_action_index;
1291 struct re_filterfile_spec *b;
1292 struct list_entry *tag_name;
1294 const size_t header_length = strlen(header);
1296 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1298 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1299 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1303 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1304 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1307 if (list_is_empty(csp->action->multi[multi_action_index])
1308 || filters_available(csp) == FALSE)
1310 /* Return early if no taggers apply or if none are available. */
1314 /* Execute all applying taggers */
1315 for (tag_name = csp->action->multi[multi_action_index]->first;
1316 NULL != tag_name; tag_name = tag_name->next)
1318 char *modified_tag = NULL;
1320 size_t size = header_length;
1323 b = get_filter(csp, tag_name->str, wanted_filter_type);
1329 joblist = b->joblist;
1331 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1333 if (NULL == joblist)
1335 log_error(LOG_LEVEL_RE_FILTER,
1336 "Tagger %s has empty joblist. Nothing to do.", b->name);
1340 /* execute their pcrs_joblist on the header. */
1341 for (job = joblist; NULL != job; job = job->next)
1343 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1347 /* Success, continue with the modified version. */
1356 /* Tagger doesn't match */
1359 /* Regex failure, log it but continue anyway. */
1360 assert(NULL != header);
1361 log_error(LOG_LEVEL_ERROR,
1362 "Problems with tagger \'%s\' and header \'%s\': %s",
1363 b->name, *header, pcrs_strerror(hits));
1365 freez(modified_tag);
1369 if (b->dynamic) pcrs_free_joblist(joblist);
1371 /* If this tagger matched */
1377 * There is no technical limitation which makes
1378 * it impossible to use empty tags, but I assume
1379 * no one would do it intentionally.
1382 log_error(LOG_LEVEL_INFO,
1383 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1387 if (!list_contains_item(csp->tags, tag))
1389 if (JB_ERR_OK != enlist(csp->tags, tag))
1391 log_error(LOG_LEVEL_ERROR,
1392 "Insufficient memory to add tag \'%s\', "
1393 "based on tagger \'%s\' and header \'%s\'",
1394 tag, b->name, *header);
1398 char *action_message;
1400 * update the action bits right away, to make
1401 * tagging based on tags set by earlier taggers
1402 * of the same kind possible.
1404 if (update_action_bits_for_tag(csp, tag))
1406 action_message = "Action bits updated accordingly.";
1410 action_message = "No action bits update necessary.";
1413 log_error(LOG_LEVEL_HEADER,
1414 "Tagger \'%s\' added tag \'%s\'. %s",
1415 b->name, tag, action_message);
1420 /* XXX: Is this log-worthy? */
1421 log_error(LOG_LEVEL_HEADER,
1422 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1432 /* here begins the family of parser functions that reformat header lines */
1434 /*********************************************************************
1436 * Function : filter_header
1438 * Description : Executes all text substitutions from all applying
1439 * +(server|client)-header-filter actions on the header.
1440 * Most of the code was copied from pcrs_filter_response,
1441 * including the rather short variable names
1444 * 1 : csp = Current client state (buffers, headers, etc...)
1445 * 2 : header = On input, pointer to header to modify.
1446 * On output, pointer to the modified header, or NULL
1447 * to remove the header. This function frees the
1448 * original string if necessary.
1450 * Returns : JB_ERR_OK on success and always succeeds
1452 *********************************************************************/
1453 static jb_err filter_header(struct client_state *csp, char **header)
1457 size_t size = strlen(*header);
1459 char *newheader = NULL;
1462 struct re_filterfile_spec *b;
1463 struct list_entry *filtername;
1465 enum filter_type wanted_filter_type;
1466 int multi_action_index;
1468 if (csp->flags & CSP_FLAG_NO_FILTERING)
1473 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1475 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1476 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1480 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1481 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1484 if (list_is_empty(csp->action->multi[multi_action_index])
1485 || filters_available(csp) == FALSE)
1487 /* Return early if no filters apply or if none are available. */
1491 /* Execute all applying header filters */
1492 for (filtername = csp->action->multi[multi_action_index]->first;
1493 filtername != NULL; filtername = filtername->next)
1495 int current_hits = 0;
1498 b = get_filter(csp, filtername->str, wanted_filter_type);
1504 joblist = b->joblist;
1506 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1508 if (NULL == joblist)
1510 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1514 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1515 *header, size, b->name);
1517 /* Apply all jobs from the joblist */
1518 for (job = joblist; NULL != job; job = job->next)
1520 matches = pcrs_execute(job, *header, size, &newheader, &size);
1523 current_hits += matches;
1524 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1526 *header = newheader;
1528 else if (0 == matches)
1530 /* Filter doesn't change header */
1536 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1537 *header, b->name, pcrs_strerror(matches));
1538 if (newheader != NULL)
1540 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1546 if (b->dynamic) pcrs_free_joblist(joblist);
1548 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1549 hits += current_hits;
1553 * Additionally checking for hits is important because if
1554 * the continue hack is triggered, server headers can
1555 * arrive empty to separate multiple heads from each other.
1557 if ((0 == size) && hits)
1559 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1567 /*********************************************************************
1569 * Function : server_connection
1571 * Description : Makes sure a proper "Connection:" header is
1572 * set and signals connection_header_adder to
1576 * 1 : csp = Current client state (buffers, headers, etc...)
1577 * 2 : header = On input, pointer to header to modify.
1578 * On output, pointer to the modified header, or NULL
1579 * to remove the header. This function frees the
1580 * original string if necessary.
1582 * Returns : JB_ERR_OK on success.
1584 *********************************************************************/
1585 static jb_err server_connection(struct client_state *csp, char **header)
1587 if (!strcmpic(*header, "Connection: keep-alive")
1588 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1589 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1593 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1594 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1596 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1599 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1601 log_error(LOG_LEVEL_HEADER,
1602 "Keeping the server header '%s' around.", *header);
1605 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1607 char *old_header = *header;
1609 *header = strdup_or_die("Connection: close");
1610 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1615 /* Signal server_connection_adder() to return early. */
1616 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1622 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1623 /*********************************************************************
1625 * Function : server_keep_alive
1627 * Description : Stores the server's keep alive timeout.
1630 * 1 : csp = Current client state (buffers, headers, etc...)
1631 * 2 : header = On input, pointer to header to modify.
1632 * On output, pointer to the modified header, or NULL
1633 * to remove the header. This function frees the
1634 * original string if necessary.
1636 * Returns : JB_ERR_OK.
1638 *********************************************************************/
1639 static jb_err server_keep_alive(struct client_state *csp, char **header)
1641 unsigned int keep_alive_timeout;
1642 const char *timeout_position = strstr(*header, "timeout=");
1644 if ((NULL == timeout_position)
1645 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1647 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1651 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1653 log_error(LOG_LEVEL_HEADER,
1654 "Reducing keep-alive timeout from %u to %u.",
1655 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1656 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1660 /* XXX: Is this log worthy? */
1661 log_error(LOG_LEVEL_HEADER,
1662 "Server keep-alive timeout is %u. Sticking with %u.",
1663 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1665 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1674 /*********************************************************************
1676 * Function : server_proxy_connection
1678 * Description : Figures out whether or not we should add a
1679 * Proxy-Connection header.
1682 * 1 : csp = Current client state (buffers, headers, etc...)
1683 * 2 : header = On input, pointer to header to modify.
1684 * On output, pointer to the modified header, or NULL
1685 * to remove the header. This function frees the
1686 * original string if necessary.
1688 * Returns : JB_ERR_OK.
1690 *********************************************************************/
1691 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1693 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1698 /*********************************************************************
1700 * Function : proxy_authentication
1702 * Description : Removes headers that are relevant for proxy
1703 * authentication unless forwarding them has
1704 * been explicitly requested.
1707 * 1 : csp = Current client state (buffers, headers, etc...)
1708 * 2 : header = On input, pointer to header to modify.
1709 * On output, pointer to the modified header, or NULL
1710 * to remove the header. This function frees the
1711 * original string if necessary.
1713 * Returns : JB_ERR_OK.
1715 *********************************************************************/
1716 static jb_err proxy_authentication(struct client_state *csp, char **header)
1718 if ((csp->config->feature_flags &
1719 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1720 log_error(LOG_LEVEL_HEADER,
1721 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1728 /*********************************************************************
1730 * Function : client_keep_alive
1732 * Description : Stores the client's keep alive timeout.
1735 * 1 : csp = Current client state (buffers, headers, etc...)
1736 * 2 : header = On input, pointer to header to modify.
1737 * On output, pointer to the modified header, or NULL
1738 * to remove the header. This function frees the
1739 * original string if necessary.
1741 * Returns : JB_ERR_OK.
1743 *********************************************************************/
1744 static jb_err client_keep_alive(struct client_state *csp, char **header)
1746 unsigned int keep_alive_timeout;
1747 char *timeout_position;
1749 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1751 log_error(LOG_LEVEL_HEADER,
1752 "keep-alive support is disabled. Crunching: %s.", *header);
1757 /* Check for parameter-less format "Keep-Alive: 100" */
1758 timeout_position = strstr(*header, ": ");
1759 if ((NULL == timeout_position)
1760 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1762 /* Assume parameter format "Keep-Alive: timeout=100" */
1763 timeout_position = strstr(*header, "timeout=");
1764 if ((NULL == timeout_position)
1765 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1767 log_error(LOG_LEVEL_HEADER,
1768 "Couldn't parse: '%s'. Using default timeout %u",
1769 *header, csp->config->keep_alive_timeout);
1776 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1778 log_error(LOG_LEVEL_HEADER,
1779 "Reducing keep-alive timeout from %u to %u.",
1780 csp->config->keep_alive_timeout, keep_alive_timeout);
1781 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1785 /* XXX: Is this log worthy? */
1786 log_error(LOG_LEVEL_HEADER,
1787 "Client keep-alive timeout is %u. Sticking with %u.",
1788 keep_alive_timeout, csp->config->keep_alive_timeout);
1796 /*********************************************************************
1798 * Function : get_content_length
1800 * Description : Gets the content length specified in a
1801 * Content-Length header.
1804 * 1 : header_value = The Content-Length header value.
1805 * 2 : length = Storage to return the value.
1807 * Returns : JB_ERR_OK on success, or
1808 * JB_ERR_PARSE if no value is recognized.
1810 *********************************************************************/
1811 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1814 assert(sizeof(unsigned long long) > 4);
1815 if (1 != sscanf(header_value, "%I64u", length))
1817 if (1 != sscanf(header_value, "%llu", length))
1820 return JB_ERR_PARSE;
1827 /*********************************************************************
1829 * Function : client_save_content_length
1831 * Description : Save the Content-Length sent by the client.
1834 * 1 : csp = Current client state (buffers, headers, etc...)
1835 * 2 : header = On input, pointer to header to modify.
1836 * On output, pointer to the modified header, or NULL
1837 * to remove the header. This function frees the
1838 * original string if necessary.
1840 * Returns : JB_ERR_OK on success, or
1841 * JB_ERR_MEMORY on out-of-memory error.
1843 *********************************************************************/
1844 static jb_err client_save_content_length(struct client_state *csp, char **header)
1846 unsigned long long content_length = 0;
1847 const char *header_value;
1849 assert(*(*header+14) == ':');
1851 header_value = *header + 15;
1852 if (JB_ERR_OK != get_content_length(header_value, &content_length))
1854 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1859 csp->expected_client_content_length = content_length;
1864 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1868 /*********************************************************************
1870 * Function : client_connection
1872 * Description : Makes sure a proper "Connection:" header is
1873 * set and signals connection_header_adder
1877 * 1 : csp = Current client state (buffers, headers, etc...)
1878 * 2 : header = On input, pointer to header to modify.
1879 * On output, pointer to the modified header, or NULL
1880 * to remove the header. This function frees the
1881 * original string if necessary.
1883 * Returns : JB_ERR_OK on success.
1885 *********************************************************************/
1886 static jb_err client_connection(struct client_state *csp, char **header)
1888 static const char connection_close[] = "Connection: close";
1890 if (!strcmpic(*header, connection_close))
1892 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1893 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1894 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1896 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1898 log_error(LOG_LEVEL_HEADER,
1899 "Removing \'%s\' to imply keep-alive.", *header);
1902 * While we imply keep-alive to the server,
1903 * we have to remember that the client didn't.
1905 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1909 char *old_header = *header;
1911 *header = strdup_or_die("Connection: keep-alive");
1912 log_error(LOG_LEVEL_HEADER,
1913 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1919 log_error(LOG_LEVEL_HEADER,
1920 "Keeping the client header '%s' around. "
1921 "The connection will not be kept alive.",
1923 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1926 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1927 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1929 log_error(LOG_LEVEL_HEADER,
1930 "Keeping the client header '%s' around. "
1931 "The server connection will be kept alive if possible.",
1933 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1934 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1938 char *old_header = *header;
1940 *header = strdup_or_die(connection_close);
1941 log_error(LOG_LEVEL_HEADER,
1942 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1946 /* Signal client_connection_header_adder() to return early. */
1947 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1953 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1954 /*********************************************************************
1956 * Function : client_proxy_connection
1958 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
1959 * appropriate and removes the Proxy-Connection
1963 * 1 : csp = Current client state (buffers, headers, etc...)
1964 * 2 : header = On input, pointer to header to modify.
1965 * On output, pointer to the modified header, or NULL
1966 * to remove the header. This function frees the
1967 * original string if necessary.
1969 * Returns : JB_ERR_OK
1971 *********************************************************************/
1972 static jb_err client_proxy_connection(struct client_state *csp, char **header)
1974 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1975 && (csp->http->ssl == 0)
1976 && (NULL == strstr(*header, "close")))
1978 log_error(LOG_LEVEL_HEADER,
1979 "The client connection can be kept alive due to: %s", *header);
1980 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1982 crumble(csp, header);
1986 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1989 /*********************************************************************
1991 * Function : client_transfer_encoding
1993 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
1994 * the request body is "chunked"
1996 * XXX: Currently not called through sed() as we
1997 * need the flag earlier on. Should be fixed.
2000 * 1 : csp = Current client state (buffers, headers, etc...)
2001 * 2 : header = On input, pointer to header to modify.
2002 * On output, pointer to the modified header, or NULL
2003 * to remove the header. This function frees the
2004 * original string if necessary.
2006 * Returns : JB_ERR_OK on success, or
2008 *********************************************************************/
2009 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2011 if (strstr(*header, "chunked"))
2013 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2014 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2021 /*********************************************************************
2023 * Function : client_expect
2025 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2026 * if the Expect header value is unsupported.
2028 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2029 * MAY and a RFC 2616 (obsolete) MUST.
2032 * 1 : csp = Current client state (buffers, headers, etc...)
2033 * 2 : header = On input, pointer to header to modify.
2034 * On output, pointer to the modified header, or NULL
2035 * to remove the header. This function frees the
2036 * original string if necessary.
2038 * Returns : JB_ERR_OK on success, or
2040 *********************************************************************/
2041 jb_err client_expect(struct client_state *csp, char **header)
2043 if (0 != strcmpic(*header, "Expect: 100-continue"))
2045 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2046 log_error(LOG_LEVEL_HEADER,
2047 "Unsupported client expectaction: %s", *header);
2055 /*********************************************************************
2057 * Function : crumble
2059 * Description : This is called if a header matches a pattern to "crunch"
2062 * 1 : csp = Current client state (buffers, headers, etc...)
2063 * 2 : header = On input, pointer to header to modify.
2064 * On output, pointer to the modified header, or NULL
2065 * to remove the header. This function frees the
2066 * original string if necessary.
2068 * Returns : JB_ERR_OK on success, or
2069 * JB_ERR_MEMORY on out-of-memory error.
2071 *********************************************************************/
2072 static jb_err crumble(struct client_state *csp, char **header)
2075 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2081 /*********************************************************************
2083 * Function : crunch_server_header
2085 * Description : Crunch server header if it matches a string supplied by the
2086 * user. Called from `sed'.
2089 * 1 : csp = Current client state (buffers, headers, etc...)
2090 * 2 : header = On input, pointer to header to modify.
2091 * On output, pointer to the modified header, or NULL
2092 * to remove the header. This function frees the
2093 * original string if necessary.
2095 * Returns : JB_ERR_OK on success and always succeeds
2097 *********************************************************************/
2098 static jb_err crunch_server_header(struct client_state *csp, char **header)
2100 const char *crunch_pattern;
2102 /* Do we feel like crunching? */
2103 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2105 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2107 /* Is the current header the lucky one? */
2108 if (strstr(*header, crunch_pattern))
2110 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2119 /*********************************************************************
2121 * Function : server_content_type
2123 * Description : Set the content-type for filterable types (text/.*,
2124 * .*xml.*, .*script.* and image/gif) unless filtering has been
2125 * forbidden (CT_TABOO) while parsing earlier headers.
2126 * NOTE: Since text/plain is commonly used by web servers
2127 * for files whose correct type is unknown, we don't
2128 * set CT_TEXT for it.
2131 * 1 : csp = Current client state (buffers, headers, etc...)
2132 * 2 : header = On input, pointer to header to modify.
2133 * On output, pointer to the modified header, or NULL
2134 * to remove the header. This function frees the
2135 * original string if necessary.
2137 * Returns : JB_ERR_OK on success, or
2138 * JB_ERR_MEMORY on out-of-memory error.
2140 *********************************************************************/
2141 static jb_err server_content_type(struct client_state *csp, char **header)
2143 /* Remove header if it isn't the first Content-Type header */
2144 if ((csp->content_type & CT_DECLARED))
2146 if (content_filters_enabled(csp->action))
2149 * Making sure the client interprets the content the same way
2150 * Privoxy did is only relevant if Privoxy modified it.
2152 * Checking for this is "hard" as it's not yet known when
2153 * this function is called, thus go shopping and and just
2154 * check if Privoxy could filter it.
2156 * The main thing is that we don't mess with the headers
2157 * unless the user signalled that it's acceptable.
2159 log_error(LOG_LEVEL_HEADER,
2160 "Multiple Content-Type headers detected. "
2161 "Removing and ignoring: %s",
2169 * Signal that the Content-Type has been set.
2171 csp->content_type |= CT_DECLARED;
2173 if (!(csp->content_type & CT_TABOO))
2176 * XXX: The assumption that text/plain is a sign of
2177 * binary data seems to be somewhat unreasonable nowadays
2178 * and should be dropped after 3.0.8 is out.
2180 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2181 || strstr(*header, "xml")
2182 || strstr(*header, "script"))
2184 csp->content_type |= CT_TEXT;
2186 else if (strstr(*header, "image/gif"))
2188 csp->content_type |= CT_GIF;
2193 * Are we messing with the content type?
2195 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2198 * Make sure the user doesn't accidentally
2199 * change the content type of binary documents.
2201 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2205 *header = strdup_or_die("Content-Type: ");
2207 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2208 if (JB_ERR_OK != err)
2210 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2211 return JB_ERR_MEMORY;
2213 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2217 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2218 "It doesn't look like a content type that should be filtered. "
2219 "Enable force-text-mode if you know what you're doing.", *header);
2227 /*********************************************************************
2229 * Function : server_transfer_coding
2231 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2232 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2233 * - Remove header if body was chunked but has been
2234 * de-chunked for filtering.
2237 * 1 : csp = Current client state (buffers, headers, etc...)
2238 * 2 : header = On input, pointer to header to modify.
2239 * On output, pointer to the modified header, or NULL
2240 * to remove the header. This function frees the
2241 * original string if necessary.
2243 * Returns : JB_ERR_OK on success, or
2244 * JB_ERR_MEMORY on out-of-memory error.
2246 *********************************************************************/
2247 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2250 * Turn off pcrs and gif filtering if body compressed
2252 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2256 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2258 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2259 csp->http->cmd, *header);
2260 #endif /* def FEATURE_ZLIB */
2261 csp->content_type = CT_TABOO;
2265 * Raise flag if body chunked
2267 if (strstr(*header, "chunked"))
2269 csp->flags |= CSP_FLAG_CHUNKED;
2272 * If the body was modified, it has been de-chunked first
2273 * and the header must be removed.
2275 * FIXME: If there is more than one transfer encoding,
2276 * only the "chunked" part should be removed here.
2278 if (csp->flags & CSP_FLAG_MODIFIED)
2280 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2289 /*********************************************************************
2291 * Function : server_content_encoding
2293 * Description : Used to check if the content is compressed, and if
2294 * FEATURE_ZLIB is disabled, filtering is disabled as
2297 * If FEATURE_ZLIB is enabled and the compression type
2298 * supported, the content is marked for decompression.
2300 * XXX: Doesn't properly deal with multiple or with
2301 * unsupported but unknown encodings.
2302 * Is case-sensitive but shouldn't be.
2305 * 1 : csp = Current client state (buffers, headers, etc...)
2306 * 2 : header = On input, pointer to header to modify.
2307 * On output, pointer to the modified header, or NULL
2308 * to remove the header. This function frees the
2309 * original string if necessary.
2311 * Returns : JB_ERR_OK on success, or
2312 * JB_ERR_MEMORY on out-of-memory error.
2314 *********************************************************************/
2315 static jb_err server_content_encoding(struct client_state *csp, char **header)
2318 if (strstr(*header, "sdch"))
2321 * Shared Dictionary Compression over HTTP isn't supported,
2322 * filtering it anyway is pretty much guaranteed to mess up
2325 csp->content_type |= CT_TABOO;
2328 * Log a warning if the user expects the content to be filtered.
2330 if (content_filters_enabled(csp->action))
2332 log_error(LOG_LEVEL_INFO,
2333 "SDCH-compressed content detected, content filtering disabled. "
2334 "Consider suppressing SDCH offers made by the client.");
2337 else if (strstr(*header, "gzip"))
2339 /* Mark for gzip decompression */
2340 csp->content_type |= CT_GZIP;
2342 else if (strstr(*header, "deflate"))
2344 /* Mark for zlib decompression */
2345 csp->content_type |= CT_DEFLATE;
2347 else if (strstr(*header, "compress"))
2350 * We can't decompress this; therefore we can't filter
2353 csp->content_type |= CT_TABOO;
2355 #else /* !defined(FEATURE_ZLIB) */
2357 * XXX: Using a black list here isn't the right approach.
2359 * In case of SDCH, building with zlib support isn't
2362 if (strstr(*header, "gzip") ||
2363 strstr(*header, "compress") ||
2364 strstr(*header, "deflate") ||
2365 strstr(*header, "sdch"))
2368 * Body is compressed, turn off pcrs and gif filtering.
2370 csp->content_type |= CT_TABOO;
2373 * Log a warning if the user expects the content to be filtered.
2375 if (content_filters_enabled(csp->action))
2377 log_error(LOG_LEVEL_INFO,
2378 "Compressed content detected, content filtering disabled. "
2379 "Consider recompiling Privoxy with zlib support or "
2380 "enable the prevent-compression action.");
2383 #endif /* defined(FEATURE_ZLIB) */
2391 /*********************************************************************
2393 * Function : server_adjust_content_encoding
2395 * Description : Remove the Content-Encoding header if the
2396 * decompression was successful and the content
2400 * 1 : csp = Current client state (buffers, headers, etc...)
2401 * 2 : header = On input, pointer to header to modify.
2402 * On output, pointer to the modified header, or NULL
2403 * to remove the header. This function frees the
2404 * original string if necessary.
2406 * Returns : JB_ERR_OK on success, or
2407 * JB_ERR_MEMORY on out-of-memory error.
2409 *********************************************************************/
2410 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2412 if ((csp->flags & CSP_FLAG_MODIFIED)
2413 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2416 * We successfully decompressed the content,
2417 * and have to clean the header now, so the
2418 * client no longer expects compressed data.
2420 * XXX: There is a difference between cleaning
2421 * and removing it completely.
2423 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2430 #endif /* defined(FEATURE_ZLIB) */
2433 /*********************************************************************
2435 * Function : server_adjust_content_length
2437 * Description : Adjust Content-Length header if we modified
2441 * 1 : csp = Current client state (buffers, headers, etc...)
2442 * 2 : header = On input, pointer to header to modify.
2443 * On output, pointer to the modified header, or NULL
2444 * to remove the header. This function frees the
2445 * original string if necessary.
2447 * Returns : JB_ERR_OK on success, or
2448 * JB_ERR_MEMORY on out-of-memory error.
2450 *********************************************************************/
2451 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2453 /* Regenerate header if the content was modified. */
2454 if (csp->flags & CSP_FLAG_MODIFIED)
2456 const size_t header_length = 50;
2458 *header = malloc(header_length);
2459 if (*header == NULL)
2461 return JB_ERR_MEMORY;
2463 create_content_length_header(csp->content_length, *header, header_length);
2464 log_error(LOG_LEVEL_HEADER,
2465 "Adjusted Content-Length to %llu", csp->content_length);
2472 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2473 /*********************************************************************
2475 * Function : server_save_content_length
2477 * Description : Save the Content-Length sent by the server.
2480 * 1 : csp = Current client state (buffers, headers, etc...)
2481 * 2 : header = On input, pointer to header to modify.
2482 * On output, pointer to the modified header, or NULL
2483 * to remove the header. This function frees the
2484 * original string if necessary.
2486 * Returns : JB_ERR_OK on success, or
2487 * JB_ERR_MEMORY on out-of-memory error.
2489 *********************************************************************/
2490 static jb_err server_save_content_length(struct client_state *csp, char **header)
2492 unsigned long long content_length = 0;
2493 const char *header_value;
2495 assert(*(*header+14) == ':');
2497 header_value = *header + 15;
2498 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2500 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2505 csp->expected_content_length = content_length;
2506 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2507 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2512 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2515 /*********************************************************************
2517 * Function : server_content_md5
2519 * Description : Crumble any Content-MD5 headers if the document was
2520 * modified. FIXME: Should we re-compute instead?
2523 * 1 : csp = Current client state (buffers, headers, etc...)
2524 * 2 : header = On input, pointer to header to modify.
2525 * On output, pointer to the modified header, or NULL
2526 * to remove the header. This function frees the
2527 * original string if necessary.
2529 * Returns : JB_ERR_OK on success, or
2530 * JB_ERR_MEMORY on out-of-memory error.
2532 *********************************************************************/
2533 static jb_err server_content_md5(struct client_state *csp, char **header)
2535 if (csp->flags & CSP_FLAG_MODIFIED)
2537 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2545 /*********************************************************************
2547 * Function : server_content_disposition
2549 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2550 * Called from `sed'.
2553 * 1 : csp = Current client state (buffers, headers, etc...)
2554 * 2 : header = On input, pointer to header to modify.
2555 * On output, pointer to the modified header, or NULL
2556 * to remove the header. This function frees the
2557 * original string if necessary.
2559 * Returns : JB_ERR_OK on success, or
2560 * JB_ERR_MEMORY on out-of-memory error.
2562 *********************************************************************/
2563 static jb_err server_content_disposition(struct client_state *csp, char **header)
2568 * Are we messing with the Content-Disposition header?
2570 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2576 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2578 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2581 * Blocking content-disposition header
2583 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2590 * Replacing Content-Disposition header
2593 *header = strdup("Content-Disposition: ");
2594 string_append(header, newval);
2596 if (*header != NULL)
2598 log_error(LOG_LEVEL_HEADER,
2599 "Content-Disposition header crunched and replaced with: %s", *header);
2602 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2606 /*********************************************************************
2608 * Function : server_last_modified
2610 * Description : Changes Last-Modified header to the actual date
2611 * to help hide-if-modified-since.
2612 * Called from `sed'.
2615 * 1 : csp = Current client state (buffers, headers, etc...)
2616 * 2 : header = On input, pointer to header to modify.
2617 * On output, pointer to the modified header, or NULL
2618 * to remove the header. This function frees the
2619 * original string if necessary.
2621 * Returns : JB_ERR_OK on success, or
2622 * JB_ERR_MEMORY on out-of-memory error.
2624 *********************************************************************/
2625 static jb_err server_last_modified(struct client_state *csp, char **header)
2628 time_t last_modified;
2632 * Are we messing with the Last-Modified header?
2634 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2640 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2642 if (0 == strcmpic(newval, "block"))
2645 * Blocking Last-Modified header. Useless but why not.
2647 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2651 else if (0 == strcmpic(newval, "reset-to-request-time"))
2654 * Setting Last-Modified Header to now.
2657 get_http_time(0, buf, sizeof(buf));
2659 *header = strdup("Last-Modified: ");
2660 string_append(header, buf);
2662 if (*header == NULL)
2664 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2668 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2671 else if (0 == strcmpic(newval, "randomize"))
2673 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2675 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2677 log_error(LOG_LEVEL_HEADER,
2678 "Couldn't parse time in %s (crunching!)", *header);
2684 struct tm *timeptr = NULL;
2686 #ifdef HAVE_GMTIME_R
2690 rtime = (long int)difftime(now, last_modified);
2693 long int days, hours, minutes, seconds;
2694 const int negative_delta = (rtime < 0);
2699 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2701 rtime = pick_from_range(rtime);
2706 last_modified += rtime;
2707 #ifdef HAVE_GMTIME_R
2708 timeptr = gmtime_r(&last_modified, &gmt);
2709 #elif defined(MUTEX_LOCKS_AVAILABLE)
2710 privoxy_mutex_lock(&gmtime_mutex);
2711 timeptr = gmtime(&last_modified);
2712 privoxy_mutex_unlock(&gmtime_mutex);
2714 timeptr = gmtime(&last_modified);
2716 if ((NULL == timeptr) || !strftime(newheader,
2717 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2719 log_error(LOG_LEVEL_ERROR,
2720 "Randomizing '%s' failed. Crunching the header without replacement.",
2727 *header = strdup("Last-Modified: ");
2728 string_append(header, newheader);
2730 if (*header == NULL)
2732 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2733 return JB_ERR_MEMORY;
2736 days = rtime / (3600 * 24);
2737 hours = rtime / 3600 % 24;
2738 minutes = rtime / 60 % 60;
2739 seconds = rtime % 60;
2741 log_error(LOG_LEVEL_HEADER,
2742 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2743 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2744 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2748 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2757 /*********************************************************************
2759 * Function : client_accept_encoding
2761 * Description : Rewrite the client's Accept-Encoding header so that
2762 * if doesn't allow compression, if the action applies.
2763 * Note: For HTTP/1.0 the absence of the header is enough.
2766 * 1 : csp = Current client state (buffers, headers, etc...)
2767 * 2 : header = On input, pointer to header to modify.
2768 * On output, pointer to the modified header, or NULL
2769 * to remove the header. This function frees the
2770 * original string if necessary.
2772 * Returns : JB_ERR_OK on success, or
2773 * JB_ERR_MEMORY on out-of-memory error.
2775 *********************************************************************/
2776 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2778 #ifdef FEATURE_COMPRESSION
2779 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2780 && strstr(*header, "deflate"))
2782 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2785 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2787 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2795 /*********************************************************************
2797 * Function : client_te
2799 * Description : Rewrite the client's TE header so that
2800 * if doesn't allow compression, if the action applies.
2803 * 1 : csp = Current client state (buffers, headers, etc...)
2804 * 2 : header = On input, pointer to header to modify.
2805 * On output, pointer to the modified header, or NULL
2806 * to remove the header. This function frees the
2807 * original string if necessary.
2809 * Returns : JB_ERR_OK on success, or
2810 * JB_ERR_MEMORY on out-of-memory error.
2812 *********************************************************************/
2813 static jb_err client_te(struct client_state *csp, char **header)
2815 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2818 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2825 /*********************************************************************
2827 * Function : client_referrer
2829 * Description : Handle the "referer" config setting properly.
2830 * Called from `sed'.
2833 * 1 : csp = Current client state (buffers, headers, etc...)
2834 * 2 : header = On input, pointer to header to modify.
2835 * On output, pointer to the modified header, or NULL
2836 * to remove the header. This function frees the
2837 * original string if necessary.
2839 * Returns : JB_ERR_OK on success, or
2840 * JB_ERR_MEMORY on out-of-memory error.
2842 *********************************************************************/
2843 static jb_err client_referrer(struct client_state *csp, char **header)
2845 const char *parameter;
2846 /* booleans for parameters we have to check multiple times */
2847 int parameter_conditional_block;
2848 int parameter_conditional_forge;
2850 #ifdef FEATURE_FORCE_LOAD
2852 * Since the referrer can include the prefix even
2853 * if the request itself is non-forced, we must
2854 * clean it unconditionally.
2856 * XXX: strclean is too broad
2858 strclean(*header, FORCE_PREFIX);
2859 #endif /* def FEATURE_FORCE_LOAD */
2861 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2863 /* Nothing left to do */
2867 parameter = csp->action->string[ACTION_STRING_REFERER];
2868 assert(parameter != NULL);
2869 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2870 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2872 if (!parameter_conditional_block && !parameter_conditional_forge)
2875 * As conditional-block and conditional-forge are the only
2876 * parameters that rely on the original referrer, we can
2877 * remove it now for all the others.
2882 if (0 == strcmpic(parameter, "block"))
2884 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2887 else if (parameter_conditional_block || parameter_conditional_forge)
2889 return handle_conditional_hide_referrer_parameter(header,
2890 csp->http->hostport, parameter_conditional_block);
2892 else if (0 == strcmpic(parameter, "forge"))
2894 return create_forged_referrer(header, csp->http->hostport);
2898 /* interpret parameter as user-supplied referer to fake */
2899 return create_fake_referrer(header, parameter);
2904 /*********************************************************************
2906 * Function : client_accept_language
2908 * Description : Handle the "Accept-Language" config setting properly.
2909 * Called from `sed'.
2912 * 1 : csp = Current client state (buffers, headers, etc...)
2913 * 2 : header = On input, pointer to header to modify.
2914 * On output, pointer to the modified header, or NULL
2915 * to remove the header. This function frees the
2916 * original string if necessary.
2918 * Returns : JB_ERR_OK on success, or
2919 * JB_ERR_MEMORY on out-of-memory error.
2921 *********************************************************************/
2922 static jb_err client_accept_language(struct client_state *csp, char **header)
2927 * Are we messing with the Accept-Language?
2929 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2931 /*I don't think so*/
2935 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2937 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2940 * Blocking Accept-Language header
2942 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2949 * Replacing Accept-Language header
2952 *header = strdup("Accept-Language: ");
2953 string_append(header, newval);
2955 if (*header == NULL)
2957 log_error(LOG_LEVEL_ERROR,
2958 "Insufficient memory. Accept-Language header crunched without replacement.");
2962 log_error(LOG_LEVEL_HEADER,
2963 "Accept-Language header crunched and replaced with: %s", *header);
2966 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2970 /*********************************************************************
2972 * Function : crunch_client_header
2974 * Description : Crunch client header if it matches a string supplied by the
2975 * user. Called from `sed'.
2978 * 1 : csp = Current client state (buffers, headers, etc...)
2979 * 2 : header = On input, pointer to header to modify.
2980 * On output, pointer to the modified header, or NULL
2981 * to remove the header. This function frees the
2982 * original string if necessary.
2984 * Returns : JB_ERR_OK on success and always succeeds
2986 *********************************************************************/
2987 static jb_err crunch_client_header(struct client_state *csp, char **header)
2989 const char *crunch_pattern;
2991 /* Do we feel like crunching? */
2992 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2994 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2996 /* Is the current header the lucky one? */
2997 if (strstr(*header, crunch_pattern))
2999 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3007 /*********************************************************************
3009 * Function : client_uagent
3011 * Description : Handle the "user-agent" config setting properly
3012 * and remember its original value to enable browser
3013 * bug workarounds. Called from `sed'.
3016 * 1 : csp = Current client state (buffers, headers, etc...)
3017 * 2 : header = On input, pointer to header to modify.
3018 * On output, pointer to the modified header, or NULL
3019 * to remove the header. This function frees the
3020 * original string if necessary.
3022 * Returns : JB_ERR_OK on success, or
3023 * JB_ERR_MEMORY on out-of-memory error.
3025 *********************************************************************/
3026 static jb_err client_uagent(struct client_state *csp, char **header)
3030 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3035 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3042 *header = strdup("User-Agent: ");
3043 string_append(header, newval);
3045 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3047 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3051 /*********************************************************************
3053 * Function : client_ua
3055 * Description : Handle "ua-" headers properly. Called from `sed'.
3058 * 1 : csp = Current client state (buffers, headers, etc...)
3059 * 2 : header = On input, pointer to header to modify.
3060 * On output, pointer to the modified header, or NULL
3061 * to remove the header. This function frees the
3062 * original string if necessary.
3064 * Returns : JB_ERR_OK on success, or
3065 * JB_ERR_MEMORY on out-of-memory error.
3067 *********************************************************************/
3068 static jb_err client_ua(struct client_state *csp, char **header)
3070 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3072 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3080 /*********************************************************************
3082 * Function : client_from
3084 * Description : Handle the "from" config setting properly.
3085 * Called from `sed'.
3088 * 1 : csp = Current client state (buffers, headers, etc...)
3089 * 2 : header = On input, pointer to header to modify.
3090 * On output, pointer to the modified header, or NULL
3091 * to remove the header. This function frees the
3092 * original string if necessary.
3094 * Returns : JB_ERR_OK on success, or
3095 * JB_ERR_MEMORY on out-of-memory error.
3097 *********************************************************************/
3098 static jb_err client_from(struct client_state *csp, char **header)
3102 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3109 newval = csp->action->string[ACTION_STRING_FROM];
3112 * Are we blocking the e-mail address?
3114 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3116 log_error(LOG_LEVEL_HEADER, "crunched From!");
3120 log_error(LOG_LEVEL_HEADER, " modified");
3122 *header = strdup("From: ");
3123 string_append(header, newval);
3125 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3129 /*********************************************************************
3131 * Function : client_send_cookie
3133 * Description : Crunches the "cookie" header if necessary.
3134 * Called from `sed'.
3136 * XXX: Stupid name, doesn't send squat.
3139 * 1 : csp = Current client state (buffers, headers, etc...)
3140 * 2 : header = On input, pointer to header to modify.
3141 * On output, pointer to the modified header, or NULL
3142 * to remove the header. This function frees the
3143 * original string if necessary.
3145 * Returns : JB_ERR_OK on success, or
3146 * JB_ERR_MEMORY on out-of-memory error.
3148 *********************************************************************/
3149 static jb_err client_send_cookie(struct client_state *csp, char **header)
3151 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3153 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3161 /*********************************************************************
3163 * Function : client_x_forwarded
3165 * Description : Handle the "x-forwarded-for" config setting properly,
3166 * also used in the add_client_headers list. Called from `sed'.
3169 * 1 : csp = Current client state (buffers, headers, etc...)
3170 * 2 : header = On input, pointer to header to modify.
3171 * On output, pointer to the modified header, or NULL
3172 * to remove the header. This function frees the
3173 * original string if necessary.
3175 * Returns : JB_ERR_OK on success, or
3176 * JB_ERR_MEMORY on out-of-memory error.
3178 *********************************************************************/
3179 jb_err client_x_forwarded(struct client_state *csp, char **header)
3181 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3183 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3185 if (0 == strcmpic(parameter, "block"))
3188 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3190 else if (0 == strcmpic(parameter, "add"))
3192 string_append(header, ", ");
3193 string_append(header, csp->ip_addr_str);
3195 if (*header == NULL)
3197 return JB_ERR_MEMORY;
3199 log_error(LOG_LEVEL_HEADER,
3200 "Appended client IP address to %s", *header);
3201 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3205 log_error(LOG_LEVEL_FATAL,
3206 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3214 /*********************************************************************
3216 * Function : client_max_forwards
3218 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3219 * from the value of the Max-Forwards header field.
3222 * 1 : csp = Current client state (buffers, headers, etc...)
3223 * 2 : header = On input, pointer to header to modify.
3224 * On output, pointer to the modified header, or NULL
3225 * to remove the header. This function frees the
3226 * original string if necessary.
3228 * Returns : JB_ERR_OK on success, or
3229 * JB_ERR_MEMORY on out-of-memory error.
3231 *********************************************************************/
3232 static jb_err client_max_forwards(struct client_state *csp, char **header)
3236 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3237 (0 == strcmpic(csp->http->gpc, "options")))
3239 assert(*(*header+12) == ':');
3240 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3242 if (max_forwards > 0)
3244 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3245 log_error(LOG_LEVEL_HEADER,
3246 "Max-Forwards value for %s request reduced to %d.",
3247 csp->http->gpc, max_forwards);
3249 else if (max_forwards < 0)
3251 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3257 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3266 /*********************************************************************
3268 * Function : client_host
3270 * Description : If the request URI did not contain host and
3271 * port information, parse and evaluate the Host
3275 * 1 : csp = Current client state (buffers, headers, etc...)
3276 * 2 : header = On input, pointer to header to modify.
3277 * On output, pointer to the modified header, or NULL
3278 * to remove the header. This function frees the
3279 * original string if necessary.
3281 * Returns : JB_ERR_OK on success, or
3282 * JB_ERR_MEMORY on out-of-memory error.
3284 *********************************************************************/
3285 static jb_err client_host(struct client_state *csp, char **header)
3289 if (strlen(*header) < 7)
3291 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3296 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3297 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3300 p = strdup_or_die((*header)+6);
3302 q = strdup_or_die(p);
3304 freez(csp->http->hostport);
3305 csp->http->hostport = p;
3306 freez(csp->http->host);
3307 csp->http->host = q;
3308 q = strchr(csp->http->host, ':');
3311 /* Terminate hostname and evaluate port string */
3313 csp->http->port = atoi(q);
3317 csp->http->port = csp->http->ssl ? 443 : 80;
3320 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3321 csp->http->hostport, csp->http->host, csp->http->port);
3324 /* Signal client_host_adder() to return right away */
3325 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3331 /*********************************************************************
3333 * Function : client_if_modified_since
3335 * Description : Remove or modify the If-Modified-Since header.
3338 * 1 : csp = Current client state (buffers, headers, etc...)
3339 * 2 : header = On input, pointer to header to modify.
3340 * On output, pointer to the modified header, or NULL
3341 * to remove the header. This function frees the
3342 * original string if necessary.
3344 * Returns : JB_ERR_OK on success, or
3345 * JB_ERR_MEMORY on out-of-memory error.
3347 *********************************************************************/
3348 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3351 #ifdef HAVE_GMTIME_R
3354 struct tm *timeptr = NULL;
3359 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3362 * The client got an error message because of a temporary problem,
3363 * the problem is gone and the client now tries to revalidate our
3364 * error message on the real server. The revalidation would always
3365 * end with the transmission of the whole document and there is
3366 * no need to expose the bogus If-Modified-Since header.
3368 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3371 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3373 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3375 if ((0 == strcmpic(newval, "block")))
3377 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3380 else /* add random value */
3382 if (JB_ERR_OK != parse_time_header(*header, &tm))
3384 log_error(LOG_LEVEL_HEADER,
3385 "Couldn't parse time in %s (crunching!)", *header);
3390 long int hours, minutes, seconds;
3391 long int rtime = strtol(newval, &endptr, 0);
3392 const int negative_range = (rtime < 0);
3396 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3397 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3403 rtime = pick_from_range(rtime);
3407 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3410 tm += rtime * (negative_range ? -1 : 1);
3411 #ifdef HAVE_GMTIME_R
3412 timeptr = gmtime_r(&tm, &gmt);
3413 #elif defined(MUTEX_LOCKS_AVAILABLE)
3414 privoxy_mutex_lock(&gmtime_mutex);
3415 timeptr = gmtime(&tm);
3416 privoxy_mutex_unlock(&gmtime_mutex);
3418 timeptr = gmtime(&tm);
3420 if ((NULL == timeptr) || !strftime(newheader,
3421 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3423 log_error(LOG_LEVEL_ERROR,
3424 "Randomizing '%s' failed. Crunching the header without replacement.",
3431 *header = strdup("If-Modified-Since: ");
3432 string_append(header, newheader);
3434 if (*header == NULL)
3436 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3437 return JB_ERR_MEMORY;
3440 hours = rtime / 3600;
3441 minutes = rtime / 60 % 60;
3442 seconds = rtime % 60;
3444 log_error(LOG_LEVEL_HEADER,
3445 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3446 *header, (negative_range) ? "subtracted" : "added", hours,
3447 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3448 seconds, (seconds == 1) ? ")" : "s)");
3457 /*********************************************************************
3459 * Function : client_if_none_match
3461 * Description : Remove the If-None-Match header.
3464 * 1 : csp = Current client state (buffers, headers, etc...)
3465 * 2 : header = On input, pointer to header to modify.
3466 * On output, pointer to the modified header, or NULL
3467 * to remove the header. This function frees the
3468 * original string if necessary.
3470 * Returns : JB_ERR_OK on success, or
3471 * JB_ERR_MEMORY on out-of-memory error.
3473 *********************************************************************/
3474 static jb_err client_if_none_match(struct client_state *csp, char **header)
3476 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3478 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3486 /*********************************************************************
3488 * Function : client_x_filter
3490 * Description : Disables filtering if the client set "X-Filter: No".
3491 * Called from `sed'.
3494 * 1 : csp = Current client state (buffers, headers, etc...)
3495 * 2 : header = On input, pointer to header to modify.
3496 * On output, pointer to the modified header, or NULL
3497 * to remove the header. This function frees the
3498 * original string if necessary.
3500 * Returns : JB_ERR_OK on success
3502 *********************************************************************/
3503 jb_err client_x_filter(struct client_state *csp, char **header)
3505 if (0 == strcmpic(*header, "X-Filter: No"))
3507 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3509 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3513 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3515 log_error(LOG_LEVEL_HEADER,
3516 "force-text-mode overruled the client's request to fetch without filtering!");
3520 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3521 csp->flags |= CSP_FLAG_NO_FILTERING;
3522 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3524 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3532 /*********************************************************************
3534 * Function : client_range
3536 * Description : Removes Range, Request-Range and If-Range headers if
3537 * content filtering is enabled and the range doesn't
3540 * If the client's version of the document has been
3541 * altered by Privoxy, the server could interpret the
3542 * range differently than the client intended in which
3543 * case the user could end up with corrupted content.
3545 * If the range starts at byte 0 this isn't an issue
3546 * so the header can pass. Partial requests like this
3547 * are used to render preview images for videos without
3548 * downloading the whole video.
3550 * While HTTP doesn't require that range requests are
3551 * honoured and the client could simply abort the download
3552 * after receiving a sufficient amount of data, various
3553 * clients don't handle complete responses to range
3554 * requests gracefully and emit misleading error messages
3558 * 1 : csp = Current client state (buffers, headers, etc...)
3559 * 2 : header = On input, pointer to header to modify.
3560 * On output, pointer to the modified header, or NULL
3561 * to remove the header. This function frees the
3562 * original string if necessary.
3564 * Returns : JB_ERR_OK
3566 *********************************************************************/
3567 static jb_err client_range(struct client_state *csp, char **header)
3569 if (content_filters_enabled(csp->action)
3570 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3572 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3573 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3580 /* the following functions add headers directly to the header list */
3582 /*********************************************************************
3584 * Function : client_host_adder
3586 * Description : Adds the Host: header field if it is missing.
3587 * Called from `sed'.
3590 * 1 : csp = Current client state (buffers, headers, etc...)
3592 * Returns : JB_ERR_OK on success, or
3593 * JB_ERR_MEMORY on out-of-memory error.
3595 *********************************************************************/
3596 static jb_err client_host_adder(struct client_state *csp)
3601 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3603 /* Header already set by the client, nothing to do. */
3607 if (!csp->http->hostport || !*(csp->http->hostport))
3609 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3610 return JB_ERR_PARSE;
3614 * remove 'user:pass@' from 'proto://user:pass@host'
3616 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3622 p = csp->http->hostport;
3625 /* XXX: Just add it, we already made sure that it will be unique */
3626 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3627 err = enlist_unique_header(csp->headers, "Host", p);
3633 /*********************************************************************
3635 * Function : client_xtra_adder
3637 * Description : Used in the add_client_headers list. Called from `sed'.
3640 * 1 : csp = Current client state (buffers, headers, etc...)
3642 * Returns : JB_ERR_OK on success, or
3643 * JB_ERR_MEMORY on out-of-memory error.
3645 *********************************************************************/
3646 static jb_err client_xtra_adder(struct client_state *csp)
3648 struct list_entry *lst;
3651 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3652 lst ; lst = lst->next)
3654 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3655 err = enlist(csp->headers, lst->str);
3667 /*********************************************************************
3669 * Function : client_x_forwarded_for_adder
3671 * Description : Used in the add_client_headers list. Called from `sed'.
3674 * 1 : csp = Current client state (buffers, headers, etc...)
3676 * Returns : JB_ERR_OK on success, or
3677 * JB_ERR_MEMORY on out-of-memory error.
3679 *********************************************************************/
3680 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3682 char *header = NULL;
3685 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3686 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3687 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3690 * If we aren't adding X-Forwarded-For headers,
3691 * or we already appended an existing X-Forwarded-For
3692 * header, there's nothing left to do here.
3697 header = strdup("X-Forwarded-For: ");
3698 string_append(&header, csp->ip_addr_str);
3702 return JB_ERR_MEMORY;
3705 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3706 err = enlist(csp->headers, header);
3713 /*********************************************************************
3715 * Function : server_connection_adder
3717 * Description : Adds an appropriate "Connection:" header to csp->headers
3718 * unless the header was already present. Called from `sed'.
3721 * 1 : csp = Current client state (buffers, headers, etc...)
3723 * Returns : JB_ERR_OK on success, or
3724 * JB_ERR_MEMORY on out-of-memory error.
3726 *********************************************************************/
3727 static jb_err server_connection_adder(struct client_state *csp)
3729 const unsigned int flags = csp->flags;
3730 const char *response_status_line = csp->headers->first->str;
3731 static const char connection_close[] = "Connection: close";
3733 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3734 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3740 * XXX: if we downgraded the response, this check will fail.
3742 if ((csp->config->feature_flags &
3743 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3744 && (NULL != response_status_line)
3745 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3746 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3747 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3751 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3752 "without Connection header implies keep-alive.");
3753 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3757 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3759 return enlist(csp->headers, connection_close);
3763 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3764 /*********************************************************************
3766 * Function : server_proxy_connection_adder
3768 * Description : Adds a "Proxy-Connection: keep-alive" header to
3769 * csp->headers when appropriate.
3772 * 1 : csp = Current client state (buffers, headers, etc...)
3774 * Returns : JB_ERR_OK on success, or
3775 * JB_ERR_MEMORY on out-of-memory error.
3777 *********************************************************************/
3778 static jb_err server_proxy_connection_adder(struct client_state *csp)
3780 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3781 jb_err err = JB_ERR_OK;
3783 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3784 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3785 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3786 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3787 || (csp->flags & CSP_FLAG_CHUNKED)))
3789 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3790 err = enlist(csp->headers, proxy_connection_header);
3795 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3798 /*********************************************************************
3800 * Function : client_connection_header_adder
3802 * Description : Adds a proper "Connection:" header to csp->headers
3803 * unless the header was already present. Called from `sed'.
3806 * 1 : csp = Current client state (buffers, headers, etc...)
3808 * Returns : JB_ERR_OK on success, or
3809 * JB_ERR_MEMORY on out-of-memory error.
3811 *********************************************************************/
3812 static jb_err client_connection_header_adder(struct client_state *csp)
3814 static const char connection_close[] = "Connection: close";
3816 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3817 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3822 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3823 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3824 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3825 && (csp->http->ssl == 0)
3826 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3828 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3831 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3833 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3835 return enlist(csp->headers, connection_close);
3839 /*********************************************************************
3841 * Function : server_http
3843 * Description : - Save the HTTP Status into csp->http->status
3844 * - Set CT_TABOO to prevent filtering if the answer
3845 * is a partial range (HTTP status 206)
3846 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3848 * - Normalize the HTTP-version.
3851 * 1 : csp = Current client state (buffers, headers, etc...)
3852 * 2 : header = On input, pointer to header to modify.
3853 * On output, pointer to the modified header, or NULL
3854 * to remove the header. This function frees the
3855 * original string if necessary.
3857 * Returns : JB_ERR_OK on success, or
3858 * JB_ERR_PARSE on fatal parse errors.
3860 *********************************************************************/
3861 static jb_err server_http(struct client_state *csp, char **header)
3863 char *reason_phrase = NULL;
3864 char *new_response_line;
3867 unsigned int major_version;
3868 unsigned int minor_version;
3870 /* Get the reason phrase which start after the second whitespace */
3871 p = strchr(*header, ' ');
3875 reason_phrase = strchr(p, ' ');
3878 if (reason_phrase != NULL)
3884 log_error(LOG_LEVEL_ERROR,
3885 "Response line lacks reason phrase: %s", *header);
3889 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
3890 &minor_version, &(csp->http->status)))
3892 log_error(LOG_LEVEL_ERROR,
3893 "Failed to parse the response line: %s", *header);
3894 return JB_ERR_PARSE;
3897 if (csp->http->status == 206)
3899 csp->content_type = CT_TABOO;
3902 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
3905 * According to RFC 7230 2.6 intermediaries MUST send
3906 * their own HTTP-version in forwarded messages.
3908 log_error(LOG_LEVEL_ERROR,
3909 "Unsupported HTTP version. Downgrading to 1.1.");
3914 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
3916 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
3920 /* Rebuild response line. */
3921 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
3922 new_response_line = malloc_or_die(length);
3924 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
3925 major_version, minor_version, csp->http->status, reason_phrase);
3927 if (0 != strcmp(*header, new_response_line))
3929 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
3930 *header, new_response_line);
3934 *header = new_response_line;
3939 /*********************************************************************
3941 * Function : add_cooky_expiry_date
3943 * Description : Adds a cookie expiry date to a string.
3946 * 1 : cookie = On input, pointer to cookie to modify.
3947 * On output, pointer to the modified header.
3948 * The original string is freed.
3949 * 2 : lifetime = Seconds the cookie should be valid
3953 *********************************************************************/
3954 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
3957 struct tm *timeptr = NULL;
3958 time_t expiry_date = time(NULL) + lifetime;
3959 #ifdef HAVE_GMTIME_R
3962 timeptr = gmtime_r(&expiry_date, &gmt);
3963 #elif defined(MUTEX_LOCKS_AVAILABLE)
3964 privoxy_mutex_lock(&gmtime_mutex);
3965 timeptr = gmtime(&expiry_date);
3966 privoxy_mutex_unlock(&gmtime_mutex);
3968 timeptr = gmtime(&expiry_date);
3971 if (NULL == timeptr)
3973 log_error(LOG_LEVEL_FATAL,
3974 "Failed to get the time in add_cooky_expiry_date()");
3976 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
3977 if (JB_ERR_OK != string_append(cookie, tmp))
3979 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
3984 /*********************************************************************
3986 * Function : server_set_cookie
3988 * Description : Handle the server "cookie" header properly.
3989 * Crunch, accept or rewrite it to a session cookie.
3990 * Called from `sed'.
3993 * 1 : csp = Current client state (buffers, headers, etc...)
3994 * 2 : header = On input, pointer to header to modify.
3995 * On output, pointer to the modified header, or NULL
3996 * to remove the header. This function frees the
3997 * original string if necessary.
3999 * Returns : JB_ERR_OK on success, or
4000 * JB_ERR_MEMORY on out-of-memory error.
4002 *********************************************************************/
4003 static jb_err server_set_cookie(struct client_state *csp, char **header)
4005 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4007 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4010 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4011 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4015 long cookie_lifetime = 0;
4018 NO_EXPIRY_DATE_SPECIFIED,
4019 EXPIRY_DATE_ACCEPTABLE,
4020 EXPIRY_DATE_UNACCEPTABLE
4021 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4023 /* A variable to store the tag we're working on */
4026 /* Skip "Set-Cookie:" (11 characters) in header */
4027 cur_tag = *header + 11;
4029 /* skip whitespace between "Set-Cookie:" and value */
4030 while (*cur_tag && privoxy_isspace(*cur_tag))
4037 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4039 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4041 cookie_lifetime = strtol(param, NULL, 0);
4042 if (cookie_lifetime < 0)
4044 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4046 cookie_lifetime *= 60;
4049 /* Loop through each tag in the cookie */
4053 char *next_tag = strchr(cur_tag, ';');
4054 if (next_tag != NULL)
4056 /* Skip the ';' character itself */
4059 /* skip whitespace ";" and start of tag */
4060 while (*next_tag && privoxy_isspace(*next_tag))
4067 /* "Next tag" is the end of the string */
4068 next_tag = cur_tag + strlen(cur_tag);
4072 * Check the expiration date to see
4073 * if the cookie is still valid, if yes,
4074 * rewrite it to a session cookie.
4076 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4078 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4080 if ((expiration_date[0] == '"')
4081 && (expiration_date[1] != '\0'))
4084 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4085 * that the expiration date isn't supposed to be quoted,
4086 * but some servers do it anyway.
4091 /* Did we detect the date properly? */
4092 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4095 * Nope, treat it as if it was still valid.
4097 * XXX: Should we remove the whole cookie instead?
4099 log_error(LOG_LEVEL_ERROR,
4100 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4101 string_move(cur_tag, next_tag);
4102 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4107 * Yes. Check if the cookie is still valid.
4109 * If the cookie is already expired it's probably
4110 * a delete cookie and even if it isn't, the browser
4111 * will discard it anyway.
4115 * XXX: timegm() isn't available on some AmigaOS
4116 * versions and our replacement doesn't work.
4118 * Our options are to either:
4120 * - disable session-cookies-only completely if timegm
4123 * - to simply remove all expired tags, like it has
4124 * been done until Privoxy 3.0.6 and to live with
4125 * the consequence that it can cause login/logout
4126 * problems on servers that don't validate their
4127 * input properly, or
4129 * - to replace it with mktime in which
4130 * case there is a slight chance of valid cookies
4131 * passing as already expired.
4133 * This is the way it's currently done and it's not
4134 * as bad as it sounds. If the missing GMT offset is
4135 * enough to change the result of the expiration check
4136 * the cookie will be only valid for a few hours
4137 * anyway, which in many cases will be shorter
4138 * than a browser session.
4140 if (cookie_time < now)
4142 log_error(LOG_LEVEL_HEADER,
4143 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4144 /* Just in case some clown sets more then one expiration date */
4146 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4148 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4150 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4151 "Its lifetime is below the limit.", *header);
4152 /* Just in case some clown sets more then one expiration date */
4154 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4159 * Still valid, delete expiration date by copying
4160 * the rest of the string over it.
4162 string_move(cur_tag, next_tag);
4164 /* That changed the header, need to issue a log message */
4165 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4168 * Note that the next tag has now been moved to *cur_tag,
4169 * so we do not need to update the cur_tag pointer.
4177 /* Move on to next cookie tag */
4182 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4184 assert(NULL != *header);
4185 if (cookie_lifetime != 0)
4187 add_cookie_expiry_date(header, cookie_lifetime);
4188 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4190 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4192 log_error(LOG_LEVEL_HEADER,
4193 "Cookie rewritten to a temporary one: %s", *header);
4202 #ifdef FEATURE_FORCE_LOAD
4203 /*********************************************************************
4205 * Function : strclean
4207 * Description : In-Situ-Eliminate all occurrences of substring in
4211 * 1 : string = string to clean
4212 * 2 : substring = substring to eliminate
4214 * Returns : Number of eliminations
4216 *********************************************************************/
4217 int strclean(char *string, const char *substring)
4223 len = strlen(substring);
4225 while((pos = strstr(string, substring)) != NULL)
4232 while (*p++ != '\0');
4239 #endif /* def FEATURE_FORCE_LOAD */
4242 /*********************************************************************
4244 * Function : parse_header_time
4246 * Description : Parses time formats used in HTTP header strings
4247 * to get the numerical respresentation.
4250 * 1 : header_time = HTTP header time as string.
4251 * 2 : result = storage for header_time in seconds
4253 * Returns : JB_ERR_OK if the time format was recognized, or
4254 * JB_ERR_PARSE otherwise.
4256 *********************************************************************/
4257 static jb_err parse_header_time(const char *header_time, time_t *result)
4261 * Checking for two-digit years first in an
4262 * attempt to work around GNU libc's strptime()
4263 * reporting negative year values when using %Y.
4265 static const char time_formats[][22] = {
4266 /* Tue, 02-Jun-37 20:00:00 */
4267 "%a, %d-%b-%y %H:%M:%S",
4268 /* Tue, 02 Jun 2037 20:00:00 */
4269 "%a, %d %b %Y %H:%M:%S",
4270 /* Tue, 02-Jun-2037 20:00:00 */
4271 "%a, %d-%b-%Y %H:%M:%S",
4272 /* Tuesday, 02-Jun-2037 20:00:00 */
4273 "%A, %d-%b-%Y %H:%M:%S",
4274 /* Tuesday Jun 02 20:00:00 2037 */
4275 "%A %b %d %H:%M:%S %Y"
4279 for (i = 0; i < SZ(time_formats); i++)
4282 * Zero out gmt to prevent time zone offsets.
4283 * Documented to be required for GNU libc.
4285 memset(&gmt, 0, sizeof(gmt));
4287 if (NULL != strptime(header_time, time_formats[i], &gmt))
4289 /* Sanity check for GNU libc. */
4290 if (gmt.tm_year < 0)
4292 log_error(LOG_LEVEL_HEADER,
4293 "Failed to parse '%s' using '%s'. Moving on.",
4294 header_time, time_formats[i]);
4297 *result = timegm(&gmt);
4299 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4301 * Verify that parsing the date recreated from the first
4302 * parse operation gets the previous result. If it doesn't,
4303 * either strptime() or strftime() are malfunctioning.
4305 * We could string-compare the recreated date with the original
4306 * header date, but this leads to false positives as strptime()
4307 * may let %a accept all day formats while strftime() will only
4311 char recreated_date[100];
4315 tm = gmtime(result);
4316 strftime(recreated_date, sizeof(recreated_date), time_formats[i], tm);
4317 memset(&gmt, 0, sizeof(gmt));
4318 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4320 log_error(LOG_LEVEL_ERROR,
4321 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4322 recreated_date, time_formats[i], header_time);
4325 result2 = timegm(&gmt);
4326 if (*result != result2)
4328 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4329 "Format: '%s'. In: '%s', out: '%s'. %d != %d. Rejecting.",
4330 time_formats[i], header_time, recreated_date, *result, result2);
4340 return JB_ERR_PARSE;
4344 /*********************************************************************
4346 * Function : parse_time_header
4348 * Description : Parses the time in an HTTP time header to get
4349 * the numerical respresentation.
4352 * 1 : header = HTTP header with a time value
4353 * 2 : result = storage for header_time in seconds
4355 * Returns : JB_ERR_OK if the time format was recognized, or
4356 * JB_ERR_PARSE otherwise.
4358 *********************************************************************/
4359 static jb_err parse_time_header(const char *header, time_t *result)
4361 const char *header_time;
4363 header_time = strchr(header, ':');
4366 * Currently this can't happen as all callers are called
4367 * through sed() which requires a header name followed by
4370 assert(header_time != NULL);
4373 if (*header_time == ' ')
4378 return parse_header_time(header_time, result);
4383 /*********************************************************************
4385 * Function : get_destination_from_headers
4387 * Description : Parse the "Host:" header to get the request's destination.
4388 * Only needed if the client's request was forcefully
4389 * redirected into Privoxy.
4391 * Code mainly copied from client_host() which is currently
4392 * run too late for this purpose.
4395 * 1 : headers = List of headers (one of them hopefully being
4396 * the "Host:" header)
4397 * 2 : http = storage for the result (host, port and hostport).
4399 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4400 * JB_ERR_PARSE if the host header couldn't be found,
4401 * JB_ERR_OK otherwise.
4403 *********************************************************************/
4404 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4412 host = get_header_value(headers, "Host:");
4416 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4417 return JB_ERR_PARSE;
4420 p = strdup_or_die(host);
4422 q = strdup_or_die(p);
4424 freez(http->hostport);
4428 q = strchr(http->host, ':');
4431 /* Terminate hostname and evaluate port string */
4433 http->port = atoi(q);
4440 /* Rebuild request URL */
4442 http->url = strdup("http://");
4443 string_append(&http->url, http->hostport);
4444 string_append(&http->url, http->path);
4445 if (http->url == NULL)
4447 return JB_ERR_MEMORY;
4450 log_error(LOG_LEVEL_HEADER,
4451 "Destination extracted from \"Host\" header. New request URL: %s",
4455 * Regenerate request line in "proxy format"
4456 * to make rewrites more convenient.
4458 assert(http->cmd != NULL);
4460 http->cmd = strdup_or_die(http->gpc);
4461 string_append(&http->cmd, " ");
4462 string_append(&http->cmd, http->url);
4463 string_append(&http->cmd, " ");
4464 string_append(&http->cmd, http->ver);
4465 if (http->cmd == NULL)
4467 return JB_ERR_MEMORY;
4475 /*********************************************************************
4477 * Function : create_forged_referrer
4479 * Description : Helper for client_referrer to forge a referer as
4480 * 'http://hostname[:port]/' to fool stupid
4481 * checks for in-site links
4484 * 1 : header = Pointer to header pointer
4485 * 2 : hostport = Host and optionally port as string
4487 * Returns : JB_ERR_OK in case of success, or
4488 * JB_ERR_MEMORY in case of memory problems.
4490 *********************************************************************/
4491 static jb_err create_forged_referrer(char **header, const char *hostport)
4493 assert(NULL == *header);
4495 *header = strdup("Referer: http://");
4496 string_append(header, hostport);
4497 string_append(header, "/");
4499 if (NULL == *header)
4501 return JB_ERR_MEMORY;
4504 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4511 /*********************************************************************
4513 * Function : create_fake_referrer
4515 * Description : Helper for client_referrer to create a fake referrer
4516 * based on a string supplied by the user.
4519 * 1 : header = Pointer to header pointer
4520 * 2 : hosthost = Referrer to fake
4522 * Returns : JB_ERR_OK in case of success, or
4523 * JB_ERR_MEMORY in case of memory problems.
4525 *********************************************************************/
4526 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4528 assert(NULL == *header);
4530 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4532 log_error(LOG_LEVEL_HEADER,
4533 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4535 *header = strdup("Referer: ");
4536 string_append(header, fake_referrer);
4538 if (NULL == *header)
4540 return JB_ERR_MEMORY;
4543 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4550 /*********************************************************************
4552 * Function : handle_conditional_hide_referrer_parameter
4554 * Description : Helper for client_referrer to crunch or forge
4555 * the referrer header if the host has changed.
4558 * 1 : header = Pointer to header pointer
4559 * 2 : host = The target host (may include the port)
4560 * 3 : parameter_conditional_block = Boolean to signal
4561 * if we're in conditional-block mode. If not set,
4562 * we're in conditional-forge mode.
4564 * Returns : JB_ERR_OK in case of success, or
4565 * JB_ERR_MEMORY in case of memory problems.
4567 *********************************************************************/
4568 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4569 const char *host, const int parameter_conditional_block)
4571 char *referer = strdup_or_die(*header);
4572 const size_t hostlength = strlen(host);
4573 const char *referer_url = NULL;
4575 /* referer begins with 'Referer: http[s]://' */
4576 if ((hostlength+17) < strlen(referer))
4579 * Shorten referer to make sure the referer is blocked
4580 * if www.example.org/www.example.com-shall-see-the-referer/
4581 * links to www.example.com/
4583 referer[hostlength+17] = '\0';
4585 referer_url = strstr(referer, "http://");
4586 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4588 /* Host has changed, Referer is invalid or a https URL. */
4589 if (parameter_conditional_block)
4591 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4598 return create_forged_referrer(header, host);
4608 /*********************************************************************
4610 * Function : create_content_length_header
4612 * Description : Creates a Content-Length header.
4615 * 1 : content_length = The content length to be used in the header.
4616 * 2 : header = Allocated space to safe the header.
4617 * 3 : buffer_length = The length of the allocated space.
4621 *********************************************************************/
4622 static void create_content_length_header(unsigned long long content_length,
4623 char *header, size_t buffer_length)
4625 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4629 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4630 /*********************************************************************
4632 * Function : get_expected_content_length
4634 * Description : Figures out the content length from a list of headers.
4637 * 1 : headers = List of headers
4639 * Returns : Number of bytes to expect
4641 *********************************************************************/
4642 unsigned long long get_expected_content_length(struct list *headers)
4644 const char *content_length_header;
4645 unsigned long long content_length = 0;
4647 content_length_header = get_header_value(headers, "Content-Length:");
4648 if (content_length_header != NULL)
4650 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4652 log_error(LOG_LEVEL_ERROR,
4653 "Failed to get the Content-Length in %s", content_length_header);
4654 /* XXX: The header will be removed later on */
4659 return content_length;