1 const char parsers_rcs[] = "$Id: parsers.c,v 1.235 2011/10/16 12:39:14 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 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
159 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
160 static jb_err server_save_content_length(struct client_state *csp, char **header);
161 static jb_err server_keep_alive(struct client_state *csp, char **header);
162 static jb_err server_proxy_connection(struct client_state *csp, char **header);
163 static jb_err client_keep_alive(struct client_state *csp, char **header);
164 static jb_err client_save_content_length(struct client_state *csp, char **header);
165 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
167 static jb_err client_host_adder (struct client_state *csp);
168 static jb_err client_xtra_adder (struct client_state *csp);
169 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
170 static jb_err client_connection_header_adder(struct client_state *csp);
171 static jb_err server_connection_adder(struct client_state *csp);
172 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
173 static jb_err server_proxy_connection_adder(struct client_state *csp);
174 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
176 static jb_err create_forged_referrer(char **header, const char *hostport);
177 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
178 static jb_err handle_conditional_hide_referrer_parameter(char **header,
179 const char *host, const int parameter_conditional_block);
180 static void create_content_length_header(unsigned long long content_length,
181 char *header, size_t buffer_length);
184 * List of functions to run on a list of headers.
188 /** The header prefix to match */
191 /** The length of the prefix to match */
194 /** The function to apply to this line */
195 const parser_func_ptr parser;
198 static const struct parsers client_patterns[] = {
199 { "referer:", 8, client_referrer },
200 { "user-agent:", 11, client_uagent },
201 { "ua-", 3, client_ua },
202 { "from:", 5, client_from },
203 { "cookie:", 7, client_send_cookie },
204 { "x-forwarded-for:", 16, client_x_forwarded },
205 { "Accept-Encoding:", 16, client_accept_encoding },
206 { "TE:", 3, client_te },
207 { "Host:", 5, client_host },
208 { "if-modified-since:", 18, client_if_modified_since },
209 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
210 { "Keep-Alive:", 11, client_keep_alive },
211 { "Content-Length:", 15, client_save_content_length },
213 { "Keep-Alive:", 11, crumble },
215 { "connection:", 11, client_connection },
216 { "proxy-connection:", 17, crumble },
217 { "max-forwards:", 13, client_max_forwards },
218 { "Accept-Language:", 16, client_accept_language },
219 { "if-none-match:", 14, client_if_none_match },
220 { "Range:", 6, client_range },
221 { "Request-Range:", 14, client_range },
222 { "If-Range:", 9, client_range },
223 { "X-Filter:", 9, client_x_filter },
224 { "*", 0, crunch_client_header },
225 { "*", 0, filter_header },
229 static const struct parsers server_patterns[] = {
230 { "HTTP/", 5, server_http },
231 { "set-cookie:", 11, server_set_cookie },
232 { "connection:", 11, server_connection },
233 { "Content-Type:", 13, server_content_type },
234 { "Content-MD5:", 12, server_content_md5 },
235 { "Content-Encoding:", 17, server_content_encoding },
236 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
237 { "Content-Length:", 15, server_save_content_length },
238 { "Keep-Alive:", 11, server_keep_alive },
239 { "Proxy-Connection:", 17, server_proxy_connection },
241 { "Keep-Alive:", 11, crumble },
242 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
243 { "Transfer-Encoding:", 18, server_transfer_coding },
244 { "content-disposition:", 20, server_content_disposition },
245 { "Last-Modified:", 14, server_last_modified },
246 { "*", 0, crunch_server_header },
247 { "*", 0, filter_header },
251 static const add_header_func_ptr add_client_headers[] = {
253 client_x_forwarded_for_adder,
255 /* Temporarily disabled: client_accept_encoding_adder, */
256 client_connection_header_adder,
260 static const add_header_func_ptr add_server_headers[] = {
261 server_connection_adder,
262 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
263 server_proxy_connection_adder,
264 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
268 /*********************************************************************
270 * Function : flush_socket
272 * Description : Write any pending "buffered" content.
275 * 1 : fd = file descriptor of the socket to read
276 * 2 : iob = The I/O buffer to flush, usually csp->iob.
278 * Returns : On success, the number of bytes written are returned (zero
279 * indicates nothing was written). On error, -1 is returned,
280 * and errno is set appropriately. If count is zero and the
281 * file descriptor refers to a regular file, 0 will be
282 * returned without causing any other effect. For a special
283 * file, the results are not portable.
285 *********************************************************************/
286 long flush_socket(jb_socket fd, struct iob *iob)
288 long len = iob->eod - iob->cur;
295 if (write_socket(fd, iob->cur, (size_t)len))
299 iob->eod = iob->cur = iob->buf;
305 /*********************************************************************
307 * Function : add_to_iob
309 * Description : Add content to the buffered page, expanding the
310 * buffer if necessary.
313 * 1 : csp = Current client state (buffers, headers, etc...)
314 * 2 : buf = holds the content to be added to the page
315 * 3 : n = number of bytes to be added
317 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
318 * or buffer limit reached.
320 *********************************************************************/
321 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
323 struct iob *iob = csp->iob;
324 size_t used, offset, need;
327 if (n <= 0) return JB_ERR_OK;
329 used = (size_t)(iob->eod - iob->buf);
330 offset = (size_t)(iob->cur - iob->buf);
331 need = used + (size_t)n + 1;
334 * If the buffer can't hold the new data, extend it first.
335 * Use the next power of two if possible, else use the actual need.
337 if (need > csp->config->buffer_limit)
339 log_error(LOG_LEVEL_INFO,
340 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
341 need, csp->config->buffer_limit);
342 return JB_ERR_MEMORY;
345 if (need > iob->size)
347 size_t want = csp->iob->size ? csp->iob->size : 512;
354 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
358 else if (NULL != (p = (char *)realloc(iob->buf, need)))
364 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
365 return JB_ERR_MEMORY;
368 /* Update the iob pointers */
369 iob->cur = p + offset;
374 /* copy the new data into the iob buffer */
375 memcpy(iob->eod, buf, (size_t)n);
377 /* point to the end of the data */
380 /* null terminate == cheap insurance */
389 /*********************************************************************
391 * Function : decompress_iob
393 * Description : Decompress buffered page, expanding the
394 * buffer as necessary. csp->iob->cur
395 * should point to the the beginning of the
396 * compressed data block.
399 * 1 : csp = Current client state (buffers, headers, etc...)
401 * Returns : JB_ERR_OK on success,
402 * JB_ERR_MEMORY if out-of-memory limit reached, and
403 * JB_ERR_COMPRESS if error decompressing buffer.
405 *********************************************************************/
406 jb_err decompress_iob(struct client_state *csp)
408 char *buf; /* new, uncompressed buffer */
409 char *cur; /* Current iob position (to keep the original
410 * iob->cur unmodified if we return early) */
411 size_t bufsize; /* allocated size of the new buffer */
412 size_t old_size; /* Content size before decompression */
413 size_t skip_size; /* Number of bytes at the beginning of the iob
414 that we should NOT decompress. */
415 int status; /* return status of the inflate() call */
416 z_stream zstr; /* used by calls to zlib */
418 assert(csp->iob->cur - csp->iob->buf > 0);
419 assert(csp->iob->eod - csp->iob->cur > 0);
421 bufsize = csp->iob->size;
422 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
423 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
427 if (bufsize < (size_t)10)
430 * This is to protect the parsing of gzipped data,
431 * but it should(?) be valid for deflated data also.
433 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
434 return JB_ERR_COMPRESS;
437 if (csp->content_type & CT_GZIP)
440 * Our task is slightly complicated by the facts that data
441 * compressed by gzip does not include a zlib header, and
442 * that there is no easily accessible interface in zlib to
443 * handle a gzip header. We strip off the gzip header by
444 * hand, and later inform zlib not to expect a header.
448 * Strip off the gzip header. Please see RFC 1952 for more
449 * explanation of the appropriate fields.
451 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
452 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
453 || (*cur++ != Z_DEFLATED))
455 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
456 return JB_ERR_COMPRESS;
461 if (flags & GZIP_FLAG_RESERVED_BITS)
463 /* The gzip header has reserved bits set; bail out. */
464 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
465 return JB_ERR_COMPRESS;
469 * Skip mtime (4 bytes), extra flags (1 byte)
470 * and OS type (1 byte).
474 /* Skip extra fields if necessary. */
475 if (flags & GZIP_FLAG_EXTRA_FIELDS)
478 * Skip a given number of bytes, specified
479 * as a 16-bit little-endian value.
481 * XXX: this code is untested and should probably be removed.
485 skip_bytes += *cur++ << 8;
488 * The number of bytes to skip should be positive
489 * and we'd like to stay in the buffer.
491 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
493 log_error(LOG_LEVEL_ERROR,
494 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
496 return JB_ERR_COMPRESS;
498 log_error(LOG_LEVEL_INFO,
499 "Skipping %d bytes for gzip compression. Does this sound right?",
504 /* Skip the filename if necessary. */
505 if (flags & GZIP_FLAG_FILE_NAME)
507 /* A null-terminated string is supposed to follow. */
508 while (*cur++ && (cur < csp->iob->eod));
511 /* Skip the comment if necessary. */
512 if (flags & GZIP_FLAG_COMMENT)
514 /* A null-terminated string is supposed to follow. */
515 while (*cur++ && (cur < csp->iob->eod));
518 /* Skip the CRC if necessary. */
519 if (flags & GZIP_FLAG_CHECKSUM)
524 if (cur >= csp->iob->eod)
527 * If the current position pointer reached or passed
528 * the buffer end, we were obviously tricked to skip
531 log_error(LOG_LEVEL_ERROR,
532 "Malformed gzip header detected. Aborting decompression.");
533 return JB_ERR_COMPRESS;
537 else if (csp->content_type & CT_DEFLATE)
540 * XXX: The debug level should be lowered
541 * before the next stable release.
543 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
545 * In theory (that is, according to RFC 1950), deflate-compressed
546 * data should begin with a two-byte zlib header and have an
547 * adler32 checksum at the end. It seems that in practice only
548 * the raw compressed data is sent. Note that this means that
549 * we are not RFC 1950-compliant here, but the advantage is that
550 * this actually works. :)
552 * We add a dummy null byte to tell zlib where the data ends,
553 * and later inform it not to expect a header.
555 * Fortunately, add_to_iob() has thoughtfully null-terminated
556 * the buffer; we can just increment the end pointer to include
563 log_error(LOG_LEVEL_ERROR,
564 "Unable to determine compression format for decompression");
565 return JB_ERR_COMPRESS;
568 /* Set up the fields required by zlib. */
569 zstr.next_in = (Bytef *)cur;
570 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
571 zstr.zalloc = Z_NULL;
573 zstr.opaque = Z_NULL;
576 * Passing -MAX_WBITS to inflateInit2 tells the library
577 * that there is no zlib header.
579 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
581 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
582 return JB_ERR_COMPRESS;
586 * Next, we allocate new storage for the inflated data.
587 * We don't modify the existing iob yet, so in case there
588 * is error in decompression we can recover gracefully.
590 buf = zalloc(bufsize);
593 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
594 return JB_ERR_MEMORY;
597 assert(bufsize >= skip_size);
598 memcpy(buf, csp->iob->buf, skip_size);
599 zstr.avail_out = (uInt)(bufsize - skip_size);
600 zstr.next_out = (Bytef *)buf + skip_size;
602 /* Try to decompress the whole stream in one shot. */
603 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
605 /* We need to allocate more memory for the output buffer. */
607 char *tmpbuf; /* used for realloc'ing the buffer */
608 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
610 if (0 == zstr.avail_in)
613 * If zlib wants more data then there's a problem, because
614 * the complete compressed file should have been buffered.
616 log_error(LOG_LEVEL_ERROR,
617 "Unexpected end of compressed iob. Using what we got so far.");
622 * If we reached the buffer limit and still didn't have enough
623 * memory, just give up. Due to the ceiling enforced by the next
624 * if block we could actually check for equality here, but as it
625 * can be easily mistaken for a bug we don't.
627 if (bufsize >= csp->config->buffer_limit)
629 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
630 return JB_ERR_MEMORY;
633 /* Try doubling the buffer size each time. */
636 /* Don't exceed the buffer limit. */
637 if (bufsize > csp->config->buffer_limit)
639 bufsize = csp->config->buffer_limit;
642 /* Try to allocate the new buffer. */
643 tmpbuf = realloc(buf, bufsize);
646 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
648 return JB_ERR_MEMORY;
652 char *oldnext_out = (char *)zstr.next_out;
655 * Update the fields for inflate() to use the new
656 * buffer, which may be in a location different from
659 zstr.avail_out += (uInt)(bufsize - oldbufsize);
660 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
663 * Compare with an uglier method of calculating these values
664 * that doesn't require the extra oldbufsize variable.
666 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
667 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
673 if (Z_STREAM_ERROR == inflateEnd(&zstr))
675 log_error(LOG_LEVEL_ERROR,
676 "Inconsistent stream state after decompression: %s", zstr.msg);
678 * XXX: Intentionally no return.
680 * According to zlib.h, Z_STREAM_ERROR is returned
681 * "if the stream state was inconsistent".
683 * I assume in this case inflate()'s status
684 * would also be something different than Z_STREAM_END
685 * so this check should be redundant, but lets see.
689 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
692 * We failed to decompress the stream and it's
693 * not simply because of missing data.
695 log_error(LOG_LEVEL_ERROR,
696 "Unexpected error while decompressing to the buffer (iob): %s",
698 return JB_ERR_COMPRESS;
702 * Finally, we can actually update the iob, since the
703 * decompression was successful. First, free the old
706 freez(csp->iob->buf);
708 /* Now, update the iob to use the new buffer. */
710 csp->iob->cur = csp->iob->buf + skip_size;
711 csp->iob->eod = (char *)zstr.next_out;
712 csp->iob->size = bufsize;
715 * Make sure the new uncompressed iob obeys some minimal
716 * consistency conditions.
718 if ((csp->iob->buf < csp->iob->cur)
719 && (csp->iob->cur <= csp->iob->eod)
720 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
722 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
723 if (new_size > (size_t)0)
725 log_error(LOG_LEVEL_RE_FILTER,
726 "Decompression successful. Old size: %d, new size: %d.",
731 /* zlib thinks this is OK, so lets do the same. */
732 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
737 /* It seems that zlib did something weird. */
738 log_error(LOG_LEVEL_ERROR,
739 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
740 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
741 csp->iob->eod, csp->iob->buf + csp->iob->size);
742 return JB_ERR_COMPRESS;
748 #endif /* defined(FEATURE_ZLIB) */
751 /*********************************************************************
753 * Function : string_move
755 * Description : memmove wrapper to move the last part of a string
756 * towards the beginning, overwriting the part in
757 * the middle. strlcpy() can't be used here as the
761 * 1 : dst = Destination to overwrite
762 * 2 : src = Source to move.
766 *********************************************************************/
767 static void string_move(char *dst, char *src)
771 /* +1 to copy the terminating nul as well. */
772 memmove(dst, src, strlen(src)+1);
776 /*********************************************************************
778 * Function : normalize_lws
780 * Description : Reduces unquoted linear white space in headers
781 * to a single space in accordance with RFC 2616 2.2.
782 * This simplifies parsing and filtering later on.
784 * XXX: Remove log messages before
785 * the next stable release?
788 * 1 : header = A header with linear white space to reduce.
792 *********************************************************************/
793 static void normalize_lws(char *header)
799 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
803 while (ijb_isspace(*q))
807 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
813 log_error(LOG_LEVEL_HEADER,
814 "Converting tab to space in '%s'", header);
819 char *end_of_token = strstr(p+1, "\"");
821 if (NULL != end_of_token)
823 /* Don't mess with quoted text. */
828 log_error(LOG_LEVEL_HEADER,
829 "Ignoring single quote in '%s'", header);
835 p = strchr(header, ':');
836 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
839 * There's still space before the colon.
847 /*********************************************************************
849 * Function : get_header
851 * Description : This (odd) routine will parse the csp->iob
852 * to get the next complete header.
855 * 1 : iob = The I/O buffer to parse, usually csp->iob.
857 * Returns : Any one of the following:
859 * 1) a pointer to a dynamically allocated string that contains a header line
860 * 2) NULL indicating that the end of the header was reached
861 * 3) "" indicating that the end of the iob was reached before finding
862 * a complete header line.
864 *********************************************************************/
865 char *get_header(struct iob *iob)
869 header = get_header_line(iob);
871 if ((header == NULL) || (*header == '\0'))
874 * No complete header read yet, tell the client.
879 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
882 * Header spans multiple lines, append the next one.
884 char *continued_header;
886 continued_header = get_header_line(iob);
887 if ((continued_header == NULL) || (*continued_header == '\0'))
890 * No complete header read yet, return what we got.
891 * XXX: Should "unread" header instead.
893 log_error(LOG_LEVEL_INFO,
894 "Failed to read a multi-line header properly: '%s'",
899 if (JB_ERR_OK != string_join(&header, continued_header))
901 log_error(LOG_LEVEL_FATAL,
902 "Out of memory while appending multiple headers.");
906 /* XXX: remove before next stable release. */
907 log_error(LOG_LEVEL_HEADER,
908 "Merged multiple header lines to: '%s'",
913 normalize_lws(header);
920 /*********************************************************************
922 * Function : get_header_line
924 * Description : This (odd) routine will parse the csp->iob
925 * to get the next header line.
928 * 1 : iob = The I/O buffer to parse, usually csp->iob.
930 * Returns : Any one of the following:
932 * 1) a pointer to a dynamically allocated string that contains a header line
933 * 2) NULL indicating that the end of the header was reached
934 * 3) "" indicating that the end of the iob was reached before finding
935 * a complete header line.
937 *********************************************************************/
938 static char *get_header_line(struct iob *iob)
942 if ((iob->cur == NULL)
943 || ((p = strchr(iob->cur, '\n')) == NULL))
945 return(""); /* couldn't find a complete header */
950 ret = strdup(iob->cur);
953 /* FIXME No way to handle error properly */
954 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
960 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
962 /* is this a blank line (i.e. the end of the header) ? */
974 /*********************************************************************
976 * Function : get_header_value
978 * Description : Get the value of a given header from a chained list
979 * of header lines or return NULL if no such header is
980 * present in the list.
983 * 1 : header_list = pointer to list
984 * 2 : header_name = string with name of header to look for.
985 * Trailing colon required, capitalization
988 * Returns : NULL if not found, else value of header
990 *********************************************************************/
991 char *get_header_value(const struct list *header_list, const char *header_name)
993 struct list_entry *cur_entry;
999 length = strlen(header_name);
1001 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1005 if (!strncmpic(cur_entry->str, header_name, length))
1008 * Found: return pointer to start of value
1010 ret = cur_entry->str + length;
1011 while (*ret && ijb_isspace(*ret)) ret++;
1025 /*********************************************************************
1027 * Function : scan_headers
1029 * Description : Scans headers, applies tags and updates action bits.
1032 * 1 : csp = Current client state (buffers, headers, etc...)
1034 * Returns : JB_ERR_OK
1036 *********************************************************************/
1037 static jb_err scan_headers(struct client_state *csp)
1039 struct list_entry *h; /* Header */
1040 jb_err err = JB_ERR_OK;
1042 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1044 /* Header crunch()ed in previous run? -> ignore */
1045 if (h->str == NULL) continue;
1046 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1047 err = header_tagger(csp, h->str);
1054 /*********************************************************************
1058 * Description : add, delete or modify lines in the HTTP header streams.
1059 * On entry, it receives a linked list of headers space
1060 * that was allocated dynamically (both the list nodes
1061 * and the header contents).
1063 * As a side effect it frees the space used by the original
1067 * 1 : csp = Current client state (buffers, headers, etc...)
1068 * 2 : filter_server_headers = Boolean to switch between
1069 * server and header filtering.
1071 * Returns : JB_ERR_OK in case off success, or
1072 * JB_ERR_MEMORY on out-of-memory error.
1074 *********************************************************************/
1075 jb_err sed(struct client_state *csp, int filter_server_headers)
1077 /* XXX: use more descriptive names. */
1078 struct list_entry *p;
1079 const struct parsers *v;
1080 const add_header_func_ptr *f;
1081 jb_err err = JB_ERR_OK;
1083 if (filter_server_headers)
1085 v = server_patterns;
1086 f = add_server_headers;
1090 v = client_patterns;
1091 f = add_client_headers;
1096 while ((err == JB_ERR_OK) && (v->str != NULL))
1098 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1100 /* Header crunch()ed in previous run? -> ignore */
1101 if (p->str == NULL) continue;
1103 /* Does the current parser handle this header? */
1104 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1105 (v->len == CHECK_EVERY_HEADER_REMAINING))
1107 err = v->parser(csp, &(p->str));
1113 /* place additional headers on the csp->headers list */
1114 while ((err == JB_ERR_OK) && (*f))
1124 /*********************************************************************
1126 * Function : update_server_headers
1128 * Description : Updates server headers after the body has been modified.
1131 * 1 : csp = Current client state (buffers, headers, etc...)
1133 * Returns : JB_ERR_OK in case off success, or
1134 * JB_ERR_MEMORY on out-of-memory error.
1136 *********************************************************************/
1137 jb_err update_server_headers(struct client_state *csp)
1139 jb_err err = JB_ERR_OK;
1141 static const struct parsers server_patterns_light[] = {
1142 { "Content-Length:", 15, server_adjust_content_length },
1143 { "Transfer-Encoding:", 18, server_transfer_coding },
1145 { "Content-Encoding:", 17, server_adjust_content_encoding },
1146 #endif /* def FEATURE_ZLIB */
1150 if (strncmpic(csp->http->cmd, "HEAD", 4))
1152 const struct parsers *v;
1153 struct list_entry *p;
1155 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1157 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1159 /* Header crunch()ed in previous run? -> ignore */
1160 if (p->str == NULL) continue;
1162 /* Does the current parser handle this header? */
1163 if (strncmpic(p->str, v->str, v->len) == 0)
1165 err = v->parser(csp, (char **)&(p->str));
1171 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1172 if ((JB_ERR_OK == err)
1173 && (csp->flags & CSP_FLAG_MODIFIED)
1174 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1175 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1179 create_content_length_header(csp->content_length, header, sizeof(header));
1180 err = enlist(csp->headers, header);
1181 if (JB_ERR_OK == err)
1183 log_error(LOG_LEVEL_HEADER,
1184 "Content modified with no Content-Length header set. "
1185 "Created: %s.", header);
1188 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1190 #ifdef FEATURE_COMPRESSION
1191 if ((JB_ERR_OK == err)
1192 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1194 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1195 if (JB_ERR_OK == err)
1197 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1206 /*********************************************************************
1208 * Function : header_tagger
1210 * Description : Executes all text substitutions from applying
1211 * tag actions and saves the result as tag.
1213 * XXX: Shares enough code with filter_header() and
1214 * pcrs_filter_response() to warrant some helper functions.
1217 * 1 : csp = Current client state (buffers, headers, etc...)
1218 * 2 : header = Header that is used as tagger input
1220 * Returns : JB_ERR_OK on success and always succeeds
1222 *********************************************************************/
1223 static jb_err header_tagger(struct client_state *csp, char *header)
1225 int wanted_filter_type;
1226 int multi_action_index;
1230 struct file_list *fl;
1231 struct re_filterfile_spec *b;
1232 struct list_entry *tag_name;
1234 const size_t header_length = strlen(header);
1236 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1238 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1239 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1243 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1244 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1247 if (filters_available(csp) == FALSE)
1249 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1250 "tagging enabled, but no taggers available.");
1254 for (i = 0; i < MAX_AF_FILES; i++)
1257 if ((NULL == fl) || (NULL == fl->f))
1260 * Either there are no filter files
1261 * left, or this filter file just
1262 * contains no valid filters.
1264 * Continue to be sure we don't miss
1265 * valid filter files that are chained
1266 * after empty or invalid ones.
1271 /* For all filters, */
1272 for (b = fl->f; b; b = b->next)
1274 if (b->type != wanted_filter_type)
1276 /* skip the ones we don't care about, */
1279 /* leaving only taggers that could apply, of which we use the ones, */
1280 for (tag_name = csp->action->multi[multi_action_index]->first;
1281 NULL != tag_name; tag_name = tag_name->next)
1283 /* that do apply, and */
1284 if (strcmp(b->name, tag_name->str) == 0)
1286 char *modified_tag = NULL;
1288 size_t size = header_length;
1289 pcrs_job *joblist = b->joblist;
1291 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1293 if (NULL == joblist)
1295 log_error(LOG_LEVEL_RE_FILTER,
1296 "Tagger %s has empty joblist. Nothing to do.", b->name);
1300 /* execute their pcrs_joblist on the header. */
1301 for (job = joblist; NULL != job; job = job->next)
1303 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1307 /* Success, continue with the modified version. */
1316 /* Tagger doesn't match */
1319 /* Regex failure, log it but continue anyway. */
1320 assert(NULL != header);
1321 log_error(LOG_LEVEL_ERROR,
1322 "Problems with tagger \'%s\' and header \'%s\': %s",
1323 b->name, *header, pcrs_strerror(hits));
1325 freez(modified_tag);
1329 if (b->dynamic) pcrs_free_joblist(joblist);
1331 /* If this tagger matched */
1337 * There is to technical limitation which makes
1338 * it impossible to use empty tags, but I assume
1339 * no one would do it intentionally.
1342 log_error(LOG_LEVEL_INFO,
1343 "Tagger \'%s\' created an empty tag. Ignored.",
1348 if (!list_contains_item(csp->tags, tag))
1350 if (JB_ERR_OK != enlist(csp->tags, tag))
1352 log_error(LOG_LEVEL_ERROR,
1353 "Insufficient memory to add tag \'%s\', "
1354 "based on tagger \'%s\' and header \'%s\'",
1355 tag, b->name, *header);
1359 char *action_message;
1361 * update the action bits right away, to make
1362 * tagging based on tags set by earlier taggers
1363 * of the same kind possible.
1365 if (update_action_bits_for_tag(csp, tag))
1367 action_message = "Action bits updated accordingly.";
1371 action_message = "No action bits update necessary.";
1374 log_error(LOG_LEVEL_HEADER,
1375 "Tagger \'%s\' added tag \'%s\'. %s",
1376 b->name, tag, action_message);
1381 /* XXX: Is this log-worthy? */
1382 log_error(LOG_LEVEL_HEADER,
1383 "Tagger \'%s\' didn't add tag \'%s\'. "
1384 "Tag already present", b->name, tag);
1387 } /* if the tagger matched */
1388 } /* if the tagger applies */
1389 } /* for every tagger that could apply */
1390 } /* for all filters */
1391 } /* for all filter files */
1396 /* here begins the family of parser functions that reformat header lines */
1398 /*********************************************************************
1400 * Function : filter_header
1402 * Description : Executes all text substitutions from all applying
1403 * +(server|client)-header-filter actions on the header.
1404 * Most of the code was copied from pcrs_filter_response,
1405 * including the rather short variable names
1408 * 1 : csp = Current client state (buffers, headers, etc...)
1409 * 2 : header = On input, pointer to header to modify.
1410 * On output, pointer to the modified header, or NULL
1411 * to remove the header. This function frees the
1412 * original string if necessary.
1414 * Returns : JB_ERR_OK on success and always succeeds
1416 *********************************************************************/
1417 static jb_err filter_header(struct client_state *csp, char **header)
1421 size_t size = strlen(*header);
1423 char *newheader = NULL;
1426 struct file_list *fl;
1427 struct re_filterfile_spec *b;
1428 struct list_entry *filtername;
1431 int wanted_filter_type;
1432 int multi_action_index;
1434 if (csp->flags & CSP_FLAG_NO_FILTERING)
1439 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1441 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1442 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1446 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1447 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1450 if (filters_available(csp) == FALSE)
1452 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1453 "header filtering enabled, but no matching filters available.");
1457 for (i = 0; i < MAX_AF_FILES; i++)
1460 if ((NULL == fl) || (NULL == fl->f))
1463 * Either there are no filter files
1464 * left, or this filter file just
1465 * contains no valid filters.
1467 * Continue to be sure we don't miss
1468 * valid filter files that are chained
1469 * after empty or invalid ones.
1474 * For all applying +filter actions, look if a filter by that
1475 * name exists and if yes, execute its pcrs_joblist on the
1478 for (b = fl->f; b; b = b->next)
1480 if (b->type != wanted_filter_type)
1482 /* Skip other filter types */
1486 for (filtername = csp->action->multi[multi_action_index]->first;
1487 filtername ; filtername = filtername->next)
1489 if (strcmp(b->name, filtername->str) == 0)
1491 int current_hits = 0;
1492 pcrs_job *joblist = b->joblist;
1494 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1496 if (NULL == joblist)
1498 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1502 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1503 *header, size, b->name);
1505 /* Apply all jobs from the joblist */
1506 for (job = joblist; NULL != job; job = job->next)
1508 matches = pcrs_execute(job, *header, size, &newheader, &size);
1511 current_hits += matches;
1512 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1514 *header = newheader;
1516 else if ( 0 == matches )
1518 /* Filter doesn't change header */
1524 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1525 *header, b->name, pcrs_strerror(matches));
1526 if (newheader != NULL)
1528 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1534 if (b->dynamic) pcrs_free_joblist(joblist);
1536 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1537 hits += current_hits;
1544 * Additionally checking for hits is important because if
1545 * the continue hack is triggered, server headers can
1546 * arrive empty to separate multiple heads from each other.
1548 if ((0 == size) && hits)
1550 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1558 /*********************************************************************
1560 * Function : server_connection
1562 * Description : Makes sure a proper "Connection:" header is
1563 * set and signals connection_header_adder to
1567 * 1 : csp = Current client state (buffers, headers, etc...)
1568 * 2 : header = On input, pointer to header to modify.
1569 * On output, pointer to the modified header, or NULL
1570 * to remove the header. This function frees the
1571 * original string if necessary.
1573 * Returns : JB_ERR_OK on success, or
1574 * JB_ERR_MEMORY on out-of-memory error.
1576 *********************************************************************/
1577 static jb_err server_connection(struct client_state *csp, char **header)
1579 if (!strcmpic(*header, "Connection: keep-alive")
1580 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1581 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1585 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1586 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1588 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1591 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1593 log_error(LOG_LEVEL_HEADER,
1594 "Keeping the server header '%s' around.", *header);
1597 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1599 char *old_header = *header;
1601 *header = strdup("Connection: close");
1604 return JB_ERR_MEMORY;
1606 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1611 /* Signal server_connection_adder() to return early. */
1612 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1618 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1619 /*********************************************************************
1621 * Function : server_keep_alive
1623 * Description : Stores the server's keep alive timeout.
1626 * 1 : csp = Current client state (buffers, headers, etc...)
1627 * 2 : header = On input, pointer to header to modify.
1628 * On output, pointer to the modified header, or NULL
1629 * to remove the header. This function frees the
1630 * original string if necessary.
1632 * Returns : JB_ERR_OK.
1634 *********************************************************************/
1635 static jb_err server_keep_alive(struct client_state *csp, char **header)
1637 unsigned int keep_alive_timeout;
1638 const char *timeout_position = strstr(*header, "timeout=");
1640 if ((NULL == timeout_position)
1641 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1643 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1647 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1649 log_error(LOG_LEVEL_HEADER,
1650 "Reducing keep-alive timeout from %u to %u.",
1651 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1652 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1656 /* XXX: Is this log worthy? */
1657 log_error(LOG_LEVEL_HEADER,
1658 "Server keep-alive timeout is %u. Sticking with %u.",
1659 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1661 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1668 /*********************************************************************
1670 * Function : server_proxy_connection
1672 * Description : Figures out whether or not we should add a
1673 * Proxy-Connection header.
1676 * 1 : csp = Current client state (buffers, headers, etc...)
1677 * 2 : header = On input, pointer to header to modify.
1678 * On output, pointer to the modified header, or NULL
1679 * to remove the header. This function frees the
1680 * original string if necessary.
1682 * Returns : JB_ERR_OK.
1684 *********************************************************************/
1685 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1687 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1692 /*********************************************************************
1694 * Function : client_keep_alive
1696 * Description : Stores the client's keep alive timeout.
1699 * 1 : csp = Current client state (buffers, headers, etc...)
1700 * 2 : header = On input, pointer to header to modify.
1701 * On output, pointer to the modified header, or NULL
1702 * to remove the header. This function frees the
1703 * original string if necessary.
1705 * Returns : JB_ERR_OK.
1707 *********************************************************************/
1708 static jb_err client_keep_alive(struct client_state *csp, char **header)
1710 unsigned int keep_alive_timeout;
1711 const char *timeout_position = strstr(*header, ": ");
1713 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1715 log_error(LOG_LEVEL_HEADER,
1716 "keep-alive support is disabled. Crunching: %s.", *header);
1721 if ((NULL == timeout_position)
1722 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1724 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1728 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1730 log_error(LOG_LEVEL_HEADER,
1731 "Reducing keep-alive timeout from %u to %u.",
1732 csp->config->keep_alive_timeout, keep_alive_timeout);
1733 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1737 /* XXX: Is this log worthy? */
1738 log_error(LOG_LEVEL_HEADER,
1739 "Client keep-alive timeout is %u. Sticking with %u.",
1740 keep_alive_timeout, csp->config->keep_alive_timeout);
1748 /*********************************************************************
1750 * Function : get_content_length
1752 * Description : Gets the content length specified in a
1753 * Content-Length header.
1756 * 1 : header = The Content-Length header.
1757 * 2 : length = Storage to return the value.
1759 * Returns : JB_ERR_OK on success, or
1760 * JB_ERR_PARSE if no value is recognized.
1762 *********************************************************************/
1763 static jb_err get_content_length(const char *header, unsigned long long *length)
1765 assert(header[14] == ':');
1768 assert(sizeof(unsigned long long) > 4);
1769 if (1 != sscanf(header+14, ": %I64u", length))
1771 if (1 != sscanf(header+14, ": %llu", length))
1774 return JB_ERR_PARSE;
1781 /*********************************************************************
1783 * Function : client_save_content_length
1785 * Description : Save the Content-Length sent by the client.
1788 * 1 : csp = Current client state (buffers, headers, etc...)
1789 * 2 : header = On input, pointer to header to modify.
1790 * On output, pointer to the modified header, or NULL
1791 * to remove the header. This function frees the
1792 * original string if necessary.
1794 * Returns : JB_ERR_OK on success, or
1795 * JB_ERR_MEMORY on out-of-memory error.
1797 *********************************************************************/
1798 static jb_err client_save_content_length(struct client_state *csp, char **header)
1800 unsigned long long content_length = 0;
1802 assert(*(*header+14) == ':');
1804 if (JB_ERR_OK != get_content_length(*header, &content_length))
1806 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1811 csp->expected_client_content_length = content_length;
1816 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1820 /*********************************************************************
1822 * Function : client_connection
1824 * Description : Makes sure a proper "Connection:" header is
1825 * set and signals connection_header_adder
1829 * 1 : csp = Current client state (buffers, headers, etc...)
1830 * 2 : header = On input, pointer to header to modify.
1831 * On output, pointer to the modified header, or NULL
1832 * to remove the header. This function frees the
1833 * original string if necessary.
1835 * Returns : JB_ERR_OK on success, or
1836 * JB_ERR_MEMORY on out-of-memory error.
1838 *********************************************************************/
1839 static jb_err client_connection(struct client_state *csp, char **header)
1841 static const char connection_close[] = "Connection: close";
1843 if (!strcmpic(*header, connection_close))
1845 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1846 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1848 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1850 log_error(LOG_LEVEL_HEADER,
1851 "Removing \'%s\' to imply keep-alive.", *header);
1854 * While we imply keep-alive to the server,
1855 * we have to remember that the client didn't.
1857 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1861 char *old_header = *header;
1863 *header = strdup("Connection: keep-alive");
1866 return JB_ERR_MEMORY;
1868 log_error(LOG_LEVEL_HEADER,
1869 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1875 log_error(LOG_LEVEL_HEADER,
1876 "Keeping the client header '%s' around. "
1877 "The connection will not be kept alive.",
1879 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1882 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1884 log_error(LOG_LEVEL_HEADER,
1885 "Keeping the client header '%s' around. "
1886 "The server connection will be kept alive if possible.",
1888 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1889 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1893 char *old_header = *header;
1895 *header = strdup(connection_close);
1898 return JB_ERR_MEMORY;
1900 log_error(LOG_LEVEL_HEADER,
1901 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1905 /* Signal client_connection_adder() to return early. */
1906 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1912 /*********************************************************************
1914 * Function : crumble
1916 * Description : This is called if a header matches a pattern to "crunch"
1919 * 1 : csp = Current client state (buffers, headers, etc...)
1920 * 2 : header = On input, pointer to header to modify.
1921 * On output, pointer to the modified header, or NULL
1922 * to remove the header. This function frees the
1923 * original string if necessary.
1925 * Returns : JB_ERR_OK on success, or
1926 * JB_ERR_MEMORY on out-of-memory error.
1928 *********************************************************************/
1929 static jb_err crumble(struct client_state *csp, char **header)
1932 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1938 /*********************************************************************
1940 * Function : crunch_server_header
1942 * Description : Crunch server header if it matches a string supplied by the
1943 * user. Called from `sed'.
1946 * 1 : csp = Current client state (buffers, headers, etc...)
1947 * 2 : header = On input, pointer to header to modify.
1948 * On output, pointer to the modified header, or NULL
1949 * to remove the header. This function frees the
1950 * original string if necessary.
1952 * Returns : JB_ERR_OK on success and always succeeds
1954 *********************************************************************/
1955 static jb_err crunch_server_header(struct client_state *csp, char **header)
1957 const char *crunch_pattern;
1959 /* Do we feel like crunching? */
1960 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1962 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1964 /* Is the current header the lucky one? */
1965 if (strstr(*header, crunch_pattern))
1967 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1976 /*********************************************************************
1978 * Function : server_content_type
1980 * Description : Set the content-type for filterable types (text/.*,
1981 * .*xml.*, .*script.* and image/gif) unless filtering has been
1982 * forbidden (CT_TABOO) while parsing earlier headers.
1983 * NOTE: Since text/plain is commonly used by web servers
1984 * for files whose correct type is unknown, we don't
1985 * set CT_TEXT for it.
1988 * 1 : csp = Current client state (buffers, headers, etc...)
1989 * 2 : header = On input, pointer to header to modify.
1990 * On output, pointer to the modified header, or NULL
1991 * to remove the header. This function frees the
1992 * original string if necessary.
1994 * Returns : JB_ERR_OK on success, or
1995 * JB_ERR_MEMORY on out-of-memory error.
1997 *********************************************************************/
1998 static jb_err server_content_type(struct client_state *csp, char **header)
2000 /* Remove header if it isn't the first Content-Type header */
2001 if ((csp->content_type & CT_DECLARED))
2004 * Another, slightly slower, way to see if
2005 * we already parsed another Content-Type header.
2007 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2009 log_error(LOG_LEVEL_ERROR,
2010 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2018 * Signal that the Content-Type has been set.
2020 csp->content_type |= CT_DECLARED;
2022 if (!(csp->content_type & CT_TABOO))
2025 * XXX: The assumption that text/plain is a sign of
2026 * binary data seems to be somewhat unreasonable nowadays
2027 * and should be dropped after 3.0.8 is out.
2029 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2030 || strstr(*header, "xml")
2031 || strstr(*header, "script"))
2033 csp->content_type |= CT_TEXT;
2035 else if (strstr(*header, "image/gif"))
2037 csp->content_type |= CT_GIF;
2042 * Are we messing with the content type?
2044 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2047 * Make sure the user doesn't accidentally
2048 * change the content type of binary documents.
2050 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2053 *header = strdup("Content-Type: ");
2054 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2058 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2059 return JB_ERR_MEMORY;
2061 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2065 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2066 "It doesn't look like a content type that should be filtered. "
2067 "Enable force-text-mode if you know what you're doing.", *header);
2075 /*********************************************************************
2077 * Function : server_transfer_coding
2079 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2080 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2081 * - Remove header if body was chunked but has been
2082 * de-chunked for filtering.
2085 * 1 : csp = Current client state (buffers, headers, etc...)
2086 * 2 : header = On input, pointer to header to modify.
2087 * On output, pointer to the modified header, or NULL
2088 * to remove the header. This function frees the
2089 * original string if necessary.
2091 * Returns : JB_ERR_OK on success, or
2092 * JB_ERR_MEMORY on out-of-memory error.
2094 *********************************************************************/
2095 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2098 * Turn off pcrs and gif filtering if body compressed
2100 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2104 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2106 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2107 csp->http->cmd, *header);
2108 #endif /* def FEATURE_ZLIB */
2109 csp->content_type = CT_TABOO;
2113 * Raise flag if body chunked
2115 if (strstr(*header, "chunked"))
2117 csp->flags |= CSP_FLAG_CHUNKED;
2120 * If the body was modified, it has been de-chunked first
2121 * and the header must be removed.
2123 * FIXME: If there is more than one transfer encoding,
2124 * only the "chunked" part should be removed here.
2126 if (csp->flags & CSP_FLAG_MODIFIED)
2128 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2137 /*********************************************************************
2139 * Function : server_content_encoding
2141 * Description : Used to check if the content is compressed, and if
2142 * FEATURE_ZLIB is disabled, filtering is disabled as
2145 * If FEATURE_ZLIB is enabled and the compression type
2146 * supported, the content is marked for decompression.
2148 * XXX: Doesn't properly deal with multiple or with
2149 * unsupported but unknown encodings.
2150 * Is case-sensitive but shouldn't be.
2153 * 1 : csp = Current client state (buffers, headers, etc...)
2154 * 2 : header = On input, pointer to header to modify.
2155 * On output, pointer to the modified header, or NULL
2156 * to remove the header. This function frees the
2157 * original string if necessary.
2159 * Returns : JB_ERR_OK on success, or
2160 * JB_ERR_MEMORY on out-of-memory error.
2162 *********************************************************************/
2163 static jb_err server_content_encoding(struct client_state *csp, char **header)
2166 if (strstr(*header, "sdch"))
2169 * Shared Dictionary Compression over HTTP isn't supported,
2170 * filtering it anyway is pretty much guaranteed to mess up
2173 csp->content_type |= CT_TABOO;
2176 * Log a warning if the user expects the content to be filtered.
2178 if ((csp->rlist != NULL) &&
2179 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2181 log_error(LOG_LEVEL_INFO,
2182 "SDCH-compressed content detected, content filtering disabled. "
2183 "Consider suppressing SDCH offers made by the client.");
2186 else if (strstr(*header, "gzip"))
2188 /* Mark for gzip decompression */
2189 csp->content_type |= CT_GZIP;
2191 else if (strstr(*header, "deflate"))
2193 /* Mark for zlib decompression */
2194 csp->content_type |= CT_DEFLATE;
2196 else if (strstr(*header, "compress"))
2199 * We can't decompress this; therefore we can't filter
2202 csp->content_type |= CT_TABOO;
2204 #else /* !defined(FEATURE_ZLIB) */
2206 * XXX: Using a black list here isn't the right approach.
2208 * In case of SDCH, building with zlib support isn't
2211 if (strstr(*header, "gzip") ||
2212 strstr(*header, "compress") ||
2213 strstr(*header, "deflate") ||
2214 strstr(*header, "sdch"))
2217 * Body is compressed, turn off pcrs and gif filtering.
2219 csp->content_type |= CT_TABOO;
2222 * Log a warning if the user expects the content to be filtered.
2224 if ((csp->rlist != NULL) &&
2225 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2227 log_error(LOG_LEVEL_INFO,
2228 "Compressed content detected, content filtering disabled. "
2229 "Consider recompiling Privoxy with zlib support or "
2230 "enable the prevent-compression action.");
2233 #endif /* defined(FEATURE_ZLIB) */
2241 /*********************************************************************
2243 * Function : server_adjust_content_encoding
2245 * Description : Remove the Content-Encoding header if the
2246 * decompression was successful and the content
2250 * 1 : csp = Current client state (buffers, headers, etc...)
2251 * 2 : header = On input, pointer to header to modify.
2252 * On output, pointer to the modified header, or NULL
2253 * to remove the header. This function frees the
2254 * original string if necessary.
2256 * Returns : JB_ERR_OK on success, or
2257 * JB_ERR_MEMORY on out-of-memory error.
2259 *********************************************************************/
2260 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2262 if ((csp->flags & CSP_FLAG_MODIFIED)
2263 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2266 * We successfully decompressed the content,
2267 * and have to clean the header now, so the
2268 * client no longer expects compressed data.
2270 * XXX: There is a difference between cleaning
2271 * and removing it completely.
2273 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2280 #endif /* defined(FEATURE_ZLIB) */
2283 /*********************************************************************
2285 * Function : server_adjust_content_length
2287 * Description : Adjust Content-Length header if we modified
2291 * 1 : csp = Current client state (buffers, headers, etc...)
2292 * 2 : header = On input, pointer to header to modify.
2293 * On output, pointer to the modified header, or NULL
2294 * to remove the header. This function frees the
2295 * original string if necessary.
2297 * Returns : JB_ERR_OK on success, or
2298 * JB_ERR_MEMORY on out-of-memory error.
2300 *********************************************************************/
2301 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2303 /* Regenerate header if the content was modified. */
2304 if (csp->flags & CSP_FLAG_MODIFIED)
2306 const size_t header_length = 50;
2308 *header = malloc(header_length);
2309 if (*header == NULL)
2311 return JB_ERR_MEMORY;
2313 create_content_length_header(csp->content_length, *header, header_length);
2314 log_error(LOG_LEVEL_HEADER,
2315 "Adjusted Content-Length to %llu", csp->content_length);
2322 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2323 /*********************************************************************
2325 * Function : server_save_content_length
2327 * Description : Save the Content-Length sent by the server.
2330 * 1 : csp = Current client state (buffers, headers, etc...)
2331 * 2 : header = On input, pointer to header to modify.
2332 * On output, pointer to the modified header, or NULL
2333 * to remove the header. This function frees the
2334 * original string if necessary.
2336 * Returns : JB_ERR_OK on success, or
2337 * JB_ERR_MEMORY on out-of-memory error.
2339 *********************************************************************/
2340 static jb_err server_save_content_length(struct client_state *csp, char **header)
2342 unsigned long long content_length = 0;
2344 assert(*(*header+14) == ':');
2346 if (JB_ERR_OK != get_content_length(*header, &content_length))
2348 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2353 csp->expected_content_length = content_length;
2354 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2355 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2360 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2363 /*********************************************************************
2365 * Function : server_content_md5
2367 * Description : Crumble any Content-MD5 headers if the document was
2368 * modified. FIXME: Should we re-compute instead?
2371 * 1 : csp = Current client state (buffers, headers, etc...)
2372 * 2 : header = On input, pointer to header to modify.
2373 * On output, pointer to the modified header, or NULL
2374 * to remove the header. This function frees the
2375 * original string if necessary.
2377 * Returns : JB_ERR_OK on success, or
2378 * JB_ERR_MEMORY on out-of-memory error.
2380 *********************************************************************/
2381 static jb_err server_content_md5(struct client_state *csp, char **header)
2383 if (csp->flags & CSP_FLAG_MODIFIED)
2385 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2393 /*********************************************************************
2395 * Function : server_content_disposition
2397 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2398 * Called from `sed'.
2401 * 1 : csp = Current client state (buffers, headers, etc...)
2402 * 2 : header = On input, pointer to header to modify.
2403 * On output, pointer to the modified header, or NULL
2404 * to remove the header. This function frees the
2405 * original string if necessary.
2407 * Returns : JB_ERR_OK on success, or
2408 * JB_ERR_MEMORY on out-of-memory error.
2410 *********************************************************************/
2411 static jb_err server_content_disposition(struct client_state *csp, char **header)
2416 * Are we messing with the Content-Disposition header?
2418 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2424 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2426 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2429 * Blocking content-disposition header
2431 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2438 * Replacing Content-Disposition header
2441 *header = strdup("Content-Disposition: ");
2442 string_append(header, newval);
2444 if (*header != NULL)
2446 log_error(LOG_LEVEL_HEADER,
2447 "Content-Disposition header crunched and replaced with: %s", *header);
2450 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2454 /*********************************************************************
2456 * Function : server_last_modified
2458 * Description : Changes Last-Modified header to the actual date
2459 * to help hide-if-modified-since.
2460 * Called from `sed'.
2463 * 1 : csp = Current client state (buffers, headers, etc...)
2464 * 2 : header = On input, pointer to header to modify.
2465 * On output, pointer to the modified header, or NULL
2466 * to remove the header. This function frees the
2467 * original string if necessary.
2469 * Returns : JB_ERR_OK on success, or
2470 * JB_ERR_MEMORY on out-of-memory error.
2472 *********************************************************************/
2473 static jb_err server_last_modified(struct client_state *csp, char **header)
2476 time_t last_modified;
2480 * Are we messing with the Last-Modified header?
2482 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2488 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2490 if (0 == strcmpic(newval, "block") )
2493 * Blocking Last-Modified header. Useless but why not.
2495 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2499 else if (0 == strcmpic(newval, "reset-to-request-time"))
2502 * Setting Last-Modified Header to now.
2505 get_http_time(0, buf, sizeof(buf));
2507 *header = strdup("Last-Modified: ");
2508 string_append(header, buf);
2510 if (*header == NULL)
2512 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2516 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2519 else if (0 == strcmpic(newval, "randomize"))
2521 const char *header_time = *header + sizeof("Last-Modified:");
2523 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2525 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2527 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2533 struct tm *timeptr = NULL;
2535 #ifdef HAVE_GMTIME_R
2539 rtime = (long int)difftime(now, last_modified);
2542 long int days, hours, minutes, seconds;
2543 const int negative_delta = (rtime < 0);
2548 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2550 rtime = pick_from_range(rtime);
2555 last_modified += rtime;
2556 #ifdef HAVE_GMTIME_R
2557 timeptr = gmtime_r(&last_modified, &gmt);
2558 #elif defined(MUTEX_LOCKS_AVAILABLE)
2559 privoxy_mutex_lock(&gmtime_mutex);
2560 timeptr = gmtime(&last_modified);
2561 privoxy_mutex_unlock(&gmtime_mutex);
2563 timeptr = gmtime(&last_modified);
2565 if ((NULL == timeptr) || !strftime(newheader,
2566 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2568 log_error(LOG_LEVEL_ERROR,
2569 "Randomizing '%s' failed. Crunching the header without replacement.",
2576 *header = strdup("Last-Modified: ");
2577 string_append(header, newheader);
2579 if (*header == NULL)
2581 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2582 return JB_ERR_MEMORY;
2585 days = rtime / (3600 * 24);
2586 hours = rtime / 3600 % 24;
2587 minutes = rtime / 60 % 60;
2588 seconds = rtime % 60;
2590 log_error(LOG_LEVEL_HEADER,
2591 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2592 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2593 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2597 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2606 /*********************************************************************
2608 * Function : client_accept_encoding
2610 * Description : Rewrite the client's Accept-Encoding header so that
2611 * if doesn't allow compression, if the action applies.
2612 * Note: For HTTP/1.0 the absence of the header is enough.
2615 * 1 : csp = Current client state (buffers, headers, etc...)
2616 * 2 : header = On input, pointer to header to modify.
2617 * On output, pointer to the modified header, or NULL
2618 * to remove the header. This function frees the
2619 * original string if necessary.
2621 * Returns : JB_ERR_OK on success, or
2622 * JB_ERR_MEMORY on out-of-memory error.
2624 *********************************************************************/
2625 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2627 #ifdef FEATURE_COMPRESSION
2628 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2629 && strstr(*header, "deflate"))
2631 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2634 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2636 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2644 /*********************************************************************
2646 * Function : client_te
2648 * Description : Rewrite the client's TE header so that
2649 * if doesn't allow compression, if the action applies.
2652 * 1 : csp = Current client state (buffers, headers, etc...)
2653 * 2 : header = On input, pointer to header to modify.
2654 * On output, pointer to the modified header, or NULL
2655 * to remove the header. This function frees the
2656 * original string if necessary.
2658 * Returns : JB_ERR_OK on success, or
2659 * JB_ERR_MEMORY on out-of-memory error.
2661 *********************************************************************/
2662 static jb_err client_te(struct client_state *csp, char **header)
2664 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2667 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2674 /*********************************************************************
2676 * Function : client_referrer
2678 * Description : Handle the "referer" config setting properly.
2679 * Called from `sed'.
2682 * 1 : csp = Current client state (buffers, headers, etc...)
2683 * 2 : header = On input, pointer to header to modify.
2684 * On output, pointer to the modified header, or NULL
2685 * to remove the header. This function frees the
2686 * original string if necessary.
2688 * Returns : JB_ERR_OK on success, or
2689 * JB_ERR_MEMORY on out-of-memory error.
2691 *********************************************************************/
2692 static jb_err client_referrer(struct client_state *csp, char **header)
2694 const char *parameter;
2695 /* booleans for parameters we have to check multiple times */
2696 int parameter_conditional_block;
2697 int parameter_conditional_forge;
2699 #ifdef FEATURE_FORCE_LOAD
2701 * Since the referrer can include the prefix even
2702 * if the request itself is non-forced, we must
2703 * clean it unconditionally.
2705 * XXX: strclean is too broad
2707 strclean(*header, FORCE_PREFIX);
2708 #endif /* def FEATURE_FORCE_LOAD */
2710 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2712 /* Nothing left to do */
2716 parameter = csp->action->string[ACTION_STRING_REFERER];
2717 assert(parameter != NULL);
2718 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2719 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2721 if (!parameter_conditional_block && !parameter_conditional_forge)
2724 * As conditional-block and conditional-forge are the only
2725 * parameters that rely on the original referrer, we can
2726 * remove it now for all the others.
2731 if (0 == strcmpic(parameter, "block"))
2733 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2736 else if (parameter_conditional_block || parameter_conditional_forge)
2738 return handle_conditional_hide_referrer_parameter(header,
2739 csp->http->hostport, parameter_conditional_block);
2741 else if (0 == strcmpic(parameter, "forge"))
2743 return create_forged_referrer(header, csp->http->hostport);
2747 /* interpret parameter as user-supplied referer to fake */
2748 return create_fake_referrer(header, parameter);
2753 /*********************************************************************
2755 * Function : client_accept_language
2757 * Description : Handle the "Accept-Language" config setting properly.
2758 * Called from `sed'.
2761 * 1 : csp = Current client state (buffers, headers, etc...)
2762 * 2 : header = On input, pointer to header to modify.
2763 * On output, pointer to the modified header, or NULL
2764 * to remove the header. This function frees the
2765 * original string if necessary.
2767 * Returns : JB_ERR_OK on success, or
2768 * JB_ERR_MEMORY on out-of-memory error.
2770 *********************************************************************/
2771 static jb_err client_accept_language(struct client_state *csp, char **header)
2776 * Are we messing with the Accept-Language?
2778 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2780 /*I don't think so*/
2784 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2786 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2789 * Blocking Accept-Language header
2791 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2798 * Replacing Accept-Language header
2801 *header = strdup("Accept-Language: ");
2802 string_append(header, newval);
2804 if (*header == NULL)
2806 log_error(LOG_LEVEL_ERROR,
2807 "Insufficient memory. Accept-Language header crunched without replacement.");
2811 log_error(LOG_LEVEL_HEADER,
2812 "Accept-Language header crunched and replaced with: %s", *header);
2815 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2819 /*********************************************************************
2821 * Function : crunch_client_header
2823 * Description : Crunch client header if it matches a string supplied by the
2824 * user. Called from `sed'.
2827 * 1 : csp = Current client state (buffers, headers, etc...)
2828 * 2 : header = On input, pointer to header to modify.
2829 * On output, pointer to the modified header, or NULL
2830 * to remove the header. This function frees the
2831 * original string if necessary.
2833 * Returns : JB_ERR_OK on success and always succeeds
2835 *********************************************************************/
2836 static jb_err crunch_client_header(struct client_state *csp, char **header)
2838 const char *crunch_pattern;
2840 /* Do we feel like crunching? */
2841 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2843 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2845 /* Is the current header the lucky one? */
2846 if (strstr(*header, crunch_pattern))
2848 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2856 /*********************************************************************
2858 * Function : client_uagent
2860 * Description : Handle the "user-agent" config setting properly
2861 * and remember its original value to enable browser
2862 * bug workarounds. Called from `sed'.
2865 * 1 : csp = Current client state (buffers, headers, etc...)
2866 * 2 : header = On input, pointer to header to modify.
2867 * On output, pointer to the modified header, or NULL
2868 * to remove the header. This function frees the
2869 * original string if necessary.
2871 * Returns : JB_ERR_OK on success, or
2872 * JB_ERR_MEMORY on out-of-memory error.
2874 *********************************************************************/
2875 static jb_err client_uagent(struct client_state *csp, char **header)
2879 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2884 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2891 *header = strdup("User-Agent: ");
2892 string_append(header, newval);
2894 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2896 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2900 /*********************************************************************
2902 * Function : client_ua
2904 * Description : Handle "ua-" headers properly. Called from `sed'.
2907 * 1 : csp = Current client state (buffers, headers, etc...)
2908 * 2 : header = On input, pointer to header to modify.
2909 * On output, pointer to the modified header, or NULL
2910 * to remove the header. This function frees the
2911 * original string if necessary.
2913 * Returns : JB_ERR_OK on success, or
2914 * JB_ERR_MEMORY on out-of-memory error.
2916 *********************************************************************/
2917 static jb_err client_ua(struct client_state *csp, char **header)
2919 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2921 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2929 /*********************************************************************
2931 * Function : client_from
2933 * Description : Handle the "from" config setting properly.
2934 * Called from `sed'.
2937 * 1 : csp = Current client state (buffers, headers, etc...)
2938 * 2 : header = On input, pointer to header to modify.
2939 * On output, pointer to the modified header, or NULL
2940 * to remove the header. This function frees the
2941 * original string if necessary.
2943 * Returns : JB_ERR_OK on success, or
2944 * JB_ERR_MEMORY on out-of-memory error.
2946 *********************************************************************/
2947 static jb_err client_from(struct client_state *csp, char **header)
2951 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2958 newval = csp->action->string[ACTION_STRING_FROM];
2961 * Are we blocking the e-mail address?
2963 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2965 log_error(LOG_LEVEL_HEADER, "crunched From!");
2969 log_error(LOG_LEVEL_HEADER, " modified");
2971 *header = strdup("From: ");
2972 string_append(header, newval);
2974 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2978 /*********************************************************************
2980 * Function : client_send_cookie
2982 * Description : Crunches the "cookie" header if necessary.
2983 * Called from `sed'.
2985 * XXX: Stupid name, doesn't send squat.
2988 * 1 : csp = Current client state (buffers, headers, etc...)
2989 * 2 : header = On input, pointer to header to modify.
2990 * On output, pointer to the modified header, or NULL
2991 * to remove the header. This function frees the
2992 * original string if necessary.
2994 * Returns : JB_ERR_OK on success, or
2995 * JB_ERR_MEMORY on out-of-memory error.
2997 *********************************************************************/
2998 static jb_err client_send_cookie(struct client_state *csp, char **header)
3000 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3002 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3010 /*********************************************************************
3012 * Function : client_x_forwarded
3014 * Description : Handle the "x-forwarded-for" config setting properly,
3015 * also used in the add_client_headers list. Called from `sed'.
3018 * 1 : csp = Current client state (buffers, headers, etc...)
3019 * 2 : header = On input, pointer to header to modify.
3020 * On output, pointer to the modified header, or NULL
3021 * to remove the header. This function frees the
3022 * original string if necessary.
3024 * Returns : JB_ERR_OK on success, or
3025 * JB_ERR_MEMORY on out-of-memory error.
3027 *********************************************************************/
3028 jb_err client_x_forwarded(struct client_state *csp, char **header)
3030 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3032 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3034 if (0 == strcmpic(parameter, "block"))
3037 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3039 else if (0 == strcmpic(parameter, "add"))
3041 string_append(header, ", ");
3042 string_append(header, csp->ip_addr_str);
3044 if (*header == NULL)
3046 return JB_ERR_MEMORY;
3048 log_error(LOG_LEVEL_HEADER,
3049 "Appended client IP address to %s", *header);
3050 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3054 log_error(LOG_LEVEL_FATAL,
3055 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3063 /*********************************************************************
3065 * Function : client_max_forwards
3067 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3068 * from the value of the Max-Forwards header field.
3071 * 1 : csp = Current client state (buffers, headers, etc...)
3072 * 2 : header = On input, pointer to header to modify.
3073 * On output, pointer to the modified header, or NULL
3074 * to remove the header. This function frees the
3075 * original string if necessary.
3077 * Returns : JB_ERR_OK on success, or
3078 * JB_ERR_MEMORY on out-of-memory error.
3080 *********************************************************************/
3081 static jb_err client_max_forwards(struct client_state *csp, char **header)
3085 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3086 (0 == strcmpic(csp->http->gpc, "options")))
3088 assert(*(*header+12) == ':');
3089 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3091 if (max_forwards > 0)
3093 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3094 log_error(LOG_LEVEL_HEADER,
3095 "Max-Forwards value for %s request reduced to %d.",
3096 csp->http->gpc, max_forwards);
3098 else if (max_forwards < 0)
3100 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3106 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3115 /*********************************************************************
3117 * Function : client_host
3119 * Description : If the request URI did not contain host and
3120 * port information, parse and evaluate the Host
3123 * Also, kill ill-formed HOST: headers as sent by
3124 * Apple's iTunes software when used with a proxy.
3127 * 1 : csp = Current client state (buffers, headers, etc...)
3128 * 2 : header = On input, pointer to header to modify.
3129 * On output, pointer to the modified header, or NULL
3130 * to remove the header. This function frees the
3131 * original string if necessary.
3133 * Returns : JB_ERR_OK on success, or
3134 * JB_ERR_MEMORY on out-of-memory error.
3136 *********************************************************************/
3137 static jb_err client_host(struct client_state *csp, char **header)
3142 * If the header field name is all upper-case, chances are that it's
3143 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3144 * not a problem -- they are regenerated later.
3146 if ((*header)[1] == 'O')
3148 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3153 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3154 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3157 if (NULL == (p = strdup((*header)+6)))
3159 return JB_ERR_MEMORY;
3162 if (NULL == (q = strdup(p)))
3165 return JB_ERR_MEMORY;
3168 freez(csp->http->hostport);
3169 csp->http->hostport = p;
3170 freez(csp->http->host);
3171 csp->http->host = q;
3172 q = strchr(csp->http->host, ':');
3175 /* Terminate hostname and evaluate port string */
3177 csp->http->port = atoi(q);
3181 csp->http->port = csp->http->ssl ? 443 : 80;
3184 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3185 csp->http->hostport, csp->http->host, csp->http->port);
3188 /* Signal client_host_adder() to return right away */
3189 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3195 /*********************************************************************
3197 * Function : client_if_modified_since
3199 * Description : Remove or modify the If-Modified-Since header.
3202 * 1 : csp = Current client state (buffers, headers, etc...)
3203 * 2 : header = On input, pointer to header to modify.
3204 * On output, pointer to the modified header, or NULL
3205 * to remove the header. This function frees the
3206 * original string if necessary.
3208 * Returns : JB_ERR_OK on success, or
3209 * JB_ERR_MEMORY on out-of-memory error.
3211 *********************************************************************/
3212 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3215 #ifdef HAVE_GMTIME_R
3218 struct tm *timeptr = NULL;
3223 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3226 * The client got an error message because of a temporary problem,
3227 * the problem is gone and the client now tries to revalidate our
3228 * error message on the real server. The revalidation would always
3229 * end with the transmission of the whole document and there is
3230 * no need to expose the bogus If-Modified-Since header.
3232 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3235 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3237 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3239 if ((0 == strcmpic(newval, "block")))
3241 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3244 else /* add random value */
3246 const char *header_time = *header + sizeof("If-Modified-Since:");
3248 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3250 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3255 long int hours, minutes, seconds;
3256 long int rtime = strtol(newval, &endptr, 0);
3257 const int negative_range = (rtime < 0);
3261 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3262 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3268 rtime = pick_from_range(rtime);
3272 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3275 tm += rtime * (negative_range ? -1 : 1);
3276 #ifdef HAVE_GMTIME_R
3277 timeptr = gmtime_r(&tm, &gmt);
3278 #elif defined(MUTEX_LOCKS_AVAILABLE)
3279 privoxy_mutex_lock(&gmtime_mutex);
3280 timeptr = gmtime(&tm);
3281 privoxy_mutex_unlock(&gmtime_mutex);
3283 timeptr = gmtime(&tm);
3285 if ((NULL == timeptr) || !strftime(newheader,
3286 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3288 log_error(LOG_LEVEL_ERROR,
3289 "Randomizing '%s' failed. Crunching the header without replacement.",
3296 *header = strdup("If-Modified-Since: ");
3297 string_append(header, newheader);
3299 if (*header == NULL)
3301 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3302 return JB_ERR_MEMORY;
3305 hours = rtime / 3600;
3306 minutes = rtime / 60 % 60;
3307 seconds = rtime % 60;
3309 log_error(LOG_LEVEL_HEADER,
3310 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3311 *header, (negative_range) ? "subtracted" : "added", hours,
3312 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3313 seconds, (seconds == 1) ? ")" : "s)");
3322 /*********************************************************************
3324 * Function : client_if_none_match
3326 * Description : Remove the If-None-Match header.
3329 * 1 : csp = Current client state (buffers, headers, etc...)
3330 * 2 : header = On input, pointer to header to modify.
3331 * On output, pointer to the modified header, or NULL
3332 * to remove the header. This function frees the
3333 * original string if necessary.
3335 * Returns : JB_ERR_OK on success, or
3336 * JB_ERR_MEMORY on out-of-memory error.
3338 *********************************************************************/
3339 static jb_err client_if_none_match(struct client_state *csp, char **header)
3341 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3343 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3351 /*********************************************************************
3353 * Function : client_x_filter
3355 * Description : Disables filtering if the client set "X-Filter: No".
3356 * Called from `sed'.
3359 * 1 : csp = Current client state (buffers, headers, etc...)
3360 * 2 : header = On input, pointer to header to modify.
3361 * On output, pointer to the modified header, or NULL
3362 * to remove the header. This function frees the
3363 * original string if necessary.
3365 * Returns : JB_ERR_OK on success
3367 *********************************************************************/
3368 jb_err client_x_filter(struct client_state *csp, char **header)
3370 if ( 0 == strcmpic(*header, "X-Filter: No"))
3372 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3374 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3378 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3380 log_error(LOG_LEVEL_HEADER,
3381 "force-text-mode overruled the client's request to fetch without filtering!");
3385 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3386 csp->flags |= CSP_FLAG_NO_FILTERING;
3387 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3389 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3397 /*********************************************************************
3399 * Function : client_range
3401 * Description : Removes Range, Request-Range and If-Range headers if
3402 * content filtering is enabled. If the client's version
3403 * of the document has been altered by Privoxy, the server
3404 * could interpret the range differently than the client
3405 * intended in which case the user could end up with
3406 * corrupted content.
3409 * 1 : csp = Current client state (buffers, headers, etc...)
3410 * 2 : header = On input, pointer to header to modify.
3411 * On output, pointer to the modified header, or NULL
3412 * to remove the header. This function frees the
3413 * original string if necessary.
3415 * Returns : JB_ERR_OK
3417 *********************************************************************/
3418 static jb_err client_range(struct client_state *csp, char **header)
3420 if (content_filters_enabled(csp->action))
3422 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3423 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3430 /* the following functions add headers directly to the header list */
3432 /*********************************************************************
3434 * Function : client_host_adder
3436 * Description : Adds the Host: header field if it is missing.
3437 * Called from `sed'.
3440 * 1 : csp = Current client state (buffers, headers, etc...)
3442 * Returns : JB_ERR_OK on success, or
3443 * JB_ERR_MEMORY on out-of-memory error.
3445 *********************************************************************/
3446 static jb_err client_host_adder(struct client_state *csp)
3451 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3453 /* Header already set by the client, nothing to do. */
3457 if ( !csp->http->hostport || !*(csp->http->hostport))
3459 /* XXX: When does this happen and why is it OK? */
3460 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3465 * remove 'user:pass@' from 'proto://user:pass@host'
3467 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3473 p = csp->http->hostport;
3476 /* XXX: Just add it, we already made sure that it will be unique */
3477 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3478 err = enlist_unique_header(csp->headers, "Host", p);
3485 /*********************************************************************
3487 * Function : client_accept_encoding_adder
3489 * Description : Add an Accept-Encoding header to the client's request
3490 * that disables compression if the action applies, and
3491 * the header is not already there. Called from `sed'.
3492 * Note: For HTTP/1.0, the absence of the header is enough.
3495 * 1 : csp = Current client state (buffers, headers, etc...)
3497 * Returns : JB_ERR_OK on success, or
3498 * JB_ERR_MEMORY on out-of-memory error.
3500 *********************************************************************/
3501 static jb_err client_accept_encoding_adder(struct client_state *csp)
3503 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3504 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3506 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3514 /*********************************************************************
3516 * Function : client_xtra_adder
3518 * Description : Used in the add_client_headers list. Called from `sed'.
3521 * 1 : csp = Current client state (buffers, headers, etc...)
3523 * Returns : JB_ERR_OK on success, or
3524 * JB_ERR_MEMORY on out-of-memory error.
3526 *********************************************************************/
3527 static jb_err client_xtra_adder(struct client_state *csp)
3529 struct list_entry *lst;
3532 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3533 lst ; lst = lst->next)
3535 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3536 err = enlist(csp->headers, lst->str);
3548 /*********************************************************************
3550 * Function : client_x_forwarded_for_adder
3552 * Description : Used in the add_client_headers list. Called from `sed'.
3555 * 1 : csp = Current client state (buffers, headers, etc...)
3557 * Returns : JB_ERR_OK on success, or
3558 * JB_ERR_MEMORY on out-of-memory error.
3560 *********************************************************************/
3561 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3563 char *header = NULL;
3566 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3567 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3568 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3571 * If we aren't adding X-Forwarded-For headers,
3572 * or we already appended an existing X-Forwarded-For
3573 * header, there's nothing left to do here.
3578 header = strdup("X-Forwarded-For: ");
3579 string_append(&header, csp->ip_addr_str);
3583 return JB_ERR_MEMORY;
3586 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3587 err = enlist(csp->headers, header);
3594 /*********************************************************************
3596 * Function : server_connection_adder
3598 * Description : Adds an appropriate "Connection:" header to csp->headers
3599 * unless the header was already present. Called from `sed'.
3602 * 1 : csp = Current client state (buffers, headers, etc...)
3604 * Returns : JB_ERR_OK on success, or
3605 * JB_ERR_MEMORY on out-of-memory error.
3607 *********************************************************************/
3608 static jb_err server_connection_adder(struct client_state *csp)
3610 const unsigned int flags = csp->flags;
3611 const char *response_status_line = csp->headers->first->str;
3612 static const char connection_close[] = "Connection: close";
3614 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3615 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3621 * XXX: if we downgraded the response, this check will fail.
3623 if ((csp->config->feature_flags &
3624 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3625 && (NULL != response_status_line)
3626 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3627 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3628 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3632 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3633 "without Connection header implies keep-alive.");
3634 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3638 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3640 return enlist(csp->headers, connection_close);
3644 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3645 /*********************************************************************
3647 * Function : server_proxy_connection_adder
3649 * Description : Adds a "Proxy-Connection: keep-alive" header to
3650 * csp->headers if the client asked for keep-alive.
3651 * XXX: We should reuse existent ones.
3654 * 1 : csp = Current client state (buffers, headers, etc...)
3656 * Returns : JB_ERR_OK on success, or
3657 * JB_ERR_MEMORY on out-of-memory error.
3659 *********************************************************************/
3660 static jb_err server_proxy_connection_adder(struct client_state *csp)
3662 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3663 jb_err err = JB_ERR_OK;
3665 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3666 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3667 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET))
3669 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3670 err = enlist(csp->headers, proxy_connection_header);
3675 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3678 /*********************************************************************
3680 * Function : client_connection_header_adder
3682 * Description : Adds a proper "Connection:" header to csp->headers
3683 * unless the header was already present. Called from `sed'.
3686 * 1 : csp = Current client state (buffers, headers, etc...)
3688 * Returns : JB_ERR_OK on success, or
3689 * JB_ERR_MEMORY on out-of-memory error.
3691 *********************************************************************/
3692 static jb_err client_connection_header_adder(struct client_state *csp)
3694 static const char connection_close[] = "Connection: close";
3696 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3697 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3702 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3703 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3704 && (csp->http->ssl == 0)
3705 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3707 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3710 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3712 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3714 return enlist(csp->headers, connection_close);
3718 /*********************************************************************
3720 * Function : server_http
3722 * Description : - Save the HTTP Status into csp->http->status
3723 * - Set CT_TABOO to prevent filtering if the answer
3724 * is a partial range (HTTP status 206)
3725 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3729 * 1 : csp = Current client state (buffers, headers, etc...)
3730 * 2 : header = On input, pointer to header to modify.
3731 * On output, pointer to the modified header, or NULL
3732 * to remove the header. This function frees the
3733 * original string if necessary.
3735 * Returns : JB_ERR_OK on success, or
3736 * JB_ERR_MEMORY on out-of-memory error.
3738 *********************************************************************/
3739 static jb_err server_http(struct client_state *csp, char **header)
3741 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3742 if (csp->http->status == 206)
3744 csp->content_type = CT_TABOO;
3747 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3749 /* XXX: Should we do a real validity check here? */
3750 if (strlen(*header) > 8)
3753 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3758 * XXX: Should we block the request or
3759 * enlist a valid status code line here?
3761 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3762 "Downgrading to HTTP/1.0 impossible.");
3770 /*********************************************************************
3772 * Function : server_set_cookie
3774 * Description : Handle the server "cookie" header properly.
3775 * Crunch, accept or rewrite it to a session cookie.
3776 * Called from `sed'.
3778 * TODO: Allow the user to specify a new expiration
3779 * time to cause the cookie to expire even before the
3780 * browser is closed.
3783 * 1 : csp = Current client state (buffers, headers, etc...)
3784 * 2 : header = On input, pointer to header to modify.
3785 * On output, pointer to the modified header, or NULL
3786 * to remove the header. This function frees the
3787 * original string if necessary.
3789 * Returns : JB_ERR_OK on success, or
3790 * JB_ERR_MEMORY on out-of-memory error.
3792 *********************************************************************/
3793 static jb_err server_set_cookie(struct client_state *csp, char **header)
3800 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3802 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3805 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3807 /* Flag whether or not to log a message */
3810 /* A variable to store the tag we're working on */
3813 /* Skip "Set-Cookie:" (11 characters) in header */
3814 cur_tag = *header + 11;
3816 /* skip whitespace between "Set-Cookie:" and value */
3817 while (*cur_tag && ijb_isspace(*cur_tag))
3822 /* Loop through each tag in the cookie */
3826 char *next_tag = strchr(cur_tag, ';');
3827 if (next_tag != NULL)
3829 /* Skip the ';' character itself */
3832 /* skip whitespace ";" and start of tag */
3833 while (*next_tag && ijb_isspace(*next_tag))
3840 /* "Next tag" is the end of the string */
3841 next_tag = cur_tag + strlen(cur_tag);
3845 * Check the expiration date to see
3846 * if the cookie is still valid, if yes,
3847 * rewrite it to a session cookie.
3849 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3851 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3853 if ((expiration_date[0] == '"')
3854 && (expiration_date[1] != '\0'))
3857 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
3858 * that the expiration date isn't supposed to be quoted,
3859 * but some servers do it anyway.
3864 /* Did we detect the date properly? */
3865 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3868 * Nope, treat it as if it was still valid.
3870 * XXX: Should we remove the whole cookie instead?
3872 log_error(LOG_LEVEL_ERROR,
3873 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3874 string_move(cur_tag, next_tag);
3880 * Yes. Check if the cookie is still valid.
3882 * If the cookie is already expired it's probably
3883 * a delete cookie and even if it isn't, the browser
3884 * will discard it anyway.
3888 * XXX: timegm() isn't available on some AmigaOS
3889 * versions and our replacement doesn't work.
3891 * Our options are to either:
3893 * - disable session-cookies-only completely if timegm
3896 * - to simply remove all expired tags, like it has
3897 * been done until Privoxy 3.0.6 and to live with
3898 * the consequence that it can cause login/logout
3899 * problems on servers that don't validate their
3900 * input properly, or
3902 * - to replace it with mktime in which
3903 * case there is a slight chance of valid cookies
3904 * passing as already expired.
3906 * This is the way it's currently done and it's not
3907 * as bad as it sounds. If the missing GMT offset is
3908 * enough to change the result of the expiration check
3909 * the cookie will be only valid for a few hours
3910 * anyway, which in many cases will be shorter
3911 * than a browser session.
3913 if (cookie_time - now < 0)
3915 log_error(LOG_LEVEL_HEADER,
3916 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3917 /* Just in case some clown sets more then one expiration date */
3923 * Still valid, delete expiration date by copying
3924 * the rest of the string over it.
3926 string_move(cur_tag, next_tag);
3928 /* That changed the header, need to issue a log message */
3932 * Note that the next tag has now been moved to *cur_tag,
3933 * so we do not need to update the cur_tag pointer.
3941 /* Move on to next cookie tag */
3948 assert(NULL != *header);
3949 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3958 #ifdef FEATURE_FORCE_LOAD
3959 /*********************************************************************
3961 * Function : strclean
3963 * Description : In-Situ-Eliminate all occurrences of substring in
3967 * 1 : string = string to clean
3968 * 2 : substring = substring to eliminate
3970 * Returns : Number of eliminations
3972 *********************************************************************/
3973 int strclean(char *string, const char *substring)
3979 len = strlen(substring);
3981 while((pos = strstr(string, substring)) != NULL)
3988 while (*p++ != '\0');
3995 #endif /* def FEATURE_FORCE_LOAD */
3998 /*********************************************************************
4000 * Function : parse_header_time
4002 * Description : Parses time formats used in HTTP header strings
4003 * to get the numerical respresentation.
4006 * 1 : header_time = HTTP header time as string.
4007 * 2 : result = storage for header_time in seconds
4009 * Returns : JB_ERR_OK if the time format was recognized, or
4010 * JB_ERR_PARSE otherwise.
4012 *********************************************************************/
4013 static jb_err parse_header_time(const char *header_time, time_t *result)
4017 * Checking for two-digit years first in an
4018 * attempt to work around GNU libc's strptime()
4019 * reporting negative year values when using %Y.
4021 static const char * const time_formats[] = {
4022 /* Tue, 02-Jun-37 20:00:00 */
4023 "%a, %d-%b-%y %H:%M:%S",
4024 /* Tue, 02 Jun 2037 20:00:00 */
4025 "%a, %d %b %Y %H:%M:%S",
4026 /* Tue, 02-Jun-2037 20:00:00 */
4027 "%a, %d-%b-%Y %H:%M:%S",
4028 /* Tuesday, 02-Jun-2037 20:00:00 */
4029 "%A, %d-%b-%Y %H:%M:%S",
4030 /* Tuesday Jun 02 20:00:00 2037 */
4031 "%A %b %d %H:%M:%S %Y"
4035 for (i = 0; i < SZ(time_formats); i++)
4038 * Zero out gmt to prevent time zone offsets.
4039 * Documented to be required for GNU libc.
4041 memset(&gmt, 0, sizeof(gmt));
4043 if (NULL != strptime(header_time, time_formats[i], &gmt))
4045 /* Sanity check for GNU libc. */
4046 if (gmt.tm_year < 0)
4048 log_error(LOG_LEVEL_HEADER,
4049 "Failed to parse '%s' using '%s'. Moving on.",
4050 header_time, time_formats[i]);
4053 *result = timegm(&gmt);
4058 return JB_ERR_PARSE;
4063 /*********************************************************************
4065 * Function : get_destination_from_headers
4067 * Description : Parse the "Host:" header to get the request's destination.
4068 * Only needed if the client's request was forcefully
4069 * redirected into Privoxy.
4071 * Code mainly copied from client_host() which is currently
4072 * run too late for this purpose.
4075 * 1 : headers = List of headers (one of them hopefully being
4076 * the "Host:" header)
4077 * 2 : http = storage for the result (host, port and hostport).
4079 * Returns : JB_ERR_MEMORY in case of memory problems,
4080 * JB_ERR_PARSE if the host header couldn't be found,
4081 * JB_ERR_OK otherwise.
4083 *********************************************************************/
4084 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4090 host = get_header_value(headers, "Host:");
4094 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4095 return JB_ERR_PARSE;
4101 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4102 return JB_ERR_MEMORY;
4105 if (NULL == (q = strdup(p)))
4108 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4109 return JB_ERR_MEMORY;
4112 freez(http->hostport);
4116 q = strchr(http->host, ':');
4119 /* Terminate hostname and evaluate port string */
4121 http->port = atoi(q);
4125 http->port = http->ssl ? 443 : 80;
4128 /* Rebuild request URL */
4130 http->url = strdup(http->ssl ? "https://" : "http://");
4131 string_append(&http->url, http->hostport);
4132 string_append(&http->url, http->path);
4133 if (http->url == NULL)
4135 return JB_ERR_MEMORY;
4138 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4146 /*********************************************************************
4148 * Function : create_forged_referrer
4150 * Description : Helper for client_referrer to forge a referer as
4151 * 'http://[hostname:port/' to fool stupid
4152 * checks for in-site links
4155 * 1 : header = Pointer to header pointer
4156 * 2 : hostport = Host and optionally port as string
4158 * Returns : JB_ERR_OK in case of success, or
4159 * JB_ERR_MEMORY in case of memory problems.
4161 *********************************************************************/
4162 static jb_err create_forged_referrer(char **header, const char *hostport)
4164 assert(NULL == *header);
4166 *header = strdup("Referer: http://");
4167 string_append(header, hostport);
4168 string_append(header, "/");
4170 if (NULL == *header)
4172 return JB_ERR_MEMORY;
4175 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4182 /*********************************************************************
4184 * Function : create_fake_referrer
4186 * Description : Helper for client_referrer to create a fake referrer
4187 * based on a string supplied by the user.
4190 * 1 : header = Pointer to header pointer
4191 * 2 : hosthost = Referrer to fake
4193 * Returns : JB_ERR_OK in case of success, or
4194 * JB_ERR_MEMORY in case of memory problems.
4196 *********************************************************************/
4197 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4199 assert(NULL == *header);
4201 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4203 log_error(LOG_LEVEL_HEADER,
4204 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4206 *header = strdup("Referer: ");
4207 string_append(header, fake_referrer);
4209 if (NULL == *header)
4211 return JB_ERR_MEMORY;
4214 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4221 /*********************************************************************
4223 * Function : handle_conditional_hide_referrer_parameter
4225 * Description : Helper for client_referrer to crunch or forge
4226 * the referrer header if the host has changed.
4229 * 1 : header = Pointer to header pointer
4230 * 2 : host = The target host (may include the port)
4231 * 3 : parameter_conditional_block = Boolean to signal
4232 * if we're in conditional-block mode. If not set,
4233 * we're in conditional-forge mode.
4235 * Returns : JB_ERR_OK in case of success, or
4236 * JB_ERR_MEMORY in case of memory problems.
4238 *********************************************************************/
4239 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4240 const char *host, const int parameter_conditional_block)
4242 char *referer = strdup(*header);
4243 const size_t hostlength = strlen(host);
4244 const char *referer_url = NULL;
4246 if (NULL == referer)
4249 return JB_ERR_MEMORY;
4252 /* referer begins with 'Referer: http[s]://' */
4253 if ((hostlength+17) < strlen(referer))
4256 * Shorten referer to make sure the referer is blocked
4257 * if www.example.org/www.example.com-shall-see-the-referer/
4258 * links to www.example.com/
4260 referer[hostlength+17] = '\0';
4262 referer_url = strstr(referer, "http://");
4263 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4265 /* Host has changed, Referer is invalid or a https URL. */
4266 if (parameter_conditional_block)
4268 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4275 return create_forged_referrer(header, host);
4285 /*********************************************************************
4287 * Function : create_content_length_header
4289 * Description : Creates a Content-Length header.
4292 * 1 : content_length = The content length to be used in the header.
4293 * 2 : header = Allocated space to safe the header.
4294 * 3 : buffer_length = The length of the allocated space.
4298 *********************************************************************/
4299 static void create_content_length_header(unsigned long long content_length,
4300 char *header, size_t buffer_length)
4302 snprintf(header, buffer_length, "Content-Length: %llu", content_length);