1 const char parsers_rcs[] = "$Id: parsers.c,v 1.75 2006/11/13 19:05:51 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_server_header'
14 * `filter_client_header', `filter_header', `crunch_server_header',
15 * `server_content_encoding', `server_content_disposition',
16 * `server_last_modified', `client_accept_language',
17 * `crunch_client_header', `client_if_modified_since',
18 * `client_if_none_match', `get_destination_from_headers',
19 * `parse_header_time' and `server_set_cookie'.
21 * Copyright : Written by and Copyright (C) 2001-2006 the SourceForge
22 * Privoxy team. http://www.privoxy.org/
24 * Based on the Internet Junkbuster originally written
25 * by and Copyright (C) 1997 Anonymous Coders and
26 * Junkbusters Corporation. http://www.junkbusters.com
28 * This program is free software; you can redistribute it
29 * and/or modify it under the terms of the GNU General
30 * Public License as published by the Free Software
31 * Foundation; either version 2 of the License, or (at
32 * your option) any later version.
34 * This program is distributed in the hope that it will
35 * be useful, but WITHOUT ANY WARRANTY; without even the
36 * implied warranty of MERCHANTABILITY or FITNESS FOR A
37 * PARTICULAR PURPOSE. See the GNU General Public
38 * License for more details.
40 * The GNU General Public License should be included with
41 * this file. If not, you can view it at
42 * http://www.gnu.org/copyleft/gpl.html
43 * or write to the Free Software Foundation, Inc., 59
44 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
48 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
49 * Make pthread mutex locking more generic. Instead of
50 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
51 * and use mutex locking unless there is an _r function
52 * available. Better safe than sorry.
54 * Fixes "./configure --disable-pthread" and should result
55 * in less threading-related problems on pthread-using platforms,
56 * but it still doesn't fix BR#1122404.
58 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
59 * The special header "X-Filter: No" now disables
60 * header filtering as well.
62 * Revision 1.73 2006/09/23 13:26:38 roro
63 * Replace TABs by spaces in source code.
65 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
66 * Don't print a log message every time filter_headers is
67 * entered or left. It only creates noise without any real
70 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
71 * Fix +hide-if-modified-since{-n}.
73 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
74 * Have hide-if-modified-since interpret the random
75 * range value as minutes instead of hours. Allows
76 * more fine-grained configuration.
78 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
79 * Always have parse_header_time return a pointer
80 * that actual makes sense, even though we currently
81 * only need it to detect problems.
83 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
84 * Added config option enable-remote-http-toggle
85 * to specify if Privoxy should recognize special
86 * headers (currently only X-Filter) to change its
87 * behaviour. Disabled by default.
89 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
90 * After filtering de-chunked instances, remove
91 * "Transfer-Encoding" header entirely instead of changing
92 * it to "Transfer-Encoding: identity", which is invalid.
93 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
95 * Don't use localtime in parse_header_time. An empty time struct
96 * is good enough, it gets overwritten by strptime anyway.
98 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
99 * Use gmtime_r if available, fallback to gmtime with mutex
100 * protection for MacOSX and use vanilla gmtime for the rest.
102 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
103 * Changed client_referrer to use the right type (size_t) for
104 * hostlenght and to shorten the temporary referrer string with
105 * '\0' instead of adding a useless line break.
107 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
108 * - Back to timegm() using GnuPG's replacement if necessary.
109 * Using mktime() and localtime() could add a on hour offset if
110 * the randomize factor was big enough to lead to a summer/wintertime
113 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
115 * - Moved randomization code into pick_from_range().
117 * - Changed parse_header_time definition.
118 * time_t isn't guaranteed to be signed and
119 * if it isn't, -1 isn't available as error code.
120 * Changed some variable types in client_if_modified_since()
121 * because of the same reason.
123 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
124 * OS/2 compilation compatibility fixups
126 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
127 * Changed include from strptime.c to strptime.h
129 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
130 * Split filter-headers{} into filter-client-headers{}
131 * and filter-server-headers{}.
132 * Added parse_header_time() to share some code.
133 * Replaced timegm() with mktime().
135 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
136 * Windows service integration
138 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
139 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
141 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
142 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
143 * with what was really the latest development (the v_3_0_branch branch)
145 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
146 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
148 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
149 * Add the ability to check jpeg images for invalid
150 * lengths of comment blocks. Defensive strategy
151 * against the exploit:
152 * Microsoft Security Bulletin MS04-028
153 * Buffer Overrun in JPEG Processing (GDI+) Could
154 * Allow Code Execution (833987)
155 * Enabled with +inspect-jpegs in actions files.
157 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
158 * Excluded text/plain objects from filtering. This fixes a
159 * couple of client-crashing, download corruption and
160 * Privoxy performance issues, whose root cause lies in
161 * web servers labelling content of unknown type as text/plain.
163 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
164 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
166 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
167 * Completing the previous change
169 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
170 * Added temporary workaround for bug in PHP < 4.2.3
172 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
173 * Wrapping all *_r functions (the non-_r versions of them) with mutex semaphores for OSX. Hopefully this will take care of all of those pesky crash reports.
175 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
176 * Fix typo: supressed -> suppressed
178 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
179 * Improved cookie logging
181 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
182 * Added basic support for OPTIONS and TRACE HTTP methods:
183 * - New parser function client_max_forwards which decrements
184 * the Max-Forwards HTTP header field of OPTIONS and TRACE
185 * requests by one before forwarding
186 * - New parser function client_host which extracts the host
187 * and port information from the HTTP header field if the
188 * request URI was not absolute
189 * - Don't crumble and re-add the Host: header, but only generate
190 * and append if missing
192 * Revision 1.56 2002/05/12 15:34:22 jongfoster
193 * Fixing typo in a comment
195 * Revision 1.55 2002/05/08 16:01:07 oes
196 * Optimized add_to_iob:
197 * - Use realloc instead of malloc(), memcpy(), free()
198 * - Expand to powers of two if possible, to get
199 * O(log n) reallocs instead of O(n).
200 * - Moved check for buffer limit here from chat
201 * - Report failure via returncode
203 * Revision 1.54 2002/04/02 15:03:16 oes
204 * Tiny code cosmetics
206 * Revision 1.53 2002/03/26 22:29:55 swa
207 * we have a new homepage!
209 * Revision 1.52 2002/03/24 13:25:43 swa
210 * name change related issues
212 * Revision 1.51 2002/03/13 00:27:05 jongfoster
215 * Revision 1.50 2002/03/12 01:45:35 oes
216 * More verbose logging
218 * Revision 1.49 2002/03/09 20:03:52 jongfoster
219 * - Making various functions return int rather than size_t.
220 * (Undoing a recent change). Since size_t is unsigned on
221 * Windows, functions like read_socket that return -1 on
222 * error cannot return a size_t.
224 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
225 * crashes, and also frequently caused JB to jump to 100%
226 * CPU and stay there. (Because it thought it had just
227 * read ((unsigned)-1) == 4Gb of data...)
229 * - The signature of write_socket has changed, it now simply
230 * returns success=0/failure=nonzero.
232 * - Trying to get rid of a few warnings --with-debug on
233 * Windows, I've introduced a new type "jb_socket". This is
234 * used for the socket file descriptors. On Windows, this
235 * is SOCKET (a typedef for unsigned). Everywhere else, it's
236 * an int. The error value can't be -1 any more, so it's
237 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
238 * Windows it maps to the #define INVALID_SOCKET.)
240 * - The signature of bind_port has changed.
242 * Revision 1.48 2002/03/07 03:46:53 oes
243 * Fixed compiler warnings etc
245 * Revision 1.47 2002/02/20 23:15:13 jongfoster
246 * Parsing functions now handle out-of-memory gracefully by returning
249 * Revision 1.46 2002/01/17 21:03:47 jongfoster
250 * Moving all our URL and URL pattern parsing code to urlmatch.c.
252 * Revision 1.45 2002/01/09 14:33:03 oes
253 * Added support for localtime_r.
255 * Revision 1.44 2001/12/14 01:22:54 steudten
256 * Remove 'user:pass@' from 'proto://user:pass@host' for the
257 * new added header 'Host: ..'. (See Req ID 491818)
259 * Revision 1.43 2001/11/23 00:26:38 jongfoster
260 * Fixing two really stupid errors in my previous commit
262 * Revision 1.42 2001/11/22 21:59:30 jongfoster
263 * Adding code to handle +no-cookies-keep
265 * Revision 1.41 2001/11/05 23:43:05 steudten
266 * Add time+date to log files.
268 * Revision 1.40 2001/10/26 20:13:09 jongfoster
269 * ctype.h is needed in Windows, too.
271 * Revision 1.39 2001/10/26 17:40:04 oes
272 * Introduced get_header_value()
273 * Removed http->user_agent, csp->referrer and csp->accept_types
274 * Removed client_accept()
276 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
277 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
278 * threads to call select() simultaneously. So, it's time to do a real, live,
279 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
280 * (native). Both versions will work, but using __OS2__ offers multi-threading.
282 * Revision 1.37 2001/10/23 21:36:02 jongfoster
283 * Documenting sed()'s error behaviou (doc change only)
285 * Revision 1.36 2001/10/13 12:51:51 joergs
286 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
287 * force-load), instead crumble Host: and add it (again) in client_host_adder
288 * (in case we get a HTTP/1.0 request without Host: header and forward it to
289 * a HTTP/1.1 server/proxy).
291 * Revision 1.35 2001/10/09 22:39:21 jongfoster
292 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
295 * Revision 1.34 2001/10/07 18:50:55 oes
296 * Added server_content_encoding, renamed server_transfer_encoding
298 * Revision 1.33 2001/10/07 18:04:49 oes
299 * Changed server_http11 to server_http and its pattern to "HTTP".
300 * Additional functionality: it now saves the HTTP status into
301 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
303 * Revision 1.32 2001/10/07 15:43:28 oes
304 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
305 * client_te and client_accept_encoding_adder, triggered by the new
306 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
307 * changed to allow only identity and chunked, and the TE header is
308 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
310 * parse_http_request no longer does anything than parsing. The rewriting
311 * of http->cmd and version mangling are gone. It now also recognizes
312 * the put and delete methods and saves the url in http->url. Removed
315 * renamed content_type and content_length to have the server_ prefix
317 * server_content_type now only works if csp->content_type != CT_TABOO
319 * added server_transfer_encoding, which
320 * - Sets CT_TABOO to prohibit filtering if encoding compresses
321 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
322 * - Change from "chunked" to "identity" if body was chunked
323 * but has been de-chunked for filtering.
325 * added server_content_md5 which crunches any Content-MD5 headers
326 * if the body was modified.
328 * made server_http11 conditional on +downgrade action
330 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
332 * Revision 1.31 2001/10/05 14:25:02 oes
333 * Crumble Keep-Alive from Server
335 * Revision 1.30 2001/09/29 12:56:03 joergs
336 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
338 * Revision 1.29 2001/09/24 21:09:24 jongfoster
339 * Fixing 2 memory leaks that Guy spotted, where the paramater to
340 * enlist() was not being free()d.
342 * Revision 1.28 2001/09/22 16:32:28 jongfoster
343 * Removing unused #includes.
345 * Revision 1.27 2001/09/20 15:45:25 steudten
347 * add casting from size_t to int for printf()
348 * remove local variable shadow s2
350 * Revision 1.26 2001/09/16 17:05:14 jongfoster
351 * Removing unused #include showarg.h
353 * Revision 1.25 2001/09/16 13:21:27 jongfoster
354 * Changes to use new list functions.
356 * Revision 1.24 2001/09/13 23:05:50 jongfoster
357 * Changing the string paramater to the header parsers a "const".
359 * Revision 1.23 2001/09/12 18:08:19 steudten
361 * In parse_http_request() header rewriting miss the host value, so
362 * from http://www.mydomain.com the result was just " / " not
363 * http://www.mydomain.com/ in case we forward.
365 * Revision 1.22 2001/09/10 10:58:53 oes
366 * Silenced compiler warnings
368 * Revision 1.21 2001/07/31 14:46:00 oes
369 * - Persistant connections now suppressed
370 * - sed() no longer appends empty header to csp->headers
372 * Revision 1.20 2001/07/30 22:08:36 jongfoster
373 * Tidying up #defines:
374 * - All feature #defines are now of the form FEATURE_xxx
375 * - Permanently turned off WIN_GUI_EDIT
376 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
378 * Revision 1.19 2001/07/25 17:21:54 oes
379 * client_uagent now saves copy of User-Agent: header value
381 * Revision 1.18 2001/07/13 14:02:46 oes
382 * - Included fix to repair broken HTTP requests that
383 * don't contain a path, not even '/'.
384 * - Removed all #ifdef PCRS
385 * - content_type now always inspected and classified as
386 * text, gif or other.
387 * - formatting / comments
389 * Revision 1.17 2001/06/29 21:45:41 oes
390 * Indentation, CRLF->LF, Tab-> Space
392 * Revision 1.16 2001/06/29 13:32:42 oes
394 * - Adapted free_http_request
395 * - Removed logentry from cancelled commit
397 * Revision 1.15 2001/06/03 19:12:38 oes
398 * deleted const struct interceptors
400 * Revision 1.14 2001/06/01 18:49:17 jongfoster
401 * Replaced "list_share" with "list" - the tiny memory gain was not
402 * worth the extra complexity.
404 * Revision 1.13 2001/05/31 21:30:33 jongfoster
405 * Removed list code - it's now in list.[ch]
406 * Renamed "permission" to "action", and changed many features
407 * to use the actions file rather than the global config.
409 * Revision 1.12 2001/05/31 17:33:13 oes
413 * Revision 1.11 2001/05/29 20:11:19 joergs
414 * '/ * inside comment' warning removed.
416 * Revision 1.10 2001/05/29 09:50:24 jongfoster
417 * Unified blocklist/imagelist/permissionslist.
418 * File format is still under discussion, but the internal changes
421 * Also modified interceptor behaviour:
422 * - We now intercept all URLs beginning with one of the following
423 * prefixes (and *only* these prefixes):
425 * * http://ijbswa.sf.net/config/
426 * * http://ijbswa.sourceforge.net/config/
427 * - New interceptors "home page" - go to http://i.j.b/ to see it.
428 * - Internal changes so that intercepted and fast redirect pages
429 * are not replaced with an image.
430 * - Interceptors now have the option to send a binary page direct
431 * to the client. (i.e. ijb-send-banner uses this)
432 * - Implemented show-url-info interceptor. (Which is why I needed
433 * the above interceptors changes - a typical URL is
434 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
435 * The previous mechanism would not have intercepted that, and
436 * if it had been intercepted then it then it would have replaced
439 * Revision 1.9 2001/05/28 17:26:33 jongfoster
440 * Fixing segfault if last header was crunched.
441 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
442 * can use the cross-platform sprintf() instead.)
444 * Revision 1.8 2001/05/27 22:17:04 oes
446 * - re_process_buffer no longer writes the modified buffer
447 * to the client, which was very ugly. It now returns the
448 * buffer, which it is then written by chat.
450 * - content_length now adjusts the Content-Length: header
451 * for modified documents rather than crunch()ing it.
452 * (Length info in csp->content_length, which is 0 for
453 * unmodified documents)
455 * - For this to work, sed() is called twice when filtering.
457 * Revision 1.7 2001/05/27 13:19:06 oes
458 * Patched Joergs solution for the content-length in.
460 * Revision 1.6 2001/05/26 13:39:32 jongfoster
461 * Only crunches Content-Length header if applying RE filtering.
462 * Without this fix, Microsoft Windows Update wouldn't work.
464 * Revision 1.5 2001/05/26 00:28:36 jongfoster
465 * Automatic reloading of config file.
466 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
467 * Most of the global variables have been moved to a new
468 * struct configuration_spec, accessed through csp->config->globalname
469 * Most of the globals remaining are used by the Win32 GUI.
471 * Revision 1.4 2001/05/22 18:46:04 oes
473 * - Enabled filtering banners by size rather than URL
474 * by adding patterns that replace all standard banner
475 * sizes with the "Junkbuster" gif to the re_filterfile
477 * - Enabled filtering WebBugs by providing a pattern
478 * which kills all 1x1 images
480 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
481 * which is selected by the (nonstandard and therefore
482 * capital) letter 'U' in the option string.
483 * It causes the quantifiers to be ungreedy by default.
484 * Appending a ? turns back to greedy (!).
486 * - Added a new interceptor ijb-send-banner, which
487 * sends back the "Junkbuster" gif. Without imagelist or
488 * MSIE detection support, or if tinygif = 1, or the
489 * URL isn't recognized as an imageurl, a lame HTML
490 * explanation is sent instead.
492 * - Added new feature, which permits blocking remote
493 * script redirects and firing back a local redirect
495 * The feature is conditionally compiled, i.e. it
496 * can be disabled with --disable-fast-redirects,
497 * plus it must be activated by a "fast-redirects"
498 * line in the config file, has its own log level
499 * and of course wants to be displayed by show-proxy-args
500 * Note: Boy, all the #ifdefs in 1001 locations and
501 * all the fumbling with configure.in and acconfig.h
502 * were *way* more work than the feature itself :-(
504 * - Because a generic redirect template was needed for
505 * this, tinygif = 3 now uses the same.
507 * - Moved GIFs, and other static HTTP response templates
512 * - Removed some >400 CRs again (Jon, you really worked
515 * Revision 1.3 2001/05/20 01:21:20 jongfoster
516 * Version 2.9.4 checkin.
517 * - Merged popupfile and cookiefile, and added control over PCRS
518 * filtering, in new "permissionsfile".
519 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
520 * file error you now get a message box (in the Win32 GUI) rather
521 * than the program exiting with no explanation.
522 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
524 * - Removed tabs from "config"
525 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
526 * - Bumped up version number.
528 * Revision 1.2 2001/05/17 23:02:36 oes
529 * - Made referrer option accept 'L' as a substitute for '§'
531 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
532 * Initial import of version 2.9.3 source tree
535 *********************************************************************/
542 #include <sys/types.h>
551 #if !defined(_WIN32) && !defined(__OS2__)
557 #ifdef FEATURE_PTHREAD
559 /* jcc.h is for mutex semapores only */
560 #endif /* def FEATURE_PTHREAD */
566 #include "jbsockets.h"
567 #include "miscutil.h"
570 #ifndef HAVE_STRPTIME
571 #include "strptime.h"
574 const char parsers_h_rcs[] = PARSERS_H_VERSION;
576 /* Fix a problem with Solaris. There should be no effect on other
578 * Solaris's isspace() is a macro which uses it's argument directly
579 * as an array index. Therefore we need to make sure that high-bit
580 * characters generate +ve values, and ideally we also want to make
581 * the argument match the declared parameter type of "int".
583 * Why did they write a character function that can't take a simple
584 * "char" argument? Doh!
586 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
587 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
590 const struct parsers client_patterns[] = {
591 { "referer:", 8, client_referrer },
592 { "user-agent:", 11, client_uagent },
593 { "ua-", 3, client_ua },
594 { "from:", 5, client_from },
595 { "cookie:", 7, client_send_cookie },
596 { "x-forwarded-for:", 16, client_x_forwarded },
597 { "Accept-Encoding:", 16, client_accept_encoding },
598 { "TE:", 3, client_te },
599 { "Host:", 5, client_host },
600 { "if-modified-since:", 18, client_if_modified_since },
601 { "Keep-Alive:", 11, crumble },
602 { "connection:", 11, crumble },
603 { "proxy-connection:", 17, crumble },
604 { "max-forwards:", 13, client_max_forwards },
605 { "Accept-Language:", 16, client_accept_language },
606 { "if-none-match:", 14, client_if_none_match },
607 { "X-Filter:", 9, client_x_filter },
608 { "*", 0, crunch_client_header },
609 { "*", 0, filter_client_header },
613 const struct parsers server_patterns[] = {
614 { "HTTP", 4, server_http },
615 { "set-cookie:", 11, server_set_cookie },
616 { "connection:", 11, crumble },
617 { "Content-Type:", 13, server_content_type },
618 { "Content-Length:", 15, server_content_length },
619 { "Content-MD5:", 12, server_content_md5 },
620 { "Content-Encoding:", 17, server_content_encoding },
621 { "Transfer-Encoding:", 18, server_transfer_coding },
622 { "Keep-Alive:", 11, crumble },
623 { "content-disposition:", 20, server_content_disposition },
624 { "Last-Modified:", 14, server_last_modified },
625 { "*", 0, crunch_server_header },
626 { "*", 0, filter_server_header },
630 const struct parsers server_patterns_light[] = {
631 { "Content-Length:", 15, server_content_length },
632 { "Transfer-Encoding:", 18, server_transfer_coding },
636 const add_header_func_ptr add_client_headers[] = {
639 client_x_forwarded_adder,
641 /* Temporarily disabled: client_accept_encoding_adder, */
642 connection_close_adder,
647 const add_header_func_ptr add_server_headers[] = {
648 connection_close_adder,
652 /*********************************************************************
654 * Function : flush_socket
656 * Description : Write any pending "buffered" content.
659 * 1 : fd = file descriptor of the socket to read
660 * 2 : csp = Current client state (buffers, headers, etc...)
662 * Returns : On success, the number of bytes written are returned (zero
663 * indicates nothing was written). On error, -1 is returned,
664 * and errno is set appropriately. If count is zero and the
665 * file descriptor refers to a regular file, 0 will be
666 * returned without causing any other effect. For a special
667 * file, the results are not portable.
669 *********************************************************************/
670 int flush_socket(jb_socket fd, struct client_state *csp)
672 struct iob *iob = csp->iob;
673 int len = iob->eod - iob->cur;
680 if (write_socket(fd, iob->cur, (size_t)len))
684 iob->eod = iob->cur = iob->buf;
690 /*********************************************************************
692 * Function : add_to_iob
694 * Description : Add content to the buffered page, expanding the
695 * buffer if necessary.
698 * 1 : csp = Current client state (buffers, headers, etc...)
699 * 2 : buf = holds the content to be added to the page
700 * 3 : n = number of bytes to be added
702 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
703 * or buffer limit reached.
705 *********************************************************************/
706 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
708 struct iob *iob = csp->iob;
709 size_t used, offset, need, want;
712 if (n <= 0) return JB_ERR_OK;
714 used = iob->eod - iob->buf;
715 offset = iob->cur - iob->buf;
719 * If the buffer can't hold the new data, extend it first.
720 * Use the next power of two if possible, else use the actual need.
722 if (need > csp->config->buffer_limit)
724 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
725 return JB_ERR_MEMORY;
728 if (need > iob->size)
730 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
732 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
736 else if (NULL != (p = (char *)realloc(iob->buf, need)))
742 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
743 return JB_ERR_MEMORY;
746 /* Update the iob pointers */
747 iob->cur = p + offset;
752 /* copy the new data into the iob buffer */
753 memcpy(iob->eod, buf, (size_t)n);
755 /* point to the end of the data */
758 /* null terminate == cheap insurance */
766 /*********************************************************************
768 * Function : get_header
770 * Description : This (odd) routine will parse the csp->iob
773 * 1 : csp = Current client state (buffers, headers, etc...)
775 * Returns : Any one of the following:
777 * 1) a pointer to a dynamically allocated string that contains a header line
778 * 2) NULL indicating that the end of the header was reached
779 * 3) "" indicating that the end of the iob was reached before finding
780 * a complete header line.
782 *********************************************************************/
783 char *get_header(struct client_state *csp)
789 if ((iob->cur == NULL)
790 || ((p = strchr(iob->cur, '\n')) == NULL))
792 return(""); /* couldn't find a complete header */
797 ret = strdup(iob->cur);
800 /* FIXME No way to handle error properly */
801 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
806 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
808 /* is this a blank line (i.e. the end of the header) ? */
820 /*********************************************************************
822 * Function : get_header_value
824 * Description : Get the value of a given header from a chained list
825 * of header lines or return NULL if no such header is
826 * present in the list.
829 * 1 : header_list = pointer to list
830 * 2 : header_name = string with name of header to look for.
831 * Trailing colon required, capitalization
834 * Returns : NULL if not found, else value of header
836 *********************************************************************/
837 char *get_header_value(const struct list *header_list, const char *header_name)
839 struct list_entry *cur_entry;
845 length = strlen(header_name);
847 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
851 if (!strncmpic(cur_entry->str, header_name, length))
854 * Found: return pointer to start of value
856 ret = (char *) (cur_entry->str + length);
857 while (*ret && ijb_isspace(*ret)) ret++;
870 /*********************************************************************
874 * Description : add, delete or modify lines in the HTTP header streams.
875 * On entry, it receives a linked list of headers space
876 * that was allocated dynamically (both the list nodes
877 * and the header contents).
879 * As a side effect it frees the space used by the original
883 * 1 : pats = list of patterns to match against headers
884 * 2 : more_headers = list of functions to add more
885 * headers (client or server)
886 * 3 : csp = Current client state (buffers, headers, etc...)
888 * Returns : Single pointer to a fully formed header, or NULL
889 * on out-of-memory error.
891 *********************************************************************/
892 char *sed(const struct parsers pats[],
893 const add_header_func_ptr more_headers[],
894 struct client_state *csp)
896 struct list_entry *p;
897 const struct parsers *v;
898 const add_header_func_ptr *f;
899 jb_err err = JB_ERR_OK;
903 * If filtering is enabled, sed is run twice,
904 * but most of the work needs to be done only once.
906 first_run = (more_headers != NULL ) ? 1 : 0;
908 if (first_run) /* Parse and print */
910 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
912 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
914 /* Header crunch()ed in previous run? -> ignore */
915 if (p->str == NULL) continue;
917 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
919 /* Does the current parser handle this header? */
920 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
922 err = v->parser(csp, (char **)&(p->str));
926 /* place any additional headers on the csp->headers list */
927 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
932 else /* Parse only */
935 * The second run is only needed if the body was modified
936 * and the content-lenght has changed.
938 if (strncmpic(csp->http->cmd, "HEAD", 4))
940 /*XXX: Code duplication*/
941 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
943 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
945 /* Header crunch()ed in previous run? -> ignore */
946 if (p->str == NULL) continue;
948 /* Does the current parser handle this header? */
949 if (strncmpic(p->str, v->str, v->len) == 0)
951 err = v->parser(csp, (char **)&(p->str));
958 if (err != JB_ERR_OK)
963 return list_to_text(csp->headers);
967 /* here begins the family of parser functions that reformat header lines */
969 /*********************************************************************
971 * Function : filter_server_header
973 * Description : Checks if server header filtering is enabled.
974 * If it is, filter_header is called to do the work.
977 * 1 : csp = Current client state (buffers, headers, etc...)
978 * 2 : header = On input, pointer to header to modify.
979 * On output, pointer to the modified header, or NULL
980 * to remove the header. This function frees the
981 * original string if necessary.
983 * Returns : JB_ERR_OK on success and always succeeds
985 *********************************************************************/
986 jb_err filter_server_header(struct client_state *csp, char **header)
988 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
990 filter_header(csp, header);
995 /*********************************************************************
997 * Function : filter_client_header
999 * Description : Checks if client header filtering is enabled.
1000 * If it is, filter_header is called to do the work.
1003 * 1 : csp = Current client state (buffers, headers, etc...)
1004 * 2 : header = On input, pointer to header to modify.
1005 * On output, pointer to the modified header, or NULL
1006 * to remove the header. This function frees the
1007 * original string if necessary.
1009 * Returns : JB_ERR_OK on success and always succeeds
1011 *********************************************************************/
1012 jb_err filter_client_header(struct client_state *csp, char **header)
1014 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
1016 filter_header(csp, header);
1021 /*********************************************************************
1023 * Function : filter_header
1025 * Description : Executes all text substitutions from all applying
1026 * +filter actions on the header.
1027 * Most of the code was copied from pcrs_filter_response,
1028 * including the rather short variable names
1031 * 1 : csp = Current client state (buffers, headers, etc...)
1032 * 2 : header = On input, pointer to header to modify.
1033 * On output, pointer to the modified header, or NULL
1034 * to remove the header. This function frees the
1035 * original string if necessary.
1037 * Returns : JB_ERR_OK on success and always succeeds
1039 *********************************************************************/
1040 jb_err filter_header(struct client_state *csp, char **header)
1044 size_t size = strlen(*header);
1046 char *newheader = NULL;
1049 struct file_list *fl;
1050 struct re_filterfile_spec *b;
1051 struct list_entry *filtername;
1053 int i, found_filters = 0;
1056 * Need to check the set of re_filterfiles...
1058 for (i = 0; i < MAX_AF_FILES; i++)
1071 if (0 == found_filters)
1073 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1077 for (i = 0; i < MAX_AF_FILES; i++)
1080 if ((NULL == fl) || (NULL == fl->f))
1083 * For all applying +filter actions, look if a filter by that
1084 * name exists and if yes, execute its pcrs_joblist on the
1087 for (b = fl->f; b; b = b->next)
1089 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1090 filtername ; filtername = filtername->next)
1092 if (strcmp(b->name, filtername->str) == 0)
1094 int current_hits = 0;
1096 if ( NULL == b->joblist )
1098 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1102 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1103 *header, size, b->name);
1105 /* Apply all jobs from the joblist */
1106 for (job = b->joblist; NULL != job; job = job->next)
1108 matches = pcrs_execute(job, *header, size, &newheader, &size);
1111 current_hits += matches;
1112 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1114 *header = newheader;
1116 else if ( 0 == matches )
1118 /* Filter doesn't change header */
1124 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1125 *header, b->name, pcrs_strerror(matches));
1126 if( newheader != NULL)
1128 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1133 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1134 hits += current_hits;
1142 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1150 /*********************************************************************
1152 * Function : crumble
1154 * Description : This is called if a header matches a pattern to "crunch"
1157 * 1 : csp = Current client state (buffers, headers, etc...)
1158 * 2 : header = On input, pointer to header to modify.
1159 * On output, pointer to the modified header, or NULL
1160 * to remove the header. This function frees the
1161 * original string if necessary.
1163 * Returns : JB_ERR_OK on success, or
1164 * JB_ERR_MEMORY on out-of-memory error.
1166 *********************************************************************/
1167 jb_err crumble(struct client_state *csp, char **header)
1169 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1174 /*********************************************************************
1176 * Function : crunch_server_header
1178 * Description : Crunch server header if it matches a string supplied by the
1179 * user. Called from `sed'.
1182 * 1 : csp = Current client state (buffers, headers, etc...)
1183 * 2 : header = On input, pointer to header to modify.
1184 * On output, pointer to the modified header, or NULL
1185 * to remove the header. This function frees the
1186 * original string if necessary.
1188 * Returns : JB_ERR_OK on success and always succeeds
1190 *********************************************************************/
1191 jb_err crunch_server_header(struct client_state *csp, char **header)
1193 const char *crunch_pattern;
1194 /*Is there a header to crunch*/
1196 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1198 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1200 /*Is the current header the lucky one?*/
1201 if (strstr(*header, crunch_pattern))
1203 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1210 /*********************************************************************
1212 * Function : server_content_type
1214 * Description : Set the content-type for filterable types (text/.*,
1215 * javascript and image/gif) unless filtering has been
1216 * forbidden (CT_TABOO) while parsing earlier headers.
1217 * NOTE: Since text/plain is commonly used by web servers
1218 * for files whose correct type is unknown, we don't
1219 * set CT_TEXT for it.
1222 * 1 : csp = Current client state (buffers, headers, etc...)
1223 * 2 : header = On input, pointer to header to modify.
1224 * On output, pointer to the modified header, or NULL
1225 * to remove the header. This function frees the
1226 * original string if necessary.
1228 * Returns : JB_ERR_OK on success, or
1229 * JB_ERR_MEMORY on out-of-memory error.
1231 *********************************************************************/
1232 jb_err server_content_type(struct client_state *csp, char **header)
1236 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1238 if (csp->content_type != CT_TABOO)
1240 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1241 || strstr(*header, "xml")
1242 || strstr(*header, "application/x-javascript"))
1243 csp->content_type = CT_TEXT;
1244 else if (strstr(*header, " image/gif"))
1245 csp->content_type = CT_GIF;
1246 else if (strstr(*header, " image/jpeg"))
1247 csp->content_type = CT_JPEG;
1249 csp->content_type = 0;
1252 * Are we enabling text mode by force?
1254 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1257 * Do we really have to?
1259 if (csp->content_type == CT_TEXT)
1261 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1265 csp->content_type = CT_TEXT;
1266 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1270 * Are we messing with the content type?
1272 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1275 * Make sure the user doesn't accidently
1276 * change the content type of binary documents.
1278 if (csp->content_type == CT_TEXT)
1281 *header = strdup("Content-Type: ");
1282 string_append(header, newval);
1286 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1287 return JB_ERR_MEMORY;
1289 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1293 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1294 "Enable force-text-mode if you know what you're doing.", *header);
1301 /*********************************************************************
1303 * Function : server_transfer_coding
1305 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1306 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1307 * - Remove header if body was chunked but has been
1308 * de-chunked for filtering.
1311 * 1 : csp = Current client state (buffers, headers, etc...)
1312 * 2 : header = On input, pointer to header to modify.
1313 * On output, pointer to the modified header, or NULL
1314 * to remove the header. This function frees the
1315 * original string if necessary.
1317 * Returns : JB_ERR_OK on success, or
1318 * JB_ERR_MEMORY on out-of-memory error.
1320 *********************************************************************/
1321 jb_err server_transfer_coding(struct client_state *csp, char **header)
1324 * Turn off pcrs and gif filtering if body compressed
1326 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1328 csp->content_type = CT_TABOO;
1332 * Raise flag if body chunked
1334 if (strstr(*header, "chunked"))
1336 csp->flags |= CSP_FLAG_CHUNKED;
1339 * If the body was modified, it has been de-chunked first
1340 * and the header must be removed.
1342 if (csp->flags & CSP_FLAG_MODIFIED)
1344 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1353 /*********************************************************************
1355 * Function : server_content_encoding
1357 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1360 * 1 : csp = Current client state (buffers, headers, etc...)
1361 * 2 : header = On input, pointer to header to modify.
1362 * On output, pointer to the modified header, or NULL
1363 * to remove the header. This function frees the
1364 * original string if necessary.
1366 * Returns : JB_ERR_OK on success, or
1367 * JB_ERR_MEMORY on out-of-memory error.
1369 *********************************************************************/
1370 jb_err server_content_encoding(struct client_state *csp, char **header)
1373 * Turn off pcrs and gif filtering if body compressed
1375 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1377 csp->content_type = CT_TABOO;
1385 /*********************************************************************
1387 * Function : server_content_length
1389 * Description : Adjust Content-Length header if we modified
1393 * 1 : csp = Current client state (buffers, headers, etc...)
1394 * 2 : header = On input, pointer to header to modify.
1395 * On output, pointer to the modified header, or NULL
1396 * to remove the header. This function frees the
1397 * original string if necessary.
1399 * Returns : JB_ERR_OK on success, or
1400 * JB_ERR_MEMORY on out-of-memory error.
1402 *********************************************************************/
1403 jb_err server_content_length(struct client_state *csp, char **header)
1405 if (csp->content_length != 0) /* Content length could have been modified */
1408 * XXX: Shouldn't we check if csp->content_length
1409 * is different than the original value?
1412 *header = (char *) zalloc(100);
1413 if (*header == NULL)
1415 return JB_ERR_MEMORY;
1418 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1420 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1427 /*********************************************************************
1429 * Function : server_content_md5
1431 * Description : Crumble any Content-MD5 headers if the document was
1432 * modified. FIXME: Should we re-compute instead?
1435 * 1 : csp = Current client state (buffers, headers, etc...)
1436 * 2 : header = On input, pointer to header to modify.
1437 * On output, pointer to the modified header, or NULL
1438 * to remove the header. This function frees the
1439 * original string if necessary.
1441 * Returns : JB_ERR_OK on success, or
1442 * JB_ERR_MEMORY on out-of-memory error.
1444 *********************************************************************/
1445 jb_err server_content_md5(struct client_state *csp, char **header)
1447 if (csp->flags & CSP_FLAG_MODIFIED)
1449 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1456 /*********************************************************************
1458 * Function : server_content_disposition
1460 * Description : If enabled, blocks or modifies the "content-disposition" header.
1461 * Called from `sed'.
1464 * 1 : csp = Current client state (buffers, headers, etc...)
1465 * 2 : header = On input, pointer to header to modify.
1466 * On output, pointer to the modified header, or NULL
1467 * to remove the header. This function frees the
1468 * original string if necessary.
1470 * Returns : JB_ERR_OK on success, or
1471 * JB_ERR_MEMORY on out-of-memory error.
1473 *********************************************************************/
1474 jb_err server_content_disposition(struct client_state *csp, char **header)
1479 * Are we messing with the content-disposition header?
1481 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1487 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1489 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1492 * Blocking content-disposition header
1494 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1501 * Replacing content-disposition header
1504 *header = strdup("content-disposition: ");
1505 string_append(header, newval);
1507 if (*header == NULL)
1509 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1513 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1516 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1519 /*********************************************************************
1521 * Function : server_last_modified
1523 * Description : Changes Last-Modified header to the actual date
1524 * to help hide-if-modified-since.
1525 * Called from `sed'.
1528 * 1 : csp = Current client state (buffers, headers, etc...)
1529 * 2 : header = On input, pointer to header to modify.
1530 * On output, pointer to the modified header, or NULL
1531 * to remove the header. This function frees the
1532 * original string if necessary.
1534 * Returns : JB_ERR_OK on success, or
1535 * JB_ERR_MEMORY on out-of-memory error.
1537 *********************************************************************/
1538 jb_err server_last_modified(struct client_state *csp, char **header)
1541 char buf[BUFFER_SIZE];
1544 #ifdef HAVE_GMTIME_R
1547 struct tm *timeptr = NULL;
1548 time_t now, last_modified;
1550 long int days, hours, minutes, seconds;
1553 * Are we messing with the Last-Modified header?
1555 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1561 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1563 if (0 == strcmpic(newval, "block") )
1566 * Blocking Last-Modified header. Useless but why not.
1568 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1572 else if (0 == strcmpic(newval, "reset-to-request-time"))
1575 * Setting Last-Modified Header to now.
1577 get_http_time(0, buf);
1579 *header = strdup("Last-Modified: ");
1580 string_append(header, buf);
1582 if (*header == NULL)
1584 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1588 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1591 else if (0 == strcmpic(newval, "randomize"))
1593 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1595 #ifdef HAVE_GMTIME_R
1596 timeptr = gmtime_r(&now, &gmt);
1597 #elif FEATURE_PTHREAD
1598 pthread_mutex_lock(&gmtime_mutex);
1599 timeptr = gmtime(&now);
1600 pthread_mutex_unlock(&gmtime_mutex);
1602 timeptr = gmtime(&now);
1604 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
1606 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1611 rtime = difftime(now, last_modified);
1614 rtime = pick_from_range(rtime);
1615 last_modified += rtime;
1616 #ifdef HAVE_GMTIME_R
1617 timeptr = gmtime_r(&last_modified, &gmt);
1618 #elif FEATURE_PTHREAD
1619 pthread_mutex_lock(&gmtime_mutex);
1620 timeptr = gmtime(&last_modified);
1621 pthread_mutex_unlock(&gmtime_mutex);
1623 timeptr = gmtime(&last_modified);
1625 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1627 *header = strdup("Last-Modified: ");
1628 string_append(header, newheader);
1630 if (*header == NULL)
1632 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
1633 return JB_ERR_MEMORY;
1636 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1638 days = rtime / (3600 * 24);
1639 hours = rtime / 3600 % 24;
1640 minutes = rtime / 60 % 60;
1641 seconds = rtime % 60;
1643 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1644 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1645 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1650 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1658 /*********************************************************************
1660 * Function : client_accept_encoding
1662 * Description : Rewrite the client's Accept-Encoding header so that
1663 * if doesn't allow compression, if the action applies.
1664 * Note: For HTTP/1.0 the absence of the header is enough.
1667 * 1 : csp = Current client state (buffers, headers, etc...)
1668 * 2 : header = On input, pointer to header to modify.
1669 * On output, pointer to the modified header, or NULL
1670 * to remove the header. This function frees the
1671 * original string if necessary.
1673 * Returns : JB_ERR_OK on success, or
1674 * JB_ERR_MEMORY on out-of-memory error.
1676 *********************************************************************/
1677 jb_err client_accept_encoding(struct client_state *csp, char **header)
1679 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1681 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1685 /* Temporarily disable the correct behaviour to
1686 * work around a PHP bug.
1688 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1690 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1691 * if (*header == NULL)
1693 * return JB_ERR_MEMORY;
1704 /*********************************************************************
1706 * Function : client_te
1708 * Description : Rewrite the client's TE header so that
1709 * if doesn't allow compression, if the action applies.
1712 * 1 : csp = Current client state (buffers, headers, etc...)
1713 * 2 : header = On input, pointer to header to modify.
1714 * On output, pointer to the modified header, or NULL
1715 * to remove the header. This function frees the
1716 * original string if necessary.
1718 * Returns : JB_ERR_OK on success, or
1719 * JB_ERR_MEMORY on out-of-memory error.
1721 *********************************************************************/
1722 jb_err client_te(struct client_state *csp, char **header)
1724 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1727 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1733 /*********************************************************************
1735 * Function : client_referrer
1737 * Description : Handle the "referer" config setting properly.
1738 * Called from `sed'.
1741 * 1 : csp = Current client state (buffers, headers, etc...)
1742 * 2 : header = On input, pointer to header to modify.
1743 * On output, pointer to the modified header, or NULL
1744 * to remove the header. This function frees the
1745 * original string if necessary.
1747 * Returns : JB_ERR_OK on success, or
1748 * JB_ERR_MEMORY on out-of-memory error.
1750 *********************************************************************/
1751 jb_err client_referrer(struct client_state *csp, char **header)
1758 #ifdef FEATURE_FORCE_LOAD
1759 /* Since the referrer can include the prefix even
1760 * if the request itself is non-forced, we must
1761 * clean it unconditionally
1763 strclean(*header, FORCE_PREFIX);
1764 #endif /* def FEATURE_FORCE_LOAD */
1767 * Are we sending referer?
1769 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1774 newval = csp->action->string[ACTION_STRING_REFERER];
1776 if ((0 != strcmpic(newval, "conditional-block")))
1780 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1785 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1788 else if (0 == strcmpic(newval, "conditional-block"))
1791 * Block referer if host has changed.
1794 if (NULL == (host = strdup(csp->http->hostport)))
1797 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1798 return JB_ERR_MEMORY;
1800 if (NULL == (referer = strdup(*header)))
1804 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1805 return JB_ERR_MEMORY;
1807 hostlenght = strlen(host);
1808 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1810 /*Shorten referer to make sure the referer is blocked
1811 *if www.example.org/www.example.com-shall-see-the-referer/
1812 *links to www.example.com/
1814 referer[hostlenght+17] = '\0';
1816 if ( 0 == strstr(referer, host)) /*Host has changed*/
1818 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1823 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1829 else if (0 != strcmpic(newval, "forge"))
1832 * We have a specific (fixed) referer we want to send.
1834 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1836 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1838 *header = strdup("Referer: ");
1839 string_append(header, newval);
1840 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1842 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1847 * Forge a referer as http://[hostname:port of REQUEST]/
1848 * to fool stupid checks for in-site links
1851 *header = strdup("Referer: http://");
1852 string_append(header, csp->http->hostport);
1853 string_append(header, "/");
1854 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1856 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1860 /*********************************************************************
1862 * Function : client_accept_language
1864 * Description : Handle the "Accept-Language" config setting properly.
1865 * Called from `sed'.
1868 * 1 : csp = Current client state (buffers, headers, etc...)
1869 * 2 : header = On input, pointer to header to modify.
1870 * On output, pointer to the modified header, or NULL
1871 * to remove the header. This function frees the
1872 * original string if necessary.
1874 * Returns : JB_ERR_OK on success, or
1875 * JB_ERR_MEMORY on out-of-memory error.
1877 *********************************************************************/
1878 jb_err client_accept_language(struct client_state *csp, char **header)
1883 * Are we messing with the Accept-Language?
1885 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1887 /*I don't think so*/
1891 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1893 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1896 * Blocking Accept-Language header
1898 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1905 * Replacing Accept-Language header
1908 *header = strdup("Accept-Language: ");
1909 string_append(header, newval);
1911 if (*header == NULL)
1913 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1917 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1920 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1923 /*********************************************************************
1925 * Function : crunch_client_header
1927 * Description : Crunch client header if it matches a string supplied by the
1928 * user. Called from `sed'.
1931 * 1 : csp = Current client state (buffers, headers, etc...)
1932 * 2 : header = On input, pointer to header to modify.
1933 * On output, pointer to the modified header, or NULL
1934 * to remove the header. This function frees the
1935 * original string if necessary.
1937 * Returns : JB_ERR_OK on success and always succeeds
1939 *********************************************************************/
1940 jb_err crunch_client_header(struct client_state *csp, char **header)
1942 const char *crunch_pattern;
1943 /*Is there a header to crunch*/
1945 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1947 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1949 /*Is the current header the lucky one?*/
1950 if (strstr(*header, crunch_pattern))
1952 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1960 /*********************************************************************
1962 * Function : client_uagent
1964 * Description : Handle the "user-agent" config setting properly
1965 * and remember its original value to enable browser
1966 * bug workarounds. Called from `sed'.
1969 * 1 : csp = Current client state (buffers, headers, etc...)
1970 * 2 : header = On input, pointer to header to modify.
1971 * On output, pointer to the modified header, or NULL
1972 * to remove the header. This function frees the
1973 * original string if necessary.
1975 * Returns : JB_ERR_OK on success, or
1976 * JB_ERR_MEMORY on out-of-memory error.
1978 *********************************************************************/
1979 jb_err client_uagent(struct client_state *csp, char **header)
1983 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1988 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1995 *header = strdup("User-Agent: ");
1996 string_append(header, newval);
1998 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2000 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2003 /*********************************************************************
2005 * Function : client_ua
2007 * Description : Handle "ua-" headers properly. Called from `sed'.
2010 * 1 : csp = Current client state (buffers, headers, etc...)
2011 * 2 : header = On input, pointer to header to modify.
2012 * On output, pointer to the modified header, or NULL
2013 * to remove the header. This function frees the
2014 * original string if necessary.
2016 * Returns : JB_ERR_OK on success, or
2017 * JB_ERR_MEMORY on out-of-memory error.
2019 *********************************************************************/
2020 jb_err client_ua(struct client_state *csp, char **header)
2022 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2024 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2032 /*********************************************************************
2034 * Function : client_from
2036 * Description : Handle the "from" config setting properly.
2037 * Called from `sed'.
2040 * 1 : csp = Current client state (buffers, headers, etc...)
2041 * 2 : header = On input, pointer to header to modify.
2042 * On output, pointer to the modified header, or NULL
2043 * to remove the header. This function frees the
2044 * original string if necessary.
2046 * Returns : JB_ERR_OK on success, or
2047 * JB_ERR_MEMORY on out-of-memory error.
2049 *********************************************************************/
2050 jb_err client_from(struct client_state *csp, char **header)
2054 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2061 newval = csp->action->string[ACTION_STRING_FROM];
2064 * Are we blocking the e-mail address?
2066 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2068 log_error(LOG_LEVEL_HEADER, "crunched From!");
2072 log_error(LOG_LEVEL_HEADER, " modified");
2074 *header = strdup("From: ");
2075 string_append(header, newval);
2077 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2081 /*********************************************************************
2083 * Function : client_send_cookie
2085 * Description : Handle the "cookie" header properly. Called from `sed'.
2086 * If cookie is accepted, add it to the cookie_list,
2087 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2090 * 1 : csp = Current client state (buffers, headers, etc...)
2091 * 2 : header = On input, pointer to header to modify.
2092 * On output, pointer to the modified header, or NULL
2093 * to remove the header. This function frees the
2094 * original string if necessary.
2096 * Returns : JB_ERR_OK on success, or
2097 * JB_ERR_MEMORY on out-of-memory error.
2099 *********************************************************************/
2100 jb_err client_send_cookie(struct client_state *csp, char **header)
2102 jb_err result = JB_ERR_OK;
2104 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2106 /* strlen("cookie: ") == 8 */
2107 result = enlist(csp->cookie_list, *header + 8);
2111 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2115 * Always remove the cookie here. The cookie header
2116 * will be sent at the end of the header.
2124 /*********************************************************************
2126 * Function : client_x_forwarded
2128 * Description : Handle the "x-forwarded-for" config setting properly,
2129 * also used in the add_client_headers list. Called from `sed'.
2132 * 1 : csp = Current client state (buffers, headers, etc...)
2133 * 2 : header = On input, pointer to header to modify.
2134 * On output, pointer to the modified header, or NULL
2135 * to remove the header. This function frees the
2136 * original string if necessary.
2138 * Returns : JB_ERR_OK on success, or
2139 * JB_ERR_MEMORY on out-of-memory error.
2141 *********************************************************************/
2142 jb_err client_x_forwarded(struct client_state *csp, char **header)
2144 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2146 /* Save it so we can re-add it later */
2147 freez(csp->x_forwarded);
2148 csp->x_forwarded = *header;
2151 * Always set *header = NULL, since this information
2152 * will be sent at the end of the header.
2159 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2166 /*********************************************************************
2168 * Function : client_max_forwards
2170 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2171 * from the value of the Max-Forwards header field.
2174 * 1 : csp = Current client state (buffers, headers, etc...)
2175 * 2 : header = On input, pointer to header to modify.
2176 * On output, pointer to the modified header, or NULL
2177 * to remove the header. This function frees the
2178 * original string if necessary.
2180 * Returns : JB_ERR_OK on success, or
2181 * JB_ERR_MEMORY on out-of-memory error.
2183 *********************************************************************/
2184 jb_err client_max_forwards(struct client_state *csp, char **header)
2186 unsigned int max_forwards;
2188 if ((0 == strcmpic(csp->http->gpc, "trace"))
2189 || (0 == strcmpic(csp->http->gpc, "options")))
2191 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2193 if (max_forwards-- >= 1)
2195 sprintf(*header, "Max-Forwards: %u", max_forwards);
2196 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2200 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2209 /*********************************************************************
2211 * Function : client_host
2213 * Description : If the request URI did not contain host and
2214 * port information, parse and evaluate the Host
2217 * Also, kill ill-formed HOST: headers as sent by
2218 * Apple's iTunes software when used with a proxy.
2221 * 1 : csp = Current client state (buffers, headers, etc...)
2222 * 2 : header = On input, pointer to header to modify.
2223 * On output, pointer to the modified header, or NULL
2224 * to remove the header. This function frees the
2225 * original string if necessary.
2227 * Returns : JB_ERR_OK on success, or
2228 * JB_ERR_MEMORY on out-of-memory error.
2230 *********************************************************************/
2231 jb_err client_host(struct client_state *csp, char **header)
2236 * If the header field name is all upper-case, chances are that it's
2237 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2238 * not a problem -- they are regenerated later.
2240 if ((*header)[1] == 'O')
2242 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2247 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2248 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2251 if (NULL == (p = strdup((*header)+6)))
2253 return JB_ERR_MEMORY;
2256 if (NULL == (q = strdup(p)))
2259 return JB_ERR_MEMORY;
2262 freez(csp->http->hostport);
2263 csp->http->hostport = p;
2264 freez(csp->http->host);
2265 csp->http->host = q;
2266 q = strchr(csp->http->host, ':');
2269 /* Terminate hostname and evaluate port string */
2271 csp->http->port = atoi(q);
2275 csp->http->port = csp->http->ssl ? 443 : 80;
2278 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2279 csp->http->hostport, csp->http->host, csp->http->port);
2285 /*********************************************************************
2287 * Function : client_if_modified_since
2289 * Description : Remove or modify the If-Modified-Since header.
2292 * 1 : csp = Current client state (buffers, headers, etc...)
2293 * 2 : header = On input, pointer to header to modify.
2294 * On output, pointer to the modified header, or NULL
2295 * to remove the header. This function frees the
2296 * original string if necessary.
2298 * Returns : JB_ERR_OK on success, or
2299 * JB_ERR_MEMORY on out-of-memory error.
2301 *********************************************************************/
2302 jb_err client_if_modified_since(struct client_state *csp, char **header)
2305 #ifdef HAVE_GMTIME_R
2308 struct tm *timeptr = NULL;
2312 long int hours, minutes, seconds;
2316 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2319 * The client got an error message because of a temporary problem,
2320 * the problem is gone and the client now tries to revalidate our
2321 * error message on the real server. The revalidation would always
2322 * end with the transmission of the whole document and there is
2323 * no need to expose the bogus If-Modified-Since header.
2325 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2328 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2330 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2332 if ((0 == strcmpic(newval, "block")))
2334 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2337 else /* add random value */
2339 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2341 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2346 rtime = strtol(newval, &endptr, 0);
2349 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2350 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2357 rtime = pick_from_range(rtime);
2361 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2364 tm += rtime * (negative ? -1 : 1);
2365 #ifdef HAVE_GMTIME_R
2366 timeptr = gmtime_r(&tm, &gmt);
2367 #elif FEATURE_PTHREAD
2368 pthread_mutex_lock(&gmtime_mutex);
2369 timeptr = gmtime(&tm);
2370 pthread_mutex_unlock(&gmtime_mutex);
2372 timeptr = gmtime(&tm);
2374 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2377 *header = strdup("If-Modified-Since: ");
2378 string_append(header, newheader);
2380 if (*header == NULL)
2382 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2383 return JB_ERR_MEMORY;
2386 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2388 hours = rtime / 3600;
2389 minutes = rtime / 60 % 60;
2390 seconds = rtime % 60;
2392 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2393 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2394 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2403 /*********************************************************************
2405 * Function : client_if_none_match
2407 * Description : Remove the If-None-Match header.
2410 * 1 : csp = Current client state (buffers, headers, etc...)
2411 * 2 : header = On input, pointer to header to modify.
2412 * On output, pointer to the modified header, or NULL
2413 * to remove the header. This function frees the
2414 * original string if necessary.
2416 * Returns : JB_ERR_OK on success, or
2417 * JB_ERR_MEMORY on out-of-memory error.
2419 *********************************************************************/
2420 jb_err client_if_none_match(struct client_state *csp, char **header)
2422 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2424 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2431 /*********************************************************************
2433 * Function : client_x_filter
2435 * Description : Disables filtering if the client set "X-Filter: No".
2436 * Called from `sed'.
2439 * 1 : csp = Current client state (buffers, headers, etc...)
2440 * 2 : header = On input, pointer to header to modify.
2441 * On output, pointer to the modified header, or NULL
2442 * to remove the header. This function frees the
2443 * original string if necessary.
2445 * Returns : JB_ERR_OK on success
2447 *********************************************************************/
2448 jb_err client_x_filter(struct client_state *csp, char **header)
2450 if ( 0 == strcmpic(*header, "X-Filter: No"))
2452 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2454 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2458 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2460 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to fetch without filtering!");
2464 csp->content_type = CT_TABOO;
2465 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
2466 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
2467 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
2469 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2476 /* the following functions add headers directly to the header list */
2478 /*********************************************************************
2480 * Function : client_host_adder
2482 * Description : Adds the Host: header field if it is missing.
2483 * Called from `sed'.
2486 * 1 : csp = Current client state (buffers, headers, etc...)
2488 * Returns : JB_ERR_OK on success, or
2489 * JB_ERR_MEMORY on out-of-memory error.
2491 *********************************************************************/
2492 jb_err client_host_adder(struct client_state *csp)
2497 if ( !csp->http->hostport || !*(csp->http->hostport))
2503 * remove 'user:pass@' from 'proto://user:pass@host'
2505 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2511 p = csp->http->hostport;
2514 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2515 err = enlist_unique_header(csp->headers, "Host", p);
2521 /*********************************************************************
2523 * Function : client_cookie_adder
2525 * Description : Used in the add_client_headers list. Called from `sed'.
2528 * 1 : csp = Current client state (buffers, headers, etc...)
2530 * Returns : JB_ERR_OK on success, or
2531 * JB_ERR_MEMORY on out-of-memory error.
2533 *********************************************************************/
2534 jb_err client_cookie_adder(struct client_state *csp)
2536 struct list_entry *lst;
2538 struct list_entry *list1 = csp->cookie_list->first;
2539 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2540 int first_cookie = 1;
2543 if ((list1 == NULL) && (list2 == NULL))
2549 tmp = strdup("Cookie: ");
2551 for (lst = list1; lst ; lst = lst->next)
2559 string_append(&tmp, "; ");
2561 string_append(&tmp, lst->str);
2564 for (lst = list2; lst ; lst = lst->next)
2572 string_append(&tmp, "; ");
2574 string_join(&tmp, cookie_encode(lst->str));
2579 return JB_ERR_MEMORY;
2582 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2583 err = enlist(csp->headers, tmp);
2589 /*********************************************************************
2591 * Function : client_accept_encoding_adder
2593 * Description : Add an Accept-Encoding header to the client's request
2594 * that disables compression if the action applies, and
2595 * the header is not already there. Called from `sed'.
2596 * Note: For HTTP/1.0, the absence of the header is enough.
2599 * 1 : csp = Current client state (buffers, headers, etc...)
2601 * Returns : JB_ERR_OK on success, or
2602 * JB_ERR_MEMORY on out-of-memory error.
2604 *********************************************************************/
2605 jb_err client_accept_encoding_adder(struct client_state *csp)
2607 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2608 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2610 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2617 /*********************************************************************
2619 * Function : client_xtra_adder
2621 * Description : Used in the add_client_headers list. Called from `sed'.
2624 * 1 : csp = Current client state (buffers, headers, etc...)
2626 * Returns : JB_ERR_OK on success, or
2627 * JB_ERR_MEMORY on out-of-memory error.
2629 *********************************************************************/
2630 jb_err client_xtra_adder(struct client_state *csp)
2632 struct list_entry *lst;
2635 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2636 lst ; lst = lst->next)
2638 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2639 err = enlist(csp->headers, lst->str);
2651 /*********************************************************************
2653 * Function : client_x_forwarded_adder
2655 * Description : Used in the add_client_headers list. Called from `sed'.
2658 * 1 : csp = Current client state (buffers, headers, etc...)
2660 * Returns : JB_ERR_OK on success, or
2661 * JB_ERR_MEMORY on out-of-memory error.
2663 *********************************************************************/
2664 jb_err client_x_forwarded_adder(struct client_state *csp)
2669 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2674 if (csp->x_forwarded)
2676 p = strdup(csp->x_forwarded);
2677 string_append(&p, ", ");
2681 p = strdup("X-Forwarded-For: ");
2683 string_append(&p, csp->ip_addr_str);
2687 return JB_ERR_MEMORY;
2690 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2691 err = enlist(csp->headers, p);
2698 /*********************************************************************
2700 * Function : connection_close_adder
2702 * Description : Adds a "Connection: close" header to csp->headers
2703 * as a temporary fix for the needed but missing HTTP/1.1
2704 * support. Called from `sed'.
2705 * FIXME: This whole function shouldn't be neccessary!
2708 * 1 : csp = Current client state (buffers, headers, etc...)
2710 * Returns : JB_ERR_OK on success, or
2711 * JB_ERR_MEMORY on out-of-memory error.
2713 *********************************************************************/
2714 jb_err connection_close_adder(struct client_state *csp)
2716 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2717 return enlist(csp->headers, "Connection: close");
2721 /*********************************************************************
2723 * Function : server_http
2725 * Description : - Save the HTTP Status into csp->http->status
2726 * - Set CT_TABOO to prevent filtering if the answer
2727 * is a partial range (HTTP status 206)
2728 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2732 * 1 : csp = Current client state (buffers, headers, etc...)
2733 * 2 : header = On input, pointer to header to modify.
2734 * On output, pointer to the modified header, or NULL
2735 * to remove the header. This function frees the
2736 * original string if necessary.
2738 * Returns : JB_ERR_OK on success, or
2739 * JB_ERR_MEMORY on out-of-memory error.
2741 *********************************************************************/
2742 jb_err server_http(struct client_state *csp, char **header)
2744 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2745 if (csp->http->status == 206)
2747 csp->content_type = CT_TABOO;
2750 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2753 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2760 /*********************************************************************
2762 * Function : server_set_cookie
2764 * Description : Handle the server "cookie" header properly.
2765 * Log cookie to the jar file. Then "crunch" it,
2766 * or accept it. Called from `sed'.
2769 * 1 : csp = Current client state (buffers, headers, etc...)
2770 * 2 : header = On input, pointer to header to modify.
2771 * On output, pointer to the modified header, or NULL
2772 * to remove the header. This function frees the
2773 * original string if necessary.
2775 * Returns : JB_ERR_OK on success, or
2776 * JB_ERR_MEMORY on out-of-memory error.
2778 *********************************************************************/
2779 jb_err server_set_cookie(struct client_state *csp, char **header)
2781 #ifdef FEATURE_COOKIE_JAR
2782 if (csp->config->jar)
2785 * Write timestamp into outbuf.
2787 * Complex because not all OSs have tm_gmtoff or
2788 * the %z field in strftime()
2790 char tempbuf[ BUFFER_SIZE ];
2794 #ifdef HAVE_LOCALTIME_R
2795 tm_now = *localtime_r(&now, &tm_now);
2796 #elif FEATURE_PTHREAD
2797 pthread_mutex_lock(&localtime_mutex);
2798 tm_now = *localtime (&now);
2799 pthread_mutex_unlock(&localtime_mutex);
2801 tm_now = *localtime (&now);
2803 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2805 /* strlen("set-cookie: ") = 12 */
2806 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2808 #endif /* def FEATURE_COOKIE_JAR */
2810 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2812 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2813 return crumble(csp, header);
2815 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2817 /* Flag whether or not to log a message */
2820 /* A variable to store the tag we're working on */
2823 /* Skip "Set-Cookie:" (11 characters) in header */
2824 cur_tag = *header + 11;
2826 /* skip whitespace between "Set-Cookie:" and value */
2827 while (*cur_tag && ijb_isspace(*cur_tag))
2832 /* Loop through each tag in the cookie */
2836 char *next_tag = strchr(cur_tag, ';');
2837 if (next_tag != NULL)
2839 /* Skip the ';' character itself */
2842 /* skip whitespace ";" and start of tag */
2843 while (*next_tag && ijb_isspace(*next_tag))
2850 /* "Next tag" is the end of the string */
2851 next_tag = cur_tag + strlen(cur_tag);
2854 /* Is this the "Expires" tag? */
2855 if (strncmpic(cur_tag, "expires=", 8) == 0)
2857 /* Delete the tag by copying the rest of the string over it.
2858 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2859 * since the behaviour of strcpy is undefined for overlapping
2862 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2864 /* That changed the header, need to issue a log message */
2867 /* Note that the next tag has now been moved to *cur_tag,
2868 * so we do not need to update the cur_tag pointer.
2873 /* Move on to next cookie tag */
2880 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2888 #ifdef FEATURE_FORCE_LOAD
2889 /*********************************************************************
2891 * Function : strclean
2893 * Description : In-Situ-Eliminate all occurances of substring in
2897 * 1 : string = string to clean
2898 * 2 : substring = substring to eliminate
2900 * Returns : Number of eliminations
2902 *********************************************************************/
2903 int strclean(const char *string, const char *substring)
2905 int hits = 0, len = strlen(substring);
2908 while((pos = strstr(string, substring)) != NULL)
2915 while (*p++ != '\0');
2922 #endif /* def FEATURE_FORCE_LOAD */
2924 /*********************************************************************
2926 * Function : parse_header_time
2928 * Description : Transforms time inside a HTTP header into
2929 * the usual time format.
2932 * 1 : header = header to parse
2933 * 2 : tm = storage for the resulting time in seconds
2935 * Returns : Time struct containing the header time, or
2936 * NULL in case of a parsing problem.
2938 *********************************************************************/
2939 struct tm *parse_header_time(char *header, time_t *tm) {
2943 struct tm * timeptr;
2945 /* Skipping header name */
2946 timestring = strstr(header, ": ");
2947 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)
2960 /*********************************************************************
2962 * Function : get_destination_from_headers
2964 * Description : Parse the "Host:" header to get the request's destination.
2965 * Only needed if the client's request was forcefully
2966 * redirected into Privoxy.
2968 * Code mainly copied from client_host() which is currently
2969 * run too late for this purpose.
2972 * 1 : headers = List of headers (one of them hopefully being
2973 * the "Host:" header)
2974 * 2 : http = storage for the result (host, port and hostport).
2976 * Returns : JB_ERR_MEMORY in case of memory problems,
2977 * JB_ERR_PARSE if the host header couldn't be found,
2978 * JB_ERR_OK otherwise.
2980 *********************************************************************/
2981 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
2987 host = get_header_value(headers, "Host:");
2991 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
2992 return JB_ERR_PARSE;
2995 if (NULL == (p = strdup((host))))
2997 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
2998 return JB_ERR_MEMORY;
3001 if (NULL == (q = strdup(p)))
3004 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3005 return JB_ERR_MEMORY;
3008 freez(http->hostport);
3012 q = strchr(http->host, ':');
3015 /* Terminate hostname and evaluate port string */
3017 http->port = atoi(q);
3021 http->port = http->ssl ? 443 : 80;
3024 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header: %s = %s:%d",
3025 http->hostport, http->host, http->port);