1 const char parsers_rcs[] = "$Id: parsers.c,v 1.298 2015/01/24 16:41:51 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-2014 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 ((csp->rlist != NULL) &&
2376 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2378 log_error(LOG_LEVEL_INFO,
2379 "Compressed content detected, content filtering disabled. "
2380 "Consider recompiling Privoxy with zlib support or "
2381 "enable the prevent-compression action.");
2384 #endif /* defined(FEATURE_ZLIB) */
2392 /*********************************************************************
2394 * Function : server_adjust_content_encoding
2396 * Description : Remove the Content-Encoding header if the
2397 * decompression was successful and the content
2401 * 1 : csp = Current client state (buffers, headers, etc...)
2402 * 2 : header = On input, pointer to header to modify.
2403 * On output, pointer to the modified header, or NULL
2404 * to remove the header. This function frees the
2405 * original string if necessary.
2407 * Returns : JB_ERR_OK on success, or
2408 * JB_ERR_MEMORY on out-of-memory error.
2410 *********************************************************************/
2411 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2413 if ((csp->flags & CSP_FLAG_MODIFIED)
2414 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2417 * We successfully decompressed the content,
2418 * and have to clean the header now, so the
2419 * client no longer expects compressed data.
2421 * XXX: There is a difference between cleaning
2422 * and removing it completely.
2424 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2431 #endif /* defined(FEATURE_ZLIB) */
2434 /*********************************************************************
2436 * Function : server_adjust_content_length
2438 * Description : Adjust Content-Length header if we modified
2442 * 1 : csp = Current client state (buffers, headers, etc...)
2443 * 2 : header = On input, pointer to header to modify.
2444 * On output, pointer to the modified header, or NULL
2445 * to remove the header. This function frees the
2446 * original string if necessary.
2448 * Returns : JB_ERR_OK on success, or
2449 * JB_ERR_MEMORY on out-of-memory error.
2451 *********************************************************************/
2452 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2454 /* Regenerate header if the content was modified. */
2455 if (csp->flags & CSP_FLAG_MODIFIED)
2457 const size_t header_length = 50;
2459 *header = malloc(header_length);
2460 if (*header == NULL)
2462 return JB_ERR_MEMORY;
2464 create_content_length_header(csp->content_length, *header, header_length);
2465 log_error(LOG_LEVEL_HEADER,
2466 "Adjusted Content-Length to %llu", csp->content_length);
2473 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2474 /*********************************************************************
2476 * Function : server_save_content_length
2478 * Description : Save the Content-Length sent by the server.
2481 * 1 : csp = Current client state (buffers, headers, etc...)
2482 * 2 : header = On input, pointer to header to modify.
2483 * On output, pointer to the modified header, or NULL
2484 * to remove the header. This function frees the
2485 * original string if necessary.
2487 * Returns : JB_ERR_OK on success, or
2488 * JB_ERR_MEMORY on out-of-memory error.
2490 *********************************************************************/
2491 static jb_err server_save_content_length(struct client_state *csp, char **header)
2493 unsigned long long content_length = 0;
2494 const char *header_value;
2496 assert(*(*header+14) == ':');
2498 header_value = *header + 15;
2499 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2501 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2506 csp->expected_content_length = content_length;
2507 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2508 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2513 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2516 /*********************************************************************
2518 * Function : server_content_md5
2520 * Description : Crumble any Content-MD5 headers if the document was
2521 * modified. FIXME: Should we re-compute instead?
2524 * 1 : csp = Current client state (buffers, headers, etc...)
2525 * 2 : header = On input, pointer to header to modify.
2526 * On output, pointer to the modified header, or NULL
2527 * to remove the header. This function frees the
2528 * original string if necessary.
2530 * Returns : JB_ERR_OK on success, or
2531 * JB_ERR_MEMORY on out-of-memory error.
2533 *********************************************************************/
2534 static jb_err server_content_md5(struct client_state *csp, char **header)
2536 if (csp->flags & CSP_FLAG_MODIFIED)
2538 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2546 /*********************************************************************
2548 * Function : server_content_disposition
2550 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2551 * Called from `sed'.
2554 * 1 : csp = Current client state (buffers, headers, etc...)
2555 * 2 : header = On input, pointer to header to modify.
2556 * On output, pointer to the modified header, or NULL
2557 * to remove the header. This function frees the
2558 * original string if necessary.
2560 * Returns : JB_ERR_OK on success, or
2561 * JB_ERR_MEMORY on out-of-memory error.
2563 *********************************************************************/
2564 static jb_err server_content_disposition(struct client_state *csp, char **header)
2569 * Are we messing with the Content-Disposition header?
2571 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2577 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2579 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2582 * Blocking content-disposition header
2584 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2591 * Replacing Content-Disposition header
2594 *header = strdup("Content-Disposition: ");
2595 string_append(header, newval);
2597 if (*header != NULL)
2599 log_error(LOG_LEVEL_HEADER,
2600 "Content-Disposition header crunched and replaced with: %s", *header);
2603 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2607 /*********************************************************************
2609 * Function : server_last_modified
2611 * Description : Changes Last-Modified header to the actual date
2612 * to help hide-if-modified-since.
2613 * Called from `sed'.
2616 * 1 : csp = Current client state (buffers, headers, etc...)
2617 * 2 : header = On input, pointer to header to modify.
2618 * On output, pointer to the modified header, or NULL
2619 * to remove the header. This function frees the
2620 * original string if necessary.
2622 * Returns : JB_ERR_OK on success, or
2623 * JB_ERR_MEMORY on out-of-memory error.
2625 *********************************************************************/
2626 static jb_err server_last_modified(struct client_state *csp, char **header)
2629 time_t last_modified;
2633 * Are we messing with the Last-Modified header?
2635 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2641 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2643 if (0 == strcmpic(newval, "block"))
2646 * Blocking Last-Modified header. Useless but why not.
2648 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2652 else if (0 == strcmpic(newval, "reset-to-request-time"))
2655 * Setting Last-Modified Header to now.
2658 get_http_time(0, buf, sizeof(buf));
2660 *header = strdup("Last-Modified: ");
2661 string_append(header, buf);
2663 if (*header == NULL)
2665 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2669 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2672 else if (0 == strcmpic(newval, "randomize"))
2674 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2676 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2678 log_error(LOG_LEVEL_HEADER,
2679 "Couldn't parse time in %s (crunching!)", *header);
2685 struct tm *timeptr = NULL;
2687 #ifdef HAVE_GMTIME_R
2691 rtime = (long int)difftime(now, last_modified);
2694 long int days, hours, minutes, seconds;
2695 const int negative_delta = (rtime < 0);
2700 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2702 rtime = pick_from_range(rtime);
2707 last_modified += rtime;
2708 #ifdef HAVE_GMTIME_R
2709 timeptr = gmtime_r(&last_modified, &gmt);
2710 #elif defined(MUTEX_LOCKS_AVAILABLE)
2711 privoxy_mutex_lock(&gmtime_mutex);
2712 timeptr = gmtime(&last_modified);
2713 privoxy_mutex_unlock(&gmtime_mutex);
2715 timeptr = gmtime(&last_modified);
2717 if ((NULL == timeptr) || !strftime(newheader,
2718 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2720 log_error(LOG_LEVEL_ERROR,
2721 "Randomizing '%s' failed. Crunching the header without replacement.",
2728 *header = strdup("Last-Modified: ");
2729 string_append(header, newheader);
2731 if (*header == NULL)
2733 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2734 return JB_ERR_MEMORY;
2737 days = rtime / (3600 * 24);
2738 hours = rtime / 3600 % 24;
2739 minutes = rtime / 60 % 60;
2740 seconds = rtime % 60;
2742 log_error(LOG_LEVEL_HEADER,
2743 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2744 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2745 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2749 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2758 /*********************************************************************
2760 * Function : client_accept_encoding
2762 * Description : Rewrite the client's Accept-Encoding header so that
2763 * if doesn't allow compression, if the action applies.
2764 * Note: For HTTP/1.0 the absence of the header is enough.
2767 * 1 : csp = Current client state (buffers, headers, etc...)
2768 * 2 : header = On input, pointer to header to modify.
2769 * On output, pointer to the modified header, or NULL
2770 * to remove the header. This function frees the
2771 * original string if necessary.
2773 * Returns : JB_ERR_OK on success, or
2774 * JB_ERR_MEMORY on out-of-memory error.
2776 *********************************************************************/
2777 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2779 #ifdef FEATURE_COMPRESSION
2780 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2781 && strstr(*header, "deflate"))
2783 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2786 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2788 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2796 /*********************************************************************
2798 * Function : client_te
2800 * Description : Rewrite the client's TE header so that
2801 * if doesn't allow compression, if the action applies.
2804 * 1 : csp = Current client state (buffers, headers, etc...)
2805 * 2 : header = On input, pointer to header to modify.
2806 * On output, pointer to the modified header, or NULL
2807 * to remove the header. This function frees the
2808 * original string if necessary.
2810 * Returns : JB_ERR_OK on success, or
2811 * JB_ERR_MEMORY on out-of-memory error.
2813 *********************************************************************/
2814 static jb_err client_te(struct client_state *csp, char **header)
2816 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2819 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2826 /*********************************************************************
2828 * Function : client_referrer
2830 * Description : Handle the "referer" config setting properly.
2831 * Called from `sed'.
2834 * 1 : csp = Current client state (buffers, headers, etc...)
2835 * 2 : header = On input, pointer to header to modify.
2836 * On output, pointer to the modified header, or NULL
2837 * to remove the header. This function frees the
2838 * original string if necessary.
2840 * Returns : JB_ERR_OK on success, or
2841 * JB_ERR_MEMORY on out-of-memory error.
2843 *********************************************************************/
2844 static jb_err client_referrer(struct client_state *csp, char **header)
2846 const char *parameter;
2847 /* booleans for parameters we have to check multiple times */
2848 int parameter_conditional_block;
2849 int parameter_conditional_forge;
2851 #ifdef FEATURE_FORCE_LOAD
2853 * Since the referrer can include the prefix even
2854 * if the request itself is non-forced, we must
2855 * clean it unconditionally.
2857 * XXX: strclean is too broad
2859 strclean(*header, FORCE_PREFIX);
2860 #endif /* def FEATURE_FORCE_LOAD */
2862 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2864 /* Nothing left to do */
2868 parameter = csp->action->string[ACTION_STRING_REFERER];
2869 assert(parameter != NULL);
2870 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2871 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2873 if (!parameter_conditional_block && !parameter_conditional_forge)
2876 * As conditional-block and conditional-forge are the only
2877 * parameters that rely on the original referrer, we can
2878 * remove it now for all the others.
2883 if (0 == strcmpic(parameter, "block"))
2885 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2888 else if (parameter_conditional_block || parameter_conditional_forge)
2890 return handle_conditional_hide_referrer_parameter(header,
2891 csp->http->hostport, parameter_conditional_block);
2893 else if (0 == strcmpic(parameter, "forge"))
2895 return create_forged_referrer(header, csp->http->hostport);
2899 /* interpret parameter as user-supplied referer to fake */
2900 return create_fake_referrer(header, parameter);
2905 /*********************************************************************
2907 * Function : client_accept_language
2909 * Description : Handle the "Accept-Language" config setting properly.
2910 * Called from `sed'.
2913 * 1 : csp = Current client state (buffers, headers, etc...)
2914 * 2 : header = On input, pointer to header to modify.
2915 * On output, pointer to the modified header, or NULL
2916 * to remove the header. This function frees the
2917 * original string if necessary.
2919 * Returns : JB_ERR_OK on success, or
2920 * JB_ERR_MEMORY on out-of-memory error.
2922 *********************************************************************/
2923 static jb_err client_accept_language(struct client_state *csp, char **header)
2928 * Are we messing with the Accept-Language?
2930 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2932 /*I don't think so*/
2936 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2938 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2941 * Blocking Accept-Language header
2943 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2950 * Replacing Accept-Language header
2953 *header = strdup("Accept-Language: ");
2954 string_append(header, newval);
2956 if (*header == NULL)
2958 log_error(LOG_LEVEL_ERROR,
2959 "Insufficient memory. Accept-Language header crunched without replacement.");
2963 log_error(LOG_LEVEL_HEADER,
2964 "Accept-Language header crunched and replaced with: %s", *header);
2967 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2971 /*********************************************************************
2973 * Function : crunch_client_header
2975 * Description : Crunch client header if it matches a string supplied by the
2976 * user. Called from `sed'.
2979 * 1 : csp = Current client state (buffers, headers, etc...)
2980 * 2 : header = On input, pointer to header to modify.
2981 * On output, pointer to the modified header, or NULL
2982 * to remove the header. This function frees the
2983 * original string if necessary.
2985 * Returns : JB_ERR_OK on success and always succeeds
2987 *********************************************************************/
2988 static jb_err crunch_client_header(struct client_state *csp, char **header)
2990 const char *crunch_pattern;
2992 /* Do we feel like crunching? */
2993 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2995 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2997 /* Is the current header the lucky one? */
2998 if (strstr(*header, crunch_pattern))
3000 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3008 /*********************************************************************
3010 * Function : client_uagent
3012 * Description : Handle the "user-agent" config setting properly
3013 * and remember its original value to enable browser
3014 * bug workarounds. Called from `sed'.
3017 * 1 : csp = Current client state (buffers, headers, etc...)
3018 * 2 : header = On input, pointer to header to modify.
3019 * On output, pointer to the modified header, or NULL
3020 * to remove the header. This function frees the
3021 * original string if necessary.
3023 * Returns : JB_ERR_OK on success, or
3024 * JB_ERR_MEMORY on out-of-memory error.
3026 *********************************************************************/
3027 static jb_err client_uagent(struct client_state *csp, char **header)
3031 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3036 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3043 *header = strdup("User-Agent: ");
3044 string_append(header, newval);
3046 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3048 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3052 /*********************************************************************
3054 * Function : client_ua
3056 * Description : Handle "ua-" headers properly. Called from `sed'.
3059 * 1 : csp = Current client state (buffers, headers, etc...)
3060 * 2 : header = On input, pointer to header to modify.
3061 * On output, pointer to the modified header, or NULL
3062 * to remove the header. This function frees the
3063 * original string if necessary.
3065 * Returns : JB_ERR_OK on success, or
3066 * JB_ERR_MEMORY on out-of-memory error.
3068 *********************************************************************/
3069 static jb_err client_ua(struct client_state *csp, char **header)
3071 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3073 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3081 /*********************************************************************
3083 * Function : client_from
3085 * Description : Handle the "from" config setting properly.
3086 * Called from `sed'.
3089 * 1 : csp = Current client state (buffers, headers, etc...)
3090 * 2 : header = On input, pointer to header to modify.
3091 * On output, pointer to the modified header, or NULL
3092 * to remove the header. This function frees the
3093 * original string if necessary.
3095 * Returns : JB_ERR_OK on success, or
3096 * JB_ERR_MEMORY on out-of-memory error.
3098 *********************************************************************/
3099 static jb_err client_from(struct client_state *csp, char **header)
3103 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3110 newval = csp->action->string[ACTION_STRING_FROM];
3113 * Are we blocking the e-mail address?
3115 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3117 log_error(LOG_LEVEL_HEADER, "crunched From!");
3121 log_error(LOG_LEVEL_HEADER, " modified");
3123 *header = strdup("From: ");
3124 string_append(header, newval);
3126 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3130 /*********************************************************************
3132 * Function : client_send_cookie
3134 * Description : Crunches the "cookie" header if necessary.
3135 * Called from `sed'.
3137 * XXX: Stupid name, doesn't send squat.
3140 * 1 : csp = Current client state (buffers, headers, etc...)
3141 * 2 : header = On input, pointer to header to modify.
3142 * On output, pointer to the modified header, or NULL
3143 * to remove the header. This function frees the
3144 * original string if necessary.
3146 * Returns : JB_ERR_OK on success, or
3147 * JB_ERR_MEMORY on out-of-memory error.
3149 *********************************************************************/
3150 static jb_err client_send_cookie(struct client_state *csp, char **header)
3152 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3154 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3162 /*********************************************************************
3164 * Function : client_x_forwarded
3166 * Description : Handle the "x-forwarded-for" config setting properly,
3167 * also used in the add_client_headers list. Called from `sed'.
3170 * 1 : csp = Current client state (buffers, headers, etc...)
3171 * 2 : header = On input, pointer to header to modify.
3172 * On output, pointer to the modified header, or NULL
3173 * to remove the header. This function frees the
3174 * original string if necessary.
3176 * Returns : JB_ERR_OK on success, or
3177 * JB_ERR_MEMORY on out-of-memory error.
3179 *********************************************************************/
3180 jb_err client_x_forwarded(struct client_state *csp, char **header)
3182 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3184 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3186 if (0 == strcmpic(parameter, "block"))
3189 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3191 else if (0 == strcmpic(parameter, "add"))
3193 string_append(header, ", ");
3194 string_append(header, csp->ip_addr_str);
3196 if (*header == NULL)
3198 return JB_ERR_MEMORY;
3200 log_error(LOG_LEVEL_HEADER,
3201 "Appended client IP address to %s", *header);
3202 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3206 log_error(LOG_LEVEL_FATAL,
3207 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3215 /*********************************************************************
3217 * Function : client_max_forwards
3219 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3220 * from the value of the Max-Forwards header field.
3223 * 1 : csp = Current client state (buffers, headers, etc...)
3224 * 2 : header = On input, pointer to header to modify.
3225 * On output, pointer to the modified header, or NULL
3226 * to remove the header. This function frees the
3227 * original string if necessary.
3229 * Returns : JB_ERR_OK on success, or
3230 * JB_ERR_MEMORY on out-of-memory error.
3232 *********************************************************************/
3233 static jb_err client_max_forwards(struct client_state *csp, char **header)
3237 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3238 (0 == strcmpic(csp->http->gpc, "options")))
3240 assert(*(*header+12) == ':');
3241 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3243 if (max_forwards > 0)
3245 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3246 log_error(LOG_LEVEL_HEADER,
3247 "Max-Forwards value for %s request reduced to %d.",
3248 csp->http->gpc, max_forwards);
3250 else if (max_forwards < 0)
3252 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3258 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3267 /*********************************************************************
3269 * Function : client_host
3271 * Description : If the request URI did not contain host and
3272 * port information, parse and evaluate the Host
3276 * 1 : csp = Current client state (buffers, headers, etc...)
3277 * 2 : header = On input, pointer to header to modify.
3278 * On output, pointer to the modified header, or NULL
3279 * to remove the header. This function frees the
3280 * original string if necessary.
3282 * Returns : JB_ERR_OK on success, or
3283 * JB_ERR_MEMORY on out-of-memory error.
3285 *********************************************************************/
3286 static jb_err client_host(struct client_state *csp, char **header)
3290 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3291 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3294 p = strdup_or_die((*header)+6);
3296 q = strdup_or_die(p);
3298 freez(csp->http->hostport);
3299 csp->http->hostport = p;
3300 freez(csp->http->host);
3301 csp->http->host = q;
3302 q = strchr(csp->http->host, ':');
3305 /* Terminate hostname and evaluate port string */
3307 csp->http->port = atoi(q);
3311 csp->http->port = csp->http->ssl ? 443 : 80;
3314 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3315 csp->http->hostport, csp->http->host, csp->http->port);
3318 /* Signal client_host_adder() to return right away */
3319 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3325 /*********************************************************************
3327 * Function : client_if_modified_since
3329 * Description : Remove or modify the If-Modified-Since header.
3332 * 1 : csp = Current client state (buffers, headers, etc...)
3333 * 2 : header = On input, pointer to header to modify.
3334 * On output, pointer to the modified header, or NULL
3335 * to remove the header. This function frees the
3336 * original string if necessary.
3338 * Returns : JB_ERR_OK on success, or
3339 * JB_ERR_MEMORY on out-of-memory error.
3341 *********************************************************************/
3342 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3345 #ifdef HAVE_GMTIME_R
3348 struct tm *timeptr = NULL;
3353 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3356 * The client got an error message because of a temporary problem,
3357 * the problem is gone and the client now tries to revalidate our
3358 * error message on the real server. The revalidation would always
3359 * end with the transmission of the whole document and there is
3360 * no need to expose the bogus If-Modified-Since header.
3362 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3365 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3367 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3369 if ((0 == strcmpic(newval, "block")))
3371 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3374 else /* add random value */
3376 if (JB_ERR_OK != parse_time_header(*header, &tm))
3378 log_error(LOG_LEVEL_HEADER,
3379 "Couldn't parse time in %s (crunching!)", *header);
3384 long int hours, minutes, seconds;
3385 long int rtime = strtol(newval, &endptr, 0);
3386 const int negative_range = (rtime < 0);
3390 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3391 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3397 rtime = pick_from_range(rtime);
3401 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3404 tm += rtime * (negative_range ? -1 : 1);
3405 #ifdef HAVE_GMTIME_R
3406 timeptr = gmtime_r(&tm, &gmt);
3407 #elif defined(MUTEX_LOCKS_AVAILABLE)
3408 privoxy_mutex_lock(&gmtime_mutex);
3409 timeptr = gmtime(&tm);
3410 privoxy_mutex_unlock(&gmtime_mutex);
3412 timeptr = gmtime(&tm);
3414 if ((NULL == timeptr) || !strftime(newheader,
3415 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3417 log_error(LOG_LEVEL_ERROR,
3418 "Randomizing '%s' failed. Crunching the header without replacement.",
3425 *header = strdup("If-Modified-Since: ");
3426 string_append(header, newheader);
3428 if (*header == NULL)
3430 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3431 return JB_ERR_MEMORY;
3434 hours = rtime / 3600;
3435 minutes = rtime / 60 % 60;
3436 seconds = rtime % 60;
3438 log_error(LOG_LEVEL_HEADER,
3439 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3440 *header, (negative_range) ? "subtracted" : "added", hours,
3441 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3442 seconds, (seconds == 1) ? ")" : "s)");
3451 /*********************************************************************
3453 * Function : client_if_none_match
3455 * Description : Remove the If-None-Match header.
3458 * 1 : csp = Current client state (buffers, headers, etc...)
3459 * 2 : header = On input, pointer to header to modify.
3460 * On output, pointer to the modified header, or NULL
3461 * to remove the header. This function frees the
3462 * original string if necessary.
3464 * Returns : JB_ERR_OK on success, or
3465 * JB_ERR_MEMORY on out-of-memory error.
3467 *********************************************************************/
3468 static jb_err client_if_none_match(struct client_state *csp, char **header)
3470 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3472 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3480 /*********************************************************************
3482 * Function : client_x_filter
3484 * Description : Disables filtering if the client set "X-Filter: No".
3485 * Called from `sed'.
3488 * 1 : csp = Current client state (buffers, headers, etc...)
3489 * 2 : header = On input, pointer to header to modify.
3490 * On output, pointer to the modified header, or NULL
3491 * to remove the header. This function frees the
3492 * original string if necessary.
3494 * Returns : JB_ERR_OK on success
3496 *********************************************************************/
3497 jb_err client_x_filter(struct client_state *csp, char **header)
3499 if (0 == strcmpic(*header, "X-Filter: No"))
3501 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3503 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3507 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3509 log_error(LOG_LEVEL_HEADER,
3510 "force-text-mode overruled the client's request to fetch without filtering!");
3514 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3515 csp->flags |= CSP_FLAG_NO_FILTERING;
3516 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3518 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3526 /*********************************************************************
3528 * Function : client_range
3530 * Description : Removes Range, Request-Range and If-Range headers if
3531 * content filtering is enabled and the range doesn't
3534 * If the client's version of the document has been
3535 * altered by Privoxy, the server could interpret the
3536 * range differently than the client intended in which
3537 * case the user could end up with corrupted content.
3539 * If the range starts at byte 0 this isn't an issue
3540 * so the header can pass. Partial requests like this
3541 * are used to render preview images for videos without
3542 * downloading the whole video.
3544 * While HTTP doesn't require that range requests are
3545 * honoured and the client could simply abort the download
3546 * after receiving a sufficient amount of data, various
3547 * clients don't handle complete responses to range
3548 * requests gracefully and emit misleading error messages
3552 * 1 : csp = Current client state (buffers, headers, etc...)
3553 * 2 : header = On input, pointer to header to modify.
3554 * On output, pointer to the modified header, or NULL
3555 * to remove the header. This function frees the
3556 * original string if necessary.
3558 * Returns : JB_ERR_OK
3560 *********************************************************************/
3561 static jb_err client_range(struct client_state *csp, char **header)
3563 if (content_filters_enabled(csp->action)
3564 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3566 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3567 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3574 /* the following functions add headers directly to the header list */
3576 /*********************************************************************
3578 * Function : client_host_adder
3580 * Description : Adds the Host: header field if it is missing.
3581 * Called from `sed'.
3584 * 1 : csp = Current client state (buffers, headers, etc...)
3586 * Returns : JB_ERR_OK on success, or
3587 * JB_ERR_MEMORY on out-of-memory error.
3589 *********************************************************************/
3590 static jb_err client_host_adder(struct client_state *csp)
3595 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3597 /* Header already set by the client, nothing to do. */
3601 if (!csp->http->hostport || !*(csp->http->hostport))
3603 /* XXX: When does this happen and why is it OK? */
3604 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3609 * remove 'user:pass@' from 'proto://user:pass@host'
3611 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3617 p = csp->http->hostport;
3620 /* XXX: Just add it, we already made sure that it will be unique */
3621 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3622 err = enlist_unique_header(csp->headers, "Host", p);
3628 /*********************************************************************
3630 * Function : client_xtra_adder
3632 * Description : Used in the add_client_headers list. Called from `sed'.
3635 * 1 : csp = Current client state (buffers, headers, etc...)
3637 * Returns : JB_ERR_OK on success, or
3638 * JB_ERR_MEMORY on out-of-memory error.
3640 *********************************************************************/
3641 static jb_err client_xtra_adder(struct client_state *csp)
3643 struct list_entry *lst;
3646 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3647 lst ; lst = lst->next)
3649 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3650 err = enlist(csp->headers, lst->str);
3662 /*********************************************************************
3664 * Function : client_x_forwarded_for_adder
3666 * Description : Used in the add_client_headers list. Called from `sed'.
3669 * 1 : csp = Current client state (buffers, headers, etc...)
3671 * Returns : JB_ERR_OK on success, or
3672 * JB_ERR_MEMORY on out-of-memory error.
3674 *********************************************************************/
3675 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3677 char *header = NULL;
3680 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3681 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3682 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3685 * If we aren't adding X-Forwarded-For headers,
3686 * or we already appended an existing X-Forwarded-For
3687 * header, there's nothing left to do here.
3692 header = strdup("X-Forwarded-For: ");
3693 string_append(&header, csp->ip_addr_str);
3697 return JB_ERR_MEMORY;
3700 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3701 err = enlist(csp->headers, header);
3708 /*********************************************************************
3710 * Function : server_connection_adder
3712 * Description : Adds an appropriate "Connection:" header to csp->headers
3713 * unless the header was already present. Called from `sed'.
3716 * 1 : csp = Current client state (buffers, headers, etc...)
3718 * Returns : JB_ERR_OK on success, or
3719 * JB_ERR_MEMORY on out-of-memory error.
3721 *********************************************************************/
3722 static jb_err server_connection_adder(struct client_state *csp)
3724 const unsigned int flags = csp->flags;
3725 const char *response_status_line = csp->headers->first->str;
3726 static const char connection_close[] = "Connection: close";
3728 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3729 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3735 * XXX: if we downgraded the response, this check will fail.
3737 if ((csp->config->feature_flags &
3738 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3739 && (NULL != response_status_line)
3740 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3741 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3742 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3746 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3747 "without Connection header implies keep-alive.");
3748 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3752 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3754 return enlist(csp->headers, connection_close);
3758 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3759 /*********************************************************************
3761 * Function : server_proxy_connection_adder
3763 * Description : Adds a "Proxy-Connection: keep-alive" header to
3764 * csp->headers when appropriate.
3767 * 1 : csp = Current client state (buffers, headers, etc...)
3769 * Returns : JB_ERR_OK on success, or
3770 * JB_ERR_MEMORY on out-of-memory error.
3772 *********************************************************************/
3773 static jb_err server_proxy_connection_adder(struct client_state *csp)
3775 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3776 jb_err err = JB_ERR_OK;
3778 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3779 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3780 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3781 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3782 || (csp->flags & CSP_FLAG_CHUNKED)))
3784 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3785 err = enlist(csp->headers, proxy_connection_header);
3790 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3793 /*********************************************************************
3795 * Function : client_connection_header_adder
3797 * Description : Adds a proper "Connection:" header to csp->headers
3798 * unless the header was already present. Called from `sed'.
3801 * 1 : csp = Current client state (buffers, headers, etc...)
3803 * Returns : JB_ERR_OK on success, or
3804 * JB_ERR_MEMORY on out-of-memory error.
3806 *********************************************************************/
3807 static jb_err client_connection_header_adder(struct client_state *csp)
3809 static const char connection_close[] = "Connection: close";
3811 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3812 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3817 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3818 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3819 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3820 && (csp->http->ssl == 0)
3821 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3823 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3826 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3828 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3830 return enlist(csp->headers, connection_close);
3834 /*********************************************************************
3836 * Function : server_http
3838 * Description : - Save the HTTP Status into csp->http->status
3839 * - Set CT_TABOO to prevent filtering if the answer
3840 * is a partial range (HTTP status 206)
3841 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3843 * - Normalize the HTTP-version.
3846 * 1 : csp = Current client state (buffers, headers, etc...)
3847 * 2 : header = On input, pointer to header to modify.
3848 * On output, pointer to the modified header, or NULL
3849 * to remove the header. This function frees the
3850 * original string if necessary.
3852 * Returns : JB_ERR_OK on success, or
3853 * JB_ERR_PARSE on fatal parse errors.
3855 *********************************************************************/
3856 static jb_err server_http(struct client_state *csp, char **header)
3858 char *reason_phrase = NULL;
3859 char *new_response_line;
3862 unsigned int major_version;
3863 unsigned int minor_version;
3865 /* Get the reason phrase which start after the second whitespace */
3866 p = strchr(*header, ' ');
3870 reason_phrase = strchr(p, ' ');
3873 if (reason_phrase != NULL)
3879 log_error(LOG_LEVEL_ERROR,
3880 "Response line lacks reason phrase: %s", *header);
3884 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
3885 &minor_version, &(csp->http->status)))
3887 log_error(LOG_LEVEL_ERROR,
3888 "Failed to parse the response line: %s", *header);
3889 return JB_ERR_PARSE;
3892 if (csp->http->status == 206)
3894 csp->content_type = CT_TABOO;
3897 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
3900 * According to RFC 7230 2.6 intermediaries MUST send
3901 * their own HTTP-version in forwarded messages.
3903 log_error(LOG_LEVEL_ERROR,
3904 "Unsupported HTTP version. Downgrading to 1.1.");
3909 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
3911 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
3915 /* Rebuild response line. */
3916 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
3917 new_response_line = malloc_or_die(length);
3919 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
3920 major_version, minor_version, csp->http->status, reason_phrase);
3922 if (0 != strcmp(*header, new_response_line))
3924 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
3925 *header, new_response_line);
3929 *header = new_response_line;
3934 /*********************************************************************
3936 * Function : add_cooky_expiry_date
3938 * Description : Adds a cookie expiry date to a string.
3941 * 1 : cookie = On input, pointer to cookie to modify.
3942 * On output, pointer to the modified header.
3943 * The original string is freed.
3944 * 2 : lifetime = Seconds the cookie should be valid
3948 *********************************************************************/
3949 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
3952 struct tm *timeptr = NULL;
3953 time_t expiry_date = time(NULL) + lifetime;
3954 #ifdef HAVE_GMTIME_R
3957 timeptr = gmtime_r(&expiry_date, &gmt);
3958 #elif defined(MUTEX_LOCKS_AVAILABLE)
3959 privoxy_mutex_lock(&gmtime_mutex);
3960 timeptr = gmtime(&expiry_date);
3961 privoxy_mutex_unlock(&gmtime_mutex);
3963 timeptr = gmtime(&expiry_date);
3966 if (NULL == timeptr)
3968 log_error(LOG_LEVEL_FATAL,
3969 "Failed to get the time in add_cooky_expiry_date()");
3971 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
3972 if (JB_ERR_OK != string_append(cookie, tmp))
3974 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
3979 /*********************************************************************
3981 * Function : server_set_cookie
3983 * Description : Handle the server "cookie" header properly.
3984 * Crunch, accept or rewrite it to a session cookie.
3985 * Called from `sed'.
3988 * 1 : csp = Current client state (buffers, headers, etc...)
3989 * 2 : header = On input, pointer to header to modify.
3990 * On output, pointer to the modified header, or NULL
3991 * to remove the header. This function frees the
3992 * original string if necessary.
3994 * Returns : JB_ERR_OK on success, or
3995 * JB_ERR_MEMORY on out-of-memory error.
3997 *********************************************************************/
3998 static jb_err server_set_cookie(struct client_state *csp, char **header)
4000 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4002 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4005 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4006 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4010 long cookie_lifetime = 0;
4013 NO_EXPIRY_DATE_SPECIFIED,
4014 EXPIRY_DATE_ACCEPTABLE,
4015 EXPIRY_DATE_UNACCEPTABLE
4016 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4018 /* A variable to store the tag we're working on */
4021 /* Skip "Set-Cookie:" (11 characters) in header */
4022 cur_tag = *header + 11;
4024 /* skip whitespace between "Set-Cookie:" and value */
4025 while (*cur_tag && privoxy_isspace(*cur_tag))
4032 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4034 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4036 cookie_lifetime = strtol(param, NULL, 0);
4037 if (cookie_lifetime < 0)
4039 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4041 cookie_lifetime *= 60;
4044 /* Loop through each tag in the cookie */
4048 char *next_tag = strchr(cur_tag, ';');
4049 if (next_tag != NULL)
4051 /* Skip the ';' character itself */
4054 /* skip whitespace ";" and start of tag */
4055 while (*next_tag && privoxy_isspace(*next_tag))
4062 /* "Next tag" is the end of the string */
4063 next_tag = cur_tag + strlen(cur_tag);
4067 * Check the expiration date to see
4068 * if the cookie is still valid, if yes,
4069 * rewrite it to a session cookie.
4071 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4073 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4075 if ((expiration_date[0] == '"')
4076 && (expiration_date[1] != '\0'))
4079 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4080 * that the expiration date isn't supposed to be quoted,
4081 * but some servers do it anyway.
4086 /* Did we detect the date properly? */
4087 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4090 * Nope, treat it as if it was still valid.
4092 * XXX: Should we remove the whole cookie instead?
4094 log_error(LOG_LEVEL_ERROR,
4095 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4096 string_move(cur_tag, next_tag);
4097 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4102 * Yes. Check if the cookie is still valid.
4104 * If the cookie is already expired it's probably
4105 * a delete cookie and even if it isn't, the browser
4106 * will discard it anyway.
4110 * XXX: timegm() isn't available on some AmigaOS
4111 * versions and our replacement doesn't work.
4113 * Our options are to either:
4115 * - disable session-cookies-only completely if timegm
4118 * - to simply remove all expired tags, like it has
4119 * been done until Privoxy 3.0.6 and to live with
4120 * the consequence that it can cause login/logout
4121 * problems on servers that don't validate their
4122 * input properly, or
4124 * - to replace it with mktime in which
4125 * case there is a slight chance of valid cookies
4126 * passing as already expired.
4128 * This is the way it's currently done and it's not
4129 * as bad as it sounds. If the missing GMT offset is
4130 * enough to change the result of the expiration check
4131 * the cookie will be only valid for a few hours
4132 * anyway, which in many cases will be shorter
4133 * than a browser session.
4135 if (cookie_time < now)
4137 log_error(LOG_LEVEL_HEADER,
4138 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4139 /* Just in case some clown sets more then one expiration date */
4141 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4143 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4145 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4146 "Its lifetime is below the limit.", *header);
4147 /* Just in case some clown sets more then one expiration date */
4149 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4154 * Still valid, delete expiration date by copying
4155 * the rest of the string over it.
4157 string_move(cur_tag, next_tag);
4159 /* That changed the header, need to issue a log message */
4160 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4163 * Note that the next tag has now been moved to *cur_tag,
4164 * so we do not need to update the cur_tag pointer.
4172 /* Move on to next cookie tag */
4177 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4179 assert(NULL != *header);
4180 if (cookie_lifetime != 0)
4182 add_cookie_expiry_date(header, cookie_lifetime);
4183 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4185 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4187 log_error(LOG_LEVEL_HEADER,
4188 "Cookie rewritten to a temporary one: %s", *header);
4197 #ifdef FEATURE_FORCE_LOAD
4198 /*********************************************************************
4200 * Function : strclean
4202 * Description : In-Situ-Eliminate all occurrences of substring in
4206 * 1 : string = string to clean
4207 * 2 : substring = substring to eliminate
4209 * Returns : Number of eliminations
4211 *********************************************************************/
4212 int strclean(char *string, const char *substring)
4218 len = strlen(substring);
4220 while((pos = strstr(string, substring)) != NULL)
4227 while (*p++ != '\0');
4234 #endif /* def FEATURE_FORCE_LOAD */
4237 /*********************************************************************
4239 * Function : parse_header_time
4241 * Description : Parses time formats used in HTTP header strings
4242 * to get the numerical respresentation.
4245 * 1 : header_time = HTTP header time as string.
4246 * 2 : result = storage for header_time in seconds
4248 * Returns : JB_ERR_OK if the time format was recognized, or
4249 * JB_ERR_PARSE otherwise.
4251 *********************************************************************/
4252 static jb_err parse_header_time(const char *header_time, time_t *result)
4256 * Checking for two-digit years first in an
4257 * attempt to work around GNU libc's strptime()
4258 * reporting negative year values when using %Y.
4260 static const char time_formats[][22] = {
4261 /* Tue, 02-Jun-37 20:00:00 */
4262 "%a, %d-%b-%y %H:%M:%S",
4263 /* Tue, 02 Jun 2037 20:00:00 */
4264 "%a, %d %b %Y %H:%M:%S",
4265 /* Tue, 02-Jun-2037 20:00:00 */
4266 "%a, %d-%b-%Y %H:%M:%S",
4267 /* Tuesday, 02-Jun-2037 20:00:00 */
4268 "%A, %d-%b-%Y %H:%M:%S",
4269 /* Tuesday Jun 02 20:00:00 2037 */
4270 "%A %b %d %H:%M:%S %Y"
4274 for (i = 0; i < SZ(time_formats); i++)
4277 * Zero out gmt to prevent time zone offsets.
4278 * Documented to be required for GNU libc.
4280 memset(&gmt, 0, sizeof(gmt));
4282 if (NULL != strptime(header_time, time_formats[i], &gmt))
4284 /* Sanity check for GNU libc. */
4285 if (gmt.tm_year < 0)
4287 log_error(LOG_LEVEL_HEADER,
4288 "Failed to parse '%s' using '%s'. Moving on.",
4289 header_time, time_formats[i]);
4292 *result = timegm(&gmt);
4294 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4296 * Verify that parsing the date recreated from the first
4297 * parse operation gets the previous result. If it doesn't,
4298 * either strptime() or strftime() are malfunctioning.
4300 * We could string-compare the recreated date with the original
4301 * header date, but this leads to false positives as strptime()
4302 * may let %a accept all day formats while strftime() will only
4306 char recreated_date[100];
4310 tm = gmtime(result);
4311 strftime(recreated_date, sizeof(recreated_date), time_formats[i], tm);
4312 memset(&gmt, 0, sizeof(gmt));
4313 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4315 log_error(LOG_LEVEL_ERROR,
4316 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4317 recreated_date, time_formats[i], header_time);
4320 result2 = timegm(&gmt);
4321 if (*result != result2)
4323 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4324 "Format: '%s'. In: '%s', out: '%s'. %d != %d. Rejecting.",
4325 time_formats[i], header_time, recreated_date, *result, result2);
4335 return JB_ERR_PARSE;
4339 /*********************************************************************
4341 * Function : parse_time_header
4343 * Description : Parses the time in an HTTP time header to get
4344 * the numerical respresentation.
4347 * 1 : header = HTTP header with a time value
4348 * 2 : result = storage for header_time in seconds
4350 * Returns : JB_ERR_OK if the time format was recognized, or
4351 * JB_ERR_PARSE otherwise.
4353 *********************************************************************/
4354 static jb_err parse_time_header(const char *header, time_t *result)
4356 const char *header_time;
4358 header_time = strchr(header, ':');
4361 * Currently this can't happen as all callers are called
4362 * through sed() which requires a header name followed by
4365 assert(header_time != NULL);
4368 if (*header_time == ' ')
4373 return parse_header_time(header_time, result);
4378 /*********************************************************************
4380 * Function : get_destination_from_headers
4382 * Description : Parse the "Host:" header to get the request's destination.
4383 * Only needed if the client's request was forcefully
4384 * redirected into Privoxy.
4386 * Code mainly copied from client_host() which is currently
4387 * run too late for this purpose.
4390 * 1 : headers = List of headers (one of them hopefully being
4391 * the "Host:" header)
4392 * 2 : http = storage for the result (host, port and hostport).
4394 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4395 * JB_ERR_PARSE if the host header couldn't be found,
4396 * JB_ERR_OK otherwise.
4398 *********************************************************************/
4399 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4405 host = get_header_value(headers, "Host:");
4409 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4410 return JB_ERR_PARSE;
4413 p = strdup_or_die(host);
4415 q = strdup_or_die(p);
4417 freez(http->hostport);
4421 q = strchr(http->host, ':');
4424 /* Terminate hostname and evaluate port string */
4426 http->port = atoi(q);
4430 http->port = http->ssl ? 443 : 80;
4433 /* Rebuild request URL */
4435 http->url = strdup(http->ssl ? "https://" : "http://");
4436 string_append(&http->url, http->hostport);
4437 string_append(&http->url, http->path);
4438 if (http->url == NULL)
4440 return JB_ERR_MEMORY;
4443 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4451 /*********************************************************************
4453 * Function : create_forged_referrer
4455 * Description : Helper for client_referrer to forge a referer as
4456 * 'http://hostname[:port]/' to fool stupid
4457 * checks for in-site links
4460 * 1 : header = Pointer to header pointer
4461 * 2 : hostport = Host and optionally port as string
4463 * Returns : JB_ERR_OK in case of success, or
4464 * JB_ERR_MEMORY in case of memory problems.
4466 *********************************************************************/
4467 static jb_err create_forged_referrer(char **header, const char *hostport)
4469 assert(NULL == *header);
4471 *header = strdup("Referer: http://");
4472 string_append(header, hostport);
4473 string_append(header, "/");
4475 if (NULL == *header)
4477 return JB_ERR_MEMORY;
4480 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4487 /*********************************************************************
4489 * Function : create_fake_referrer
4491 * Description : Helper for client_referrer to create a fake referrer
4492 * based on a string supplied by the user.
4495 * 1 : header = Pointer to header pointer
4496 * 2 : hosthost = Referrer to fake
4498 * Returns : JB_ERR_OK in case of success, or
4499 * JB_ERR_MEMORY in case of memory problems.
4501 *********************************************************************/
4502 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4504 assert(NULL == *header);
4506 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4508 log_error(LOG_LEVEL_HEADER,
4509 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4511 *header = strdup("Referer: ");
4512 string_append(header, fake_referrer);
4514 if (NULL == *header)
4516 return JB_ERR_MEMORY;
4519 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4526 /*********************************************************************
4528 * Function : handle_conditional_hide_referrer_parameter
4530 * Description : Helper for client_referrer to crunch or forge
4531 * the referrer header if the host has changed.
4534 * 1 : header = Pointer to header pointer
4535 * 2 : host = The target host (may include the port)
4536 * 3 : parameter_conditional_block = Boolean to signal
4537 * if we're in conditional-block mode. If not set,
4538 * we're in conditional-forge mode.
4540 * Returns : JB_ERR_OK in case of success, or
4541 * JB_ERR_MEMORY in case of memory problems.
4543 *********************************************************************/
4544 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4545 const char *host, const int parameter_conditional_block)
4547 char *referer = strdup_or_die(*header);
4548 const size_t hostlength = strlen(host);
4549 const char *referer_url = NULL;
4551 /* referer begins with 'Referer: http[s]://' */
4552 if ((hostlength+17) < strlen(referer))
4555 * Shorten referer to make sure the referer is blocked
4556 * if www.example.org/www.example.com-shall-see-the-referer/
4557 * links to www.example.com/
4559 referer[hostlength+17] = '\0';
4561 referer_url = strstr(referer, "http://");
4562 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4564 /* Host has changed, Referer is invalid or a https URL. */
4565 if (parameter_conditional_block)
4567 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4574 return create_forged_referrer(header, host);
4584 /*********************************************************************
4586 * Function : create_content_length_header
4588 * Description : Creates a Content-Length header.
4591 * 1 : content_length = The content length to be used in the header.
4592 * 2 : header = Allocated space to safe the header.
4593 * 3 : buffer_length = The length of the allocated space.
4597 *********************************************************************/
4598 static void create_content_length_header(unsigned long long content_length,
4599 char *header, size_t buffer_length)
4601 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4605 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4606 /*********************************************************************
4608 * Function : get_expected_content_length
4610 * Description : Figures out the content length from a list of headers.
4613 * 1 : headers = List of headers
4615 * Returns : Number of bytes to expect
4617 *********************************************************************/
4618 unsigned long long get_expected_content_length(struct list *headers)
4620 const char *content_length_header;
4621 unsigned long long content_length = 0;
4623 content_length_header = get_header_value(headers, "Content-Length:");
4624 if (content_length_header != NULL)
4626 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4628 log_error(LOG_LEVEL_ERROR,
4629 "Failed to get the Content-Length in %s", content_length_header);
4630 /* XXX: The header will be removed later on */
4635 return content_length;