1 const char parsers_rcs[] = "$Id: parsers.c,v 1.208 2009/09/06 14:10:07 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2009 the
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
45 *********************************************************************/
52 #include <sys/types.h>
62 * Convince GNU's libc to provide a strptime prototype.
71 #define GZIP_IDENTIFIER_1 0x1f
72 #define GZIP_IDENTIFIER_2 0x8b
74 #define GZIP_FLAG_CHECKSUM 0x02
75 #define GZIP_FLAG_EXTRA_FIELDS 0x04
76 #define GZIP_FLAG_FILE_NAME 0x08
77 #define GZIP_FLAG_COMMENT 0x10
78 #define GZIP_FLAG_RESERVED_BITS 0xe0
81 #if !defined(_WIN32) && !defined(__OS2__)
87 #ifdef FEATURE_PTHREAD
89 /* jcc.h is for mutex semapores only */
90 #endif /* def FEATURE_PTHREAD */
95 #include "jbsockets.h"
101 #ifndef HAVE_STRPTIME
102 #include "strptime.h"
105 const char parsers_h_rcs[] = PARSERS_H_VERSION;
107 /* Fix a problem with Solaris. There should be no effect on other
109 * Solaris's isspace() is a macro which uses its argument directly
110 * as an array index. Therefore we need to make sure that high-bit
111 * characters generate +ve values, and ideally we also want to make
112 * the argument match the declared parameter type of "int".
114 * Why did they write a character function that can't take a simple
115 * "char" argument? Doh!
117 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
118 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
120 static char *get_header_line(struct iob *iob);
121 static jb_err scan_headers(struct client_state *csp);
122 static jb_err header_tagger(struct client_state *csp, char *header);
123 static jb_err parse_header_time(const char *header_time, time_t *result);
125 static jb_err crumble (struct client_state *csp, char **header);
126 static jb_err filter_header (struct client_state *csp, char **header);
127 static jb_err client_connection (struct client_state *csp, char **header);
128 static jb_err client_referrer (struct client_state *csp, char **header);
129 static jb_err client_uagent (struct client_state *csp, char **header);
130 static jb_err client_ua (struct client_state *csp, char **header);
131 static jb_err client_from (struct client_state *csp, char **header);
132 static jb_err client_send_cookie (struct client_state *csp, char **header);
133 static jb_err client_x_forwarded (struct client_state *csp, char **header);
134 static jb_err client_accept_encoding (struct client_state *csp, char **header);
135 static jb_err client_te (struct client_state *csp, char **header);
136 static jb_err client_max_forwards (struct client_state *csp, char **header);
137 static jb_err client_host (struct client_state *csp, char **header);
138 static jb_err client_if_modified_since (struct client_state *csp, char **header);
139 static jb_err client_accept_language (struct client_state *csp, char **header);
140 static jb_err client_if_none_match (struct client_state *csp, char **header);
141 static jb_err crunch_client_header (struct client_state *csp, char **header);
142 static jb_err client_x_filter (struct client_state *csp, char **header);
143 static jb_err client_range (struct client_state *csp, char **header);
144 static jb_err server_set_cookie (struct client_state *csp, char **header);
145 static jb_err server_connection (struct client_state *csp, char **header);
146 static jb_err server_content_type (struct client_state *csp, char **header);
147 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
148 static jb_err server_content_md5 (struct client_state *csp, char **header);
149 static jb_err server_content_encoding (struct client_state *csp, char **header);
150 static jb_err server_transfer_coding (struct client_state *csp, char **header);
151 static jb_err server_http (struct client_state *csp, char **header);
152 static jb_err crunch_server_header (struct client_state *csp, char **header);
153 static jb_err server_last_modified (struct client_state *csp, char **header);
154 static jb_err server_content_disposition(struct client_state *csp, char **header);
156 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
157 static jb_err server_save_content_length(struct client_state *csp, char **header);
158 static jb_err server_keep_alive(struct client_state *csp, char **header);
159 static jb_err server_proxy_connection(struct client_state *csp, char **header);
160 static jb_err client_keep_alive(struct client_state *csp, char **header);
161 static jb_err client_save_content_length(struct client_state *csp, char **header);
162 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
164 static jb_err client_host_adder (struct client_state *csp);
165 static jb_err client_xtra_adder (struct client_state *csp);
166 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
167 static jb_err client_connection_header_adder(struct client_state *csp);
168 static jb_err server_connection_adder(struct client_state *csp);
169 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
170 static jb_err server_proxy_connection_adder(struct client_state *csp);
171 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
173 static jb_err create_forged_referrer(char **header, const char *hostport);
174 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
175 static jb_err handle_conditional_hide_referrer_parameter(char **header,
176 const char *host, const int parameter_conditional_block);
177 static void create_content_length_header(unsigned long long content_length,
178 char *header, size_t buffer_length);
181 * List of functions to run on a list of headers.
185 /** The header prefix to match */
188 /** The length of the prefix to match */
191 /** The function to apply to this line */
192 const parser_func_ptr parser;
195 static const struct parsers client_patterns[] = {
196 { "referer:", 8, client_referrer },
197 { "user-agent:", 11, client_uagent },
198 { "ua-", 3, client_ua },
199 { "from:", 5, client_from },
200 { "cookie:", 7, client_send_cookie },
201 { "x-forwarded-for:", 16, client_x_forwarded },
202 { "Accept-Encoding:", 16, client_accept_encoding },
203 { "TE:", 3, client_te },
204 { "Host:", 5, client_host },
205 { "if-modified-since:", 18, client_if_modified_since },
206 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
207 { "Keep-Alive:", 11, client_keep_alive },
208 { "Content-Length:", 15, client_save_content_length },
210 { "Keep-Alive:", 11, crumble },
212 { "connection:", 11, client_connection },
213 { "proxy-connection:", 17, crumble },
214 { "max-forwards:", 13, client_max_forwards },
215 { "Accept-Language:", 16, client_accept_language },
216 { "if-none-match:", 14, client_if_none_match },
217 { "Range:", 6, client_range },
218 { "Request-Range:", 14, client_range },
219 { "If-Range:", 9, client_range },
220 { "X-Filter:", 9, client_x_filter },
221 { "*", 0, crunch_client_header },
222 { "*", 0, filter_header },
226 static const struct parsers server_patterns[] = {
227 { "HTTP/", 5, server_http },
228 { "set-cookie:", 11, server_set_cookie },
229 { "connection:", 11, server_connection },
230 { "Content-Type:", 13, server_content_type },
231 { "Content-MD5:", 12, server_content_md5 },
232 { "Content-Encoding:", 17, server_content_encoding },
233 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
234 { "Content-Length:", 15, server_save_content_length },
235 { "Keep-Alive:", 11, server_keep_alive },
236 { "Proxy-Connection:", 17, server_proxy_connection },
238 { "Keep-Alive:", 11, crumble },
239 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
240 { "Transfer-Encoding:", 18, server_transfer_coding },
241 { "content-disposition:", 20, server_content_disposition },
242 { "Last-Modified:", 14, server_last_modified },
243 { "*", 0, crunch_server_header },
244 { "*", 0, filter_header },
248 static const add_header_func_ptr add_client_headers[] = {
250 client_x_forwarded_for_adder,
252 /* Temporarily disabled: client_accept_encoding_adder, */
253 client_connection_header_adder,
257 static const add_header_func_ptr add_server_headers[] = {
258 server_connection_adder,
259 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
260 server_proxy_connection_adder,
261 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
265 /*********************************************************************
267 * Function : flush_socket
269 * Description : Write any pending "buffered" content.
272 * 1 : fd = file descriptor of the socket to read
273 * 2 : iob = The I/O buffer to flush, usually csp->iob.
275 * Returns : On success, the number of bytes written are returned (zero
276 * indicates nothing was written). On error, -1 is returned,
277 * and errno is set appropriately. If count is zero and the
278 * file descriptor refers to a regular file, 0 will be
279 * returned without causing any other effect. For a special
280 * file, the results are not portable.
282 *********************************************************************/
283 long flush_socket(jb_socket fd, struct iob *iob)
285 long len = iob->eod - iob->cur;
292 if (write_socket(fd, iob->cur, (size_t)len))
296 iob->eod = iob->cur = iob->buf;
302 /*********************************************************************
304 * Function : add_to_iob
306 * Description : Add content to the buffered page, expanding the
307 * buffer if necessary.
310 * 1 : csp = Current client state (buffers, headers, etc...)
311 * 2 : buf = holds the content to be added to the page
312 * 3 : n = number of bytes to be added
314 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
315 * or buffer limit reached.
317 *********************************************************************/
318 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
320 struct iob *iob = csp->iob;
321 size_t used, offset, need, want;
324 if (n <= 0) return JB_ERR_OK;
326 used = (size_t)(iob->eod - iob->buf);
327 offset = (size_t)(iob->cur - iob->buf);
328 need = used + (size_t)n + 1;
331 * If the buffer can't hold the new data, extend it first.
332 * Use the next power of two if possible, else use the actual need.
334 if (need > csp->config->buffer_limit)
336 log_error(LOG_LEVEL_INFO,
337 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
338 need, csp->config->buffer_limit);
339 return JB_ERR_MEMORY;
342 if (need > iob->size)
344 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
346 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
350 else if (NULL != (p = (char *)realloc(iob->buf, need)))
356 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
357 return JB_ERR_MEMORY;
360 /* Update the iob pointers */
361 iob->cur = p + offset;
366 /* copy the new data into the iob buffer */
367 memcpy(iob->eod, buf, (size_t)n);
369 /* point to the end of the data */
372 /* null terminate == cheap insurance */
381 /*********************************************************************
383 * Function : decompress_iob
385 * Description : Decompress buffered page, expanding the
386 * buffer as necessary. csp->iob->cur
387 * should point to the the beginning of the
388 * compressed data block.
391 * 1 : csp = Current client state (buffers, headers, etc...)
393 * Returns : JB_ERR_OK on success,
394 * JB_ERR_MEMORY if out-of-memory limit reached, and
395 * JB_ERR_COMPRESS if error decompressing buffer.
397 *********************************************************************/
398 jb_err decompress_iob(struct client_state *csp)
400 char *buf; /* new, uncompressed buffer */
401 char *cur; /* Current iob position (to keep the original
402 * iob->cur unmodified if we return early) */
403 size_t bufsize; /* allocated size of the new buffer */
404 size_t old_size; /* Content size before decompression */
405 size_t skip_size; /* Number of bytes at the beginning of the iob
406 that we should NOT decompress. */
407 int status; /* return status of the inflate() call */
408 z_stream zstr; /* used by calls to zlib */
410 assert(csp->iob->cur - csp->iob->buf > 0);
411 assert(csp->iob->eod - csp->iob->cur > 0);
413 bufsize = csp->iob->size;
414 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
415 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
419 if (bufsize < (size_t)10)
422 * This is to protect the parsing of gzipped data,
423 * but it should(?) be valid for deflated data also.
425 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
426 return JB_ERR_COMPRESS;
429 if (csp->content_type & CT_GZIP)
432 * Our task is slightly complicated by the facts that data
433 * compressed by gzip does not include a zlib header, and
434 * that there is no easily accessible interface in zlib to
435 * handle a gzip header. We strip off the gzip header by
436 * hand, and later inform zlib not to expect a header.
440 * Strip off the gzip header. Please see RFC 1952 for more
441 * explanation of the appropriate fields.
443 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
444 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
445 || (*cur++ != Z_DEFLATED))
447 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
448 return JB_ERR_COMPRESS;
453 if (flags & GZIP_FLAG_RESERVED_BITS)
455 /* The gzip header has reserved bits set; bail out. */
456 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
457 return JB_ERR_COMPRESS;
461 * Skip mtime (4 bytes), extra flags (1 byte)
462 * and OS type (1 byte).
466 /* Skip extra fields if necessary. */
467 if (flags & GZIP_FLAG_EXTRA_FIELDS)
470 * Skip a given number of bytes, specified
471 * as a 16-bit little-endian value.
473 * XXX: this code is untested and should probably be removed.
477 skip_bytes += *cur++ << 8;
480 * The number of bytes to skip should be positive
481 * and we'd like to stay in the buffer.
483 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
485 log_error(LOG_LEVEL_ERROR,
486 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
488 return JB_ERR_COMPRESS;
490 log_error(LOG_LEVEL_INFO,
491 "Skipping %d bytes for gzip compression. Does this sound right?",
496 /* Skip the filename if necessary. */
497 if (flags & GZIP_FLAG_FILE_NAME)
499 /* A null-terminated string is supposed to follow. */
500 while (*cur++ && (cur < csp->iob->eod));
503 /* Skip the comment if necessary. */
504 if (flags & GZIP_FLAG_COMMENT)
506 /* A null-terminated string is supposed to follow. */
507 while (*cur++ && (cur < csp->iob->eod));
510 /* Skip the CRC if necessary. */
511 if (flags & GZIP_FLAG_CHECKSUM)
516 if (cur >= csp->iob->eod)
519 * If the current position pointer reached or passed
520 * the buffer end, we were obviously tricked to skip
523 log_error(LOG_LEVEL_ERROR,
524 "Malformed gzip header detected. Aborting decompression.");
525 return JB_ERR_COMPRESS;
529 else if (csp->content_type & CT_DEFLATE)
532 * XXX: The debug level should be lowered
533 * before the next stable release.
535 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
537 * In theory (that is, according to RFC 1950), deflate-compressed
538 * data should begin with a two-byte zlib header and have an
539 * adler32 checksum at the end. It seems that in practice only
540 * the raw compressed data is sent. Note that this means that
541 * we are not RFC 1950-compliant here, but the advantage is that
542 * this actually works. :)
544 * We add a dummy null byte to tell zlib where the data ends,
545 * and later inform it not to expect a header.
547 * Fortunately, add_to_iob() has thoughtfully null-terminated
548 * the buffer; we can just increment the end pointer to include
555 log_error(LOG_LEVEL_ERROR,
556 "Unable to determine compression format for decompression");
557 return JB_ERR_COMPRESS;
560 /* Set up the fields required by zlib. */
561 zstr.next_in = (Bytef *)cur;
562 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
563 zstr.zalloc = Z_NULL;
565 zstr.opaque = Z_NULL;
568 * Passing -MAX_WBITS to inflateInit2 tells the library
569 * that there is no zlib header.
571 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
573 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
574 return JB_ERR_COMPRESS;
578 * Next, we allocate new storage for the inflated data.
579 * We don't modify the existing iob yet, so in case there
580 * is error in decompression we can recover gracefully.
582 buf = zalloc(bufsize);
585 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
586 return JB_ERR_MEMORY;
589 assert(bufsize >= skip_size);
590 memcpy(buf, csp->iob->buf, skip_size);
591 zstr.avail_out = (uInt)(bufsize - skip_size);
592 zstr.next_out = (Bytef *)buf + skip_size;
594 /* Try to decompress the whole stream in one shot. */
595 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
597 /* We need to allocate more memory for the output buffer. */
599 char *tmpbuf; /* used for realloc'ing the buffer */
600 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
602 if (0 == zstr.avail_in)
605 * If zlib wants more data then there's a problem, because
606 * the complete compressed file should have been buffered.
608 log_error(LOG_LEVEL_ERROR,
609 "Unexpected end of compressed iob. Using what we got so far.");
614 * If we tried the limit and still didn't have enough
615 * memory, just give up.
617 if (bufsize == csp->config->buffer_limit)
619 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
620 return JB_ERR_MEMORY;
623 /* Try doubling the buffer size each time. */
626 /* Don't exceed the buffer limit. */
627 if (bufsize > csp->config->buffer_limit)
629 bufsize = csp->config->buffer_limit;
632 /* Try to allocate the new buffer. */
633 tmpbuf = realloc(buf, bufsize);
636 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
638 return JB_ERR_MEMORY;
642 char *oldnext_out = (char *)zstr.next_out;
645 * Update the fields for inflate() to use the new
646 * buffer, which may be in a location different from
649 zstr.avail_out += (uInt)(bufsize - oldbufsize);
650 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
653 * Compare with an uglier method of calculating these values
654 * that doesn't require the extra oldbufsize variable.
656 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
657 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
663 if (Z_STREAM_ERROR == inflateEnd(&zstr))
665 log_error(LOG_LEVEL_ERROR,
666 "Inconsistent stream state after decompression: %s", zstr.msg);
668 * XXX: Intentionally no return.
670 * According to zlib.h, Z_STREAM_ERROR is returned
671 * "if the stream state was inconsistent".
673 * I assume in this case inflate()'s status
674 * would also be something different than Z_STREAM_END
675 * so this check should be redundant, but lets see.
679 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
682 * We failed to decompress the stream and it's
683 * not simply because of missing data.
685 log_error(LOG_LEVEL_ERROR,
686 "Unexpected error while decompressing to the buffer (iob): %s",
688 return JB_ERR_COMPRESS;
692 * Finally, we can actually update the iob, since the
693 * decompression was successful. First, free the old
696 freez(csp->iob->buf);
698 /* Now, update the iob to use the new buffer. */
700 csp->iob->cur = csp->iob->buf + skip_size;
701 csp->iob->eod = (char *)zstr.next_out;
702 csp->iob->size = bufsize;
705 * Make sure the new uncompressed iob obeys some minimal
706 * consistency conditions.
708 if ((csp->iob->buf < csp->iob->cur)
709 && (csp->iob->cur <= csp->iob->eod)
710 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
712 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
713 if (new_size > (size_t)0)
715 log_error(LOG_LEVEL_RE_FILTER,
716 "Decompression successful. Old size: %d, new size: %d.",
721 /* zlib thinks this is OK, so lets do the same. */
722 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
727 /* It seems that zlib did something weird. */
728 log_error(LOG_LEVEL_ERROR,
729 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
730 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
731 csp->iob->eod, csp->iob->buf + csp->iob->size);
732 return JB_ERR_COMPRESS;
738 #endif /* defined(FEATURE_ZLIB) */
741 /*********************************************************************
743 * Function : string_move
745 * Description : memmove wrapper to move the last part of a string
746 * towards the beginning, overwriting the part in
747 * the middle. strlcpy() can't be used here as the
751 * 1 : dst = Destination to overwrite
752 * 2 : src = Source to move.
756 *********************************************************************/
757 static void string_move(char *dst, char *src)
761 /* +1 to copy the terminating nul as well. */
762 memmove(dst, src, strlen(src)+1);
766 /*********************************************************************
768 * Function : normalize_lws
770 * Description : Reduces unquoted linear white space in headers
771 * to a single space in accordance with RFC 2616 2.2.
772 * This simplifies parsing and filtering later on.
774 * XXX: Remove log messages before
775 * the next stable release?
778 * 1 : header = A header with linear white space to reduce.
782 *********************************************************************/
783 static void normalize_lws(char *header)
789 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
793 while (ijb_isspace(*q))
797 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
803 log_error(LOG_LEVEL_HEADER,
804 "Converting tab to space in '%s'", header);
809 char *end_of_token = strstr(p+1, "\"");
811 if (NULL != end_of_token)
813 /* Don't mess with quoted text. */
818 log_error(LOG_LEVEL_HEADER,
819 "Ignoring single quote in '%s'", header);
825 p = strchr(header, ':');
826 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
829 * There's still space before the colon.
837 /*********************************************************************
839 * Function : get_header
841 * Description : This (odd) routine will parse the csp->iob
842 * to get the next complete header.
845 * 1 : iob = The I/O buffer to parse, usually csp->iob.
847 * Returns : Any one of the following:
849 * 1) a pointer to a dynamically allocated string that contains a header line
850 * 2) NULL indicating that the end of the header was reached
851 * 3) "" indicating that the end of the iob was reached before finding
852 * a complete header line.
854 *********************************************************************/
855 char *get_header(struct iob *iob)
859 header = get_header_line(iob);
861 if ((header == NULL) || (*header == '\0'))
864 * No complete header read yet, tell the client.
869 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
872 * Header spans multiple lines, append the next one.
874 char *continued_header;
876 continued_header = get_header_line(iob);
877 if ((continued_header == NULL) || (*continued_header == '\0'))
880 * No complete header read yet, return what we got.
881 * XXX: Should "unread" header instead.
883 log_error(LOG_LEVEL_INFO,
884 "Failed to read a multi-line header properly: '%s'",
889 if (JB_ERR_OK != string_join(&header, continued_header))
891 log_error(LOG_LEVEL_FATAL,
892 "Out of memory while appending multiple headers.");
896 /* XXX: remove before next stable release. */
897 log_error(LOG_LEVEL_HEADER,
898 "Merged multiple header lines to: '%s'",
903 normalize_lws(header);
910 /*********************************************************************
912 * Function : get_header_line
914 * Description : This (odd) routine will parse the csp->iob
915 * to get the next header line.
918 * 1 : iob = The I/O buffer to parse, usually csp->iob.
920 * Returns : Any one of the following:
922 * 1) a pointer to a dynamically allocated string that contains a header line
923 * 2) NULL indicating that the end of the header was reached
924 * 3) "" indicating that the end of the iob was reached before finding
925 * a complete header line.
927 *********************************************************************/
928 static char *get_header_line(struct iob *iob)
932 if ((iob->cur == NULL)
933 || ((p = strchr(iob->cur, '\n')) == NULL))
935 return(""); /* couldn't find a complete header */
940 ret = strdup(iob->cur);
943 /* FIXME No way to handle error properly */
944 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
950 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
952 /* is this a blank line (i.e. the end of the header) ? */
964 /*********************************************************************
966 * Function : get_header_value
968 * Description : Get the value of a given header from a chained list
969 * of header lines or return NULL if no such header is
970 * present in the list.
973 * 1 : header_list = pointer to list
974 * 2 : header_name = string with name of header to look for.
975 * Trailing colon required, capitalization
978 * Returns : NULL if not found, else value of header
980 *********************************************************************/
981 char *get_header_value(const struct list *header_list, const char *header_name)
983 struct list_entry *cur_entry;
989 length = strlen(header_name);
991 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
995 if (!strncmpic(cur_entry->str, header_name, length))
998 * Found: return pointer to start of value
1000 ret = cur_entry->str + length;
1001 while (*ret && ijb_isspace(*ret)) ret++;
1015 /*********************************************************************
1017 * Function : scan_headers
1019 * Description : Scans headers, applies tags and updates action bits.
1022 * 1 : csp = Current client state (buffers, headers, etc...)
1024 * Returns : JB_ERR_OK
1026 *********************************************************************/
1027 static jb_err scan_headers(struct client_state *csp)
1029 struct list_entry *h; /* Header */
1030 jb_err err = JB_ERR_OK;
1032 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1034 /* Header crunch()ed in previous run? -> ignore */
1035 if (h->str == NULL) continue;
1036 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1037 err = header_tagger(csp, h->str);
1044 /*********************************************************************
1048 * Description : add, delete or modify lines in the HTTP header streams.
1049 * On entry, it receives a linked list of headers space
1050 * that was allocated dynamically (both the list nodes
1051 * and the header contents).
1053 * As a side effect it frees the space used by the original
1057 * 1 : csp = Current client state (buffers, headers, etc...)
1058 * 2 : filter_server_headers = Boolean to switch between
1059 * server and header filtering.
1061 * Returns : JB_ERR_OK in case off success, or
1062 * JB_ERR_MEMORY on out-of-memory error.
1064 *********************************************************************/
1065 jb_err sed(struct client_state *csp, int filter_server_headers)
1067 /* XXX: use more descriptive names. */
1068 struct list_entry *p;
1069 const struct parsers *v;
1070 const add_header_func_ptr *f;
1071 jb_err err = JB_ERR_OK;
1073 if (filter_server_headers)
1075 v = server_patterns;
1076 f = add_server_headers;
1080 v = client_patterns;
1081 f = add_client_headers;
1086 while ((err == JB_ERR_OK) && (v->str != NULL))
1088 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1090 /* Header crunch()ed in previous run? -> ignore */
1091 if (p->str == NULL) continue;
1093 /* Does the current parser handle this header? */
1094 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1095 (v->len == CHECK_EVERY_HEADER_REMAINING))
1097 err = v->parser(csp, &(p->str));
1103 /* place additional headers on the csp->headers list */
1104 while ((err == JB_ERR_OK) && (*f))
1114 /*********************************************************************
1116 * Function : update_server_headers
1118 * Description : Updates server headers after the body has been modified.
1121 * 1 : csp = Current client state (buffers, headers, etc...)
1123 * Returns : JB_ERR_OK in case off success, or
1124 * JB_ERR_MEMORY on out-of-memory error.
1126 *********************************************************************/
1127 jb_err update_server_headers(struct client_state *csp)
1129 jb_err err = JB_ERR_OK;
1131 static const struct parsers server_patterns_light[] = {
1132 { "Content-Length:", 15, server_adjust_content_length },
1133 { "Transfer-Encoding:", 18, server_transfer_coding },
1135 { "Content-Encoding:", 17, server_content_encoding },
1136 #endif /* def FEATURE_ZLIB */
1140 if (strncmpic(csp->http->cmd, "HEAD", 4))
1142 const struct parsers *v;
1143 struct list_entry *p;
1145 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1147 for (p = csp->headers->first; (err == JB_ERR_OK) && (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)
1155 err = v->parser(csp, (char **)&(p->str));
1161 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1162 if ((JB_ERR_OK == err)
1163 && (csp->flags & CSP_FLAG_MODIFIED)
1164 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1165 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1169 create_content_length_header(csp->content_length, header, sizeof(header));
1170 err = enlist(csp->headers, header);
1171 if (JB_ERR_OK == err)
1173 log_error(LOG_LEVEL_HEADER,
1174 "Content modified with no Content-Length header set. "
1175 "Created: %s.", header);
1178 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1184 /*********************************************************************
1186 * Function : header_tagger
1188 * Description : Executes all text substitutions from applying
1189 * tag actions and saves the result as tag.
1191 * XXX: Shares enough code with filter_header() and
1192 * pcrs_filter_response() to warrant some helper functions.
1195 * 1 : csp = Current client state (buffers, headers, etc...)
1196 * 2 : header = Header that is used as tagger input
1198 * Returns : JB_ERR_OK on success and always succeeds
1200 *********************************************************************/
1201 static jb_err header_tagger(struct client_state *csp, char *header)
1203 int wanted_filter_type;
1204 int multi_action_index;
1208 struct file_list *fl;
1209 struct re_filterfile_spec *b;
1210 struct list_entry *tag_name;
1212 int found_filters = 0;
1213 const size_t header_length = strlen(header);
1215 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1217 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1218 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1222 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1223 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1226 /* Check if there are any filters */
1227 for (i = 0; i < MAX_AF_FILES; i++)
1240 if (0 == found_filters)
1242 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1243 "tagging enabled, but no taggers available.");
1247 for (i = 0; i < MAX_AF_FILES; i++)
1250 if ((NULL == fl) || (NULL == fl->f))
1253 * Either there are no filter files
1254 * left, or this filter file just
1255 * contains no valid filters.
1257 * Continue to be sure we don't miss
1258 * valid filter files that are chained
1259 * after empty or invalid ones.
1264 /* For all filters, */
1265 for (b = fl->f; b; b = b->next)
1267 if (b->type != wanted_filter_type)
1269 /* skip the ones we don't care about, */
1272 /* leaving only taggers that could apply, of which we use the ones, */
1273 for (tag_name = csp->action->multi[multi_action_index]->first;
1274 NULL != tag_name; tag_name = tag_name->next)
1276 /* that do apply, and */
1277 if (strcmp(b->name, tag_name->str) == 0)
1279 char *modified_tag = NULL;
1281 size_t size = header_length;
1282 pcrs_job *joblist = b->joblist;
1284 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1286 if (NULL == joblist)
1288 log_error(LOG_LEVEL_RE_FILTER,
1289 "Tagger %s has empty joblist. Nothing to do.", b->name);
1293 /* execute their pcrs_joblist on the header. */
1294 for (job = joblist; NULL != job; job = job->next)
1296 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1300 /* Success, continue with the modified version. */
1309 /* Tagger doesn't match */
1312 /* Regex failure, log it but continue anyway. */
1313 assert(NULL != header);
1314 log_error(LOG_LEVEL_ERROR,
1315 "Problems with tagger \'%s\' and header \'%s\': %s",
1316 b->name, *header, pcrs_strerror(hits));
1318 freez(modified_tag);
1322 if (b->dynamic) pcrs_free_joblist(joblist);
1324 /* If this tagger matched */
1330 * There is to technical limitation which makes
1331 * it impossible to use empty tags, but I assume
1332 * no one would do it intentionally.
1335 log_error(LOG_LEVEL_INFO,
1336 "Tagger \'%s\' created an empty tag. Ignored.",
1341 if (!list_contains_item(csp->tags, tag))
1343 if (JB_ERR_OK != enlist(csp->tags, tag))
1345 log_error(LOG_LEVEL_ERROR,
1346 "Insufficient memory to add tag \'%s\', "
1347 "based on tagger \'%s\' and header \'%s\'",
1348 tag, b->name, *header);
1352 char *action_message;
1354 * update the action bits right away, to make
1355 * tagging based on tags set by earlier taggers
1356 * of the same kind possible.
1358 if (update_action_bits_for_tag(csp, tag))
1360 action_message = "Action bits updated accordingly.";
1364 action_message = "No action bits update necessary.";
1367 log_error(LOG_LEVEL_HEADER,
1368 "Tagger \'%s\' added tag \'%s\'. %s",
1369 b->name, tag, action_message);
1374 /* XXX: Is this log-worthy? */
1375 log_error(LOG_LEVEL_HEADER,
1376 "Tagger \'%s\' didn't add tag \'%s\'. "
1377 "Tag already present", b->name, tag);
1380 } /* if the tagger matched */
1381 } /* if the tagger applies */
1382 } /* for every tagger that could apply */
1383 } /* for all filters */
1384 } /* for all filter files */
1389 /* here begins the family of parser functions that reformat header lines */
1391 /*********************************************************************
1393 * Function : filter_header
1395 * Description : Executes all text substitutions from all applying
1396 * +(server|client)-header-filter actions on the header.
1397 * Most of the code was copied from pcrs_filter_response,
1398 * including the rather short variable names
1401 * 1 : csp = Current client state (buffers, headers, etc...)
1402 * 2 : header = On input, pointer to header to modify.
1403 * On output, pointer to the modified header, or NULL
1404 * to remove the header. This function frees the
1405 * original string if necessary.
1407 * Returns : JB_ERR_OK on success and always succeeds
1409 *********************************************************************/
1410 static jb_err filter_header(struct client_state *csp, char **header)
1414 size_t size = strlen(*header);
1416 char *newheader = NULL;
1419 struct file_list *fl;
1420 struct re_filterfile_spec *b;
1421 struct list_entry *filtername;
1423 int i, found_filters = 0;
1424 int wanted_filter_type;
1425 int multi_action_index;
1427 if (csp->flags & CSP_FLAG_NO_FILTERING)
1432 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1434 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1435 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1439 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1440 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1444 * Need to check the set of re_filterfiles...
1446 for (i = 0; i < MAX_AF_FILES; i++)
1459 if (0 == found_filters)
1461 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1462 "header filtering enabled, but no matching filters available.");
1466 for (i = 0; i < MAX_AF_FILES; i++)
1469 if ((NULL == fl) || (NULL == fl->f))
1472 * Either there are no filter files
1473 * left, or this filter file just
1474 * contains no valid filters.
1476 * Continue to be sure we don't miss
1477 * valid filter files that are chained
1478 * after empty or invalid ones.
1483 * For all applying +filter actions, look if a filter by that
1484 * name exists and if yes, execute its pcrs_joblist on the
1487 for (b = fl->f; b; b = b->next)
1489 if (b->type != wanted_filter_type)
1491 /* Skip other filter types */
1495 for (filtername = csp->action->multi[multi_action_index]->first;
1496 filtername ; filtername = filtername->next)
1498 if (strcmp(b->name, filtername->str) == 0)
1500 int current_hits = 0;
1501 pcrs_job *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;
1553 * Additionally checking for hits is important because if
1554 * the continue hack is triggered, server headers can
1555 * arrive empty to separate multiple heads from each other.
1557 if ((0 == size) && hits)
1559 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1567 /*********************************************************************
1569 * Function : server_connection
1571 * Description : Makes sure a proper "Connection:" header is
1572 * set and signals connection_header_adder to
1576 * 1 : csp = Current client state (buffers, headers, etc...)
1577 * 2 : header = On input, pointer to header to modify.
1578 * On output, pointer to the modified header, or NULL
1579 * to remove the header. This function frees the
1580 * original string if necessary.
1582 * Returns : JB_ERR_OK on success, or
1583 * JB_ERR_MEMORY on out-of-memory error.
1585 *********************************************************************/
1586 static jb_err server_connection(struct client_state *csp, char **header)
1588 if (!strcmpic(*header, "Connection: keep-alive")
1589 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1590 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1594 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1595 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1597 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1600 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1602 log_error(LOG_LEVEL_HEADER,
1603 "Keeping the server header '%s' around.", *header);
1606 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1608 char *old_header = *header;
1610 *header = strdup("Connection: close");
1613 return JB_ERR_MEMORY;
1615 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1620 /* Signal server_connection_adder() to return early. */
1621 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1627 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1628 /*********************************************************************
1630 * Function : server_keep_alive
1632 * Description : Stores the server's keep alive timeout.
1635 * 1 : csp = Current client state (buffers, headers, etc...)
1636 * 2 : header = On input, pointer to header to modify.
1637 * On output, pointer to the modified header, or NULL
1638 * to remove the header. This function frees the
1639 * original string if necessary.
1641 * Returns : JB_ERR_OK.
1643 *********************************************************************/
1644 static jb_err server_keep_alive(struct client_state *csp, char **header)
1646 unsigned int keep_alive_timeout;
1647 const char *timeout_position = strstr(*header, "timeout=");
1649 if ((NULL == timeout_position)
1650 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1652 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1656 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1658 log_error(LOG_LEVEL_HEADER,
1659 "Reducing keep-alive timeout from %u to %u.",
1660 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1661 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1665 /* XXX: Is this log worthy? */
1666 log_error(LOG_LEVEL_HEADER,
1667 "Server keep-alive timeout is %u. Sticking with %u.",
1668 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1670 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1677 /*********************************************************************
1679 * Function : server_proxy_connection
1681 * Description : Figures out whether or not we should add a
1682 * Proxy-Connection header.
1685 * 1 : csp = Current client state (buffers, headers, etc...)
1686 * 2 : header = On input, pointer to header to modify.
1687 * On output, pointer to the modified header, or NULL
1688 * to remove the header. This function frees the
1689 * original string if necessary.
1691 * Returns : JB_ERR_OK.
1693 *********************************************************************/
1694 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1696 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1701 /*********************************************************************
1703 * Function : client_keep_alive
1705 * Description : Stores the client's keep alive timeout.
1708 * 1 : csp = Current client state (buffers, headers, etc...)
1709 * 2 : header = On input, pointer to header to modify.
1710 * On output, pointer to the modified header, or NULL
1711 * to remove the header. This function frees the
1712 * original string if necessary.
1714 * Returns : JB_ERR_OK.
1716 *********************************************************************/
1717 static jb_err client_keep_alive(struct client_state *csp, char **header)
1719 unsigned int keep_alive_timeout;
1720 const char *timeout_position = strstr(*header, ": ");
1722 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1724 log_error(LOG_LEVEL_HEADER,
1725 "keep-alive support is disabled. Crunching: %s.", *header);
1730 if ((NULL == timeout_position)
1731 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1733 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1737 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1739 log_error(LOG_LEVEL_HEADER,
1740 "Reducing keep-alive timeout from %u to %u.",
1741 csp->config->keep_alive_timeout, keep_alive_timeout);
1742 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1746 /* XXX: Is this log worthy? */
1747 log_error(LOG_LEVEL_HEADER,
1748 "Client keep-alive timeout is %u. Sticking with %u.",
1749 keep_alive_timeout, csp->config->keep_alive_timeout);
1757 /*********************************************************************
1759 * Function : get_content_length
1761 * Description : Gets the content length specified in a
1762 * Content-Length header.
1765 * 1 : header = The Content-Length header.
1766 * 2 : length = Storage to return the value.
1768 * Returns : JB_ERR_OK on success, or
1769 * JB_ERR_PARSE if no value is recognized.
1771 *********************************************************************/
1772 static jb_err get_content_length(const char *header, unsigned long long *length)
1774 assert(header[14] == ':');
1777 assert(sizeof(unsigned long long) > 4);
1778 if (1 != sscanf(header+14, ": %I64u", length))
1780 if (1 != sscanf(header+14, ": %llu", length))
1783 return JB_ERR_PARSE;
1790 /*********************************************************************
1792 * Function : client_save_content_length
1794 * Description : Save the Content-Length sent by the client.
1797 * 1 : csp = Current client state (buffers, headers, etc...)
1798 * 2 : header = On input, pointer to header to modify.
1799 * On output, pointer to the modified header, or NULL
1800 * to remove the header. This function frees the
1801 * original string if necessary.
1803 * Returns : JB_ERR_OK on success, or
1804 * JB_ERR_MEMORY on out-of-memory error.
1806 *********************************************************************/
1807 static jb_err client_save_content_length(struct client_state *csp, char **header)
1809 unsigned long long content_length = 0;
1811 assert(*(*header+14) == ':');
1813 if (JB_ERR_OK != get_content_length(*header, &content_length))
1815 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1820 csp->expected_client_content_length = content_length;
1825 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1829 /*********************************************************************
1831 * Function : client_connection
1833 * Description : Makes sure a proper "Connection:" header is
1834 * set and signals connection_header_adder
1838 * 1 : csp = Current client state (buffers, headers, etc...)
1839 * 2 : header = On input, pointer to header to modify.
1840 * On output, pointer to the modified header, or NULL
1841 * to remove the header. This function frees the
1842 * original string if necessary.
1844 * Returns : JB_ERR_OK on success, or
1845 * JB_ERR_MEMORY on out-of-memory error.
1847 *********************************************************************/
1848 static jb_err client_connection(struct client_state *csp, char **header)
1850 static const char connection_close[] = "Connection: close";
1852 if (!strcmpic(*header, connection_close))
1854 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1855 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1857 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1859 log_error(LOG_LEVEL_HEADER,
1860 "Removing \'%s\' to imply keep-alive.", *header);
1865 char *old_header = *header;
1867 *header = strdup("Connection: keep-alive");
1870 return JB_ERR_MEMORY;
1872 log_error(LOG_LEVEL_HEADER,
1873 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1879 log_error(LOG_LEVEL_HEADER,
1880 "Keeping the client header '%s' around. "
1881 "The connection will not be kept alive.",
1883 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1886 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1888 log_error(LOG_LEVEL_HEADER,
1889 "Keeping the client header '%s' around. "
1890 "The server connection will be kept alive if possible.",
1892 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1893 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1897 char *old_header = *header;
1899 *header = strdup(connection_close);
1902 return JB_ERR_MEMORY;
1904 log_error(LOG_LEVEL_HEADER,
1905 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1909 /* Signal client_connection_adder() to return early. */
1910 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1916 /*********************************************************************
1918 * Function : crumble
1920 * Description : This is called if a header matches a pattern to "crunch"
1923 * 1 : csp = Current client state (buffers, headers, etc...)
1924 * 2 : header = On input, pointer to header to modify.
1925 * On output, pointer to the modified header, or NULL
1926 * to remove the header. This function frees the
1927 * original string if necessary.
1929 * Returns : JB_ERR_OK on success, or
1930 * JB_ERR_MEMORY on out-of-memory error.
1932 *********************************************************************/
1933 static jb_err crumble(struct client_state *csp, char **header)
1936 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1942 /*********************************************************************
1944 * Function : crunch_server_header
1946 * Description : Crunch server header if it matches a string supplied by the
1947 * user. Called from `sed'.
1950 * 1 : csp = Current client state (buffers, headers, etc...)
1951 * 2 : header = On input, pointer to header to modify.
1952 * On output, pointer to the modified header, or NULL
1953 * to remove the header. This function frees the
1954 * original string if necessary.
1956 * Returns : JB_ERR_OK on success and always succeeds
1958 *********************************************************************/
1959 static jb_err crunch_server_header(struct client_state *csp, char **header)
1961 const char *crunch_pattern;
1963 /* Do we feel like crunching? */
1964 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1966 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1968 /* Is the current header the lucky one? */
1969 if (strstr(*header, crunch_pattern))
1971 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1980 /*********************************************************************
1982 * Function : server_content_type
1984 * Description : Set the content-type for filterable types (text/.*,
1985 * .*xml.*, javascript and image/gif) unless filtering has been
1986 * forbidden (CT_TABOO) while parsing earlier headers.
1987 * NOTE: Since text/plain is commonly used by web servers
1988 * for files whose correct type is unknown, we don't
1989 * set CT_TEXT for it.
1992 * 1 : csp = Current client state (buffers, headers, etc...)
1993 * 2 : header = On input, pointer to header to modify.
1994 * On output, pointer to the modified header, or NULL
1995 * to remove the header. This function frees the
1996 * original string if necessary.
1998 * Returns : JB_ERR_OK on success, or
1999 * JB_ERR_MEMORY on out-of-memory error.
2001 *********************************************************************/
2002 static jb_err server_content_type(struct client_state *csp, char **header)
2004 /* Remove header if it isn't the first Content-Type header */
2005 if ((csp->content_type & CT_DECLARED))
2008 * Another, slightly slower, way to see if
2009 * we already parsed another Content-Type header.
2011 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2013 log_error(LOG_LEVEL_ERROR,
2014 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2022 * Signal that the Content-Type has been set.
2024 csp->content_type |= CT_DECLARED;
2026 if (!(csp->content_type & CT_TABOO))
2029 * XXX: The assumption that text/plain is a sign of
2030 * binary data seems to be somewhat unreasonable nowadays
2031 * and should be dropped after 3.0.8 is out.
2033 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2034 || strstr(*header, "xml")
2035 || strstr(*header, "application/x-javascript"))
2037 csp->content_type |= CT_TEXT;
2039 else if (strstr(*header, "image/gif"))
2041 csp->content_type |= CT_GIF;
2046 * Are we messing with the content type?
2048 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2051 * Make sure the user doesn't accidently
2052 * change the content type of binary documents.
2054 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2057 *header = strdup("Content-Type: ");
2058 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2062 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2063 return JB_ERR_MEMORY;
2065 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2069 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2070 "It doesn't look like a content type that should be filtered. "
2071 "Enable force-text-mode if you know what you're doing.", *header);
2079 /*********************************************************************
2081 * Function : server_transfer_coding
2083 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2084 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2085 * - Remove header if body was chunked but has been
2086 * de-chunked for filtering.
2089 * 1 : csp = Current client state (buffers, headers, etc...)
2090 * 2 : header = On input, pointer to header to modify.
2091 * On output, pointer to the modified header, or NULL
2092 * to remove the header. This function frees the
2093 * original string if necessary.
2095 * Returns : JB_ERR_OK on success, or
2096 * JB_ERR_MEMORY on out-of-memory error.
2098 *********************************************************************/
2099 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2102 * Turn off pcrs and gif filtering if body compressed
2104 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2108 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2110 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2111 csp->http->cmd, *header);
2112 #endif /* def FEATURE_ZLIB */
2113 csp->content_type = CT_TABOO;
2117 * Raise flag if body chunked
2119 if (strstr(*header, "chunked"))
2121 csp->flags |= CSP_FLAG_CHUNKED;
2124 * If the body was modified, it has been de-chunked first
2125 * and the header must be removed.
2127 * FIXME: If there is more than one transfer encoding,
2128 * only the "chunked" part should be removed here.
2130 if (csp->flags & CSP_FLAG_MODIFIED)
2132 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2141 /*********************************************************************
2143 * Function : server_content_encoding
2145 * Description : This function is run twice for each request,
2146 * unless FEATURE_ZLIB and filtering are disabled.
2148 * The first run is used to check if the content
2149 * is compressed, if FEATURE_ZLIB is disabled
2150 * filtering is then disabled as well, if FEATURE_ZLIB
2151 * is enabled the content is marked for decompression.
2153 * The second run is used to remove the Content-Encoding
2154 * header if the decompression was successful.
2157 * 1 : csp = Current client state (buffers, headers, etc...)
2158 * 2 : header = On input, pointer to header to modify.
2159 * On output, pointer to the modified header, or NULL
2160 * to remove the header. This function frees the
2161 * original string if necessary.
2163 * Returns : JB_ERR_OK on success, or
2164 * JB_ERR_MEMORY on out-of-memory error.
2166 *********************************************************************/
2167 static jb_err server_content_encoding(struct client_state *csp, char **header)
2170 if ((csp->flags & CSP_FLAG_MODIFIED)
2171 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2174 * We successfully decompressed the content,
2175 * and have to clean the header now, so the
2176 * client no longer expects compressed data..
2178 * XXX: There is a difference between cleaning
2179 * and removing it completely.
2181 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2184 else if (strstr(*header, "gzip"))
2186 /* Mark for gzip decompression */
2187 csp->content_type |= CT_GZIP;
2189 else if (strstr(*header, "deflate"))
2191 /* Mark for zlib decompression */
2192 csp->content_type |= CT_DEFLATE;
2194 else if (strstr(*header, "compress"))
2197 * We can't decompress this; therefore we can't filter
2200 csp->content_type |= CT_TABOO;
2202 #else /* !defined(FEATURE_ZLIB) */
2203 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2206 * Body is compressed, turn off pcrs and gif filtering.
2208 csp->content_type |= CT_TABOO;
2211 * Log a warning if the user expects the content to be filtered.
2213 if ((csp->rlist != NULL) &&
2214 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2216 log_error(LOG_LEVEL_INFO,
2217 "Compressed content detected, content filtering disabled. "
2218 "Consider recompiling Privoxy with zlib support or "
2219 "enable the prevent-compression action.");
2222 #endif /* defined(FEATURE_ZLIB) */
2229 /*********************************************************************
2231 * Function : server_adjust_content_length
2233 * Description : Adjust Content-Length header if we modified
2237 * 1 : csp = Current client state (buffers, headers, etc...)
2238 * 2 : header = On input, pointer to header to modify.
2239 * On output, pointer to the modified header, or NULL
2240 * to remove the header. This function frees the
2241 * original string if necessary.
2243 * Returns : JB_ERR_OK on success, or
2244 * JB_ERR_MEMORY on out-of-memory error.
2246 *********************************************************************/
2247 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2249 /* Regenerate header if the content was modified. */
2250 if (csp->flags & CSP_FLAG_MODIFIED)
2252 const size_t header_length = 50;
2254 *header = malloc(header_length);
2255 if (*header == NULL)
2257 return JB_ERR_MEMORY;
2259 create_content_length_header(csp->content_length, *header, header_length);
2260 log_error(LOG_LEVEL_HEADER,
2261 "Adjusted Content-Length to %llu", csp->content_length);
2268 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2269 /*********************************************************************
2271 * Function : server_save_content_length
2273 * Description : Save the Content-Length sent by the server.
2276 * 1 : csp = Current client state (buffers, headers, etc...)
2277 * 2 : header = On input, pointer to header to modify.
2278 * On output, pointer to the modified header, or NULL
2279 * to remove the header. This function frees the
2280 * original string if necessary.
2282 * Returns : JB_ERR_OK on success, or
2283 * JB_ERR_MEMORY on out-of-memory error.
2285 *********************************************************************/
2286 static jb_err server_save_content_length(struct client_state *csp, char **header)
2288 unsigned long long content_length = 0;
2290 assert(*(*header+14) == ':');
2292 if (JB_ERR_OK != get_content_length(*header, &content_length))
2294 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2299 csp->expected_content_length = content_length;
2300 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2301 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2306 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2309 /*********************************************************************
2311 * Function : server_content_md5
2313 * Description : Crumble any Content-MD5 headers if the document was
2314 * modified. FIXME: Should we re-compute instead?
2317 * 1 : csp = Current client state (buffers, headers, etc...)
2318 * 2 : header = On input, pointer to header to modify.
2319 * On output, pointer to the modified header, or NULL
2320 * to remove the header. This function frees the
2321 * original string if necessary.
2323 * Returns : JB_ERR_OK on success, or
2324 * JB_ERR_MEMORY on out-of-memory error.
2326 *********************************************************************/
2327 static jb_err server_content_md5(struct client_state *csp, char **header)
2329 if (csp->flags & CSP_FLAG_MODIFIED)
2331 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2339 /*********************************************************************
2341 * Function : server_content_disposition
2343 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2344 * Called from `sed'.
2347 * 1 : csp = Current client state (buffers, headers, etc...)
2348 * 2 : header = On input, pointer to header to modify.
2349 * On output, pointer to the modified header, or NULL
2350 * to remove the header. This function frees the
2351 * original string if necessary.
2353 * Returns : JB_ERR_OK on success, or
2354 * JB_ERR_MEMORY on out-of-memory error.
2356 *********************************************************************/
2357 static jb_err server_content_disposition(struct client_state *csp, char **header)
2362 * Are we messing with the Content-Disposition header?
2364 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2370 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2372 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2375 * Blocking content-disposition header
2377 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2384 * Replacing Content-Disposition header
2387 *header = strdup("Content-Disposition: ");
2388 string_append(header, newval);
2390 if (*header != NULL)
2392 log_error(LOG_LEVEL_HEADER,
2393 "Content-Disposition header crunched and replaced with: %s", *header);
2396 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2400 /*********************************************************************
2402 * Function : server_last_modified
2404 * Description : Changes Last-Modified header to the actual date
2405 * to help hide-if-modified-since.
2406 * Called from `sed'.
2409 * 1 : csp = Current client state (buffers, headers, etc...)
2410 * 2 : header = On input, pointer to header to modify.
2411 * On output, pointer to the modified header, or NULL
2412 * to remove the header. This function frees the
2413 * original string if necessary.
2415 * Returns : JB_ERR_OK on success, or
2416 * JB_ERR_MEMORY on out-of-memory error.
2418 *********************************************************************/
2419 static jb_err server_last_modified(struct client_state *csp, char **header)
2422 char buf[BUFFER_SIZE];
2425 #ifdef HAVE_GMTIME_R
2428 struct tm *timeptr = NULL;
2429 time_t now, last_modified;
2430 long int days, hours, minutes, seconds;
2433 * Are we messing with the Last-Modified header?
2435 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2441 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2443 if (0 == strcmpic(newval, "block") )
2446 * Blocking Last-Modified header. Useless but why not.
2448 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2452 else if (0 == strcmpic(newval, "reset-to-request-time"))
2455 * Setting Last-Modified Header to now.
2457 get_http_time(0, buf, sizeof(buf));
2459 *header = strdup("Last-Modified: ");
2460 string_append(header, buf);
2462 if (*header == NULL)
2464 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2468 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2471 else if (0 == strcmpic(newval, "randomize"))
2473 const char *header_time = *header + sizeof("Last-Modified:");
2475 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2477 #ifdef HAVE_GMTIME_R
2478 gmtime_r(&now, &gmt);
2479 #elif defined(MUTEX_LOCKS_AVAILABLE)
2480 privoxy_mutex_lock(&gmtime_mutex);
2482 privoxy_mutex_unlock(&gmtime_mutex);
2486 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2488 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2493 long int rtime = (long int)difftime(now, last_modified);
2496 const int negative_delta = (rtime < 0);
2501 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2503 rtime = pick_from_range(rtime);
2508 last_modified += rtime;
2509 #ifdef HAVE_GMTIME_R
2510 timeptr = gmtime_r(&last_modified, &gmt);
2511 #elif defined(MUTEX_LOCKS_AVAILABLE)
2512 privoxy_mutex_lock(&gmtime_mutex);
2513 timeptr = gmtime(&last_modified);
2514 privoxy_mutex_unlock(&gmtime_mutex);
2516 timeptr = gmtime(&last_modified);
2518 if ((NULL == timeptr) || !strftime(newheader,
2519 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2521 log_error(LOG_LEVEL_ERROR,
2522 "Randomizing '%s' failed. Crunching the header without replacement.",
2529 *header = strdup("Last-Modified: ");
2530 string_append(header, newheader);
2532 if (*header == NULL)
2534 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2535 return JB_ERR_MEMORY;
2538 days = rtime / (3600 * 24);
2539 hours = rtime / 3600 % 24;
2540 minutes = rtime / 60 % 60;
2541 seconds = rtime % 60;
2543 log_error(LOG_LEVEL_HEADER,
2544 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2545 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2546 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2550 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2559 /*********************************************************************
2561 * Function : client_accept_encoding
2563 * Description : Rewrite the client's Accept-Encoding header so that
2564 * if doesn't allow compression, if the action applies.
2565 * Note: For HTTP/1.0 the absence of the header is enough.
2568 * 1 : csp = Current client state (buffers, headers, etc...)
2569 * 2 : header = On input, pointer to header to modify.
2570 * On output, pointer to the modified header, or NULL
2571 * to remove the header. This function frees the
2572 * original string if necessary.
2574 * Returns : JB_ERR_OK on success, or
2575 * JB_ERR_MEMORY on out-of-memory error.
2577 *********************************************************************/
2578 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2580 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2582 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2586 /* Temporarily disable the correct behaviour to
2587 * work around a PHP bug.
2589 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2591 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2592 * if (*header == NULL)
2594 * return JB_ERR_MEMORY;
2605 /*********************************************************************
2607 * Function : client_te
2609 * Description : Rewrite the client's TE header so that
2610 * if doesn't allow compression, if the action applies.
2613 * 1 : csp = Current client state (buffers, headers, etc...)
2614 * 2 : header = On input, pointer to header to modify.
2615 * On output, pointer to the modified header, or NULL
2616 * to remove the header. This function frees the
2617 * original string if necessary.
2619 * Returns : JB_ERR_OK on success, or
2620 * JB_ERR_MEMORY on out-of-memory error.
2622 *********************************************************************/
2623 static jb_err client_te(struct client_state *csp, char **header)
2625 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2628 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2635 /*********************************************************************
2637 * Function : client_referrer
2639 * Description : Handle the "referer" config setting properly.
2640 * Called from `sed'.
2643 * 1 : csp = Current client state (buffers, headers, etc...)
2644 * 2 : header = On input, pointer to header to modify.
2645 * On output, pointer to the modified header, or NULL
2646 * to remove the header. This function frees the
2647 * original string if necessary.
2649 * Returns : JB_ERR_OK on success, or
2650 * JB_ERR_MEMORY on out-of-memory error.
2652 *********************************************************************/
2653 static jb_err client_referrer(struct client_state *csp, char **header)
2655 const char *parameter;
2656 /* booleans for parameters we have to check multiple times */
2657 int parameter_conditional_block;
2658 int parameter_conditional_forge;
2660 #ifdef FEATURE_FORCE_LOAD
2662 * Since the referrer can include the prefix even
2663 * if the request itself is non-forced, we must
2664 * clean it unconditionally.
2666 * XXX: strclean is too broad
2668 strclean(*header, FORCE_PREFIX);
2669 #endif /* def FEATURE_FORCE_LOAD */
2671 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2673 /* Nothing left to do */
2677 parameter = csp->action->string[ACTION_STRING_REFERER];
2678 assert(parameter != NULL);
2679 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2680 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2682 if (!parameter_conditional_block && !parameter_conditional_forge)
2685 * As conditional-block and conditional-forge are the only
2686 * parameters that rely on the original referrer, we can
2687 * remove it now for all the others.
2692 if (0 == strcmpic(parameter, "block"))
2694 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2697 else if (parameter_conditional_block || parameter_conditional_forge)
2699 return handle_conditional_hide_referrer_parameter(header,
2700 csp->http->hostport, parameter_conditional_block);
2702 else if (0 == strcmpic(parameter, "forge"))
2704 return create_forged_referrer(header, csp->http->hostport);
2708 /* interpret parameter as user-supplied referer to fake */
2709 return create_fake_referrer(header, parameter);
2714 /*********************************************************************
2716 * Function : client_accept_language
2718 * Description : Handle the "Accept-Language" config setting properly.
2719 * Called from `sed'.
2722 * 1 : csp = Current client state (buffers, headers, etc...)
2723 * 2 : header = On input, pointer to header to modify.
2724 * On output, pointer to the modified header, or NULL
2725 * to remove the header. This function frees the
2726 * original string if necessary.
2728 * Returns : JB_ERR_OK on success, or
2729 * JB_ERR_MEMORY on out-of-memory error.
2731 *********************************************************************/
2732 static jb_err client_accept_language(struct client_state *csp, char **header)
2737 * Are we messing with the Accept-Language?
2739 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2741 /*I don't think so*/
2745 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2747 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2750 * Blocking Accept-Language header
2752 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2759 * Replacing Accept-Language header
2762 *header = strdup("Accept-Language: ");
2763 string_append(header, newval);
2765 if (*header == NULL)
2767 log_error(LOG_LEVEL_ERROR,
2768 "Insufficient memory. Accept-Language header crunched without replacement.");
2772 log_error(LOG_LEVEL_HEADER,
2773 "Accept-Language header crunched and replaced with: %s", *header);
2776 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2780 /*********************************************************************
2782 * Function : crunch_client_header
2784 * Description : Crunch client header if it matches a string supplied by the
2785 * user. Called from `sed'.
2788 * 1 : csp = Current client state (buffers, headers, etc...)
2789 * 2 : header = On input, pointer to header to modify.
2790 * On output, pointer to the modified header, or NULL
2791 * to remove the header. This function frees the
2792 * original string if necessary.
2794 * Returns : JB_ERR_OK on success and always succeeds
2796 *********************************************************************/
2797 static jb_err crunch_client_header(struct client_state *csp, char **header)
2799 const char *crunch_pattern;
2801 /* Do we feel like crunching? */
2802 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2804 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2806 /* Is the current header the lucky one? */
2807 if (strstr(*header, crunch_pattern))
2809 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2817 /*********************************************************************
2819 * Function : client_uagent
2821 * Description : Handle the "user-agent" config setting properly
2822 * and remember its original value to enable browser
2823 * bug workarounds. Called from `sed'.
2826 * 1 : csp = Current client state (buffers, headers, etc...)
2827 * 2 : header = On input, pointer to header to modify.
2828 * On output, pointer to the modified header, or NULL
2829 * to remove the header. This function frees the
2830 * original string if necessary.
2832 * Returns : JB_ERR_OK on success, or
2833 * JB_ERR_MEMORY on out-of-memory error.
2835 *********************************************************************/
2836 static jb_err client_uagent(struct client_state *csp, char **header)
2840 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2845 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2852 *header = strdup("User-Agent: ");
2853 string_append(header, newval);
2855 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2857 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2861 /*********************************************************************
2863 * Function : client_ua
2865 * Description : Handle "ua-" headers properly. Called from `sed'.
2868 * 1 : csp = Current client state (buffers, headers, etc...)
2869 * 2 : header = On input, pointer to header to modify.
2870 * On output, pointer to the modified header, or NULL
2871 * to remove the header. This function frees the
2872 * original string if necessary.
2874 * Returns : JB_ERR_OK on success, or
2875 * JB_ERR_MEMORY on out-of-memory error.
2877 *********************************************************************/
2878 static jb_err client_ua(struct client_state *csp, char **header)
2880 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2882 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2890 /*********************************************************************
2892 * Function : client_from
2894 * Description : Handle the "from" config setting properly.
2895 * Called from `sed'.
2898 * 1 : csp = Current client state (buffers, headers, etc...)
2899 * 2 : header = On input, pointer to header to modify.
2900 * On output, pointer to the modified header, or NULL
2901 * to remove the header. This function frees the
2902 * original string if necessary.
2904 * Returns : JB_ERR_OK on success, or
2905 * JB_ERR_MEMORY on out-of-memory error.
2907 *********************************************************************/
2908 static jb_err client_from(struct client_state *csp, char **header)
2912 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2919 newval = csp->action->string[ACTION_STRING_FROM];
2922 * Are we blocking the e-mail address?
2924 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2926 log_error(LOG_LEVEL_HEADER, "crunched From!");
2930 log_error(LOG_LEVEL_HEADER, " modified");
2932 *header = strdup("From: ");
2933 string_append(header, newval);
2935 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2939 /*********************************************************************
2941 * Function : client_send_cookie
2943 * Description : Crunches the "cookie" header if necessary.
2944 * Called from `sed'.
2946 * XXX: Stupid name, doesn't send squat.
2949 * 1 : csp = Current client state (buffers, headers, etc...)
2950 * 2 : header = On input, pointer to header to modify.
2951 * On output, pointer to the modified header, or NULL
2952 * to remove the header. This function frees the
2953 * original string if necessary.
2955 * Returns : JB_ERR_OK on success, or
2956 * JB_ERR_MEMORY on out-of-memory error.
2958 *********************************************************************/
2959 static jb_err client_send_cookie(struct client_state *csp, char **header)
2961 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2963 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2971 /*********************************************************************
2973 * Function : client_x_forwarded
2975 * Description : Handle the "x-forwarded-for" config setting properly,
2976 * also used in the add_client_headers list. Called from `sed'.
2979 * 1 : csp = Current client state (buffers, headers, etc...)
2980 * 2 : header = On input, pointer to header to modify.
2981 * On output, pointer to the modified header, or NULL
2982 * to remove the header. This function frees the
2983 * original string if necessary.
2985 * Returns : JB_ERR_OK on success, or
2986 * JB_ERR_MEMORY on out-of-memory error.
2988 *********************************************************************/
2989 jb_err client_x_forwarded(struct client_state *csp, char **header)
2991 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2993 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2995 if (0 == strcmpic(parameter, "block"))
2998 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3000 else if (0 == strcmpic(parameter, "add"))
3002 string_append(header, ", ");
3003 string_append(header, csp->ip_addr_str);
3005 if (*header == NULL)
3007 return JB_ERR_MEMORY;
3009 log_error(LOG_LEVEL_HEADER,
3010 "Appended client IP address to %s", *header);
3011 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3015 log_error(LOG_LEVEL_FATAL,
3016 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3024 /*********************************************************************
3026 * Function : client_max_forwards
3028 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3029 * from the value of the Max-Forwards header field.
3032 * 1 : csp = Current client state (buffers, headers, etc...)
3033 * 2 : header = On input, pointer to header to modify.
3034 * On output, pointer to the modified header, or NULL
3035 * to remove the header. This function frees the
3036 * original string if necessary.
3038 * Returns : JB_ERR_OK on success, or
3039 * JB_ERR_MEMORY on out-of-memory error.
3041 *********************************************************************/
3042 static jb_err client_max_forwards(struct client_state *csp, char **header)
3046 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3047 (0 == strcmpic(csp->http->gpc, "options")))
3049 assert(*(*header+12) == ':');
3050 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3052 if (max_forwards > 0)
3054 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3055 log_error(LOG_LEVEL_HEADER,
3056 "Max-Forwards value for %s request reduced to %d.",
3057 csp->http->gpc, max_forwards);
3059 else if (max_forwards < 0)
3061 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3067 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3076 /*********************************************************************
3078 * Function : client_host
3080 * Description : If the request URI did not contain host and
3081 * port information, parse and evaluate the Host
3084 * Also, kill ill-formed HOST: headers as sent by
3085 * Apple's iTunes software when used with a proxy.
3088 * 1 : csp = Current client state (buffers, headers, etc...)
3089 * 2 : header = On input, pointer to header to modify.
3090 * On output, pointer to the modified header, or NULL
3091 * to remove the header. This function frees the
3092 * original string if necessary.
3094 * Returns : JB_ERR_OK on success, or
3095 * JB_ERR_MEMORY on out-of-memory error.
3097 *********************************************************************/
3098 static jb_err client_host(struct client_state *csp, char **header)
3103 * If the header field name is all upper-case, chances are that it's
3104 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3105 * not a problem -- they are regenerated later.
3107 if ((*header)[1] == 'O')
3109 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3114 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3115 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3118 if (NULL == (p = strdup((*header)+6)))
3120 return JB_ERR_MEMORY;
3123 if (NULL == (q = strdup(p)))
3126 return JB_ERR_MEMORY;
3129 freez(csp->http->hostport);
3130 csp->http->hostport = p;
3131 freez(csp->http->host);
3132 csp->http->host = q;
3133 q = strchr(csp->http->host, ':');
3136 /* Terminate hostname and evaluate port string */
3138 csp->http->port = atoi(q);
3142 csp->http->port = csp->http->ssl ? 443 : 80;
3145 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3146 csp->http->hostport, csp->http->host, csp->http->port);
3149 /* Signal client_host_adder() to return right away */
3150 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3156 /*********************************************************************
3158 * Function : client_if_modified_since
3160 * Description : Remove or modify the If-Modified-Since header.
3163 * 1 : csp = Current client state (buffers, headers, etc...)
3164 * 2 : header = On input, pointer to header to modify.
3165 * On output, pointer to the modified header, or NULL
3166 * to remove the header. This function frees the
3167 * original string if necessary.
3169 * Returns : JB_ERR_OK on success, or
3170 * JB_ERR_MEMORY on out-of-memory error.
3172 *********************************************************************/
3173 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3176 #ifdef HAVE_GMTIME_R
3179 struct tm *timeptr = NULL;
3182 long int hours, minutes, seconds;
3185 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3188 * The client got an error message because of a temporary problem,
3189 * the problem is gone and the client now tries to revalidate our
3190 * error message on the real server. The revalidation would always
3191 * end with the transmission of the whole document and there is
3192 * no need to expose the bogus If-Modified-Since header.
3194 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3197 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3199 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3201 if ((0 == strcmpic(newval, "block")))
3203 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3206 else /* add random value */
3208 const char *header_time = *header + sizeof("If-Modified-Since:");
3210 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3212 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3217 long int rtime = strtol(newval, &endptr, 0);
3218 const int negative_range = (rtime < 0);
3222 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3223 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3229 rtime = pick_from_range(rtime);
3233 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3236 tm += rtime * (negative_range ? -1 : 1);
3237 #ifdef HAVE_GMTIME_R
3238 timeptr = gmtime_r(&tm, &gmt);
3239 #elif defined(MUTEX_LOCKS_AVAILABLE)
3240 privoxy_mutex_lock(&gmtime_mutex);
3241 timeptr = gmtime(&tm);
3242 privoxy_mutex_unlock(&gmtime_mutex);
3244 timeptr = gmtime(&tm);
3246 if ((NULL == timeptr) || !strftime(newheader,
3247 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3249 log_error(LOG_LEVEL_ERROR,
3250 "Randomizing '%s' failed. Crunching the header without replacement.",
3257 *header = strdup("If-Modified-Since: ");
3258 string_append(header, newheader);
3260 if (*header == NULL)
3262 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3263 return JB_ERR_MEMORY;
3266 hours = rtime / 3600;
3267 minutes = rtime / 60 % 60;
3268 seconds = rtime % 60;
3270 log_error(LOG_LEVEL_HEADER,
3271 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3272 *header, (negative_range) ? "subtracted" : "added", hours,
3273 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3274 seconds, (seconds == 1) ? ")" : "s)");
3283 /*********************************************************************
3285 * Function : client_if_none_match
3287 * Description : Remove the If-None-Match header.
3290 * 1 : csp = Current client state (buffers, headers, etc...)
3291 * 2 : header = On input, pointer to header to modify.
3292 * On output, pointer to the modified header, or NULL
3293 * to remove the header. This function frees the
3294 * original string if necessary.
3296 * Returns : JB_ERR_OK on success, or
3297 * JB_ERR_MEMORY on out-of-memory error.
3299 *********************************************************************/
3300 static jb_err client_if_none_match(struct client_state *csp, char **header)
3302 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3304 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3312 /*********************************************************************
3314 * Function : client_x_filter
3316 * Description : Disables filtering if the client set "X-Filter: No".
3317 * Called from `sed'.
3320 * 1 : csp = Current client state (buffers, headers, etc...)
3321 * 2 : header = On input, pointer to header to modify.
3322 * On output, pointer to the modified header, or NULL
3323 * to remove the header. This function frees the
3324 * original string if necessary.
3326 * Returns : JB_ERR_OK on success
3328 *********************************************************************/
3329 jb_err client_x_filter(struct client_state *csp, char **header)
3331 if ( 0 == strcmpic(*header, "X-Filter: No"))
3333 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3335 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3339 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3341 log_error(LOG_LEVEL_HEADER,
3342 "force-text-mode overruled the client's request to fetch without filtering!");
3346 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3347 csp->flags |= CSP_FLAG_NO_FILTERING;
3348 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3350 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3358 /*********************************************************************
3360 * Function : client_range
3362 * Description : Removes Range, Request-Range and If-Range headers if
3363 * content filtering is enabled. If the client's version
3364 * of the document has been altered by Privoxy, the server
3365 * could interpret the range differently than the client
3366 * intended in which case the user could end up with
3367 * corrupted content.
3370 * 1 : csp = Current client state (buffers, headers, etc...)
3371 * 2 : header = On input, pointer to header to modify.
3372 * On output, pointer to the modified header, or NULL
3373 * to remove the header. This function frees the
3374 * original string if necessary.
3376 * Returns : JB_ERR_OK
3378 *********************************************************************/
3379 static jb_err client_range(struct client_state *csp, char **header)
3381 if (content_filters_enabled(csp->action))
3383 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3384 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3391 /* the following functions add headers directly to the header list */
3393 /*********************************************************************
3395 * Function : client_host_adder
3397 * Description : Adds the Host: header field if it is missing.
3398 * Called from `sed'.
3401 * 1 : csp = Current client state (buffers, headers, etc...)
3403 * Returns : JB_ERR_OK on success, or
3404 * JB_ERR_MEMORY on out-of-memory error.
3406 *********************************************************************/
3407 static jb_err client_host_adder(struct client_state *csp)
3412 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3414 /* Header already set by the client, nothing to do. */
3418 if ( !csp->http->hostport || !*(csp->http->hostport))
3420 /* XXX: When does this happen and why is it OK? */
3421 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3426 * remove 'user:pass@' from 'proto://user:pass@host'
3428 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3434 p = csp->http->hostport;
3437 /* XXX: Just add it, we already made sure that it will be unique */
3438 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3439 err = enlist_unique_header(csp->headers, "Host", p);
3446 /*********************************************************************
3448 * Function : client_accept_encoding_adder
3450 * Description : Add an Accept-Encoding header to the client's request
3451 * that disables compression if the action applies, and
3452 * the header is not already there. Called from `sed'.
3453 * Note: For HTTP/1.0, the absence of the header is enough.
3456 * 1 : csp = Current client state (buffers, headers, etc...)
3458 * Returns : JB_ERR_OK on success, or
3459 * JB_ERR_MEMORY on out-of-memory error.
3461 *********************************************************************/
3462 static jb_err client_accept_encoding_adder(struct client_state *csp)
3464 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3465 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3467 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3475 /*********************************************************************
3477 * Function : client_xtra_adder
3479 * Description : Used in the add_client_headers list. Called from `sed'.
3482 * 1 : csp = Current client state (buffers, headers, etc...)
3484 * Returns : JB_ERR_OK on success, or
3485 * JB_ERR_MEMORY on out-of-memory error.
3487 *********************************************************************/
3488 static jb_err client_xtra_adder(struct client_state *csp)
3490 struct list_entry *lst;
3493 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3494 lst ; lst = lst->next)
3496 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3497 err = enlist(csp->headers, lst->str);
3509 /*********************************************************************
3511 * Function : client_x_forwarded_for_adder
3513 * Description : Used in the add_client_headers list. Called from `sed'.
3516 * 1 : csp = Current client state (buffers, headers, etc...)
3518 * Returns : JB_ERR_OK on success, or
3519 * JB_ERR_MEMORY on out-of-memory error.
3521 *********************************************************************/
3522 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3524 char *header = NULL;
3527 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3528 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3529 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3532 * If we aren't adding X-Forwarded-For headers,
3533 * or we already appended an existing X-Forwarded-For
3534 * header, there's nothing left to do here.
3539 header = strdup("X-Forwarded-For: ");
3540 string_append(&header, csp->ip_addr_str);
3544 return JB_ERR_MEMORY;
3547 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3548 err = enlist(csp->headers, header);
3555 /*********************************************************************
3557 * Function : server_connection_adder
3559 * Description : Adds an appropiate "Connection:" header to csp->headers
3560 * unless the header was already present. Called from `sed'.
3563 * 1 : csp = Current client state (buffers, headers, etc...)
3565 * Returns : JB_ERR_OK on success, or
3566 * JB_ERR_MEMORY on out-of-memory error.
3568 *********************************************************************/
3569 static jb_err server_connection_adder(struct client_state *csp)
3571 const unsigned int flags = csp->flags;
3572 const char *response_status_line = csp->headers->first->str;
3573 static const char connection_close[] = "Connection: close";
3575 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3576 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3582 * XXX: if we downgraded the response, this check will fail.
3584 if ((csp->config->feature_flags &
3585 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3586 && (NULL != response_status_line)
3587 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3588 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3589 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3593 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3594 "without Connection header implies keep-alive.");
3595 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3599 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3601 return enlist(csp->headers, connection_close);
3605 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3606 /*********************************************************************
3608 * Function : server_proxy_connection_adder
3610 * Description : Adds a "Proxy-Connection: keep-alive" header to
3611 * csp->headers if the client asked for keep-alive.
3612 * XXX: We should reuse existant ones.
3615 * 1 : csp = Current client state (buffers, headers, etc...)
3617 * Returns : JB_ERR_OK on success, or
3618 * JB_ERR_MEMORY on out-of-memory error.
3620 *********************************************************************/
3621 static jb_err server_proxy_connection_adder(struct client_state *csp)
3623 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3624 jb_err err = JB_ERR_OK;
3626 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3627 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3628 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET))
3630 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3631 err = enlist(csp->headers, proxy_connection_header);
3636 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3639 /*********************************************************************
3641 * Function : client_connection_header_adder
3643 * Description : Adds a proper "Connection:" header to csp->headers
3644 * unless the header was already present. Called from `sed'.
3647 * 1 : csp = Current client state (buffers, headers, etc...)
3649 * Returns : JB_ERR_OK on success, or
3650 * JB_ERR_MEMORY on out-of-memory error.
3652 *********************************************************************/
3653 static jb_err client_connection_header_adder(struct client_state *csp)
3655 static const char connection_close[] = "Connection: close";
3657 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3658 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3663 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3664 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3665 && (csp->http->ssl == 0)
3666 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3668 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3671 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3673 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3675 return enlist(csp->headers, connection_close);
3679 /*********************************************************************
3681 * Function : server_http
3683 * Description : - Save the HTTP Status into csp->http->status
3684 * - Set CT_TABOO to prevent filtering if the answer
3685 * is a partial range (HTTP status 206)
3686 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3690 * 1 : csp = Current client state (buffers, headers, etc...)
3691 * 2 : header = On input, pointer to header to modify.
3692 * On output, pointer to the modified header, or NULL
3693 * to remove the header. This function frees the
3694 * original string if necessary.
3696 * Returns : JB_ERR_OK on success, or
3697 * JB_ERR_MEMORY on out-of-memory error.
3699 *********************************************************************/
3700 static jb_err server_http(struct client_state *csp, char **header)
3702 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3703 if (csp->http->status == 206)
3705 csp->content_type = CT_TABOO;
3708 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3710 /* XXX: Should we do a real validity check here? */
3711 if (strlen(*header) > 8)
3714 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3719 * XXX: Should we block the request or
3720 * enlist a valid status code line here?
3722 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3723 "Downgrading to HTTP/1.0 impossible.");
3731 /*********************************************************************
3733 * Function : server_set_cookie
3735 * Description : Handle the server "cookie" header properly.
3736 * Crunch, accept or rewrite it to a session cookie.
3737 * Called from `sed'.
3739 * TODO: Allow the user to specify a new expiration
3740 * time to cause the cookie to expire even before the
3741 * browser is closed.
3744 * 1 : csp = Current client state (buffers, headers, etc...)
3745 * 2 : header = On input, pointer to header to modify.
3746 * On output, pointer to the modified header, or NULL
3747 * to remove the header. This function frees the
3748 * original string if necessary.
3750 * Returns : JB_ERR_OK on success, or
3751 * JB_ERR_MEMORY on out-of-memory error.
3753 *********************************************************************/
3754 static jb_err server_set_cookie(struct client_state *csp, char **header)
3761 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3763 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3766 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3768 /* Flag whether or not to log a message */
3771 /* A variable to store the tag we're working on */
3774 /* Skip "Set-Cookie:" (11 characters) in header */
3775 cur_tag = *header + 11;
3777 /* skip whitespace between "Set-Cookie:" and value */
3778 while (*cur_tag && ijb_isspace(*cur_tag))
3783 /* Loop through each tag in the cookie */
3787 char *next_tag = strchr(cur_tag, ';');
3788 if (next_tag != NULL)
3790 /* Skip the ';' character itself */
3793 /* skip whitespace ";" and start of tag */
3794 while (*next_tag && ijb_isspace(*next_tag))
3801 /* "Next tag" is the end of the string */
3802 next_tag = cur_tag + strlen(cur_tag);
3806 * Check the expiration date to see
3807 * if the cookie is still valid, if yes,
3808 * rewrite it to a session cookie.
3810 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3812 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3814 /* Did we detect the date properly? */
3815 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3818 * Nope, treat it as if it was still valid.
3820 * XXX: Should we remove the whole cookie instead?
3822 log_error(LOG_LEVEL_ERROR,
3823 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3824 string_move(cur_tag, next_tag);
3830 * Yes. Check if the cookie is still valid.
3832 * If the cookie is already expired it's probably
3833 * a delete cookie and even if it isn't, the browser
3834 * will discard it anyway.
3838 * XXX: timegm() isn't available on some AmigaOS
3839 * versions and our replacement doesn't work.
3841 * Our options are to either:
3843 * - disable session-cookies-only completely if timegm
3846 * - to simply remove all expired tags, like it has
3847 * been done until Privoxy 3.0.6 and to live with
3848 * the consequence that it can cause login/logout
3849 * problems on servers that don't validate their
3850 * input properly, or
3852 * - to replace it with mktime in which
3853 * case there is a slight chance of valid cookies
3854 * passing as already expired.
3856 * This is the way it's currently done and it's not
3857 * as bad as it sounds. If the missing GMT offset is
3858 * enough to change the result of the expiration check
3859 * the cookie will be only valid for a few hours
3860 * anyway, which in many cases will be shorter
3861 * than a browser session.
3863 if (cookie_time - now < 0)
3865 log_error(LOG_LEVEL_HEADER,
3866 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3867 /* Just in case some clown sets more then one expiration date */
3873 * Still valid, delete expiration date by copying
3874 * the rest of the string over it.
3876 string_move(cur_tag, next_tag);
3878 /* That changed the header, need to issue a log message */
3882 * Note that the next tag has now been moved to *cur_tag,
3883 * so we do not need to update the cur_tag pointer.
3891 /* Move on to next cookie tag */
3898 assert(NULL != *header);
3899 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3908 #ifdef FEATURE_FORCE_LOAD
3909 /*********************************************************************
3911 * Function : strclean
3913 * Description : In-Situ-Eliminate all occurances of substring in
3917 * 1 : string = string to clean
3918 * 2 : substring = substring to eliminate
3920 * Returns : Number of eliminations
3922 *********************************************************************/
3923 int strclean(char *string, const char *substring)
3929 len = strlen(substring);
3931 while((pos = strstr(string, substring)) != NULL)
3938 while (*p++ != '\0');
3945 #endif /* def FEATURE_FORCE_LOAD */
3948 /*********************************************************************
3950 * Function : parse_header_time
3952 * Description : Parses time formats used in HTTP header strings
3953 * to get the numerical respresentation.
3956 * 1 : header_time = HTTP header time as string.
3957 * 2 : result = storage for header_time in seconds
3959 * Returns : JB_ERR_OK if the time format was recognized, or
3960 * JB_ERR_PARSE otherwise.
3962 *********************************************************************/
3963 static jb_err parse_header_time(const char *header_time, time_t *result)
3968 * Zero out gmt to prevent time zone offsets.
3970 * While this is only necessary on some platforms
3971 * (mingw32 for example), I don't know how to
3972 * detect these automatically and doing it everywhere
3975 memset(&gmt, 0, sizeof(gmt));
3977 /* Tue, 02 Jun 2037 20:00:00 */
3978 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3979 /* Tue, 02-Jun-2037 20:00:00 */
3980 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3981 /* Tue, 02-Jun-37 20:00:00 */
3982 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3983 /* Tuesday, 02-Jun-2037 20:00:00 */
3984 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3985 /* Tuesday Jun 02 20:00:00 2037 */
3986 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3988 return JB_ERR_PARSE;
3991 *result = timegm(&gmt);
3998 /*********************************************************************
4000 * Function : get_destination_from_headers
4002 * Description : Parse the "Host:" header to get the request's destination.
4003 * Only needed if the client's request was forcefully
4004 * redirected into Privoxy.
4006 * Code mainly copied from client_host() which is currently
4007 * run too late for this purpose.
4010 * 1 : headers = List of headers (one of them hopefully being
4011 * the "Host:" header)
4012 * 2 : http = storage for the result (host, port and hostport).
4014 * Returns : JB_ERR_MEMORY in case of memory problems,
4015 * JB_ERR_PARSE if the host header couldn't be found,
4016 * JB_ERR_OK otherwise.
4018 *********************************************************************/
4019 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4025 host = get_header_value(headers, "Host:");
4029 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4030 return JB_ERR_PARSE;
4033 if (NULL == (p = strdup((host))))
4035 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4036 return JB_ERR_MEMORY;
4039 if (NULL == (q = strdup(p)))
4042 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4043 return JB_ERR_MEMORY;
4046 freez(http->hostport);
4050 q = strchr(http->host, ':');
4053 /* Terminate hostname and evaluate port string */
4055 http->port = atoi(q);
4059 http->port = http->ssl ? 443 : 80;
4062 /* Rebuild request URL */
4064 http->url = strdup(http->ssl ? "https://" : "http://");
4065 string_append(&http->url, http->hostport);
4066 string_append(&http->url, http->path);
4067 if (http->url == NULL)
4069 return JB_ERR_MEMORY;
4072 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4080 /*********************************************************************
4082 * Function : create_forged_referrer
4084 * Description : Helper for client_referrer to forge a referer as
4085 * 'http://[hostname:port/' to fool stupid
4086 * checks for in-site links
4089 * 1 : header = Pointer to header pointer
4090 * 2 : hostport = Host and optionally port as string
4092 * Returns : JB_ERR_OK in case of success, or
4093 * JB_ERR_MEMORY in case of memory problems.
4095 *********************************************************************/
4096 static jb_err create_forged_referrer(char **header, const char *hostport)
4098 assert(NULL == *header);
4100 *header = strdup("Referer: http://");
4101 string_append(header, hostport);
4102 string_append(header, "/");
4104 if (NULL == *header)
4106 return JB_ERR_MEMORY;
4109 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4116 /*********************************************************************
4118 * Function : create_fake_referrer
4120 * Description : Helper for client_referrer to create a fake referrer
4121 * based on a string supplied by the user.
4124 * 1 : header = Pointer to header pointer
4125 * 2 : hosthost = Referrer to fake
4127 * Returns : JB_ERR_OK in case of success, or
4128 * JB_ERR_MEMORY in case of memory problems.
4130 *********************************************************************/
4131 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4133 assert(NULL == *header);
4135 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4137 log_error(LOG_LEVEL_HEADER,
4138 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4140 *header = strdup("Referer: ");
4141 string_append(header, fake_referrer);
4143 if (NULL == *header)
4145 return JB_ERR_MEMORY;
4148 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4155 /*********************************************************************
4157 * Function : handle_conditional_hide_referrer_parameter
4159 * Description : Helper for client_referrer to crunch or forge
4160 * the referrer header if the host has changed.
4163 * 1 : header = Pointer to header pointer
4164 * 2 : host = The target host (may include the port)
4165 * 3 : parameter_conditional_block = Boolean to signal
4166 * if we're in conditional-block mode. If not set,
4167 * we're in conditional-forge mode.
4169 * Returns : JB_ERR_OK in case of success, or
4170 * JB_ERR_MEMORY in case of memory problems.
4172 *********************************************************************/
4173 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4174 const char *host, const int parameter_conditional_block)
4176 char *referer = strdup(*header);
4177 const size_t hostlenght = strlen(host);
4178 const char *referer_url = NULL;
4180 if (NULL == referer)
4183 return JB_ERR_MEMORY;
4186 /* referer begins with 'Referer: http[s]://' */
4187 if ((hostlenght+17) < strlen(referer))
4190 * Shorten referer to make sure the referer is blocked
4191 * if www.example.org/www.example.com-shall-see-the-referer/
4192 * links to www.example.com/
4194 referer[hostlenght+17] = '\0';
4196 referer_url = strstr(referer, "http://");
4197 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4199 /* Host has changed, Referer is invalid or a https URL. */
4200 if (parameter_conditional_block)
4202 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4209 return create_forged_referrer(header, host);
4219 /*********************************************************************
4221 * Function : create_content_length_header
4223 * Description : Creates a Content-Length header.
4226 * 1 : content_length = The content length to be used in the header.
4227 * 2 : header = Allocated space to safe the header.
4228 * 3 : buffer_length = The length of the allocated space.
4232 *********************************************************************/
4233 static void create_content_length_header(unsigned long long content_length,
4234 char *header, size_t buffer_length)
4236 snprintf(header, buffer_length, "Content-Length: %llu", content_length);