1 const char parsers_rcs[] = "$Id: parsers.c,v 1.293 2014/10/18 11:24:34 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);
100 static jb_err crumble (struct client_state *csp, char **header);
101 static jb_err filter_header (struct client_state *csp, char **header);
102 static jb_err client_connection (struct client_state *csp, char **header);
103 static jb_err client_referrer (struct client_state *csp, char **header);
104 static jb_err client_uagent (struct client_state *csp, char **header);
105 static jb_err client_ua (struct client_state *csp, char **header);
106 static jb_err client_from (struct client_state *csp, char **header);
107 static jb_err client_send_cookie (struct client_state *csp, char **header);
108 static jb_err client_x_forwarded (struct client_state *csp, char **header);
109 static jb_err client_accept_encoding (struct client_state *csp, char **header);
110 static jb_err client_te (struct client_state *csp, char **header);
111 static jb_err client_max_forwards (struct client_state *csp, char **header);
112 static jb_err client_host (struct client_state *csp, char **header);
113 static jb_err client_if_modified_since (struct client_state *csp, char **header);
114 static jb_err client_accept_language (struct client_state *csp, char **header);
115 static jb_err client_if_none_match (struct client_state *csp, char **header);
116 static jb_err crunch_client_header (struct client_state *csp, char **header);
117 static jb_err client_x_filter (struct client_state *csp, char **header);
118 static jb_err client_range (struct client_state *csp, char **header);
119 static jb_err client_expect (struct client_state *csp, char **header);
120 static jb_err server_set_cookie (struct client_state *csp, char **header);
121 static jb_err server_connection (struct client_state *csp, char **header);
122 static jb_err server_content_type (struct client_state *csp, char **header);
123 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
124 static jb_err server_content_md5 (struct client_state *csp, char **header);
125 static jb_err server_content_encoding (struct client_state *csp, char **header);
126 static jb_err server_transfer_coding (struct client_state *csp, char **header);
127 static jb_err server_http (struct client_state *csp, char **header);
128 static jb_err crunch_server_header (struct client_state *csp, char **header);
129 static jb_err server_last_modified (struct client_state *csp, char **header);
130 static jb_err server_content_disposition(struct client_state *csp, char **header);
132 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
135 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
136 static jb_err server_save_content_length(struct client_state *csp, char **header);
137 static jb_err server_keep_alive(struct client_state *csp, char **header);
138 static jb_err server_proxy_connection(struct client_state *csp, char **header);
139 static jb_err client_keep_alive(struct client_state *csp, char **header);
140 static jb_err client_save_content_length(struct client_state *csp, char **header);
141 static jb_err client_proxy_connection(struct client_state *csp, char **header);
142 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
144 static jb_err client_host_adder (struct client_state *csp);
145 static jb_err client_xtra_adder (struct client_state *csp);
146 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
147 static jb_err client_connection_header_adder(struct client_state *csp);
148 static jb_err server_connection_adder(struct client_state *csp);
149 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
150 static jb_err server_proxy_connection_adder(struct client_state *csp);
151 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
152 static jb_err proxy_authentication(struct client_state *csp, char **header);
154 static jb_err create_forged_referrer(char **header, const char *hostport);
155 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
156 static jb_err handle_conditional_hide_referrer_parameter(char **header,
157 const char *host, const int parameter_conditional_block);
158 static void create_content_length_header(unsigned long long content_length,
159 char *header, size_t buffer_length);
162 * List of functions to run on a list of headers.
166 /** The header prefix to match */
169 /** The length of the prefix to match */
172 /** The function to apply to this line */
173 const parser_func_ptr parser;
176 static const struct parsers client_patterns[] = {
177 { "referer:", 8, client_referrer },
178 { "user-agent:", 11, client_uagent },
179 { "ua-", 3, client_ua },
180 { "from:", 5, client_from },
181 { "cookie:", 7, client_send_cookie },
182 { "x-forwarded-for:", 16, client_x_forwarded },
183 { "Accept-Encoding:", 16, client_accept_encoding },
184 { "TE:", 3, client_te },
185 { "Host:", 5, client_host },
186 { "if-modified-since:", 18, client_if_modified_since },
187 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
188 { "Keep-Alive:", 11, client_keep_alive },
189 { "Content-Length:", 15, client_save_content_length },
190 { "Proxy-Connection:", 17, client_proxy_connection },
192 { "Keep-Alive:", 11, crumble },
193 { "Proxy-Connection:", 17, crumble },
195 { "connection:", 11, client_connection },
196 { "max-forwards:", 13, client_max_forwards },
197 { "Accept-Language:", 16, client_accept_language },
198 { "if-none-match:", 14, client_if_none_match },
199 { "Range:", 6, client_range },
200 { "Request-Range:", 14, client_range },
201 { "If-Range:", 9, client_range },
202 { "X-Filter:", 9, client_x_filter },
203 { "Proxy-Authorization:", 20, proxy_authentication },
205 { "Transfer-Encoding:", 18, client_transfer_encoding },
207 { "Expect:", 7, client_expect },
208 { "*", 0, crunch_client_header },
209 { "*", 0, filter_header },
213 static const struct parsers server_patterns[] = {
214 { "HTTP/", 5, server_http },
215 { "set-cookie:", 11, server_set_cookie },
216 { "connection:", 11, server_connection },
217 { "Content-Type:", 13, server_content_type },
218 { "Content-MD5:", 12, server_content_md5 },
219 { "Content-Encoding:", 17, server_content_encoding },
220 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
221 { "Content-Length:", 15, server_save_content_length },
222 { "Keep-Alive:", 11, server_keep_alive },
223 { "Proxy-Connection:", 17, server_proxy_connection },
225 { "Keep-Alive:", 11, crumble },
226 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
227 { "Transfer-Encoding:", 18, server_transfer_coding },
228 { "content-disposition:", 20, server_content_disposition },
229 { "Last-Modified:", 14, server_last_modified },
230 { "Proxy-Authenticate:", 19, proxy_authentication },
231 { "*", 0, crunch_server_header },
232 { "*", 0, filter_header },
236 static const add_header_func_ptr add_client_headers[] = {
238 client_x_forwarded_for_adder,
240 client_connection_header_adder,
244 static const add_header_func_ptr add_server_headers[] = {
245 server_connection_adder,
246 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
247 server_proxy_connection_adder,
248 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
252 /*********************************************************************
254 * Function : flush_socket
256 * Description : Write any pending "buffered" content.
259 * 1 : fd = file descriptor of the socket to read
260 * 2 : iob = The I/O buffer to flush, usually csp->iob.
262 * Returns : On success, the number of bytes written are returned (zero
263 * indicates nothing was written). On error, -1 is returned,
264 * and errno is set appropriately. If count is zero and the
265 * file descriptor refers to a regular file, 0 will be
266 * returned without causing any other effect. For a special
267 * file, the results are not portable.
269 *********************************************************************/
270 long flush_socket(jb_socket fd, struct iob *iob)
272 long len = iob->eod - iob->cur;
279 if (write_socket(fd, iob->cur, (size_t)len))
283 iob->eod = iob->cur = iob->buf;
289 /*********************************************************************
291 * Function : add_to_iob
293 * Description : Add content to the buffer, expanding the
294 * buffer if necessary.
297 * 1 : iob = Destination buffer.
298 * 2 : buffer_limit = Limit to which the destination may grow
299 * 3 : src = holds the content to be added
300 * 4 : n = number of bytes to be added
302 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
303 * or buffer limit reached.
305 *********************************************************************/
306 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
308 size_t used, offset, need;
311 if (n <= 0) return JB_ERR_OK;
313 used = (size_t)(iob->eod - iob->buf);
314 offset = (size_t)(iob->cur - iob->buf);
315 need = used + (size_t)n + 1;
318 * If the buffer can't hold the new data, extend it first.
319 * Use the next power of two if possible, else use the actual need.
321 if (need > buffer_limit)
323 log_error(LOG_LEVEL_INFO,
324 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
326 return JB_ERR_MEMORY;
329 if (need > iob->size)
331 size_t want = iob->size ? iob->size : 512;
338 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
342 else if (NULL != (p = (char *)realloc(iob->buf, need)))
348 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
349 return JB_ERR_MEMORY;
352 /* Update the iob pointers */
353 iob->cur = p + offset;
358 /* copy the new data into the iob buffer */
359 memcpy(iob->eod, src, (size_t)n);
361 /* point to the end of the data */
364 /* null terminate == cheap insurance */
372 /*********************************************************************
374 * Function : clear_iob
376 * Description : Frees the memory allocated for an I/O buffer and
377 * resets the structure.
380 * 1 : iob = I/O buffer to clear.
382 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
383 * or buffer limit reached.
385 *********************************************************************/
386 void clear_iob(struct iob *iob)
389 memset(iob, '\0', sizeof(*iob));;
394 /*********************************************************************
396 * Function : decompress_iob
398 * Description : Decompress buffered page, expanding the
399 * buffer as necessary. csp->iob->cur
400 * should point to the the beginning of the
401 * compressed data block.
404 * 1 : csp = Current client state (buffers, headers, etc...)
406 * Returns : JB_ERR_OK on success,
407 * JB_ERR_MEMORY if out-of-memory limit reached, and
408 * JB_ERR_COMPRESS if error decompressing buffer.
410 *********************************************************************/
411 jb_err decompress_iob(struct client_state *csp)
413 char *buf; /* new, uncompressed buffer */
414 char *cur; /* Current iob position (to keep the original
415 * iob->cur unmodified if we return early) */
416 size_t bufsize; /* allocated size of the new buffer */
417 size_t old_size; /* Content size before decompression */
418 size_t skip_size; /* Number of bytes at the beginning of the iob
419 that we should NOT decompress. */
420 int status; /* return status of the inflate() call */
421 z_stream zstr; /* used by calls to zlib */
423 assert(csp->iob->cur - csp->iob->buf > 0);
424 assert(csp->iob->eod - csp->iob->cur > 0);
426 bufsize = csp->iob->size;
427 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
428 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
432 if (bufsize < (size_t)10)
435 * This is to protect the parsing of gzipped data,
436 * but it should(?) be valid for deflated data also.
438 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
439 return JB_ERR_COMPRESS;
442 if (csp->content_type & CT_GZIP)
445 * Our task is slightly complicated by the facts that data
446 * compressed by gzip does not include a zlib header, and
447 * that there is no easily accessible interface in zlib to
448 * handle a gzip header. We strip off the gzip header by
449 * hand, and later inform zlib not to expect a header.
453 * Strip off the gzip header. Please see RFC 1952 for more
454 * explanation of the appropriate fields.
456 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
457 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
458 || (*cur++ != Z_DEFLATED))
460 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
461 return JB_ERR_COMPRESS;
466 if (flags & GZIP_FLAG_RESERVED_BITS)
468 /* The gzip header has reserved bits set; bail out. */
469 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
470 return JB_ERR_COMPRESS;
474 * Skip mtime (4 bytes), extra flags (1 byte)
475 * and OS type (1 byte).
479 /* Skip extra fields if necessary. */
480 if (flags & GZIP_FLAG_EXTRA_FIELDS)
483 * Skip a given number of bytes, specified
484 * as a 16-bit little-endian value.
486 * XXX: this code is untested and should probably be removed.
490 skip_bytes += *cur++ << 8;
493 * The number of bytes to skip should be positive
494 * and we'd like to stay in the buffer.
496 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
498 log_error(LOG_LEVEL_ERROR,
499 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
501 return JB_ERR_COMPRESS;
503 log_error(LOG_LEVEL_INFO,
504 "Skipping %d bytes for gzip compression. Does this sound right?",
509 /* Skip the filename if necessary. */
510 if (flags & GZIP_FLAG_FILE_NAME)
512 /* A null-terminated string is supposed to follow. */
513 while (*cur++ && (cur < csp->iob->eod));
516 /* Skip the comment if necessary. */
517 if (flags & GZIP_FLAG_COMMENT)
519 /* A null-terminated string is supposed to follow. */
520 while (*cur++ && (cur < csp->iob->eod));
523 /* Skip the CRC if necessary. */
524 if (flags & GZIP_FLAG_CHECKSUM)
529 if (cur >= csp->iob->eod)
532 * If the current position pointer reached or passed
533 * the buffer end, we were obviously tricked to skip
536 log_error(LOG_LEVEL_ERROR,
537 "Malformed gzip header detected. Aborting decompression.");
538 return JB_ERR_COMPRESS;
542 else if (csp->content_type & CT_DEFLATE)
545 * In theory (that is, according to RFC 1950), deflate-compressed
546 * data should begin with a two-byte zlib header and have an
547 * adler32 checksum at the end. It seems that in practice only
548 * the raw compressed data is sent. Note that this means that
549 * we are not RFC 1950-compliant here, but the advantage is that
550 * this actually works. :)
552 * We add a dummy null byte to tell zlib where the data ends,
553 * and later inform it not to expect a header.
555 * Fortunately, add_to_iob() has thoughtfully null-terminated
556 * the buffer; we can just increment the end pointer to include
563 log_error(LOG_LEVEL_ERROR,
564 "Unable to determine compression format for decompression");
565 return JB_ERR_COMPRESS;
568 /* Set up the fields required by zlib. */
569 zstr.next_in = (Bytef *)cur;
570 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
571 zstr.zalloc = Z_NULL;
573 zstr.opaque = Z_NULL;
576 * Passing -MAX_WBITS to inflateInit2 tells the library
577 * that there is no zlib header.
579 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
581 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
582 return JB_ERR_COMPRESS;
586 * Next, we allocate new storage for the inflated data.
587 * We don't modify the existing iob yet, so in case there
588 * is error in decompression we can recover gracefully.
590 buf = zalloc(bufsize);
593 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
594 return JB_ERR_MEMORY;
597 assert(bufsize >= skip_size);
598 memcpy(buf, csp->iob->buf, skip_size);
599 zstr.avail_out = (uInt)(bufsize - skip_size);
600 zstr.next_out = (Bytef *)buf + skip_size;
602 /* Try to decompress the whole stream in one shot. */
603 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
605 /* We need to allocate more memory for the output buffer. */
607 char *tmpbuf; /* used for realloc'ing the buffer */
608 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
610 if (0 == zstr.avail_in)
613 * If zlib wants more data then there's a problem, because
614 * the complete compressed file should have been buffered.
616 log_error(LOG_LEVEL_ERROR,
617 "Unexpected end of compressed iob. Using what we got so far.");
622 * If we reached the buffer limit and still didn't have enough
623 * memory, just give up. Due to the ceiling enforced by the next
624 * if block we could actually check for equality here, but as it
625 * can be easily mistaken for a bug we don't.
627 if (bufsize >= csp->config->buffer_limit)
629 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
630 return JB_ERR_MEMORY;
633 /* Try doubling the buffer size each time. */
636 /* Don't exceed the buffer limit. */
637 if (bufsize > csp->config->buffer_limit)
639 bufsize = csp->config->buffer_limit;
642 /* Try to allocate the new buffer. */
643 tmpbuf = realloc(buf, bufsize);
646 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
648 return JB_ERR_MEMORY;
652 char *oldnext_out = (char *)zstr.next_out;
655 * Update the fields for inflate() to use the new
656 * buffer, which may be in a location different from
659 zstr.avail_out += (uInt)(bufsize - oldbufsize);
660 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
663 * Compare with an uglier method of calculating these values
664 * that doesn't require the extra oldbufsize variable.
666 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
667 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
673 if (Z_STREAM_ERROR == inflateEnd(&zstr))
675 log_error(LOG_LEVEL_ERROR,
676 "Inconsistent stream state after decompression: %s", zstr.msg);
678 * XXX: Intentionally no return.
680 * According to zlib.h, Z_STREAM_ERROR is returned
681 * "if the stream state was inconsistent".
683 * I assume in this case inflate()'s status
684 * would also be something different than Z_STREAM_END
685 * so this check should be redundant, but lets see.
689 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
692 * We failed to decompress the stream and it's
693 * not simply because of missing data.
695 log_error(LOG_LEVEL_ERROR,
696 "Unexpected error while decompressing to the buffer (iob): %s",
698 return JB_ERR_COMPRESS;
702 * Finally, we can actually update the iob, since the
703 * decompression was successful. First, free the old
706 freez(csp->iob->buf);
708 /* Now, update the iob to use the new buffer. */
710 csp->iob->cur = csp->iob->buf + skip_size;
711 csp->iob->eod = (char *)zstr.next_out;
712 csp->iob->size = bufsize;
715 * Make sure the new uncompressed iob obeys some minimal
716 * consistency conditions.
718 if ((csp->iob->buf < csp->iob->cur)
719 && (csp->iob->cur <= csp->iob->eod)
720 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
722 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
723 if (new_size > (size_t)0)
725 log_error(LOG_LEVEL_RE_FILTER,
726 "Decompression successful. Old size: %d, new size: %d.",
731 /* zlib thinks this is OK, so lets do the same. */
732 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
737 /* It seems that zlib did something weird. */
738 log_error(LOG_LEVEL_ERROR,
739 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
740 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
741 csp->iob->eod, csp->iob->buf + csp->iob->size);
742 return JB_ERR_COMPRESS;
748 #endif /* defined(FEATURE_ZLIB) */
751 /*********************************************************************
753 * Function : normalize_lws
755 * Description : Reduces unquoted linear whitespace in headers to
756 * a single space in accordance with RFC 7230 3.2.4.
757 * This simplifies parsing and filtering later on.
760 * 1 : header = A header with linear whitespace to reduce.
764 *********************************************************************/
765 static void normalize_lws(char *header)
771 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
775 while (privoxy_isspace(*q))
779 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
785 log_error(LOG_LEVEL_HEADER,
786 "Converting tab to space in '%s'", header);
791 char *end_of_token = strstr(p+1, "\"");
793 if (NULL != end_of_token)
795 /* Don't mess with quoted text. */
800 log_error(LOG_LEVEL_HEADER,
801 "Ignoring single quote in '%s'", header);
807 p = strchr(header, ':');
808 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
811 * There's still space before the colon.
819 /*********************************************************************
821 * Function : get_header
823 * Description : This (odd) routine will parse the csp->iob
824 * to get the next complete header.
827 * 1 : iob = The I/O buffer to parse, usually csp->iob.
829 * Returns : Any one of the following:
831 * 1) a pointer to a dynamically allocated string that contains a header line
832 * 2) NULL indicating that the end of the header was reached
833 * 3) "" indicating that the end of the iob was reached before finding
834 * a complete header line.
836 *********************************************************************/
837 char *get_header(struct iob *iob)
841 header = get_header_line(iob);
843 if ((header == NULL) || (*header == '\0'))
846 * No complete header read yet, tell the client.
851 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
854 * Header spans multiple lines, append the next one.
856 char *continued_header;
858 continued_header = get_header_line(iob);
859 if ((continued_header == NULL) || (*continued_header == '\0'))
862 * No complete header read yet, return what we got.
863 * XXX: Should "unread" header instead.
865 log_error(LOG_LEVEL_INFO,
866 "Failed to read a multi-line header properly: '%s'",
871 if (JB_ERR_OK != string_join(&header, continued_header))
873 log_error(LOG_LEVEL_FATAL,
874 "Out of memory while appending multiple headers.");
878 /* XXX: remove before next stable release. */
879 log_error(LOG_LEVEL_HEADER,
880 "Merged multiple header lines to: '%s'",
885 normalize_lws(header);
892 /*********************************************************************
894 * Function : get_header_line
896 * Description : This (odd) routine will parse the csp->iob
897 * to get the next header line.
900 * 1 : iob = The I/O buffer to parse, usually csp->iob.
902 * Returns : Any one of the following:
904 * 1) a pointer to a dynamically allocated string that contains a header line
905 * 2) NULL indicating that the end of the header was reached
906 * 3) "" indicating that the end of the iob was reached before finding
907 * a complete header line.
909 *********************************************************************/
910 static char *get_header_line(struct iob *iob)
914 if ((iob->cur == NULL)
915 || ((p = strchr(iob->cur, '\n')) == NULL))
917 return(""); /* couldn't find a complete header */
922 ret = strdup(iob->cur);
925 /* FIXME No way to handle error properly */
926 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
932 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
934 /* is this a blank line (i.e. the end of the header) ? */
946 /*********************************************************************
948 * Function : get_header_value
950 * Description : Get the value of a given header from a chained list
951 * of header lines or return NULL if no such header is
952 * present in the list.
955 * 1 : header_list = pointer to list
956 * 2 : header_name = string with name of header to look for.
957 * Trailing colon required, capitalization
960 * Returns : NULL if not found, else value of header
962 *********************************************************************/
963 char *get_header_value(const struct list *header_list, const char *header_name)
965 struct list_entry *cur_entry;
971 length = strlen(header_name);
973 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
977 if (!strncmpic(cur_entry->str, header_name, length))
980 * Found: return pointer to start of value
982 ret = cur_entry->str + length;
983 while (*ret && privoxy_isspace(*ret)) ret++;
997 /*********************************************************************
999 * Function : scan_headers
1001 * Description : Scans headers, applies tags and updates action bits.
1004 * 1 : csp = Current client state (buffers, headers, etc...)
1006 * Returns : JB_ERR_OK
1008 *********************************************************************/
1009 static jb_err scan_headers(struct client_state *csp)
1011 struct list_entry *h; /* Header */
1012 jb_err err = JB_ERR_OK;
1014 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1016 /* Header crunch()ed in previous run? -> ignore */
1017 if (h->str == NULL) continue;
1018 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1019 err = header_tagger(csp, h->str);
1026 /*********************************************************************
1028 * Function : enforce_header_order
1030 * Description : Enforces a given header order.
1033 * 1 : headers = List of headers to order.
1034 * 2 : ordered_headers = List of ordered header names.
1038 *********************************************************************/
1039 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1041 struct list_entry *sorted_header;
1042 struct list new_headers[1];
1043 struct list_entry *header;
1045 init_list(new_headers);
1047 /* The request line is always the first "header" */
1049 assert(NULL != headers->first->str);
1050 enlist(new_headers, headers->first->str);
1051 freez(headers->first->str)
1053 /* Enlist the specified headers in the given order */
1055 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1056 sorted_header = sorted_header->next)
1058 const size_t sorted_header_length = strlen(sorted_header->str);
1059 for (header = headers->first; header != NULL; header = header->next)
1061 /* Header enlisted in previous run? -> ignore */
1062 if (header->str == NULL) continue;
1064 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1065 && (header->str[sorted_header_length] == ':'))
1067 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1068 if (JB_ERR_OK != enlist(new_headers, header->str))
1070 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1077 /* Enlist the rest of the headers behind the ordered ones */
1078 for (header = headers->first; header != NULL; header = header->next)
1080 /* Header enlisted in previous run? -> ignore */
1081 if (header->str == NULL) continue;
1083 log_error(LOG_LEVEL_HEADER,
1084 "Enlisting left-over header %s", header->str);
1085 if (JB_ERR_OK != enlist(new_headers, header->str))
1087 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1092 list_remove_all(headers);
1093 list_duplicate(headers, new_headers);
1094 list_remove_all(new_headers);
1100 /*********************************************************************
1104 * Description : add, delete or modify lines in the HTTP header streams.
1105 * On entry, it receives a linked list of headers space
1106 * that was allocated dynamically (both the list nodes
1107 * and the header contents).
1109 * As a side effect it frees the space used by the original
1113 * 1 : csp = Current client state (buffers, headers, etc...)
1114 * 2 : filter_server_headers = Boolean to switch between
1115 * server and header filtering.
1117 * Returns : JB_ERR_OK in case off success, or
1118 * JB_ERR_MEMORY on some out-of-memory errors, or
1119 * JB_ERR_PARSE in case of fatal parse errors.
1121 *********************************************************************/
1122 jb_err sed(struct client_state *csp, int filter_server_headers)
1124 /* XXX: use more descriptive names. */
1125 struct list_entry *p;
1126 const struct parsers *v;
1127 const add_header_func_ptr *f;
1128 jb_err err = JB_ERR_OK;
1132 if (filter_server_headers)
1134 v = server_patterns;
1135 f = add_server_headers;
1136 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1140 v = client_patterns;
1141 f = add_client_headers;
1142 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1145 while (v->str != NULL)
1147 for (p = csp->headers->first; p != NULL; p = p->next)
1149 /* Header crunch()ed in previous run? -> ignore */
1150 if (p->str == NULL) continue;
1152 /* Does the current parser handle this header? */
1153 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1154 (v->len == CHECK_EVERY_HEADER_REMAINING))
1156 err = v->parser(csp, &(p->str));
1157 if (err != JB_ERR_OK)
1166 /* place additional headers on the csp->headers list */
1167 while ((err == JB_ERR_OK) && (*f))
1173 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1175 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1182 /*********************************************************************
1184 * Function : update_server_headers
1186 * Description : Updates server headers after the body has been modified.
1189 * 1 : csp = Current client state (buffers, headers, etc...)
1191 * Returns : JB_ERR_OK in case off success, or
1192 * JB_ERR_MEMORY on out-of-memory error.
1194 *********************************************************************/
1195 jb_err update_server_headers(struct client_state *csp)
1197 jb_err err = JB_ERR_OK;
1199 static const struct parsers server_patterns_light[] = {
1200 { "Content-Length:", 15, server_adjust_content_length },
1201 { "Transfer-Encoding:", 18, server_transfer_coding },
1203 { "Content-Encoding:", 17, server_adjust_content_encoding },
1204 #endif /* def FEATURE_ZLIB */
1208 if (strncmpic(csp->http->cmd, "HEAD", 4))
1210 const struct parsers *v;
1211 struct list_entry *p;
1213 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1215 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1217 /* Header crunch()ed in previous run? -> ignore */
1218 if (p->str == NULL) continue;
1220 /* Does the current parser handle this header? */
1221 if (strncmpic(p->str, v->str, v->len) == 0)
1223 err = v->parser(csp, (char **)&(p->str));
1229 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1230 if ((JB_ERR_OK == err)
1231 && (csp->flags & CSP_FLAG_MODIFIED)
1232 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1233 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1237 create_content_length_header(csp->content_length, header, sizeof(header));
1238 err = enlist(csp->headers, header);
1239 if (JB_ERR_OK == err)
1241 log_error(LOG_LEVEL_HEADER,
1242 "Content modified with no Content-Length header set. "
1243 "Created: %s.", header);
1244 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1247 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1249 #ifdef FEATURE_COMPRESSION
1250 if ((JB_ERR_OK == err)
1251 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1253 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1254 if (JB_ERR_OK == err)
1256 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1265 /*********************************************************************
1267 * Function : header_tagger
1269 * Description : Executes all text substitutions from applying
1270 * tag actions and saves the result as tag.
1272 * XXX: Shares enough code with filter_header() and
1273 * pcrs_filter_response() to warrant some helper functions.
1276 * 1 : csp = Current client state (buffers, headers, etc...)
1277 * 2 : header = Header that is used as tagger input
1279 * Returns : JB_ERR_OK on success and always succeeds
1281 *********************************************************************/
1282 static jb_err header_tagger(struct client_state *csp, char *header)
1284 enum filter_type wanted_filter_type;
1285 int multi_action_index;
1288 struct re_filterfile_spec *b;
1289 struct list_entry *tag_name;
1291 const size_t header_length = strlen(header);
1293 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1295 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1296 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1300 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1301 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1304 if (list_is_empty(csp->action->multi[multi_action_index])
1305 || filters_available(csp) == FALSE)
1307 /* Return early if no taggers apply or if none are available. */
1311 /* Execute all applying taggers */
1312 for (tag_name = csp->action->multi[multi_action_index]->first;
1313 NULL != tag_name; tag_name = tag_name->next)
1315 char *modified_tag = NULL;
1317 size_t size = header_length;
1320 b = get_filter(csp, tag_name->str, wanted_filter_type);
1326 joblist = b->joblist;
1328 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1330 if (NULL == joblist)
1332 log_error(LOG_LEVEL_RE_FILTER,
1333 "Tagger %s has empty joblist. Nothing to do.", b->name);
1337 /* execute their pcrs_joblist on the header. */
1338 for (job = joblist; NULL != job; job = job->next)
1340 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1344 /* Success, continue with the modified version. */
1353 /* Tagger doesn't match */
1356 /* Regex failure, log it but continue anyway. */
1357 assert(NULL != header);
1358 log_error(LOG_LEVEL_ERROR,
1359 "Problems with tagger \'%s\' and header \'%s\': %s",
1360 b->name, *header, pcrs_strerror(hits));
1362 freez(modified_tag);
1366 if (b->dynamic) pcrs_free_joblist(joblist);
1368 /* If this tagger matched */
1374 * There is no technical limitation which makes
1375 * it impossible to use empty tags, but I assume
1376 * no one would do it intentionally.
1379 log_error(LOG_LEVEL_INFO,
1380 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1384 if (!list_contains_item(csp->tags, tag))
1386 if (JB_ERR_OK != enlist(csp->tags, tag))
1388 log_error(LOG_LEVEL_ERROR,
1389 "Insufficient memory to add tag \'%s\', "
1390 "based on tagger \'%s\' and header \'%s\'",
1391 tag, b->name, *header);
1395 char *action_message;
1397 * update the action bits right away, to make
1398 * tagging based on tags set by earlier taggers
1399 * of the same kind possible.
1401 if (update_action_bits_for_tag(csp, tag))
1403 action_message = "Action bits updated accordingly.";
1407 action_message = "No action bits update necessary.";
1410 log_error(LOG_LEVEL_HEADER,
1411 "Tagger \'%s\' added tag \'%s\'. %s",
1412 b->name, tag, action_message);
1417 /* XXX: Is this log-worthy? */
1418 log_error(LOG_LEVEL_HEADER,
1419 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1429 /* here begins the family of parser functions that reformat header lines */
1431 /*********************************************************************
1433 * Function : filter_header
1435 * Description : Executes all text substitutions from all applying
1436 * +(server|client)-header-filter actions on the header.
1437 * Most of the code was copied from pcrs_filter_response,
1438 * including the rather short variable names
1441 * 1 : csp = Current client state (buffers, headers, etc...)
1442 * 2 : header = On input, pointer to header to modify.
1443 * On output, pointer to the modified header, or NULL
1444 * to remove the header. This function frees the
1445 * original string if necessary.
1447 * Returns : JB_ERR_OK on success and always succeeds
1449 *********************************************************************/
1450 static jb_err filter_header(struct client_state *csp, char **header)
1454 size_t size = strlen(*header);
1456 char *newheader = NULL;
1459 struct re_filterfile_spec *b;
1460 struct list_entry *filtername;
1462 enum filter_type wanted_filter_type;
1463 int multi_action_index;
1465 if (csp->flags & CSP_FLAG_NO_FILTERING)
1470 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1472 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1473 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1477 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1478 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1481 if (list_is_empty(csp->action->multi[multi_action_index])
1482 || filters_available(csp) == FALSE)
1484 /* Return early if no filters apply or if none are available. */
1488 /* Execute all applying header filters */
1489 for (filtername = csp->action->multi[multi_action_index]->first;
1490 filtername != NULL; filtername = filtername->next)
1492 int current_hits = 0;
1495 b = get_filter(csp, filtername->str, wanted_filter_type);
1501 joblist = b->joblist;
1503 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1505 if (NULL == joblist)
1507 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1511 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1512 *header, size, b->name);
1514 /* Apply all jobs from the joblist */
1515 for (job = joblist; NULL != job; job = job->next)
1517 matches = pcrs_execute(job, *header, size, &newheader, &size);
1520 current_hits += matches;
1521 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1523 *header = newheader;
1525 else if (0 == matches)
1527 /* Filter doesn't change header */
1533 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1534 *header, b->name, pcrs_strerror(matches));
1535 if (newheader != NULL)
1537 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1543 if (b->dynamic) pcrs_free_joblist(joblist);
1545 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1546 hits += current_hits;
1550 * Additionally checking for hits is important because if
1551 * the continue hack is triggered, server headers can
1552 * arrive empty to separate multiple heads from each other.
1554 if ((0 == size) && hits)
1556 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1564 /*********************************************************************
1566 * Function : server_connection
1568 * Description : Makes sure a proper "Connection:" header is
1569 * set and signals connection_header_adder to
1573 * 1 : csp = Current client state (buffers, headers, etc...)
1574 * 2 : header = On input, pointer to header to modify.
1575 * On output, pointer to the modified header, or NULL
1576 * to remove the header. This function frees the
1577 * original string if necessary.
1579 * Returns : JB_ERR_OK on success.
1581 *********************************************************************/
1582 static jb_err server_connection(struct client_state *csp, char **header)
1584 if (!strcmpic(*header, "Connection: keep-alive")
1585 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1586 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1590 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1591 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1593 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1596 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1598 log_error(LOG_LEVEL_HEADER,
1599 "Keeping the server header '%s' around.", *header);
1602 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1604 char *old_header = *header;
1606 *header = strdup_or_die("Connection: close");
1607 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1612 /* Signal server_connection_adder() to return early. */
1613 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1619 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1620 /*********************************************************************
1622 * Function : server_keep_alive
1624 * Description : Stores the server's keep alive timeout.
1627 * 1 : csp = Current client state (buffers, headers, etc...)
1628 * 2 : header = On input, pointer to header to modify.
1629 * On output, pointer to the modified header, or NULL
1630 * to remove the header. This function frees the
1631 * original string if necessary.
1633 * Returns : JB_ERR_OK.
1635 *********************************************************************/
1636 static jb_err server_keep_alive(struct client_state *csp, char **header)
1638 unsigned int keep_alive_timeout;
1639 const char *timeout_position = strstr(*header, "timeout=");
1641 if ((NULL == timeout_position)
1642 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1644 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1648 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1650 log_error(LOG_LEVEL_HEADER,
1651 "Reducing keep-alive timeout from %u to %u.",
1652 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1653 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1657 /* XXX: Is this log worthy? */
1658 log_error(LOG_LEVEL_HEADER,
1659 "Server keep-alive timeout is %u. Sticking with %u.",
1660 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1662 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1669 /*********************************************************************
1671 * Function : server_proxy_connection
1673 * Description : Figures out whether or not we should add a
1674 * Proxy-Connection header.
1677 * 1 : csp = Current client state (buffers, headers, etc...)
1678 * 2 : header = On input, pointer to header to modify.
1679 * On output, pointer to the modified header, or NULL
1680 * to remove the header. This function frees the
1681 * original string if necessary.
1683 * Returns : JB_ERR_OK.
1685 *********************************************************************/
1686 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1688 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1693 /*********************************************************************
1695 * Function : proxy_authentication
1697 * Description : Removes headers that are relevant for proxy
1698 * authentication unless forwarding them has
1699 * been explicitly requested.
1702 * 1 : csp = Current client state (buffers, headers, etc...)
1703 * 2 : header = On input, pointer to header to modify.
1704 * On output, pointer to the modified header, or NULL
1705 * to remove the header. This function frees the
1706 * original string if necessary.
1708 * Returns : JB_ERR_OK.
1710 *********************************************************************/
1711 static jb_err proxy_authentication(struct client_state *csp, char **header)
1713 if ((csp->config->feature_flags &
1714 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1715 log_error(LOG_LEVEL_HEADER,
1716 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1723 /*********************************************************************
1725 * Function : client_keep_alive
1727 * Description : Stores the client's keep alive timeout.
1730 * 1 : csp = Current client state (buffers, headers, etc...)
1731 * 2 : header = On input, pointer to header to modify.
1732 * On output, pointer to the modified header, or NULL
1733 * to remove the header. This function frees the
1734 * original string if necessary.
1736 * Returns : JB_ERR_OK.
1738 *********************************************************************/
1739 static jb_err client_keep_alive(struct client_state *csp, char **header)
1741 unsigned int keep_alive_timeout;
1742 char *timeout_position;
1744 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1746 log_error(LOG_LEVEL_HEADER,
1747 "keep-alive support is disabled. Crunching: %s.", *header);
1752 /* Check for parameter-less format "Keep-Alive: 100" */
1753 timeout_position = strstr(*header, ": ");
1754 if ((NULL == timeout_position)
1755 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1757 /* Assume parameter format "Keep-Alive: timeout=100" */
1758 timeout_position = strstr(*header, "timeout=");
1759 if ((NULL == timeout_position)
1760 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1762 log_error(LOG_LEVEL_HEADER,
1763 "Couldn't parse: '%s'. Using default timeout %u",
1764 *header, csp->config->keep_alive_timeout);
1771 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1773 log_error(LOG_LEVEL_HEADER,
1774 "Reducing keep-alive timeout from %u to %u.",
1775 csp->config->keep_alive_timeout, keep_alive_timeout);
1776 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1780 /* XXX: Is this log worthy? */
1781 log_error(LOG_LEVEL_HEADER,
1782 "Client keep-alive timeout is %u. Sticking with %u.",
1783 keep_alive_timeout, csp->config->keep_alive_timeout);
1791 /*********************************************************************
1793 * Function : get_content_length
1795 * Description : Gets the content length specified in a
1796 * Content-Length header.
1799 * 1 : header_value = The Content-Length header value.
1800 * 2 : length = Storage to return the value.
1802 * Returns : JB_ERR_OK on success, or
1803 * JB_ERR_PARSE if no value is recognized.
1805 *********************************************************************/
1806 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1809 assert(sizeof(unsigned long long) > 4);
1810 if (1 != sscanf(header_value, "%I64u", length))
1812 if (1 != sscanf(header_value, "%llu", length))
1815 return JB_ERR_PARSE;
1822 /*********************************************************************
1824 * Function : client_save_content_length
1826 * Description : Save the Content-Length sent by the client.
1829 * 1 : csp = Current client state (buffers, headers, etc...)
1830 * 2 : header = On input, pointer to header to modify.
1831 * On output, pointer to the modified header, or NULL
1832 * to remove the header. This function frees the
1833 * original string if necessary.
1835 * Returns : JB_ERR_OK on success, or
1836 * JB_ERR_MEMORY on out-of-memory error.
1838 *********************************************************************/
1839 static jb_err client_save_content_length(struct client_state *csp, char **header)
1841 unsigned long long content_length = 0;
1842 const char *header_value;
1844 assert(*(*header+14) == ':');
1846 header_value = *header + 15;
1847 if (JB_ERR_OK != get_content_length(header_value, &content_length))
1849 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1854 csp->expected_client_content_length = content_length;
1859 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1863 /*********************************************************************
1865 * Function : client_connection
1867 * Description : Makes sure a proper "Connection:" header is
1868 * set and signals connection_header_adder
1872 * 1 : csp = Current client state (buffers, headers, etc...)
1873 * 2 : header = On input, pointer to header to modify.
1874 * On output, pointer to the modified header, or NULL
1875 * to remove the header. This function frees the
1876 * original string if necessary.
1878 * Returns : JB_ERR_OK on success.
1880 *********************************************************************/
1881 static jb_err client_connection(struct client_state *csp, char **header)
1883 static const char connection_close[] = "Connection: close";
1885 if (!strcmpic(*header, connection_close))
1887 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1888 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1889 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1891 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1893 log_error(LOG_LEVEL_HEADER,
1894 "Removing \'%s\' to imply keep-alive.", *header);
1897 * While we imply keep-alive to the server,
1898 * we have to remember that the client didn't.
1900 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1904 char *old_header = *header;
1906 *header = strdup_or_die("Connection: keep-alive");
1907 log_error(LOG_LEVEL_HEADER,
1908 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1914 log_error(LOG_LEVEL_HEADER,
1915 "Keeping the client header '%s' around. "
1916 "The connection will not be kept alive.",
1918 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1921 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1922 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1924 log_error(LOG_LEVEL_HEADER,
1925 "Keeping the client header '%s' around. "
1926 "The server connection will be kept alive if possible.",
1928 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1929 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1933 char *old_header = *header;
1935 *header = strdup_or_die(connection_close);
1936 log_error(LOG_LEVEL_HEADER,
1937 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1941 /* Signal client_connection_header_adder() to return early. */
1942 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1948 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1949 /*********************************************************************
1951 * Function : client_proxy_connection
1953 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
1954 * appropriate and removes the Proxy-Connection
1958 * 1 : csp = Current client state (buffers, headers, etc...)
1959 * 2 : header = On input, pointer to header to modify.
1960 * On output, pointer to the modified header, or NULL
1961 * to remove the header. This function frees the
1962 * original string if necessary.
1964 * Returns : JB_ERR_OK
1966 *********************************************************************/
1967 static jb_err client_proxy_connection(struct client_state *csp, char **header)
1969 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1970 && (csp->http->ssl == 0)
1971 && (NULL == strstr(*header, "close")))
1973 log_error(LOG_LEVEL_HEADER,
1974 "The client connection can be kept alive due to: %s", *header);
1975 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1977 crumble(csp, header);
1981 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1984 /*********************************************************************
1986 * Function : client_transfer_encoding
1988 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
1989 * the request body is "chunked"
1991 * XXX: Currently not called through sed() as we
1992 * need the flag earlier on. Should be fixed.
1995 * 1 : csp = Current client state (buffers, headers, etc...)
1996 * 2 : header = On input, pointer to header to modify.
1997 * On output, pointer to the modified header, or NULL
1998 * to remove the header. This function frees the
1999 * original string if necessary.
2001 * Returns : JB_ERR_OK on success, or
2003 *********************************************************************/
2004 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2006 if (strstr(*header, "chunked"))
2008 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2009 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2016 /*********************************************************************
2018 * Function : client_expect
2020 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2021 * if the Expect header value is unsupported.
2023 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2024 * MAY and a RFC 2616 (obsolete) MUST.
2027 * 1 : csp = Current client state (buffers, headers, etc...)
2028 * 2 : header = On input, pointer to header to modify.
2029 * On output, pointer to the modified header, or NULL
2030 * to remove the header. This function frees the
2031 * original string if necessary.
2033 * Returns : JB_ERR_OK on success, or
2035 *********************************************************************/
2036 jb_err client_expect(struct client_state *csp, char **header)
2038 if (0 != strcmpic(*header, "Expect: 100-continue"))
2040 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2041 log_error(LOG_LEVEL_HEADER,
2042 "Unsupported client expectaction: %s", *header);
2050 /*********************************************************************
2052 * Function : crumble
2054 * Description : This is called if a header matches a pattern to "crunch"
2057 * 1 : csp = Current client state (buffers, headers, etc...)
2058 * 2 : header = On input, pointer to header to modify.
2059 * On output, pointer to the modified header, or NULL
2060 * to remove the header. This function frees the
2061 * original string if necessary.
2063 * Returns : JB_ERR_OK on success, or
2064 * JB_ERR_MEMORY on out-of-memory error.
2066 *********************************************************************/
2067 static jb_err crumble(struct client_state *csp, char **header)
2070 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2076 /*********************************************************************
2078 * Function : crunch_server_header
2080 * Description : Crunch server header if it matches a string supplied by the
2081 * user. Called from `sed'.
2084 * 1 : csp = Current client state (buffers, headers, etc...)
2085 * 2 : header = On input, pointer to header to modify.
2086 * On output, pointer to the modified header, or NULL
2087 * to remove the header. This function frees the
2088 * original string if necessary.
2090 * Returns : JB_ERR_OK on success and always succeeds
2092 *********************************************************************/
2093 static jb_err crunch_server_header(struct client_state *csp, char **header)
2095 const char *crunch_pattern;
2097 /* Do we feel like crunching? */
2098 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2100 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2102 /* Is the current header the lucky one? */
2103 if (strstr(*header, crunch_pattern))
2105 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2114 /*********************************************************************
2116 * Function : server_content_type
2118 * Description : Set the content-type for filterable types (text/.*,
2119 * .*xml.*, .*script.* and image/gif) unless filtering has been
2120 * forbidden (CT_TABOO) while parsing earlier headers.
2121 * NOTE: Since text/plain is commonly used by web servers
2122 * for files whose correct type is unknown, we don't
2123 * set CT_TEXT for it.
2126 * 1 : csp = Current client state (buffers, headers, etc...)
2127 * 2 : header = On input, pointer to header to modify.
2128 * On output, pointer to the modified header, or NULL
2129 * to remove the header. This function frees the
2130 * original string if necessary.
2132 * Returns : JB_ERR_OK on success, or
2133 * JB_ERR_MEMORY on out-of-memory error.
2135 *********************************************************************/
2136 static jb_err server_content_type(struct client_state *csp, char **header)
2138 /* Remove header if it isn't the first Content-Type header */
2139 if ((csp->content_type & CT_DECLARED))
2141 if (content_filters_enabled(csp->action))
2144 * Making sure the client interprets the content the same way
2145 * Privoxy did is only relevant if Privoxy modified it.
2147 * Checking for this is "hard" as it's not yet known when
2148 * this function is called, thus go shopping and and just
2149 * check if Privoxy could filter it.
2151 * The main thing is that we don't mess with the headers
2152 * unless the user signalled that it's acceptable.
2154 log_error(LOG_LEVEL_HEADER,
2155 "Multiple Content-Type headers detected. "
2156 "Removing and ignoring: %s",
2164 * Signal that the Content-Type has been set.
2166 csp->content_type |= CT_DECLARED;
2168 if (!(csp->content_type & CT_TABOO))
2171 * XXX: The assumption that text/plain is a sign of
2172 * binary data seems to be somewhat unreasonable nowadays
2173 * and should be dropped after 3.0.8 is out.
2175 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2176 || strstr(*header, "xml")
2177 || strstr(*header, "script"))
2179 csp->content_type |= CT_TEXT;
2181 else if (strstr(*header, "image/gif"))
2183 csp->content_type |= CT_GIF;
2188 * Are we messing with the content type?
2190 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2193 * Make sure the user doesn't accidentally
2194 * change the content type of binary documents.
2196 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2199 *header = strdup_or_die("Content-Type: ");
2200 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2204 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2205 return JB_ERR_MEMORY;
2207 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2211 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2212 "It doesn't look like a content type that should be filtered. "
2213 "Enable force-text-mode if you know what you're doing.", *header);
2221 /*********************************************************************
2223 * Function : server_transfer_coding
2225 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2226 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2227 * - Remove header if body was chunked but has been
2228 * de-chunked for filtering.
2231 * 1 : csp = Current client state (buffers, headers, etc...)
2232 * 2 : header = On input, pointer to header to modify.
2233 * On output, pointer to the modified header, or NULL
2234 * to remove the header. This function frees the
2235 * original string if necessary.
2237 * Returns : JB_ERR_OK on success, or
2238 * JB_ERR_MEMORY on out-of-memory error.
2240 *********************************************************************/
2241 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2244 * Turn off pcrs and gif filtering if body compressed
2246 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2250 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2252 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2253 csp->http->cmd, *header);
2254 #endif /* def FEATURE_ZLIB */
2255 csp->content_type = CT_TABOO;
2259 * Raise flag if body chunked
2261 if (strstr(*header, "chunked"))
2263 csp->flags |= CSP_FLAG_CHUNKED;
2266 * If the body was modified, it has been de-chunked first
2267 * and the header must be removed.
2269 * FIXME: If there is more than one transfer encoding,
2270 * only the "chunked" part should be removed here.
2272 if (csp->flags & CSP_FLAG_MODIFIED)
2274 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2283 /*********************************************************************
2285 * Function : server_content_encoding
2287 * Description : Used to check if the content is compressed, and if
2288 * FEATURE_ZLIB is disabled, filtering is disabled as
2291 * If FEATURE_ZLIB is enabled and the compression type
2292 * supported, the content is marked for decompression.
2294 * XXX: Doesn't properly deal with multiple or with
2295 * unsupported but unknown encodings.
2296 * Is case-sensitive but shouldn't be.
2299 * 1 : csp = Current client state (buffers, headers, etc...)
2300 * 2 : header = On input, pointer to header to modify.
2301 * On output, pointer to the modified header, or NULL
2302 * to remove the header. This function frees the
2303 * original string if necessary.
2305 * Returns : JB_ERR_OK on success, or
2306 * JB_ERR_MEMORY on out-of-memory error.
2308 *********************************************************************/
2309 static jb_err server_content_encoding(struct client_state *csp, char **header)
2312 if (strstr(*header, "sdch"))
2315 * Shared Dictionary Compression over HTTP isn't supported,
2316 * filtering it anyway is pretty much guaranteed to mess up
2319 csp->content_type |= CT_TABOO;
2322 * Log a warning if the user expects the content to be filtered.
2324 if (content_filters_enabled(csp->action))
2326 log_error(LOG_LEVEL_INFO,
2327 "SDCH-compressed content detected, content filtering disabled. "
2328 "Consider suppressing SDCH offers made by the client.");
2331 else if (strstr(*header, "gzip"))
2333 /* Mark for gzip decompression */
2334 csp->content_type |= CT_GZIP;
2336 else if (strstr(*header, "deflate"))
2338 /* Mark for zlib decompression */
2339 csp->content_type |= CT_DEFLATE;
2341 else if (strstr(*header, "compress"))
2344 * We can't decompress this; therefore we can't filter
2347 csp->content_type |= CT_TABOO;
2349 #else /* !defined(FEATURE_ZLIB) */
2351 * XXX: Using a black list here isn't the right approach.
2353 * In case of SDCH, building with zlib support isn't
2356 if (strstr(*header, "gzip") ||
2357 strstr(*header, "compress") ||
2358 strstr(*header, "deflate") ||
2359 strstr(*header, "sdch"))
2362 * Body is compressed, turn off pcrs and gif filtering.
2364 csp->content_type |= CT_TABOO;
2367 * Log a warning if the user expects the content to be filtered.
2369 if ((csp->rlist != NULL) &&
2370 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2372 log_error(LOG_LEVEL_INFO,
2373 "Compressed content detected, content filtering disabled. "
2374 "Consider recompiling Privoxy with zlib support or "
2375 "enable the prevent-compression action.");
2378 #endif /* defined(FEATURE_ZLIB) */
2386 /*********************************************************************
2388 * Function : server_adjust_content_encoding
2390 * Description : Remove the Content-Encoding header if the
2391 * decompression was successful and the content
2395 * 1 : csp = Current client state (buffers, headers, etc...)
2396 * 2 : header = On input, pointer to header to modify.
2397 * On output, pointer to the modified header, or NULL
2398 * to remove the header. This function frees the
2399 * original string if necessary.
2401 * Returns : JB_ERR_OK on success, or
2402 * JB_ERR_MEMORY on out-of-memory error.
2404 *********************************************************************/
2405 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2407 if ((csp->flags & CSP_FLAG_MODIFIED)
2408 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2411 * We successfully decompressed the content,
2412 * and have to clean the header now, so the
2413 * client no longer expects compressed data.
2415 * XXX: There is a difference between cleaning
2416 * and removing it completely.
2418 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2425 #endif /* defined(FEATURE_ZLIB) */
2428 /*********************************************************************
2430 * Function : server_adjust_content_length
2432 * Description : Adjust Content-Length header if we modified
2436 * 1 : csp = Current client state (buffers, headers, etc...)
2437 * 2 : header = On input, pointer to header to modify.
2438 * On output, pointer to the modified header, or NULL
2439 * to remove the header. This function frees the
2440 * original string if necessary.
2442 * Returns : JB_ERR_OK on success, or
2443 * JB_ERR_MEMORY on out-of-memory error.
2445 *********************************************************************/
2446 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2448 /* Regenerate header if the content was modified. */
2449 if (csp->flags & CSP_FLAG_MODIFIED)
2451 const size_t header_length = 50;
2453 *header = malloc(header_length);
2454 if (*header == NULL)
2456 return JB_ERR_MEMORY;
2458 create_content_length_header(csp->content_length, *header, header_length);
2459 log_error(LOG_LEVEL_HEADER,
2460 "Adjusted Content-Length to %llu", csp->content_length);
2467 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2468 /*********************************************************************
2470 * Function : server_save_content_length
2472 * Description : Save the Content-Length sent by the server.
2475 * 1 : csp = Current client state (buffers, headers, etc...)
2476 * 2 : header = On input, pointer to header to modify.
2477 * On output, pointer to the modified header, or NULL
2478 * to remove the header. This function frees the
2479 * original string if necessary.
2481 * Returns : JB_ERR_OK on success, or
2482 * JB_ERR_MEMORY on out-of-memory error.
2484 *********************************************************************/
2485 static jb_err server_save_content_length(struct client_state *csp, char **header)
2487 unsigned long long content_length = 0;
2488 const char *header_value;
2490 assert(*(*header+14) == ':');
2492 header_value = *header + 15;
2493 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2495 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2500 csp->expected_content_length = content_length;
2501 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2502 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2507 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2510 /*********************************************************************
2512 * Function : server_content_md5
2514 * Description : Crumble any Content-MD5 headers if the document was
2515 * modified. FIXME: Should we re-compute instead?
2518 * 1 : csp = Current client state (buffers, headers, etc...)
2519 * 2 : header = On input, pointer to header to modify.
2520 * On output, pointer to the modified header, or NULL
2521 * to remove the header. This function frees the
2522 * original string if necessary.
2524 * Returns : JB_ERR_OK on success, or
2525 * JB_ERR_MEMORY on out-of-memory error.
2527 *********************************************************************/
2528 static jb_err server_content_md5(struct client_state *csp, char **header)
2530 if (csp->flags & CSP_FLAG_MODIFIED)
2532 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2540 /*********************************************************************
2542 * Function : server_content_disposition
2544 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2545 * Called from `sed'.
2548 * 1 : csp = Current client state (buffers, headers, etc...)
2549 * 2 : header = On input, pointer to header to modify.
2550 * On output, pointer to the modified header, or NULL
2551 * to remove the header. This function frees the
2552 * original string if necessary.
2554 * Returns : JB_ERR_OK on success, or
2555 * JB_ERR_MEMORY on out-of-memory error.
2557 *********************************************************************/
2558 static jb_err server_content_disposition(struct client_state *csp, char **header)
2563 * Are we messing with the Content-Disposition header?
2565 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2571 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2573 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2576 * Blocking content-disposition header
2578 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2585 * Replacing Content-Disposition header
2588 *header = strdup("Content-Disposition: ");
2589 string_append(header, newval);
2591 if (*header != NULL)
2593 log_error(LOG_LEVEL_HEADER,
2594 "Content-Disposition header crunched and replaced with: %s", *header);
2597 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2601 /*********************************************************************
2603 * Function : server_last_modified
2605 * Description : Changes Last-Modified header to the actual date
2606 * to help hide-if-modified-since.
2607 * Called from `sed'.
2610 * 1 : csp = Current client state (buffers, headers, etc...)
2611 * 2 : header = On input, pointer to header to modify.
2612 * On output, pointer to the modified header, or NULL
2613 * to remove the header. This function frees the
2614 * original string if necessary.
2616 * Returns : JB_ERR_OK on success, or
2617 * JB_ERR_MEMORY on out-of-memory error.
2619 *********************************************************************/
2620 static jb_err server_last_modified(struct client_state *csp, char **header)
2623 time_t last_modified;
2627 * Are we messing with the Last-Modified header?
2629 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2635 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2637 if (0 == strcmpic(newval, "block"))
2640 * Blocking Last-Modified header. Useless but why not.
2642 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2646 else if (0 == strcmpic(newval, "reset-to-request-time"))
2649 * Setting Last-Modified Header to now.
2652 get_http_time(0, buf, sizeof(buf));
2654 *header = strdup("Last-Modified: ");
2655 string_append(header, buf);
2657 if (*header == NULL)
2659 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2663 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2666 else if (0 == strcmpic(newval, "randomize"))
2668 const char *header_time = *header + sizeof("Last-Modified:");
2670 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2672 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2674 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2680 struct tm *timeptr = NULL;
2682 #ifdef HAVE_GMTIME_R
2686 rtime = (long int)difftime(now, last_modified);
2689 long int days, hours, minutes, seconds;
2690 const int negative_delta = (rtime < 0);
2695 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2697 rtime = pick_from_range(rtime);
2702 last_modified += rtime;
2703 #ifdef HAVE_GMTIME_R
2704 timeptr = gmtime_r(&last_modified, &gmt);
2705 #elif defined(MUTEX_LOCKS_AVAILABLE)
2706 privoxy_mutex_lock(&gmtime_mutex);
2707 timeptr = gmtime(&last_modified);
2708 privoxy_mutex_unlock(&gmtime_mutex);
2710 timeptr = gmtime(&last_modified);
2712 if ((NULL == timeptr) || !strftime(newheader,
2713 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2715 log_error(LOG_LEVEL_ERROR,
2716 "Randomizing '%s' failed. Crunching the header without replacement.",
2723 *header = strdup("Last-Modified: ");
2724 string_append(header, newheader);
2726 if (*header == NULL)
2728 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2729 return JB_ERR_MEMORY;
2732 days = rtime / (3600 * 24);
2733 hours = rtime / 3600 % 24;
2734 minutes = rtime / 60 % 60;
2735 seconds = rtime % 60;
2737 log_error(LOG_LEVEL_HEADER,
2738 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2739 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2740 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2744 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2753 /*********************************************************************
2755 * Function : client_accept_encoding
2757 * Description : Rewrite the client's Accept-Encoding header so that
2758 * if doesn't allow compression, if the action applies.
2759 * Note: For HTTP/1.0 the absence of the header is enough.
2762 * 1 : csp = Current client state (buffers, headers, etc...)
2763 * 2 : header = On input, pointer to header to modify.
2764 * On output, pointer to the modified header, or NULL
2765 * to remove the header. This function frees the
2766 * original string if necessary.
2768 * Returns : JB_ERR_OK on success, or
2769 * JB_ERR_MEMORY on out-of-memory error.
2771 *********************************************************************/
2772 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2774 #ifdef FEATURE_COMPRESSION
2775 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2776 && strstr(*header, "deflate"))
2778 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2781 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2783 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2791 /*********************************************************************
2793 * Function : client_te
2795 * Description : Rewrite the client's TE header so that
2796 * if doesn't allow compression, if the action applies.
2799 * 1 : csp = Current client state (buffers, headers, etc...)
2800 * 2 : header = On input, pointer to header to modify.
2801 * On output, pointer to the modified header, or NULL
2802 * to remove the header. This function frees the
2803 * original string if necessary.
2805 * Returns : JB_ERR_OK on success, or
2806 * JB_ERR_MEMORY on out-of-memory error.
2808 *********************************************************************/
2809 static jb_err client_te(struct client_state *csp, char **header)
2811 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2814 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2821 /*********************************************************************
2823 * Function : client_referrer
2825 * Description : Handle the "referer" config setting properly.
2826 * Called from `sed'.
2829 * 1 : csp = Current client state (buffers, headers, etc...)
2830 * 2 : header = On input, pointer to header to modify.
2831 * On output, pointer to the modified header, or NULL
2832 * to remove the header. This function frees the
2833 * original string if necessary.
2835 * Returns : JB_ERR_OK on success, or
2836 * JB_ERR_MEMORY on out-of-memory error.
2838 *********************************************************************/
2839 static jb_err client_referrer(struct client_state *csp, char **header)
2841 const char *parameter;
2842 /* booleans for parameters we have to check multiple times */
2843 int parameter_conditional_block;
2844 int parameter_conditional_forge;
2846 #ifdef FEATURE_FORCE_LOAD
2848 * Since the referrer can include the prefix even
2849 * if the request itself is non-forced, we must
2850 * clean it unconditionally.
2852 * XXX: strclean is too broad
2854 strclean(*header, FORCE_PREFIX);
2855 #endif /* def FEATURE_FORCE_LOAD */
2857 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2859 /* Nothing left to do */
2863 parameter = csp->action->string[ACTION_STRING_REFERER];
2864 assert(parameter != NULL);
2865 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2866 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2868 if (!parameter_conditional_block && !parameter_conditional_forge)
2871 * As conditional-block and conditional-forge are the only
2872 * parameters that rely on the original referrer, we can
2873 * remove it now for all the others.
2878 if (0 == strcmpic(parameter, "block"))
2880 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2883 else if (parameter_conditional_block || parameter_conditional_forge)
2885 return handle_conditional_hide_referrer_parameter(header,
2886 csp->http->hostport, parameter_conditional_block);
2888 else if (0 == strcmpic(parameter, "forge"))
2890 return create_forged_referrer(header, csp->http->hostport);
2894 /* interpret parameter as user-supplied referer to fake */
2895 return create_fake_referrer(header, parameter);
2900 /*********************************************************************
2902 * Function : client_accept_language
2904 * Description : Handle the "Accept-Language" config setting properly.
2905 * Called from `sed'.
2908 * 1 : csp = Current client state (buffers, headers, etc...)
2909 * 2 : header = On input, pointer to header to modify.
2910 * On output, pointer to the modified header, or NULL
2911 * to remove the header. This function frees the
2912 * original string if necessary.
2914 * Returns : JB_ERR_OK on success, or
2915 * JB_ERR_MEMORY on out-of-memory error.
2917 *********************************************************************/
2918 static jb_err client_accept_language(struct client_state *csp, char **header)
2923 * Are we messing with the Accept-Language?
2925 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2927 /*I don't think so*/
2931 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2933 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2936 * Blocking Accept-Language header
2938 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2945 * Replacing Accept-Language header
2948 *header = strdup("Accept-Language: ");
2949 string_append(header, newval);
2951 if (*header == NULL)
2953 log_error(LOG_LEVEL_ERROR,
2954 "Insufficient memory. Accept-Language header crunched without replacement.");
2958 log_error(LOG_LEVEL_HEADER,
2959 "Accept-Language header crunched and replaced with: %s", *header);
2962 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2966 /*********************************************************************
2968 * Function : crunch_client_header
2970 * Description : Crunch client header if it matches a string supplied by the
2971 * user. Called from `sed'.
2974 * 1 : csp = Current client state (buffers, headers, etc...)
2975 * 2 : header = On input, pointer to header to modify.
2976 * On output, pointer to the modified header, or NULL
2977 * to remove the header. This function frees the
2978 * original string if necessary.
2980 * Returns : JB_ERR_OK on success and always succeeds
2982 *********************************************************************/
2983 static jb_err crunch_client_header(struct client_state *csp, char **header)
2985 const char *crunch_pattern;
2987 /* Do we feel like crunching? */
2988 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2990 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2992 /* Is the current header the lucky one? */
2993 if (strstr(*header, crunch_pattern))
2995 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3003 /*********************************************************************
3005 * Function : client_uagent
3007 * Description : Handle the "user-agent" config setting properly
3008 * and remember its original value to enable browser
3009 * bug workarounds. Called from `sed'.
3012 * 1 : csp = Current client state (buffers, headers, etc...)
3013 * 2 : header = On input, pointer to header to modify.
3014 * On output, pointer to the modified header, or NULL
3015 * to remove the header. This function frees the
3016 * original string if necessary.
3018 * Returns : JB_ERR_OK on success, or
3019 * JB_ERR_MEMORY on out-of-memory error.
3021 *********************************************************************/
3022 static jb_err client_uagent(struct client_state *csp, char **header)
3026 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3031 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3038 *header = strdup("User-Agent: ");
3039 string_append(header, newval);
3041 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3043 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3047 /*********************************************************************
3049 * Function : client_ua
3051 * Description : Handle "ua-" headers properly. Called from `sed'.
3054 * 1 : csp = Current client state (buffers, headers, etc...)
3055 * 2 : header = On input, pointer to header to modify.
3056 * On output, pointer to the modified header, or NULL
3057 * to remove the header. This function frees the
3058 * original string if necessary.
3060 * Returns : JB_ERR_OK on success, or
3061 * JB_ERR_MEMORY on out-of-memory error.
3063 *********************************************************************/
3064 static jb_err client_ua(struct client_state *csp, char **header)
3066 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3068 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3076 /*********************************************************************
3078 * Function : client_from
3080 * Description : Handle the "from" config setting properly.
3081 * Called from `sed'.
3084 * 1 : csp = Current client state (buffers, headers, etc...)
3085 * 2 : header = On input, pointer to header to modify.
3086 * On output, pointer to the modified header, or NULL
3087 * to remove the header. This function frees the
3088 * original string if necessary.
3090 * Returns : JB_ERR_OK on success, or
3091 * JB_ERR_MEMORY on out-of-memory error.
3093 *********************************************************************/
3094 static jb_err client_from(struct client_state *csp, char **header)
3098 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3105 newval = csp->action->string[ACTION_STRING_FROM];
3108 * Are we blocking the e-mail address?
3110 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3112 log_error(LOG_LEVEL_HEADER, "crunched From!");
3116 log_error(LOG_LEVEL_HEADER, " modified");
3118 *header = strdup("From: ");
3119 string_append(header, newval);
3121 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3125 /*********************************************************************
3127 * Function : client_send_cookie
3129 * Description : Crunches the "cookie" header if necessary.
3130 * Called from `sed'.
3132 * XXX: Stupid name, doesn't send squat.
3135 * 1 : csp = Current client state (buffers, headers, etc...)
3136 * 2 : header = On input, pointer to header to modify.
3137 * On output, pointer to the modified header, or NULL
3138 * to remove the header. This function frees the
3139 * original string if necessary.
3141 * Returns : JB_ERR_OK on success, or
3142 * JB_ERR_MEMORY on out-of-memory error.
3144 *********************************************************************/
3145 static jb_err client_send_cookie(struct client_state *csp, char **header)
3147 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3149 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3157 /*********************************************************************
3159 * Function : client_x_forwarded
3161 * Description : Handle the "x-forwarded-for" config setting properly,
3162 * also used in the add_client_headers list. Called from `sed'.
3165 * 1 : csp = Current client state (buffers, headers, etc...)
3166 * 2 : header = On input, pointer to header to modify.
3167 * On output, pointer to the modified header, or NULL
3168 * to remove the header. This function frees the
3169 * original string if necessary.
3171 * Returns : JB_ERR_OK on success, or
3172 * JB_ERR_MEMORY on out-of-memory error.
3174 *********************************************************************/
3175 jb_err client_x_forwarded(struct client_state *csp, char **header)
3177 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3179 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3181 if (0 == strcmpic(parameter, "block"))
3184 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3186 else if (0 == strcmpic(parameter, "add"))
3188 string_append(header, ", ");
3189 string_append(header, csp->ip_addr_str);
3191 if (*header == NULL)
3193 return JB_ERR_MEMORY;
3195 log_error(LOG_LEVEL_HEADER,
3196 "Appended client IP address to %s", *header);
3197 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3201 log_error(LOG_LEVEL_FATAL,
3202 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3210 /*********************************************************************
3212 * Function : client_max_forwards
3214 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3215 * from the value of the Max-Forwards header field.
3218 * 1 : csp = Current client state (buffers, headers, etc...)
3219 * 2 : header = On input, pointer to header to modify.
3220 * On output, pointer to the modified header, or NULL
3221 * to remove the header. This function frees the
3222 * original string if necessary.
3224 * Returns : JB_ERR_OK on success, or
3225 * JB_ERR_MEMORY on out-of-memory error.
3227 *********************************************************************/
3228 static jb_err client_max_forwards(struct client_state *csp, char **header)
3232 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3233 (0 == strcmpic(csp->http->gpc, "options")))
3235 assert(*(*header+12) == ':');
3236 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3238 if (max_forwards > 0)
3240 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3241 log_error(LOG_LEVEL_HEADER,
3242 "Max-Forwards value for %s request reduced to %d.",
3243 csp->http->gpc, max_forwards);
3245 else if (max_forwards < 0)
3247 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3253 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3262 /*********************************************************************
3264 * Function : client_host
3266 * Description : If the request URI did not contain host and
3267 * port information, parse and evaluate the Host
3271 * 1 : csp = Current client state (buffers, headers, etc...)
3272 * 2 : header = On input, pointer to header to modify.
3273 * On output, pointer to the modified header, or NULL
3274 * to remove the header. This function frees the
3275 * original string if necessary.
3277 * Returns : JB_ERR_OK on success, or
3278 * JB_ERR_MEMORY on out-of-memory error.
3280 *********************************************************************/
3281 static jb_err client_host(struct client_state *csp, char **header)
3285 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3286 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3289 p = strdup_or_die((*header)+6);
3291 q = strdup_or_die(p);
3293 freez(csp->http->hostport);
3294 csp->http->hostport = p;
3295 freez(csp->http->host);
3296 csp->http->host = q;
3297 q = strchr(csp->http->host, ':');
3300 /* Terminate hostname and evaluate port string */
3302 csp->http->port = atoi(q);
3306 csp->http->port = csp->http->ssl ? 443 : 80;
3309 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3310 csp->http->hostport, csp->http->host, csp->http->port);
3313 /* Signal client_host_adder() to return right away */
3314 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3320 /*********************************************************************
3322 * Function : client_if_modified_since
3324 * Description : Remove or modify the If-Modified-Since header.
3327 * 1 : csp = Current client state (buffers, headers, etc...)
3328 * 2 : header = On input, pointer to header to modify.
3329 * On output, pointer to the modified header, or NULL
3330 * to remove the header. This function frees the
3331 * original string if necessary.
3333 * Returns : JB_ERR_OK on success, or
3334 * JB_ERR_MEMORY on out-of-memory error.
3336 *********************************************************************/
3337 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3340 #ifdef HAVE_GMTIME_R
3343 struct tm *timeptr = NULL;
3348 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3351 * The client got an error message because of a temporary problem,
3352 * the problem is gone and the client now tries to revalidate our
3353 * error message on the real server. The revalidation would always
3354 * end with the transmission of the whole document and there is
3355 * no need to expose the bogus If-Modified-Since header.
3357 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3360 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3362 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3364 if ((0 == strcmpic(newval, "block")))
3366 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3369 else /* add random value */
3371 const char *header_time = *header + sizeof("If-Modified-Since:");
3373 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3375 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3380 long int hours, minutes, seconds;
3381 long int rtime = strtol(newval, &endptr, 0);
3382 const int negative_range = (rtime < 0);
3386 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3387 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3393 rtime = pick_from_range(rtime);
3397 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3400 tm += rtime * (negative_range ? -1 : 1);
3401 #ifdef HAVE_GMTIME_R
3402 timeptr = gmtime_r(&tm, &gmt);
3403 #elif defined(MUTEX_LOCKS_AVAILABLE)
3404 privoxy_mutex_lock(&gmtime_mutex);
3405 timeptr = gmtime(&tm);
3406 privoxy_mutex_unlock(&gmtime_mutex);
3408 timeptr = gmtime(&tm);
3410 if ((NULL == timeptr) || !strftime(newheader,
3411 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3413 log_error(LOG_LEVEL_ERROR,
3414 "Randomizing '%s' failed. Crunching the header without replacement.",
3421 *header = strdup("If-Modified-Since: ");
3422 string_append(header, newheader);
3424 if (*header == NULL)
3426 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3427 return JB_ERR_MEMORY;
3430 hours = rtime / 3600;
3431 minutes = rtime / 60 % 60;
3432 seconds = rtime % 60;
3434 log_error(LOG_LEVEL_HEADER,
3435 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3436 *header, (negative_range) ? "subtracted" : "added", hours,
3437 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3438 seconds, (seconds == 1) ? ")" : "s)");
3447 /*********************************************************************
3449 * Function : client_if_none_match
3451 * Description : Remove the If-None-Match header.
3454 * 1 : csp = Current client state (buffers, headers, etc...)
3455 * 2 : header = On input, pointer to header to modify.
3456 * On output, pointer to the modified header, or NULL
3457 * to remove the header. This function frees the
3458 * original string if necessary.
3460 * Returns : JB_ERR_OK on success, or
3461 * JB_ERR_MEMORY on out-of-memory error.
3463 *********************************************************************/
3464 static jb_err client_if_none_match(struct client_state *csp, char **header)
3466 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3468 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3476 /*********************************************************************
3478 * Function : client_x_filter
3480 * Description : Disables filtering if the client set "X-Filter: No".
3481 * Called from `sed'.
3484 * 1 : csp = Current client state (buffers, headers, etc...)
3485 * 2 : header = On input, pointer to header to modify.
3486 * On output, pointer to the modified header, or NULL
3487 * to remove the header. This function frees the
3488 * original string if necessary.
3490 * Returns : JB_ERR_OK on success
3492 *********************************************************************/
3493 jb_err client_x_filter(struct client_state *csp, char **header)
3495 if (0 == strcmpic(*header, "X-Filter: No"))
3497 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3499 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3503 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3505 log_error(LOG_LEVEL_HEADER,
3506 "force-text-mode overruled the client's request to fetch without filtering!");
3510 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3511 csp->flags |= CSP_FLAG_NO_FILTERING;
3512 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3514 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3522 /*********************************************************************
3524 * Function : client_range
3526 * Description : Removes Range, Request-Range and If-Range headers if
3527 * content filtering is enabled and the range doesn't
3530 * If the client's version of the document has been
3531 * altered by Privoxy, the server could interpret the
3532 * range differently than the client intended in which
3533 * case the user could end up with corrupted content.
3535 * If the range starts at byte 0 this isn't an issue
3536 * so the header can pass. Partial requests like this
3537 * are used to render preview images for videos without
3538 * downloading the whole video.
3540 * While HTTP doesn't require that range requests are
3541 * honoured and the client could simply abort the download
3542 * after receiving a sufficient amount of data, various
3543 * clients don't handle complete responses to range
3544 * requests gracefully and emit misleading error messages
3548 * 1 : csp = Current client state (buffers, headers, etc...)
3549 * 2 : header = On input, pointer to header to modify.
3550 * On output, pointer to the modified header, or NULL
3551 * to remove the header. This function frees the
3552 * original string if necessary.
3554 * Returns : JB_ERR_OK
3556 *********************************************************************/
3557 static jb_err client_range(struct client_state *csp, char **header)
3559 if (content_filters_enabled(csp->action)
3560 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3562 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3563 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3570 /* the following functions add headers directly to the header list */
3572 /*********************************************************************
3574 * Function : client_host_adder
3576 * Description : Adds the Host: header field if it is missing.
3577 * Called from `sed'.
3580 * 1 : csp = Current client state (buffers, headers, etc...)
3582 * Returns : JB_ERR_OK on success, or
3583 * JB_ERR_MEMORY on out-of-memory error.
3585 *********************************************************************/
3586 static jb_err client_host_adder(struct client_state *csp)
3591 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3593 /* Header already set by the client, nothing to do. */
3597 if (!csp->http->hostport || !*(csp->http->hostport))
3599 /* XXX: When does this happen and why is it OK? */
3600 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3605 * remove 'user:pass@' from 'proto://user:pass@host'
3607 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3613 p = csp->http->hostport;
3616 /* XXX: Just add it, we already made sure that it will be unique */
3617 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3618 err = enlist_unique_header(csp->headers, "Host", p);
3624 /*********************************************************************
3626 * Function : client_xtra_adder
3628 * Description : Used in the add_client_headers list. Called from `sed'.
3631 * 1 : csp = Current client state (buffers, headers, etc...)
3633 * Returns : JB_ERR_OK on success, or
3634 * JB_ERR_MEMORY on out-of-memory error.
3636 *********************************************************************/
3637 static jb_err client_xtra_adder(struct client_state *csp)
3639 struct list_entry *lst;
3642 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3643 lst ; lst = lst->next)
3645 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3646 err = enlist(csp->headers, lst->str);
3658 /*********************************************************************
3660 * Function : client_x_forwarded_for_adder
3662 * Description : Used in the add_client_headers list. Called from `sed'.
3665 * 1 : csp = Current client state (buffers, headers, etc...)
3667 * Returns : JB_ERR_OK on success, or
3668 * JB_ERR_MEMORY on out-of-memory error.
3670 *********************************************************************/
3671 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3673 char *header = NULL;
3676 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3677 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3678 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3681 * If we aren't adding X-Forwarded-For headers,
3682 * or we already appended an existing X-Forwarded-For
3683 * header, there's nothing left to do here.
3688 header = strdup("X-Forwarded-For: ");
3689 string_append(&header, csp->ip_addr_str);
3693 return JB_ERR_MEMORY;
3696 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3697 err = enlist(csp->headers, header);
3704 /*********************************************************************
3706 * Function : server_connection_adder
3708 * Description : Adds an appropriate "Connection:" header to csp->headers
3709 * unless the header was already present. Called from `sed'.
3712 * 1 : csp = Current client state (buffers, headers, etc...)
3714 * Returns : JB_ERR_OK on success, or
3715 * JB_ERR_MEMORY on out-of-memory error.
3717 *********************************************************************/
3718 static jb_err server_connection_adder(struct client_state *csp)
3720 const unsigned int flags = csp->flags;
3721 const char *response_status_line = csp->headers->first->str;
3722 static const char connection_close[] = "Connection: close";
3724 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3725 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3731 * XXX: if we downgraded the response, this check will fail.
3733 if ((csp->config->feature_flags &
3734 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3735 && (NULL != response_status_line)
3736 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3737 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3738 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3742 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3743 "without Connection header implies keep-alive.");
3744 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3748 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3750 return enlist(csp->headers, connection_close);
3754 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3755 /*********************************************************************
3757 * Function : server_proxy_connection_adder
3759 * Description : Adds a "Proxy-Connection: keep-alive" header to
3760 * csp->headers when appropriate.
3763 * 1 : csp = Current client state (buffers, headers, etc...)
3765 * Returns : JB_ERR_OK on success, or
3766 * JB_ERR_MEMORY on out-of-memory error.
3768 *********************************************************************/
3769 static jb_err server_proxy_connection_adder(struct client_state *csp)
3771 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3772 jb_err err = JB_ERR_OK;
3774 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3775 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3776 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3777 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3778 || (csp->flags & CSP_FLAG_CHUNKED)))
3780 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3781 err = enlist(csp->headers, proxy_connection_header);
3786 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3789 /*********************************************************************
3791 * Function : client_connection_header_adder
3793 * Description : Adds a proper "Connection:" header to csp->headers
3794 * unless the header was already present. Called from `sed'.
3797 * 1 : csp = Current client state (buffers, headers, etc...)
3799 * Returns : JB_ERR_OK on success, or
3800 * JB_ERR_MEMORY on out-of-memory error.
3802 *********************************************************************/
3803 static jb_err client_connection_header_adder(struct client_state *csp)
3805 static const char connection_close[] = "Connection: close";
3807 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3808 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3813 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3814 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3815 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3816 && (csp->http->ssl == 0)
3817 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3819 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3822 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3824 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3826 return enlist(csp->headers, connection_close);
3830 /*********************************************************************
3832 * Function : server_http
3834 * Description : - Save the HTTP Status into csp->http->status
3835 * - Set CT_TABOO to prevent filtering if the answer
3836 * is a partial range (HTTP status 206)
3837 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3839 * - Normalize the HTTP-version.
3842 * 1 : csp = Current client state (buffers, headers, etc...)
3843 * 2 : header = On input, pointer to header to modify.
3844 * On output, pointer to the modified header, or NULL
3845 * to remove the header. This function frees the
3846 * original string if necessary.
3848 * Returns : JB_ERR_OK on success, or
3849 * JB_ERR_PARSE on fatal parse errors.
3851 *********************************************************************/
3852 static jb_err server_http(struct client_state *csp, char **header)
3854 char *reason_phrase = NULL;
3855 char *new_response_line;
3858 unsigned int major_version;
3859 unsigned int minor_version;
3861 /* Get the reason phrase which start after the second whitespace */
3862 p = strchr(*header, ' ');
3866 reason_phrase = strchr(p, ' ');
3869 if (reason_phrase != NULL)
3875 log_error(LOG_LEVEL_ERROR,
3876 "Response line lacks reason phrase: %s", *header);
3880 if (3 != sscanf(*header, "HTTP/%u.%u %u", &major_version,
3881 &minor_version, &(csp->http->status)))
3883 log_error(LOG_LEVEL_ERROR,
3884 "Failed to parse the response line: %s", *header);
3885 return JB_ERR_PARSE;
3888 if (csp->http->status == 206)
3890 csp->content_type = CT_TABOO;
3893 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
3896 * According to RFC 7230 2.6 intermediaries MUST send
3897 * their own HTTP-version in forwarded messages.
3899 log_error(LOG_LEVEL_ERROR,
3900 "Unsupported HTTP version. Downgrading to 1.1.");
3905 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
3907 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
3911 /* Rebuild response line. */
3912 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
3913 new_response_line = malloc_or_die(length);
3915 snprintf(new_response_line, length, "HTTP/%u.%u %u %s",
3916 major_version, minor_version, csp->http->status, reason_phrase);
3918 if (0 != strcmp(*header, new_response_line))
3920 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
3921 *header, new_response_line);
3925 *header = new_response_line;
3930 /*********************************************************************
3932 * Function : add_cooky_expiry_date
3934 * Description : Adds a cookie expiry date to a string.
3937 * 1 : cookie = On input, pointer to cookie to modify.
3938 * On output, pointer to the modified header.
3939 * The original string is freed.
3940 * 2 : lifetime = Seconds the cookie should be valid
3944 *********************************************************************/
3945 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
3948 struct tm *timeptr = NULL;
3949 time_t expiry_date = time(NULL) + lifetime;
3950 #ifdef HAVE_GMTIME_R
3953 timeptr = gmtime_r(&expiry_date, &gmt);
3954 #elif defined(MUTEX_LOCKS_AVAILABLE)
3955 privoxy_mutex_lock(&gmtime_mutex);
3956 timeptr = gmtime(&expiry_date);
3957 privoxy_mutex_unlock(&gmtime_mutex);
3959 timeptr = gmtime(&expiry_date);
3962 if (NULL == timeptr)
3964 log_error(LOG_LEVEL_FATAL,
3965 "Failed to get the time in add_cooky_expiry_date()");
3967 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
3968 if (JB_ERR_OK != string_append(cookie, tmp))
3970 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
3975 /*********************************************************************
3977 * Function : server_set_cookie
3979 * Description : Handle the server "cookie" header properly.
3980 * Crunch, accept or rewrite it to a session cookie.
3981 * Called from `sed'.
3984 * 1 : csp = Current client state (buffers, headers, etc...)
3985 * 2 : header = On input, pointer to header to modify.
3986 * On output, pointer to the modified header, or NULL
3987 * to remove the header. This function frees the
3988 * original string if necessary.
3990 * Returns : JB_ERR_OK on success, or
3991 * JB_ERR_MEMORY on out-of-memory error.
3993 *********************************************************************/
3994 static jb_err server_set_cookie(struct client_state *csp, char **header)
3996 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
3998 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4001 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4002 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4006 long cookie_lifetime = 0;
4009 NO_EXPIRY_DATE_SPECIFIED,
4010 EXPIRY_DATE_ACCEPTABLE,
4011 EXPIRY_DATE_UNACCEPTABLE
4012 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4014 /* A variable to store the tag we're working on */
4017 /* Skip "Set-Cookie:" (11 characters) in header */
4018 cur_tag = *header + 11;
4020 /* skip whitespace between "Set-Cookie:" and value */
4021 while (*cur_tag && privoxy_isspace(*cur_tag))
4028 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4030 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4032 cookie_lifetime = strtol(param, NULL, 0);
4033 if (cookie_lifetime < 0)
4035 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4037 cookie_lifetime *= 60;
4040 /* Loop through each tag in the cookie */
4044 char *next_tag = strchr(cur_tag, ';');
4045 if (next_tag != NULL)
4047 /* Skip the ';' character itself */
4050 /* skip whitespace ";" and start of tag */
4051 while (*next_tag && privoxy_isspace(*next_tag))
4058 /* "Next tag" is the end of the string */
4059 next_tag = cur_tag + strlen(cur_tag);
4063 * Check the expiration date to see
4064 * if the cookie is still valid, if yes,
4065 * rewrite it to a session cookie.
4067 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4069 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4071 if ((expiration_date[0] == '"')
4072 && (expiration_date[1] != '\0'))
4075 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4076 * that the expiration date isn't supposed to be quoted,
4077 * but some servers do it anyway.
4082 /* Did we detect the date properly? */
4083 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4086 * Nope, treat it as if it was still valid.
4088 * XXX: Should we remove the whole cookie instead?
4090 log_error(LOG_LEVEL_ERROR,
4091 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4092 string_move(cur_tag, next_tag);
4093 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4098 * Yes. Check if the cookie is still valid.
4100 * If the cookie is already expired it's probably
4101 * a delete cookie and even if it isn't, the browser
4102 * will discard it anyway.
4106 * XXX: timegm() isn't available on some AmigaOS
4107 * versions and our replacement doesn't work.
4109 * Our options are to either:
4111 * - disable session-cookies-only completely if timegm
4114 * - to simply remove all expired tags, like it has
4115 * been done until Privoxy 3.0.6 and to live with
4116 * the consequence that it can cause login/logout
4117 * problems on servers that don't validate their
4118 * input properly, or
4120 * - to replace it with mktime in which
4121 * case there is a slight chance of valid cookies
4122 * passing as already expired.
4124 * This is the way it's currently done and it's not
4125 * as bad as it sounds. If the missing GMT offset is
4126 * enough to change the result of the expiration check
4127 * the cookie will be only valid for a few hours
4128 * anyway, which in many cases will be shorter
4129 * than a browser session.
4131 if (cookie_time < now)
4133 log_error(LOG_LEVEL_HEADER,
4134 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4135 /* Just in case some clown sets more then one expiration date */
4137 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4139 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4141 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4142 "Its lifetime is below the limit.", *header);
4143 /* Just in case some clown sets more then one expiration date */
4145 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4150 * Still valid, delete expiration date by copying
4151 * the rest of the string over it.
4153 string_move(cur_tag, next_tag);
4155 /* That changed the header, need to issue a log message */
4156 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4159 * Note that the next tag has now been moved to *cur_tag,
4160 * so we do not need to update the cur_tag pointer.
4168 /* Move on to next cookie tag */
4173 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4175 assert(NULL != *header);
4176 if (cookie_lifetime != 0)
4178 add_cookie_expiry_date(header, cookie_lifetime);
4179 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4181 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4183 log_error(LOG_LEVEL_HEADER,
4184 "Cookie rewritten to a temporary one: %s", *header);
4193 #ifdef FEATURE_FORCE_LOAD
4194 /*********************************************************************
4196 * Function : strclean
4198 * Description : In-Situ-Eliminate all occurrences of substring in
4202 * 1 : string = string to clean
4203 * 2 : substring = substring to eliminate
4205 * Returns : Number of eliminations
4207 *********************************************************************/
4208 int strclean(char *string, const char *substring)
4214 len = strlen(substring);
4216 while((pos = strstr(string, substring)) != NULL)
4223 while (*p++ != '\0');
4230 #endif /* def FEATURE_FORCE_LOAD */
4233 /*********************************************************************
4235 * Function : parse_header_time
4237 * Description : Parses time formats used in HTTP header strings
4238 * to get the numerical respresentation.
4241 * 1 : header_time = HTTP header time as string.
4242 * 2 : result = storage for header_time in seconds
4244 * Returns : JB_ERR_OK if the time format was recognized, or
4245 * JB_ERR_PARSE otherwise.
4247 *********************************************************************/
4248 static jb_err parse_header_time(const char *header_time, time_t *result)
4252 * Checking for two-digit years first in an
4253 * attempt to work around GNU libc's strptime()
4254 * reporting negative year values when using %Y.
4256 static const char time_formats[][22] = {
4257 /* Tue, 02-Jun-37 20:00:00 */
4258 "%a, %d-%b-%y %H:%M:%S",
4259 /* Tue, 02 Jun 2037 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 /* Tuesday, 02-Jun-2037 20:00:00 */
4264 "%A, %d-%b-%Y %H:%M:%S",
4265 /* Tuesday Jun 02 20:00:00 2037 */
4266 "%A %b %d %H:%M:%S %Y"
4270 for (i = 0; i < SZ(time_formats); i++)
4273 * Zero out gmt to prevent time zone offsets.
4274 * Documented to be required for GNU libc.
4276 memset(&gmt, 0, sizeof(gmt));
4278 if (NULL != strptime(header_time, time_formats[i], &gmt))
4280 /* Sanity check for GNU libc. */
4281 if (gmt.tm_year < 0)
4283 log_error(LOG_LEVEL_HEADER,
4284 "Failed to parse '%s' using '%s'. Moving on.",
4285 header_time, time_formats[i]);
4288 *result = timegm(&gmt);
4290 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4292 * Verify that parsing the date recreated from the first
4293 * parse operation gets the previous result. If it doesn't,
4294 * either strptime() or strftime() are malfunctioning.
4296 * We could string-compare the recreated date with the original
4297 * header date, but this leads to false positives as strptime()
4298 * may let %a accept all day formats while strftime() will only
4302 char recreated_date[100];
4306 tm = gmtime(result);
4307 strftime(recreated_date, sizeof(recreated_date), time_formats[i], tm);
4308 memset(&gmt, 0, sizeof(gmt));
4309 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4311 log_error(LOG_LEVEL_ERROR,
4312 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4313 recreated_date, time_formats[i], header_time);
4316 result2 = timegm(&gmt);
4317 if (*result != result2)
4319 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4320 "Format: '%s'. In: '%s', out: '%s'. %d != %d. Rejecting.",
4321 time_formats[i], header_time, recreated_date, *result, result2);
4331 return JB_ERR_PARSE;
4336 /*********************************************************************
4338 * Function : get_destination_from_headers
4340 * Description : Parse the "Host:" header to get the request's destination.
4341 * Only needed if the client's request was forcefully
4342 * redirected into Privoxy.
4344 * Code mainly copied from client_host() which is currently
4345 * run too late for this purpose.
4348 * 1 : headers = List of headers (one of them hopefully being
4349 * the "Host:" header)
4350 * 2 : http = storage for the result (host, port and hostport).
4352 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4353 * JB_ERR_PARSE if the host header couldn't be found,
4354 * JB_ERR_OK otherwise.
4356 *********************************************************************/
4357 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4363 host = get_header_value(headers, "Host:");
4367 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4368 return JB_ERR_PARSE;
4371 p = strdup_or_die(host);
4373 q = strdup_or_die(p);
4375 freez(http->hostport);
4379 q = strchr(http->host, ':');
4382 /* Terminate hostname and evaluate port string */
4384 http->port = atoi(q);
4388 http->port = http->ssl ? 443 : 80;
4391 /* Rebuild request URL */
4393 http->url = strdup(http->ssl ? "https://" : "http://");
4394 string_append(&http->url, http->hostport);
4395 string_append(&http->url, http->path);
4396 if (http->url == NULL)
4398 return JB_ERR_MEMORY;
4401 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4409 /*********************************************************************
4411 * Function : create_forged_referrer
4413 * Description : Helper for client_referrer to forge a referer as
4414 * 'http://hostname[:port]/' to fool stupid
4415 * checks for in-site links
4418 * 1 : header = Pointer to header pointer
4419 * 2 : hostport = Host and optionally port as string
4421 * Returns : JB_ERR_OK in case of success, or
4422 * JB_ERR_MEMORY in case of memory problems.
4424 *********************************************************************/
4425 static jb_err create_forged_referrer(char **header, const char *hostport)
4427 assert(NULL == *header);
4429 *header = strdup("Referer: http://");
4430 string_append(header, hostport);
4431 string_append(header, "/");
4433 if (NULL == *header)
4435 return JB_ERR_MEMORY;
4438 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4445 /*********************************************************************
4447 * Function : create_fake_referrer
4449 * Description : Helper for client_referrer to create a fake referrer
4450 * based on a string supplied by the user.
4453 * 1 : header = Pointer to header pointer
4454 * 2 : hosthost = Referrer to fake
4456 * Returns : JB_ERR_OK in case of success, or
4457 * JB_ERR_MEMORY in case of memory problems.
4459 *********************************************************************/
4460 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4462 assert(NULL == *header);
4464 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4466 log_error(LOG_LEVEL_HEADER,
4467 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4469 *header = strdup("Referer: ");
4470 string_append(header, fake_referrer);
4472 if (NULL == *header)
4474 return JB_ERR_MEMORY;
4477 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4484 /*********************************************************************
4486 * Function : handle_conditional_hide_referrer_parameter
4488 * Description : Helper for client_referrer to crunch or forge
4489 * the referrer header if the host has changed.
4492 * 1 : header = Pointer to header pointer
4493 * 2 : host = The target host (may include the port)
4494 * 3 : parameter_conditional_block = Boolean to signal
4495 * if we're in conditional-block mode. If not set,
4496 * we're in conditional-forge mode.
4498 * Returns : JB_ERR_OK in case of success, or
4499 * JB_ERR_MEMORY in case of memory problems.
4501 *********************************************************************/
4502 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4503 const char *host, const int parameter_conditional_block)
4505 char *referer = strdup_or_die(*header);
4506 const size_t hostlength = strlen(host);
4507 const char *referer_url = NULL;
4509 /* referer begins with 'Referer: http[s]://' */
4510 if ((hostlength+17) < strlen(referer))
4513 * Shorten referer to make sure the referer is blocked
4514 * if www.example.org/www.example.com-shall-see-the-referer/
4515 * links to www.example.com/
4517 referer[hostlength+17] = '\0';
4519 referer_url = strstr(referer, "http://");
4520 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4522 /* Host has changed, Referer is invalid or a https URL. */
4523 if (parameter_conditional_block)
4525 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4532 return create_forged_referrer(header, host);
4542 /*********************************************************************
4544 * Function : create_content_length_header
4546 * Description : Creates a Content-Length header.
4549 * 1 : content_length = The content length to be used in the header.
4550 * 2 : header = Allocated space to safe the header.
4551 * 3 : buffer_length = The length of the allocated space.
4555 *********************************************************************/
4556 static void create_content_length_header(unsigned long long content_length,
4557 char *header, size_t buffer_length)
4559 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4563 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4564 /*********************************************************************
4566 * Function : get_expected_content_length
4568 * Description : Figures out the content length from a list of headers.
4571 * 1 : headers = List of headers
4573 * Returns : Number of bytes to expect
4575 *********************************************************************/
4576 unsigned long long get_expected_content_length(struct list *headers)
4578 const char *content_length_header;
4579 unsigned long long content_length = 0;
4581 content_length_header = get_header_value(headers, "Content-Length:");
4582 if (content_length_header != NULL)
4584 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4586 log_error(LOG_LEVEL_ERROR,
4587 "Failed to get the Content-Length in %s", content_length_header);
4588 /* XXX: The header will be removed later on */
4593 return content_length;