1 const char parsers_rcs[] = "$Id: parsers.c,v 1.194 2009/07/11 11:16:19 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 client_keep_alive(struct client_state *csp, char **header);
160 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
162 static jb_err client_host_adder (struct client_state *csp);
163 static jb_err client_xtra_adder (struct client_state *csp);
164 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
165 static jb_err client_connection_header_adder(struct client_state *csp);
166 static jb_err server_connection_adder(struct client_state *csp);
167 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
168 static jb_err server_proxy_connection_adder(struct client_state *csp);
169 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
171 static jb_err create_forged_referrer(char **header, const char *hostport);
172 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
173 static jb_err handle_conditional_hide_referrer_parameter(char **header,
174 const char *host, const int parameter_conditional_block);
175 static void create_content_length_header(unsigned long long content_length,
176 char *header, size_t buffer_length);
179 * List of functions to run on a list of headers.
183 /** The header prefix to match */
186 /** The length of the prefix to match */
189 /** The function to apply to this line */
190 const parser_func_ptr parser;
193 static const struct parsers client_patterns[] = {
194 { "referer:", 8, client_referrer },
195 { "user-agent:", 11, client_uagent },
196 { "ua-", 3, client_ua },
197 { "from:", 5, client_from },
198 { "cookie:", 7, client_send_cookie },
199 { "x-forwarded-for:", 16, client_x_forwarded },
200 { "Accept-Encoding:", 16, client_accept_encoding },
201 { "TE:", 3, client_te },
202 { "Host:", 5, client_host },
203 { "if-modified-since:", 18, client_if_modified_since },
204 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
205 { "Keep-Alive:", 11, client_keep_alive },
207 { "Keep-Alive:", 11, crumble },
209 { "connection:", 11, client_connection },
210 { "proxy-connection:", 17, crumble },
211 { "max-forwards:", 13, client_max_forwards },
212 { "Accept-Language:", 16, client_accept_language },
213 { "if-none-match:", 14, client_if_none_match },
214 { "Range:", 6, client_range },
215 { "Request-Range:", 14, client_range },
216 { "If-Range:", 9, client_range },
217 { "X-Filter:", 9, client_x_filter },
218 { "*", 0, crunch_client_header },
219 { "*", 0, filter_header },
223 static const struct parsers server_patterns[] = {
224 { "HTTP/", 5, server_http },
225 { "set-cookie:", 11, server_set_cookie },
226 { "connection:", 11, server_connection },
227 { "Content-Type:", 13, server_content_type },
228 { "Content-MD5:", 12, server_content_md5 },
229 { "Content-Encoding:", 17, server_content_encoding },
230 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
231 { "Content-Length:", 15, server_save_content_length },
232 { "Keep-Alive:", 11, server_keep_alive },
234 { "Keep-Alive:", 11, crumble },
235 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
236 { "Transfer-Encoding:", 18, server_transfer_coding },
237 { "content-disposition:", 20, server_content_disposition },
238 { "Last-Modified:", 14, server_last_modified },
239 { "*", 0, crunch_server_header },
240 { "*", 0, filter_header },
244 static const add_header_func_ptr add_client_headers[] = {
246 client_x_forwarded_for_adder,
248 /* Temporarily disabled: client_accept_encoding_adder, */
249 client_connection_header_adder,
253 static const add_header_func_ptr add_server_headers[] = {
254 server_connection_adder,
255 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
256 server_proxy_connection_adder,
257 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
261 /*********************************************************************
263 * Function : flush_socket
265 * Description : Write any pending "buffered" content.
268 * 1 : fd = file descriptor of the socket to read
269 * 2 : iob = The I/O buffer to flush, usually csp->iob.
271 * Returns : On success, the number of bytes written are returned (zero
272 * indicates nothing was written). On error, -1 is returned,
273 * and errno is set appropriately. If count is zero and the
274 * file descriptor refers to a regular file, 0 will be
275 * returned without causing any other effect. For a special
276 * file, the results are not portable.
278 *********************************************************************/
279 long flush_socket(jb_socket fd, struct iob *iob)
281 long len = iob->eod - iob->cur;
288 if (write_socket(fd, iob->cur, (size_t)len))
292 iob->eod = iob->cur = iob->buf;
298 /*********************************************************************
300 * Function : add_to_iob
302 * Description : Add content to the buffered page, expanding the
303 * buffer if necessary.
306 * 1 : csp = Current client state (buffers, headers, etc...)
307 * 2 : buf = holds the content to be added to the page
308 * 3 : n = number of bytes to be added
310 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
311 * or buffer limit reached.
313 *********************************************************************/
314 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
316 struct iob *iob = csp->iob;
317 size_t used, offset, need, want;
320 if (n <= 0) return JB_ERR_OK;
322 used = (size_t)(iob->eod - iob->buf);
323 offset = (size_t)(iob->cur - iob->buf);
324 need = used + (size_t)n + 1;
327 * If the buffer can't hold the new data, extend it first.
328 * Use the next power of two if possible, else use the actual need.
330 if (need > csp->config->buffer_limit)
332 log_error(LOG_LEVEL_INFO,
333 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
334 need, csp->config->buffer_limit);
335 return JB_ERR_MEMORY;
338 if (need > iob->size)
340 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
342 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
346 else if (NULL != (p = (char *)realloc(iob->buf, need)))
352 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
353 return JB_ERR_MEMORY;
356 /* Update the iob pointers */
357 iob->cur = p + offset;
362 /* copy the new data into the iob buffer */
363 memcpy(iob->eod, buf, (size_t)n);
365 /* point to the end of the data */
368 /* null terminate == cheap insurance */
377 /*********************************************************************
379 * Function : decompress_iob
381 * Description : Decompress buffered page, expanding the
382 * buffer as necessary. csp->iob->cur
383 * should point to the the beginning of the
384 * compressed data block.
387 * 1 : csp = Current client state (buffers, headers, etc...)
389 * Returns : JB_ERR_OK on success,
390 * JB_ERR_MEMORY if out-of-memory limit reached, and
391 * JB_ERR_COMPRESS if error decompressing buffer.
393 *********************************************************************/
394 jb_err decompress_iob(struct client_state *csp)
396 char *buf; /* new, uncompressed buffer */
397 char *cur; /* Current iob position (to keep the original
398 * iob->cur unmodified if we return early) */
399 size_t bufsize; /* allocated size of the new buffer */
400 size_t old_size; /* Content size before decompression */
401 size_t skip_size; /* Number of bytes at the beginning of the iob
402 that we should NOT decompress. */
403 int status; /* return status of the inflate() call */
404 z_stream zstr; /* used by calls to zlib */
406 assert(csp->iob->cur - csp->iob->buf > 0);
407 assert(csp->iob->eod - csp->iob->cur > 0);
409 bufsize = csp->iob->size;
410 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
411 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
415 if (bufsize < (size_t)10)
418 * This is to protect the parsing of gzipped data,
419 * but it should(?) be valid for deflated data also.
421 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
422 return JB_ERR_COMPRESS;
425 if (csp->content_type & CT_GZIP)
428 * Our task is slightly complicated by the facts that data
429 * compressed by gzip does not include a zlib header, and
430 * that there is no easily accessible interface in zlib to
431 * handle a gzip header. We strip off the gzip header by
432 * hand, and later inform zlib not to expect a header.
436 * Strip off the gzip header. Please see RFC 1952 for more
437 * explanation of the appropriate fields.
439 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
440 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
441 || (*cur++ != Z_DEFLATED))
443 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
444 return JB_ERR_COMPRESS;
449 if (flags & GZIP_FLAG_RESERVED_BITS)
451 /* The gzip header has reserved bits set; bail out. */
452 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
453 return JB_ERR_COMPRESS;
457 * Skip mtime (4 bytes), extra flags (1 byte)
458 * and OS type (1 byte).
462 /* Skip extra fields if necessary. */
463 if (flags & GZIP_FLAG_EXTRA_FIELDS)
466 * Skip a given number of bytes, specified
467 * as a 16-bit little-endian value.
469 * XXX: this code is untested and should probably be removed.
473 skip_bytes += *cur++ << 8;
476 * The number of bytes to skip should be positive
477 * and we'd like to stay in the buffer.
479 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
481 log_error(LOG_LEVEL_ERROR,
482 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
484 return JB_ERR_COMPRESS;
486 log_error(LOG_LEVEL_INFO,
487 "Skipping %d bytes for gzip compression. Does this sound right?",
492 /* Skip the filename if necessary. */
493 if (flags & GZIP_FLAG_FILE_NAME)
495 /* A null-terminated string is supposed to follow. */
496 while (*cur++ && (cur < csp->iob->eod));
499 /* Skip the comment if necessary. */
500 if (flags & GZIP_FLAG_COMMENT)
502 /* A null-terminated string is supposed to follow. */
503 while (*cur++ && (cur < csp->iob->eod));
506 /* Skip the CRC if necessary. */
507 if (flags & GZIP_FLAG_CHECKSUM)
512 if (cur >= csp->iob->eod)
515 * If the current position pointer reached or passed
516 * the buffer end, we were obviously tricked to skip
519 log_error(LOG_LEVEL_ERROR,
520 "Malformed gzip header detected. Aborting decompression.");
521 return JB_ERR_COMPRESS;
525 else if (csp->content_type & CT_DEFLATE)
528 * XXX: The debug level should be lowered
529 * before the next stable release.
531 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
533 * In theory (that is, according to RFC 1950), deflate-compressed
534 * data should begin with a two-byte zlib header and have an
535 * adler32 checksum at the end. It seems that in practice only
536 * the raw compressed data is sent. Note that this means that
537 * we are not RFC 1950-compliant here, but the advantage is that
538 * this actually works. :)
540 * We add a dummy null byte to tell zlib where the data ends,
541 * and later inform it not to expect a header.
543 * Fortunately, add_to_iob() has thoughtfully null-terminated
544 * the buffer; we can just increment the end pointer to include
551 log_error(LOG_LEVEL_ERROR,
552 "Unable to determine compression format for decompression");
553 return JB_ERR_COMPRESS;
556 /* Set up the fields required by zlib. */
557 zstr.next_in = (Bytef *)cur;
558 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
559 zstr.zalloc = Z_NULL;
561 zstr.opaque = Z_NULL;
564 * Passing -MAX_WBITS to inflateInit2 tells the library
565 * that there is no zlib header.
567 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
569 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
570 return JB_ERR_COMPRESS;
574 * Next, we allocate new storage for the inflated data.
575 * We don't modify the existing iob yet, so in case there
576 * is error in decompression we can recover gracefully.
578 buf = zalloc(bufsize);
581 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
582 return JB_ERR_MEMORY;
585 assert(bufsize >= skip_size);
586 memcpy(buf, csp->iob->buf, skip_size);
587 zstr.avail_out = bufsize - skip_size;
588 zstr.next_out = (Bytef *)buf + skip_size;
590 /* Try to decompress the whole stream in one shot. */
591 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
593 /* We need to allocate more memory for the output buffer. */
595 char *tmpbuf; /* used for realloc'ing the buffer */
596 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
598 if (0 == zstr.avail_in)
601 * If zlib wants more data then there's a problem, because
602 * the complete compressed file should have been buffered.
604 log_error(LOG_LEVEL_ERROR,
605 "Unexpected end of compressed iob. Using what we got so far.");
610 * If we tried the limit and still didn't have enough
611 * memory, just give up.
613 if (bufsize == csp->config->buffer_limit)
615 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
616 return JB_ERR_MEMORY;
619 /* Try doubling the buffer size each time. */
622 /* Don't exceed the buffer limit. */
623 if (bufsize > csp->config->buffer_limit)
625 bufsize = csp->config->buffer_limit;
628 /* Try to allocate the new buffer. */
629 tmpbuf = realloc(buf, bufsize);
632 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
634 return JB_ERR_MEMORY;
638 char *oldnext_out = (char *)zstr.next_out;
641 * Update the fields for inflate() to use the new
642 * buffer, which may be in a location different from
645 zstr.avail_out += bufsize - oldbufsize;
646 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
649 * Compare with an uglier method of calculating these values
650 * that doesn't require the extra oldbufsize variable.
652 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
653 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
654 assert(zstr.avail_out > 0U);
660 if (Z_STREAM_ERROR == inflateEnd(&zstr))
662 log_error(LOG_LEVEL_ERROR,
663 "Inconsistent stream state after decompression: %s", zstr.msg);
665 * XXX: Intentionally no return.
667 * According to zlib.h, Z_STREAM_ERROR is returned
668 * "if the stream state was inconsistent".
670 * I assume in this case inflate()'s status
671 * would also be something different than Z_STREAM_END
672 * so this check should be redundant, but lets see.
676 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
679 * We failed to decompress the stream and it's
680 * not simply because of missing data.
682 log_error(LOG_LEVEL_ERROR,
683 "Unexpected error while decompressing to the buffer (iob): %s",
685 return JB_ERR_COMPRESS;
689 * Finally, we can actually update the iob, since the
690 * decompression was successful. First, free the old
693 freez(csp->iob->buf);
695 /* Now, update the iob to use the new buffer. */
697 csp->iob->cur = csp->iob->buf + skip_size;
698 csp->iob->eod = (char *)zstr.next_out;
699 csp->iob->size = bufsize;
702 * Make sure the new uncompressed iob obeys some minimal
703 * consistency conditions.
705 if ((csp->iob->buf < csp->iob->cur)
706 && (csp->iob->cur <= csp->iob->eod)
707 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
709 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
710 if (new_size > (size_t)0)
712 log_error(LOG_LEVEL_RE_FILTER,
713 "Decompression successful. Old size: %d, new size: %d.",
718 /* zlib thinks this is OK, so lets do the same. */
719 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
724 /* It seems that zlib did something weird. */
725 log_error(LOG_LEVEL_ERROR,
726 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
727 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
728 csp->iob->eod, csp->iob->buf + csp->iob->size);
729 return JB_ERR_COMPRESS;
735 #endif /* defined(FEATURE_ZLIB) */
738 /*********************************************************************
740 * Function : string_move
742 * Description : memmove wrapper to move the last part of a string
743 * towards the beginning, overwriting the part in
744 * the middle. strlcpy() can't be used here as the
748 * 1 : dst = Destination to overwrite
749 * 2 : src = Source to move.
753 *********************************************************************/
754 static void string_move(char *dst, char *src)
758 /* +1 to copy the terminating nul as well. */
759 memmove(dst, src, strlen(src)+1);
763 /*********************************************************************
765 * Function : normalize_lws
767 * Description : Reduces unquoted linear white space in headers
768 * to a single space in accordance with RFC 2616 2.2.
769 * This simplifies parsing and filtering later on.
771 * XXX: Remove log messages before
772 * the next stable release?
775 * 1 : header = A header with linear white space to reduce.
779 *********************************************************************/
780 static void normalize_lws(char *header)
786 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
790 while (ijb_isspace(*q))
794 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
800 log_error(LOG_LEVEL_HEADER,
801 "Converting tab to space in '%s'", header);
806 char *end_of_token = strstr(p+1, "\"");
808 if (NULL != end_of_token)
810 /* Don't mess with quoted text. */
815 log_error(LOG_LEVEL_HEADER,
816 "Ignoring single quote in '%s'", header);
822 p = strchr(header, ':');
823 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
826 * There's still space before the colon.
834 /*********************************************************************
836 * Function : get_header
838 * Description : This (odd) routine will parse the csp->iob
839 * to get the next complete header.
842 * 1 : iob = The I/O buffer to parse, usually csp->iob.
844 * Returns : Any one of the following:
846 * 1) a pointer to a dynamically allocated string that contains a header line
847 * 2) NULL indicating that the end of the header was reached
848 * 3) "" indicating that the end of the iob was reached before finding
849 * a complete header line.
851 *********************************************************************/
852 char *get_header(struct iob *iob)
856 header = get_header_line(iob);
858 if ((header == NULL) || (*header == '\0'))
861 * No complete header read yet, tell the client.
866 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
869 * Header spans multiple lines, append the next one.
871 char *continued_header;
873 continued_header = get_header_line(iob);
874 if ((continued_header == NULL) || (*continued_header == '\0'))
877 * No complete header read yet, return what we got.
878 * XXX: Should "unread" header instead.
880 log_error(LOG_LEVEL_INFO,
881 "Failed to read a multi-line header properly: '%s'",
886 if (JB_ERR_OK != string_join(&header, continued_header))
888 log_error(LOG_LEVEL_FATAL,
889 "Out of memory while appending multiple headers.");
893 /* XXX: remove before next stable release. */
894 log_error(LOG_LEVEL_HEADER,
895 "Merged multiple header lines to: '%s'",
900 normalize_lws(header);
907 /*********************************************************************
909 * Function : get_header_line
911 * Description : This (odd) routine will parse the csp->iob
912 * to get the next header line.
915 * 1 : iob = The I/O buffer to parse, usually csp->iob.
917 * Returns : Any one of the following:
919 * 1) a pointer to a dynamically allocated string that contains a header line
920 * 2) NULL indicating that the end of the header was reached
921 * 3) "" indicating that the end of the iob was reached before finding
922 * a complete header line.
924 *********************************************************************/
925 static char *get_header_line(struct iob *iob)
929 if ((iob->cur == NULL)
930 || ((p = strchr(iob->cur, '\n')) == NULL))
932 return(""); /* couldn't find a complete header */
937 ret = strdup(iob->cur);
940 /* FIXME No way to handle error properly */
941 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
947 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
949 /* is this a blank line (i.e. the end of the header) ? */
961 /*********************************************************************
963 * Function : get_header_value
965 * Description : Get the value of a given header from a chained list
966 * of header lines or return NULL if no such header is
967 * present in the list.
970 * 1 : header_list = pointer to list
971 * 2 : header_name = string with name of header to look for.
972 * Trailing colon required, capitalization
975 * Returns : NULL if not found, else value of header
977 *********************************************************************/
978 char *get_header_value(const struct list *header_list, const char *header_name)
980 struct list_entry *cur_entry;
986 length = strlen(header_name);
988 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
992 if (!strncmpic(cur_entry->str, header_name, length))
995 * Found: return pointer to start of value
997 ret = cur_entry->str + length;
998 while (*ret && ijb_isspace(*ret)) ret++;
1012 /*********************************************************************
1014 * Function : scan_headers
1016 * Description : Scans headers, applies tags and updates action bits.
1019 * 1 : csp = Current client state (buffers, headers, etc...)
1021 * Returns : JB_ERR_OK
1023 *********************************************************************/
1024 static jb_err scan_headers(struct client_state *csp)
1026 struct list_entry *h; /* Header */
1027 jb_err err = JB_ERR_OK;
1029 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1031 /* Header crunch()ed in previous run? -> ignore */
1032 if (h->str == NULL) continue;
1033 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1034 err = header_tagger(csp, h->str);
1041 /*********************************************************************
1045 * Description : add, delete or modify lines in the HTTP header streams.
1046 * On entry, it receives a linked list of headers space
1047 * that was allocated dynamically (both the list nodes
1048 * and the header contents).
1050 * As a side effect it frees the space used by the original
1054 * 1 : csp = Current client state (buffers, headers, etc...)
1055 * 2 : filter_server_headers = Boolean to switch between
1056 * server and header filtering.
1058 * Returns : JB_ERR_OK in case off success, or
1059 * JB_ERR_MEMORY on out-of-memory error.
1061 *********************************************************************/
1062 jb_err sed(struct client_state *csp, int filter_server_headers)
1064 /* XXX: use more descriptive names. */
1065 struct list_entry *p;
1066 const struct parsers *v;
1067 const add_header_func_ptr *f;
1068 jb_err err = JB_ERR_OK;
1070 if (filter_server_headers)
1072 v = server_patterns;
1073 f = add_server_headers;
1077 v = client_patterns;
1078 f = add_client_headers;
1083 while ((err == JB_ERR_OK) && (v->str != NULL))
1085 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1087 /* Header crunch()ed in previous run? -> ignore */
1088 if (p->str == NULL) continue;
1090 /* Does the current parser handle this header? */
1091 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1092 (v->len == CHECK_EVERY_HEADER_REMAINING))
1094 err = v->parser(csp, &(p->str));
1100 /* place additional headers on the csp->headers list */
1101 while ((err == JB_ERR_OK) && (*f))
1111 /*********************************************************************
1113 * Function : update_server_headers
1115 * Description : Updates server headers after the body has been modified.
1118 * 1 : csp = Current client state (buffers, headers, etc...)
1120 * Returns : JB_ERR_OK in case off success, or
1121 * JB_ERR_MEMORY on out-of-memory error.
1123 *********************************************************************/
1124 jb_err update_server_headers(struct client_state *csp)
1126 jb_err err = JB_ERR_OK;
1128 static const struct parsers server_patterns_light[] = {
1129 { "Content-Length:", 15, server_adjust_content_length },
1130 { "Transfer-Encoding:", 18, server_transfer_coding },
1132 { "Content-Encoding:", 17, server_content_encoding },
1133 #endif /* def FEATURE_ZLIB */
1137 if (strncmpic(csp->http->cmd, "HEAD", 4))
1139 const struct parsers *v;
1140 struct list_entry *p;
1142 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1144 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1146 /* Header crunch()ed in previous run? -> ignore */
1147 if (p->str == NULL) continue;
1149 /* Does the current parser handle this header? */
1150 if (strncmpic(p->str, v->str, v->len) == 0)
1152 err = v->parser(csp, (char **)&(p->str));
1158 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1159 if ((JB_ERR_OK == err)
1160 && (csp->flags & CSP_FLAG_MODIFIED)
1161 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1162 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1166 create_content_length_header(csp->content_length, header, sizeof(header));
1167 err = enlist(csp->headers, header);
1168 if (JB_ERR_OK == err)
1170 log_error(LOG_LEVEL_HEADER,
1171 "Content modified with no Content-Length header set. "
1172 "Created: %s.", header);
1175 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1181 /*********************************************************************
1183 * Function : header_tagger
1185 * Description : Executes all text substitutions from applying
1186 * tag actions and saves the result as tag.
1188 * XXX: Shares enough code with filter_header() and
1189 * pcrs_filter_response() to warrant some helper functions.
1192 * 1 : csp = Current client state (buffers, headers, etc...)
1193 * 2 : header = Header that is used as tagger input
1195 * Returns : JB_ERR_OK on success and always succeeds
1197 *********************************************************************/
1198 static jb_err header_tagger(struct client_state *csp, char *header)
1200 int wanted_filter_type;
1201 int multi_action_index;
1205 struct file_list *fl;
1206 struct re_filterfile_spec *b;
1207 struct list_entry *tag_name;
1209 int found_filters = 0;
1210 const size_t header_length = strlen(header);
1212 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1214 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1215 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1219 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1220 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1223 /* Check if there are any filters */
1224 for (i = 0; i < MAX_AF_FILES; i++)
1237 if (0 == found_filters)
1239 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1240 "tagging enabled, but no taggers available.");
1244 for (i = 0; i < MAX_AF_FILES; i++)
1247 if ((NULL == fl) || (NULL == fl->f))
1250 * Either there are no filter files
1251 * left, or this filter file just
1252 * contains no valid filters.
1254 * Continue to be sure we don't miss
1255 * valid filter files that are chained
1256 * after empty or invalid ones.
1261 /* For all filters, */
1262 for (b = fl->f; b; b = b->next)
1264 if (b->type != wanted_filter_type)
1266 /* skip the ones we don't care about, */
1269 /* leaving only taggers that could apply, of which we use the ones, */
1270 for (tag_name = csp->action->multi[multi_action_index]->first;
1271 NULL != tag_name; tag_name = tag_name->next)
1273 /* that do apply, and */
1274 if (strcmp(b->name, tag_name->str) == 0)
1276 char *modified_tag = NULL;
1278 size_t size = header_length;
1279 pcrs_job *joblist = b->joblist;
1281 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1283 if (NULL == joblist)
1285 log_error(LOG_LEVEL_RE_FILTER,
1286 "Tagger %s has empty joblist. Nothing to do.", b->name);
1290 /* execute their pcrs_joblist on the header. */
1291 for (job = joblist; NULL != job; job = job->next)
1293 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1297 /* Success, continue with the modified version. */
1306 /* Tagger doesn't match */
1309 /* Regex failure, log it but continue anyway. */
1310 assert(NULL != header);
1311 log_error(LOG_LEVEL_ERROR,
1312 "Problems with tagger \'%s\' and header \'%s\': %s",
1313 b->name, *header, pcrs_strerror(hits));
1315 freez(modified_tag);
1319 if (b->dynamic) pcrs_free_joblist(joblist);
1321 /* If this tagger matched */
1327 * There is to technical limitation which makes
1328 * it impossible to use empty tags, but I assume
1329 * no one would do it intentionally.
1332 log_error(LOG_LEVEL_INFO,
1333 "Tagger \'%s\' created an empty tag. Ignored.",
1338 if (!list_contains_item(csp->tags, tag))
1340 if (JB_ERR_OK != enlist(csp->tags, tag))
1342 log_error(LOG_LEVEL_ERROR,
1343 "Insufficient memory to add tag \'%s\', "
1344 "based on tagger \'%s\' and header \'%s\'",
1345 tag, b->name, *header);
1349 char *action_message;
1351 * update the action bits right away, to make
1352 * tagging based on tags set by earlier taggers
1353 * of the same kind possible.
1355 if (update_action_bits_for_tag(csp, tag))
1357 action_message = "Action bits updated accordingly.";
1361 action_message = "No action bits update necessary.";
1364 log_error(LOG_LEVEL_HEADER,
1365 "Tagger \'%s\' added tag \'%s\'. %s",
1366 b->name, tag, action_message);
1371 /* XXX: Is this log-worthy? */
1372 log_error(LOG_LEVEL_HEADER,
1373 "Tagger \'%s\' didn't add tag \'%s\'. "
1374 "Tag already present", b->name, tag);
1377 } /* if the tagger matched */
1378 } /* if the tagger applies */
1379 } /* for every tagger that could apply */
1380 } /* for all filters */
1381 } /* for all filter files */
1386 /* here begins the family of parser functions that reformat header lines */
1388 /*********************************************************************
1390 * Function : filter_header
1392 * Description : Executes all text substitutions from all applying
1393 * +(server|client)-header-filter actions on the header.
1394 * Most of the code was copied from pcrs_filter_response,
1395 * including the rather short variable names
1398 * 1 : csp = Current client state (buffers, headers, etc...)
1399 * 2 : header = On input, pointer to header to modify.
1400 * On output, pointer to the modified header, or NULL
1401 * to remove the header. This function frees the
1402 * original string if necessary.
1404 * Returns : JB_ERR_OK on success and always succeeds
1406 *********************************************************************/
1407 static jb_err filter_header(struct client_state *csp, char **header)
1411 size_t size = strlen(*header);
1413 char *newheader = NULL;
1416 struct file_list *fl;
1417 struct re_filterfile_spec *b;
1418 struct list_entry *filtername;
1420 int i, found_filters = 0;
1421 int wanted_filter_type;
1422 int multi_action_index;
1424 if (csp->flags & CSP_FLAG_NO_FILTERING)
1429 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1431 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1432 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1436 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1437 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1441 * Need to check the set of re_filterfiles...
1443 for (i = 0; i < MAX_AF_FILES; i++)
1456 if (0 == found_filters)
1458 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1459 "header filtering enabled, but no matching filters available.");
1463 for (i = 0; i < MAX_AF_FILES; i++)
1466 if ((NULL == fl) || (NULL == fl->f))
1469 * Either there are no filter files
1470 * left, or this filter file just
1471 * contains no valid filters.
1473 * Continue to be sure we don't miss
1474 * valid filter files that are chained
1475 * after empty or invalid ones.
1480 * For all applying +filter actions, look if a filter by that
1481 * name exists and if yes, execute its pcrs_joblist on the
1484 for (b = fl->f; b; b = b->next)
1486 if (b->type != wanted_filter_type)
1488 /* Skip other filter types */
1492 for (filtername = csp->action->multi[multi_action_index]->first;
1493 filtername ; filtername = filtername->next)
1495 if (strcmp(b->name, filtername->str) == 0)
1497 int current_hits = 0;
1498 pcrs_job *joblist = b->joblist;
1500 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1502 if (NULL == joblist)
1504 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1508 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1509 *header, size, b->name);
1511 /* Apply all jobs from the joblist */
1512 for (job = joblist; NULL != job; job = job->next)
1514 matches = pcrs_execute(job, *header, size, &newheader, &size);
1517 current_hits += matches;
1518 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1520 *header = newheader;
1522 else if ( 0 == matches )
1524 /* Filter doesn't change header */
1530 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1531 *header, b->name, pcrs_strerror(matches));
1532 if (newheader != NULL)
1534 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1540 if (b->dynamic) pcrs_free_joblist(joblist);
1542 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1543 hits += current_hits;
1550 * Additionally checking for hits is important because if
1551 * the continue hack is triggered, server headers can
1552 * arrive empty to separate multiple heads from each other.
1554 if ((0 == size) && hits)
1556 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1564 /*********************************************************************
1566 * Function : server_connection
1568 * Description : Makes sure a proper "Connection:" header is
1569 * set and signals connection_header_adder to
1573 * 1 : csp = Current client state (buffers, headers, etc...)
1574 * 2 : header = On input, pointer to header to modify.
1575 * On output, pointer to the modified header, or NULL
1576 * to remove the header. This function frees the
1577 * original string if necessary.
1579 * Returns : JB_ERR_OK on success, or
1580 * JB_ERR_MEMORY on out-of-memory error.
1582 *********************************************************************/
1583 static jb_err server_connection(struct client_state *csp, char **header)
1585 if (!strcmpic(*header, "Connection: keep-alive")
1586 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1587 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1591 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1592 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1594 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1597 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1599 log_error(LOG_LEVEL_HEADER,
1600 "Keeping the server header '%s' around.", *header);
1603 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1605 char *old_header = *header;
1607 *header = strdup("Connection: close");
1610 return JB_ERR_MEMORY;
1612 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1617 /* Signal server_connection_adder() to return early. */
1618 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1624 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1625 /*********************************************************************
1627 * Function : server_keep_alive
1629 * Description : Stores the server's keep alive timeout.
1632 * 1 : csp = Current client state (buffers, headers, etc...)
1633 * 2 : header = On input, pointer to header to modify.
1634 * On output, pointer to the modified header, or NULL
1635 * to remove the header. This function frees the
1636 * original string if necessary.
1638 * Returns : JB_ERR_OK.
1640 *********************************************************************/
1641 static jb_err server_keep_alive(struct client_state *csp, char **header)
1643 unsigned int keep_alive_timeout;
1644 const char *timeout_position = strstr(*header, "timeout=");
1646 if ((NULL == timeout_position)
1647 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1649 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1653 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1655 log_error(LOG_LEVEL_HEADER,
1656 "Reducing keep-alive timeout from %u to %u.",
1657 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1658 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1662 /* XXX: Is this log worthy? */
1663 log_error(LOG_LEVEL_HEADER,
1664 "Server keep-alive timeout is %u. Sticking with %u.",
1665 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1673 /*********************************************************************
1675 * Function : client_keep_alive
1677 * Description : Stores the client's keep alive timeout.
1680 * 1 : csp = Current client state (buffers, headers, etc...)
1681 * 2 : header = On input, pointer to header to modify.
1682 * On output, pointer to the modified header, or NULL
1683 * to remove the header. This function frees the
1684 * original string if necessary.
1686 * Returns : JB_ERR_OK.
1688 *********************************************************************/
1689 static jb_err client_keep_alive(struct client_state *csp, char **header)
1691 unsigned int keep_alive_timeout;
1692 const char *timeout_position = strstr(*header, ": ");
1694 if ((NULL == timeout_position)
1695 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1697 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1701 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1703 log_error(LOG_LEVEL_HEADER,
1704 "Reducing keep-alive timeout from %u to %u.",
1705 csp->config->keep_alive_timeout, keep_alive_timeout);
1706 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1710 /* XXX: Is this log worthy? */
1711 log_error(LOG_LEVEL_HEADER,
1712 "Client keep-alive timeout is %u. Sticking with %u.",
1713 keep_alive_timeout, csp->config->keep_alive_timeout);
1719 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1723 /*********************************************************************
1725 * Function : client_connection
1727 * Description : Makes sure a proper "Connection:" header is
1728 * set and signals connection_header_adder
1732 * 1 : csp = Current client state (buffers, headers, etc...)
1733 * 2 : header = On input, pointer to header to modify.
1734 * On output, pointer to the modified header, or NULL
1735 * to remove the header. This function frees the
1736 * original string if necessary.
1738 * Returns : JB_ERR_OK on success, or
1739 * JB_ERR_MEMORY on out-of-memory error.
1741 *********************************************************************/
1742 static jb_err client_connection(struct client_state *csp, char **header)
1744 static const char connection_close[] = "Connection: close";
1746 if (!strcmpic(*header, connection_close))
1748 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1749 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1751 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1753 log_error(LOG_LEVEL_HEADER,
1754 "Removing \'%s\' to imply keep-alive.", *header);
1759 char *old_header = *header;
1761 *header = strdup("Connection: keep-alive");
1764 return JB_ERR_MEMORY;
1766 log_error(LOG_LEVEL_HEADER,
1767 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1770 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1774 log_error(LOG_LEVEL_HEADER,
1775 "Keeping the client header '%s' around. "
1776 "The connection will not be kept alive.",
1778 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1781 char *old_header = *header;
1783 *header = strdup(connection_close);
1786 return JB_ERR_MEMORY;
1788 log_error(LOG_LEVEL_HEADER,
1789 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1791 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1793 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1796 log_error(LOG_LEVEL_HEADER,
1797 "Keeping the client header '%s' around. "
1798 "The server connection will be kept alive if possible.",
1800 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1802 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1804 /* Signal client_connection_adder() to return early. */
1805 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1811 /*********************************************************************
1813 * Function : crumble
1815 * Description : This is called if a header matches a pattern to "crunch"
1818 * 1 : csp = Current client state (buffers, headers, etc...)
1819 * 2 : header = On input, pointer to header to modify.
1820 * On output, pointer to the modified header, or NULL
1821 * to remove the header. This function frees the
1822 * original string if necessary.
1824 * Returns : JB_ERR_OK on success, or
1825 * JB_ERR_MEMORY on out-of-memory error.
1827 *********************************************************************/
1828 static jb_err crumble(struct client_state *csp, char **header)
1831 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1837 /*********************************************************************
1839 * Function : crunch_server_header
1841 * Description : Crunch server header if it matches a string supplied by the
1842 * user. Called from `sed'.
1845 * 1 : csp = Current client state (buffers, headers, etc...)
1846 * 2 : header = On input, pointer to header to modify.
1847 * On output, pointer to the modified header, or NULL
1848 * to remove the header. This function frees the
1849 * original string if necessary.
1851 * Returns : JB_ERR_OK on success and always succeeds
1853 *********************************************************************/
1854 static jb_err crunch_server_header(struct client_state *csp, char **header)
1856 const char *crunch_pattern;
1858 /* Do we feel like crunching? */
1859 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1861 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1863 /* Is the current header the lucky one? */
1864 if (strstr(*header, crunch_pattern))
1866 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1875 /*********************************************************************
1877 * Function : server_content_type
1879 * Description : Set the content-type for filterable types (text/.*,
1880 * .*xml.*, javascript and image/gif) unless filtering has been
1881 * forbidden (CT_TABOO) while parsing earlier headers.
1882 * NOTE: Since text/plain is commonly used by web servers
1883 * for files whose correct type is unknown, we don't
1884 * set CT_TEXT for it.
1887 * 1 : csp = Current client state (buffers, headers, etc...)
1888 * 2 : header = On input, pointer to header to modify.
1889 * On output, pointer to the modified header, or NULL
1890 * to remove the header. This function frees the
1891 * original string if necessary.
1893 * Returns : JB_ERR_OK on success, or
1894 * JB_ERR_MEMORY on out-of-memory error.
1896 *********************************************************************/
1897 static jb_err server_content_type(struct client_state *csp, char **header)
1899 /* Remove header if it isn't the first Content-Type header */
1900 if ((csp->content_type & CT_DECLARED))
1903 * Another, slightly slower, way to see if
1904 * we already parsed another Content-Type header.
1906 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1908 log_error(LOG_LEVEL_ERROR,
1909 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1917 * Signal that the Content-Type has been set.
1919 csp->content_type |= CT_DECLARED;
1921 if (!(csp->content_type & CT_TABOO))
1924 * XXX: The assumption that text/plain is a sign of
1925 * binary data seems to be somewhat unreasonable nowadays
1926 * and should be dropped after 3.0.8 is out.
1928 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
1929 || strstr(*header, "xml")
1930 || strstr(*header, "application/x-javascript"))
1932 csp->content_type |= CT_TEXT;
1934 else if (strstr(*header, "image/gif"))
1936 csp->content_type |= CT_GIF;
1941 * Are we messing with the content type?
1943 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1946 * Make sure the user doesn't accidently
1947 * change the content type of binary documents.
1949 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
1952 *header = strdup("Content-Type: ");
1953 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1957 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1958 return JB_ERR_MEMORY;
1960 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1964 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
1965 "It doesn't look like a content type that should be filtered. "
1966 "Enable force-text-mode if you know what you're doing.", *header);
1974 /*********************************************************************
1976 * Function : server_transfer_coding
1978 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1979 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1980 * - Remove header if body was chunked but has been
1981 * de-chunked for filtering.
1984 * 1 : csp = Current client state (buffers, headers, etc...)
1985 * 2 : header = On input, pointer to header to modify.
1986 * On output, pointer to the modified header, or NULL
1987 * to remove the header. This function frees the
1988 * original string if necessary.
1990 * Returns : JB_ERR_OK on success, or
1991 * JB_ERR_MEMORY on out-of-memory error.
1993 *********************************************************************/
1994 static jb_err server_transfer_coding(struct client_state *csp, char **header)
1997 * Turn off pcrs and gif filtering if body compressed
1999 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2003 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2005 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2006 csp->http->cmd, *header);
2007 #endif /* def FEATURE_ZLIB */
2008 csp->content_type = CT_TABOO;
2012 * Raise flag if body chunked
2014 if (strstr(*header, "chunked"))
2016 csp->flags |= CSP_FLAG_CHUNKED;
2019 * If the body was modified, it has been de-chunked first
2020 * and the header must be removed.
2022 * FIXME: If there is more than one transfer encoding,
2023 * only the "chunked" part should be removed here.
2025 if (csp->flags & CSP_FLAG_MODIFIED)
2027 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2036 /*********************************************************************
2038 * Function : server_content_encoding
2040 * Description : This function is run twice for each request,
2041 * unless FEATURE_ZLIB and filtering are disabled.
2043 * The first run is used to check if the content
2044 * is compressed, if FEATURE_ZLIB is disabled
2045 * filtering is then disabled as well, if FEATURE_ZLIB
2046 * is enabled the content is marked for decompression.
2048 * The second run is used to remove the Content-Encoding
2049 * header if the decompression was successful.
2052 * 1 : csp = Current client state (buffers, headers, etc...)
2053 * 2 : header = On input, pointer to header to modify.
2054 * On output, pointer to the modified header, or NULL
2055 * to remove the header. This function frees the
2056 * original string if necessary.
2058 * Returns : JB_ERR_OK on success, or
2059 * JB_ERR_MEMORY on out-of-memory error.
2061 *********************************************************************/
2062 static jb_err server_content_encoding(struct client_state *csp, char **header)
2065 if ((csp->flags & CSP_FLAG_MODIFIED)
2066 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2069 * We successfully decompressed the content,
2070 * and have to clean the header now, so the
2071 * client no longer expects compressed data..
2073 * XXX: There is a difference between cleaning
2074 * and removing it completely.
2076 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2079 else if (strstr(*header, "gzip"))
2081 /* Mark for gzip decompression */
2082 csp->content_type |= CT_GZIP;
2084 else if (strstr(*header, "deflate"))
2086 /* Mark for zlib decompression */
2087 csp->content_type |= CT_DEFLATE;
2089 else if (strstr(*header, "compress"))
2092 * We can't decompress this; therefore we can't filter
2095 csp->content_type |= CT_TABOO;
2097 #else /* !defined(FEATURE_ZLIB) */
2098 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2101 * Body is compressed, turn off pcrs and gif filtering.
2103 csp->content_type |= CT_TABOO;
2106 * Log a warning if the user expects the content to be filtered.
2108 if ((csp->rlist != NULL) &&
2109 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2111 log_error(LOG_LEVEL_INFO,
2112 "Compressed content detected, content filtering disabled. "
2113 "Consider recompiling Privoxy with zlib support or "
2114 "enable the prevent-compression action.");
2117 #endif /* defined(FEATURE_ZLIB) */
2124 /*********************************************************************
2126 * Function : server_adjust_content_length
2128 * Description : Adjust Content-Length header if we modified
2132 * 1 : csp = Current client state (buffers, headers, etc...)
2133 * 2 : header = On input, pointer to header to modify.
2134 * On output, pointer to the modified header, or NULL
2135 * to remove the header. This function frees the
2136 * original string if necessary.
2138 * Returns : JB_ERR_OK on success, or
2139 * JB_ERR_MEMORY on out-of-memory error.
2141 *********************************************************************/
2142 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2144 /* Regenerate header if the content was modified. */
2145 if (csp->flags & CSP_FLAG_MODIFIED)
2147 const size_t header_length = 50;
2149 *header = malloc(header_length);
2150 if (*header == NULL)
2152 return JB_ERR_MEMORY;
2154 create_content_length_header(csp->content_length, *header, header_length);
2155 log_error(LOG_LEVEL_HEADER,
2156 "Adjusted Content-Length to %llu", csp->content_length);
2163 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2164 /*********************************************************************
2166 * Function : server_save_content_length
2168 * Description : Save the Content-Length sent by the server.
2171 * 1 : csp = Current client state (buffers, headers, etc...)
2172 * 2 : header = On input, pointer to header to modify.
2173 * On output, pointer to the modified header, or NULL
2174 * to remove the header. This function frees the
2175 * original string if necessary.
2177 * Returns : JB_ERR_OK on success, or
2178 * JB_ERR_MEMORY on out-of-memory error.
2180 *********************************************************************/
2181 static jb_err server_save_content_length(struct client_state *csp, char **header)
2183 unsigned long long content_length = 0;
2185 assert(*(*header+14) == ':');
2188 if (1 != sscanf(*header+14, ": %I64u", &content_length))
2190 if (1 != sscanf(*header+14, ": %llu", &content_length))
2193 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2198 csp->expected_content_length = content_length;
2199 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2200 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2205 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2208 /*********************************************************************
2210 * Function : server_content_md5
2212 * Description : Crumble any Content-MD5 headers if the document was
2213 * modified. FIXME: Should we re-compute instead?
2216 * 1 : csp = Current client state (buffers, headers, etc...)
2217 * 2 : header = On input, pointer to header to modify.
2218 * On output, pointer to the modified header, or NULL
2219 * to remove the header. This function frees the
2220 * original string if necessary.
2222 * Returns : JB_ERR_OK on success, or
2223 * JB_ERR_MEMORY on out-of-memory error.
2225 *********************************************************************/
2226 static jb_err server_content_md5(struct client_state *csp, char **header)
2228 if (csp->flags & CSP_FLAG_MODIFIED)
2230 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2238 /*********************************************************************
2240 * Function : server_content_disposition
2242 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2243 * Called from `sed'.
2246 * 1 : csp = Current client state (buffers, headers, etc...)
2247 * 2 : header = On input, pointer to header to modify.
2248 * On output, pointer to the modified header, or NULL
2249 * to remove the header. This function frees the
2250 * original string if necessary.
2252 * Returns : JB_ERR_OK on success, or
2253 * JB_ERR_MEMORY on out-of-memory error.
2255 *********************************************************************/
2256 static jb_err server_content_disposition(struct client_state *csp, char **header)
2261 * Are we messing with the Content-Disposition header?
2263 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2269 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2271 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2274 * Blocking content-disposition header
2276 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2283 * Replacing Content-Disposition header
2286 *header = strdup("Content-Disposition: ");
2287 string_append(header, newval);
2289 if (*header != NULL)
2291 log_error(LOG_LEVEL_HEADER,
2292 "Content-Disposition header crunched and replaced with: %s", *header);
2295 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2299 /*********************************************************************
2301 * Function : server_last_modified
2303 * Description : Changes Last-Modified header to the actual date
2304 * to help hide-if-modified-since.
2305 * Called from `sed'.
2308 * 1 : csp = Current client state (buffers, headers, etc...)
2309 * 2 : header = On input, pointer to header to modify.
2310 * On output, pointer to the modified header, or NULL
2311 * to remove the header. This function frees the
2312 * original string if necessary.
2314 * Returns : JB_ERR_OK on success, or
2315 * JB_ERR_MEMORY on out-of-memory error.
2317 *********************************************************************/
2318 static jb_err server_last_modified(struct client_state *csp, char **header)
2321 char buf[BUFFER_SIZE];
2324 #ifdef HAVE_GMTIME_R
2327 struct tm *timeptr = NULL;
2328 time_t now, last_modified;
2329 long int days, hours, minutes, seconds;
2332 * Are we messing with the Last-Modified header?
2334 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2340 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2342 if (0 == strcmpic(newval, "block") )
2345 * Blocking Last-Modified header. Useless but why not.
2347 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2351 else if (0 == strcmpic(newval, "reset-to-request-time"))
2354 * Setting Last-Modified Header to now.
2356 get_http_time(0, buf, sizeof(buf));
2358 *header = strdup("Last-Modified: ");
2359 string_append(header, buf);
2361 if (*header == NULL)
2363 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2367 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2370 else if (0 == strcmpic(newval, "randomize"))
2372 const char *header_time = *header + sizeof("Last-Modified:");
2374 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2376 #ifdef HAVE_GMTIME_R
2377 gmtime_r(&now, &gmt);
2378 #elif defined(MUTEX_LOCKS_AVAILABLE)
2379 privoxy_mutex_lock(&gmtime_mutex);
2381 privoxy_mutex_unlock(&gmtime_mutex);
2385 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2387 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2392 long int rtime = (long int)difftime(now, last_modified);
2395 const int negative_delta = (rtime < 0);
2400 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2402 rtime = pick_from_range(rtime);
2407 last_modified += rtime;
2408 #ifdef HAVE_GMTIME_R
2409 timeptr = gmtime_r(&last_modified, &gmt);
2410 #elif defined(MUTEX_LOCKS_AVAILABLE)
2411 privoxy_mutex_lock(&gmtime_mutex);
2412 timeptr = gmtime(&last_modified);
2413 privoxy_mutex_unlock(&gmtime_mutex);
2415 timeptr = gmtime(&last_modified);
2417 if ((NULL == timeptr) || !strftime(newheader,
2418 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2420 log_error(LOG_LEVEL_ERROR,
2421 "Randomizing '%s' failed. Crunching the header without replacement.",
2428 *header = strdup("Last-Modified: ");
2429 string_append(header, newheader);
2431 if (*header == NULL)
2433 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2434 return JB_ERR_MEMORY;
2437 days = rtime / (3600 * 24);
2438 hours = rtime / 3600 % 24;
2439 minutes = rtime / 60 % 60;
2440 seconds = rtime % 60;
2442 log_error(LOG_LEVEL_HEADER,
2443 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2444 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2445 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2449 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2458 /*********************************************************************
2460 * Function : client_accept_encoding
2462 * Description : Rewrite the client's Accept-Encoding header so that
2463 * if doesn't allow compression, if the action applies.
2464 * Note: For HTTP/1.0 the absence of the header is enough.
2467 * 1 : csp = Current client state (buffers, headers, etc...)
2468 * 2 : header = On input, pointer to header to modify.
2469 * On output, pointer to the modified header, or NULL
2470 * to remove the header. This function frees the
2471 * original string if necessary.
2473 * Returns : JB_ERR_OK on success, or
2474 * JB_ERR_MEMORY on out-of-memory error.
2476 *********************************************************************/
2477 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2479 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2481 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2485 /* Temporarily disable the correct behaviour to
2486 * work around a PHP bug.
2488 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2490 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2491 * if (*header == NULL)
2493 * return JB_ERR_MEMORY;
2504 /*********************************************************************
2506 * Function : client_te
2508 * Description : Rewrite the client's TE header so that
2509 * if doesn't allow compression, if the action applies.
2512 * 1 : csp = Current client state (buffers, headers, etc...)
2513 * 2 : header = On input, pointer to header to modify.
2514 * On output, pointer to the modified header, or NULL
2515 * to remove the header. This function frees the
2516 * original string if necessary.
2518 * Returns : JB_ERR_OK on success, or
2519 * JB_ERR_MEMORY on out-of-memory error.
2521 *********************************************************************/
2522 static jb_err client_te(struct client_state *csp, char **header)
2524 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2527 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2534 /*********************************************************************
2536 * Function : client_referrer
2538 * Description : Handle the "referer" config setting properly.
2539 * Called from `sed'.
2542 * 1 : csp = Current client state (buffers, headers, etc...)
2543 * 2 : header = On input, pointer to header to modify.
2544 * On output, pointer to the modified header, or NULL
2545 * to remove the header. This function frees the
2546 * original string if necessary.
2548 * Returns : JB_ERR_OK on success, or
2549 * JB_ERR_MEMORY on out-of-memory error.
2551 *********************************************************************/
2552 static jb_err client_referrer(struct client_state *csp, char **header)
2554 const char *parameter;
2555 /* booleans for parameters we have to check multiple times */
2556 int parameter_conditional_block;
2557 int parameter_conditional_forge;
2559 #ifdef FEATURE_FORCE_LOAD
2561 * Since the referrer can include the prefix even
2562 * if the request itself is non-forced, we must
2563 * clean it unconditionally.
2565 * XXX: strclean is too broad
2567 strclean(*header, FORCE_PREFIX);
2568 #endif /* def FEATURE_FORCE_LOAD */
2570 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2572 /* Nothing left to do */
2576 parameter = csp->action->string[ACTION_STRING_REFERER];
2577 assert(parameter != NULL);
2578 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2579 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2581 if (!parameter_conditional_block && !parameter_conditional_forge)
2584 * As conditional-block and conditional-forge are the only
2585 * parameters that rely on the original referrer, we can
2586 * remove it now for all the others.
2591 if (0 == strcmpic(parameter, "block"))
2593 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2596 else if (parameter_conditional_block || parameter_conditional_forge)
2598 return handle_conditional_hide_referrer_parameter(header,
2599 csp->http->hostport, parameter_conditional_block);
2601 else if (0 == strcmpic(parameter, "forge"))
2603 return create_forged_referrer(header, csp->http->hostport);
2607 /* interpret parameter as user-supplied referer to fake */
2608 return create_fake_referrer(header, parameter);
2613 /*********************************************************************
2615 * Function : client_accept_language
2617 * Description : Handle the "Accept-Language" config setting properly.
2618 * Called from `sed'.
2621 * 1 : csp = Current client state (buffers, headers, etc...)
2622 * 2 : header = On input, pointer to header to modify.
2623 * On output, pointer to the modified header, or NULL
2624 * to remove the header. This function frees the
2625 * original string if necessary.
2627 * Returns : JB_ERR_OK on success, or
2628 * JB_ERR_MEMORY on out-of-memory error.
2630 *********************************************************************/
2631 static jb_err client_accept_language(struct client_state *csp, char **header)
2636 * Are we messing with the Accept-Language?
2638 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2640 /*I don't think so*/
2644 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2646 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2649 * Blocking Accept-Language header
2651 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2658 * Replacing Accept-Language header
2661 *header = strdup("Accept-Language: ");
2662 string_append(header, newval);
2664 if (*header == NULL)
2666 log_error(LOG_LEVEL_ERROR,
2667 "Insufficient memory. Accept-Language header crunched without replacement.");
2671 log_error(LOG_LEVEL_HEADER,
2672 "Accept-Language header crunched and replaced with: %s", *header);
2675 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2679 /*********************************************************************
2681 * Function : crunch_client_header
2683 * Description : Crunch client header if it matches a string supplied by the
2684 * user. Called from `sed'.
2687 * 1 : csp = Current client state (buffers, headers, etc...)
2688 * 2 : header = On input, pointer to header to modify.
2689 * On output, pointer to the modified header, or NULL
2690 * to remove the header. This function frees the
2691 * original string if necessary.
2693 * Returns : JB_ERR_OK on success and always succeeds
2695 *********************************************************************/
2696 static jb_err crunch_client_header(struct client_state *csp, char **header)
2698 const char *crunch_pattern;
2700 /* Do we feel like crunching? */
2701 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2703 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2705 /* Is the current header the lucky one? */
2706 if (strstr(*header, crunch_pattern))
2708 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2716 /*********************************************************************
2718 * Function : client_uagent
2720 * Description : Handle the "user-agent" config setting properly
2721 * and remember its original value to enable browser
2722 * bug workarounds. Called from `sed'.
2725 * 1 : csp = Current client state (buffers, headers, etc...)
2726 * 2 : header = On input, pointer to header to modify.
2727 * On output, pointer to the modified header, or NULL
2728 * to remove the header. This function frees the
2729 * original string if necessary.
2731 * Returns : JB_ERR_OK on success, or
2732 * JB_ERR_MEMORY on out-of-memory error.
2734 *********************************************************************/
2735 static jb_err client_uagent(struct client_state *csp, char **header)
2739 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2744 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2751 *header = strdup("User-Agent: ");
2752 string_append(header, newval);
2754 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2756 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2760 /*********************************************************************
2762 * Function : client_ua
2764 * Description : Handle "ua-" headers properly. Called from `sed'.
2767 * 1 : csp = Current client state (buffers, headers, etc...)
2768 * 2 : header = On input, pointer to header to modify.
2769 * On output, pointer to the modified header, or NULL
2770 * to remove the header. This function frees the
2771 * original string if necessary.
2773 * Returns : JB_ERR_OK on success, or
2774 * JB_ERR_MEMORY on out-of-memory error.
2776 *********************************************************************/
2777 static jb_err client_ua(struct client_state *csp, char **header)
2779 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2781 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2789 /*********************************************************************
2791 * Function : client_from
2793 * Description : Handle the "from" config setting properly.
2794 * Called from `sed'.
2797 * 1 : csp = Current client state (buffers, headers, etc...)
2798 * 2 : header = On input, pointer to header to modify.
2799 * On output, pointer to the modified header, or NULL
2800 * to remove the header. This function frees the
2801 * original string if necessary.
2803 * Returns : JB_ERR_OK on success, or
2804 * JB_ERR_MEMORY on out-of-memory error.
2806 *********************************************************************/
2807 static jb_err client_from(struct client_state *csp, char **header)
2811 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2818 newval = csp->action->string[ACTION_STRING_FROM];
2821 * Are we blocking the e-mail address?
2823 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2825 log_error(LOG_LEVEL_HEADER, "crunched From!");
2829 log_error(LOG_LEVEL_HEADER, " modified");
2831 *header = strdup("From: ");
2832 string_append(header, newval);
2834 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2838 /*********************************************************************
2840 * Function : client_send_cookie
2842 * Description : Crunches the "cookie" header if necessary.
2843 * Called from `sed'.
2845 * XXX: Stupid name, doesn't send squat.
2848 * 1 : csp = Current client state (buffers, headers, etc...)
2849 * 2 : header = On input, pointer to header to modify.
2850 * On output, pointer to the modified header, or NULL
2851 * to remove the header. This function frees the
2852 * original string if necessary.
2854 * Returns : JB_ERR_OK on success, or
2855 * JB_ERR_MEMORY on out-of-memory error.
2857 *********************************************************************/
2858 static jb_err client_send_cookie(struct client_state *csp, char **header)
2860 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2862 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2870 /*********************************************************************
2872 * Function : client_x_forwarded
2874 * Description : Handle the "x-forwarded-for" config setting properly,
2875 * also used in the add_client_headers list. Called from `sed'.
2878 * 1 : csp = Current client state (buffers, headers, etc...)
2879 * 2 : header = On input, pointer to header to modify.
2880 * On output, pointer to the modified header, or NULL
2881 * to remove the header. This function frees the
2882 * original string if necessary.
2884 * Returns : JB_ERR_OK on success, or
2885 * JB_ERR_MEMORY on out-of-memory error.
2887 *********************************************************************/
2888 jb_err client_x_forwarded(struct client_state *csp, char **header)
2890 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2892 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2894 if (0 == strcmpic(parameter, "block"))
2897 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2899 else if (0 == strcmpic(parameter, "add"))
2901 string_append(header, ", ");
2902 string_append(header, csp->ip_addr_str);
2904 if (*header == NULL)
2906 return JB_ERR_MEMORY;
2908 log_error(LOG_LEVEL_HEADER,
2909 "Appended client IP address to %s", *header);
2910 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
2914 log_error(LOG_LEVEL_FATAL,
2915 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
2923 /*********************************************************************
2925 * Function : client_max_forwards
2927 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2928 * from the value of the Max-Forwards header field.
2931 * 1 : csp = Current client state (buffers, headers, etc...)
2932 * 2 : header = On input, pointer to header to modify.
2933 * On output, pointer to the modified header, or NULL
2934 * to remove the header. This function frees the
2935 * original string if necessary.
2937 * Returns : JB_ERR_OK on success, or
2938 * JB_ERR_MEMORY on out-of-memory error.
2940 *********************************************************************/
2941 static jb_err client_max_forwards(struct client_state *csp, char **header)
2945 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2946 (0 == strcmpic(csp->http->gpc, "options")))
2948 assert(*(*header+12) == ':');
2949 if (1 == sscanf(*header+12, ": %d", &max_forwards))
2951 if (max_forwards > 0)
2953 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
2954 log_error(LOG_LEVEL_HEADER,
2955 "Max-Forwards value for %s request reduced to %d.",
2956 csp->http->gpc, max_forwards);
2958 else if (max_forwards < 0)
2960 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2966 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2975 /*********************************************************************
2977 * Function : client_host
2979 * Description : If the request URI did not contain host and
2980 * port information, parse and evaluate the Host
2983 * Also, kill ill-formed HOST: headers as sent by
2984 * Apple's iTunes software when used with a proxy.
2987 * 1 : csp = Current client state (buffers, headers, etc...)
2988 * 2 : header = On input, pointer to header to modify.
2989 * On output, pointer to the modified header, or NULL
2990 * to remove the header. This function frees the
2991 * original string if necessary.
2993 * Returns : JB_ERR_OK on success, or
2994 * JB_ERR_MEMORY on out-of-memory error.
2996 *********************************************************************/
2997 static jb_err client_host(struct client_state *csp, char **header)
3002 * If the header field name is all upper-case, chances are that it's
3003 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3004 * not a problem -- they are regenerated later.
3006 if ((*header)[1] == 'O')
3008 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3013 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3014 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3017 if (NULL == (p = strdup((*header)+6)))
3019 return JB_ERR_MEMORY;
3022 if (NULL == (q = strdup(p)))
3025 return JB_ERR_MEMORY;
3028 freez(csp->http->hostport);
3029 csp->http->hostport = p;
3030 freez(csp->http->host);
3031 csp->http->host = q;
3032 q = strchr(csp->http->host, ':');
3035 /* Terminate hostname and evaluate port string */
3037 csp->http->port = atoi(q);
3041 csp->http->port = csp->http->ssl ? 443 : 80;
3044 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3045 csp->http->hostport, csp->http->host, csp->http->port);
3048 /* Signal client_host_adder() to return right away */
3049 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3055 /*********************************************************************
3057 * Function : client_if_modified_since
3059 * Description : Remove or modify the If-Modified-Since header.
3062 * 1 : csp = Current client state (buffers, headers, etc...)
3063 * 2 : header = On input, pointer to header to modify.
3064 * On output, pointer to the modified header, or NULL
3065 * to remove the header. This function frees the
3066 * original string if necessary.
3068 * Returns : JB_ERR_OK on success, or
3069 * JB_ERR_MEMORY on out-of-memory error.
3071 *********************************************************************/
3072 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3075 #ifdef HAVE_GMTIME_R
3078 struct tm *timeptr = NULL;
3081 long int hours, minutes, seconds;
3084 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3087 * The client got an error message because of a temporary problem,
3088 * the problem is gone and the client now tries to revalidate our
3089 * error message on the real server. The revalidation would always
3090 * end with the transmission of the whole document and there is
3091 * no need to expose the bogus If-Modified-Since header.
3093 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3096 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3098 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3100 if ((0 == strcmpic(newval, "block")))
3102 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3105 else /* add random value */
3107 const char *header_time = *header + sizeof("If-Modified-Since:");
3109 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3111 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3116 long int rtime = strtol(newval, &endptr, 0);
3117 const int negative_range = (rtime < 0);
3121 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3122 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3128 rtime = pick_from_range(rtime);
3132 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3135 tm += rtime * (negative_range ? -1 : 1);
3136 #ifdef HAVE_GMTIME_R
3137 timeptr = gmtime_r(&tm, &gmt);
3138 #elif defined(MUTEX_LOCKS_AVAILABLE)
3139 privoxy_mutex_lock(&gmtime_mutex);
3140 timeptr = gmtime(&tm);
3141 privoxy_mutex_unlock(&gmtime_mutex);
3143 timeptr = gmtime(&tm);
3145 if ((NULL == timeptr) || !strftime(newheader,
3146 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3148 log_error(LOG_LEVEL_ERROR,
3149 "Randomizing '%s' failed. Crunching the header without replacement.",
3156 *header = strdup("If-Modified-Since: ");
3157 string_append(header, newheader);
3159 if (*header == NULL)
3161 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3162 return JB_ERR_MEMORY;
3165 hours = rtime / 3600;
3166 minutes = rtime / 60 % 60;
3167 seconds = rtime % 60;
3169 log_error(LOG_LEVEL_HEADER,
3170 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3171 *header, (negative_range) ? "subtracted" : "added", hours,
3172 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3173 seconds, (seconds == 1) ? ")" : "s)");
3182 /*********************************************************************
3184 * Function : client_if_none_match
3186 * Description : Remove the If-None-Match header.
3189 * 1 : csp = Current client state (buffers, headers, etc...)
3190 * 2 : header = On input, pointer to header to modify.
3191 * On output, pointer to the modified header, or NULL
3192 * to remove the header. This function frees the
3193 * original string if necessary.
3195 * Returns : JB_ERR_OK on success, or
3196 * JB_ERR_MEMORY on out-of-memory error.
3198 *********************************************************************/
3199 static jb_err client_if_none_match(struct client_state *csp, char **header)
3201 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3203 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3211 /*********************************************************************
3213 * Function : client_x_filter
3215 * Description : Disables filtering if the client set "X-Filter: No".
3216 * Called from `sed'.
3219 * 1 : csp = Current client state (buffers, headers, etc...)
3220 * 2 : header = On input, pointer to header to modify.
3221 * On output, pointer to the modified header, or NULL
3222 * to remove the header. This function frees the
3223 * original string if necessary.
3225 * Returns : JB_ERR_OK on success
3227 *********************************************************************/
3228 jb_err client_x_filter(struct client_state *csp, char **header)
3230 if ( 0 == strcmpic(*header, "X-Filter: No"))
3232 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3234 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3238 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3240 log_error(LOG_LEVEL_HEADER,
3241 "force-text-mode overruled the client's request to fetch without filtering!");
3245 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3246 csp->flags |= CSP_FLAG_NO_FILTERING;
3247 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3249 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3257 /*********************************************************************
3259 * Function : client_range
3261 * Description : Removes Range, Request-Range and If-Range headers if
3262 * content filtering is enabled. If the client's version
3263 * of the document has been altered by Privoxy, the server
3264 * could interpret the range differently than the client
3265 * intended in which case the user could end up with
3266 * corrupted content.
3269 * 1 : csp = Current client state (buffers, headers, etc...)
3270 * 2 : header = On input, pointer to header to modify.
3271 * On output, pointer to the modified header, or NULL
3272 * to remove the header. This function frees the
3273 * original string if necessary.
3275 * Returns : JB_ERR_OK
3277 *********************************************************************/
3278 static jb_err client_range(struct client_state *csp, char **header)
3280 if (content_filters_enabled(csp->action))
3282 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3283 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3290 /* the following functions add headers directly to the header list */
3292 /*********************************************************************
3294 * Function : client_host_adder
3296 * Description : Adds the Host: header field if it is missing.
3297 * Called from `sed'.
3300 * 1 : csp = Current client state (buffers, headers, etc...)
3302 * Returns : JB_ERR_OK on success, or
3303 * JB_ERR_MEMORY on out-of-memory error.
3305 *********************************************************************/
3306 static jb_err client_host_adder(struct client_state *csp)
3311 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3313 /* Header already set by the client, nothing to do. */
3317 if ( !csp->http->hostport || !*(csp->http->hostport))
3319 /* XXX: When does this happen and why is it OK? */
3320 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3325 * remove 'user:pass@' from 'proto://user:pass@host'
3327 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3333 p = csp->http->hostport;
3336 /* XXX: Just add it, we already made sure that it will be unique */
3337 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3338 err = enlist_unique_header(csp->headers, "Host", p);
3345 /*********************************************************************
3347 * Function : client_accept_encoding_adder
3349 * Description : Add an Accept-Encoding header to the client's request
3350 * that disables compression if the action applies, and
3351 * the header is not already there. Called from `sed'.
3352 * Note: For HTTP/1.0, the absence of the header is enough.
3355 * 1 : csp = Current client state (buffers, headers, etc...)
3357 * Returns : JB_ERR_OK on success, or
3358 * JB_ERR_MEMORY on out-of-memory error.
3360 *********************************************************************/
3361 static jb_err client_accept_encoding_adder(struct client_state *csp)
3363 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3364 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3366 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3374 /*********************************************************************
3376 * Function : client_xtra_adder
3378 * Description : Used in the add_client_headers list. Called from `sed'.
3381 * 1 : csp = Current client state (buffers, headers, etc...)
3383 * Returns : JB_ERR_OK on success, or
3384 * JB_ERR_MEMORY on out-of-memory error.
3386 *********************************************************************/
3387 static jb_err client_xtra_adder(struct client_state *csp)
3389 struct list_entry *lst;
3392 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3393 lst ; lst = lst->next)
3395 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3396 err = enlist(csp->headers, lst->str);
3408 /*********************************************************************
3410 * Function : client_x_forwarded_for_adder
3412 * Description : Used in the add_client_headers list. Called from `sed'.
3415 * 1 : csp = Current client state (buffers, headers, etc...)
3417 * Returns : JB_ERR_OK on success, or
3418 * JB_ERR_MEMORY on out-of-memory error.
3420 *********************************************************************/
3421 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3423 char *header = NULL;
3426 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3427 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3428 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3431 * If we aren't adding X-Forwarded-For headers,
3432 * or we already appended an existing X-Forwarded-For
3433 * header, there's nothing left to do here.
3438 header = strdup("X-Forwarded-For: ");
3439 string_append(&header, csp->ip_addr_str);
3443 return JB_ERR_MEMORY;
3446 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3447 err = enlist(csp->headers, header);
3454 /*********************************************************************
3456 * Function : server_connection_adder
3458 * Description : Adds an appropiate "Connection:" header to csp->headers
3459 * unless the header was already present. Called from `sed'.
3462 * 1 : csp = Current client state (buffers, headers, etc...)
3464 * Returns : JB_ERR_OK on success, or
3465 * JB_ERR_MEMORY on out-of-memory error.
3467 *********************************************************************/
3468 static jb_err server_connection_adder(struct client_state *csp)
3470 const unsigned int flags = csp->flags;
3471 const char *response_status_line = csp->headers->first->str;
3472 static const char connection_close[] = "Connection: close";
3474 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3475 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3481 * XXX: if we downgraded the response, this check will fail.
3483 if ((csp->config->feature_flags &
3484 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3485 && (NULL != response_status_line)
3486 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3487 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3488 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3490 && (csp->http->status == 200)
3494 * XXX: not doing this for status codes other than 200 works
3495 * around problems with broken servers that will keep the
3496 * connection open, but terminate the connection when the
3497 * next request arrives. Once we are able to figure out which
3498 * requests are safe to send again, this will probably no
3499 * longer be necessary.
3501 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3502 "without Connection header implies keep-alive.");
3503 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3507 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3509 return enlist(csp->headers, connection_close);
3513 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3514 /*********************************************************************
3516 * Function : server_proxy_connection_adder
3518 * Description : Adds a "Proxy-Connection: keep-alive" header to
3519 * csp->headers if the client asked for keep-alive.
3520 * XXX: We should reuse existant ones.
3523 * 1 : csp = Current client state (buffers, headers, etc...)
3525 * Returns : JB_ERR_OK on success, or
3526 * JB_ERR_MEMORY on out-of-memory error.
3528 *********************************************************************/
3529 static jb_err server_proxy_connection_adder(struct client_state *csp)
3531 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3532 jb_err err = JB_ERR_OK;
3534 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3535 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
3537 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3538 err = enlist(csp->headers, proxy_connection_header);
3543 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3546 /*********************************************************************
3548 * Function : client_connection_header_adder
3550 * Description : Adds a proper "Connection:" header to csp->headers
3551 * unless the header was already present. Called from `sed'.
3554 * 1 : csp = Current client state (buffers, headers, etc...)
3556 * Returns : JB_ERR_OK on success, or
3557 * JB_ERR_MEMORY on out-of-memory error.
3559 *********************************************************************/
3560 static jb_err client_connection_header_adder(struct client_state *csp)
3562 static const char connection_close[] = "Connection: close";
3564 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3565 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3570 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3571 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3572 && (csp->http->ssl == 0)
3573 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3575 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3578 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3580 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3582 return enlist(csp->headers, connection_close);
3586 /*********************************************************************
3588 * Function : server_http
3590 * Description : - Save the HTTP Status into csp->http->status
3591 * - Set CT_TABOO to prevent filtering if the answer
3592 * is a partial range (HTTP status 206)
3593 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3597 * 1 : csp = Current client state (buffers, headers, etc...)
3598 * 2 : header = On input, pointer to header to modify.
3599 * On output, pointer to the modified header, or NULL
3600 * to remove the header. This function frees the
3601 * original string if necessary.
3603 * Returns : JB_ERR_OK on success, or
3604 * JB_ERR_MEMORY on out-of-memory error.
3606 *********************************************************************/
3607 static jb_err server_http(struct client_state *csp, char **header)
3609 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3610 if (csp->http->status == 206)
3612 csp->content_type = CT_TABOO;
3615 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3617 /* XXX: Should we do a real validity check here? */
3618 if (strlen(*header) > 8)
3621 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3626 * XXX: Should we block the request or
3627 * enlist a valid status code line here?
3629 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3630 "Downgrading to HTTP/1.0 impossible.");
3638 /*********************************************************************
3640 * Function : server_set_cookie
3642 * Description : Handle the server "cookie" header properly.
3643 * Log cookie to the jar file. Then "crunch",
3644 * accept or rewrite it to a session cookie.
3645 * Called from `sed'.
3647 * TODO: Allow the user to specify a new expiration
3648 * time to cause the cookie to expire even before the
3649 * browser is closed.
3652 * 1 : csp = Current client state (buffers, headers, etc...)
3653 * 2 : header = On input, pointer to header to modify.
3654 * On output, pointer to the modified header, or NULL
3655 * to remove the header. This function frees the
3656 * original string if necessary.
3658 * Returns : JB_ERR_OK on success, or
3659 * JB_ERR_MEMORY on out-of-memory error.
3661 *********************************************************************/
3662 static jb_err server_set_cookie(struct client_state *csp, char **header)
3669 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3671 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3674 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3676 /* Flag whether or not to log a message */
3679 /* A variable to store the tag we're working on */
3682 /* Skip "Set-Cookie:" (11 characters) in header */
3683 cur_tag = *header + 11;
3685 /* skip whitespace between "Set-Cookie:" and value */
3686 while (*cur_tag && ijb_isspace(*cur_tag))
3691 /* Loop through each tag in the cookie */
3695 char *next_tag = strchr(cur_tag, ';');
3696 if (next_tag != NULL)
3698 /* Skip the ';' character itself */
3701 /* skip whitespace ";" and start of tag */
3702 while (*next_tag && ijb_isspace(*next_tag))
3709 /* "Next tag" is the end of the string */
3710 next_tag = cur_tag + strlen(cur_tag);
3714 * Check the expiration date to see
3715 * if the cookie is still valid, if yes,
3716 * rewrite it to a session cookie.
3718 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3720 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3722 /* Did we detect the date properly? */
3723 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3726 * Nope, treat it as if it was still valid.
3728 * XXX: Should we remove the whole cookie instead?
3730 log_error(LOG_LEVEL_ERROR,
3731 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3732 string_move(cur_tag, next_tag);
3738 * Yes. Check if the cookie is still valid.
3740 * If the cookie is already expired it's probably
3741 * a delete cookie and even if it isn't, the browser
3742 * will discard it anyway.
3746 * XXX: timegm() isn't available on some AmigaOS
3747 * versions and our replacement doesn't work.
3749 * Our options are to either:
3751 * - disable session-cookies-only completely if timegm
3754 * - to simply remove all expired tags, like it has
3755 * been done until Privoxy 3.0.6 and to live with
3756 * the consequence that it can cause login/logout
3757 * problems on servers that don't validate their
3758 * input properly, or
3760 * - to replace it with mktime in which
3761 * case there is a slight chance of valid cookies
3762 * passing as already expired.
3764 * This is the way it's currently done and it's not
3765 * as bad as it sounds. If the missing GMT offset is
3766 * enough to change the result of the expiration check
3767 * the cookie will be only valid for a few hours
3768 * anyway, which in many cases will be shorter
3769 * than a browser session.
3771 if (cookie_time - now < 0)
3773 log_error(LOG_LEVEL_HEADER,
3774 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3775 /* Just in case some clown sets more then one expiration date */
3781 * Still valid, delete expiration date by copying
3782 * the rest of the string over it.
3784 string_move(cur_tag, next_tag);
3786 /* That changed the header, need to issue a log message */
3790 * Note that the next tag has now been moved to *cur_tag,
3791 * so we do not need to update the cur_tag pointer.
3799 /* Move on to next cookie tag */
3806 assert(NULL != *header);
3807 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3816 #ifdef FEATURE_FORCE_LOAD
3817 /*********************************************************************
3819 * Function : strclean
3821 * Description : In-Situ-Eliminate all occurances of substring in
3825 * 1 : string = string to clean
3826 * 2 : substring = substring to eliminate
3828 * Returns : Number of eliminations
3830 *********************************************************************/
3831 int strclean(char *string, const char *substring)
3837 len = strlen(substring);
3839 while((pos = strstr(string, substring)) != NULL)
3846 while (*p++ != '\0');
3853 #endif /* def FEATURE_FORCE_LOAD */
3856 /*********************************************************************
3858 * Function : parse_header_time
3860 * Description : Parses time formats used in HTTP header strings
3861 * to get the numerical respresentation.
3864 * 1 : header_time = HTTP header time as string.
3865 * 2 : result = storage for header_time in seconds
3867 * Returns : JB_ERR_OK if the time format was recognized, or
3868 * JB_ERR_PARSE otherwise.
3870 *********************************************************************/
3871 static jb_err parse_header_time(const char *header_time, time_t *result)
3876 * Zero out gmt to prevent time zone offsets.
3878 * While this is only necessary on some platforms
3879 * (mingw32 for example), I don't know how to
3880 * detect these automatically and doing it everywhere
3883 memset(&gmt, 0, sizeof(gmt));
3885 /* Tue, 02 Jun 2037 20:00:00 */
3886 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3887 /* Tue, 02-Jun-2037 20:00:00 */
3888 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3889 /* Tue, 02-Jun-37 20:00:00 */
3890 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3891 /* Tuesday, 02-Jun-2037 20:00:00 */
3892 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3893 /* Tuesday Jun 02 20:00:00 2037 */
3894 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3896 return JB_ERR_PARSE;
3899 *result = timegm(&gmt);
3906 /*********************************************************************
3908 * Function : get_destination_from_headers
3910 * Description : Parse the "Host:" header to get the request's destination.
3911 * Only needed if the client's request was forcefully
3912 * redirected into Privoxy.
3914 * Code mainly copied from client_host() which is currently
3915 * run too late for this purpose.
3918 * 1 : headers = List of headers (one of them hopefully being
3919 * the "Host:" header)
3920 * 2 : http = storage for the result (host, port and hostport).
3922 * Returns : JB_ERR_MEMORY in case of memory problems,
3923 * JB_ERR_PARSE if the host header couldn't be found,
3924 * JB_ERR_OK otherwise.
3926 *********************************************************************/
3927 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3933 host = get_header_value(headers, "Host:");
3937 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3938 return JB_ERR_PARSE;
3941 if (NULL == (p = strdup((host))))
3943 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3944 return JB_ERR_MEMORY;
3947 if (NULL == (q = strdup(p)))
3950 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3951 return JB_ERR_MEMORY;
3954 freez(http->hostport);
3958 q = strchr(http->host, ':');
3961 /* Terminate hostname and evaluate port string */
3963 http->port = atoi(q);
3967 http->port = http->ssl ? 443 : 80;
3970 /* Rebuild request URL */
3972 http->url = strdup(http->ssl ? "https://" : "http://");
3973 string_append(&http->url, http->hostport);
3974 string_append(&http->url, http->path);
3975 if (http->url == NULL)
3977 return JB_ERR_MEMORY;
3980 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
3988 /*********************************************************************
3990 * Function : create_forged_referrer
3992 * Description : Helper for client_referrer to forge a referer as
3993 * 'http://[hostname:port/' to fool stupid
3994 * checks for in-site links
3997 * 1 : header = Pointer to header pointer
3998 * 2 : hostport = Host and optionally port as string
4000 * Returns : JB_ERR_OK in case of success, or
4001 * JB_ERR_MEMORY in case of memory problems.
4003 *********************************************************************/
4004 static jb_err create_forged_referrer(char **header, const char *hostport)
4006 assert(NULL == *header);
4008 *header = strdup("Referer: http://");
4009 string_append(header, hostport);
4010 string_append(header, "/");
4012 if (NULL == *header)
4014 return JB_ERR_MEMORY;
4017 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4024 /*********************************************************************
4026 * Function : create_fake_referrer
4028 * Description : Helper for client_referrer to create a fake referrer
4029 * based on a string supplied by the user.
4032 * 1 : header = Pointer to header pointer
4033 * 2 : hosthost = Referrer to fake
4035 * Returns : JB_ERR_OK in case of success, or
4036 * JB_ERR_MEMORY in case of memory problems.
4038 *********************************************************************/
4039 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4041 assert(NULL == *header);
4043 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4045 log_error(LOG_LEVEL_HEADER,
4046 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4048 *header = strdup("Referer: ");
4049 string_append(header, fake_referrer);
4051 if (NULL == *header)
4053 return JB_ERR_MEMORY;
4056 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4063 /*********************************************************************
4065 * Function : handle_conditional_hide_referrer_parameter
4067 * Description : Helper for client_referrer to crunch or forge
4068 * the referrer header if the host has changed.
4071 * 1 : header = Pointer to header pointer
4072 * 2 : host = The target host (may include the port)
4073 * 3 : parameter_conditional_block = Boolean to signal
4074 * if we're in conditional-block mode. If not set,
4075 * we're in conditional-forge mode.
4077 * Returns : JB_ERR_OK in case of success, or
4078 * JB_ERR_MEMORY in case of memory problems.
4080 *********************************************************************/
4081 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4082 const char *host, const int parameter_conditional_block)
4084 char *referer = strdup(*header);
4085 const size_t hostlenght = strlen(host);
4086 const char *referer_url = NULL;
4088 if (NULL == referer)
4091 return JB_ERR_MEMORY;
4094 /* referer begins with 'Referer: http[s]://' */
4095 if ((hostlenght+17) < strlen(referer))
4098 * Shorten referer to make sure the referer is blocked
4099 * if www.example.org/www.example.com-shall-see-the-referer/
4100 * links to www.example.com/
4102 referer[hostlenght+17] = '\0';
4104 referer_url = strstr(referer, "http://");
4105 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4107 /* Host has changed, Referer is invalid or a https URL. */
4108 if (parameter_conditional_block)
4110 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4117 return create_forged_referrer(header, host);
4127 /*********************************************************************
4129 * Function : create_content_length_header
4131 * Description : Creates a Content-Length header.
4134 * 1 : content_length = The content length to be used in the header.
4135 * 2 : header = Allocated space to safe the header.
4136 * 3 : buffer_length = The length of the allocated space.
4140 *********************************************************************/
4141 static void create_content_length_header(unsigned long long content_length,
4142 char *header, size_t buffer_length)
4144 snprintf(header, buffer_length, "Content-Length: %llu", content_length);