1 const char parsers_rcs[] = "$Id: parsers.c,v 1.297 2014/11/12 11:59:47 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
8 * Copyright : Written by and Copyright (C) 2001-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, "Buffer too small decompressing iob");
440 return JB_ERR_COMPRESS;
443 if (csp->content_type & CT_GZIP)
446 * Our task is slightly complicated by the facts that data
447 * compressed by gzip does not include a zlib header, and
448 * that there is no easily accessible interface in zlib to
449 * handle a gzip header. We strip off the gzip header by
450 * hand, and later inform zlib not to expect a header.
454 * Strip off the gzip header. Please see RFC 1952 for more
455 * explanation of the appropriate fields.
457 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
458 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
459 || (*cur++ != Z_DEFLATED))
461 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
462 return JB_ERR_COMPRESS;
467 if (flags & GZIP_FLAG_RESERVED_BITS)
469 /* The gzip header has reserved bits set; bail out. */
470 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
471 return JB_ERR_COMPRESS;
475 * Skip mtime (4 bytes), extra flags (1 byte)
476 * and OS type (1 byte).
480 /* Skip extra fields if necessary. */
481 if (flags & GZIP_FLAG_EXTRA_FIELDS)
484 * Skip a given number of bytes, specified
485 * as a 16-bit little-endian value.
487 * XXX: this code is untested and should probably be removed.
491 skip_bytes += *cur++ << 8;
494 * The number of bytes to skip should be positive
495 * and we'd like to stay in the buffer.
497 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
499 log_error(LOG_LEVEL_ERROR,
500 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
502 return JB_ERR_COMPRESS;
504 log_error(LOG_LEVEL_INFO,
505 "Skipping %d bytes for gzip compression. Does this sound right?",
510 /* Skip the filename if necessary. */
511 if (flags & GZIP_FLAG_FILE_NAME)
513 /* A null-terminated string is supposed to follow. */
514 while (*cur++ && (cur < csp->iob->eod));
517 /* Skip the comment if necessary. */
518 if (flags & GZIP_FLAG_COMMENT)
520 /* A null-terminated string is supposed to follow. */
521 while (*cur++ && (cur < csp->iob->eod));
524 /* Skip the CRC if necessary. */
525 if (flags & GZIP_FLAG_CHECKSUM)
530 if (cur >= csp->iob->eod)
533 * If the current position pointer reached or passed
534 * the buffer end, we were obviously tricked to skip
537 log_error(LOG_LEVEL_ERROR,
538 "Malformed gzip header detected. Aborting decompression.");
539 return JB_ERR_COMPRESS;
543 else if (csp->content_type & CT_DEFLATE)
546 * In theory (that is, according to RFC 1950), deflate-compressed
547 * data should begin with a two-byte zlib header and have an
548 * adler32 checksum at the end. It seems that in practice only
549 * the raw compressed data is sent. Note that this means that
550 * we are not RFC 1950-compliant here, but the advantage is that
551 * this actually works. :)
553 * We add a dummy null byte to tell zlib where the data ends,
554 * and later inform it not to expect a header.
556 * Fortunately, add_to_iob() has thoughtfully null-terminated
557 * the buffer; we can just increment the end pointer to include
564 log_error(LOG_LEVEL_ERROR,
565 "Unable to determine compression format for decompression");
566 return JB_ERR_COMPRESS;
569 /* Set up the fields required by zlib. */
570 zstr.next_in = (Bytef *)cur;
571 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
572 zstr.zalloc = Z_NULL;
574 zstr.opaque = Z_NULL;
577 * Passing -MAX_WBITS to inflateInit2 tells the library
578 * that there is no zlib header.
580 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
582 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
583 return JB_ERR_COMPRESS;
587 * Next, we allocate new storage for the inflated data.
588 * We don't modify the existing iob yet, so in case there
589 * is error in decompression we can recover gracefully.
591 buf = zalloc(bufsize);
594 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
595 return JB_ERR_MEMORY;
598 assert(bufsize >= skip_size);
599 memcpy(buf, csp->iob->buf, skip_size);
600 zstr.avail_out = (uInt)(bufsize - skip_size);
601 zstr.next_out = (Bytef *)buf + skip_size;
603 /* Try to decompress the whole stream in one shot. */
604 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
606 /* We need to allocate more memory for the output buffer. */
608 char *tmpbuf; /* used for realloc'ing the buffer */
609 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
611 if (0 == zstr.avail_in)
614 * If zlib wants more data then there's a problem, because
615 * the complete compressed file should have been buffered.
617 log_error(LOG_LEVEL_ERROR,
618 "Unexpected end of compressed iob. Using what we got so far.");
623 * If we reached the buffer limit and still didn't have enough
624 * memory, just give up. Due to the ceiling enforced by the next
625 * if block we could actually check for equality here, but as it
626 * can be easily mistaken for a bug we don't.
628 if (bufsize >= csp->config->buffer_limit)
630 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
631 return JB_ERR_MEMORY;
634 /* Try doubling the buffer size each time. */
637 /* Don't exceed the buffer limit. */
638 if (bufsize > csp->config->buffer_limit)
640 bufsize = csp->config->buffer_limit;
643 /* Try to allocate the new buffer. */
644 tmpbuf = realloc(buf, bufsize);
647 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
649 return JB_ERR_MEMORY;
653 char *oldnext_out = (char *)zstr.next_out;
656 * Update the fields for inflate() to use the new
657 * buffer, which may be in a location different from
660 zstr.avail_out += (uInt)(bufsize - oldbufsize);
661 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
664 * Compare with an uglier method of calculating these values
665 * that doesn't require the extra oldbufsize variable.
667 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
668 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
674 if (Z_STREAM_ERROR == inflateEnd(&zstr))
676 log_error(LOG_LEVEL_ERROR,
677 "Inconsistent stream state after decompression: %s", zstr.msg);
679 * XXX: Intentionally no return.
681 * According to zlib.h, Z_STREAM_ERROR is returned
682 * "if the stream state was inconsistent".
684 * I assume in this case inflate()'s status
685 * would also be something different than Z_STREAM_END
686 * so this check should be redundant, but lets see.
690 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
693 * We failed to decompress the stream and it's
694 * not simply because of missing data.
696 log_error(LOG_LEVEL_ERROR,
697 "Unexpected error while decompressing to the buffer (iob): %s",
699 return JB_ERR_COMPRESS;
703 * Finally, we can actually update the iob, since the
704 * decompression was successful. First, free the old
707 freez(csp->iob->buf);
709 /* Now, update the iob to use the new buffer. */
711 csp->iob->cur = csp->iob->buf + skip_size;
712 csp->iob->eod = (char *)zstr.next_out;
713 csp->iob->size = bufsize;
716 * Make sure the new uncompressed iob obeys some minimal
717 * consistency conditions.
719 if ((csp->iob->buf < csp->iob->cur)
720 && (csp->iob->cur <= csp->iob->eod)
721 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
723 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
724 if (new_size > (size_t)0)
726 log_error(LOG_LEVEL_RE_FILTER,
727 "Decompression successful. Old size: %d, new size: %d.",
732 /* zlib thinks this is OK, so lets do the same. */
733 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
738 /* It seems that zlib did something weird. */
739 log_error(LOG_LEVEL_ERROR,
740 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
741 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
742 csp->iob->eod, csp->iob->buf + csp->iob->size);
743 return JB_ERR_COMPRESS;
749 #endif /* defined(FEATURE_ZLIB) */
752 /*********************************************************************
754 * Function : normalize_lws
756 * Description : Reduces unquoted linear whitespace in headers to
757 * a single space in accordance with RFC 7230 3.2.4.
758 * This simplifies parsing and filtering later on.
761 * 1 : header = A header with linear whitespace to reduce.
765 *********************************************************************/
766 static void normalize_lws(char *header)
772 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
776 while (privoxy_isspace(*q))
780 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
786 log_error(LOG_LEVEL_HEADER,
787 "Converting tab to space in '%s'", header);
792 char *end_of_token = strstr(p+1, "\"");
794 if (NULL != end_of_token)
796 /* Don't mess with quoted text. */
801 log_error(LOG_LEVEL_HEADER,
802 "Ignoring single quote in '%s'", header);
808 p = strchr(header, ':');
809 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
812 * There's still space before the colon.
820 /*********************************************************************
822 * Function : get_header
824 * Description : This (odd) routine will parse the csp->iob
825 * to get the next complete header.
828 * 1 : iob = The I/O buffer to parse, usually csp->iob.
830 * Returns : Any one of the following:
832 * 1) a pointer to a dynamically allocated string that contains a header line
833 * 2) NULL indicating that the end of the header was reached
834 * 3) "" indicating that the end of the iob was reached before finding
835 * a complete header line.
837 *********************************************************************/
838 char *get_header(struct iob *iob)
842 header = get_header_line(iob);
844 if ((header == NULL) || (*header == '\0'))
847 * No complete header read yet, tell the client.
852 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
855 * Header spans multiple lines, append the next one.
857 char *continued_header;
859 continued_header = get_header_line(iob);
860 if ((continued_header == NULL) || (*continued_header == '\0'))
863 * No complete header read yet, return what we got.
864 * XXX: Should "unread" header instead.
866 log_error(LOG_LEVEL_INFO,
867 "Failed to read a multi-line header properly: '%s'",
872 if (JB_ERR_OK != string_join(&header, continued_header))
874 log_error(LOG_LEVEL_FATAL,
875 "Out of memory while appending multiple headers.");
879 /* XXX: remove before next stable release. */
880 log_error(LOG_LEVEL_HEADER,
881 "Merged multiple header lines to: '%s'",
886 normalize_lws(header);
893 /*********************************************************************
895 * Function : get_header_line
897 * Description : This (odd) routine will parse the csp->iob
898 * to get the next header line.
901 * 1 : iob = The I/O buffer to parse, usually csp->iob.
903 * Returns : Any one of the following:
905 * 1) a pointer to a dynamically allocated string that contains a header line
906 * 2) NULL indicating that the end of the header was reached
907 * 3) "" indicating that the end of the iob was reached before finding
908 * a complete header line.
910 *********************************************************************/
911 static char *get_header_line(struct iob *iob)
915 if ((iob->cur == NULL)
916 || ((p = strchr(iob->cur, '\n')) == NULL))
918 return(""); /* couldn't find a complete header */
923 ret = strdup(iob->cur);
926 /* FIXME No way to handle error properly */
927 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
933 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
935 /* is this a blank line (i.e. the end of the header) ? */
947 /*********************************************************************
949 * Function : get_header_value
951 * Description : Get the value of a given header from a chained list
952 * of header lines or return NULL if no such header is
953 * present in the list.
956 * 1 : header_list = pointer to list
957 * 2 : header_name = string with name of header to look for.
958 * Trailing colon required, capitalization
961 * Returns : NULL if not found, else value of header
963 *********************************************************************/
964 char *get_header_value(const struct list *header_list, const char *header_name)
966 struct list_entry *cur_entry;
972 length = strlen(header_name);
974 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
978 if (!strncmpic(cur_entry->str, header_name, length))
981 * Found: return pointer to start of value
983 ret = cur_entry->str + length;
984 while (*ret && privoxy_isspace(*ret)) ret++;
998 /*********************************************************************
1000 * Function : scan_headers
1002 * Description : Scans headers, applies tags and updates action bits.
1005 * 1 : csp = Current client state (buffers, headers, etc...)
1007 * Returns : JB_ERR_OK
1009 *********************************************************************/
1010 static jb_err scan_headers(struct client_state *csp)
1012 struct list_entry *h; /* Header */
1013 jb_err err = JB_ERR_OK;
1015 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1017 /* Header crunch()ed in previous run? -> ignore */
1018 if (h->str == NULL) continue;
1019 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1020 err = header_tagger(csp, h->str);
1027 /*********************************************************************
1029 * Function : enforce_header_order
1031 * Description : Enforces a given header order.
1034 * 1 : headers = List of headers to order.
1035 * 2 : ordered_headers = List of ordered header names.
1039 *********************************************************************/
1040 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1042 struct list_entry *sorted_header;
1043 struct list new_headers[1];
1044 struct list_entry *header;
1046 init_list(new_headers);
1048 /* The request line is always the first "header" */
1050 assert(NULL != headers->first->str);
1051 enlist(new_headers, headers->first->str);
1052 freez(headers->first->str)
1054 /* Enlist the specified headers in the given order */
1056 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1057 sorted_header = sorted_header->next)
1059 const size_t sorted_header_length = strlen(sorted_header->str);
1060 for (header = headers->first; header != NULL; header = header->next)
1062 /* Header enlisted in previous run? -> ignore */
1063 if (header->str == NULL) continue;
1065 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1066 && (header->str[sorted_header_length] == ':'))
1068 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1069 if (JB_ERR_OK != enlist(new_headers, header->str))
1071 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1078 /* Enlist the rest of the headers behind the ordered ones */
1079 for (header = headers->first; header != NULL; header = header->next)
1081 /* Header enlisted in previous run? -> ignore */
1082 if (header->str == NULL) continue;
1084 log_error(LOG_LEVEL_HEADER,
1085 "Enlisting left-over header %s", header->str);
1086 if (JB_ERR_OK != enlist(new_headers, header->str))
1088 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1093 list_remove_all(headers);
1094 list_duplicate(headers, new_headers);
1095 list_remove_all(new_headers);
1101 /*********************************************************************
1105 * Description : add, delete or modify lines in the HTTP header streams.
1106 * On entry, it receives a linked list of headers space
1107 * that was allocated dynamically (both the list nodes
1108 * and the header contents).
1110 * As a side effect it frees the space used by the original
1114 * 1 : csp = Current client state (buffers, headers, etc...)
1115 * 2 : filter_server_headers = Boolean to switch between
1116 * server and header filtering.
1118 * Returns : JB_ERR_OK in case off success, or
1119 * JB_ERR_MEMORY on some out-of-memory errors, or
1120 * JB_ERR_PARSE in case of fatal parse errors.
1122 *********************************************************************/
1123 jb_err sed(struct client_state *csp, int filter_server_headers)
1125 /* XXX: use more descriptive names. */
1126 struct list_entry *p;
1127 const struct parsers *v;
1128 const add_header_func_ptr *f;
1129 jb_err err = JB_ERR_OK;
1133 if (filter_server_headers)
1135 v = server_patterns;
1136 f = add_server_headers;
1137 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1141 v = client_patterns;
1142 f = add_client_headers;
1143 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1146 while (v->str != NULL)
1148 for (p = csp->headers->first; p != NULL; p = p->next)
1150 /* Header crunch()ed in previous run? -> ignore */
1151 if (p->str == NULL) continue;
1153 /* Does the current parser handle this header? */
1154 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1155 (v->len == CHECK_EVERY_HEADER_REMAINING))
1157 err = v->parser(csp, &(p->str));
1158 if (err != JB_ERR_OK)
1167 /* place additional headers on the csp->headers list */
1168 while ((err == JB_ERR_OK) && (*f))
1174 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1176 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1183 /*********************************************************************
1185 * Function : update_server_headers
1187 * Description : Updates server headers after the body has been modified.
1190 * 1 : csp = Current client state (buffers, headers, etc...)
1192 * Returns : JB_ERR_OK in case off success, or
1193 * JB_ERR_MEMORY on out-of-memory error.
1195 *********************************************************************/
1196 jb_err update_server_headers(struct client_state *csp)
1198 jb_err err = JB_ERR_OK;
1200 static const struct parsers server_patterns_light[] = {
1201 { "Content-Length:", 15, server_adjust_content_length },
1202 { "Transfer-Encoding:", 18, server_transfer_coding },
1204 { "Content-Encoding:", 17, server_adjust_content_encoding },
1205 #endif /* def FEATURE_ZLIB */
1209 if (strncmpic(csp->http->cmd, "HEAD", 4))
1211 const struct parsers *v;
1212 struct list_entry *p;
1214 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1216 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1218 /* Header crunch()ed in previous run? -> ignore */
1219 if (p->str == NULL) continue;
1221 /* Does the current parser handle this header? */
1222 if (strncmpic(p->str, v->str, v->len) == 0)
1224 err = v->parser(csp, (char **)&(p->str));
1230 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1231 if ((JB_ERR_OK == err)
1232 && (csp->flags & CSP_FLAG_MODIFIED)
1233 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1234 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1238 create_content_length_header(csp->content_length, header, sizeof(header));
1239 err = enlist(csp->headers, header);
1240 if (JB_ERR_OK == err)
1242 log_error(LOG_LEVEL_HEADER,
1243 "Content modified with no Content-Length header set. "
1244 "Created: %s.", header);
1245 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1248 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1250 #ifdef FEATURE_COMPRESSION
1251 if ((JB_ERR_OK == err)
1252 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1254 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1255 if (JB_ERR_OK == err)
1257 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1266 /*********************************************************************
1268 * Function : header_tagger
1270 * Description : Executes all text substitutions from applying
1271 * tag actions and saves the result as tag.
1273 * XXX: Shares enough code with filter_header() and
1274 * pcrs_filter_response() to warrant some helper functions.
1277 * 1 : csp = Current client state (buffers, headers, etc...)
1278 * 2 : header = Header that is used as tagger input
1280 * Returns : JB_ERR_OK on success and always succeeds
1282 *********************************************************************/
1283 static jb_err header_tagger(struct client_state *csp, char *header)
1285 enum filter_type wanted_filter_type;
1286 int multi_action_index;
1289 struct re_filterfile_spec *b;
1290 struct list_entry *tag_name;
1292 const size_t header_length = strlen(header);
1294 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1296 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1297 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1301 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1302 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1305 if (list_is_empty(csp->action->multi[multi_action_index])
1306 || filters_available(csp) == FALSE)
1308 /* Return early if no taggers apply or if none are available. */
1312 /* Execute all applying taggers */
1313 for (tag_name = csp->action->multi[multi_action_index]->first;
1314 NULL != tag_name; tag_name = tag_name->next)
1316 char *modified_tag = NULL;
1318 size_t size = header_length;
1321 b = get_filter(csp, tag_name->str, wanted_filter_type);
1327 joblist = b->joblist;
1329 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1331 if (NULL == joblist)
1333 log_error(LOG_LEVEL_RE_FILTER,
1334 "Tagger %s has empty joblist. Nothing to do.", b->name);
1338 /* execute their pcrs_joblist on the header. */
1339 for (job = joblist; NULL != job; job = job->next)
1341 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1345 /* Success, continue with the modified version. */
1354 /* Tagger doesn't match */
1357 /* Regex failure, log it but continue anyway. */
1358 assert(NULL != header);
1359 log_error(LOG_LEVEL_ERROR,
1360 "Problems with tagger \'%s\' and header \'%s\': %s",
1361 b->name, *header, pcrs_strerror(hits));
1363 freez(modified_tag);
1367 if (b->dynamic) pcrs_free_joblist(joblist);
1369 /* If this tagger matched */
1375 * There is no technical limitation which makes
1376 * it impossible to use empty tags, but I assume
1377 * no one would do it intentionally.
1380 log_error(LOG_LEVEL_INFO,
1381 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1385 if (!list_contains_item(csp->tags, tag))
1387 if (JB_ERR_OK != enlist(csp->tags, tag))
1389 log_error(LOG_LEVEL_ERROR,
1390 "Insufficient memory to add tag \'%s\', "
1391 "based on tagger \'%s\' and header \'%s\'",
1392 tag, b->name, *header);
1396 char *action_message;
1398 * update the action bits right away, to make
1399 * tagging based on tags set by earlier taggers
1400 * of the same kind possible.
1402 if (update_action_bits_for_tag(csp, tag))
1404 action_message = "Action bits updated accordingly.";
1408 action_message = "No action bits update necessary.";
1411 log_error(LOG_LEVEL_HEADER,
1412 "Tagger \'%s\' added tag \'%s\'. %s",
1413 b->name, tag, action_message);
1418 /* XXX: Is this log-worthy? */
1419 log_error(LOG_LEVEL_HEADER,
1420 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1430 /* here begins the family of parser functions that reformat header lines */
1432 /*********************************************************************
1434 * Function : filter_header
1436 * Description : Executes all text substitutions from all applying
1437 * +(server|client)-header-filter actions on the header.
1438 * Most of the code was copied from pcrs_filter_response,
1439 * including the rather short variable names
1442 * 1 : csp = Current client state (buffers, headers, etc...)
1443 * 2 : header = On input, pointer to header to modify.
1444 * On output, pointer to the modified header, or NULL
1445 * to remove the header. This function frees the
1446 * original string if necessary.
1448 * Returns : JB_ERR_OK on success and always succeeds
1450 *********************************************************************/
1451 static jb_err filter_header(struct client_state *csp, char **header)
1455 size_t size = strlen(*header);
1457 char *newheader = NULL;
1460 struct re_filterfile_spec *b;
1461 struct list_entry *filtername;
1463 enum filter_type wanted_filter_type;
1464 int multi_action_index;
1466 if (csp->flags & CSP_FLAG_NO_FILTERING)
1471 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1473 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1474 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1478 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1479 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1482 if (list_is_empty(csp->action->multi[multi_action_index])
1483 || filters_available(csp) == FALSE)
1485 /* Return early if no filters apply or if none are available. */
1489 /* Execute all applying header filters */
1490 for (filtername = csp->action->multi[multi_action_index]->first;
1491 filtername != NULL; filtername = filtername->next)
1493 int current_hits = 0;
1496 b = get_filter(csp, filtername->str, wanted_filter_type);
1502 joblist = b->joblist;
1504 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1506 if (NULL == joblist)
1508 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1512 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1513 *header, size, b->name);
1515 /* Apply all jobs from the joblist */
1516 for (job = joblist; NULL != job; job = job->next)
1518 matches = pcrs_execute(job, *header, size, &newheader, &size);
1521 current_hits += matches;
1522 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1524 *header = newheader;
1526 else if (0 == matches)
1528 /* Filter doesn't change header */
1534 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1535 *header, b->name, pcrs_strerror(matches));
1536 if (newheader != NULL)
1538 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1544 if (b->dynamic) pcrs_free_joblist(joblist);
1546 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1547 hits += current_hits;
1551 * Additionally checking for hits is important because if
1552 * the continue hack is triggered, server headers can
1553 * arrive empty to separate multiple heads from each other.
1555 if ((0 == size) && hits)
1557 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1565 /*********************************************************************
1567 * Function : server_connection
1569 * Description : Makes sure a proper "Connection:" header is
1570 * set and signals connection_header_adder to
1574 * 1 : csp = Current client state (buffers, headers, etc...)
1575 * 2 : header = On input, pointer to header to modify.
1576 * On output, pointer to the modified header, or NULL
1577 * to remove the header. This function frees the
1578 * original string if necessary.
1580 * Returns : JB_ERR_OK on success.
1582 *********************************************************************/
1583 static jb_err server_connection(struct client_state *csp, char **header)
1585 if (!strcmpic(*header, "Connection: keep-alive")
1586 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1587 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1591 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1592 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1594 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1597 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1599 log_error(LOG_LEVEL_HEADER,
1600 "Keeping the server header '%s' around.", *header);
1603 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1605 char *old_header = *header;
1607 *header = strdup_or_die("Connection: close");
1608 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1613 /* Signal server_connection_adder() to return early. */
1614 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1620 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1621 /*********************************************************************
1623 * Function : server_keep_alive
1625 * Description : Stores the server's keep alive timeout.
1628 * 1 : csp = Current client state (buffers, headers, etc...)
1629 * 2 : header = On input, pointer to header to modify.
1630 * On output, pointer to the modified header, or NULL
1631 * to remove the header. This function frees the
1632 * original string if necessary.
1634 * Returns : JB_ERR_OK.
1636 *********************************************************************/
1637 static jb_err server_keep_alive(struct client_state *csp, char **header)
1639 unsigned int keep_alive_timeout;
1640 const char *timeout_position = strstr(*header, "timeout=");
1642 if ((NULL == timeout_position)
1643 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1645 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1649 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1651 log_error(LOG_LEVEL_HEADER,
1652 "Reducing keep-alive timeout from %u to %u.",
1653 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1654 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1658 /* XXX: Is this log worthy? */
1659 log_error(LOG_LEVEL_HEADER,
1660 "Server keep-alive timeout is %u. Sticking with %u.",
1661 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1663 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1672 /*********************************************************************
1674 * Function : server_proxy_connection
1676 * Description : Figures out whether or not we should add a
1677 * Proxy-Connection header.
1680 * 1 : csp = Current client state (buffers, headers, etc...)
1681 * 2 : header = On input, pointer to header to modify.
1682 * On output, pointer to the modified header, or NULL
1683 * to remove the header. This function frees the
1684 * original string if necessary.
1686 * Returns : JB_ERR_OK.
1688 *********************************************************************/
1689 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1691 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1696 /*********************************************************************
1698 * Function : proxy_authentication
1700 * Description : Removes headers that are relevant for proxy
1701 * authentication unless forwarding them has
1702 * been explicitly requested.
1705 * 1 : csp = Current client state (buffers, headers, etc...)
1706 * 2 : header = On input, pointer to header to modify.
1707 * On output, pointer to the modified header, or NULL
1708 * to remove the header. This function frees the
1709 * original string if necessary.
1711 * Returns : JB_ERR_OK.
1713 *********************************************************************/
1714 static jb_err proxy_authentication(struct client_state *csp, char **header)
1716 if ((csp->config->feature_flags &
1717 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1718 log_error(LOG_LEVEL_HEADER,
1719 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1726 /*********************************************************************
1728 * Function : client_keep_alive
1730 * Description : Stores the client's keep alive timeout.
1733 * 1 : csp = Current client state (buffers, headers, etc...)
1734 * 2 : header = On input, pointer to header to modify.
1735 * On output, pointer to the modified header, or NULL
1736 * to remove the header. This function frees the
1737 * original string if necessary.
1739 * Returns : JB_ERR_OK.
1741 *********************************************************************/
1742 static jb_err client_keep_alive(struct client_state *csp, char **header)
1744 unsigned int keep_alive_timeout;
1745 char *timeout_position;
1747 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1749 log_error(LOG_LEVEL_HEADER,
1750 "keep-alive support is disabled. Crunching: %s.", *header);
1755 /* Check for parameter-less format "Keep-Alive: 100" */
1756 timeout_position = strstr(*header, ": ");
1757 if ((NULL == timeout_position)
1758 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1760 /* Assume parameter format "Keep-Alive: timeout=100" */
1761 timeout_position = strstr(*header, "timeout=");
1762 if ((NULL == timeout_position)
1763 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1765 log_error(LOG_LEVEL_HEADER,
1766 "Couldn't parse: '%s'. Using default timeout %u",
1767 *header, csp->config->keep_alive_timeout);
1774 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1776 log_error(LOG_LEVEL_HEADER,
1777 "Reducing keep-alive timeout from %u to %u.",
1778 csp->config->keep_alive_timeout, keep_alive_timeout);
1779 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1783 /* XXX: Is this log worthy? */
1784 log_error(LOG_LEVEL_HEADER,
1785 "Client keep-alive timeout is %u. Sticking with %u.",
1786 keep_alive_timeout, csp->config->keep_alive_timeout);
1794 /*********************************************************************
1796 * Function : get_content_length
1798 * Description : Gets the content length specified in a
1799 * Content-Length header.
1802 * 1 : header_value = The Content-Length header value.
1803 * 2 : length = Storage to return the value.
1805 * Returns : JB_ERR_OK on success, or
1806 * JB_ERR_PARSE if no value is recognized.
1808 *********************************************************************/
1809 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1812 assert(sizeof(unsigned long long) > 4);
1813 if (1 != sscanf(header_value, "%I64u", length))
1815 if (1 != sscanf(header_value, "%llu", length))
1818 return JB_ERR_PARSE;
1825 /*********************************************************************
1827 * Function : client_save_content_length
1829 * Description : Save the Content-Length sent by the client.
1832 * 1 : csp = Current client state (buffers, headers, etc...)
1833 * 2 : header = On input, pointer to header to modify.
1834 * On output, pointer to the modified header, or NULL
1835 * to remove the header. This function frees the
1836 * original string if necessary.
1838 * Returns : JB_ERR_OK on success, or
1839 * JB_ERR_MEMORY on out-of-memory error.
1841 *********************************************************************/
1842 static jb_err client_save_content_length(struct client_state *csp, char **header)
1844 unsigned long long content_length = 0;
1845 const char *header_value;
1847 assert(*(*header+14) == ':');
1849 header_value = *header + 15;
1850 if (JB_ERR_OK != get_content_length(header_value, &content_length))
1852 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1857 csp->expected_client_content_length = content_length;
1862 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1866 /*********************************************************************
1868 * Function : client_connection
1870 * Description : Makes sure a proper "Connection:" header is
1871 * set and signals connection_header_adder
1875 * 1 : csp = Current client state (buffers, headers, etc...)
1876 * 2 : header = On input, pointer to header to modify.
1877 * On output, pointer to the modified header, or NULL
1878 * to remove the header. This function frees the
1879 * original string if necessary.
1881 * Returns : JB_ERR_OK on success.
1883 *********************************************************************/
1884 static jb_err client_connection(struct client_state *csp, char **header)
1886 static const char connection_close[] = "Connection: close";
1888 if (!strcmpic(*header, connection_close))
1890 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1891 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1892 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1894 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1896 log_error(LOG_LEVEL_HEADER,
1897 "Removing \'%s\' to imply keep-alive.", *header);
1900 * While we imply keep-alive to the server,
1901 * we have to remember that the client didn't.
1903 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1907 char *old_header = *header;
1909 *header = strdup_or_die("Connection: keep-alive");
1910 log_error(LOG_LEVEL_HEADER,
1911 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1917 log_error(LOG_LEVEL_HEADER,
1918 "Keeping the client header '%s' around. "
1919 "The connection will not be kept alive.",
1921 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1924 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1925 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1927 log_error(LOG_LEVEL_HEADER,
1928 "Keeping the client header '%s' around. "
1929 "The server connection will be kept alive if possible.",
1931 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1932 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1936 char *old_header = *header;
1938 *header = strdup_or_die(connection_close);
1939 log_error(LOG_LEVEL_HEADER,
1940 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1944 /* Signal client_connection_header_adder() to return early. */
1945 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1951 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1952 /*********************************************************************
1954 * Function : client_proxy_connection
1956 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
1957 * appropriate and removes the Proxy-Connection
1961 * 1 : csp = Current client state (buffers, headers, etc...)
1962 * 2 : header = On input, pointer to header to modify.
1963 * On output, pointer to the modified header, or NULL
1964 * to remove the header. This function frees the
1965 * original string if necessary.
1967 * Returns : JB_ERR_OK
1969 *********************************************************************/
1970 static jb_err client_proxy_connection(struct client_state *csp, char **header)
1972 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1973 && (csp->http->ssl == 0)
1974 && (NULL == strstr(*header, "close")))
1976 log_error(LOG_LEVEL_HEADER,
1977 "The client connection can be kept alive due to: %s", *header);
1978 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1980 crumble(csp, header);
1984 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1987 /*********************************************************************
1989 * Function : client_transfer_encoding
1991 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
1992 * the request body is "chunked"
1994 * XXX: Currently not called through sed() as we
1995 * need the flag earlier on. Should be fixed.
1998 * 1 : csp = Current client state (buffers, headers, etc...)
1999 * 2 : header = On input, pointer to header to modify.
2000 * On output, pointer to the modified header, or NULL
2001 * to remove the header. This function frees the
2002 * original string if necessary.
2004 * Returns : JB_ERR_OK on success, or
2006 *********************************************************************/
2007 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2009 if (strstr(*header, "chunked"))
2011 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2012 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2019 /*********************************************************************
2021 * Function : client_expect
2023 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2024 * if the Expect header value is unsupported.
2026 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2027 * MAY and a RFC 2616 (obsolete) MUST.
2030 * 1 : csp = Current client state (buffers, headers, etc...)
2031 * 2 : header = On input, pointer to header to modify.
2032 * On output, pointer to the modified header, or NULL
2033 * to remove the header. This function frees the
2034 * original string if necessary.
2036 * Returns : JB_ERR_OK on success, or
2038 *********************************************************************/
2039 jb_err client_expect(struct client_state *csp, char **header)
2041 if (0 != strcmpic(*header, "Expect: 100-continue"))
2043 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2044 log_error(LOG_LEVEL_HEADER,
2045 "Unsupported client expectaction: %s", *header);
2053 /*********************************************************************
2055 * Function : crumble
2057 * Description : This is called if a header matches a pattern to "crunch"
2060 * 1 : csp = Current client state (buffers, headers, etc...)
2061 * 2 : header = On input, pointer to header to modify.
2062 * On output, pointer to the modified header, or NULL
2063 * to remove the header. This function frees the
2064 * original string if necessary.
2066 * Returns : JB_ERR_OK on success, or
2067 * JB_ERR_MEMORY on out-of-memory error.
2069 *********************************************************************/
2070 static jb_err crumble(struct client_state *csp, char **header)
2073 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2079 /*********************************************************************
2081 * Function : crunch_server_header
2083 * Description : Crunch server header if it matches a string supplied by the
2084 * user. Called from `sed'.
2087 * 1 : csp = Current client state (buffers, headers, etc...)
2088 * 2 : header = On input, pointer to header to modify.
2089 * On output, pointer to the modified header, or NULL
2090 * to remove the header. This function frees the
2091 * original string if necessary.
2093 * Returns : JB_ERR_OK on success and always succeeds
2095 *********************************************************************/
2096 static jb_err crunch_server_header(struct client_state *csp, char **header)
2098 const char *crunch_pattern;
2100 /* Do we feel like crunching? */
2101 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2103 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2105 /* Is the current header the lucky one? */
2106 if (strstr(*header, crunch_pattern))
2108 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2117 /*********************************************************************
2119 * Function : server_content_type
2121 * Description : Set the content-type for filterable types (text/.*,
2122 * .*xml.*, .*script.* and image/gif) unless filtering has been
2123 * forbidden (CT_TABOO) while parsing earlier headers.
2124 * NOTE: Since text/plain is commonly used by web servers
2125 * for files whose correct type is unknown, we don't
2126 * set CT_TEXT for it.
2129 * 1 : csp = Current client state (buffers, headers, etc...)
2130 * 2 : header = On input, pointer to header to modify.
2131 * On output, pointer to the modified header, or NULL
2132 * to remove the header. This function frees the
2133 * original string if necessary.
2135 * Returns : JB_ERR_OK on success, or
2136 * JB_ERR_MEMORY on out-of-memory error.
2138 *********************************************************************/
2139 static jb_err server_content_type(struct client_state *csp, char **header)
2141 /* Remove header if it isn't the first Content-Type header */
2142 if ((csp->content_type & CT_DECLARED))
2144 if (content_filters_enabled(csp->action))
2147 * Making sure the client interprets the content the same way
2148 * Privoxy did is only relevant if Privoxy modified it.
2150 * Checking for this is "hard" as it's not yet known when
2151 * this function is called, thus go shopping and and just
2152 * check if Privoxy could filter it.
2154 * The main thing is that we don't mess with the headers
2155 * unless the user signalled that it's acceptable.
2157 log_error(LOG_LEVEL_HEADER,
2158 "Multiple Content-Type headers detected. "
2159 "Removing and ignoring: %s",
2167 * Signal that the Content-Type has been set.
2169 csp->content_type |= CT_DECLARED;
2171 if (!(csp->content_type & CT_TABOO))
2174 * XXX: The assumption that text/plain is a sign of
2175 * binary data seems to be somewhat unreasonable nowadays
2176 * and should be dropped after 3.0.8 is out.
2178 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2179 || strstr(*header, "xml")
2180 || strstr(*header, "script"))
2182 csp->content_type |= CT_TEXT;
2184 else if (strstr(*header, "image/gif"))
2186 csp->content_type |= CT_GIF;
2191 * Are we messing with the content type?
2193 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2196 * Make sure the user doesn't accidentally
2197 * change the content type of binary documents.
2199 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2203 *header = strdup_or_die("Content-Type: ");
2205 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2206 if (JB_ERR_OK != err)
2208 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2209 return JB_ERR_MEMORY;
2211 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2215 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2216 "It doesn't look like a content type that should be filtered. "
2217 "Enable force-text-mode if you know what you're doing.", *header);
2225 /*********************************************************************
2227 * Function : server_transfer_coding
2229 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2230 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2231 * - Remove header if body was chunked but has been
2232 * de-chunked for filtering.
2235 * 1 : csp = Current client state (buffers, headers, etc...)
2236 * 2 : header = On input, pointer to header to modify.
2237 * On output, pointer to the modified header, or NULL
2238 * to remove the header. This function frees the
2239 * original string if necessary.
2241 * Returns : JB_ERR_OK on success, or
2242 * JB_ERR_MEMORY on out-of-memory error.
2244 *********************************************************************/
2245 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2248 * Turn off pcrs and gif filtering if body compressed
2250 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2254 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2256 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2257 csp->http->cmd, *header);
2258 #endif /* def FEATURE_ZLIB */
2259 csp->content_type = CT_TABOO;
2263 * Raise flag if body chunked
2265 if (strstr(*header, "chunked"))
2267 csp->flags |= CSP_FLAG_CHUNKED;
2270 * If the body was modified, it has been de-chunked first
2271 * and the header must be removed.
2273 * FIXME: If there is more than one transfer encoding,
2274 * only the "chunked" part should be removed here.
2276 if (csp->flags & CSP_FLAG_MODIFIED)
2278 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2287 /*********************************************************************
2289 * Function : server_content_encoding
2291 * Description : Used to check if the content is compressed, and if
2292 * FEATURE_ZLIB is disabled, filtering is disabled as
2295 * If FEATURE_ZLIB is enabled and the compression type
2296 * supported, the content is marked for decompression.
2298 * XXX: Doesn't properly deal with multiple or with
2299 * unsupported but unknown encodings.
2300 * Is case-sensitive but shouldn't be.
2303 * 1 : csp = Current client state (buffers, headers, etc...)
2304 * 2 : header = On input, pointer to header to modify.
2305 * On output, pointer to the modified header, or NULL
2306 * to remove the header. This function frees the
2307 * original string if necessary.
2309 * Returns : JB_ERR_OK on success, or
2310 * JB_ERR_MEMORY on out-of-memory error.
2312 *********************************************************************/
2313 static jb_err server_content_encoding(struct client_state *csp, char **header)
2316 if (strstr(*header, "sdch"))
2319 * Shared Dictionary Compression over HTTP isn't supported,
2320 * filtering it anyway is pretty much guaranteed to mess up
2323 csp->content_type |= CT_TABOO;
2326 * Log a warning if the user expects the content to be filtered.
2328 if (content_filters_enabled(csp->action))
2330 log_error(LOG_LEVEL_INFO,
2331 "SDCH-compressed content detected, content filtering disabled. "
2332 "Consider suppressing SDCH offers made by the client.");
2335 else if (strstr(*header, "gzip"))
2337 /* Mark for gzip decompression */
2338 csp->content_type |= CT_GZIP;
2340 else if (strstr(*header, "deflate"))
2342 /* Mark for zlib decompression */
2343 csp->content_type |= CT_DEFLATE;
2345 else if (strstr(*header, "compress"))
2348 * We can't decompress this; therefore we can't filter
2351 csp->content_type |= CT_TABOO;
2353 #else /* !defined(FEATURE_ZLIB) */
2355 * XXX: Using a black list here isn't the right approach.
2357 * In case of SDCH, building with zlib support isn't
2360 if (strstr(*header, "gzip") ||
2361 strstr(*header, "compress") ||
2362 strstr(*header, "deflate") ||
2363 strstr(*header, "sdch"))
2366 * Body is compressed, turn off pcrs and gif filtering.
2368 csp->content_type |= CT_TABOO;
2371 * Log a warning if the user expects the content to be filtered.
2373 if ((csp->rlist != NULL) &&
2374 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2376 log_error(LOG_LEVEL_INFO,
2377 "Compressed content detected, content filtering disabled. "
2378 "Consider recompiling Privoxy with zlib support or "
2379 "enable the prevent-compression action.");
2382 #endif /* defined(FEATURE_ZLIB) */
2390 /*********************************************************************
2392 * Function : server_adjust_content_encoding
2394 * Description : Remove the Content-Encoding header if the
2395 * decompression was successful and the content
2399 * 1 : csp = Current client state (buffers, headers, etc...)
2400 * 2 : header = On input, pointer to header to modify.
2401 * On output, pointer to the modified header, or NULL
2402 * to remove the header. This function frees the
2403 * original string if necessary.
2405 * Returns : JB_ERR_OK on success, or
2406 * JB_ERR_MEMORY on out-of-memory error.
2408 *********************************************************************/
2409 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2411 if ((csp->flags & CSP_FLAG_MODIFIED)
2412 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2415 * We successfully decompressed the content,
2416 * and have to clean the header now, so the
2417 * client no longer expects compressed data.
2419 * XXX: There is a difference between cleaning
2420 * and removing it completely.
2422 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2429 #endif /* defined(FEATURE_ZLIB) */
2432 /*********************************************************************
2434 * Function : server_adjust_content_length
2436 * Description : Adjust Content-Length header if we modified
2440 * 1 : csp = Current client state (buffers, headers, etc...)
2441 * 2 : header = On input, pointer to header to modify.
2442 * On output, pointer to the modified header, or NULL
2443 * to remove the header. This function frees the
2444 * original string if necessary.
2446 * Returns : JB_ERR_OK on success, or
2447 * JB_ERR_MEMORY on out-of-memory error.
2449 *********************************************************************/
2450 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2452 /* Regenerate header if the content was modified. */
2453 if (csp->flags & CSP_FLAG_MODIFIED)
2455 const size_t header_length = 50;
2457 *header = malloc(header_length);
2458 if (*header == NULL)
2460 return JB_ERR_MEMORY;
2462 create_content_length_header(csp->content_length, *header, header_length);
2463 log_error(LOG_LEVEL_HEADER,
2464 "Adjusted Content-Length to %llu", csp->content_length);
2471 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2472 /*********************************************************************
2474 * Function : server_save_content_length
2476 * Description : Save the Content-Length sent by the server.
2479 * 1 : csp = Current client state (buffers, headers, etc...)
2480 * 2 : header = On input, pointer to header to modify.
2481 * On output, pointer to the modified header, or NULL
2482 * to remove the header. This function frees the
2483 * original string if necessary.
2485 * Returns : JB_ERR_OK on success, or
2486 * JB_ERR_MEMORY on out-of-memory error.
2488 *********************************************************************/
2489 static jb_err server_save_content_length(struct client_state *csp, char **header)
2491 unsigned long long content_length = 0;
2492 const char *header_value;
2494 assert(*(*header+14) == ':');
2496 header_value = *header + 15;
2497 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2499 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2504 csp->expected_content_length = content_length;
2505 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2506 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2511 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2514 /*********************************************************************
2516 * Function : server_content_md5
2518 * Description : Crumble any Content-MD5 headers if the document was
2519 * modified. FIXME: Should we re-compute instead?
2522 * 1 : csp = Current client state (buffers, headers, etc...)
2523 * 2 : header = On input, pointer to header to modify.
2524 * On output, pointer to the modified header, or NULL
2525 * to remove the header. This function frees the
2526 * original string if necessary.
2528 * Returns : JB_ERR_OK on success, or
2529 * JB_ERR_MEMORY on out-of-memory error.
2531 *********************************************************************/
2532 static jb_err server_content_md5(struct client_state *csp, char **header)
2534 if (csp->flags & CSP_FLAG_MODIFIED)
2536 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2544 /*********************************************************************
2546 * Function : server_content_disposition
2548 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2549 * Called from `sed'.
2552 * 1 : csp = Current client state (buffers, headers, etc...)
2553 * 2 : header = On input, pointer to header to modify.
2554 * On output, pointer to the modified header, or NULL
2555 * to remove the header. This function frees the
2556 * original string if necessary.
2558 * Returns : JB_ERR_OK on success, or
2559 * JB_ERR_MEMORY on out-of-memory error.
2561 *********************************************************************/
2562 static jb_err server_content_disposition(struct client_state *csp, char **header)
2567 * Are we messing with the Content-Disposition header?
2569 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2575 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2577 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2580 * Blocking content-disposition header
2582 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2589 * Replacing Content-Disposition header
2592 *header = strdup("Content-Disposition: ");
2593 string_append(header, newval);
2595 if (*header != NULL)
2597 log_error(LOG_LEVEL_HEADER,
2598 "Content-Disposition header crunched and replaced with: %s", *header);
2601 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2605 /*********************************************************************
2607 * Function : server_last_modified
2609 * Description : Changes Last-Modified header to the actual date
2610 * to help hide-if-modified-since.
2611 * Called from `sed'.
2614 * 1 : csp = Current client state (buffers, headers, etc...)
2615 * 2 : header = On input, pointer to header to modify.
2616 * On output, pointer to the modified header, or NULL
2617 * to remove the header. This function frees the
2618 * original string if necessary.
2620 * Returns : JB_ERR_OK on success, or
2621 * JB_ERR_MEMORY on out-of-memory error.
2623 *********************************************************************/
2624 static jb_err server_last_modified(struct client_state *csp, char **header)
2627 time_t last_modified;
2631 * Are we messing with the Last-Modified header?
2633 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2639 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2641 if (0 == strcmpic(newval, "block"))
2644 * Blocking Last-Modified header. Useless but why not.
2646 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2650 else if (0 == strcmpic(newval, "reset-to-request-time"))
2653 * Setting Last-Modified Header to now.
2656 get_http_time(0, buf, sizeof(buf));
2658 *header = strdup("Last-Modified: ");
2659 string_append(header, buf);
2661 if (*header == NULL)
2663 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2667 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2670 else if (0 == strcmpic(newval, "randomize"))
2672 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2674 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2676 log_error(LOG_LEVEL_HEADER,
2677 "Couldn't parse time in %s (crunching!)", *header);
2683 struct tm *timeptr = NULL;
2685 #ifdef HAVE_GMTIME_R
2689 rtime = (long int)difftime(now, last_modified);
2692 long int days, hours, minutes, seconds;
2693 const int negative_delta = (rtime < 0);
2698 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2700 rtime = pick_from_range(rtime);
2705 last_modified += rtime;
2706 #ifdef HAVE_GMTIME_R
2707 timeptr = gmtime_r(&last_modified, &gmt);
2708 #elif defined(MUTEX_LOCKS_AVAILABLE)
2709 privoxy_mutex_lock(&gmtime_mutex);
2710 timeptr = gmtime(&last_modified);
2711 privoxy_mutex_unlock(&gmtime_mutex);
2713 timeptr = gmtime(&last_modified);
2715 if ((NULL == timeptr) || !strftime(newheader,
2716 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2718 log_error(LOG_LEVEL_ERROR,
2719 "Randomizing '%s' failed. Crunching the header without replacement.",
2726 *header = strdup("Last-Modified: ");
2727 string_append(header, newheader);
2729 if (*header == NULL)
2731 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2732 return JB_ERR_MEMORY;
2735 days = rtime / (3600 * 24);
2736 hours = rtime / 3600 % 24;
2737 minutes = rtime / 60 % 60;
2738 seconds = rtime % 60;
2740 log_error(LOG_LEVEL_HEADER,
2741 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2742 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2743 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2747 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2756 /*********************************************************************
2758 * Function : client_accept_encoding
2760 * Description : Rewrite the client's Accept-Encoding header so that
2761 * if doesn't allow compression, if the action applies.
2762 * Note: For HTTP/1.0 the absence of the header is enough.
2765 * 1 : csp = Current client state (buffers, headers, etc...)
2766 * 2 : header = On input, pointer to header to modify.
2767 * On output, pointer to the modified header, or NULL
2768 * to remove the header. This function frees the
2769 * original string if necessary.
2771 * Returns : JB_ERR_OK on success, or
2772 * JB_ERR_MEMORY on out-of-memory error.
2774 *********************************************************************/
2775 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2777 #ifdef FEATURE_COMPRESSION
2778 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2779 && strstr(*header, "deflate"))
2781 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2784 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2786 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2794 /*********************************************************************
2796 * Function : client_te
2798 * Description : Rewrite the client's TE header so that
2799 * if doesn't allow compression, if the action applies.
2802 * 1 : csp = Current client state (buffers, headers, etc...)
2803 * 2 : header = On input, pointer to header to modify.
2804 * On output, pointer to the modified header, or NULL
2805 * to remove the header. This function frees the
2806 * original string if necessary.
2808 * Returns : JB_ERR_OK on success, or
2809 * JB_ERR_MEMORY on out-of-memory error.
2811 *********************************************************************/
2812 static jb_err client_te(struct client_state *csp, char **header)
2814 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2817 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2824 /*********************************************************************
2826 * Function : client_referrer
2828 * Description : Handle the "referer" config setting properly.
2829 * Called from `sed'.
2832 * 1 : csp = Current client state (buffers, headers, etc...)
2833 * 2 : header = On input, pointer to header to modify.
2834 * On output, pointer to the modified header, or NULL
2835 * to remove the header. This function frees the
2836 * original string if necessary.
2838 * Returns : JB_ERR_OK on success, or
2839 * JB_ERR_MEMORY on out-of-memory error.
2841 *********************************************************************/
2842 static jb_err client_referrer(struct client_state *csp, char **header)
2844 const char *parameter;
2845 /* booleans for parameters we have to check multiple times */
2846 int parameter_conditional_block;
2847 int parameter_conditional_forge;
2849 #ifdef FEATURE_FORCE_LOAD
2851 * Since the referrer can include the prefix even
2852 * if the request itself is non-forced, we must
2853 * clean it unconditionally.
2855 * XXX: strclean is too broad
2857 strclean(*header, FORCE_PREFIX);
2858 #endif /* def FEATURE_FORCE_LOAD */
2860 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2862 /* Nothing left to do */
2866 parameter = csp->action->string[ACTION_STRING_REFERER];
2867 assert(parameter != NULL);
2868 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2869 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2871 if (!parameter_conditional_block && !parameter_conditional_forge)
2874 * As conditional-block and conditional-forge are the only
2875 * parameters that rely on the original referrer, we can
2876 * remove it now for all the others.
2881 if (0 == strcmpic(parameter, "block"))
2883 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2886 else if (parameter_conditional_block || parameter_conditional_forge)
2888 return handle_conditional_hide_referrer_parameter(header,
2889 csp->http->hostport, parameter_conditional_block);
2891 else if (0 == strcmpic(parameter, "forge"))
2893 return create_forged_referrer(header, csp->http->hostport);
2897 /* interpret parameter as user-supplied referer to fake */
2898 return create_fake_referrer(header, parameter);
2903 /*********************************************************************
2905 * Function : client_accept_language
2907 * Description : Handle the "Accept-Language" config setting properly.
2908 * Called from `sed'.
2911 * 1 : csp = Current client state (buffers, headers, etc...)
2912 * 2 : header = On input, pointer to header to modify.
2913 * On output, pointer to the modified header, or NULL
2914 * to remove the header. This function frees the
2915 * original string if necessary.
2917 * Returns : JB_ERR_OK on success, or
2918 * JB_ERR_MEMORY on out-of-memory error.
2920 *********************************************************************/
2921 static jb_err client_accept_language(struct client_state *csp, char **header)
2926 * Are we messing with the Accept-Language?
2928 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2930 /*I don't think so*/
2934 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2936 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2939 * Blocking Accept-Language header
2941 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2948 * Replacing Accept-Language header
2951 *header = strdup("Accept-Language: ");
2952 string_append(header, newval);
2954 if (*header == NULL)
2956 log_error(LOG_LEVEL_ERROR,
2957 "Insufficient memory. Accept-Language header crunched without replacement.");
2961 log_error(LOG_LEVEL_HEADER,
2962 "Accept-Language header crunched and replaced with: %s", *header);
2965 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2969 /*********************************************************************
2971 * Function : crunch_client_header
2973 * Description : Crunch client header if it matches a string supplied by the
2974 * user. Called from `sed'.
2977 * 1 : csp = Current client state (buffers, headers, etc...)
2978 * 2 : header = On input, pointer to header to modify.
2979 * On output, pointer to the modified header, or NULL
2980 * to remove the header. This function frees the
2981 * original string if necessary.
2983 * Returns : JB_ERR_OK on success and always succeeds
2985 *********************************************************************/
2986 static jb_err crunch_client_header(struct client_state *csp, char **header)
2988 const char *crunch_pattern;
2990 /* Do we feel like crunching? */
2991 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2993 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2995 /* Is the current header the lucky one? */
2996 if (strstr(*header, crunch_pattern))
2998 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3006 /*********************************************************************
3008 * Function : client_uagent
3010 * Description : Handle the "user-agent" config setting properly
3011 * and remember its original value to enable browser
3012 * bug workarounds. Called from `sed'.
3015 * 1 : csp = Current client state (buffers, headers, etc...)
3016 * 2 : header = On input, pointer to header to modify.
3017 * On output, pointer to the modified header, or NULL
3018 * to remove the header. This function frees the
3019 * original string if necessary.
3021 * Returns : JB_ERR_OK on success, or
3022 * JB_ERR_MEMORY on out-of-memory error.
3024 *********************************************************************/
3025 static jb_err client_uagent(struct client_state *csp, char **header)
3029 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3034 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3041 *header = strdup("User-Agent: ");
3042 string_append(header, newval);
3044 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3046 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3050 /*********************************************************************
3052 * Function : client_ua
3054 * Description : Handle "ua-" headers properly. Called from `sed'.
3057 * 1 : csp = Current client state (buffers, headers, etc...)
3058 * 2 : header = On input, pointer to header to modify.
3059 * On output, pointer to the modified header, or NULL
3060 * to remove the header. This function frees the
3061 * original string if necessary.
3063 * Returns : JB_ERR_OK on success, or
3064 * JB_ERR_MEMORY on out-of-memory error.
3066 *********************************************************************/
3067 static jb_err client_ua(struct client_state *csp, char **header)
3069 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3071 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3079 /*********************************************************************
3081 * Function : client_from
3083 * Description : Handle the "from" config setting properly.
3084 * Called from `sed'.
3087 * 1 : csp = Current client state (buffers, headers, etc...)
3088 * 2 : header = On input, pointer to header to modify.
3089 * On output, pointer to the modified header, or NULL
3090 * to remove the header. This function frees the
3091 * original string if necessary.
3093 * Returns : JB_ERR_OK on success, or
3094 * JB_ERR_MEMORY on out-of-memory error.
3096 *********************************************************************/
3097 static jb_err client_from(struct client_state *csp, char **header)
3101 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3108 newval = csp->action->string[ACTION_STRING_FROM];
3111 * Are we blocking the e-mail address?
3113 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3115 log_error(LOG_LEVEL_HEADER, "crunched From!");
3119 log_error(LOG_LEVEL_HEADER, " modified");
3121 *header = strdup("From: ");
3122 string_append(header, newval);
3124 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3128 /*********************************************************************
3130 * Function : client_send_cookie
3132 * Description : Crunches the "cookie" header if necessary.
3133 * Called from `sed'.
3135 * XXX: Stupid name, doesn't send squat.
3138 * 1 : csp = Current client state (buffers, headers, etc...)
3139 * 2 : header = On input, pointer to header to modify.
3140 * On output, pointer to the modified header, or NULL
3141 * to remove the header. This function frees the
3142 * original string if necessary.
3144 * Returns : JB_ERR_OK on success, or
3145 * JB_ERR_MEMORY on out-of-memory error.
3147 *********************************************************************/
3148 static jb_err client_send_cookie(struct client_state *csp, char **header)
3150 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3152 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3160 /*********************************************************************
3162 * Function : client_x_forwarded
3164 * Description : Handle the "x-forwarded-for" config setting properly,
3165 * also used in the add_client_headers list. Called from `sed'.
3168 * 1 : csp = Current client state (buffers, headers, etc...)
3169 * 2 : header = On input, pointer to header to modify.
3170 * On output, pointer to the modified header, or NULL
3171 * to remove the header. This function frees the
3172 * original string if necessary.
3174 * Returns : JB_ERR_OK on success, or
3175 * JB_ERR_MEMORY on out-of-memory error.
3177 *********************************************************************/
3178 jb_err client_x_forwarded(struct client_state *csp, char **header)
3180 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3182 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3184 if (0 == strcmpic(parameter, "block"))
3187 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3189 else if (0 == strcmpic(parameter, "add"))
3191 string_append(header, ", ");
3192 string_append(header, csp->ip_addr_str);
3194 if (*header == NULL)
3196 return JB_ERR_MEMORY;
3198 log_error(LOG_LEVEL_HEADER,
3199 "Appended client IP address to %s", *header);
3200 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3204 log_error(LOG_LEVEL_FATAL,
3205 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3213 /*********************************************************************
3215 * Function : client_max_forwards
3217 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3218 * from the value of the Max-Forwards header field.
3221 * 1 : csp = Current client state (buffers, headers, etc...)
3222 * 2 : header = On input, pointer to header to modify.
3223 * On output, pointer to the modified header, or NULL
3224 * to remove the header. This function frees the
3225 * original string if necessary.
3227 * Returns : JB_ERR_OK on success, or
3228 * JB_ERR_MEMORY on out-of-memory error.
3230 *********************************************************************/
3231 static jb_err client_max_forwards(struct client_state *csp, char **header)
3235 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3236 (0 == strcmpic(csp->http->gpc, "options")))
3238 assert(*(*header+12) == ':');
3239 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3241 if (max_forwards > 0)
3243 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3244 log_error(LOG_LEVEL_HEADER,
3245 "Max-Forwards value for %s request reduced to %d.",
3246 csp->http->gpc, max_forwards);
3248 else if (max_forwards < 0)
3250 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3256 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3265 /*********************************************************************
3267 * Function : client_host
3269 * Description : If the request URI did not contain host and
3270 * port information, parse and evaluate the Host
3274 * 1 : csp = Current client state (buffers, headers, etc...)
3275 * 2 : header = On input, pointer to header to modify.
3276 * On output, pointer to the modified header, or NULL
3277 * to remove the header. This function frees the
3278 * original string if necessary.
3280 * Returns : JB_ERR_OK on success, or
3281 * JB_ERR_MEMORY on out-of-memory error.
3283 *********************************************************************/
3284 static jb_err client_host(struct client_state *csp, char **header)
3288 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3289 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3292 p = strdup_or_die((*header)+6);
3294 q = strdup_or_die(p);
3296 freez(csp->http->hostport);
3297 csp->http->hostport = p;
3298 freez(csp->http->host);
3299 csp->http->host = q;
3300 q = strchr(csp->http->host, ':');
3303 /* Terminate hostname and evaluate port string */
3305 csp->http->port = atoi(q);
3309 csp->http->port = csp->http->ssl ? 443 : 80;
3312 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3313 csp->http->hostport, csp->http->host, csp->http->port);
3316 /* Signal client_host_adder() to return right away */
3317 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3323 /*********************************************************************
3325 * Function : client_if_modified_since
3327 * Description : Remove or modify the If-Modified-Since header.
3330 * 1 : csp = Current client state (buffers, headers, etc...)
3331 * 2 : header = On input, pointer to header to modify.
3332 * On output, pointer to the modified header, or NULL
3333 * to remove the header. This function frees the
3334 * original string if necessary.
3336 * Returns : JB_ERR_OK on success, or
3337 * JB_ERR_MEMORY on out-of-memory error.
3339 *********************************************************************/
3340 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3343 #ifdef HAVE_GMTIME_R
3346 struct tm *timeptr = NULL;
3351 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3354 * The client got an error message because of a temporary problem,
3355 * the problem is gone and the client now tries to revalidate our
3356 * error message on the real server. The revalidation would always
3357 * end with the transmission of the whole document and there is
3358 * no need to expose the bogus If-Modified-Since header.
3360 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3363 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3365 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3367 if ((0 == strcmpic(newval, "block")))
3369 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3372 else /* add random value */
3374 if (JB_ERR_OK != parse_time_header(*header, &tm))
3376 log_error(LOG_LEVEL_HEADER,
3377 "Couldn't parse time in %s (crunching!)", *header);
3382 long int hours, minutes, seconds;
3383 long int rtime = strtol(newval, &endptr, 0);
3384 const int negative_range = (rtime < 0);
3388 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3389 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3395 rtime = pick_from_range(rtime);
3399 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3402 tm += rtime * (negative_range ? -1 : 1);
3403 #ifdef HAVE_GMTIME_R
3404 timeptr = gmtime_r(&tm, &gmt);
3405 #elif defined(MUTEX_LOCKS_AVAILABLE)
3406 privoxy_mutex_lock(&gmtime_mutex);
3407 timeptr = gmtime(&tm);
3408 privoxy_mutex_unlock(&gmtime_mutex);
3410 timeptr = gmtime(&tm);
3412 if ((NULL == timeptr) || !strftime(newheader,
3413 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3415 log_error(LOG_LEVEL_ERROR,
3416 "Randomizing '%s' failed. Crunching the header without replacement.",
3423 *header = strdup("If-Modified-Since: ");
3424 string_append(header, newheader);
3426 if (*header == NULL)
3428 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3429 return JB_ERR_MEMORY;
3432 hours = rtime / 3600;
3433 minutes = rtime / 60 % 60;
3434 seconds = rtime % 60;
3436 log_error(LOG_LEVEL_HEADER,
3437 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3438 *header, (negative_range) ? "subtracted" : "added", hours,
3439 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3440 seconds, (seconds == 1) ? ")" : "s)");
3449 /*********************************************************************
3451 * Function : client_if_none_match
3453 * Description : Remove the If-None-Match header.
3456 * 1 : csp = Current client state (buffers, headers, etc...)
3457 * 2 : header = On input, pointer to header to modify.
3458 * On output, pointer to the modified header, or NULL
3459 * to remove the header. This function frees the
3460 * original string if necessary.
3462 * Returns : JB_ERR_OK on success, or
3463 * JB_ERR_MEMORY on out-of-memory error.
3465 *********************************************************************/
3466 static jb_err client_if_none_match(struct client_state *csp, char **header)
3468 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3470 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3478 /*********************************************************************
3480 * Function : client_x_filter
3482 * Description : Disables filtering if the client set "X-Filter: No".
3483 * Called from `sed'.
3486 * 1 : csp = Current client state (buffers, headers, etc...)
3487 * 2 : header = On input, pointer to header to modify.
3488 * On output, pointer to the modified header, or NULL
3489 * to remove the header. This function frees the
3490 * original string if necessary.
3492 * Returns : JB_ERR_OK on success
3494 *********************************************************************/
3495 jb_err client_x_filter(struct client_state *csp, char **header)
3497 if (0 == strcmpic(*header, "X-Filter: No"))
3499 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3501 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3505 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3507 log_error(LOG_LEVEL_HEADER,
3508 "force-text-mode overruled the client's request to fetch without filtering!");
3512 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3513 csp->flags |= CSP_FLAG_NO_FILTERING;
3514 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3516 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3524 /*********************************************************************
3526 * Function : client_range
3528 * Description : Removes Range, Request-Range and If-Range headers if
3529 * content filtering is enabled and the range doesn't
3532 * If the client's version of the document has been
3533 * altered by Privoxy, the server could interpret the
3534 * range differently than the client intended in which
3535 * case the user could end up with corrupted content.
3537 * If the range starts at byte 0 this isn't an issue
3538 * so the header can pass. Partial requests like this
3539 * are used to render preview images for videos without
3540 * downloading the whole video.
3542 * While HTTP doesn't require that range requests are
3543 * honoured and the client could simply abort the download
3544 * after receiving a sufficient amount of data, various
3545 * clients don't handle complete responses to range
3546 * requests gracefully and emit misleading error messages
3550 * 1 : csp = Current client state (buffers, headers, etc...)
3551 * 2 : header = On input, pointer to header to modify.
3552 * On output, pointer to the modified header, or NULL
3553 * to remove the header. This function frees the
3554 * original string if necessary.
3556 * Returns : JB_ERR_OK
3558 *********************************************************************/
3559 static jb_err client_range(struct client_state *csp, char **header)
3561 if (content_filters_enabled(csp->action)
3562 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3564 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3565 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3572 /* the following functions add headers directly to the header list */
3574 /*********************************************************************
3576 * Function : client_host_adder
3578 * Description : Adds the Host: header field if it is missing.
3579 * Called from `sed'.
3582 * 1 : csp = Current client state (buffers, headers, etc...)
3584 * Returns : JB_ERR_OK on success, or
3585 * JB_ERR_MEMORY on out-of-memory error.
3587 *********************************************************************/
3588 static jb_err client_host_adder(struct client_state *csp)
3593 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3595 /* Header already set by the client, nothing to do. */
3599 if (!csp->http->hostport || !*(csp->http->hostport))
3601 /* XXX: When does this happen and why is it OK? */
3602 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3607 * remove 'user:pass@' from 'proto://user:pass@host'
3609 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3615 p = csp->http->hostport;
3618 /* XXX: Just add it, we already made sure that it will be unique */
3619 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3620 err = enlist_unique_header(csp->headers, "Host", p);
3626 /*********************************************************************
3628 * Function : client_xtra_adder
3630 * Description : Used in the add_client_headers list. Called from `sed'.
3633 * 1 : csp = Current client state (buffers, headers, etc...)
3635 * Returns : JB_ERR_OK on success, or
3636 * JB_ERR_MEMORY on out-of-memory error.
3638 *********************************************************************/
3639 static jb_err client_xtra_adder(struct client_state *csp)
3641 struct list_entry *lst;
3644 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3645 lst ; lst = lst->next)
3647 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3648 err = enlist(csp->headers, lst->str);
3660 /*********************************************************************
3662 * Function : client_x_forwarded_for_adder
3664 * Description : Used in the add_client_headers list. Called from `sed'.
3667 * 1 : csp = Current client state (buffers, headers, etc...)
3669 * Returns : JB_ERR_OK on success, or
3670 * JB_ERR_MEMORY on out-of-memory error.
3672 *********************************************************************/
3673 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3675 char *header = NULL;
3678 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3679 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3680 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3683 * If we aren't adding X-Forwarded-For headers,
3684 * or we already appended an existing X-Forwarded-For
3685 * header, there's nothing left to do here.
3690 header = strdup("X-Forwarded-For: ");
3691 string_append(&header, csp->ip_addr_str);
3695 return JB_ERR_MEMORY;
3698 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3699 err = enlist(csp->headers, header);
3706 /*********************************************************************
3708 * Function : server_connection_adder
3710 * Description : Adds an appropriate "Connection:" header to csp->headers
3711 * unless the header was already present. Called from `sed'.
3714 * 1 : csp = Current client state (buffers, headers, etc...)
3716 * Returns : JB_ERR_OK on success, or
3717 * JB_ERR_MEMORY on out-of-memory error.
3719 *********************************************************************/
3720 static jb_err server_connection_adder(struct client_state *csp)
3722 const unsigned int flags = csp->flags;
3723 const char *response_status_line = csp->headers->first->str;
3724 static const char connection_close[] = "Connection: close";
3726 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3727 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3733 * XXX: if we downgraded the response, this check will fail.
3735 if ((csp->config->feature_flags &
3736 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3737 && (NULL != response_status_line)
3738 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3739 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3740 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3744 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3745 "without Connection header implies keep-alive.");
3746 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3750 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3752 return enlist(csp->headers, connection_close);
3756 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3757 /*********************************************************************
3759 * Function : server_proxy_connection_adder
3761 * Description : Adds a "Proxy-Connection: keep-alive" header to
3762 * csp->headers when appropriate.
3765 * 1 : csp = Current client state (buffers, headers, etc...)
3767 * Returns : JB_ERR_OK on success, or
3768 * JB_ERR_MEMORY on out-of-memory error.
3770 *********************************************************************/
3771 static jb_err server_proxy_connection_adder(struct client_state *csp)
3773 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3774 jb_err err = JB_ERR_OK;
3776 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3777 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3778 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3779 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3780 || (csp->flags & CSP_FLAG_CHUNKED)))
3782 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3783 err = enlist(csp->headers, proxy_connection_header);
3788 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3791 /*********************************************************************
3793 * Function : client_connection_header_adder
3795 * Description : Adds a proper "Connection:" header to csp->headers
3796 * unless the header was already present. Called from `sed'.
3799 * 1 : csp = Current client state (buffers, headers, etc...)
3801 * Returns : JB_ERR_OK on success, or
3802 * JB_ERR_MEMORY on out-of-memory error.
3804 *********************************************************************/
3805 static jb_err client_connection_header_adder(struct client_state *csp)
3807 static const char connection_close[] = "Connection: close";
3809 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3810 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3815 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3816 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3817 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3818 && (csp->http->ssl == 0)
3819 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3821 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3824 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3826 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3828 return enlist(csp->headers, connection_close);
3832 /*********************************************************************
3834 * Function : server_http
3836 * Description : - Save the HTTP Status into csp->http->status
3837 * - Set CT_TABOO to prevent filtering if the answer
3838 * is a partial range (HTTP status 206)
3839 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3841 * - Normalize the HTTP-version.
3844 * 1 : csp = Current client state (buffers, headers, etc...)
3845 * 2 : header = On input, pointer to header to modify.
3846 * On output, pointer to the modified header, or NULL
3847 * to remove the header. This function frees the
3848 * original string if necessary.
3850 * Returns : JB_ERR_OK on success, or
3851 * JB_ERR_PARSE on fatal parse errors.
3853 *********************************************************************/
3854 static jb_err server_http(struct client_state *csp, char **header)
3856 char *reason_phrase = NULL;
3857 char *new_response_line;
3860 unsigned int major_version;
3861 unsigned int minor_version;
3863 /* Get the reason phrase which start after the second whitespace */
3864 p = strchr(*header, ' ');
3868 reason_phrase = strchr(p, ' ');
3871 if (reason_phrase != NULL)
3877 log_error(LOG_LEVEL_ERROR,
3878 "Response line lacks reason phrase: %s", *header);
3882 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
3883 &minor_version, &(csp->http->status)))
3885 log_error(LOG_LEVEL_ERROR,
3886 "Failed to parse the response line: %s", *header);
3887 return JB_ERR_PARSE;
3890 if (csp->http->status == 206)
3892 csp->content_type = CT_TABOO;
3895 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
3898 * According to RFC 7230 2.6 intermediaries MUST send
3899 * their own HTTP-version in forwarded messages.
3901 log_error(LOG_LEVEL_ERROR,
3902 "Unsupported HTTP version. Downgrading to 1.1.");
3907 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
3909 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
3913 /* Rebuild response line. */
3914 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
3915 new_response_line = malloc_or_die(length);
3917 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
3918 major_version, minor_version, csp->http->status, reason_phrase);
3920 if (0 != strcmp(*header, new_response_line))
3922 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
3923 *header, new_response_line);
3927 *header = new_response_line;
3932 /*********************************************************************
3934 * Function : add_cooky_expiry_date
3936 * Description : Adds a cookie expiry date to a string.
3939 * 1 : cookie = On input, pointer to cookie to modify.
3940 * On output, pointer to the modified header.
3941 * The original string is freed.
3942 * 2 : lifetime = Seconds the cookie should be valid
3946 *********************************************************************/
3947 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
3950 struct tm *timeptr = NULL;
3951 time_t expiry_date = time(NULL) + lifetime;
3952 #ifdef HAVE_GMTIME_R
3955 timeptr = gmtime_r(&expiry_date, &gmt);
3956 #elif defined(MUTEX_LOCKS_AVAILABLE)
3957 privoxy_mutex_lock(&gmtime_mutex);
3958 timeptr = gmtime(&expiry_date);
3959 privoxy_mutex_unlock(&gmtime_mutex);
3961 timeptr = gmtime(&expiry_date);
3964 if (NULL == timeptr)
3966 log_error(LOG_LEVEL_FATAL,
3967 "Failed to get the time in add_cooky_expiry_date()");
3969 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
3970 if (JB_ERR_OK != string_append(cookie, tmp))
3972 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
3977 /*********************************************************************
3979 * Function : server_set_cookie
3981 * Description : Handle the server "cookie" header properly.
3982 * Crunch, accept or rewrite it to a session cookie.
3983 * Called from `sed'.
3986 * 1 : csp = Current client state (buffers, headers, etc...)
3987 * 2 : header = On input, pointer to header to modify.
3988 * On output, pointer to the modified header, or NULL
3989 * to remove the header. This function frees the
3990 * original string if necessary.
3992 * Returns : JB_ERR_OK on success, or
3993 * JB_ERR_MEMORY on out-of-memory error.
3995 *********************************************************************/
3996 static jb_err server_set_cookie(struct client_state *csp, char **header)
3998 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4000 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4003 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4004 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4008 long cookie_lifetime = 0;
4011 NO_EXPIRY_DATE_SPECIFIED,
4012 EXPIRY_DATE_ACCEPTABLE,
4013 EXPIRY_DATE_UNACCEPTABLE
4014 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4016 /* A variable to store the tag we're working on */
4019 /* Skip "Set-Cookie:" (11 characters) in header */
4020 cur_tag = *header + 11;
4022 /* skip whitespace between "Set-Cookie:" and value */
4023 while (*cur_tag && privoxy_isspace(*cur_tag))
4030 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4032 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4034 cookie_lifetime = strtol(param, NULL, 0);
4035 if (cookie_lifetime < 0)
4037 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4039 cookie_lifetime *= 60;
4042 /* Loop through each tag in the cookie */
4046 char *next_tag = strchr(cur_tag, ';');
4047 if (next_tag != NULL)
4049 /* Skip the ';' character itself */
4052 /* skip whitespace ";" and start of tag */
4053 while (*next_tag && privoxy_isspace(*next_tag))
4060 /* "Next tag" is the end of the string */
4061 next_tag = cur_tag + strlen(cur_tag);
4065 * Check the expiration date to see
4066 * if the cookie is still valid, if yes,
4067 * rewrite it to a session cookie.
4069 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4071 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4073 if ((expiration_date[0] == '"')
4074 && (expiration_date[1] != '\0'))
4077 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4078 * that the expiration date isn't supposed to be quoted,
4079 * but some servers do it anyway.
4084 /* Did we detect the date properly? */
4085 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4088 * Nope, treat it as if it was still valid.
4090 * XXX: Should we remove the whole cookie instead?
4092 log_error(LOG_LEVEL_ERROR,
4093 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4094 string_move(cur_tag, next_tag);
4095 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4100 * Yes. Check if the cookie is still valid.
4102 * If the cookie is already expired it's probably
4103 * a delete cookie and even if it isn't, the browser
4104 * will discard it anyway.
4108 * XXX: timegm() isn't available on some AmigaOS
4109 * versions and our replacement doesn't work.
4111 * Our options are to either:
4113 * - disable session-cookies-only completely if timegm
4116 * - to simply remove all expired tags, like it has
4117 * been done until Privoxy 3.0.6 and to live with
4118 * the consequence that it can cause login/logout
4119 * problems on servers that don't validate their
4120 * input properly, or
4122 * - to replace it with mktime in which
4123 * case there is a slight chance of valid cookies
4124 * passing as already expired.
4126 * This is the way it's currently done and it's not
4127 * as bad as it sounds. If the missing GMT offset is
4128 * enough to change the result of the expiration check
4129 * the cookie will be only valid for a few hours
4130 * anyway, which in many cases will be shorter
4131 * than a browser session.
4133 if (cookie_time < now)
4135 log_error(LOG_LEVEL_HEADER,
4136 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4137 /* Just in case some clown sets more then one expiration date */
4139 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4141 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4143 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4144 "Its lifetime is below the limit.", *header);
4145 /* Just in case some clown sets more then one expiration date */
4147 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4152 * Still valid, delete expiration date by copying
4153 * the rest of the string over it.
4155 string_move(cur_tag, next_tag);
4157 /* That changed the header, need to issue a log message */
4158 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4161 * Note that the next tag has now been moved to *cur_tag,
4162 * so we do not need to update the cur_tag pointer.
4170 /* Move on to next cookie tag */
4175 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4177 assert(NULL != *header);
4178 if (cookie_lifetime != 0)
4180 add_cookie_expiry_date(header, cookie_lifetime);
4181 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4183 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4185 log_error(LOG_LEVEL_HEADER,
4186 "Cookie rewritten to a temporary one: %s", *header);
4195 #ifdef FEATURE_FORCE_LOAD
4196 /*********************************************************************
4198 * Function : strclean
4200 * Description : In-Situ-Eliminate all occurrences of substring in
4204 * 1 : string = string to clean
4205 * 2 : substring = substring to eliminate
4207 * Returns : Number of eliminations
4209 *********************************************************************/
4210 int strclean(char *string, const char *substring)
4216 len = strlen(substring);
4218 while((pos = strstr(string, substring)) != NULL)
4225 while (*p++ != '\0');
4232 #endif /* def FEATURE_FORCE_LOAD */
4235 /*********************************************************************
4237 * Function : parse_header_time
4239 * Description : Parses time formats used in HTTP header strings
4240 * to get the numerical respresentation.
4243 * 1 : header_time = HTTP header time as string.
4244 * 2 : result = storage for header_time in seconds
4246 * Returns : JB_ERR_OK if the time format was recognized, or
4247 * JB_ERR_PARSE otherwise.
4249 *********************************************************************/
4250 static jb_err parse_header_time(const char *header_time, time_t *result)
4254 * Checking for two-digit years first in an
4255 * attempt to work around GNU libc's strptime()
4256 * reporting negative year values when using %Y.
4258 static const char time_formats[][22] = {
4259 /* Tue, 02-Jun-37 20:00:00 */
4260 "%a, %d-%b-%y %H:%M:%S",
4261 /* Tue, 02 Jun 2037 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 /* Tuesday, 02-Jun-2037 20:00:00 */
4266 "%A, %d-%b-%Y %H:%M:%S",
4267 /* Tuesday Jun 02 20:00:00 2037 */
4268 "%A %b %d %H:%M:%S %Y"
4272 for (i = 0; i < SZ(time_formats); i++)
4275 * Zero out gmt to prevent time zone offsets.
4276 * Documented to be required for GNU libc.
4278 memset(&gmt, 0, sizeof(gmt));
4280 if (NULL != strptime(header_time, time_formats[i], &gmt))
4282 /* Sanity check for GNU libc. */
4283 if (gmt.tm_year < 0)
4285 log_error(LOG_LEVEL_HEADER,
4286 "Failed to parse '%s' using '%s'. Moving on.",
4287 header_time, time_formats[i]);
4290 *result = timegm(&gmt);
4292 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4294 * Verify that parsing the date recreated from the first
4295 * parse operation gets the previous result. If it doesn't,
4296 * either strptime() or strftime() are malfunctioning.
4298 * We could string-compare the recreated date with the original
4299 * header date, but this leads to false positives as strptime()
4300 * may let %a accept all day formats while strftime() will only
4304 char recreated_date[100];
4308 tm = gmtime(result);
4309 strftime(recreated_date, sizeof(recreated_date), time_formats[i], tm);
4310 memset(&gmt, 0, sizeof(gmt));
4311 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4313 log_error(LOG_LEVEL_ERROR,
4314 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4315 recreated_date, time_formats[i], header_time);
4318 result2 = timegm(&gmt);
4319 if (*result != result2)
4321 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4322 "Format: '%s'. In: '%s', out: '%s'. %d != %d. Rejecting.",
4323 time_formats[i], header_time, recreated_date, *result, result2);
4333 return JB_ERR_PARSE;
4337 /*********************************************************************
4339 * Function : parse_time_header
4341 * Description : Parses the time in an HTTP time header to get
4342 * the numerical respresentation.
4345 * 1 : header = HTTP header with a time value
4346 * 2 : result = storage for header_time in seconds
4348 * Returns : JB_ERR_OK if the time format was recognized, or
4349 * JB_ERR_PARSE otherwise.
4351 *********************************************************************/
4352 static jb_err parse_time_header(const char *header, time_t *result)
4354 const char *header_time;
4356 header_time = strchr(header, ':');
4359 * Currently this can't happen as all callers are called
4360 * through sed() which requires a header name followed by
4363 assert(header_time != NULL);
4366 if (*header_time == ' ')
4371 return parse_header_time(header_time, result);
4376 /*********************************************************************
4378 * Function : get_destination_from_headers
4380 * Description : Parse the "Host:" header to get the request's destination.
4381 * Only needed if the client's request was forcefully
4382 * redirected into Privoxy.
4384 * Code mainly copied from client_host() which is currently
4385 * run too late for this purpose.
4388 * 1 : headers = List of headers (one of them hopefully being
4389 * the "Host:" header)
4390 * 2 : http = storage for the result (host, port and hostport).
4392 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4393 * JB_ERR_PARSE if the host header couldn't be found,
4394 * JB_ERR_OK otherwise.
4396 *********************************************************************/
4397 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4403 host = get_header_value(headers, "Host:");
4407 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4408 return JB_ERR_PARSE;
4411 p = strdup_or_die(host);
4413 q = strdup_or_die(p);
4415 freez(http->hostport);
4419 q = strchr(http->host, ':');
4422 /* Terminate hostname and evaluate port string */
4424 http->port = atoi(q);
4428 http->port = http->ssl ? 443 : 80;
4431 /* Rebuild request URL */
4433 http->url = strdup(http->ssl ? "https://" : "http://");
4434 string_append(&http->url, http->hostport);
4435 string_append(&http->url, http->path);
4436 if (http->url == NULL)
4438 return JB_ERR_MEMORY;
4441 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4449 /*********************************************************************
4451 * Function : create_forged_referrer
4453 * Description : Helper for client_referrer to forge a referer as
4454 * 'http://hostname[:port]/' to fool stupid
4455 * checks for in-site links
4458 * 1 : header = Pointer to header pointer
4459 * 2 : hostport = Host and optionally port as string
4461 * Returns : JB_ERR_OK in case of success, or
4462 * JB_ERR_MEMORY in case of memory problems.
4464 *********************************************************************/
4465 static jb_err create_forged_referrer(char **header, const char *hostport)
4467 assert(NULL == *header);
4469 *header = strdup("Referer: http://");
4470 string_append(header, hostport);
4471 string_append(header, "/");
4473 if (NULL == *header)
4475 return JB_ERR_MEMORY;
4478 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4485 /*********************************************************************
4487 * Function : create_fake_referrer
4489 * Description : Helper for client_referrer to create a fake referrer
4490 * based on a string supplied by the user.
4493 * 1 : header = Pointer to header pointer
4494 * 2 : hosthost = Referrer to fake
4496 * Returns : JB_ERR_OK in case of success, or
4497 * JB_ERR_MEMORY in case of memory problems.
4499 *********************************************************************/
4500 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4502 assert(NULL == *header);
4504 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4506 log_error(LOG_LEVEL_HEADER,
4507 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4509 *header = strdup("Referer: ");
4510 string_append(header, fake_referrer);
4512 if (NULL == *header)
4514 return JB_ERR_MEMORY;
4517 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4524 /*********************************************************************
4526 * Function : handle_conditional_hide_referrer_parameter
4528 * Description : Helper for client_referrer to crunch or forge
4529 * the referrer header if the host has changed.
4532 * 1 : header = Pointer to header pointer
4533 * 2 : host = The target host (may include the port)
4534 * 3 : parameter_conditional_block = Boolean to signal
4535 * if we're in conditional-block mode. If not set,
4536 * we're in conditional-forge mode.
4538 * Returns : JB_ERR_OK in case of success, or
4539 * JB_ERR_MEMORY in case of memory problems.
4541 *********************************************************************/
4542 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4543 const char *host, const int parameter_conditional_block)
4545 char *referer = strdup_or_die(*header);
4546 const size_t hostlength = strlen(host);
4547 const char *referer_url = NULL;
4549 /* referer begins with 'Referer: http[s]://' */
4550 if ((hostlength+17) < strlen(referer))
4553 * Shorten referer to make sure the referer is blocked
4554 * if www.example.org/www.example.com-shall-see-the-referer/
4555 * links to www.example.com/
4557 referer[hostlength+17] = '\0';
4559 referer_url = strstr(referer, "http://");
4560 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4562 /* Host has changed, Referer is invalid or a https URL. */
4563 if (parameter_conditional_block)
4565 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4572 return create_forged_referrer(header, host);
4582 /*********************************************************************
4584 * Function : create_content_length_header
4586 * Description : Creates a Content-Length header.
4589 * 1 : content_length = The content length to be used in the header.
4590 * 2 : header = Allocated space to safe the header.
4591 * 3 : buffer_length = The length of the allocated space.
4595 *********************************************************************/
4596 static void create_content_length_header(unsigned long long content_length,
4597 char *header, size_t buffer_length)
4599 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4603 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4604 /*********************************************************************
4606 * Function : get_expected_content_length
4608 * Description : Figures out the content length from a list of headers.
4611 * 1 : headers = List of headers
4613 * Returns : Number of bytes to expect
4615 *********************************************************************/
4616 unsigned long long get_expected_content_length(struct list *headers)
4618 const char *content_length_header;
4619 unsigned long long content_length = 0;
4621 content_length_header = get_header_value(headers, "Content-Length:");
4622 if (content_length_header != NULL)
4624 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4626 log_error(LOG_LEVEL_ERROR,
4627 "Failed to get the Content-Length in %s", content_length_header);
4628 /* XXX: The header will be removed later on */
4633 return content_length;