1 const char parsers_rcs[] = "$Id: parsers.c,v 1.198 2009/07/14 17:50:34 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2009 the
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
45 *********************************************************************/
52 #include <sys/types.h>
62 * Convince GNU's libc to provide a strptime prototype.
71 #define GZIP_IDENTIFIER_1 0x1f
72 #define GZIP_IDENTIFIER_2 0x8b
74 #define GZIP_FLAG_CHECKSUM 0x02
75 #define GZIP_FLAG_EXTRA_FIELDS 0x04
76 #define GZIP_FLAG_FILE_NAME 0x08
77 #define GZIP_FLAG_COMMENT 0x10
78 #define GZIP_FLAG_RESERVED_BITS 0xe0
81 #if !defined(_WIN32) && !defined(__OS2__)
87 #ifdef FEATURE_PTHREAD
89 /* jcc.h is for mutex semapores only */
90 #endif /* def FEATURE_PTHREAD */
95 #include "jbsockets.h"
101 #ifndef HAVE_STRPTIME
102 #include "strptime.h"
105 const char parsers_h_rcs[] = PARSERS_H_VERSION;
107 /* Fix a problem with Solaris. There should be no effect on other
109 * Solaris's isspace() is a macro which uses its argument directly
110 * as an array index. Therefore we need to make sure that high-bit
111 * characters generate +ve values, and ideally we also want to make
112 * the argument match the declared parameter type of "int".
114 * Why did they write a character function that can't take a simple
115 * "char" argument? Doh!
117 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
118 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
120 static char *get_header_line(struct iob *iob);
121 static jb_err scan_headers(struct client_state *csp);
122 static jb_err header_tagger(struct client_state *csp, char *header);
123 static jb_err parse_header_time(const char *header_time, time_t *result);
125 static jb_err crumble (struct client_state *csp, char **header);
126 static jb_err filter_header (struct client_state *csp, char **header);
127 static jb_err client_connection (struct client_state *csp, char **header);
128 static jb_err client_referrer (struct client_state *csp, char **header);
129 static jb_err client_uagent (struct client_state *csp, char **header);
130 static jb_err client_ua (struct client_state *csp, char **header);
131 static jb_err client_from (struct client_state *csp, char **header);
132 static jb_err client_send_cookie (struct client_state *csp, char **header);
133 static jb_err client_x_forwarded (struct client_state *csp, char **header);
134 static jb_err client_accept_encoding (struct client_state *csp, char **header);
135 static jb_err client_te (struct client_state *csp, char **header);
136 static jb_err client_max_forwards (struct client_state *csp, char **header);
137 static jb_err client_host (struct client_state *csp, char **header);
138 static jb_err client_if_modified_since (struct client_state *csp, char **header);
139 static jb_err client_accept_language (struct client_state *csp, char **header);
140 static jb_err client_if_none_match (struct client_state *csp, char **header);
141 static jb_err crunch_client_header (struct client_state *csp, char **header);
142 static jb_err client_x_filter (struct client_state *csp, char **header);
143 static jb_err client_range (struct client_state *csp, char **header);
144 static jb_err server_set_cookie (struct client_state *csp, char **header);
145 static jb_err server_connection (struct client_state *csp, char **header);
146 static jb_err server_content_type (struct client_state *csp, char **header);
147 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
148 static jb_err server_content_md5 (struct client_state *csp, char **header);
149 static jb_err server_content_encoding (struct client_state *csp, char **header);
150 static jb_err server_transfer_coding (struct client_state *csp, char **header);
151 static jb_err server_http (struct client_state *csp, char **header);
152 static jb_err crunch_server_header (struct client_state *csp, char **header);
153 static jb_err server_last_modified (struct client_state *csp, char **header);
154 static jb_err server_content_disposition(struct client_state *csp, char **header);
156 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
157 static jb_err server_save_content_length(struct client_state *csp, char **header);
158 static jb_err server_keep_alive(struct client_state *csp, char **header);
159 static jb_err server_proxy_connection(struct client_state *csp, char **header);
160 static jb_err client_keep_alive(struct client_state *csp, char **header);
161 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
163 static jb_err client_host_adder (struct client_state *csp);
164 static jb_err client_xtra_adder (struct client_state *csp);
165 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
166 static jb_err client_connection_header_adder(struct client_state *csp);
167 static jb_err server_connection_adder(struct client_state *csp);
168 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
169 static jb_err server_proxy_connection_adder(struct client_state *csp);
170 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
172 static jb_err create_forged_referrer(char **header, const char *hostport);
173 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
174 static jb_err handle_conditional_hide_referrer_parameter(char **header,
175 const char *host, const int parameter_conditional_block);
176 static void create_content_length_header(unsigned long long content_length,
177 char *header, size_t buffer_length);
180 * List of functions to run on a list of headers.
184 /** The header prefix to match */
187 /** The length of the prefix to match */
190 /** The function to apply to this line */
191 const parser_func_ptr parser;
194 static const struct parsers client_patterns[] = {
195 { "referer:", 8, client_referrer },
196 { "user-agent:", 11, client_uagent },
197 { "ua-", 3, client_ua },
198 { "from:", 5, client_from },
199 { "cookie:", 7, client_send_cookie },
200 { "x-forwarded-for:", 16, client_x_forwarded },
201 { "Accept-Encoding:", 16, client_accept_encoding },
202 { "TE:", 3, client_te },
203 { "Host:", 5, client_host },
204 { "if-modified-since:", 18, client_if_modified_since },
205 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
206 { "Keep-Alive:", 11, client_keep_alive },
208 { "Keep-Alive:", 11, crumble },
210 { "connection:", 11, client_connection },
211 { "proxy-connection:", 17, crumble },
212 { "max-forwards:", 13, client_max_forwards },
213 { "Accept-Language:", 16, client_accept_language },
214 { "if-none-match:", 14, client_if_none_match },
215 { "Range:", 6, client_range },
216 { "Request-Range:", 14, client_range },
217 { "If-Range:", 9, client_range },
218 { "X-Filter:", 9, client_x_filter },
219 { "*", 0, crunch_client_header },
220 { "*", 0, filter_header },
224 static const struct parsers server_patterns[] = {
225 { "HTTP/", 5, server_http },
226 { "set-cookie:", 11, server_set_cookie },
227 { "connection:", 11, server_connection },
228 { "Content-Type:", 13, server_content_type },
229 { "Content-MD5:", 12, server_content_md5 },
230 { "Content-Encoding:", 17, server_content_encoding },
231 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
232 { "Content-Length:", 15, server_save_content_length },
233 { "Keep-Alive:", 11, server_keep_alive },
234 { "Proxy-Connection:", 17, server_proxy_connection },
236 { "Keep-Alive:", 11, crumble },
237 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
238 { "Transfer-Encoding:", 18, server_transfer_coding },
239 { "content-disposition:", 20, server_content_disposition },
240 { "Last-Modified:", 14, server_last_modified },
241 { "*", 0, crunch_server_header },
242 { "*", 0, filter_header },
246 static const add_header_func_ptr add_client_headers[] = {
248 client_x_forwarded_for_adder,
250 /* Temporarily disabled: client_accept_encoding_adder, */
251 client_connection_header_adder,
255 static const add_header_func_ptr add_server_headers[] = {
256 server_connection_adder,
257 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
258 server_proxy_connection_adder,
259 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
263 /*********************************************************************
265 * Function : flush_socket
267 * Description : Write any pending "buffered" content.
270 * 1 : fd = file descriptor of the socket to read
271 * 2 : iob = The I/O buffer to flush, usually csp->iob.
273 * Returns : On success, the number of bytes written are returned (zero
274 * indicates nothing was written). On error, -1 is returned,
275 * and errno is set appropriately. If count is zero and the
276 * file descriptor refers to a regular file, 0 will be
277 * returned without causing any other effect. For a special
278 * file, the results are not portable.
280 *********************************************************************/
281 long flush_socket(jb_socket fd, struct iob *iob)
283 long len = iob->eod - iob->cur;
290 if (write_socket(fd, iob->cur, (size_t)len))
294 iob->eod = iob->cur = iob->buf;
300 /*********************************************************************
302 * Function : add_to_iob
304 * Description : Add content to the buffered page, expanding the
305 * buffer if necessary.
308 * 1 : csp = Current client state (buffers, headers, etc...)
309 * 2 : buf = holds the content to be added to the page
310 * 3 : n = number of bytes to be added
312 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
313 * or buffer limit reached.
315 *********************************************************************/
316 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
318 struct iob *iob = csp->iob;
319 size_t used, offset, need, want;
322 if (n <= 0) return JB_ERR_OK;
324 used = (size_t)(iob->eod - iob->buf);
325 offset = (size_t)(iob->cur - iob->buf);
326 need = used + (size_t)n + 1;
329 * If the buffer can't hold the new data, extend it first.
330 * Use the next power of two if possible, else use the actual need.
332 if (need > csp->config->buffer_limit)
334 log_error(LOG_LEVEL_INFO,
335 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
336 need, csp->config->buffer_limit);
337 return JB_ERR_MEMORY;
340 if (need > iob->size)
342 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
344 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
348 else if (NULL != (p = (char *)realloc(iob->buf, need)))
354 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
355 return JB_ERR_MEMORY;
358 /* Update the iob pointers */
359 iob->cur = p + offset;
364 /* copy the new data into the iob buffer */
365 memcpy(iob->eod, buf, (size_t)n);
367 /* point to the end of the data */
370 /* null terminate == cheap insurance */
379 /*********************************************************************
381 * Function : decompress_iob
383 * Description : Decompress buffered page, expanding the
384 * buffer as necessary. csp->iob->cur
385 * should point to the the beginning of the
386 * compressed data block.
389 * 1 : csp = Current client state (buffers, headers, etc...)
391 * Returns : JB_ERR_OK on success,
392 * JB_ERR_MEMORY if out-of-memory limit reached, and
393 * JB_ERR_COMPRESS if error decompressing buffer.
395 *********************************************************************/
396 jb_err decompress_iob(struct client_state *csp)
398 char *buf; /* new, uncompressed buffer */
399 char *cur; /* Current iob position (to keep the original
400 * iob->cur unmodified if we return early) */
401 size_t bufsize; /* allocated size of the new buffer */
402 size_t old_size; /* Content size before decompression */
403 size_t skip_size; /* Number of bytes at the beginning of the iob
404 that we should NOT decompress. */
405 int status; /* return status of the inflate() call */
406 z_stream zstr; /* used by calls to zlib */
408 assert(csp->iob->cur - csp->iob->buf > 0);
409 assert(csp->iob->eod - csp->iob->cur > 0);
411 bufsize = csp->iob->size;
412 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
413 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
417 if (bufsize < (size_t)10)
420 * This is to protect the parsing of gzipped data,
421 * but it should(?) be valid for deflated data also.
423 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
424 return JB_ERR_COMPRESS;
427 if (csp->content_type & CT_GZIP)
430 * Our task is slightly complicated by the facts that data
431 * compressed by gzip does not include a zlib header, and
432 * that there is no easily accessible interface in zlib to
433 * handle a gzip header. We strip off the gzip header by
434 * hand, and later inform zlib not to expect a header.
438 * Strip off the gzip header. Please see RFC 1952 for more
439 * explanation of the appropriate fields.
441 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
442 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
443 || (*cur++ != Z_DEFLATED))
445 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
446 return JB_ERR_COMPRESS;
451 if (flags & GZIP_FLAG_RESERVED_BITS)
453 /* The gzip header has reserved bits set; bail out. */
454 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
455 return JB_ERR_COMPRESS;
459 * Skip mtime (4 bytes), extra flags (1 byte)
460 * and OS type (1 byte).
464 /* Skip extra fields if necessary. */
465 if (flags & GZIP_FLAG_EXTRA_FIELDS)
468 * Skip a given number of bytes, specified
469 * as a 16-bit little-endian value.
471 * XXX: this code is untested and should probably be removed.
475 skip_bytes += *cur++ << 8;
478 * The number of bytes to skip should be positive
479 * and we'd like to stay in the buffer.
481 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
483 log_error(LOG_LEVEL_ERROR,
484 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
486 return JB_ERR_COMPRESS;
488 log_error(LOG_LEVEL_INFO,
489 "Skipping %d bytes for gzip compression. Does this sound right?",
494 /* Skip the filename if necessary. */
495 if (flags & GZIP_FLAG_FILE_NAME)
497 /* A null-terminated string is supposed to follow. */
498 while (*cur++ && (cur < csp->iob->eod));
501 /* Skip the comment if necessary. */
502 if (flags & GZIP_FLAG_COMMENT)
504 /* A null-terminated string is supposed to follow. */
505 while (*cur++ && (cur < csp->iob->eod));
508 /* Skip the CRC if necessary. */
509 if (flags & GZIP_FLAG_CHECKSUM)
514 if (cur >= csp->iob->eod)
517 * If the current position pointer reached or passed
518 * the buffer end, we were obviously tricked to skip
521 log_error(LOG_LEVEL_ERROR,
522 "Malformed gzip header detected. Aborting decompression.");
523 return JB_ERR_COMPRESS;
527 else if (csp->content_type & CT_DEFLATE)
530 * XXX: The debug level should be lowered
531 * before the next stable release.
533 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
535 * In theory (that is, according to RFC 1950), deflate-compressed
536 * data should begin with a two-byte zlib header and have an
537 * adler32 checksum at the end. It seems that in practice only
538 * the raw compressed data is sent. Note that this means that
539 * we are not RFC 1950-compliant here, but the advantage is that
540 * this actually works. :)
542 * We add a dummy null byte to tell zlib where the data ends,
543 * and later inform it not to expect a header.
545 * Fortunately, add_to_iob() has thoughtfully null-terminated
546 * the buffer; we can just increment the end pointer to include
553 log_error(LOG_LEVEL_ERROR,
554 "Unable to determine compression format for decompression");
555 return JB_ERR_COMPRESS;
558 /* Set up the fields required by zlib. */
559 zstr.next_in = (Bytef *)cur;
560 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
561 zstr.zalloc = Z_NULL;
563 zstr.opaque = Z_NULL;
566 * Passing -MAX_WBITS to inflateInit2 tells the library
567 * that there is no zlib header.
569 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
571 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
572 return JB_ERR_COMPRESS;
576 * Next, we allocate new storage for the inflated data.
577 * We don't modify the existing iob yet, so in case there
578 * is error in decompression we can recover gracefully.
580 buf = zalloc(bufsize);
583 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
584 return JB_ERR_MEMORY;
587 assert(bufsize >= skip_size);
588 memcpy(buf, csp->iob->buf, skip_size);
589 zstr.avail_out = bufsize - skip_size;
590 zstr.next_out = (Bytef *)buf + skip_size;
592 /* Try to decompress the whole stream in one shot. */
593 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
595 /* We need to allocate more memory for the output buffer. */
597 char *tmpbuf; /* used for realloc'ing the buffer */
598 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
600 if (0 == zstr.avail_in)
603 * If zlib wants more data then there's a problem, because
604 * the complete compressed file should have been buffered.
606 log_error(LOG_LEVEL_ERROR,
607 "Unexpected end of compressed iob. Using what we got so far.");
612 * If we tried the limit and still didn't have enough
613 * memory, just give up.
615 if (bufsize == csp->config->buffer_limit)
617 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
618 return JB_ERR_MEMORY;
621 /* Try doubling the buffer size each time. */
624 /* Don't exceed the buffer limit. */
625 if (bufsize > csp->config->buffer_limit)
627 bufsize = csp->config->buffer_limit;
630 /* Try to allocate the new buffer. */
631 tmpbuf = realloc(buf, bufsize);
634 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
636 return JB_ERR_MEMORY;
640 char *oldnext_out = (char *)zstr.next_out;
643 * Update the fields for inflate() to use the new
644 * buffer, which may be in a location different from
647 zstr.avail_out += bufsize - oldbufsize;
648 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
651 * Compare with an uglier method of calculating these values
652 * that doesn't require the extra oldbufsize variable.
654 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
655 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
656 assert(zstr.avail_out > 0U);
662 if (Z_STREAM_ERROR == inflateEnd(&zstr))
664 log_error(LOG_LEVEL_ERROR,
665 "Inconsistent stream state after decompression: %s", zstr.msg);
667 * XXX: Intentionally no return.
669 * According to zlib.h, Z_STREAM_ERROR is returned
670 * "if the stream state was inconsistent".
672 * I assume in this case inflate()'s status
673 * would also be something different than Z_STREAM_END
674 * so this check should be redundant, but lets see.
678 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
681 * We failed to decompress the stream and it's
682 * not simply because of missing data.
684 log_error(LOG_LEVEL_ERROR,
685 "Unexpected error while decompressing to the buffer (iob): %s",
687 return JB_ERR_COMPRESS;
691 * Finally, we can actually update the iob, since the
692 * decompression was successful. First, free the old
695 freez(csp->iob->buf);
697 /* Now, update the iob to use the new buffer. */
699 csp->iob->cur = csp->iob->buf + skip_size;
700 csp->iob->eod = (char *)zstr.next_out;
701 csp->iob->size = bufsize;
704 * Make sure the new uncompressed iob obeys some minimal
705 * consistency conditions.
707 if ((csp->iob->buf < csp->iob->cur)
708 && (csp->iob->cur <= csp->iob->eod)
709 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
711 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
712 if (new_size > (size_t)0)
714 log_error(LOG_LEVEL_RE_FILTER,
715 "Decompression successful. Old size: %d, new size: %d.",
720 /* zlib thinks this is OK, so lets do the same. */
721 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
726 /* It seems that zlib did something weird. */
727 log_error(LOG_LEVEL_ERROR,
728 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
729 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
730 csp->iob->eod, csp->iob->buf + csp->iob->size);
731 return JB_ERR_COMPRESS;
737 #endif /* defined(FEATURE_ZLIB) */
740 /*********************************************************************
742 * Function : string_move
744 * Description : memmove wrapper to move the last part of a string
745 * towards the beginning, overwriting the part in
746 * the middle. strlcpy() can't be used here as the
750 * 1 : dst = Destination to overwrite
751 * 2 : src = Source to move.
755 *********************************************************************/
756 static void string_move(char *dst, char *src)
760 /* +1 to copy the terminating nul as well. */
761 memmove(dst, src, strlen(src)+1);
765 /*********************************************************************
767 * Function : normalize_lws
769 * Description : Reduces unquoted linear white space in headers
770 * to a single space in accordance with RFC 2616 2.2.
771 * This simplifies parsing and filtering later on.
773 * XXX: Remove log messages before
774 * the next stable release?
777 * 1 : header = A header with linear white space to reduce.
781 *********************************************************************/
782 static void normalize_lws(char *header)
788 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
792 while (ijb_isspace(*q))
796 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
802 log_error(LOG_LEVEL_HEADER,
803 "Converting tab to space in '%s'", header);
808 char *end_of_token = strstr(p+1, "\"");
810 if (NULL != end_of_token)
812 /* Don't mess with quoted text. */
817 log_error(LOG_LEVEL_HEADER,
818 "Ignoring single quote in '%s'", header);
824 p = strchr(header, ':');
825 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
828 * There's still space before the colon.
836 /*********************************************************************
838 * Function : get_header
840 * Description : This (odd) routine will parse the csp->iob
841 * to get the next complete header.
844 * 1 : iob = The I/O buffer to parse, usually csp->iob.
846 * Returns : Any one of the following:
848 * 1) a pointer to a dynamically allocated string that contains a header line
849 * 2) NULL indicating that the end of the header was reached
850 * 3) "" indicating that the end of the iob was reached before finding
851 * a complete header line.
853 *********************************************************************/
854 char *get_header(struct iob *iob)
858 header = get_header_line(iob);
860 if ((header == NULL) || (*header == '\0'))
863 * No complete header read yet, tell the client.
868 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
871 * Header spans multiple lines, append the next one.
873 char *continued_header;
875 continued_header = get_header_line(iob);
876 if ((continued_header == NULL) || (*continued_header == '\0'))
879 * No complete header read yet, return what we got.
880 * XXX: Should "unread" header instead.
882 log_error(LOG_LEVEL_INFO,
883 "Failed to read a multi-line header properly: '%s'",
888 if (JB_ERR_OK != string_join(&header, continued_header))
890 log_error(LOG_LEVEL_FATAL,
891 "Out of memory while appending multiple headers.");
895 /* XXX: remove before next stable release. */
896 log_error(LOG_LEVEL_HEADER,
897 "Merged multiple header lines to: '%s'",
902 normalize_lws(header);
909 /*********************************************************************
911 * Function : get_header_line
913 * Description : This (odd) routine will parse the csp->iob
914 * to get the next header line.
917 * 1 : iob = The I/O buffer to parse, usually csp->iob.
919 * Returns : Any one of the following:
921 * 1) a pointer to a dynamically allocated string that contains a header line
922 * 2) NULL indicating that the end of the header was reached
923 * 3) "" indicating that the end of the iob was reached before finding
924 * a complete header line.
926 *********************************************************************/
927 static char *get_header_line(struct iob *iob)
931 if ((iob->cur == NULL)
932 || ((p = strchr(iob->cur, '\n')) == NULL))
934 return(""); /* couldn't find a complete header */
939 ret = strdup(iob->cur);
942 /* FIXME No way to handle error properly */
943 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
949 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
951 /* is this a blank line (i.e. the end of the header) ? */
963 /*********************************************************************
965 * Function : get_header_value
967 * Description : Get the value of a given header from a chained list
968 * of header lines or return NULL if no such header is
969 * present in the list.
972 * 1 : header_list = pointer to list
973 * 2 : header_name = string with name of header to look for.
974 * Trailing colon required, capitalization
977 * Returns : NULL if not found, else value of header
979 *********************************************************************/
980 char *get_header_value(const struct list *header_list, const char *header_name)
982 struct list_entry *cur_entry;
988 length = strlen(header_name);
990 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
994 if (!strncmpic(cur_entry->str, header_name, length))
997 * Found: return pointer to start of value
999 ret = cur_entry->str + length;
1000 while (*ret && ijb_isspace(*ret)) ret++;
1014 /*********************************************************************
1016 * Function : scan_headers
1018 * Description : Scans headers, applies tags and updates action bits.
1021 * 1 : csp = Current client state (buffers, headers, etc...)
1023 * Returns : JB_ERR_OK
1025 *********************************************************************/
1026 static jb_err scan_headers(struct client_state *csp)
1028 struct list_entry *h; /* Header */
1029 jb_err err = JB_ERR_OK;
1031 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1033 /* Header crunch()ed in previous run? -> ignore */
1034 if (h->str == NULL) continue;
1035 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1036 err = header_tagger(csp, h->str);
1043 /*********************************************************************
1047 * Description : add, delete or modify lines in the HTTP header streams.
1048 * On entry, it receives a linked list of headers space
1049 * that was allocated dynamically (both the list nodes
1050 * and the header contents).
1052 * As a side effect it frees the space used by the original
1056 * 1 : csp = Current client state (buffers, headers, etc...)
1057 * 2 : filter_server_headers = Boolean to switch between
1058 * server and header filtering.
1060 * Returns : JB_ERR_OK in case off success, or
1061 * JB_ERR_MEMORY on out-of-memory error.
1063 *********************************************************************/
1064 jb_err sed(struct client_state *csp, int filter_server_headers)
1066 /* XXX: use more descriptive names. */
1067 struct list_entry *p;
1068 const struct parsers *v;
1069 const add_header_func_ptr *f;
1070 jb_err err = JB_ERR_OK;
1072 if (filter_server_headers)
1074 v = server_patterns;
1075 f = add_server_headers;
1079 v = client_patterns;
1080 f = add_client_headers;
1085 while ((err == JB_ERR_OK) && (v->str != NULL))
1087 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1089 /* Header crunch()ed in previous run? -> ignore */
1090 if (p->str == NULL) continue;
1092 /* Does the current parser handle this header? */
1093 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1094 (v->len == CHECK_EVERY_HEADER_REMAINING))
1096 err = v->parser(csp, &(p->str));
1102 /* place additional headers on the csp->headers list */
1103 while ((err == JB_ERR_OK) && (*f))
1113 /*********************************************************************
1115 * Function : update_server_headers
1117 * Description : Updates server headers after the body has been modified.
1120 * 1 : csp = Current client state (buffers, headers, etc...)
1122 * Returns : JB_ERR_OK in case off success, or
1123 * JB_ERR_MEMORY on out-of-memory error.
1125 *********************************************************************/
1126 jb_err update_server_headers(struct client_state *csp)
1128 jb_err err = JB_ERR_OK;
1130 static const struct parsers server_patterns_light[] = {
1131 { "Content-Length:", 15, server_adjust_content_length },
1132 { "Transfer-Encoding:", 18, server_transfer_coding },
1134 { "Content-Encoding:", 17, server_content_encoding },
1135 #endif /* def FEATURE_ZLIB */
1139 if (strncmpic(csp->http->cmd, "HEAD", 4))
1141 const struct parsers *v;
1142 struct list_entry *p;
1144 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1146 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1148 /* Header crunch()ed in previous run? -> ignore */
1149 if (p->str == NULL) continue;
1151 /* Does the current parser handle this header? */
1152 if (strncmpic(p->str, v->str, v->len) == 0)
1154 err = v->parser(csp, (char **)&(p->str));
1160 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1161 if ((JB_ERR_OK == err)
1162 && (csp->flags & CSP_FLAG_MODIFIED)
1163 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1164 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1168 create_content_length_header(csp->content_length, header, sizeof(header));
1169 err = enlist(csp->headers, header);
1170 if (JB_ERR_OK == err)
1172 log_error(LOG_LEVEL_HEADER,
1173 "Content modified with no Content-Length header set. "
1174 "Created: %s.", header);
1177 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1183 /*********************************************************************
1185 * Function : header_tagger
1187 * Description : Executes all text substitutions from applying
1188 * tag actions and saves the result as tag.
1190 * XXX: Shares enough code with filter_header() and
1191 * pcrs_filter_response() to warrant some helper functions.
1194 * 1 : csp = Current client state (buffers, headers, etc...)
1195 * 2 : header = Header that is used as tagger input
1197 * Returns : JB_ERR_OK on success and always succeeds
1199 *********************************************************************/
1200 static jb_err header_tagger(struct client_state *csp, char *header)
1202 int wanted_filter_type;
1203 int multi_action_index;
1207 struct file_list *fl;
1208 struct re_filterfile_spec *b;
1209 struct list_entry *tag_name;
1211 int found_filters = 0;
1212 const size_t header_length = strlen(header);
1214 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1216 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1217 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1221 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1222 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1225 /* Check if there are any filters */
1226 for (i = 0; i < MAX_AF_FILES; i++)
1239 if (0 == found_filters)
1241 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1242 "tagging enabled, but no taggers available.");
1246 for (i = 0; i < MAX_AF_FILES; i++)
1249 if ((NULL == fl) || (NULL == fl->f))
1252 * Either there are no filter files
1253 * left, or this filter file just
1254 * contains no valid filters.
1256 * Continue to be sure we don't miss
1257 * valid filter files that are chained
1258 * after empty or invalid ones.
1263 /* For all filters, */
1264 for (b = fl->f; b; b = b->next)
1266 if (b->type != wanted_filter_type)
1268 /* skip the ones we don't care about, */
1271 /* leaving only taggers that could apply, of which we use the ones, */
1272 for (tag_name = csp->action->multi[multi_action_index]->first;
1273 NULL != tag_name; tag_name = tag_name->next)
1275 /* that do apply, and */
1276 if (strcmp(b->name, tag_name->str) == 0)
1278 char *modified_tag = NULL;
1280 size_t size = header_length;
1281 pcrs_job *joblist = b->joblist;
1283 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1285 if (NULL == joblist)
1287 log_error(LOG_LEVEL_RE_FILTER,
1288 "Tagger %s has empty joblist. Nothing to do.", b->name);
1292 /* execute their pcrs_joblist on the header. */
1293 for (job = joblist; NULL != job; job = job->next)
1295 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1299 /* Success, continue with the modified version. */
1308 /* Tagger doesn't match */
1311 /* Regex failure, log it but continue anyway. */
1312 assert(NULL != header);
1313 log_error(LOG_LEVEL_ERROR,
1314 "Problems with tagger \'%s\' and header \'%s\': %s",
1315 b->name, *header, pcrs_strerror(hits));
1317 freez(modified_tag);
1321 if (b->dynamic) pcrs_free_joblist(joblist);
1323 /* If this tagger matched */
1329 * There is to technical limitation which makes
1330 * it impossible to use empty tags, but I assume
1331 * no one would do it intentionally.
1334 log_error(LOG_LEVEL_INFO,
1335 "Tagger \'%s\' created an empty tag. Ignored.",
1340 if (!list_contains_item(csp->tags, tag))
1342 if (JB_ERR_OK != enlist(csp->tags, tag))
1344 log_error(LOG_LEVEL_ERROR,
1345 "Insufficient memory to add tag \'%s\', "
1346 "based on tagger \'%s\' and header \'%s\'",
1347 tag, b->name, *header);
1351 char *action_message;
1353 * update the action bits right away, to make
1354 * tagging based on tags set by earlier taggers
1355 * of the same kind possible.
1357 if (update_action_bits_for_tag(csp, tag))
1359 action_message = "Action bits updated accordingly.";
1363 action_message = "No action bits update necessary.";
1366 log_error(LOG_LEVEL_HEADER,
1367 "Tagger \'%s\' added tag \'%s\'. %s",
1368 b->name, tag, action_message);
1373 /* XXX: Is this log-worthy? */
1374 log_error(LOG_LEVEL_HEADER,
1375 "Tagger \'%s\' didn't add tag \'%s\'. "
1376 "Tag already present", b->name, tag);
1379 } /* if the tagger matched */
1380 } /* if the tagger applies */
1381 } /* for every tagger that could apply */
1382 } /* for all filters */
1383 } /* for all filter files */
1388 /* here begins the family of parser functions that reformat header lines */
1390 /*********************************************************************
1392 * Function : filter_header
1394 * Description : Executes all text substitutions from all applying
1395 * +(server|client)-header-filter actions on the header.
1396 * Most of the code was copied from pcrs_filter_response,
1397 * including the rather short variable names
1400 * 1 : csp = Current client state (buffers, headers, etc...)
1401 * 2 : header = On input, pointer to header to modify.
1402 * On output, pointer to the modified header, or NULL
1403 * to remove the header. This function frees the
1404 * original string if necessary.
1406 * Returns : JB_ERR_OK on success and always succeeds
1408 *********************************************************************/
1409 static jb_err filter_header(struct client_state *csp, char **header)
1413 size_t size = strlen(*header);
1415 char *newheader = NULL;
1418 struct file_list *fl;
1419 struct re_filterfile_spec *b;
1420 struct list_entry *filtername;
1422 int i, found_filters = 0;
1423 int wanted_filter_type;
1424 int multi_action_index;
1426 if (csp->flags & CSP_FLAG_NO_FILTERING)
1431 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1433 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1434 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1438 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1439 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1443 * Need to check the set of re_filterfiles...
1445 for (i = 0; i < MAX_AF_FILES; i++)
1458 if (0 == found_filters)
1460 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1461 "header filtering enabled, but no matching filters available.");
1465 for (i = 0; i < MAX_AF_FILES; i++)
1468 if ((NULL == fl) || (NULL == fl->f))
1471 * Either there are no filter files
1472 * left, or this filter file just
1473 * contains no valid filters.
1475 * Continue to be sure we don't miss
1476 * valid filter files that are chained
1477 * after empty or invalid ones.
1482 * For all applying +filter actions, look if a filter by that
1483 * name exists and if yes, execute its pcrs_joblist on the
1486 for (b = fl->f; b; b = b->next)
1488 if (b->type != wanted_filter_type)
1490 /* Skip other filter types */
1494 for (filtername = csp->action->multi[multi_action_index]->first;
1495 filtername ; filtername = filtername->next)
1497 if (strcmp(b->name, filtername->str) == 0)
1499 int current_hits = 0;
1500 pcrs_job *joblist = b->joblist;
1502 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1504 if (NULL == joblist)
1506 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1510 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1511 *header, size, b->name);
1513 /* Apply all jobs from the joblist */
1514 for (job = joblist; NULL != job; job = job->next)
1516 matches = pcrs_execute(job, *header, size, &newheader, &size);
1519 current_hits += matches;
1520 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1522 *header = newheader;
1524 else if ( 0 == matches )
1526 /* Filter doesn't change header */
1532 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1533 *header, b->name, pcrs_strerror(matches));
1534 if (newheader != NULL)
1536 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1542 if (b->dynamic) pcrs_free_joblist(joblist);
1544 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1545 hits += current_hits;
1552 * Additionally checking for hits is important because if
1553 * the continue hack is triggered, server headers can
1554 * arrive empty to separate multiple heads from each other.
1556 if ((0 == size) && hits)
1558 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1566 /*********************************************************************
1568 * Function : server_connection
1570 * Description : Makes sure a proper "Connection:" header is
1571 * set and signals connection_header_adder to
1575 * 1 : csp = Current client state (buffers, headers, etc...)
1576 * 2 : header = On input, pointer to header to modify.
1577 * On output, pointer to the modified header, or NULL
1578 * to remove the header. This function frees the
1579 * original string if necessary.
1581 * Returns : JB_ERR_OK on success, or
1582 * JB_ERR_MEMORY on out-of-memory error.
1584 *********************************************************************/
1585 static jb_err server_connection(struct client_state *csp, char **header)
1587 if (!strcmpic(*header, "Connection: keep-alive")
1588 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1589 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1593 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1594 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1596 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1599 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1601 log_error(LOG_LEVEL_HEADER,
1602 "Keeping the server header '%s' around.", *header);
1605 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1607 char *old_header = *header;
1609 *header = strdup("Connection: close");
1612 return JB_ERR_MEMORY;
1614 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1619 /* Signal server_connection_adder() to return early. */
1620 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1626 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1627 /*********************************************************************
1629 * Function : server_keep_alive
1631 * Description : Stores the server's keep alive timeout.
1634 * 1 : csp = Current client state (buffers, headers, etc...)
1635 * 2 : header = On input, pointer to header to modify.
1636 * On output, pointer to the modified header, or NULL
1637 * to remove the header. This function frees the
1638 * original string if necessary.
1640 * Returns : JB_ERR_OK.
1642 *********************************************************************/
1643 static jb_err server_keep_alive(struct client_state *csp, char **header)
1645 unsigned int keep_alive_timeout;
1646 const char *timeout_position = strstr(*header, "timeout=");
1648 if ((NULL == timeout_position)
1649 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1651 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1655 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1657 log_error(LOG_LEVEL_HEADER,
1658 "Reducing keep-alive timeout from %u to %u.",
1659 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1660 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1664 /* XXX: Is this log worthy? */
1665 log_error(LOG_LEVEL_HEADER,
1666 "Server keep-alive timeout is %u. Sticking with %u.",
1667 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1669 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1676 /*********************************************************************
1678 * Function : server_proxy_connection
1680 * Description : Figures out whether or not we should add a
1681 * Proxy-Connection header.
1684 * 1 : csp = Current client state (buffers, headers, etc...)
1685 * 2 : header = On input, pointer to header to modify.
1686 * On output, pointer to the modified header, or NULL
1687 * to remove the header. This function frees the
1688 * original string if necessary.
1690 * Returns : JB_ERR_OK.
1692 *********************************************************************/
1693 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1695 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1700 /*********************************************************************
1702 * Function : client_keep_alive
1704 * Description : Stores the client's keep alive timeout.
1707 * 1 : csp = Current client state (buffers, headers, etc...)
1708 * 2 : header = On input, pointer to header to modify.
1709 * On output, pointer to the modified header, or NULL
1710 * to remove the header. This function frees the
1711 * original string if necessary.
1713 * Returns : JB_ERR_OK.
1715 *********************************************************************/
1716 static jb_err client_keep_alive(struct client_state *csp, char **header)
1718 unsigned int keep_alive_timeout;
1719 const char *timeout_position = strstr(*header, ": ");
1721 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1723 log_error(LOG_LEVEL_HEADER,
1724 "keep-alive support is disabled. Crunching: %s.", *header);
1729 if ((NULL == timeout_position)
1730 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1732 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1736 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1738 log_error(LOG_LEVEL_HEADER,
1739 "Reducing keep-alive timeout from %u to %u.",
1740 csp->config->keep_alive_timeout, keep_alive_timeout);
1741 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1745 /* XXX: Is this log worthy? */
1746 log_error(LOG_LEVEL_HEADER,
1747 "Client keep-alive timeout is %u. Sticking with %u.",
1748 keep_alive_timeout, csp->config->keep_alive_timeout);
1754 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1758 /*********************************************************************
1760 * Function : client_connection
1762 * Description : Makes sure a proper "Connection:" header is
1763 * set and signals connection_header_adder
1767 * 1 : csp = Current client state (buffers, headers, etc...)
1768 * 2 : header = On input, pointer to header to modify.
1769 * On output, pointer to the modified header, or NULL
1770 * to remove the header. This function frees the
1771 * original string if necessary.
1773 * Returns : JB_ERR_OK on success, or
1774 * JB_ERR_MEMORY on out-of-memory error.
1776 *********************************************************************/
1777 static jb_err client_connection(struct client_state *csp, char **header)
1779 static const char connection_close[] = "Connection: close";
1781 if (!strcmpic(*header, connection_close))
1783 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1784 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1786 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1788 log_error(LOG_LEVEL_HEADER,
1789 "Removing \'%s\' to imply keep-alive.", *header);
1794 char *old_header = *header;
1796 *header = strdup("Connection: keep-alive");
1799 return JB_ERR_MEMORY;
1801 log_error(LOG_LEVEL_HEADER,
1802 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1805 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1809 log_error(LOG_LEVEL_HEADER,
1810 "Keeping the client header '%s' around. "
1811 "The connection will not be kept alive.",
1813 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1816 char *old_header = *header;
1818 *header = strdup(connection_close);
1821 return JB_ERR_MEMORY;
1823 log_error(LOG_LEVEL_HEADER,
1824 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1826 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1828 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1831 log_error(LOG_LEVEL_HEADER,
1832 "Keeping the client header '%s' around. "
1833 "The server connection will be kept alive if possible.",
1835 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1837 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1839 /* Signal client_connection_adder() to return early. */
1840 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1846 /*********************************************************************
1848 * Function : crumble
1850 * Description : This is called if a header matches a pattern to "crunch"
1853 * 1 : csp = Current client state (buffers, headers, etc...)
1854 * 2 : header = On input, pointer to header to modify.
1855 * On output, pointer to the modified header, or NULL
1856 * to remove the header. This function frees the
1857 * original string if necessary.
1859 * Returns : JB_ERR_OK on success, or
1860 * JB_ERR_MEMORY on out-of-memory error.
1862 *********************************************************************/
1863 static jb_err crumble(struct client_state *csp, char **header)
1866 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1872 /*********************************************************************
1874 * Function : crunch_server_header
1876 * Description : Crunch server header if it matches a string supplied by the
1877 * user. Called from `sed'.
1880 * 1 : csp = Current client state (buffers, headers, etc...)
1881 * 2 : header = On input, pointer to header to modify.
1882 * On output, pointer to the modified header, or NULL
1883 * to remove the header. This function frees the
1884 * original string if necessary.
1886 * Returns : JB_ERR_OK on success and always succeeds
1888 *********************************************************************/
1889 static jb_err crunch_server_header(struct client_state *csp, char **header)
1891 const char *crunch_pattern;
1893 /* Do we feel like crunching? */
1894 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1896 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1898 /* Is the current header the lucky one? */
1899 if (strstr(*header, crunch_pattern))
1901 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1910 /*********************************************************************
1912 * Function : server_content_type
1914 * Description : Set the content-type for filterable types (text/.*,
1915 * .*xml.*, javascript and image/gif) unless filtering has been
1916 * forbidden (CT_TABOO) while parsing earlier headers.
1917 * NOTE: Since text/plain is commonly used by web servers
1918 * for files whose correct type is unknown, we don't
1919 * set CT_TEXT for it.
1922 * 1 : csp = Current client state (buffers, headers, etc...)
1923 * 2 : header = On input, pointer to header to modify.
1924 * On output, pointer to the modified header, or NULL
1925 * to remove the header. This function frees the
1926 * original string if necessary.
1928 * Returns : JB_ERR_OK on success, or
1929 * JB_ERR_MEMORY on out-of-memory error.
1931 *********************************************************************/
1932 static jb_err server_content_type(struct client_state *csp, char **header)
1934 /* Remove header if it isn't the first Content-Type header */
1935 if ((csp->content_type & CT_DECLARED))
1938 * Another, slightly slower, way to see if
1939 * we already parsed another Content-Type header.
1941 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1943 log_error(LOG_LEVEL_ERROR,
1944 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1952 * Signal that the Content-Type has been set.
1954 csp->content_type |= CT_DECLARED;
1956 if (!(csp->content_type & CT_TABOO))
1959 * XXX: The assumption that text/plain is a sign of
1960 * binary data seems to be somewhat unreasonable nowadays
1961 * and should be dropped after 3.0.8 is out.
1963 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
1964 || strstr(*header, "xml")
1965 || strstr(*header, "application/x-javascript"))
1967 csp->content_type |= CT_TEXT;
1969 else if (strstr(*header, "image/gif"))
1971 csp->content_type |= CT_GIF;
1976 * Are we messing with the content type?
1978 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1981 * Make sure the user doesn't accidently
1982 * change the content type of binary documents.
1984 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
1987 *header = strdup("Content-Type: ");
1988 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1992 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1993 return JB_ERR_MEMORY;
1995 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1999 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2000 "It doesn't look like a content type that should be filtered. "
2001 "Enable force-text-mode if you know what you're doing.", *header);
2009 /*********************************************************************
2011 * Function : server_transfer_coding
2013 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2014 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2015 * - Remove header if body was chunked but has been
2016 * de-chunked for filtering.
2019 * 1 : csp = Current client state (buffers, headers, etc...)
2020 * 2 : header = On input, pointer to header to modify.
2021 * On output, pointer to the modified header, or NULL
2022 * to remove the header. This function frees the
2023 * original string if necessary.
2025 * Returns : JB_ERR_OK on success, or
2026 * JB_ERR_MEMORY on out-of-memory error.
2028 *********************************************************************/
2029 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2032 * Turn off pcrs and gif filtering if body compressed
2034 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2038 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2040 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2041 csp->http->cmd, *header);
2042 #endif /* def FEATURE_ZLIB */
2043 csp->content_type = CT_TABOO;
2047 * Raise flag if body chunked
2049 if (strstr(*header, "chunked"))
2051 csp->flags |= CSP_FLAG_CHUNKED;
2054 * If the body was modified, it has been de-chunked first
2055 * and the header must be removed.
2057 * FIXME: If there is more than one transfer encoding,
2058 * only the "chunked" part should be removed here.
2060 if (csp->flags & CSP_FLAG_MODIFIED)
2062 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2071 /*********************************************************************
2073 * Function : server_content_encoding
2075 * Description : This function is run twice for each request,
2076 * unless FEATURE_ZLIB and filtering are disabled.
2078 * The first run is used to check if the content
2079 * is compressed, if FEATURE_ZLIB is disabled
2080 * filtering is then disabled as well, if FEATURE_ZLIB
2081 * is enabled the content is marked for decompression.
2083 * The second run is used to remove the Content-Encoding
2084 * header if the decompression was successful.
2087 * 1 : csp = Current client state (buffers, headers, etc...)
2088 * 2 : header = On input, pointer to header to modify.
2089 * On output, pointer to the modified header, or NULL
2090 * to remove the header. This function frees the
2091 * original string if necessary.
2093 * Returns : JB_ERR_OK on success, or
2094 * JB_ERR_MEMORY on out-of-memory error.
2096 *********************************************************************/
2097 static jb_err server_content_encoding(struct client_state *csp, char **header)
2100 if ((csp->flags & CSP_FLAG_MODIFIED)
2101 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2104 * We successfully decompressed the content,
2105 * and have to clean the header now, so the
2106 * client no longer expects compressed data..
2108 * XXX: There is a difference between cleaning
2109 * and removing it completely.
2111 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2114 else if (strstr(*header, "gzip"))
2116 /* Mark for gzip decompression */
2117 csp->content_type |= CT_GZIP;
2119 else if (strstr(*header, "deflate"))
2121 /* Mark for zlib decompression */
2122 csp->content_type |= CT_DEFLATE;
2124 else if (strstr(*header, "compress"))
2127 * We can't decompress this; therefore we can't filter
2130 csp->content_type |= CT_TABOO;
2132 #else /* !defined(FEATURE_ZLIB) */
2133 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2136 * Body is compressed, turn off pcrs and gif filtering.
2138 csp->content_type |= CT_TABOO;
2141 * Log a warning if the user expects the content to be filtered.
2143 if ((csp->rlist != NULL) &&
2144 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2146 log_error(LOG_LEVEL_INFO,
2147 "Compressed content detected, content filtering disabled. "
2148 "Consider recompiling Privoxy with zlib support or "
2149 "enable the prevent-compression action.");
2152 #endif /* defined(FEATURE_ZLIB) */
2159 /*********************************************************************
2161 * Function : server_adjust_content_length
2163 * Description : Adjust Content-Length header if we modified
2167 * 1 : csp = Current client state (buffers, headers, etc...)
2168 * 2 : header = On input, pointer to header to modify.
2169 * On output, pointer to the modified header, or NULL
2170 * to remove the header. This function frees the
2171 * original string if necessary.
2173 * Returns : JB_ERR_OK on success, or
2174 * JB_ERR_MEMORY on out-of-memory error.
2176 *********************************************************************/
2177 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2179 /* Regenerate header if the content was modified. */
2180 if (csp->flags & CSP_FLAG_MODIFIED)
2182 const size_t header_length = 50;
2184 *header = malloc(header_length);
2185 if (*header == NULL)
2187 return JB_ERR_MEMORY;
2189 create_content_length_header(csp->content_length, *header, header_length);
2190 log_error(LOG_LEVEL_HEADER,
2191 "Adjusted Content-Length to %llu", csp->content_length);
2198 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2199 /*********************************************************************
2201 * Function : server_save_content_length
2203 * Description : Save the Content-Length sent by the server.
2206 * 1 : csp = Current client state (buffers, headers, etc...)
2207 * 2 : header = On input, pointer to header to modify.
2208 * On output, pointer to the modified header, or NULL
2209 * to remove the header. This function frees the
2210 * original string if necessary.
2212 * Returns : JB_ERR_OK on success, or
2213 * JB_ERR_MEMORY on out-of-memory error.
2215 *********************************************************************/
2216 static jb_err server_save_content_length(struct client_state *csp, char **header)
2218 unsigned long long content_length = 0;
2220 assert(*(*header+14) == ':');
2223 if (1 != sscanf(*header+14, ": %I64u", &content_length))
2225 if (1 != sscanf(*header+14, ": %llu", &content_length))
2228 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2233 csp->expected_content_length = content_length;
2234 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2235 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2240 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2243 /*********************************************************************
2245 * Function : server_content_md5
2247 * Description : Crumble any Content-MD5 headers if the document was
2248 * modified. FIXME: Should we re-compute instead?
2251 * 1 : csp = Current client state (buffers, headers, etc...)
2252 * 2 : header = On input, pointer to header to modify.
2253 * On output, pointer to the modified header, or NULL
2254 * to remove the header. This function frees the
2255 * original string if necessary.
2257 * Returns : JB_ERR_OK on success, or
2258 * JB_ERR_MEMORY on out-of-memory error.
2260 *********************************************************************/
2261 static jb_err server_content_md5(struct client_state *csp, char **header)
2263 if (csp->flags & CSP_FLAG_MODIFIED)
2265 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2273 /*********************************************************************
2275 * Function : server_content_disposition
2277 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2278 * Called from `sed'.
2281 * 1 : csp = Current client state (buffers, headers, etc...)
2282 * 2 : header = On input, pointer to header to modify.
2283 * On output, pointer to the modified header, or NULL
2284 * to remove the header. This function frees the
2285 * original string if necessary.
2287 * Returns : JB_ERR_OK on success, or
2288 * JB_ERR_MEMORY on out-of-memory error.
2290 *********************************************************************/
2291 static jb_err server_content_disposition(struct client_state *csp, char **header)
2296 * Are we messing with the Content-Disposition header?
2298 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2304 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2306 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2309 * Blocking content-disposition header
2311 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2318 * Replacing Content-Disposition header
2321 *header = strdup("Content-Disposition: ");
2322 string_append(header, newval);
2324 if (*header != NULL)
2326 log_error(LOG_LEVEL_HEADER,
2327 "Content-Disposition header crunched and replaced with: %s", *header);
2330 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2334 /*********************************************************************
2336 * Function : server_last_modified
2338 * Description : Changes Last-Modified header to the actual date
2339 * to help hide-if-modified-since.
2340 * Called from `sed'.
2343 * 1 : csp = Current client state (buffers, headers, etc...)
2344 * 2 : header = On input, pointer to header to modify.
2345 * On output, pointer to the modified header, or NULL
2346 * to remove the header. This function frees the
2347 * original string if necessary.
2349 * Returns : JB_ERR_OK on success, or
2350 * JB_ERR_MEMORY on out-of-memory error.
2352 *********************************************************************/
2353 static jb_err server_last_modified(struct client_state *csp, char **header)
2356 char buf[BUFFER_SIZE];
2359 #ifdef HAVE_GMTIME_R
2362 struct tm *timeptr = NULL;
2363 time_t now, last_modified;
2364 long int days, hours, minutes, seconds;
2367 * Are we messing with the Last-Modified header?
2369 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2375 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2377 if (0 == strcmpic(newval, "block") )
2380 * Blocking Last-Modified header. Useless but why not.
2382 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2386 else if (0 == strcmpic(newval, "reset-to-request-time"))
2389 * Setting Last-Modified Header to now.
2391 get_http_time(0, buf, sizeof(buf));
2393 *header = strdup("Last-Modified: ");
2394 string_append(header, buf);
2396 if (*header == NULL)
2398 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2402 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2405 else if (0 == strcmpic(newval, "randomize"))
2407 const char *header_time = *header + sizeof("Last-Modified:");
2409 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2411 #ifdef HAVE_GMTIME_R
2412 gmtime_r(&now, &gmt);
2413 #elif defined(MUTEX_LOCKS_AVAILABLE)
2414 privoxy_mutex_lock(&gmtime_mutex);
2416 privoxy_mutex_unlock(&gmtime_mutex);
2420 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2422 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2427 long int rtime = (long int)difftime(now, last_modified);
2430 const int negative_delta = (rtime < 0);
2435 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2437 rtime = pick_from_range(rtime);
2442 last_modified += rtime;
2443 #ifdef HAVE_GMTIME_R
2444 timeptr = gmtime_r(&last_modified, &gmt);
2445 #elif defined(MUTEX_LOCKS_AVAILABLE)
2446 privoxy_mutex_lock(&gmtime_mutex);
2447 timeptr = gmtime(&last_modified);
2448 privoxy_mutex_unlock(&gmtime_mutex);
2450 timeptr = gmtime(&last_modified);
2452 if ((NULL == timeptr) || !strftime(newheader,
2453 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2455 log_error(LOG_LEVEL_ERROR,
2456 "Randomizing '%s' failed. Crunching the header without replacement.",
2463 *header = strdup("Last-Modified: ");
2464 string_append(header, newheader);
2466 if (*header == NULL)
2468 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2469 return JB_ERR_MEMORY;
2472 days = rtime / (3600 * 24);
2473 hours = rtime / 3600 % 24;
2474 minutes = rtime / 60 % 60;
2475 seconds = rtime % 60;
2477 log_error(LOG_LEVEL_HEADER,
2478 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2479 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2480 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2484 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2493 /*********************************************************************
2495 * Function : client_accept_encoding
2497 * Description : Rewrite the client's Accept-Encoding header so that
2498 * if doesn't allow compression, if the action applies.
2499 * Note: For HTTP/1.0 the absence of the header is enough.
2502 * 1 : csp = Current client state (buffers, headers, etc...)
2503 * 2 : header = On input, pointer to header to modify.
2504 * On output, pointer to the modified header, or NULL
2505 * to remove the header. This function frees the
2506 * original string if necessary.
2508 * Returns : JB_ERR_OK on success, or
2509 * JB_ERR_MEMORY on out-of-memory error.
2511 *********************************************************************/
2512 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2514 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2516 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2520 /* Temporarily disable the correct behaviour to
2521 * work around a PHP bug.
2523 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2525 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2526 * if (*header == NULL)
2528 * return JB_ERR_MEMORY;
2539 /*********************************************************************
2541 * Function : client_te
2543 * Description : Rewrite the client's TE header so that
2544 * if doesn't allow compression, if the action applies.
2547 * 1 : csp = Current client state (buffers, headers, etc...)
2548 * 2 : header = On input, pointer to header to modify.
2549 * On output, pointer to the modified header, or NULL
2550 * to remove the header. This function frees the
2551 * original string if necessary.
2553 * Returns : JB_ERR_OK on success, or
2554 * JB_ERR_MEMORY on out-of-memory error.
2556 *********************************************************************/
2557 static jb_err client_te(struct client_state *csp, char **header)
2559 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2562 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2569 /*********************************************************************
2571 * Function : client_referrer
2573 * Description : Handle the "referer" config setting properly.
2574 * Called from `sed'.
2577 * 1 : csp = Current client state (buffers, headers, etc...)
2578 * 2 : header = On input, pointer to header to modify.
2579 * On output, pointer to the modified header, or NULL
2580 * to remove the header. This function frees the
2581 * original string if necessary.
2583 * Returns : JB_ERR_OK on success, or
2584 * JB_ERR_MEMORY on out-of-memory error.
2586 *********************************************************************/
2587 static jb_err client_referrer(struct client_state *csp, char **header)
2589 const char *parameter;
2590 /* booleans for parameters we have to check multiple times */
2591 int parameter_conditional_block;
2592 int parameter_conditional_forge;
2594 #ifdef FEATURE_FORCE_LOAD
2596 * Since the referrer can include the prefix even
2597 * if the request itself is non-forced, we must
2598 * clean it unconditionally.
2600 * XXX: strclean is too broad
2602 strclean(*header, FORCE_PREFIX);
2603 #endif /* def FEATURE_FORCE_LOAD */
2605 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2607 /* Nothing left to do */
2611 parameter = csp->action->string[ACTION_STRING_REFERER];
2612 assert(parameter != NULL);
2613 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2614 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2616 if (!parameter_conditional_block && !parameter_conditional_forge)
2619 * As conditional-block and conditional-forge are the only
2620 * parameters that rely on the original referrer, we can
2621 * remove it now for all the others.
2626 if (0 == strcmpic(parameter, "block"))
2628 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2631 else if (parameter_conditional_block || parameter_conditional_forge)
2633 return handle_conditional_hide_referrer_parameter(header,
2634 csp->http->hostport, parameter_conditional_block);
2636 else if (0 == strcmpic(parameter, "forge"))
2638 return create_forged_referrer(header, csp->http->hostport);
2642 /* interpret parameter as user-supplied referer to fake */
2643 return create_fake_referrer(header, parameter);
2648 /*********************************************************************
2650 * Function : client_accept_language
2652 * Description : Handle the "Accept-Language" config setting properly.
2653 * Called from `sed'.
2656 * 1 : csp = Current client state (buffers, headers, etc...)
2657 * 2 : header = On input, pointer to header to modify.
2658 * On output, pointer to the modified header, or NULL
2659 * to remove the header. This function frees the
2660 * original string if necessary.
2662 * Returns : JB_ERR_OK on success, or
2663 * JB_ERR_MEMORY on out-of-memory error.
2665 *********************************************************************/
2666 static jb_err client_accept_language(struct client_state *csp, char **header)
2671 * Are we messing with the Accept-Language?
2673 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2675 /*I don't think so*/
2679 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2681 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2684 * Blocking Accept-Language header
2686 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2693 * Replacing Accept-Language header
2696 *header = strdup("Accept-Language: ");
2697 string_append(header, newval);
2699 if (*header == NULL)
2701 log_error(LOG_LEVEL_ERROR,
2702 "Insufficient memory. Accept-Language header crunched without replacement.");
2706 log_error(LOG_LEVEL_HEADER,
2707 "Accept-Language header crunched and replaced with: %s", *header);
2710 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2714 /*********************************************************************
2716 * Function : crunch_client_header
2718 * Description : Crunch client header if it matches a string supplied by the
2719 * user. Called from `sed'.
2722 * 1 : csp = Current client state (buffers, headers, etc...)
2723 * 2 : header = On input, pointer to header to modify.
2724 * On output, pointer to the modified header, or NULL
2725 * to remove the header. This function frees the
2726 * original string if necessary.
2728 * Returns : JB_ERR_OK on success and always succeeds
2730 *********************************************************************/
2731 static jb_err crunch_client_header(struct client_state *csp, char **header)
2733 const char *crunch_pattern;
2735 /* Do we feel like crunching? */
2736 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2738 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2740 /* Is the current header the lucky one? */
2741 if (strstr(*header, crunch_pattern))
2743 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2751 /*********************************************************************
2753 * Function : client_uagent
2755 * Description : Handle the "user-agent" config setting properly
2756 * and remember its original value to enable browser
2757 * bug workarounds. Called from `sed'.
2760 * 1 : csp = Current client state (buffers, headers, etc...)
2761 * 2 : header = On input, pointer to header to modify.
2762 * On output, pointer to the modified header, or NULL
2763 * to remove the header. This function frees the
2764 * original string if necessary.
2766 * Returns : JB_ERR_OK on success, or
2767 * JB_ERR_MEMORY on out-of-memory error.
2769 *********************************************************************/
2770 static jb_err client_uagent(struct client_state *csp, char **header)
2774 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2779 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2786 *header = strdup("User-Agent: ");
2787 string_append(header, newval);
2789 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2791 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2795 /*********************************************************************
2797 * Function : client_ua
2799 * Description : Handle "ua-" headers properly. Called from `sed'.
2802 * 1 : csp = Current client state (buffers, headers, etc...)
2803 * 2 : header = On input, pointer to header to modify.
2804 * On output, pointer to the modified header, or NULL
2805 * to remove the header. This function frees the
2806 * original string if necessary.
2808 * Returns : JB_ERR_OK on success, or
2809 * JB_ERR_MEMORY on out-of-memory error.
2811 *********************************************************************/
2812 static jb_err client_ua(struct client_state *csp, char **header)
2814 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2816 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2824 /*********************************************************************
2826 * Function : client_from
2828 * Description : Handle the "from" config setting properly.
2829 * Called from `sed'.
2832 * 1 : csp = Current client state (buffers, headers, etc...)
2833 * 2 : header = On input, pointer to header to modify.
2834 * On output, pointer to the modified header, or NULL
2835 * to remove the header. This function frees the
2836 * original string if necessary.
2838 * Returns : JB_ERR_OK on success, or
2839 * JB_ERR_MEMORY on out-of-memory error.
2841 *********************************************************************/
2842 static jb_err client_from(struct client_state *csp, char **header)
2846 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2853 newval = csp->action->string[ACTION_STRING_FROM];
2856 * Are we blocking the e-mail address?
2858 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2860 log_error(LOG_LEVEL_HEADER, "crunched From!");
2864 log_error(LOG_LEVEL_HEADER, " modified");
2866 *header = strdup("From: ");
2867 string_append(header, newval);
2869 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2873 /*********************************************************************
2875 * Function : client_send_cookie
2877 * Description : Crunches the "cookie" header if necessary.
2878 * Called from `sed'.
2880 * XXX: Stupid name, doesn't send squat.
2883 * 1 : csp = Current client state (buffers, headers, etc...)
2884 * 2 : header = On input, pointer to header to modify.
2885 * On output, pointer to the modified header, or NULL
2886 * to remove the header. This function frees the
2887 * original string if necessary.
2889 * Returns : JB_ERR_OK on success, or
2890 * JB_ERR_MEMORY on out-of-memory error.
2892 *********************************************************************/
2893 static jb_err client_send_cookie(struct client_state *csp, char **header)
2895 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2897 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2905 /*********************************************************************
2907 * Function : client_x_forwarded
2909 * Description : Handle the "x-forwarded-for" config setting properly,
2910 * also used in the add_client_headers list. Called from `sed'.
2913 * 1 : csp = Current client state (buffers, headers, etc...)
2914 * 2 : header = On input, pointer to header to modify.
2915 * On output, pointer to the modified header, or NULL
2916 * to remove the header. This function frees the
2917 * original string if necessary.
2919 * Returns : JB_ERR_OK on success, or
2920 * JB_ERR_MEMORY on out-of-memory error.
2922 *********************************************************************/
2923 jb_err client_x_forwarded(struct client_state *csp, char **header)
2925 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2927 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2929 if (0 == strcmpic(parameter, "block"))
2932 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2934 else if (0 == strcmpic(parameter, "add"))
2936 string_append(header, ", ");
2937 string_append(header, csp->ip_addr_str);
2939 if (*header == NULL)
2941 return JB_ERR_MEMORY;
2943 log_error(LOG_LEVEL_HEADER,
2944 "Appended client IP address to %s", *header);
2945 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
2949 log_error(LOG_LEVEL_FATAL,
2950 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
2958 /*********************************************************************
2960 * Function : client_max_forwards
2962 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2963 * from the value of the Max-Forwards header field.
2966 * 1 : csp = Current client state (buffers, headers, etc...)
2967 * 2 : header = On input, pointer to header to modify.
2968 * On output, pointer to the modified header, or NULL
2969 * to remove the header. This function frees the
2970 * original string if necessary.
2972 * Returns : JB_ERR_OK on success, or
2973 * JB_ERR_MEMORY on out-of-memory error.
2975 *********************************************************************/
2976 static jb_err client_max_forwards(struct client_state *csp, char **header)
2980 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2981 (0 == strcmpic(csp->http->gpc, "options")))
2983 assert(*(*header+12) == ':');
2984 if (1 == sscanf(*header+12, ": %d", &max_forwards))
2986 if (max_forwards > 0)
2988 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
2989 log_error(LOG_LEVEL_HEADER,
2990 "Max-Forwards value for %s request reduced to %d.",
2991 csp->http->gpc, max_forwards);
2993 else if (max_forwards < 0)
2995 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3001 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3010 /*********************************************************************
3012 * Function : client_host
3014 * Description : If the request URI did not contain host and
3015 * port information, parse and evaluate the Host
3018 * Also, kill ill-formed HOST: headers as sent by
3019 * Apple's iTunes software when used with a proxy.
3022 * 1 : csp = Current client state (buffers, headers, etc...)
3023 * 2 : header = On input, pointer to header to modify.
3024 * On output, pointer to the modified header, or NULL
3025 * to remove the header. This function frees the
3026 * original string if necessary.
3028 * Returns : JB_ERR_OK on success, or
3029 * JB_ERR_MEMORY on out-of-memory error.
3031 *********************************************************************/
3032 static jb_err client_host(struct client_state *csp, char **header)
3037 * If the header field name is all upper-case, chances are that it's
3038 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3039 * not a problem -- they are regenerated later.
3041 if ((*header)[1] == 'O')
3043 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3048 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3049 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3052 if (NULL == (p = strdup((*header)+6)))
3054 return JB_ERR_MEMORY;
3057 if (NULL == (q = strdup(p)))
3060 return JB_ERR_MEMORY;
3063 freez(csp->http->hostport);
3064 csp->http->hostport = p;
3065 freez(csp->http->host);
3066 csp->http->host = q;
3067 q = strchr(csp->http->host, ':');
3070 /* Terminate hostname and evaluate port string */
3072 csp->http->port = atoi(q);
3076 csp->http->port = csp->http->ssl ? 443 : 80;
3079 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3080 csp->http->hostport, csp->http->host, csp->http->port);
3083 /* Signal client_host_adder() to return right away */
3084 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3090 /*********************************************************************
3092 * Function : client_if_modified_since
3094 * Description : Remove or modify the If-Modified-Since header.
3097 * 1 : csp = Current client state (buffers, headers, etc...)
3098 * 2 : header = On input, pointer to header to modify.
3099 * On output, pointer to the modified header, or NULL
3100 * to remove the header. This function frees the
3101 * original string if necessary.
3103 * Returns : JB_ERR_OK on success, or
3104 * JB_ERR_MEMORY on out-of-memory error.
3106 *********************************************************************/
3107 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3110 #ifdef HAVE_GMTIME_R
3113 struct tm *timeptr = NULL;
3116 long int hours, minutes, seconds;
3119 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3122 * The client got an error message because of a temporary problem,
3123 * the problem is gone and the client now tries to revalidate our
3124 * error message on the real server. The revalidation would always
3125 * end with the transmission of the whole document and there is
3126 * no need to expose the bogus If-Modified-Since header.
3128 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3131 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3133 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3135 if ((0 == strcmpic(newval, "block")))
3137 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3140 else /* add random value */
3142 const char *header_time = *header + sizeof("If-Modified-Since:");
3144 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3146 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3151 long int rtime = strtol(newval, &endptr, 0);
3152 const int negative_range = (rtime < 0);
3156 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3157 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3163 rtime = pick_from_range(rtime);
3167 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3170 tm += rtime * (negative_range ? -1 : 1);
3171 #ifdef HAVE_GMTIME_R
3172 timeptr = gmtime_r(&tm, &gmt);
3173 #elif defined(MUTEX_LOCKS_AVAILABLE)
3174 privoxy_mutex_lock(&gmtime_mutex);
3175 timeptr = gmtime(&tm);
3176 privoxy_mutex_unlock(&gmtime_mutex);
3178 timeptr = gmtime(&tm);
3180 if ((NULL == timeptr) || !strftime(newheader,
3181 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3183 log_error(LOG_LEVEL_ERROR,
3184 "Randomizing '%s' failed. Crunching the header without replacement.",
3191 *header = strdup("If-Modified-Since: ");
3192 string_append(header, newheader);
3194 if (*header == NULL)
3196 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3197 return JB_ERR_MEMORY;
3200 hours = rtime / 3600;
3201 minutes = rtime / 60 % 60;
3202 seconds = rtime % 60;
3204 log_error(LOG_LEVEL_HEADER,
3205 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3206 *header, (negative_range) ? "subtracted" : "added", hours,
3207 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3208 seconds, (seconds == 1) ? ")" : "s)");
3217 /*********************************************************************
3219 * Function : client_if_none_match
3221 * Description : Remove the If-None-Match header.
3224 * 1 : csp = Current client state (buffers, headers, etc...)
3225 * 2 : header = On input, pointer to header to modify.
3226 * On output, pointer to the modified header, or NULL
3227 * to remove the header. This function frees the
3228 * original string if necessary.
3230 * Returns : JB_ERR_OK on success, or
3231 * JB_ERR_MEMORY on out-of-memory error.
3233 *********************************************************************/
3234 static jb_err client_if_none_match(struct client_state *csp, char **header)
3236 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3238 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3246 /*********************************************************************
3248 * Function : client_x_filter
3250 * Description : Disables filtering if the client set "X-Filter: No".
3251 * Called from `sed'.
3254 * 1 : csp = Current client state (buffers, headers, etc...)
3255 * 2 : header = On input, pointer to header to modify.
3256 * On output, pointer to the modified header, or NULL
3257 * to remove the header. This function frees the
3258 * original string if necessary.
3260 * Returns : JB_ERR_OK on success
3262 *********************************************************************/
3263 jb_err client_x_filter(struct client_state *csp, char **header)
3265 if ( 0 == strcmpic(*header, "X-Filter: No"))
3267 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3269 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3273 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3275 log_error(LOG_LEVEL_HEADER,
3276 "force-text-mode overruled the client's request to fetch without filtering!");
3280 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3281 csp->flags |= CSP_FLAG_NO_FILTERING;
3282 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3284 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3292 /*********************************************************************
3294 * Function : client_range
3296 * Description : Removes Range, Request-Range and If-Range headers if
3297 * content filtering is enabled. If the client's version
3298 * of the document has been altered by Privoxy, the server
3299 * could interpret the range differently than the client
3300 * intended in which case the user could end up with
3301 * corrupted content.
3304 * 1 : csp = Current client state (buffers, headers, etc...)
3305 * 2 : header = On input, pointer to header to modify.
3306 * On output, pointer to the modified header, or NULL
3307 * to remove the header. This function frees the
3308 * original string if necessary.
3310 * Returns : JB_ERR_OK
3312 *********************************************************************/
3313 static jb_err client_range(struct client_state *csp, char **header)
3315 if (content_filters_enabled(csp->action))
3317 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3318 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3325 /* the following functions add headers directly to the header list */
3327 /*********************************************************************
3329 * Function : client_host_adder
3331 * Description : Adds the Host: header field if it is missing.
3332 * Called from `sed'.
3335 * 1 : csp = Current client state (buffers, headers, etc...)
3337 * Returns : JB_ERR_OK on success, or
3338 * JB_ERR_MEMORY on out-of-memory error.
3340 *********************************************************************/
3341 static jb_err client_host_adder(struct client_state *csp)
3346 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3348 /* Header already set by the client, nothing to do. */
3352 if ( !csp->http->hostport || !*(csp->http->hostport))
3354 /* XXX: When does this happen and why is it OK? */
3355 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3360 * remove 'user:pass@' from 'proto://user:pass@host'
3362 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3368 p = csp->http->hostport;
3371 /* XXX: Just add it, we already made sure that it will be unique */
3372 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3373 err = enlist_unique_header(csp->headers, "Host", p);
3380 /*********************************************************************
3382 * Function : client_accept_encoding_adder
3384 * Description : Add an Accept-Encoding header to the client's request
3385 * that disables compression if the action applies, and
3386 * the header is not already there. Called from `sed'.
3387 * Note: For HTTP/1.0, the absence of the header is enough.
3390 * 1 : csp = Current client state (buffers, headers, etc...)
3392 * Returns : JB_ERR_OK on success, or
3393 * JB_ERR_MEMORY on out-of-memory error.
3395 *********************************************************************/
3396 static jb_err client_accept_encoding_adder(struct client_state *csp)
3398 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3399 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3401 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3409 /*********************************************************************
3411 * Function : client_xtra_adder
3413 * Description : Used in the add_client_headers list. Called from `sed'.
3416 * 1 : csp = Current client state (buffers, headers, etc...)
3418 * Returns : JB_ERR_OK on success, or
3419 * JB_ERR_MEMORY on out-of-memory error.
3421 *********************************************************************/
3422 static jb_err client_xtra_adder(struct client_state *csp)
3424 struct list_entry *lst;
3427 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3428 lst ; lst = lst->next)
3430 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3431 err = enlist(csp->headers, lst->str);
3443 /*********************************************************************
3445 * Function : client_x_forwarded_for_adder
3447 * Description : Used in the add_client_headers list. Called from `sed'.
3450 * 1 : csp = Current client state (buffers, headers, etc...)
3452 * Returns : JB_ERR_OK on success, or
3453 * JB_ERR_MEMORY on out-of-memory error.
3455 *********************************************************************/
3456 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3458 char *header = NULL;
3461 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3462 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3463 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3466 * If we aren't adding X-Forwarded-For headers,
3467 * or we already appended an existing X-Forwarded-For
3468 * header, there's nothing left to do here.
3473 header = strdup("X-Forwarded-For: ");
3474 string_append(&header, csp->ip_addr_str);
3478 return JB_ERR_MEMORY;
3481 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3482 err = enlist(csp->headers, header);
3489 /*********************************************************************
3491 * Function : server_connection_adder
3493 * Description : Adds an appropiate "Connection:" header to csp->headers
3494 * unless the header was already present. Called from `sed'.
3497 * 1 : csp = Current client state (buffers, headers, etc...)
3499 * Returns : JB_ERR_OK on success, or
3500 * JB_ERR_MEMORY on out-of-memory error.
3502 *********************************************************************/
3503 static jb_err server_connection_adder(struct client_state *csp)
3505 const unsigned int flags = csp->flags;
3506 const char *response_status_line = csp->headers->first->str;
3507 static const char connection_close[] = "Connection: close";
3509 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3510 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3516 * XXX: if we downgraded the response, this check will fail.
3518 if ((csp->config->feature_flags &
3519 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3520 && (NULL != response_status_line)
3521 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3522 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3523 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3527 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3528 "without Connection header implies keep-alive.");
3529 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3533 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3535 return enlist(csp->headers, connection_close);
3539 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3540 /*********************************************************************
3542 * Function : server_proxy_connection_adder
3544 * Description : Adds a "Proxy-Connection: keep-alive" header to
3545 * csp->headers if the client asked for keep-alive.
3546 * XXX: We should reuse existant ones.
3549 * 1 : csp = Current client state (buffers, headers, etc...)
3551 * Returns : JB_ERR_OK on success, or
3552 * JB_ERR_MEMORY on out-of-memory error.
3554 *********************************************************************/
3555 static jb_err server_proxy_connection_adder(struct client_state *csp)
3557 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3558 jb_err err = JB_ERR_OK;
3560 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3561 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3562 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET))
3564 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3565 err = enlist(csp->headers, proxy_connection_header);
3570 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3573 /*********************************************************************
3575 * Function : client_connection_header_adder
3577 * Description : Adds a proper "Connection:" header to csp->headers
3578 * unless the header was already present. Called from `sed'.
3581 * 1 : csp = Current client state (buffers, headers, etc...)
3583 * Returns : JB_ERR_OK on success, or
3584 * JB_ERR_MEMORY on out-of-memory error.
3586 *********************************************************************/
3587 static jb_err client_connection_header_adder(struct client_state *csp)
3589 static const char connection_close[] = "Connection: close";
3591 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3592 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3597 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3598 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3599 && (csp->http->ssl == 0)
3600 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3602 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3605 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3607 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3609 return enlist(csp->headers, connection_close);
3613 /*********************************************************************
3615 * Function : server_http
3617 * Description : - Save the HTTP Status into csp->http->status
3618 * - Set CT_TABOO to prevent filtering if the answer
3619 * is a partial range (HTTP status 206)
3620 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3624 * 1 : csp = Current client state (buffers, headers, etc...)
3625 * 2 : header = On input, pointer to header to modify.
3626 * On output, pointer to the modified header, or NULL
3627 * to remove the header. This function frees the
3628 * original string if necessary.
3630 * Returns : JB_ERR_OK on success, or
3631 * JB_ERR_MEMORY on out-of-memory error.
3633 *********************************************************************/
3634 static jb_err server_http(struct client_state *csp, char **header)
3636 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3637 if (csp->http->status == 206)
3639 csp->content_type = CT_TABOO;
3642 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3644 /* XXX: Should we do a real validity check here? */
3645 if (strlen(*header) > 8)
3648 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3653 * XXX: Should we block the request or
3654 * enlist a valid status code line here?
3656 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3657 "Downgrading to HTTP/1.0 impossible.");
3665 /*********************************************************************
3667 * Function : server_set_cookie
3669 * Description : Handle the server "cookie" header properly.
3670 * Log cookie to the jar file. Then "crunch",
3671 * accept or rewrite it to a session cookie.
3672 * Called from `sed'.
3674 * TODO: Allow the user to specify a new expiration
3675 * time to cause the cookie to expire even before the
3676 * browser is closed.
3679 * 1 : csp = Current client state (buffers, headers, etc...)
3680 * 2 : header = On input, pointer to header to modify.
3681 * On output, pointer to the modified header, or NULL
3682 * to remove the header. This function frees the
3683 * original string if necessary.
3685 * Returns : JB_ERR_OK on success, or
3686 * JB_ERR_MEMORY on out-of-memory error.
3688 *********************************************************************/
3689 static jb_err server_set_cookie(struct client_state *csp, char **header)
3696 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3698 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3701 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3703 /* Flag whether or not to log a message */
3706 /* A variable to store the tag we're working on */
3709 /* Skip "Set-Cookie:" (11 characters) in header */
3710 cur_tag = *header + 11;
3712 /* skip whitespace between "Set-Cookie:" and value */
3713 while (*cur_tag && ijb_isspace(*cur_tag))
3718 /* Loop through each tag in the cookie */
3722 char *next_tag = strchr(cur_tag, ';');
3723 if (next_tag != NULL)
3725 /* Skip the ';' character itself */
3728 /* skip whitespace ";" and start of tag */
3729 while (*next_tag && ijb_isspace(*next_tag))
3736 /* "Next tag" is the end of the string */
3737 next_tag = cur_tag + strlen(cur_tag);
3741 * Check the expiration date to see
3742 * if the cookie is still valid, if yes,
3743 * rewrite it to a session cookie.
3745 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3747 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3749 /* Did we detect the date properly? */
3750 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3753 * Nope, treat it as if it was still valid.
3755 * XXX: Should we remove the whole cookie instead?
3757 log_error(LOG_LEVEL_ERROR,
3758 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3759 string_move(cur_tag, next_tag);
3765 * Yes. Check if the cookie is still valid.
3767 * If the cookie is already expired it's probably
3768 * a delete cookie and even if it isn't, the browser
3769 * will discard it anyway.
3773 * XXX: timegm() isn't available on some AmigaOS
3774 * versions and our replacement doesn't work.
3776 * Our options are to either:
3778 * - disable session-cookies-only completely if timegm
3781 * - to simply remove all expired tags, like it has
3782 * been done until Privoxy 3.0.6 and to live with
3783 * the consequence that it can cause login/logout
3784 * problems on servers that don't validate their
3785 * input properly, or
3787 * - to replace it with mktime in which
3788 * case there is a slight chance of valid cookies
3789 * passing as already expired.
3791 * This is the way it's currently done and it's not
3792 * as bad as it sounds. If the missing GMT offset is
3793 * enough to change the result of the expiration check
3794 * the cookie will be only valid for a few hours
3795 * anyway, which in many cases will be shorter
3796 * than a browser session.
3798 if (cookie_time - now < 0)
3800 log_error(LOG_LEVEL_HEADER,
3801 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3802 /* Just in case some clown sets more then one expiration date */
3808 * Still valid, delete expiration date by copying
3809 * the rest of the string over it.
3811 string_move(cur_tag, next_tag);
3813 /* That changed the header, need to issue a log message */
3817 * Note that the next tag has now been moved to *cur_tag,
3818 * so we do not need to update the cur_tag pointer.
3826 /* Move on to next cookie tag */
3833 assert(NULL != *header);
3834 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3843 #ifdef FEATURE_FORCE_LOAD
3844 /*********************************************************************
3846 * Function : strclean
3848 * Description : In-Situ-Eliminate all occurances of substring in
3852 * 1 : string = string to clean
3853 * 2 : substring = substring to eliminate
3855 * Returns : Number of eliminations
3857 *********************************************************************/
3858 int strclean(char *string, const char *substring)
3864 len = strlen(substring);
3866 while((pos = strstr(string, substring)) != NULL)
3873 while (*p++ != '\0');
3880 #endif /* def FEATURE_FORCE_LOAD */
3883 /*********************************************************************
3885 * Function : parse_header_time
3887 * Description : Parses time formats used in HTTP header strings
3888 * to get the numerical respresentation.
3891 * 1 : header_time = HTTP header time as string.
3892 * 2 : result = storage for header_time in seconds
3894 * Returns : JB_ERR_OK if the time format was recognized, or
3895 * JB_ERR_PARSE otherwise.
3897 *********************************************************************/
3898 static jb_err parse_header_time(const char *header_time, time_t *result)
3903 * Zero out gmt to prevent time zone offsets.
3905 * While this is only necessary on some platforms
3906 * (mingw32 for example), I don't know how to
3907 * detect these automatically and doing it everywhere
3910 memset(&gmt, 0, sizeof(gmt));
3912 /* Tue, 02 Jun 2037 20:00:00 */
3913 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3914 /* Tue, 02-Jun-2037 20:00:00 */
3915 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3916 /* Tue, 02-Jun-37 20:00:00 */
3917 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3918 /* Tuesday, 02-Jun-2037 20:00:00 */
3919 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3920 /* Tuesday Jun 02 20:00:00 2037 */
3921 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3923 return JB_ERR_PARSE;
3926 *result = timegm(&gmt);
3933 /*********************************************************************
3935 * Function : get_destination_from_headers
3937 * Description : Parse the "Host:" header to get the request's destination.
3938 * Only needed if the client's request was forcefully
3939 * redirected into Privoxy.
3941 * Code mainly copied from client_host() which is currently
3942 * run too late for this purpose.
3945 * 1 : headers = List of headers (one of them hopefully being
3946 * the "Host:" header)
3947 * 2 : http = storage for the result (host, port and hostport).
3949 * Returns : JB_ERR_MEMORY in case of memory problems,
3950 * JB_ERR_PARSE if the host header couldn't be found,
3951 * JB_ERR_OK otherwise.
3953 *********************************************************************/
3954 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3960 host = get_header_value(headers, "Host:");
3964 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3965 return JB_ERR_PARSE;
3968 if (NULL == (p = strdup((host))))
3970 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3971 return JB_ERR_MEMORY;
3974 if (NULL == (q = strdup(p)))
3977 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3978 return JB_ERR_MEMORY;
3981 freez(http->hostport);
3985 q = strchr(http->host, ':');
3988 /* Terminate hostname and evaluate port string */
3990 http->port = atoi(q);
3994 http->port = http->ssl ? 443 : 80;
3997 /* Rebuild request URL */
3999 http->url = strdup(http->ssl ? "https://" : "http://");
4000 string_append(&http->url, http->hostport);
4001 string_append(&http->url, http->path);
4002 if (http->url == NULL)
4004 return JB_ERR_MEMORY;
4007 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4015 /*********************************************************************
4017 * Function : create_forged_referrer
4019 * Description : Helper for client_referrer to forge a referer as
4020 * 'http://[hostname:port/' to fool stupid
4021 * checks for in-site links
4024 * 1 : header = Pointer to header pointer
4025 * 2 : hostport = Host and optionally port as string
4027 * Returns : JB_ERR_OK in case of success, or
4028 * JB_ERR_MEMORY in case of memory problems.
4030 *********************************************************************/
4031 static jb_err create_forged_referrer(char **header, const char *hostport)
4033 assert(NULL == *header);
4035 *header = strdup("Referer: http://");
4036 string_append(header, hostport);
4037 string_append(header, "/");
4039 if (NULL == *header)
4041 return JB_ERR_MEMORY;
4044 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4051 /*********************************************************************
4053 * Function : create_fake_referrer
4055 * Description : Helper for client_referrer to create a fake referrer
4056 * based on a string supplied by the user.
4059 * 1 : header = Pointer to header pointer
4060 * 2 : hosthost = Referrer to fake
4062 * Returns : JB_ERR_OK in case of success, or
4063 * JB_ERR_MEMORY in case of memory problems.
4065 *********************************************************************/
4066 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4068 assert(NULL == *header);
4070 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4072 log_error(LOG_LEVEL_HEADER,
4073 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4075 *header = strdup("Referer: ");
4076 string_append(header, fake_referrer);
4078 if (NULL == *header)
4080 return JB_ERR_MEMORY;
4083 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4090 /*********************************************************************
4092 * Function : handle_conditional_hide_referrer_parameter
4094 * Description : Helper for client_referrer to crunch or forge
4095 * the referrer header if the host has changed.
4098 * 1 : header = Pointer to header pointer
4099 * 2 : host = The target host (may include the port)
4100 * 3 : parameter_conditional_block = Boolean to signal
4101 * if we're in conditional-block mode. If not set,
4102 * we're in conditional-forge mode.
4104 * Returns : JB_ERR_OK in case of success, or
4105 * JB_ERR_MEMORY in case of memory problems.
4107 *********************************************************************/
4108 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4109 const char *host, const int parameter_conditional_block)
4111 char *referer = strdup(*header);
4112 const size_t hostlenght = strlen(host);
4113 const char *referer_url = NULL;
4115 if (NULL == referer)
4118 return JB_ERR_MEMORY;
4121 /* referer begins with 'Referer: http[s]://' */
4122 if ((hostlenght+17) < strlen(referer))
4125 * Shorten referer to make sure the referer is blocked
4126 * if www.example.org/www.example.com-shall-see-the-referer/
4127 * links to www.example.com/
4129 referer[hostlenght+17] = '\0';
4131 referer_url = strstr(referer, "http://");
4132 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4134 /* Host has changed, Referer is invalid or a https URL. */
4135 if (parameter_conditional_block)
4137 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4144 return create_forged_referrer(header, host);
4154 /*********************************************************************
4156 * Function : create_content_length_header
4158 * Description : Creates a Content-Length header.
4161 * 1 : content_length = The content length to be used in the header.
4162 * 2 : header = Allocated space to safe the header.
4163 * 3 : buffer_length = The length of the allocated space.
4167 *********************************************************************/
4168 static void create_content_length_header(unsigned long long content_length,
4169 char *header, size_t buffer_length)
4171 snprintf(header, buffer_length, "Content-Length: %llu", content_length);