1 const char parsers_rcs[] = "$Id: parsers.c,v 1.156 2009/05/13 18:22:45 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.
72 #if !defined(_WIN32) && !defined(__OS2__)
78 #ifdef FEATURE_PTHREAD
80 /* jcc.h is for mutex semapores only */
81 #endif /* def FEATURE_PTHREAD */
86 #include "jbsockets.h"
96 const char parsers_h_rcs[] = PARSERS_H_VERSION;
98 /* Fix a problem with Solaris. There should be no effect on other
100 * Solaris's isspace() is a macro which uses its argument directly
101 * as an array index. Therefore we need to make sure that high-bit
102 * characters generate +ve values, and ideally we also want to make
103 * the argument match the declared parameter type of "int".
105 * Why did they write a character function that can't take a simple
106 * "char" argument? Doh!
108 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
109 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
111 static char *get_header_line(struct iob *iob);
112 static jb_err scan_headers(struct client_state *csp);
113 static jb_err header_tagger(struct client_state *csp, char *header);
114 static jb_err parse_header_time(const char *header_time, time_t *result);
116 static jb_err crumble (struct client_state *csp, char **header);
117 static jb_err filter_header (struct client_state *csp, char **header);
118 static jb_err client_connection (struct client_state *csp, char **header);
119 static jb_err client_referrer (struct client_state *csp, char **header);
120 static jb_err client_uagent (struct client_state *csp, char **header);
121 static jb_err client_ua (struct client_state *csp, char **header);
122 static jb_err client_from (struct client_state *csp, char **header);
123 static jb_err client_send_cookie (struct client_state *csp, char **header);
124 static jb_err client_x_forwarded (struct client_state *csp, char **header);
125 static jb_err client_accept_encoding (struct client_state *csp, char **header);
126 static jb_err client_te (struct client_state *csp, char **header);
127 static jb_err client_max_forwards (struct client_state *csp, char **header);
128 static jb_err client_host (struct client_state *csp, char **header);
129 static jb_err client_if_modified_since (struct client_state *csp, char **header);
130 static jb_err client_accept_language (struct client_state *csp, char **header);
131 static jb_err client_if_none_match (struct client_state *csp, char **header);
132 static jb_err crunch_client_header (struct client_state *csp, char **header);
133 static jb_err client_x_filter (struct client_state *csp, char **header);
134 static jb_err client_range (struct client_state *csp, char **header);
135 static jb_err server_set_cookie (struct client_state *csp, char **header);
136 static jb_err server_connection (struct client_state *csp, char **header);
137 static jb_err server_content_type (struct client_state *csp, char **header);
138 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
139 static jb_err server_content_md5 (struct client_state *csp, char **header);
140 static jb_err server_content_encoding (struct client_state *csp, char **header);
141 static jb_err server_transfer_coding (struct client_state *csp, char **header);
142 static jb_err server_http (struct client_state *csp, char **header);
143 static jb_err crunch_server_header (struct client_state *csp, char **header);
144 static jb_err server_last_modified (struct client_state *csp, char **header);
145 static jb_err server_content_disposition(struct client_state *csp, char **header);
147 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
148 static jb_err server_save_content_length(struct client_state *csp, char **header);
149 static jb_err server_keep_alive(struct client_state *csp, char **header);
150 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
152 static jb_err client_host_adder (struct client_state *csp);
153 static jb_err client_xtra_adder (struct client_state *csp);
154 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
155 static jb_err client_connection_header_adder(struct client_state *csp);
156 static jb_err server_connection_adder(struct client_state *csp);
157 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
158 static jb_err server_proxy_connection_adder(struct client_state *csp);
159 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
161 static jb_err create_forged_referrer(char **header, const char *hostport);
162 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
163 static jb_err handle_conditional_hide_referrer_parameter(char **header,
164 const char *host, const int parameter_conditional_block);
165 static const char *get_appropiate_connection_header(const struct client_state *csp);
168 * List of functions to run on a list of headers.
172 /** The header prefix to match */
175 /** The length of the prefix to match */
178 /** The function to apply to this line */
179 const parser_func_ptr parser;
182 static const struct parsers client_patterns[] = {
183 { "referer:", 8, client_referrer },
184 { "user-agent:", 11, client_uagent },
185 { "ua-", 3, client_ua },
186 { "from:", 5, client_from },
187 { "cookie:", 7, client_send_cookie },
188 { "x-forwarded-for:", 16, client_x_forwarded },
189 { "Accept-Encoding:", 16, client_accept_encoding },
190 { "TE:", 3, client_te },
191 { "Host:", 5, client_host },
192 { "if-modified-since:", 18, client_if_modified_since },
193 #ifndef FEATURE_CONNECTION_KEEP_ALIVE
194 { "Keep-Alive:", 11, crumble },
196 { "connection:", 11, client_connection },
197 { "proxy-connection:", 17, crumble },
198 { "max-forwards:", 13, client_max_forwards },
199 { "Accept-Language:", 16, client_accept_language },
200 { "if-none-match:", 14, client_if_none_match },
201 { "Range:", 6, client_range },
202 { "Request-Range:", 14, client_range },
203 { "If-Range:", 9, client_range },
204 { "X-Filter:", 9, client_x_filter },
205 { "*", 0, crunch_client_header },
206 { "*", 0, filter_header },
210 static const struct parsers server_patterns[] = {
211 { "HTTP/", 5, server_http },
212 { "set-cookie:", 11, server_set_cookie },
213 { "connection:", 11, server_connection },
214 { "Content-Type:", 13, server_content_type },
215 { "Content-MD5:", 12, server_content_md5 },
216 { "Content-Encoding:", 17, server_content_encoding },
217 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
218 { "Content-Length:", 15, server_save_content_length },
219 { "Keep-Alive:", 11, server_keep_alive },
221 { "Keep-Alive:", 11, crumble },
222 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
223 { "Transfer-Encoding:", 18, server_transfer_coding },
224 { "content-disposition:", 20, server_content_disposition },
225 { "Last-Modified:", 14, server_last_modified },
226 { "*", 0, crunch_server_header },
227 { "*", 0, filter_header },
231 static const add_header_func_ptr add_client_headers[] = {
233 client_x_forwarded_for_adder,
235 /* Temporarily disabled: client_accept_encoding_adder, */
236 client_connection_header_adder,
240 static const add_header_func_ptr add_server_headers[] = {
241 server_connection_adder,
242 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
243 server_proxy_connection_adder,
244 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
248 /*********************************************************************
250 * Function : flush_socket
252 * Description : Write any pending "buffered" content.
255 * 1 : fd = file descriptor of the socket to read
256 * 2 : iob = The I/O buffer to flush, usually csp->iob.
258 * Returns : On success, the number of bytes written are returned (zero
259 * indicates nothing was written). On error, -1 is returned,
260 * and errno is set appropriately. If count is zero and the
261 * file descriptor refers to a regular file, 0 will be
262 * returned without causing any other effect. For a special
263 * file, the results are not portable.
265 *********************************************************************/
266 long flush_socket(jb_socket fd, struct iob *iob)
268 long len = iob->eod - iob->cur;
275 if (write_socket(fd, iob->cur, (size_t)len))
279 iob->eod = iob->cur = iob->buf;
285 /*********************************************************************
287 * Function : add_to_iob
289 * Description : Add content to the buffered page, expanding the
290 * buffer if necessary.
293 * 1 : csp = Current client state (buffers, headers, etc...)
294 * 2 : buf = holds the content to be added to the page
295 * 3 : n = number of bytes to be added
297 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
298 * or buffer limit reached.
300 *********************************************************************/
301 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
303 struct iob *iob = csp->iob;
304 size_t used, offset, need, want;
307 if (n <= 0) return JB_ERR_OK;
309 used = (size_t)(iob->eod - iob->buf);
310 offset = (size_t)(iob->cur - iob->buf);
311 need = used + (size_t)n + 1;
314 * If the buffer can't hold the new data, extend it first.
315 * Use the next power of two if possible, else use the actual need.
317 if (need > csp->config->buffer_limit)
319 log_error(LOG_LEVEL_INFO,
320 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
321 need, csp->config->buffer_limit);
322 return JB_ERR_MEMORY;
325 if (need > iob->size)
327 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
329 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
333 else if (NULL != (p = (char *)realloc(iob->buf, need)))
339 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
340 return JB_ERR_MEMORY;
343 /* Update the iob pointers */
344 iob->cur = p + offset;
349 /* copy the new data into the iob buffer */
350 memcpy(iob->eod, buf, (size_t)n);
352 /* point to the end of the data */
355 /* null terminate == cheap insurance */
364 /*********************************************************************
366 * Function : decompress_iob
368 * Description : Decompress buffered page, expanding the
369 * buffer as necessary. csp->iob->cur
370 * should point to the the beginning of the
371 * compressed data block.
374 * 1 : csp = Current client state (buffers, headers, etc...)
376 * Returns : JB_ERR_OK on success,
377 * JB_ERR_MEMORY if out-of-memory limit reached, and
378 * JB_ERR_COMPRESS if error decompressing buffer.
380 *********************************************************************/
381 jb_err decompress_iob(struct client_state *csp)
383 char *buf; /* new, uncompressed buffer */
384 char *cur; /* Current iob position (to keep the original
385 * iob->cur unmodified if we return early) */
386 size_t bufsize; /* allocated size of the new buffer */
387 size_t old_size; /* Content size before decompression */
388 size_t skip_size; /* Number of bytes at the beginning of the iob
389 that we should NOT decompress. */
390 int status; /* return status of the inflate() call */
391 z_stream zstr; /* used by calls to zlib */
393 assert(csp->iob->cur - csp->iob->buf > 0);
394 assert(csp->iob->eod - csp->iob->cur > 0);
396 bufsize = csp->iob->size;
397 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
398 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
402 if (bufsize < (size_t)10)
405 * This is to protect the parsing of gzipped data,
406 * but it should(?) be valid for deflated data also.
408 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
409 return JB_ERR_COMPRESS;
412 if (csp->content_type & CT_GZIP)
415 * Our task is slightly complicated by the facts that data
416 * compressed by gzip does not include a zlib header, and
417 * that there is no easily accessible interface in zlib to
418 * handle a gzip header. We strip off the gzip header by
419 * hand, and later inform zlib not to expect a header.
423 * Strip off the gzip header. Please see RFC 1952 for more
424 * explanation of the appropriate fields.
426 if ((*cur++ != (char)0x1f)
427 || (*cur++ != (char)0x8b)
428 || (*cur++ != Z_DEFLATED))
430 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
431 return JB_ERR_COMPRESS;
437 * XXX: These magic numbers should be replaced
438 * with macros to give a better idea what they do.
442 /* The gzip header has reserved bits set; bail out. */
443 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
444 return JB_ERR_COMPRESS;
448 /* Skip extra fields if necessary. */
452 * Skip a given number of bytes, specified
453 * as a 16-bit little-endian value.
456 * XXX: This code used to be:
458 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
460 * which I had to change into:
462 * cur += *cur++ + (*cur++ << 8);
464 * at which point gcc43 finally noticed that the value
465 * of cur is undefined (it depends on which of the
466 * summands is evaluated first).
468 * I haven't come across a site where this
469 * code is actually executed yet, but I hope
474 skip_bytes = *cur++ << 8;
476 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
479 * The number of bytes to skip should be positive
480 * and we'd like to stay in the buffer.
482 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
484 log_error(LOG_LEVEL_ERROR,
485 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
487 return JB_ERR_COMPRESS;
489 log_error(LOG_LEVEL_INFO,
490 "Skipping %d bytes for gzip compression. Does this sound right?",
495 /* Skip the filename if necessary. */
498 /* A null-terminated string is supposed to follow. */
499 while (*cur++ && (cur < csp->iob->eod));
503 /* Skip the comment if necessary. */
506 /* A null-terminated string is supposed to follow. */
507 while (*cur++ && (cur < csp->iob->eod));
510 /* Skip the CRC if necessary. */
516 if (cur >= csp->iob->eod)
519 * If the current position pointer reached or passed
520 * the buffer end, we were obviously tricked to skip
523 log_error(LOG_LEVEL_ERROR,
524 "Malformed gzip header detected. Aborting decompression.");
525 return JB_ERR_COMPRESS;
529 else if (csp->content_type & CT_DEFLATE)
532 * XXX: The debug level should be lowered
533 * before the next stable release.
535 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
537 * In theory (that is, according to RFC 1950), deflate-compressed
538 * data should begin with a two-byte zlib header and have an
539 * adler32 checksum at the end. It seems that in practice only
540 * the raw compressed data is sent. Note that this means that
541 * we are not RFC 1950-compliant here, but the advantage is that
542 * this actually works. :)
544 * We add a dummy null byte to tell zlib where the data ends,
545 * and later inform it not to expect a header.
547 * Fortunately, add_to_iob() has thoughtfully null-terminated
548 * the buffer; we can just increment the end pointer to include
555 log_error(LOG_LEVEL_ERROR,
556 "Unable to determine compression format for decompression");
557 return JB_ERR_COMPRESS;
560 /* Set up the fields required by zlib. */
561 zstr.next_in = (Bytef *)cur;
562 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
563 zstr.zalloc = Z_NULL;
565 zstr.opaque = Z_NULL;
568 * Passing -MAX_WBITS to inflateInit2 tells the library
569 * that there is no zlib header.
571 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
573 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
574 return JB_ERR_COMPRESS;
578 * Next, we allocate new storage for the inflated data.
579 * We don't modify the existing iob yet, so in case there
580 * is error in decompression we can recover gracefully.
582 buf = zalloc(bufsize);
585 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
586 return JB_ERR_MEMORY;
589 assert(bufsize >= skip_size);
590 memcpy(buf, csp->iob->buf, skip_size);
591 zstr.avail_out = bufsize - skip_size;
592 zstr.next_out = (Bytef *)buf + skip_size;
594 /* Try to decompress the whole stream in one shot. */
595 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
597 /* We need to allocate more memory for the output buffer. */
599 char *tmpbuf; /* used for realloc'ing the buffer */
600 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
603 * If zlib wants more data then there's a problem, because
604 * the complete compressed file should have been buffered.
606 if (0 == zstr.avail_in)
608 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
609 return JB_ERR_COMPRESS;
613 * If we tried the limit and still didn't have enough
614 * memory, just give up.
616 if (bufsize == csp->config->buffer_limit)
618 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
619 return JB_ERR_MEMORY;
622 /* Try doubling the buffer size each time. */
625 /* Don't exceed the buffer limit. */
626 if (bufsize > csp->config->buffer_limit)
628 bufsize = csp->config->buffer_limit;
631 /* Try to allocate the new buffer. */
632 tmpbuf = realloc(buf, bufsize);
635 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
637 return JB_ERR_MEMORY;
641 char *oldnext_out = (char *)zstr.next_out;
644 * Update the fields for inflate() to use the new
645 * buffer, which may be in a location different from
648 zstr.avail_out += bufsize - oldbufsize;
649 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
652 * Compare with an uglier method of calculating these values
653 * that doesn't require the extra oldbufsize variable.
655 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
656 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
657 assert(zstr.avail_out > 0U);
663 if (Z_STREAM_ERROR == inflateEnd(&zstr))
665 log_error(LOG_LEVEL_ERROR,
666 "Inconsistent stream state after decompression: %s", zstr.msg);
668 * XXX: Intentionally no return.
670 * According to zlib.h, Z_STREAM_ERROR is returned
671 * "if the stream state was inconsistent".
673 * I assume in this case inflate()'s status
674 * would also be something different than Z_STREAM_END
675 * so this check should be redundant, but lets see.
679 if (status != Z_STREAM_END)
681 /* We failed to decompress the stream. */
682 log_error(LOG_LEVEL_ERROR,
683 "Error in decompressing to the buffer (iob): %s", zstr.msg);
684 return JB_ERR_COMPRESS;
688 * Finally, we can actually update the iob, since the
689 * decompression was successful. First, free the old
692 freez(csp->iob->buf);
694 /* Now, update the iob to use the new buffer. */
696 csp->iob->cur = csp->iob->buf + skip_size;
697 csp->iob->eod = (char *)zstr.next_out;
698 csp->iob->size = bufsize;
701 * Make sure the new uncompressed iob obeys some minimal
702 * consistency conditions.
704 if ((csp->iob->buf < csp->iob->cur)
705 && (csp->iob->cur <= csp->iob->eod)
706 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
708 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
709 if (new_size > (size_t)0)
711 log_error(LOG_LEVEL_RE_FILTER,
712 "Decompression successful. Old size: %d, new size: %d.",
717 /* zlib thinks this is OK, so lets do the same. */
718 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
723 /* It seems that zlib did something weird. */
724 log_error(LOG_LEVEL_ERROR,
725 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
726 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
727 csp->iob->eod, csp->iob->buf + csp->iob->size);
728 return JB_ERR_COMPRESS;
734 #endif /* defined(FEATURE_ZLIB) */
737 /*********************************************************************
739 * Function : string_move
741 * Description : memmove wrapper to move the last part of a string
742 * towards the beginning, overwriting the part in
743 * the middle. strlcpy() can't be used here as the
747 * 1 : dst = Destination to overwrite
748 * 2 : src = Source to move.
752 *********************************************************************/
753 static void string_move(char *dst, char *src)
757 /* +1 to copy the terminating nul as well. */
758 memmove(dst, src, strlen(src)+1);
762 /*********************************************************************
764 * Function : normalize_lws
766 * Description : Reduces unquoted linear white space in headers
767 * to a single space in accordance with RFC 2616 2.2.
768 * This simplifies parsing and filtering later on.
770 * XXX: Remove log messages before
771 * the next stable release?
774 * 1 : header = A header with linear white space to reduce.
778 *********************************************************************/
779 static void normalize_lws(char *header)
785 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
789 while (ijb_isspace(*q))
793 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
799 log_error(LOG_LEVEL_HEADER,
800 "Converting tab to space in '%s'", header);
805 char *end_of_token = strstr(p+1, "\"");
807 if (NULL != end_of_token)
809 /* Don't mess with quoted text. */
814 log_error(LOG_LEVEL_HEADER,
815 "Ignoring single quote in '%s'", header);
821 p = strchr(header, ':');
822 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
825 * There's still space before the colon.
833 /*********************************************************************
835 * Function : get_header
837 * Description : This (odd) routine will parse the csp->iob
838 * to get the next complete header.
841 * 1 : iob = The I/O buffer to parse, usually csp->iob.
843 * Returns : Any one of the following:
845 * 1) a pointer to a dynamically allocated string that contains a header line
846 * 2) NULL indicating that the end of the header was reached
847 * 3) "" indicating that the end of the iob was reached before finding
848 * a complete header line.
850 *********************************************************************/
851 char *get_header(struct iob *iob)
855 header = get_header_line(iob);
857 if ((header == NULL) || (*header == '\0'))
860 * No complete header read yet, tell the client.
865 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
868 * Header spans multiple lines, append the next one.
870 char *continued_header;
872 continued_header = get_header_line(iob);
873 if ((continued_header == NULL) || (*continued_header == '\0'))
876 * No complete header read yet, return what we got.
877 * XXX: Should "unread" header instead.
879 log_error(LOG_LEVEL_INFO,
880 "Failed to read a multi-line header properly: '%s'",
885 if (JB_ERR_OK != string_join(&header, continued_header))
887 log_error(LOG_LEVEL_FATAL,
888 "Out of memory while appending multiple headers.");
892 /* XXX: remove before next stable release. */
893 log_error(LOG_LEVEL_HEADER,
894 "Merged multiple header lines to: '%s'",
899 normalize_lws(header);
906 /*********************************************************************
908 * Function : get_header_line
910 * Description : This (odd) routine will parse the csp->iob
911 * to get the next header line.
914 * 1 : iob = The I/O buffer to parse, usually csp->iob.
916 * Returns : Any one of the following:
918 * 1) a pointer to a dynamically allocated string that contains a header line
919 * 2) NULL indicating that the end of the header was reached
920 * 3) "" indicating that the end of the iob was reached before finding
921 * a complete header line.
923 *********************************************************************/
924 static char *get_header_line(struct iob *iob)
928 if ((iob->cur == NULL)
929 || ((p = strchr(iob->cur, '\n')) == NULL))
931 return(""); /* couldn't find a complete header */
936 ret = strdup(iob->cur);
939 /* FIXME No way to handle error properly */
940 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
946 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
948 /* is this a blank line (i.e. the end of the header) ? */
960 /*********************************************************************
962 * Function : get_header_value
964 * Description : Get the value of a given header from a chained list
965 * of header lines or return NULL if no such header is
966 * present in the list.
969 * 1 : header_list = pointer to list
970 * 2 : header_name = string with name of header to look for.
971 * Trailing colon required, capitalization
974 * Returns : NULL if not found, else value of header
976 *********************************************************************/
977 char *get_header_value(const struct list *header_list, const char *header_name)
979 struct list_entry *cur_entry;
985 length = strlen(header_name);
987 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
991 if (!strncmpic(cur_entry->str, header_name, length))
994 * Found: return pointer to start of value
996 ret = cur_entry->str + length;
997 while (*ret && ijb_isspace(*ret)) ret++;
1011 /*********************************************************************
1013 * Function : scan_headers
1015 * Description : Scans headers, applies tags and updates action bits.
1018 * 1 : csp = Current client state (buffers, headers, etc...)
1020 * Returns : JB_ERR_OK
1022 *********************************************************************/
1023 static jb_err scan_headers(struct client_state *csp)
1025 struct list_entry *h; /* Header */
1026 jb_err err = JB_ERR_OK;
1028 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1030 /* Header crunch()ed in previous run? -> ignore */
1031 if (h->str == NULL) continue;
1032 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1033 err = header_tagger(csp, h->str);
1040 /*********************************************************************
1044 * Description : add, delete or modify lines in the HTTP header streams.
1045 * On entry, it receives a linked list of headers space
1046 * that was allocated dynamically (both the list nodes
1047 * and the header contents).
1049 * As a side effect it frees the space used by the original
1053 * 1 : csp = Current client state (buffers, headers, etc...)
1054 * 2 : filter_server_headers = Boolean to switch between
1055 * server and header filtering.
1057 * Returns : JB_ERR_OK in case off success, or
1058 * JB_ERR_MEMORY on out-of-memory error.
1060 *********************************************************************/
1061 jb_err sed(struct client_state *csp, int filter_server_headers)
1063 /* XXX: use more descriptive names. */
1064 struct list_entry *p;
1065 const struct parsers *v;
1066 const add_header_func_ptr *f;
1067 jb_err err = JB_ERR_OK;
1069 if (filter_server_headers)
1071 v = server_patterns;
1072 f = add_server_headers;
1076 v = client_patterns;
1077 f = add_client_headers;
1082 while ((err == JB_ERR_OK) && (v->str != NULL))
1084 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1086 /* Header crunch()ed in previous run? -> ignore */
1087 if (p->str == NULL) continue;
1089 /* Does the current parser handle this header? */
1090 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1091 (v->len == CHECK_EVERY_HEADER_REMAINING))
1093 err = v->parser(csp, &(p->str));
1099 /* place additional headers on the csp->headers list */
1100 while ((err == JB_ERR_OK) && (*f))
1110 /*********************************************************************
1112 * Function : update_server_headers
1114 * Description : Updates server headers after the body has been modified.
1117 * 1 : csp = Current client state (buffers, headers, etc...)
1119 * Returns : JB_ERR_OK in case off success, or
1120 * JB_ERR_MEMORY on out-of-memory error.
1122 *********************************************************************/
1123 jb_err update_server_headers(struct client_state *csp)
1125 jb_err err = JB_ERR_OK;
1127 static const struct parsers server_patterns_light[] = {
1128 { "Content-Length:", 15, server_adjust_content_length },
1129 { "Transfer-Encoding:", 18, server_transfer_coding },
1131 { "Content-Encoding:", 17, server_content_encoding },
1132 #endif /* def FEATURE_ZLIB */
1136 if (strncmpic(csp->http->cmd, "HEAD", 4))
1138 const struct parsers *v;
1139 struct list_entry *p;
1141 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1143 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1145 /* Header crunch()ed in previous run? -> ignore */
1146 if (p->str == NULL) continue;
1148 /* Does the current parser handle this header? */
1149 if (strncmpic(p->str, v->str, v->len) == 0)
1151 err = v->parser(csp, (char **)&(p->str));
1161 /*********************************************************************
1163 * Function : header_tagger
1165 * Description : Executes all text substitutions from applying
1166 * tag actions and saves the result as tag.
1168 * XXX: Shares enough code with filter_header() and
1169 * pcrs_filter_response() to warrant some helper functions.
1172 * 1 : csp = Current client state (buffers, headers, etc...)
1173 * 2 : header = Header that is used as tagger input
1175 * Returns : JB_ERR_OK on success and always succeeds
1177 *********************************************************************/
1178 static jb_err header_tagger(struct client_state *csp, char *header)
1180 int wanted_filter_type;
1181 int multi_action_index;
1185 struct file_list *fl;
1186 struct re_filterfile_spec *b;
1187 struct list_entry *tag_name;
1189 int found_filters = 0;
1190 const size_t header_length = strlen(header);
1192 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1194 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1195 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1199 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1200 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1203 /* Check if there are any filters */
1204 for (i = 0; i < MAX_AF_FILES; i++)
1217 if (0 == found_filters)
1219 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1220 "tagging enabled, but no taggers available.");
1224 for (i = 0; i < MAX_AF_FILES; i++)
1227 if ((NULL == fl) || (NULL == fl->f))
1230 * Either there are no filter files
1231 * left, or this filter file just
1232 * contains no valid filters.
1234 * Continue to be sure we don't miss
1235 * valid filter files that are chained
1236 * after empty or invalid ones.
1241 /* For all filters, */
1242 for (b = fl->f; b; b = b->next)
1244 if (b->type != wanted_filter_type)
1246 /* skip the ones we don't care about, */
1249 /* leaving only taggers that could apply, of which we use the ones, */
1250 for (tag_name = csp->action->multi[multi_action_index]->first;
1251 NULL != tag_name; tag_name = tag_name->next)
1253 /* that do apply, and */
1254 if (strcmp(b->name, tag_name->str) == 0)
1256 char *modified_tag = NULL;
1258 size_t size = header_length;
1259 pcrs_job *joblist = b->joblist;
1261 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1263 if (NULL == joblist)
1265 log_error(LOG_LEVEL_RE_FILTER,
1266 "Tagger %s has empty joblist. Nothing to do.", b->name);
1270 /* execute their pcrs_joblist on the header. */
1271 for (job = joblist; NULL != job; job = job->next)
1273 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1277 /* Success, continue with the modified version. */
1286 /* Tagger doesn't match */
1289 /* Regex failure, log it but continue anyway. */
1290 assert(NULL != header);
1291 log_error(LOG_LEVEL_ERROR,
1292 "Problems with tagger \'%s\' and header \'%s\': %s",
1293 b->name, *header, pcrs_strerror(hits));
1295 freez(modified_tag);
1299 if (b->dynamic) pcrs_free_joblist(joblist);
1301 /* If this tagger matched */
1307 * There is to technical limitation which makes
1308 * it impossible to use empty tags, but I assume
1309 * no one would do it intentionally.
1312 log_error(LOG_LEVEL_INFO,
1313 "Tagger \'%s\' created an empty tag. Ignored.",
1318 if (!list_contains_item(csp->tags, tag))
1320 if (JB_ERR_OK != enlist(csp->tags, tag))
1322 log_error(LOG_LEVEL_ERROR,
1323 "Insufficient memory to add tag \'%s\', "
1324 "based on tagger \'%s\' and header \'%s\'",
1325 tag, b->name, *header);
1329 char *action_message;
1331 * update the action bits right away, to make
1332 * tagging based on tags set by earlier taggers
1333 * of the same kind possible.
1335 if (update_action_bits_for_tag(csp, tag))
1337 action_message = "Action bits updated accordingly.";
1341 action_message = "No action bits update necessary.";
1344 log_error(LOG_LEVEL_HEADER,
1345 "Tagger \'%s\' added tag \'%s\'. %s",
1346 b->name, tag, action_message);
1351 /* XXX: Is this log-worthy? */
1352 log_error(LOG_LEVEL_HEADER,
1353 "Tagger \'%s\' didn't add tag \'%s\'. "
1354 "Tag already present", b->name, tag);
1357 } /* if the tagger matched */
1358 } /* if the tagger applies */
1359 } /* for every tagger that could apply */
1360 } /* for all filters */
1361 } /* for all filter files */
1366 /* here begins the family of parser functions that reformat header lines */
1368 /*********************************************************************
1370 * Function : filter_header
1372 * Description : Executes all text substitutions from all applying
1373 * +(server|client)-header-filter actions on the header.
1374 * Most of the code was copied from pcrs_filter_response,
1375 * including the rather short variable names
1378 * 1 : csp = Current client state (buffers, headers, etc...)
1379 * 2 : header = On input, pointer to header to modify.
1380 * On output, pointer to the modified header, or NULL
1381 * to remove the header. This function frees the
1382 * original string if necessary.
1384 * Returns : JB_ERR_OK on success and always succeeds
1386 *********************************************************************/
1387 static jb_err filter_header(struct client_state *csp, char **header)
1391 size_t size = strlen(*header);
1393 char *newheader = NULL;
1396 struct file_list *fl;
1397 struct re_filterfile_spec *b;
1398 struct list_entry *filtername;
1400 int i, found_filters = 0;
1401 int wanted_filter_type;
1402 int multi_action_index;
1404 if (csp->flags & CSP_FLAG_NO_FILTERING)
1409 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1411 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1412 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1416 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1417 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1421 * Need to check the set of re_filterfiles...
1423 for (i = 0; i < MAX_AF_FILES; i++)
1436 if (0 == found_filters)
1438 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1439 "header filtering enabled, but no matching filters available.");
1443 for (i = 0; i < MAX_AF_FILES; i++)
1446 if ((NULL == fl) || (NULL == fl->f))
1449 * Either there are no filter files
1450 * left, or this filter file just
1451 * contains no valid filters.
1453 * Continue to be sure we don't miss
1454 * valid filter files that are chained
1455 * after empty or invalid ones.
1460 * For all applying +filter actions, look if a filter by that
1461 * name exists and if yes, execute its pcrs_joblist on the
1464 for (b = fl->f; b; b = b->next)
1466 if (b->type != wanted_filter_type)
1468 /* Skip other filter types */
1472 for (filtername = csp->action->multi[multi_action_index]->first;
1473 filtername ; filtername = filtername->next)
1475 if (strcmp(b->name, filtername->str) == 0)
1477 int current_hits = 0;
1478 pcrs_job *joblist = b->joblist;
1480 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1482 if (NULL == joblist)
1484 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1488 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1489 *header, size, b->name);
1491 /* Apply all jobs from the joblist */
1492 for (job = joblist; NULL != job; job = job->next)
1494 matches = pcrs_execute(job, *header, size, &newheader, &size);
1497 current_hits += matches;
1498 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1500 *header = newheader;
1502 else if ( 0 == matches )
1504 /* Filter doesn't change header */
1510 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1511 *header, b->name, pcrs_strerror(matches));
1512 if (newheader != NULL)
1514 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1520 if (b->dynamic) pcrs_free_joblist(joblist);
1522 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1523 hits += current_hits;
1530 * Additionally checking for hits is important because if
1531 * the continue hack is triggered, server headers can
1532 * arrive empty to separate multiple heads from each other.
1534 if ((0 == size) && hits)
1536 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1544 /*********************************************************************
1546 * Function : server_connection
1548 * Description : Makes sure a proper "Connection:" header is
1549 * set and signals connection_header_adder to
1553 * 1 : csp = Current client state (buffers, headers, etc...)
1554 * 2 : header = On input, pointer to header to modify.
1555 * On output, pointer to the modified header, or NULL
1556 * to remove the header. This function frees the
1557 * original string if necessary.
1559 * Returns : JB_ERR_OK on success, or
1560 * JB_ERR_MEMORY on out-of-memory error.
1562 *********************************************************************/
1563 static jb_err server_connection(struct client_state *csp, char **header)
1565 /* Do we have a 'Connection: close' header? */
1566 if (strcmpic(*header, "Connection: close"))
1568 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1569 if ((csp->config->feature_flags &
1570 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1571 && !strcmpic(*header, "Connection: keep-alive"))
1573 /* Remember to keep the connection alive. */
1574 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1576 log_error(LOG_LEVEL_HEADER,
1577 "Keeping the server header '%s' around.", *header);
1579 char *old_header = *header;
1581 *header = strdup("Connection: close");
1584 return JB_ERR_MEMORY;
1586 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1588 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1591 /* Signal server_connection_adder() to return early. */
1592 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1598 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1599 /*********************************************************************
1601 * Function : server_keep_alive
1603 * Description : Stores the servers keep alive timeout.
1606 * 1 : csp = Current client state (buffers, headers, etc...)
1607 * 2 : header = On input, pointer to header to modify.
1608 * On output, pointer to the modified header, or NULL
1609 * to remove the header. This function frees the
1610 * original string if necessary.
1612 * Returns : JB_ERR_OK.
1614 *********************************************************************/
1615 static jb_err server_keep_alive(struct client_state *csp, char **header)
1617 unsigned int keep_alive_timeout;
1618 const char *timeout_position = strstr(*header, "timeout=");
1620 if ((NULL != timeout_position)
1621 && (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1623 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1627 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1629 log_error(LOG_LEVEL_HEADER,
1630 "Reducing keep-alive timeout from %u to %u.",
1631 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1632 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1636 /* XXX: Is this log worthy? */
1637 log_error(LOG_LEVEL_HEADER,
1638 "Server keep-alive timeout is %u. Sticking with %u.",
1639 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1645 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1649 /*********************************************************************
1651 * Function : client_connection
1653 * Description : Makes sure a proper "Connection:" header is
1654 * set and signals connection_header_adder
1658 * 1 : csp = Current client state (buffers, headers, etc...)
1659 * 2 : header = On input, pointer to header to modify.
1660 * On output, pointer to the modified header, or NULL
1661 * to remove the header. This function frees the
1662 * original string if necessary.
1664 * Returns : JB_ERR_OK on success, or
1665 * JB_ERR_MEMORY on out-of-memory error.
1667 *********************************************************************/
1668 static jb_err client_connection(struct client_state *csp, char **header)
1670 const char *wanted_header = get_appropiate_connection_header(csp);
1672 if (strcmpic(*header, wanted_header))
1674 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1675 log_error(LOG_LEVEL_HEADER,
1676 "Keeping the client header '%s' around. "
1677 "The connection will not be kept alive.",
1680 char *old_header = *header;
1682 *header = strdup(wanted_header);
1685 return JB_ERR_MEMORY;
1687 log_error(LOG_LEVEL_HEADER,
1688 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1690 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1692 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1695 log_error(LOG_LEVEL_HEADER,
1696 "Keeping the client header '%s' around. "
1697 "The server connection will be kept alive if possible.",
1699 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1701 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1703 /* Signal client_connection_adder() to return early. */
1704 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1710 /*********************************************************************
1712 * Function : crumble
1714 * Description : This is called if a header matches a pattern to "crunch"
1717 * 1 : csp = Current client state (buffers, headers, etc...)
1718 * 2 : header = On input, pointer to header to modify.
1719 * On output, pointer to the modified header, or NULL
1720 * to remove the header. This function frees the
1721 * original string if necessary.
1723 * Returns : JB_ERR_OK on success, or
1724 * JB_ERR_MEMORY on out-of-memory error.
1726 *********************************************************************/
1727 static jb_err crumble(struct client_state *csp, char **header)
1730 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1736 /*********************************************************************
1738 * Function : crunch_server_header
1740 * Description : Crunch server header if it matches a string supplied by the
1741 * user. Called from `sed'.
1744 * 1 : csp = Current client state (buffers, headers, etc...)
1745 * 2 : header = On input, pointer to header to modify.
1746 * On output, pointer to the modified header, or NULL
1747 * to remove the header. This function frees the
1748 * original string if necessary.
1750 * Returns : JB_ERR_OK on success and always succeeds
1752 *********************************************************************/
1753 static jb_err crunch_server_header(struct client_state *csp, char **header)
1755 const char *crunch_pattern;
1757 /* Do we feel like crunching? */
1758 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1760 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1762 /* Is the current header the lucky one? */
1763 if (strstr(*header, crunch_pattern))
1765 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1774 /*********************************************************************
1776 * Function : server_content_type
1778 * Description : Set the content-type for filterable types (text/.*,
1779 * .*xml.*, javascript and image/gif) unless filtering has been
1780 * forbidden (CT_TABOO) while parsing earlier headers.
1781 * NOTE: Since text/plain is commonly used by web servers
1782 * for files whose correct type is unknown, we don't
1783 * set CT_TEXT for it.
1786 * 1 : csp = Current client state (buffers, headers, etc...)
1787 * 2 : header = On input, pointer to header to modify.
1788 * On output, pointer to the modified header, or NULL
1789 * to remove the header. This function frees the
1790 * original string if necessary.
1792 * Returns : JB_ERR_OK on success, or
1793 * JB_ERR_MEMORY on out-of-memory error.
1795 *********************************************************************/
1796 static jb_err server_content_type(struct client_state *csp, char **header)
1798 /* Remove header if it isn't the first Content-Type header */
1799 if ((csp->content_type & CT_DECLARED))
1802 * Another, slightly slower, way to see if
1803 * we already parsed another Content-Type header.
1805 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1807 log_error(LOG_LEVEL_ERROR,
1808 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1816 * Signal that the Content-Type has been set.
1818 csp->content_type |= CT_DECLARED;
1820 if (!(csp->content_type & CT_TABOO))
1823 * XXX: The assumption that text/plain is a sign of
1824 * binary data seems to be somewhat unreasonable nowadays
1825 * and should be dropped after 3.0.8 is out.
1827 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
1828 || strstr(*header, "xml")
1829 || strstr(*header, "application/x-javascript"))
1831 csp->content_type |= CT_TEXT;
1833 else if (strstr(*header, "image/gif"))
1835 csp->content_type |= CT_GIF;
1840 * Are we messing with the content type?
1842 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1845 * Make sure the user doesn't accidently
1846 * change the content type of binary documents.
1848 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
1851 *header = strdup("Content-Type: ");
1852 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1856 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1857 return JB_ERR_MEMORY;
1859 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1863 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
1864 "It doesn't look like a content type that should be filtered. "
1865 "Enable force-text-mode if you know what you're doing.", *header);
1873 /*********************************************************************
1875 * Function : server_transfer_coding
1877 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1878 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1879 * - Remove header if body was chunked but has been
1880 * de-chunked for filtering.
1883 * 1 : csp = Current client state (buffers, headers, etc...)
1884 * 2 : header = On input, pointer to header to modify.
1885 * On output, pointer to the modified header, or NULL
1886 * to remove the header. This function frees the
1887 * original string if necessary.
1889 * Returns : JB_ERR_OK on success, or
1890 * JB_ERR_MEMORY on out-of-memory error.
1892 *********************************************************************/
1893 static jb_err server_transfer_coding(struct client_state *csp, char **header)
1896 * Turn off pcrs and gif filtering if body compressed
1898 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1902 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1904 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1905 csp->http->cmd, *header);
1906 #endif /* def FEATURE_ZLIB */
1907 csp->content_type = CT_TABOO;
1911 * Raise flag if body chunked
1913 if (strstr(*header, "chunked"))
1915 csp->flags |= CSP_FLAG_CHUNKED;
1918 * If the body was modified, it has been de-chunked first
1919 * and the header must be removed.
1921 * FIXME: If there is more than one transfer encoding,
1922 * only the "chunked" part should be removed here.
1924 if (csp->flags & CSP_FLAG_MODIFIED)
1926 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1935 /*********************************************************************
1937 * Function : server_content_encoding
1939 * Description : This function is run twice for each request,
1940 * unless FEATURE_ZLIB and filtering are disabled.
1942 * The first run is used to check if the content
1943 * is compressed, if FEATURE_ZLIB is disabled
1944 * filtering is then disabled as well, if FEATURE_ZLIB
1945 * is enabled the content is marked for decompression.
1947 * The second run is used to remove the Content-Encoding
1948 * header if the decompression was successful.
1951 * 1 : csp = Current client state (buffers, headers, etc...)
1952 * 2 : header = On input, pointer to header to modify.
1953 * On output, pointer to the modified header, or NULL
1954 * to remove the header. This function frees the
1955 * original string if necessary.
1957 * Returns : JB_ERR_OK on success, or
1958 * JB_ERR_MEMORY on out-of-memory error.
1960 *********************************************************************/
1961 static jb_err server_content_encoding(struct client_state *csp, char **header)
1964 if ((csp->flags & CSP_FLAG_MODIFIED)
1965 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1968 * We successfully decompressed the content,
1969 * and have to clean the header now, so the
1970 * client no longer expects compressed data..
1972 * XXX: There is a difference between cleaning
1973 * and removing it completely.
1975 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1978 else if (strstr(*header, "gzip"))
1980 /* Mark for gzip decompression */
1981 csp->content_type |= CT_GZIP;
1983 else if (strstr(*header, "deflate"))
1985 /* Mark for zlib decompression */
1986 csp->content_type |= CT_DEFLATE;
1988 else if (strstr(*header, "compress"))
1991 * We can't decompress this; therefore we can't filter
1994 csp->content_type |= CT_TABOO;
1996 #else /* !defined(FEATURE_ZLIB) */
1997 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2000 * Body is compressed, turn off pcrs and gif filtering.
2002 csp->content_type |= CT_TABOO;
2005 * Log a warning if the user expects the content to be filtered.
2007 if ((csp->rlist != NULL) &&
2008 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2010 log_error(LOG_LEVEL_INFO,
2011 "Compressed content detected, content filtering disabled. "
2012 "Consider recompiling Privoxy with zlib support or "
2013 "enable the prevent-compression action.");
2016 #endif /* defined(FEATURE_ZLIB) */
2023 /*********************************************************************
2025 * Function : server_adjust_content_length
2027 * Description : Adjust Content-Length header if we modified
2031 * 1 : csp = Current client state (buffers, headers, etc...)
2032 * 2 : header = On input, pointer to header to modify.
2033 * On output, pointer to the modified header, or NULL
2034 * to remove the header. This function frees the
2035 * original string if necessary.
2037 * Returns : JB_ERR_OK on success, or
2038 * JB_ERR_MEMORY on out-of-memory error.
2040 *********************************************************************/
2041 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2043 const size_t max_header_length = 80;
2045 /* Regenerate header if the content was modified. */
2046 if (csp->flags & CSP_FLAG_MODIFIED)
2049 *header = (char *) zalloc(max_header_length);
2050 if (*header == NULL)
2052 return JB_ERR_MEMORY;
2055 snprintf(*header, max_header_length, "Content-Length: %d",
2056 (int)csp->content_length);
2057 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2058 (int)csp->content_length);
2065 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2066 /*********************************************************************
2068 * Function : server_save_content_length
2070 * Description : Save the Content-Length sent by the server.
2073 * 1 : csp = Current client state (buffers, headers, etc...)
2074 * 2 : header = On input, pointer to header to modify.
2075 * On output, pointer to the modified header, or NULL
2076 * to remove the header. This function frees the
2077 * original string if necessary.
2079 * Returns : JB_ERR_OK on success, or
2080 * JB_ERR_MEMORY on out-of-memory error.
2082 *********************************************************************/
2083 static jb_err server_save_content_length(struct client_state *csp, char **header)
2085 unsigned long long content_length = 0;
2087 assert(*(*header+14) == ':');
2089 if (1 != sscanf(*header+14, ": %llu", &content_length))
2091 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2096 csp->expected_content_length = content_length;
2097 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2102 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2105 /*********************************************************************
2107 * Function : server_content_md5
2109 * Description : Crumble any Content-MD5 headers if the document was
2110 * modified. FIXME: Should we re-compute instead?
2113 * 1 : csp = Current client state (buffers, headers, etc...)
2114 * 2 : header = On input, pointer to header to modify.
2115 * On output, pointer to the modified header, or NULL
2116 * to remove the header. This function frees the
2117 * original string if necessary.
2119 * Returns : JB_ERR_OK on success, or
2120 * JB_ERR_MEMORY on out-of-memory error.
2122 *********************************************************************/
2123 static jb_err server_content_md5(struct client_state *csp, char **header)
2125 if (csp->flags & CSP_FLAG_MODIFIED)
2127 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2135 /*********************************************************************
2137 * Function : server_content_disposition
2139 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2140 * Called from `sed'.
2143 * 1 : csp = Current client state (buffers, headers, etc...)
2144 * 2 : header = On input, pointer to header to modify.
2145 * On output, pointer to the modified header, or NULL
2146 * to remove the header. This function frees the
2147 * original string if necessary.
2149 * Returns : JB_ERR_OK on success, or
2150 * JB_ERR_MEMORY on out-of-memory error.
2152 *********************************************************************/
2153 static jb_err server_content_disposition(struct client_state *csp, char **header)
2158 * Are we messing with the Content-Disposition header?
2160 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2166 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2168 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2171 * Blocking content-disposition header
2173 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2180 * Replacing Content-Disposition header
2183 *header = strdup("Content-Disposition: ");
2184 string_append(header, newval);
2186 if (*header != NULL)
2188 log_error(LOG_LEVEL_HEADER,
2189 "Content-Disposition header crunched and replaced with: %s", *header);
2192 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2196 /*********************************************************************
2198 * Function : server_last_modified
2200 * Description : Changes Last-Modified header to the actual date
2201 * to help hide-if-modified-since.
2202 * Called from `sed'.
2205 * 1 : csp = Current client state (buffers, headers, etc...)
2206 * 2 : header = On input, pointer to header to modify.
2207 * On output, pointer to the modified header, or NULL
2208 * to remove the header. This function frees the
2209 * original string if necessary.
2211 * Returns : JB_ERR_OK on success, or
2212 * JB_ERR_MEMORY on out-of-memory error.
2214 *********************************************************************/
2215 static jb_err server_last_modified(struct client_state *csp, char **header)
2218 char buf[BUFFER_SIZE];
2221 #ifdef HAVE_GMTIME_R
2224 struct tm *timeptr = NULL;
2225 time_t now, last_modified;
2227 long int days, hours, minutes, seconds;
2230 * Are we messing with the Last-Modified header?
2232 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2238 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2240 if (0 == strcmpic(newval, "block") )
2243 * Blocking Last-Modified header. Useless but why not.
2245 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2249 else if (0 == strcmpic(newval, "reset-to-request-time"))
2252 * Setting Last-Modified Header to now.
2254 get_http_time(0, buf, sizeof(buf));
2256 *header = strdup("Last-Modified: ");
2257 string_append(header, buf);
2259 if (*header == NULL)
2261 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2265 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2268 else if (0 == strcmpic(newval, "randomize"))
2270 const char *header_time = *header + sizeof("Last-Modified:");
2272 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2274 #ifdef HAVE_GMTIME_R
2275 timeptr = gmtime_r(&now, &gmt);
2276 #elif FEATURE_PTHREAD
2277 privoxy_mutex_lock(&gmtime_mutex);
2278 timeptr = gmtime(&now);
2279 privoxy_mutex_unlock(&gmtime_mutex);
2281 timeptr = gmtime(&now);
2283 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2285 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2290 rtime = (long int)difftime(now, last_modified);
2299 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2301 rtime = pick_from_range(rtime);
2302 if (negative) rtime *= -1;
2303 last_modified += rtime;
2304 #ifdef HAVE_GMTIME_R
2305 timeptr = gmtime_r(&last_modified, &gmt);
2306 #elif FEATURE_PTHREAD
2307 privoxy_mutex_lock(&gmtime_mutex);
2308 timeptr = gmtime(&last_modified);
2309 privoxy_mutex_unlock(&gmtime_mutex);
2311 timeptr = gmtime(&last_modified);
2313 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2315 *header = strdup("Last-Modified: ");
2316 string_append(header, newheader);
2318 if (*header == NULL)
2320 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2321 return JB_ERR_MEMORY;
2324 days = rtime / (3600 * 24);
2325 hours = rtime / 3600 % 24;
2326 minutes = rtime / 60 % 60;
2327 seconds = rtime % 60;
2329 log_error(LOG_LEVEL_HEADER,
2330 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2331 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2332 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2336 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2345 /*********************************************************************
2347 * Function : client_accept_encoding
2349 * Description : Rewrite the client's Accept-Encoding header so that
2350 * if doesn't allow compression, if the action applies.
2351 * Note: For HTTP/1.0 the absence of the header is enough.
2354 * 1 : csp = Current client state (buffers, headers, etc...)
2355 * 2 : header = On input, pointer to header to modify.
2356 * On output, pointer to the modified header, or NULL
2357 * to remove the header. This function frees the
2358 * original string if necessary.
2360 * Returns : JB_ERR_OK on success, or
2361 * JB_ERR_MEMORY on out-of-memory error.
2363 *********************************************************************/
2364 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2366 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2368 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2372 /* Temporarily disable the correct behaviour to
2373 * work around a PHP bug.
2375 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2377 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2378 * if (*header == NULL)
2380 * return JB_ERR_MEMORY;
2391 /*********************************************************************
2393 * Function : client_te
2395 * Description : Rewrite the client's TE header so that
2396 * if doesn't allow compression, if the action applies.
2399 * 1 : csp = Current client state (buffers, headers, etc...)
2400 * 2 : header = On input, pointer to header to modify.
2401 * On output, pointer to the modified header, or NULL
2402 * to remove the header. This function frees the
2403 * original string if necessary.
2405 * Returns : JB_ERR_OK on success, or
2406 * JB_ERR_MEMORY on out-of-memory error.
2408 *********************************************************************/
2409 static jb_err client_te(struct client_state *csp, char **header)
2411 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2414 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2421 /*********************************************************************
2423 * Function : client_referrer
2425 * Description : Handle the "referer" config setting properly.
2426 * Called from `sed'.
2429 * 1 : csp = Current client state (buffers, headers, etc...)
2430 * 2 : header = On input, pointer to header to modify.
2431 * On output, pointer to the modified header, or NULL
2432 * to remove the header. This function frees the
2433 * original string if necessary.
2435 * Returns : JB_ERR_OK on success, or
2436 * JB_ERR_MEMORY on out-of-memory error.
2438 *********************************************************************/
2439 static jb_err client_referrer(struct client_state *csp, char **header)
2441 const char *parameter;
2442 /* booleans for parameters we have to check multiple times */
2443 int parameter_conditional_block;
2444 int parameter_conditional_forge;
2446 #ifdef FEATURE_FORCE_LOAD
2448 * Since the referrer can include the prefix even
2449 * if the request itself is non-forced, we must
2450 * clean it unconditionally.
2452 * XXX: strclean is too broad
2454 strclean(*header, FORCE_PREFIX);
2455 #endif /* def FEATURE_FORCE_LOAD */
2457 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2459 /* Nothing left to do */
2463 parameter = csp->action->string[ACTION_STRING_REFERER];
2464 assert(parameter != NULL);
2465 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2466 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2468 if (!parameter_conditional_block && !parameter_conditional_forge)
2471 * As conditional-block and conditional-forge are the only
2472 * parameters that rely on the original referrer, we can
2473 * remove it now for all the others.
2478 if (0 == strcmpic(parameter, "block"))
2480 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2483 else if (parameter_conditional_block || parameter_conditional_forge)
2485 return handle_conditional_hide_referrer_parameter(header,
2486 csp->http->hostport, parameter_conditional_block);
2488 else if (0 == strcmpic(parameter, "forge"))
2490 return create_forged_referrer(header, csp->http->hostport);
2494 /* interpret parameter as user-supplied referer to fake */
2495 return create_fake_referrer(header, parameter);
2500 /*********************************************************************
2502 * Function : client_accept_language
2504 * Description : Handle the "Accept-Language" config setting properly.
2505 * Called from `sed'.
2508 * 1 : csp = Current client state (buffers, headers, etc...)
2509 * 2 : header = On input, pointer to header to modify.
2510 * On output, pointer to the modified header, or NULL
2511 * to remove the header. This function frees the
2512 * original string if necessary.
2514 * Returns : JB_ERR_OK on success, or
2515 * JB_ERR_MEMORY on out-of-memory error.
2517 *********************************************************************/
2518 static jb_err client_accept_language(struct client_state *csp, char **header)
2523 * Are we messing with the Accept-Language?
2525 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2527 /*I don't think so*/
2531 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2533 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2536 * Blocking Accept-Language header
2538 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2545 * Replacing Accept-Language header
2548 *header = strdup("Accept-Language: ");
2549 string_append(header, newval);
2551 if (*header == NULL)
2553 log_error(LOG_LEVEL_ERROR,
2554 "Insufficient memory. Accept-Language header crunched without replacement.");
2558 log_error(LOG_LEVEL_HEADER,
2559 "Accept-Language header crunched and replaced with: %s", *header);
2562 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2566 /*********************************************************************
2568 * Function : crunch_client_header
2570 * Description : Crunch client header if it matches a string supplied by the
2571 * user. Called from `sed'.
2574 * 1 : csp = Current client state (buffers, headers, etc...)
2575 * 2 : header = On input, pointer to header to modify.
2576 * On output, pointer to the modified header, or NULL
2577 * to remove the header. This function frees the
2578 * original string if necessary.
2580 * Returns : JB_ERR_OK on success and always succeeds
2582 *********************************************************************/
2583 static jb_err crunch_client_header(struct client_state *csp, char **header)
2585 const char *crunch_pattern;
2587 /* Do we feel like crunching? */
2588 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2590 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2592 /* Is the current header the lucky one? */
2593 if (strstr(*header, crunch_pattern))
2595 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2603 /*********************************************************************
2605 * Function : client_uagent
2607 * Description : Handle the "user-agent" config setting properly
2608 * and remember its original value to enable browser
2609 * bug workarounds. Called from `sed'.
2612 * 1 : csp = Current client state (buffers, headers, etc...)
2613 * 2 : header = On input, pointer to header to modify.
2614 * On output, pointer to the modified header, or NULL
2615 * to remove the header. This function frees the
2616 * original string if necessary.
2618 * Returns : JB_ERR_OK on success, or
2619 * JB_ERR_MEMORY on out-of-memory error.
2621 *********************************************************************/
2622 static jb_err client_uagent(struct client_state *csp, char **header)
2626 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2631 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2638 *header = strdup("User-Agent: ");
2639 string_append(header, newval);
2641 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2643 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2647 /*********************************************************************
2649 * Function : client_ua
2651 * Description : Handle "ua-" headers properly. Called from `sed'.
2654 * 1 : csp = Current client state (buffers, headers, etc...)
2655 * 2 : header = On input, pointer to header to modify.
2656 * On output, pointer to the modified header, or NULL
2657 * to remove the header. This function frees the
2658 * original string if necessary.
2660 * Returns : JB_ERR_OK on success, or
2661 * JB_ERR_MEMORY on out-of-memory error.
2663 *********************************************************************/
2664 static jb_err client_ua(struct client_state *csp, char **header)
2666 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2668 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2676 /*********************************************************************
2678 * Function : client_from
2680 * Description : Handle the "from" config setting properly.
2681 * Called from `sed'.
2684 * 1 : csp = Current client state (buffers, headers, etc...)
2685 * 2 : header = On input, pointer to header to modify.
2686 * On output, pointer to the modified header, or NULL
2687 * to remove the header. This function frees the
2688 * original string if necessary.
2690 * Returns : JB_ERR_OK on success, or
2691 * JB_ERR_MEMORY on out-of-memory error.
2693 *********************************************************************/
2694 static jb_err client_from(struct client_state *csp, char **header)
2698 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2705 newval = csp->action->string[ACTION_STRING_FROM];
2708 * Are we blocking the e-mail address?
2710 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2712 log_error(LOG_LEVEL_HEADER, "crunched From!");
2716 log_error(LOG_LEVEL_HEADER, " modified");
2718 *header = strdup("From: ");
2719 string_append(header, newval);
2721 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2725 /*********************************************************************
2727 * Function : client_send_cookie
2729 * Description : Crunches the "cookie" header if necessary.
2730 * Called from `sed'.
2732 * XXX: Stupid name, doesn't send squat.
2735 * 1 : csp = Current client state (buffers, headers, etc...)
2736 * 2 : header = On input, pointer to header to modify.
2737 * On output, pointer to the modified header, or NULL
2738 * to remove the header. This function frees the
2739 * original string if necessary.
2741 * Returns : JB_ERR_OK on success, or
2742 * JB_ERR_MEMORY on out-of-memory error.
2744 *********************************************************************/
2745 static jb_err client_send_cookie(struct client_state *csp, char **header)
2747 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2749 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2757 /*********************************************************************
2759 * Function : client_x_forwarded
2761 * Description : Handle the "x-forwarded-for" config setting properly,
2762 * also used in the add_client_headers list. Called from `sed'.
2765 * 1 : csp = Current client state (buffers, headers, etc...)
2766 * 2 : header = On input, pointer to header to modify.
2767 * On output, pointer to the modified header, or NULL
2768 * to remove the header. This function frees the
2769 * original string if necessary.
2771 * Returns : JB_ERR_OK on success, or
2772 * JB_ERR_MEMORY on out-of-memory error.
2774 *********************************************************************/
2775 jb_err client_x_forwarded(struct client_state *csp, char **header)
2777 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2779 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2781 if (0 == strcmpic(parameter, "block"))
2784 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2786 else if (0 == strcmpic(parameter, "add"))
2788 string_append(header, ", ");
2789 string_append(header, csp->ip_addr_str);
2791 if (*header == NULL)
2793 return JB_ERR_MEMORY;
2795 log_error(LOG_LEVEL_HEADER,
2796 "Appended client IP address to %s", *header);
2797 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
2801 log_error(LOG_LEVEL_FATAL,
2802 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
2810 /*********************************************************************
2812 * Function : client_max_forwards
2814 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2815 * from the value of the Max-Forwards header field.
2818 * 1 : csp = Current client state (buffers, headers, etc...)
2819 * 2 : header = On input, pointer to header to modify.
2820 * On output, pointer to the modified header, or NULL
2821 * to remove the header. This function frees the
2822 * original string if necessary.
2824 * Returns : JB_ERR_OK on success, or
2825 * JB_ERR_MEMORY on out-of-memory error.
2827 *********************************************************************/
2828 static jb_err client_max_forwards(struct client_state *csp, char **header)
2832 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2833 (0 == strcmpic(csp->http->gpc, "options")))
2835 assert(*(*header+12) == ':');
2836 if (1 == sscanf(*header+12, ": %d", &max_forwards))
2838 if (max_forwards > 0)
2840 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
2841 log_error(LOG_LEVEL_HEADER,
2842 "Max-Forwards value for %s request reduced to %d.",
2843 csp->http->gpc, max_forwards);
2845 else if (max_forwards < 0)
2847 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2853 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2862 /*********************************************************************
2864 * Function : client_host
2866 * Description : If the request URI did not contain host and
2867 * port information, parse and evaluate the Host
2870 * Also, kill ill-formed HOST: headers as sent by
2871 * Apple's iTunes software when used with a proxy.
2874 * 1 : csp = Current client state (buffers, headers, etc...)
2875 * 2 : header = On input, pointer to header to modify.
2876 * On output, pointer to the modified header, or NULL
2877 * to remove the header. This function frees the
2878 * original string if necessary.
2880 * Returns : JB_ERR_OK on success, or
2881 * JB_ERR_MEMORY on out-of-memory error.
2883 *********************************************************************/
2884 static jb_err client_host(struct client_state *csp, char **header)
2889 * If the header field name is all upper-case, chances are that it's
2890 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2891 * not a problem -- they are regenerated later.
2893 if ((*header)[1] == 'O')
2895 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2900 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2901 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2904 if (NULL == (p = strdup((*header)+6)))
2906 return JB_ERR_MEMORY;
2909 if (NULL == (q = strdup(p)))
2912 return JB_ERR_MEMORY;
2915 freez(csp->http->hostport);
2916 csp->http->hostport = p;
2917 freez(csp->http->host);
2918 csp->http->host = q;
2919 q = strchr(csp->http->host, ':');
2922 /* Terminate hostname and evaluate port string */
2924 csp->http->port = atoi(q);
2928 csp->http->port = csp->http->ssl ? 443 : 80;
2931 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2932 csp->http->hostport, csp->http->host, csp->http->port);
2935 /* Signal client_host_adder() to return right away */
2936 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
2942 /*********************************************************************
2944 * Function : client_if_modified_since
2946 * Description : Remove or modify the If-Modified-Since header.
2949 * 1 : csp = Current client state (buffers, headers, etc...)
2950 * 2 : header = On input, pointer to header to modify.
2951 * On output, pointer to the modified header, or NULL
2952 * to remove the header. This function frees the
2953 * original string if necessary.
2955 * Returns : JB_ERR_OK on success, or
2956 * JB_ERR_MEMORY on out-of-memory error.
2958 *********************************************************************/
2959 static jb_err client_if_modified_since(struct client_state *csp, char **header)
2962 #ifdef HAVE_GMTIME_R
2965 struct tm *timeptr = NULL;
2969 long int hours, minutes, seconds;
2973 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2976 * The client got an error message because of a temporary problem,
2977 * the problem is gone and the client now tries to revalidate our
2978 * error message on the real server. The revalidation would always
2979 * end with the transmission of the whole document and there is
2980 * no need to expose the bogus If-Modified-Since header.
2982 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2985 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2987 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2989 if ((0 == strcmpic(newval, "block")))
2991 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2994 else /* add random value */
2996 const char *header_time = *header + sizeof("If-Modified-Since:");
2998 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3000 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3005 rtime = strtol(newval, &endptr, 0);
3008 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3009 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3016 rtime = pick_from_range(rtime);
3020 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3023 tm += rtime * (negative ? -1 : 1);
3024 #ifdef HAVE_GMTIME_R
3025 timeptr = gmtime_r(&tm, &gmt);
3026 #elif FEATURE_PTHREAD
3027 privoxy_mutex_lock(&gmtime_mutex);
3028 timeptr = gmtime(&tm);
3029 privoxy_mutex_unlock(&gmtime_mutex);
3031 timeptr = gmtime(&tm);
3033 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3036 *header = strdup("If-Modified-Since: ");
3037 string_append(header, newheader);
3039 if (*header == NULL)
3041 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3042 return JB_ERR_MEMORY;
3045 hours = rtime / 3600;
3046 minutes = rtime / 60 % 60;
3047 seconds = rtime % 60;
3049 log_error(LOG_LEVEL_HEADER,
3050 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3051 *header, (negative) ? "subtracted" : "added", hours,
3052 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3053 seconds, (seconds == 1) ? ")" : "s)");
3062 /*********************************************************************
3064 * Function : client_if_none_match
3066 * Description : Remove the If-None-Match header.
3069 * 1 : csp = Current client state (buffers, headers, etc...)
3070 * 2 : header = On input, pointer to header to modify.
3071 * On output, pointer to the modified header, or NULL
3072 * to remove the header. This function frees the
3073 * original string if necessary.
3075 * Returns : JB_ERR_OK on success, or
3076 * JB_ERR_MEMORY on out-of-memory error.
3078 *********************************************************************/
3079 static jb_err client_if_none_match(struct client_state *csp, char **header)
3081 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3083 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3091 /*********************************************************************
3093 * Function : client_x_filter
3095 * Description : Disables filtering if the client set "X-Filter: No".
3096 * Called from `sed'.
3099 * 1 : csp = Current client state (buffers, headers, etc...)
3100 * 2 : header = On input, pointer to header to modify.
3101 * On output, pointer to the modified header, or NULL
3102 * to remove the header. This function frees the
3103 * original string if necessary.
3105 * Returns : JB_ERR_OK on success
3107 *********************************************************************/
3108 jb_err client_x_filter(struct client_state *csp, char **header)
3110 if ( 0 == strcmpic(*header, "X-Filter: No"))
3112 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3114 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3118 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3120 log_error(LOG_LEVEL_HEADER,
3121 "force-text-mode overruled the client's request to fetch without filtering!");
3125 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3126 csp->flags |= CSP_FLAG_NO_FILTERING;
3127 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3129 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3137 /*********************************************************************
3139 * Function : client_range
3141 * Description : Removes Range, Request-Range and If-Range headers if
3142 * content filtering is enabled. If the client's version
3143 * of the document has been altered by Privoxy, the server
3144 * could interpret the range differently than the client
3145 * intended in which case the user could end up with
3146 * corrupted content.
3149 * 1 : csp = Current client state (buffers, headers, etc...)
3150 * 2 : header = On input, pointer to header to modify.
3151 * On output, pointer to the modified header, or NULL
3152 * to remove the header. This function frees the
3153 * original string if necessary.
3155 * Returns : JB_ERR_OK
3157 *********************************************************************/
3158 static jb_err client_range(struct client_state *csp, char **header)
3160 if (content_filters_enabled(csp->action))
3162 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3163 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3170 /* the following functions add headers directly to the header list */
3172 /*********************************************************************
3174 * Function : client_host_adder
3176 * Description : Adds the Host: header field if it is missing.
3177 * Called from `sed'.
3180 * 1 : csp = Current client state (buffers, headers, etc...)
3182 * Returns : JB_ERR_OK on success, or
3183 * JB_ERR_MEMORY on out-of-memory error.
3185 *********************************************************************/
3186 static jb_err client_host_adder(struct client_state *csp)
3191 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3193 /* Header already set by the client, nothing to do. */
3197 if ( !csp->http->hostport || !*(csp->http->hostport))
3199 /* XXX: When does this happen and why is it OK? */
3200 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3205 * remove 'user:pass@' from 'proto://user:pass@host'
3207 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3213 p = csp->http->hostport;
3216 /* XXX: Just add it, we already made sure that it will be unique */
3217 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3218 err = enlist_unique_header(csp->headers, "Host", p);
3225 /*********************************************************************
3227 * Function : client_accept_encoding_adder
3229 * Description : Add an Accept-Encoding header to the client's request
3230 * that disables compression if the action applies, and
3231 * the header is not already there. Called from `sed'.
3232 * Note: For HTTP/1.0, the absence of the header is enough.
3235 * 1 : csp = Current client state (buffers, headers, etc...)
3237 * Returns : JB_ERR_OK on success, or
3238 * JB_ERR_MEMORY on out-of-memory error.
3240 *********************************************************************/
3241 static jb_err client_accept_encoding_adder(struct client_state *csp)
3243 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3244 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3246 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3254 /*********************************************************************
3256 * Function : client_xtra_adder
3258 * Description : Used in the add_client_headers list. Called from `sed'.
3261 * 1 : csp = Current client state (buffers, headers, etc...)
3263 * Returns : JB_ERR_OK on success, or
3264 * JB_ERR_MEMORY on out-of-memory error.
3266 *********************************************************************/
3267 static jb_err client_xtra_adder(struct client_state *csp)
3269 struct list_entry *lst;
3272 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3273 lst ; lst = lst->next)
3275 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3276 err = enlist(csp->headers, lst->str);
3288 /*********************************************************************
3290 * Function : client_x_forwarded_for_adder
3292 * Description : Used in the add_client_headers list. Called from `sed'.
3295 * 1 : csp = Current client state (buffers, headers, etc...)
3297 * Returns : JB_ERR_OK on success, or
3298 * JB_ERR_MEMORY on out-of-memory error.
3300 *********************************************************************/
3301 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3303 char *header = NULL;
3306 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3307 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3308 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3311 * If we aren't adding X-Forwarded-For headers,
3312 * or we already appended an existing X-Forwarded-For
3313 * header, there's nothing left to do here.
3318 header = strdup("X-Forwarded-For: ");
3319 string_append(&header, csp->ip_addr_str);
3323 return JB_ERR_MEMORY;
3326 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3327 err = enlist(csp->headers, header);
3334 /*********************************************************************
3336 * Function : server_connection_adder
3338 * Description : Adds an appropiate "Connection:" header to csp->headers
3339 * unless the header was already present. Called from `sed'.
3342 * 1 : csp = Current client state (buffers, headers, etc...)
3344 * Returns : JB_ERR_OK on success, or
3345 * JB_ERR_MEMORY on out-of-memory error.
3347 *********************************************************************/
3348 static jb_err server_connection_adder(struct client_state *csp)
3350 const unsigned int flags = csp->flags;
3351 const char *response_status_line = csp->headers->first->str;
3352 const char *wanted_header = get_appropiate_connection_header(csp);
3354 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3355 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3361 * XXX: if we downgraded the response, this check will fail.
3363 if ((csp->config->feature_flags &
3364 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3365 && (NULL != response_status_line)
3366 && !strncmpic(response_status_line, "HTTP/1.1", 8))
3368 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3369 "without Connection header implies keep-alive.");
3370 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3373 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3375 return enlist(csp->headers, wanted_header);
3379 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3380 /*********************************************************************
3382 * Function : server_proxy_connection_adder
3384 * Description : Adds a "Proxy-Connection: keep-alive" header to
3385 * csp->headers. XXX: We should reuse existant ones.
3388 * 1 : csp = Current client state (buffers, headers, etc...)
3390 * Returns : JB_ERR_OK on success, or
3391 * JB_ERR_MEMORY on out-of-memory error.
3393 *********************************************************************/
3394 static jb_err server_proxy_connection_adder(struct client_state *csp)
3396 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3397 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3398 return enlist(csp->headers, proxy_connection_header);
3400 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3403 /*********************************************************************
3405 * Function : client_connection_header_adder
3407 * Description : Adds a proper "Connection:" header to csp->headers
3408 * unless the header was already present. Called from `sed'.
3411 * 1 : csp = Current client state (buffers, headers, etc...)
3413 * Returns : JB_ERR_OK on success, or
3414 * JB_ERR_MEMORY on out-of-memory error.
3416 *********************************************************************/
3417 static jb_err client_connection_header_adder(struct client_state *csp)
3419 const unsigned int flags = csp->flags;
3420 const char *wanted_header = get_appropiate_connection_header(csp);
3422 if (!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3423 && (flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3428 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3430 return enlist(csp->headers, wanted_header);
3434 /*********************************************************************
3436 * Function : server_http
3438 * Description : - Save the HTTP Status into csp->http->status
3439 * - Set CT_TABOO to prevent filtering if the answer
3440 * is a partial range (HTTP status 206)
3441 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3445 * 1 : csp = Current client state (buffers, headers, etc...)
3446 * 2 : header = On input, pointer to header to modify.
3447 * On output, pointer to the modified header, or NULL
3448 * to remove the header. This function frees the
3449 * original string if necessary.
3451 * Returns : JB_ERR_OK on success, or
3452 * JB_ERR_MEMORY on out-of-memory error.
3454 *********************************************************************/
3455 static jb_err server_http(struct client_state *csp, char **header)
3457 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3458 if (csp->http->status == 206)
3460 csp->content_type = CT_TABOO;
3463 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3465 /* XXX: Should we do a real validity check here? */
3466 if (strlen(*header) > 8)
3469 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3474 * XXX: Should we block the request or
3475 * enlist a valid status code line here?
3477 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3478 "Downgrading to HTTP/1.0 impossible.");
3486 /*********************************************************************
3488 * Function : server_set_cookie
3490 * Description : Handle the server "cookie" header properly.
3491 * Log cookie to the jar file. Then "crunch",
3492 * accept or rewrite it to a session cookie.
3493 * Called from `sed'.
3495 * TODO: Allow the user to specify a new expiration
3496 * time to cause the cookie to expire even before the
3497 * browser is closed.
3500 * 1 : csp = Current client state (buffers, headers, etc...)
3501 * 2 : header = On input, pointer to header to modify.
3502 * On output, pointer to the modified header, or NULL
3503 * to remove the header. This function frees the
3504 * original string if necessary.
3506 * Returns : JB_ERR_OK on success, or
3507 * JB_ERR_MEMORY on out-of-memory error.
3509 *********************************************************************/
3510 static jb_err server_set_cookie(struct client_state *csp, char **header)
3517 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3519 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3522 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3524 /* Flag whether or not to log a message */
3527 /* A variable to store the tag we're working on */
3530 /* Skip "Set-Cookie:" (11 characters) in header */
3531 cur_tag = *header + 11;
3533 /* skip whitespace between "Set-Cookie:" and value */
3534 while (*cur_tag && ijb_isspace(*cur_tag))
3539 /* Loop through each tag in the cookie */
3543 char *next_tag = strchr(cur_tag, ';');
3544 if (next_tag != NULL)
3546 /* Skip the ';' character itself */
3549 /* skip whitespace ";" and start of tag */
3550 while (*next_tag && ijb_isspace(*next_tag))
3557 /* "Next tag" is the end of the string */
3558 next_tag = cur_tag + strlen(cur_tag);
3562 * Check the expiration date to see
3563 * if the cookie is still valid, if yes,
3564 * rewrite it to a session cookie.
3566 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3568 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3570 /* Did we detect the date properly? */
3571 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3574 * Nope, treat it as if it was still valid.
3576 * XXX: Should we remove the whole cookie instead?
3578 log_error(LOG_LEVEL_ERROR,
3579 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3580 string_move(cur_tag, next_tag);
3586 * Yes. Check if the cookie is still valid.
3588 * If the cookie is already expired it's probably
3589 * a delete cookie and even if it isn't, the browser
3590 * will discard it anyway.
3594 * XXX: timegm() isn't available on some AmigaOS
3595 * versions and our replacement doesn't work.
3597 * Our options are to either:
3599 * - disable session-cookies-only completely if timegm
3602 * - to simply remove all expired tags, like it has
3603 * been done until Privoxy 3.0.6 and to live with
3604 * the consequence that it can cause login/logout
3605 * problems on servers that don't validate their
3606 * input properly, or
3608 * - to replace it with mktime in which
3609 * case there is a slight chance of valid cookies
3610 * passing as already expired.
3612 * This is the way it's currently done and it's not
3613 * as bad as it sounds. If the missing GMT offset is
3614 * enough to change the result of the expiration check
3615 * the cookie will be only valid for a few hours
3616 * anyway, which in many cases will be shorter
3617 * than a browser session.
3619 if (cookie_time - now < 0)
3621 log_error(LOG_LEVEL_HEADER,
3622 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3623 /* Just in case some clown sets more then one expiration date */
3629 * Still valid, delete expiration date by copying
3630 * the rest of the string over it.
3632 string_move(cur_tag, next_tag);
3634 /* That changed the header, need to issue a log message */
3638 * Note that the next tag has now been moved to *cur_tag,
3639 * so we do not need to update the cur_tag pointer.
3647 /* Move on to next cookie tag */
3654 assert(NULL != *header);
3655 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3664 #ifdef FEATURE_FORCE_LOAD
3665 /*********************************************************************
3667 * Function : strclean
3669 * Description : In-Situ-Eliminate all occurances of substring in
3673 * 1 : string = string to clean
3674 * 2 : substring = substring to eliminate
3676 * Returns : Number of eliminations
3678 *********************************************************************/
3679 int strclean(char *string, const char *substring)
3685 len = strlen(substring);
3687 while((pos = strstr(string, substring)) != NULL)
3694 while (*p++ != '\0');
3701 #endif /* def FEATURE_FORCE_LOAD */
3704 /*********************************************************************
3706 * Function : parse_header_time
3708 * Description : Parses time formats used in HTTP header strings
3709 * to get the numerical respresentation.
3712 * 1 : header_time = HTTP header time as string.
3713 * 2 : result = storage for header_time in seconds
3715 * Returns : JB_ERR_OK if the time format was recognized, or
3716 * JB_ERR_PARSE otherwise.
3718 *********************************************************************/
3719 static jb_err parse_header_time(const char *header_time, time_t *result)
3724 * Zero out gmt to prevent time zone offsets.
3726 * While this is only necessary on some platforms
3727 * (mingw32 for example), I don't know how to
3728 * detect these automatically and doing it everywhere
3731 memset(&gmt, 0, sizeof(gmt));
3733 /* Tue, 02 Jun 2037 20:00:00 */
3734 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3735 /* Tue, 02-Jun-2037 20:00:00 */
3736 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3737 /* Tue, 02-Jun-37 20:00:00 */
3738 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3739 /* Tuesday, 02-Jun-2037 20:00:00 */
3740 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3741 /* Tuesday Jun 02 20:00:00 2037 */
3742 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3744 return JB_ERR_PARSE;
3747 *result = timegm(&gmt);
3754 /*********************************************************************
3756 * Function : get_destination_from_headers
3758 * Description : Parse the "Host:" header to get the request's destination.
3759 * Only needed if the client's request was forcefully
3760 * redirected into Privoxy.
3762 * Code mainly copied from client_host() which is currently
3763 * run too late for this purpose.
3766 * 1 : headers = List of headers (one of them hopefully being
3767 * the "Host:" header)
3768 * 2 : http = storage for the result (host, port and hostport).
3770 * Returns : JB_ERR_MEMORY in case of memory problems,
3771 * JB_ERR_PARSE if the host header couldn't be found,
3772 * JB_ERR_OK otherwise.
3774 *********************************************************************/
3775 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3781 host = get_header_value(headers, "Host:");
3785 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3786 return JB_ERR_PARSE;
3789 if (NULL == (p = strdup((host))))
3791 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3792 return JB_ERR_MEMORY;
3795 if (NULL == (q = strdup(p)))
3798 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3799 return JB_ERR_MEMORY;
3802 freez(http->hostport);
3806 q = strchr(http->host, ':');
3809 /* Terminate hostname and evaluate port string */
3811 http->port = atoi(q);
3815 http->port = http->ssl ? 443 : 80;
3818 /* Rebuild request URL */
3820 http->url = strdup(http->ssl ? "https://" : "http://");
3821 string_append(&http->url, http->hostport);
3822 string_append(&http->url, http->path);
3823 if (http->url == NULL)
3825 return JB_ERR_MEMORY;
3828 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
3836 /*********************************************************************
3838 * Function : create_forged_referrer
3840 * Description : Helper for client_referrer to forge a referer as
3841 * 'http://[hostname:port/' to fool stupid
3842 * checks for in-site links
3845 * 1 : header = Pointer to header pointer
3846 * 2 : hostport = Host and optionally port as string
3848 * Returns : JB_ERR_OK in case of success, or
3849 * JB_ERR_MEMORY in case of memory problems.
3851 *********************************************************************/
3852 static jb_err create_forged_referrer(char **header, const char *hostport)
3854 assert(NULL == *header);
3856 *header = strdup("Referer: http://");
3857 string_append(header, hostport);
3858 string_append(header, "/");
3860 if (NULL == *header)
3862 return JB_ERR_MEMORY;
3865 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
3872 /*********************************************************************
3874 * Function : create_fake_referrer
3876 * Description : Helper for client_referrer to create a fake referrer
3877 * based on a string supplied by the user.
3880 * 1 : header = Pointer to header pointer
3881 * 2 : hosthost = Referrer to fake
3883 * Returns : JB_ERR_OK in case of success, or
3884 * JB_ERR_MEMORY in case of memory problems.
3886 *********************************************************************/
3887 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
3889 assert(NULL == *header);
3891 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
3893 log_error(LOG_LEVEL_HEADER,
3894 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
3896 *header = strdup("Referer: ");
3897 string_append(header, fake_referrer);
3899 if (NULL == *header)
3901 return JB_ERR_MEMORY;
3904 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
3911 /*********************************************************************
3913 * Function : handle_conditional_hide_referrer_parameter
3915 * Description : Helper for client_referrer to crunch or forge
3916 * the referrer header if the host has changed.
3919 * 1 : header = Pointer to header pointer
3920 * 2 : host = The target host (may include the port)
3921 * 3 : parameter_conditional_block = Boolean to signal
3922 * if we're in conditional-block mode. If not set,
3923 * we're in conditional-forge mode.
3925 * Returns : JB_ERR_OK in case of success, or
3926 * JB_ERR_MEMORY in case of memory problems.
3928 *********************************************************************/
3929 static jb_err handle_conditional_hide_referrer_parameter(char **header,
3930 const char *host, const int parameter_conditional_block)
3932 char *referer = strdup(*header);
3933 const size_t hostlenght = strlen(host);
3934 const char *referer_url = NULL;
3936 if (NULL == referer)
3939 return JB_ERR_MEMORY;
3942 /* referer begins with 'Referer: http[s]://' */
3943 if ((hostlenght+17) < strlen(referer))
3946 * Shorten referer to make sure the referer is blocked
3947 * if www.example.org/www.example.com-shall-see-the-referer/
3948 * links to www.example.com/
3950 referer[hostlenght+17] = '\0';
3952 referer_url = strstr(referer, "http://");
3953 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
3955 /* Host has changed, Referer is invalid or a https URL. */
3956 if (parameter_conditional_block)
3958 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
3965 return create_forged_referrer(header, host);
3975 /*********************************************************************
3977 * Function : get_appropiate_connection_header
3979 * Description : Returns an appropiate Connection header
3980 * depending on whether or not we try to keep
3981 * the connection to the server alive.
3984 * 1 : csp = Current client state (buffers, headers, etc...)
3986 * Returns : Pointer to statically allocated header buffer.
3988 *********************************************************************/
3989 static const char *get_appropiate_connection_header(const struct client_state *csp)
3991 static const char connection_keep_alive[] = "Connection: keep-alive";
3992 static const char connection_close[] = "Connection: close";
3994 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3995 && (csp->http->ssl == 0))
3997 return connection_keep_alive;
3999 return connection_close;