1 const char parsers_rcs[] = "$Id: parsers.c,v 1.81 2006/12/31 22:21:33 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.81 2006/12/31 22:21:33 fabiankeil
49 * Skip empty filter files in filter_header()
50 * but don't ignore the ones that come afterwards.
51 * Fixes BR 1619208, this time for real.
53 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
54 * Reverted parts of my last commit
55 * to keep error handling working.
57 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
58 * Fixed gcc43 conversion warnings.
60 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
61 * Bringing back the "useless" localtime() call
62 * I removed in revision 1.67. On some platforms
63 * it's necessary to prevent time zone offsets.
65 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
66 * Rebuild request URL in get_destination_from_headers()
67 * to make sure redirect{pcrs command} works as expected
68 * for intercepted requests.
70 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
71 * Added get_destination_from_headers().
73 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
74 * Make pthread mutex locking more generic. Instead of
75 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
76 * and use mutex locking unless there is an _r function
77 * available. Better safe than sorry.
79 * Fixes "./configure --disable-pthread" and should result
80 * in less threading-related problems on pthread-using platforms,
81 * but it still doesn't fix BR#1122404.
83 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
84 * The special header "X-Filter: No" now disables
85 * header filtering as well.
87 * Revision 1.73 2006/09/23 13:26:38 roro
88 * Replace TABs by spaces in source code.
90 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
91 * Don't print a log message every time filter_headers is
92 * entered or left. It only creates noise without any real
95 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
96 * Fix +hide-if-modified-since{-n}.
98 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
99 * Have hide-if-modified-since interpret the random
100 * range value as minutes instead of hours. Allows
101 * more fine-grained configuration.
103 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
104 * Always have parse_header_time return a pointer
105 * that actual makes sense, even though we currently
106 * only need it to detect problems.
108 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
109 * Added config option enable-remote-http-toggle
110 * to specify if Privoxy should recognize special
111 * headers (currently only X-Filter) to change its
112 * behaviour. Disabled by default.
114 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
115 * After filtering de-chunked instances, remove
116 * "Transfer-Encoding" header entirely instead of changing
117 * it to "Transfer-Encoding: identity", which is invalid.
118 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
120 * Don't use localtime in parse_header_time. An empty time struct
121 * is good enough, it gets overwritten by strptime anyway.
123 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
124 * Use gmtime_r if available, fallback to gmtime with mutex
125 * protection for MacOSX and use vanilla gmtime for the rest.
127 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
128 * Changed client_referrer to use the right type (size_t) for
129 * hostlenght and to shorten the temporary referrer string with
130 * '\0' instead of adding a useless line break.
132 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
133 * - Back to timegm() using GnuPG's replacement if necessary.
134 * Using mktime() and localtime() could add a on hour offset if
135 * the randomize factor was big enough to lead to a summer/wintertime
138 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
140 * - Moved randomization code into pick_from_range().
142 * - Changed parse_header_time definition.
143 * time_t isn't guaranteed to be signed and
144 * if it isn't, -1 isn't available as error code.
145 * Changed some variable types in client_if_modified_since()
146 * because of the same reason.
148 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
149 * OS/2 compilation compatibility fixups
151 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
152 * Changed include from strptime.c to strptime.h
154 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
155 * Split filter-headers{} into filter-client-headers{}
156 * and filter-server-headers{}.
157 * Added parse_header_time() to share some code.
158 * Replaced timegm() with mktime().
160 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
161 * Windows service integration
163 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
164 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
166 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
167 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
168 * with what was really the latest development (the v_3_0_branch branch)
170 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
171 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
173 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
174 * Add the ability to check jpeg images for invalid
175 * lengths of comment blocks. Defensive strategy
176 * against the exploit:
177 * Microsoft Security Bulletin MS04-028
178 * Buffer Overrun in JPEG Processing (GDI+) Could
179 * Allow Code Execution (833987)
180 * Enabled with +inspect-jpegs in actions files.
182 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
183 * Excluded text/plain objects from filtering. This fixes a
184 * couple of client-crashing, download corruption and
185 * Privoxy performance issues, whose root cause lies in
186 * web servers labelling content of unknown type as text/plain.
188 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
189 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
191 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
192 * Completing the previous change
194 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
195 * Added temporary workaround for bug in PHP < 4.2.3
197 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
198 * 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.
200 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
201 * Fix typo: supressed -> suppressed
203 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
204 * Improved cookie logging
206 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
207 * Added basic support for OPTIONS and TRACE HTTP methods:
208 * - New parser function client_max_forwards which decrements
209 * the Max-Forwards HTTP header field of OPTIONS and TRACE
210 * requests by one before forwarding
211 * - New parser function client_host which extracts the host
212 * and port information from the HTTP header field if the
213 * request URI was not absolute
214 * - Don't crumble and re-add the Host: header, but only generate
215 * and append if missing
217 * Revision 1.56 2002/05/12 15:34:22 jongfoster
218 * Fixing typo in a comment
220 * Revision 1.55 2002/05/08 16:01:07 oes
221 * Optimized add_to_iob:
222 * - Use realloc instead of malloc(), memcpy(), free()
223 * - Expand to powers of two if possible, to get
224 * O(log n) reallocs instead of O(n).
225 * - Moved check for buffer limit here from chat
226 * - Report failure via returncode
228 * Revision 1.54 2002/04/02 15:03:16 oes
229 * Tiny code cosmetics
231 * Revision 1.53 2002/03/26 22:29:55 swa
232 * we have a new homepage!
234 * Revision 1.52 2002/03/24 13:25:43 swa
235 * name change related issues
237 * Revision 1.51 2002/03/13 00:27:05 jongfoster
240 * Revision 1.50 2002/03/12 01:45:35 oes
241 * More verbose logging
243 * Revision 1.49 2002/03/09 20:03:52 jongfoster
244 * - Making various functions return int rather than size_t.
245 * (Undoing a recent change). Since size_t is unsigned on
246 * Windows, functions like read_socket that return -1 on
247 * error cannot return a size_t.
249 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
250 * crashes, and also frequently caused JB to jump to 100%
251 * CPU and stay there. (Because it thought it had just
252 * read ((unsigned)-1) == 4Gb of data...)
254 * - The signature of write_socket has changed, it now simply
255 * returns success=0/failure=nonzero.
257 * - Trying to get rid of a few warnings --with-debug on
258 * Windows, I've introduced a new type "jb_socket". This is
259 * used for the socket file descriptors. On Windows, this
260 * is SOCKET (a typedef for unsigned). Everywhere else, it's
261 * an int. The error value can't be -1 any more, so it's
262 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
263 * Windows it maps to the #define INVALID_SOCKET.)
265 * - The signature of bind_port has changed.
267 * Revision 1.48 2002/03/07 03:46:53 oes
268 * Fixed compiler warnings etc
270 * Revision 1.47 2002/02/20 23:15:13 jongfoster
271 * Parsing functions now handle out-of-memory gracefully by returning
274 * Revision 1.46 2002/01/17 21:03:47 jongfoster
275 * Moving all our URL and URL pattern parsing code to urlmatch.c.
277 * Revision 1.45 2002/01/09 14:33:03 oes
278 * Added support for localtime_r.
280 * Revision 1.44 2001/12/14 01:22:54 steudten
281 * Remove 'user:pass@' from 'proto://user:pass@host' for the
282 * new added header 'Host: ..'. (See Req ID 491818)
284 * Revision 1.43 2001/11/23 00:26:38 jongfoster
285 * Fixing two really stupid errors in my previous commit
287 * Revision 1.42 2001/11/22 21:59:30 jongfoster
288 * Adding code to handle +no-cookies-keep
290 * Revision 1.41 2001/11/05 23:43:05 steudten
291 * Add time+date to log files.
293 * Revision 1.40 2001/10/26 20:13:09 jongfoster
294 * ctype.h is needed in Windows, too.
296 * Revision 1.39 2001/10/26 17:40:04 oes
297 * Introduced get_header_value()
298 * Removed http->user_agent, csp->referrer and csp->accept_types
299 * Removed client_accept()
301 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
302 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
303 * threads to call select() simultaneously. So, it's time to do a real, live,
304 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
305 * (native). Both versions will work, but using __OS2__ offers multi-threading.
307 * Revision 1.37 2001/10/23 21:36:02 jongfoster
308 * Documenting sed()'s error behaviou (doc change only)
310 * Revision 1.36 2001/10/13 12:51:51 joergs
311 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
312 * force-load), instead crumble Host: and add it (again) in client_host_adder
313 * (in case we get a HTTP/1.0 request without Host: header and forward it to
314 * a HTTP/1.1 server/proxy).
316 * Revision 1.35 2001/10/09 22:39:21 jongfoster
317 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
320 * Revision 1.34 2001/10/07 18:50:55 oes
321 * Added server_content_encoding, renamed server_transfer_encoding
323 * Revision 1.33 2001/10/07 18:04:49 oes
324 * Changed server_http11 to server_http and its pattern to "HTTP".
325 * Additional functionality: it now saves the HTTP status into
326 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
328 * Revision 1.32 2001/10/07 15:43:28 oes
329 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
330 * client_te and client_accept_encoding_adder, triggered by the new
331 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
332 * changed to allow only identity and chunked, and the TE header is
333 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
335 * parse_http_request no longer does anything than parsing. The rewriting
336 * of http->cmd and version mangling are gone. It now also recognizes
337 * the put and delete methods and saves the url in http->url. Removed
340 * renamed content_type and content_length to have the server_ prefix
342 * server_content_type now only works if csp->content_type != CT_TABOO
344 * added server_transfer_encoding, which
345 * - Sets CT_TABOO to prohibit filtering if encoding compresses
346 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
347 * - Change from "chunked" to "identity" if body was chunked
348 * but has been de-chunked for filtering.
350 * added server_content_md5 which crunches any Content-MD5 headers
351 * if the body was modified.
353 * made server_http11 conditional on +downgrade action
355 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
357 * Revision 1.31 2001/10/05 14:25:02 oes
358 * Crumble Keep-Alive from Server
360 * Revision 1.30 2001/09/29 12:56:03 joergs
361 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
363 * Revision 1.29 2001/09/24 21:09:24 jongfoster
364 * Fixing 2 memory leaks that Guy spotted, where the paramater to
365 * enlist() was not being free()d.
367 * Revision 1.28 2001/09/22 16:32:28 jongfoster
368 * Removing unused #includes.
370 * Revision 1.27 2001/09/20 15:45:25 steudten
372 * add casting from size_t to int for printf()
373 * remove local variable shadow s2
375 * Revision 1.26 2001/09/16 17:05:14 jongfoster
376 * Removing unused #include showarg.h
378 * Revision 1.25 2001/09/16 13:21:27 jongfoster
379 * Changes to use new list functions.
381 * Revision 1.24 2001/09/13 23:05:50 jongfoster
382 * Changing the string paramater to the header parsers a "const".
384 * Revision 1.23 2001/09/12 18:08:19 steudten
386 * In parse_http_request() header rewriting miss the host value, so
387 * from http://www.mydomain.com the result was just " / " not
388 * http://www.mydomain.com/ in case we forward.
390 * Revision 1.22 2001/09/10 10:58:53 oes
391 * Silenced compiler warnings
393 * Revision 1.21 2001/07/31 14:46:00 oes
394 * - Persistant connections now suppressed
395 * - sed() no longer appends empty header to csp->headers
397 * Revision 1.20 2001/07/30 22:08:36 jongfoster
398 * Tidying up #defines:
399 * - All feature #defines are now of the form FEATURE_xxx
400 * - Permanently turned off WIN_GUI_EDIT
401 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
403 * Revision 1.19 2001/07/25 17:21:54 oes
404 * client_uagent now saves copy of User-Agent: header value
406 * Revision 1.18 2001/07/13 14:02:46 oes
407 * - Included fix to repair broken HTTP requests that
408 * don't contain a path, not even '/'.
409 * - Removed all #ifdef PCRS
410 * - content_type now always inspected and classified as
411 * text, gif or other.
412 * - formatting / comments
414 * Revision 1.17 2001/06/29 21:45:41 oes
415 * Indentation, CRLF->LF, Tab-> Space
417 * Revision 1.16 2001/06/29 13:32:42 oes
419 * - Adapted free_http_request
420 * - Removed logentry from cancelled commit
422 * Revision 1.15 2001/06/03 19:12:38 oes
423 * deleted const struct interceptors
425 * Revision 1.14 2001/06/01 18:49:17 jongfoster
426 * Replaced "list_share" with "list" - the tiny memory gain was not
427 * worth the extra complexity.
429 * Revision 1.13 2001/05/31 21:30:33 jongfoster
430 * Removed list code - it's now in list.[ch]
431 * Renamed "permission" to "action", and changed many features
432 * to use the actions file rather than the global config.
434 * Revision 1.12 2001/05/31 17:33:13 oes
438 * Revision 1.11 2001/05/29 20:11:19 joergs
439 * '/ * inside comment' warning removed.
441 * Revision 1.10 2001/05/29 09:50:24 jongfoster
442 * Unified blocklist/imagelist/permissionslist.
443 * File format is still under discussion, but the internal changes
446 * Also modified interceptor behaviour:
447 * - We now intercept all URLs beginning with one of the following
448 * prefixes (and *only* these prefixes):
450 * * http://ijbswa.sf.net/config/
451 * * http://ijbswa.sourceforge.net/config/
452 * - New interceptors "home page" - go to http://i.j.b/ to see it.
453 * - Internal changes so that intercepted and fast redirect pages
454 * are not replaced with an image.
455 * - Interceptors now have the option to send a binary page direct
456 * to the client. (i.e. ijb-send-banner uses this)
457 * - Implemented show-url-info interceptor. (Which is why I needed
458 * the above interceptors changes - a typical URL is
459 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
460 * The previous mechanism would not have intercepted that, and
461 * if it had been intercepted then it then it would have replaced
464 * Revision 1.9 2001/05/28 17:26:33 jongfoster
465 * Fixing segfault if last header was crunched.
466 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
467 * can use the cross-platform sprintf() instead.)
469 * Revision 1.8 2001/05/27 22:17:04 oes
471 * - re_process_buffer no longer writes the modified buffer
472 * to the client, which was very ugly. It now returns the
473 * buffer, which it is then written by chat.
475 * - content_length now adjusts the Content-Length: header
476 * for modified documents rather than crunch()ing it.
477 * (Length info in csp->content_length, which is 0 for
478 * unmodified documents)
480 * - For this to work, sed() is called twice when filtering.
482 * Revision 1.7 2001/05/27 13:19:06 oes
483 * Patched Joergs solution for the content-length in.
485 * Revision 1.6 2001/05/26 13:39:32 jongfoster
486 * Only crunches Content-Length header if applying RE filtering.
487 * Without this fix, Microsoft Windows Update wouldn't work.
489 * Revision 1.5 2001/05/26 00:28:36 jongfoster
490 * Automatic reloading of config file.
491 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
492 * Most of the global variables have been moved to a new
493 * struct configuration_spec, accessed through csp->config->globalname
494 * Most of the globals remaining are used by the Win32 GUI.
496 * Revision 1.4 2001/05/22 18:46:04 oes
498 * - Enabled filtering banners by size rather than URL
499 * by adding patterns that replace all standard banner
500 * sizes with the "Junkbuster" gif to the re_filterfile
502 * - Enabled filtering WebBugs by providing a pattern
503 * which kills all 1x1 images
505 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
506 * which is selected by the (nonstandard and therefore
507 * capital) letter 'U' in the option string.
508 * It causes the quantifiers to be ungreedy by default.
509 * Appending a ? turns back to greedy (!).
511 * - Added a new interceptor ijb-send-banner, which
512 * sends back the "Junkbuster" gif. Without imagelist or
513 * MSIE detection support, or if tinygif = 1, or the
514 * URL isn't recognized as an imageurl, a lame HTML
515 * explanation is sent instead.
517 * - Added new feature, which permits blocking remote
518 * script redirects and firing back a local redirect
520 * The feature is conditionally compiled, i.e. it
521 * can be disabled with --disable-fast-redirects,
522 * plus it must be activated by a "fast-redirects"
523 * line in the config file, has its own log level
524 * and of course wants to be displayed by show-proxy-args
525 * Note: Boy, all the #ifdefs in 1001 locations and
526 * all the fumbling with configure.in and acconfig.h
527 * were *way* more work than the feature itself :-(
529 * - Because a generic redirect template was needed for
530 * this, tinygif = 3 now uses the same.
532 * - Moved GIFs, and other static HTTP response templates
537 * - Removed some >400 CRs again (Jon, you really worked
540 * Revision 1.3 2001/05/20 01:21:20 jongfoster
541 * Version 2.9.4 checkin.
542 * - Merged popupfile and cookiefile, and added control over PCRS
543 * filtering, in new "permissionsfile".
544 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
545 * file error you now get a message box (in the Win32 GUI) rather
546 * than the program exiting with no explanation.
547 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
549 * - Removed tabs from "config"
550 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
551 * - Bumped up version number.
553 * Revision 1.2 2001/05/17 23:02:36 oes
554 * - Made referrer option accept 'L' as a substitute for '§'
556 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
557 * Initial import of version 2.9.3 source tree
560 *********************************************************************/
567 #include <sys/types.h>
580 #if !defined(_WIN32) && !defined(__OS2__)
586 #ifdef FEATURE_PTHREAD
588 /* jcc.h is for mutex semapores only */
589 #endif /* def FEATURE_PTHREAD */
595 #include "jbsockets.h"
596 #include "miscutil.h"
599 #ifndef HAVE_STRPTIME
600 #include "strptime.h"
603 const char parsers_h_rcs[] = PARSERS_H_VERSION;
605 /* Fix a problem with Solaris. There should be no effect on other
607 * Solaris's isspace() is a macro which uses it's argument directly
608 * as an array index. Therefore we need to make sure that high-bit
609 * characters generate +ve values, and ideally we also want to make
610 * the argument match the declared parameter type of "int".
612 * Why did they write a character function that can't take a simple
613 * "char" argument? Doh!
615 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
616 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
619 const struct parsers client_patterns[] = {
620 { "referer:", 8, client_referrer },
621 { "user-agent:", 11, client_uagent },
622 { "ua-", 3, client_ua },
623 { "from:", 5, client_from },
624 { "cookie:", 7, client_send_cookie },
625 { "x-forwarded-for:", 16, client_x_forwarded },
626 { "Accept-Encoding:", 16, client_accept_encoding },
627 { "TE:", 3, client_te },
628 { "Host:", 5, client_host },
629 { "if-modified-since:", 18, client_if_modified_since },
630 { "Keep-Alive:", 11, crumble },
631 { "connection:", 11, crumble },
632 { "proxy-connection:", 17, crumble },
633 { "max-forwards:", 13, client_max_forwards },
634 { "Accept-Language:", 16, client_accept_language },
635 { "if-none-match:", 14, client_if_none_match },
636 { "X-Filter:", 9, client_x_filter },
637 { "*", 0, crunch_client_header },
638 { "*", 0, filter_client_header },
642 const struct parsers server_patterns[] = {
643 { "HTTP", 4, server_http },
644 { "set-cookie:", 11, server_set_cookie },
645 { "connection:", 11, crumble },
646 { "Content-Type:", 13, server_content_type },
647 { "Content-Length:", 15, server_content_length },
648 { "Content-MD5:", 12, server_content_md5 },
649 { "Content-Encoding:", 17, server_content_encoding },
650 { "Transfer-Encoding:", 18, server_transfer_coding },
651 { "Keep-Alive:", 11, crumble },
652 { "content-disposition:", 20, server_content_disposition },
653 { "Last-Modified:", 14, server_last_modified },
654 { "*", 0, crunch_server_header },
655 { "*", 0, filter_server_header },
659 const struct parsers server_patterns_light[] = {
660 { "Content-Length:", 15, server_content_length },
661 { "Transfer-Encoding:", 18, server_transfer_coding },
663 { "Content-Encoding:", 17, server_content_encoding },
664 #endif /* def FEATURE_ZLIB */
668 const add_header_func_ptr add_client_headers[] = {
671 client_x_forwarded_adder,
673 /* Temporarily disabled: client_accept_encoding_adder, */
674 connection_close_adder,
679 const add_header_func_ptr add_server_headers[] = {
680 connection_close_adder,
684 /*********************************************************************
686 * Function : flush_socket
688 * Description : Write any pending "buffered" content.
691 * 1 : fd = file descriptor of the socket to read
692 * 2 : csp = Current client state (buffers, headers, etc...)
694 * Returns : On success, the number of bytes written are returned (zero
695 * indicates nothing was written). On error, -1 is returned,
696 * and errno is set appropriately. If count is zero and the
697 * file descriptor refers to a regular file, 0 will be
698 * returned without causing any other effect. For a special
699 * file, the results are not portable.
701 *********************************************************************/
702 int flush_socket(jb_socket fd, struct client_state *csp)
704 struct iob *iob = csp->iob;
705 int len = iob->eod - iob->cur;
712 if (write_socket(fd, iob->cur, (size_t)len))
716 iob->eod = iob->cur = iob->buf;
722 /*********************************************************************
724 * Function : add_to_iob
726 * Description : Add content to the buffered page, expanding the
727 * buffer if necessary.
730 * 1 : csp = Current client state (buffers, headers, etc...)
731 * 2 : buf = holds the content to be added to the page
732 * 3 : n = number of bytes to be added
734 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
735 * or buffer limit reached.
737 *********************************************************************/
738 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
740 struct iob *iob = csp->iob;
741 size_t used, offset, need, want;
744 if (n <= 0) return JB_ERR_OK;
746 used = (size_t)(iob->eod - iob->buf);
747 offset = (size_t)(iob->cur - iob->buf);
748 need = used + (size_t)n + 1;
751 * If the buffer can't hold the new data, extend it first.
752 * Use the next power of two if possible, else use the actual need.
754 if (need > csp->config->buffer_limit)
756 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
757 return JB_ERR_MEMORY;
760 if (need > iob->size)
762 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
764 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
768 else if (NULL != (p = (char *)realloc(iob->buf, need)))
774 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
775 return JB_ERR_MEMORY;
778 /* Update the iob pointers */
779 iob->cur = p + offset;
784 /* copy the new data into the iob buffer */
785 memcpy(iob->eod, buf, (size_t)n);
787 /* point to the end of the data */
790 /* null terminate == cheap insurance */
799 /*********************************************************************
801 * Function : decompress_iob
803 * Description : Decompress buffered page, expanding the
804 * buffer as necessary. csp->iob->cur
805 * should point to the the beginning of the
806 * compressed data block.
809 * 1 : csp = Current client state (buffers, headers, etc...)
811 * Returns : JB_ERR_OK on success,
812 * JB_ERR_MEMORY if out-of-memory limit reached, and
813 * JB_ERR_COMPRESS if error decompressing buffer.
815 *********************************************************************/
816 jb_err decompress_iob(struct client_state *csp)
818 char *buf; /* new, uncompressed buffer */
819 size_t bufsize; /* allocated size of the new buffer */
820 size_t skip_size; /* Number of bytes at the beginning of the iob
821 that we should NOT decompress. */
822 int status; /* return status of the inflate() call */
823 z_stream zstr; /* used by calls to zlib */
825 bufsize = csp->iob->size;
826 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
831 * This is to protect the parsing of gzipped data,
832 * but it should(?) be valid for deflated data also.
834 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
835 return JB_ERR_COMPRESS;
838 if (csp->content_type & CT_GZIP)
841 * Our task is slightly complicated by the facts that data
842 * compressed by gzip does not include a zlib header, and
843 * that there is no easily accessible interface in zlib to
844 * handle a gzip header. We strip off the gzip header by
845 * hand, and later inform zlib not to expect a header.
849 * Strip off the gzip header. Please see RFC 1952 for more
850 * explanation of the appropriate fields.
852 if ((*csp->iob->cur++ != (char)0x1f)
853 || (*csp->iob->cur++ != (char)0x8b)
854 || (*csp->iob->cur++ != Z_DEFLATED))
856 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
857 return JB_ERR_COMPRESS;
861 int flags = *csp->iob->cur++;
863 * XXX: These magic numbers should be replaced
864 * with macros to give a better idea what they do.
868 /* The gzip header has reserved bits set; bail out. */
869 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
870 return JB_ERR_COMPRESS;
874 /* Skip extra fields if necessary. */
878 * Skip a given number of bytes, specified
879 * as a 16-bit little-endian value.
881 csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
884 /* Skip the filename if necessary. */
887 /* A null-terminated string follows. */
888 while (*csp->iob->cur++);
891 /* Skip the comment if necessary. */
894 while (*csp->iob->cur++);
897 /* Skip the CRC if necessary. */
904 else if (csp->content_type & CT_DEFLATE)
906 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *csp->iob->cur);
908 * In theory (that is, according to RFC 1950), deflate-compressed
909 * data should begin with a two-byte zlib header and have an
910 * adler32 checksum at the end. It seems that in practice only
911 * the raw compressed data is sent. Note that this means that
912 * we are not RFC 1950-compliant here, but the advantage is that
913 * this actually works. :)
915 * We add a dummy null byte to tell zlib where the data ends,
916 * and later inform it not to expect a header.
918 * Fortunately, add_to_iob() has thoughtfully null-terminated
919 * the buffer; we can just increment the end pointer to include
926 log_error (LOG_LEVEL_ERROR,
927 "Unable to determine compression format for decompression");
928 return JB_ERR_COMPRESS;
931 /* Set up the fields required by zlib. */
932 zstr.next_in = (Bytef *)csp->iob->cur;
933 zstr.avail_in = (unsigned long)(csp->iob->eod - csp->iob->cur);
934 zstr.zalloc = Z_NULL;
936 zstr.opaque = Z_NULL;
939 * Passing -MAX_WBITS to inflateInit2 tells the library
940 * that there is no zlib header.
942 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
944 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
945 return JB_ERR_COMPRESS;
949 * Next, we allocate new storage for the inflated data.
950 * We don't modify the existing iob yet, so in case there
951 * is error in decompression we can recover gracefully.
953 buf = zalloc (bufsize);
956 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
957 return JB_ERR_MEMORY;
960 assert(bufsize >= skip_size);
961 memcpy(buf, csp->iob->buf, skip_size);
962 zstr.avail_out = bufsize - skip_size;
963 zstr.next_out = (Bytef *)buf + skip_size;
965 /* Try to decompress the whole stream in one shot. */
966 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
968 /* We need to allocate more memory for the output buffer. */
970 char *tmpbuf; /* used for realloc'ing the buffer */
971 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
974 * If zlib wants more data then there's a problem, because
975 * the complete compressed file should have been buffered.
977 if (0 == zstr.avail_in)
979 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
980 return JB_ERR_COMPRESS;
984 * If we tried the limit and still didn't have enough
985 * memory, just give up.
987 if (bufsize == csp->config->buffer_limit)
989 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
990 return JB_ERR_MEMORY;
993 /* Try doubling the buffer size each time. */
996 /* Don't exceed the buffer limit. */
997 if (bufsize > csp->config->buffer_limit)
999 bufsize = csp->config->buffer_limit;
1002 /* Try to allocate the new buffer. */
1003 tmpbuf = realloc(buf, bufsize);
1006 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1008 return JB_ERR_MEMORY;
1012 char *oldnext_out = (char *)zstr.next_out;
1015 * Update the fields for inflate() to use the new
1016 * buffer, which may be in a location different from
1019 zstr.avail_out += bufsize - oldbufsize;
1020 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1023 * Compare with an uglier method of calculating these values
1024 * that doesn't require the extra oldbufsize variable.
1026 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1027 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1028 assert(zstr.avail_out > 0);
1035 if (status != Z_STREAM_END)
1037 /* We failed to decompress the stream. */
1038 log_error(LOG_LEVEL_ERROR,
1039 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1040 return JB_ERR_COMPRESS;
1044 * Finally, we can actually update the iob, since the
1045 * decompression was successful. First, free the old
1048 freez(csp->iob->buf);
1050 /* Now, update the iob to use the new buffer. */
1051 csp->iob->buf = buf;
1052 csp->iob->cur = csp->iob->buf + skip_size;
1053 csp->iob->eod = (char *)zstr.next_out;
1054 csp->iob->size = bufsize;
1057 * Make sure the new uncompressed iob obeys some minimal
1058 * consistency conditions.
1060 if ((csp->iob->buf < csp->iob->cur)
1061 && (csp->iob->cur <= csp->iob->eod)
1062 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1064 char t = csp->iob->cur[100];
1065 csp->iob->cur[100] = '\0';
1067 * XXX: The debug level should be lowered
1068 * before the next stable release.
1070 log_error(LOG_LEVEL_INFO, "Sucessfully decompressed: %s", csp->iob->cur);
1071 csp->iob->cur[100] = t;
1076 /* It seems that zlib did something weird. */
1077 log_error(LOG_LEVEL_ERROR,
1078 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1079 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1080 csp->iob->eod, csp->iob->buf + csp->iob->size);
1081 return JB_ERR_COMPRESS;
1085 #endif /* defined(FEATURE_ZLIB) */
1088 /*********************************************************************
1090 * Function : get_header
1092 * Description : This (odd) routine will parse the csp->iob
1095 * 1 : csp = Current client state (buffers, headers, etc...)
1097 * Returns : Any one of the following:
1099 * 1) a pointer to a dynamically allocated string that contains a header line
1100 * 2) NULL indicating that the end of the header was reached
1101 * 3) "" indicating that the end of the iob was reached before finding
1102 * a complete header line.
1104 *********************************************************************/
1105 char *get_header(struct client_state *csp)
1111 if ((iob->cur == NULL)
1112 || ((p = strchr(iob->cur, '\n')) == NULL))
1114 return(""); /* couldn't find a complete header */
1119 ret = strdup(iob->cur);
1122 /* FIXME No way to handle error properly */
1123 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1128 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1130 /* is this a blank line (i.e. the end of the header) ? */
1142 /*********************************************************************
1144 * Function : get_header_value
1146 * Description : Get the value of a given header from a chained list
1147 * of header lines or return NULL if no such header is
1148 * present in the list.
1151 * 1 : header_list = pointer to list
1152 * 2 : header_name = string with name of header to look for.
1153 * Trailing colon required, capitalization
1156 * Returns : NULL if not found, else value of header
1158 *********************************************************************/
1159 char *get_header_value(const struct list *header_list, const char *header_name)
1161 struct list_entry *cur_entry;
1165 assert(header_list);
1166 assert(header_name);
1167 length = strlen(header_name);
1169 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1173 if (!strncmpic(cur_entry->str, header_name, length))
1176 * Found: return pointer to start of value
1178 ret = (char *) (cur_entry->str + length);
1179 while (*ret && ijb_isspace(*ret)) ret++;
1192 /*********************************************************************
1196 * Description : add, delete or modify lines in the HTTP header streams.
1197 * On entry, it receives a linked list of headers space
1198 * that was allocated dynamically (both the list nodes
1199 * and the header contents).
1201 * As a side effect it frees the space used by the original
1205 * 1 : pats = list of patterns to match against headers
1206 * 2 : more_headers = list of functions to add more
1207 * headers (client or server)
1208 * 3 : csp = Current client state (buffers, headers, etc...)
1210 * Returns : Single pointer to a fully formed header, or NULL
1211 * on out-of-memory error.
1213 *********************************************************************/
1214 char *sed(const struct parsers pats[],
1215 const add_header_func_ptr more_headers[],
1216 struct client_state *csp)
1218 struct list_entry *p;
1219 const struct parsers *v;
1220 const add_header_func_ptr *f;
1221 jb_err err = JB_ERR_OK;
1225 * If filtering is enabled, sed is run twice,
1226 * but most of the work needs to be done only once.
1228 first_run = (more_headers != NULL ) ? 1 : 0;
1230 if (first_run) /* Parse and print */
1232 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1234 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1236 /* Header crunch()ed in previous run? -> ignore */
1237 if (p->str == NULL) continue;
1239 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
1241 /* Does the current parser handle this header? */
1242 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1244 err = v->parser(csp, (char **)&(p->str));
1248 /* place any additional headers on the csp->headers list */
1249 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1254 else /* Parse only */
1257 * The second run is only needed if the body was modified
1258 * and the content-lenght has changed.
1260 if (strncmpic(csp->http->cmd, "HEAD", 4))
1262 /*XXX: Code duplication */
1263 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1265 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1267 /* Header crunch()ed in previous run? -> ignore */
1268 if (p->str == NULL) continue;
1270 /* Does the current parser handle this header? */
1271 if (strncmpic(p->str, v->str, v->len) == 0)
1273 err = v->parser(csp, (char **)&(p->str));
1280 if (err != JB_ERR_OK)
1285 return list_to_text(csp->headers);
1289 /* here begins the family of parser functions that reformat header lines */
1291 /*********************************************************************
1293 * Function : filter_server_header
1295 * Description : Checks if server header filtering is enabled.
1296 * If it is, filter_header is called to do the work.
1299 * 1 : csp = Current client state (buffers, headers, etc...)
1300 * 2 : header = On input, pointer to header to modify.
1301 * On output, pointer to the modified header, or NULL
1302 * to remove the header. This function frees the
1303 * original string if necessary.
1305 * Returns : JB_ERR_OK on success and always succeeds
1307 *********************************************************************/
1308 jb_err filter_server_header(struct client_state *csp, char **header)
1310 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
1312 filter_header(csp, header);
1317 /*********************************************************************
1319 * Function : filter_client_header
1321 * Description : Checks if client header filtering is enabled.
1322 * If it is, filter_header is called to do the work.
1325 * 1 : csp = Current client state (buffers, headers, etc...)
1326 * 2 : header = On input, pointer to header to modify.
1327 * On output, pointer to the modified header, or NULL
1328 * to remove the header. This function frees the
1329 * original string if necessary.
1331 * Returns : JB_ERR_OK on success and always succeeds
1333 *********************************************************************/
1334 jb_err filter_client_header(struct client_state *csp, char **header)
1336 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
1338 filter_header(csp, header);
1343 /*********************************************************************
1345 * Function : filter_header
1347 * Description : Executes all text substitutions from all applying
1348 * +filter actions on the header.
1349 * Most of the code was copied from pcrs_filter_response,
1350 * including the rather short variable names
1353 * 1 : csp = Current client state (buffers, headers, etc...)
1354 * 2 : header = On input, pointer to header to modify.
1355 * On output, pointer to the modified header, or NULL
1356 * to remove the header. This function frees the
1357 * original string if necessary.
1359 * Returns : JB_ERR_OK on success and always succeeds
1361 *********************************************************************/
1362 jb_err filter_header(struct client_state *csp, char **header)
1366 size_t size = strlen(*header);
1368 char *newheader = NULL;
1371 struct file_list *fl;
1372 struct re_filterfile_spec *b;
1373 struct list_entry *filtername;
1375 int i, found_filters = 0;
1378 * Need to check the set of re_filterfiles...
1380 for (i = 0; i < MAX_AF_FILES; i++)
1393 if (0 == found_filters)
1395 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1399 for (i = 0; i < MAX_AF_FILES; i++)
1402 if ((NULL == fl) || (NULL == fl->f))
1405 * Either there are no filter files
1406 * left, or this filter file just
1407 * contains no valid filters.
1409 * Continue to be sure we don't miss
1410 * valid filter files that are chained
1411 * after empty or invalid ones.
1416 * For all applying +filter actions, look if a filter by that
1417 * name exists and if yes, execute its pcrs_joblist on the
1420 for (b = fl->f; b; b = b->next)
1422 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1423 filtername ; filtername = filtername->next)
1425 if (strcmp(b->name, filtername->str) == 0)
1427 int current_hits = 0;
1429 if ( NULL == b->joblist )
1431 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1435 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1436 *header, size, b->name);
1438 /* Apply all jobs from the joblist */
1439 for (job = b->joblist; NULL != job; job = job->next)
1441 matches = pcrs_execute(job, *header, size, &newheader, &size);
1444 current_hits += matches;
1445 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1447 *header = newheader;
1449 else if ( 0 == matches )
1451 /* Filter doesn't change header */
1457 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1458 *header, b->name, pcrs_strerror(matches));
1459 if( newheader != NULL)
1461 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1466 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1467 hits += current_hits;
1475 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1483 /*********************************************************************
1485 * Function : crumble
1487 * Description : This is called if a header matches a pattern to "crunch"
1490 * 1 : csp = Current client state (buffers, headers, etc...)
1491 * 2 : header = On input, pointer to header to modify.
1492 * On output, pointer to the modified header, or NULL
1493 * to remove the header. This function frees the
1494 * original string if necessary.
1496 * Returns : JB_ERR_OK on success, or
1497 * JB_ERR_MEMORY on out-of-memory error.
1499 *********************************************************************/
1500 jb_err crumble(struct client_state *csp, char **header)
1502 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1507 /*********************************************************************
1509 * Function : crunch_server_header
1511 * Description : Crunch server header if it matches a string supplied by the
1512 * user. Called from `sed'.
1515 * 1 : csp = Current client state (buffers, headers, etc...)
1516 * 2 : header = On input, pointer to header to modify.
1517 * On output, pointer to the modified header, or NULL
1518 * to remove the header. This function frees the
1519 * original string if necessary.
1521 * Returns : JB_ERR_OK on success and always succeeds
1523 *********************************************************************/
1524 jb_err crunch_server_header(struct client_state *csp, char **header)
1526 const char *crunch_pattern;
1527 /*Is there a header to crunch*/
1529 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1531 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1533 /*Is the current header the lucky one?*/
1534 if (strstr(*header, crunch_pattern))
1536 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1543 /*********************************************************************
1545 * Function : server_content_type
1547 * Description : Set the content-type for filterable types (text/.*,
1548 * javascript and image/gif) unless filtering has been
1549 * forbidden (CT_TABOO) while parsing earlier headers.
1550 * NOTE: Since text/plain is commonly used by web servers
1551 * for files whose correct type is unknown, we don't
1552 * set CT_TEXT for it.
1555 * 1 : csp = Current client state (buffers, headers, etc...)
1556 * 2 : header = On input, pointer to header to modify.
1557 * On output, pointer to the modified header, or NULL
1558 * to remove the header. This function frees the
1559 * original string if necessary.
1561 * Returns : JB_ERR_OK on success, or
1562 * JB_ERR_MEMORY on out-of-memory error.
1564 *********************************************************************/
1565 jb_err server_content_type(struct client_state *csp, char **header)
1569 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1571 assert(!csp->content_type || (csp->content_type == CT_TABOO));
1573 if (!(csp->content_type & CT_TABOO))
1575 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1576 || strstr(*header, "xml")
1577 || strstr(*header, "application/x-javascript"))
1579 csp->content_type |= CT_TEXT;
1581 else if (strstr(*header, " image/gif"))
1583 csp->content_type |= CT_GIF;
1585 else if (strstr(*header, " image/jpeg"))
1587 csp->content_type |= CT_JPEG;
1591 csp->content_type = 0;
1595 * Are we enabling text mode by force?
1597 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1600 * Do we really have to?
1602 if (csp->content_type & CT_TEXT)
1604 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1608 csp->content_type |= CT_TEXT;
1609 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1613 * Are we messing with the content type?
1615 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1618 * Make sure the user doesn't accidently
1619 * change the content type of binary documents.
1621 if (csp->content_type & CT_TEXT)
1624 *header = strdup("Content-Type: ");
1625 string_append(header, newval);
1629 log_error(LOG_LEVEL_HEADER,
1630 "Insufficient memory. Content-Type crunched without replacement!");
1631 return JB_ERR_MEMORY;
1633 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1637 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1638 "Enable force-text-mode if you know what you're doing.", *header);
1645 /*********************************************************************
1647 * Function : server_transfer_coding
1649 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1650 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1651 * - Remove header if body was chunked but has been
1652 * de-chunked for filtering.
1655 * 1 : csp = Current client state (buffers, headers, etc...)
1656 * 2 : header = On input, pointer to header to modify.
1657 * On output, pointer to the modified header, or NULL
1658 * to remove the header. This function frees the
1659 * original string if necessary.
1661 * Returns : JB_ERR_OK on success, or
1662 * JB_ERR_MEMORY on out-of-memory error.
1664 *********************************************************************/
1665 jb_err server_transfer_coding(struct client_state *csp, char **header)
1668 * Turn off pcrs and gif filtering if body compressed
1670 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1674 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1676 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1677 csp->http->cmd, *header);
1678 #endif /* def FEATURE_ZLIB */
1679 csp->content_type = CT_TABOO;
1683 * Raise flag if body chunked
1685 if (strstr(*header, "chunked"))
1687 csp->flags |= CSP_FLAG_CHUNKED;
1690 * If the body was modified, it has been de-chunked first
1691 * and the header must be removed.
1693 * FIXME: If there is more than one transfer encoding,
1694 * only the "chunked" part should be removed here.
1696 if (csp->flags & CSP_FLAG_MODIFIED)
1698 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1707 /*********************************************************************
1709 * Function : server_content_encoding
1711 * Description : This function is run twice for each request,
1712 * unless FEATURE_ZLIB and filtering are disabled.
1714 * The first run is used to check if the content
1715 * is compressed, if FEATURE_ZLIB is disabled
1716 * filtering is then disabled as well, if FEATURE_ZLIB
1717 * is enabled the content is marked for decompression.
1719 * The second run is used to remove the Content-Encoding
1720 * header if the decompression was successful.
1723 * 1 : csp = Current client state (buffers, headers, etc...)
1724 * 2 : header = On input, pointer to header to modify.
1725 * On output, pointer to the modified header, or NULL
1726 * to remove the header. This function frees the
1727 * original string if necessary.
1729 * Returns : JB_ERR_OK on success, or
1730 * JB_ERR_MEMORY on out-of-memory error.
1732 *********************************************************************/
1733 jb_err server_content_encoding(struct client_state *csp, char **header)
1736 /* XXX: Why would we modify the content if it was taboo? */
1737 if ((csp->flags & CSP_FLAG_MODIFIED) && !(csp->content_type & CT_TABOO))
1740 * We successfully decompressed the content,
1741 * and have to clean the header now, so the
1742 * client no longer expects compressed data..
1744 * XXX: There is a difference between cleaning
1745 * and removing it completely.
1747 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1750 else if (strstr(*header, "gzip"))
1752 /* Mark for gzip decompression */
1753 csp->content_type |= CT_GZIP;
1755 else if (strstr(*header, "deflate"))
1757 /* Mark for zlib decompression */
1758 csp->content_type |= CT_DEFLATE;
1760 else if (strstr(*header, "compress"))
1763 * We can't decompress this; therefore we can't filter
1766 csp->content_type |= CT_TABOO;
1768 #else /* !defined(FEATURE_ZLIB) */
1769 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1772 * Body is compressed, turn off pcrs and gif filtering.
1774 csp->content_type |= CT_TABOO;
1776 #endif /* !defined(FEATURE_ZLIB) */
1783 /*********************************************************************
1785 * Function : server_content_length
1787 * Description : Adjust Content-Length header if we modified
1791 * 1 : csp = Current client state (buffers, headers, etc...)
1792 * 2 : header = On input, pointer to header to modify.
1793 * On output, pointer to the modified header, or NULL
1794 * to remove the header. This function frees the
1795 * original string if necessary.
1797 * Returns : JB_ERR_OK on success, or
1798 * JB_ERR_MEMORY on out-of-memory error.
1800 *********************************************************************/
1801 jb_err server_content_length(struct client_state *csp, char **header)
1803 if (csp->content_length != 0) /* Content length could have been modified */
1806 * XXX: Shouldn't we check if csp->content_length
1807 * is different than the original value?
1810 *header = (char *) zalloc(100);
1811 if (*header == NULL)
1813 return JB_ERR_MEMORY;
1816 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1818 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1825 /*********************************************************************
1827 * Function : server_content_md5
1829 * Description : Crumble any Content-MD5 headers if the document was
1830 * modified. FIXME: Should we re-compute instead?
1833 * 1 : csp = Current client state (buffers, headers, etc...)
1834 * 2 : header = On input, pointer to header to modify.
1835 * On output, pointer to the modified header, or NULL
1836 * to remove the header. This function frees the
1837 * original string if necessary.
1839 * Returns : JB_ERR_OK on success, or
1840 * JB_ERR_MEMORY on out-of-memory error.
1842 *********************************************************************/
1843 jb_err server_content_md5(struct client_state *csp, char **header)
1845 if (csp->flags & CSP_FLAG_MODIFIED)
1847 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1854 /*********************************************************************
1856 * Function : server_content_disposition
1858 * Description : If enabled, blocks or modifies the "content-disposition" header.
1859 * Called from `sed'.
1862 * 1 : csp = Current client state (buffers, headers, etc...)
1863 * 2 : header = On input, pointer to header to modify.
1864 * On output, pointer to the modified header, or NULL
1865 * to remove the header. This function frees the
1866 * original string if necessary.
1868 * Returns : JB_ERR_OK on success, or
1869 * JB_ERR_MEMORY on out-of-memory error.
1871 *********************************************************************/
1872 jb_err server_content_disposition(struct client_state *csp, char **header)
1877 * Are we messing with the content-disposition header?
1879 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1885 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1887 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1890 * Blocking content-disposition header
1892 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1899 * Replacing content-disposition header
1902 *header = strdup("content-disposition: ");
1903 string_append(header, newval);
1905 if (*header == NULL)
1907 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1911 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1914 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1917 /*********************************************************************
1919 * Function : server_last_modified
1921 * Description : Changes Last-Modified header to the actual date
1922 * to help hide-if-modified-since.
1923 * Called from `sed'.
1926 * 1 : csp = Current client state (buffers, headers, etc...)
1927 * 2 : header = On input, pointer to header to modify.
1928 * On output, pointer to the modified header, or NULL
1929 * to remove the header. This function frees the
1930 * original string if necessary.
1932 * Returns : JB_ERR_OK on success, or
1933 * JB_ERR_MEMORY on out-of-memory error.
1935 *********************************************************************/
1936 jb_err server_last_modified(struct client_state *csp, char **header)
1939 char buf[BUFFER_SIZE];
1942 #ifdef HAVE_GMTIME_R
1945 struct tm *timeptr = NULL;
1946 time_t now, last_modified;
1948 long int days, hours, minutes, seconds;
1951 * Are we messing with the Last-Modified header?
1953 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1959 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1961 if (0 == strcmpic(newval, "block") )
1964 * Blocking Last-Modified header. Useless but why not.
1966 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1970 else if (0 == strcmpic(newval, "reset-to-request-time"))
1973 * Setting Last-Modified Header to now.
1975 get_http_time(0, buf);
1977 *header = strdup("Last-Modified: ");
1978 string_append(header, buf);
1980 if (*header == NULL)
1982 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1986 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1989 else if (0 == strcmpic(newval, "randomize"))
1991 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1993 #ifdef HAVE_GMTIME_R
1994 timeptr = gmtime_r(&now, &gmt);
1995 #elif FEATURE_PTHREAD
1996 pthread_mutex_lock(&gmtime_mutex);
1997 timeptr = gmtime(&now);
1998 pthread_mutex_unlock(&gmtime_mutex);
2000 timeptr = gmtime(&now);
2002 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
2004 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2009 rtime = (long int)difftime(now, last_modified);
2012 rtime = pick_from_range(rtime);
2013 last_modified += rtime;
2014 #ifdef HAVE_GMTIME_R
2015 timeptr = gmtime_r(&last_modified, &gmt);
2016 #elif FEATURE_PTHREAD
2017 pthread_mutex_lock(&gmtime_mutex);
2018 timeptr = gmtime(&last_modified);
2019 pthread_mutex_unlock(&gmtime_mutex);
2021 timeptr = gmtime(&last_modified);
2023 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2025 *header = strdup("Last-Modified: ");
2026 string_append(header, newheader);
2028 if (*header == NULL)
2030 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2031 return JB_ERR_MEMORY;
2034 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2036 days = rtime / (3600 * 24);
2037 hours = rtime / 3600 % 24;
2038 minutes = rtime / 60 % 60;
2039 seconds = rtime % 60;
2041 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2042 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2043 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2048 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2056 /*********************************************************************
2058 * Function : client_accept_encoding
2060 * Description : Rewrite the client's Accept-Encoding header so that
2061 * if doesn't allow compression, if the action applies.
2062 * Note: For HTTP/1.0 the absence of the header is enough.
2065 * 1 : csp = Current client state (buffers, headers, etc...)
2066 * 2 : header = On input, pointer to header to modify.
2067 * On output, pointer to the modified header, or NULL
2068 * to remove the header. This function frees the
2069 * original string if necessary.
2071 * Returns : JB_ERR_OK on success, or
2072 * JB_ERR_MEMORY on out-of-memory error.
2074 *********************************************************************/
2075 jb_err client_accept_encoding(struct client_state *csp, char **header)
2077 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2079 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2083 /* Temporarily disable the correct behaviour to
2084 * work around a PHP bug.
2086 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2088 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2089 * if (*header == NULL)
2091 * return JB_ERR_MEMORY;
2102 /*********************************************************************
2104 * Function : client_te
2106 * Description : Rewrite the client's TE header so that
2107 * if doesn't allow compression, if the action applies.
2110 * 1 : csp = Current client state (buffers, headers, etc...)
2111 * 2 : header = On input, pointer to header to modify.
2112 * On output, pointer to the modified header, or NULL
2113 * to remove the header. This function frees the
2114 * original string if necessary.
2116 * Returns : JB_ERR_OK on success, or
2117 * JB_ERR_MEMORY on out-of-memory error.
2119 *********************************************************************/
2120 jb_err client_te(struct client_state *csp, char **header)
2122 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2125 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2131 /*********************************************************************
2133 * Function : client_referrer
2135 * Description : Handle the "referer" config setting properly.
2136 * Called from `sed'.
2139 * 1 : csp = Current client state (buffers, headers, etc...)
2140 * 2 : header = On input, pointer to header to modify.
2141 * On output, pointer to the modified header, or NULL
2142 * to remove the header. This function frees the
2143 * original string if necessary.
2145 * Returns : JB_ERR_OK on success, or
2146 * JB_ERR_MEMORY on out-of-memory error.
2148 *********************************************************************/
2149 jb_err client_referrer(struct client_state *csp, char **header)
2156 #ifdef FEATURE_FORCE_LOAD
2157 /* Since the referrer can include the prefix even
2158 * if the request itself is non-forced, we must
2159 * clean it unconditionally
2161 strclean(*header, FORCE_PREFIX);
2162 #endif /* def FEATURE_FORCE_LOAD */
2165 * Are we sending referer?
2167 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2172 newval = csp->action->string[ACTION_STRING_REFERER];
2174 if ((0 != strcmpic(newval, "conditional-block")))
2178 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2183 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2186 else if (0 == strcmpic(newval, "conditional-block"))
2189 * Block referer if host has changed.
2192 if (NULL == (host = strdup(csp->http->hostport)))
2195 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2196 return JB_ERR_MEMORY;
2198 if (NULL == (referer = strdup(*header)))
2202 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2203 return JB_ERR_MEMORY;
2205 hostlenght = strlen(host);
2206 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2208 /*Shorten referer to make sure the referer is blocked
2209 *if www.example.org/www.example.com-shall-see-the-referer/
2210 *links to www.example.com/
2212 referer[hostlenght+17] = '\0';
2214 if ( 0 == strstr(referer, host)) /*Host has changed*/
2216 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2221 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2227 else if (0 != strcmpic(newval, "forge"))
2230 * We have a specific (fixed) referer we want to send.
2232 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2234 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2236 *header = strdup("Referer: ");
2237 string_append(header, newval);
2238 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2240 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2245 * Forge a referer as http://[hostname:port of REQUEST]/
2246 * to fool stupid checks for in-site links
2249 *header = strdup("Referer: http://");
2250 string_append(header, csp->http->hostport);
2251 string_append(header, "/");
2252 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2254 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2258 /*********************************************************************
2260 * Function : client_accept_language
2262 * Description : Handle the "Accept-Language" config setting properly.
2263 * Called from `sed'.
2266 * 1 : csp = Current client state (buffers, headers, etc...)
2267 * 2 : header = On input, pointer to header to modify.
2268 * On output, pointer to the modified header, or NULL
2269 * to remove the header. This function frees the
2270 * original string if necessary.
2272 * Returns : JB_ERR_OK on success, or
2273 * JB_ERR_MEMORY on out-of-memory error.
2275 *********************************************************************/
2276 jb_err client_accept_language(struct client_state *csp, char **header)
2281 * Are we messing with the Accept-Language?
2283 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2285 /*I don't think so*/
2289 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2291 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2294 * Blocking Accept-Language header
2296 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2303 * Replacing Accept-Language header
2306 *header = strdup("Accept-Language: ");
2307 string_append(header, newval);
2309 if (*header == NULL)
2311 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
2315 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
2318 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2321 /*********************************************************************
2323 * Function : crunch_client_header
2325 * Description : Crunch client header if it matches a string supplied by the
2326 * user. Called from `sed'.
2329 * 1 : csp = Current client state (buffers, headers, etc...)
2330 * 2 : header = On input, pointer to header to modify.
2331 * On output, pointer to the modified header, or NULL
2332 * to remove the header. This function frees the
2333 * original string if necessary.
2335 * Returns : JB_ERR_OK on success and always succeeds
2337 *********************************************************************/
2338 jb_err crunch_client_header(struct client_state *csp, char **header)
2340 const char *crunch_pattern;
2341 /*Is there a header to crunch*/
2343 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2345 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2347 /*Is the current header the lucky one?*/
2348 if (strstr(*header, crunch_pattern))
2350 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2358 /*********************************************************************
2360 * Function : client_uagent
2362 * Description : Handle the "user-agent" config setting properly
2363 * and remember its original value to enable browser
2364 * bug workarounds. Called from `sed'.
2367 * 1 : csp = Current client state (buffers, headers, etc...)
2368 * 2 : header = On input, pointer to header to modify.
2369 * On output, pointer to the modified header, or NULL
2370 * to remove the header. This function frees the
2371 * original string if necessary.
2373 * Returns : JB_ERR_OK on success, or
2374 * JB_ERR_MEMORY on out-of-memory error.
2376 *********************************************************************/
2377 jb_err client_uagent(struct client_state *csp, char **header)
2381 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2386 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2393 *header = strdup("User-Agent: ");
2394 string_append(header, newval);
2396 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2398 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2401 /*********************************************************************
2403 * Function : client_ua
2405 * Description : Handle "ua-" headers properly. Called from `sed'.
2408 * 1 : csp = Current client state (buffers, headers, etc...)
2409 * 2 : header = On input, pointer to header to modify.
2410 * On output, pointer to the modified header, or NULL
2411 * to remove the header. This function frees the
2412 * original string if necessary.
2414 * Returns : JB_ERR_OK on success, or
2415 * JB_ERR_MEMORY on out-of-memory error.
2417 *********************************************************************/
2418 jb_err client_ua(struct client_state *csp, char **header)
2420 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2422 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2430 /*********************************************************************
2432 * Function : client_from
2434 * Description : Handle the "from" config setting properly.
2435 * Called from `sed'.
2438 * 1 : csp = Current client state (buffers, headers, etc...)
2439 * 2 : header = On input, pointer to header to modify.
2440 * On output, pointer to the modified header, or NULL
2441 * to remove the header. This function frees the
2442 * original string if necessary.
2444 * Returns : JB_ERR_OK on success, or
2445 * JB_ERR_MEMORY on out-of-memory error.
2447 *********************************************************************/
2448 jb_err client_from(struct client_state *csp, char **header)
2452 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2459 newval = csp->action->string[ACTION_STRING_FROM];
2462 * Are we blocking the e-mail address?
2464 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2466 log_error(LOG_LEVEL_HEADER, "crunched From!");
2470 log_error(LOG_LEVEL_HEADER, " modified");
2472 *header = strdup("From: ");
2473 string_append(header, newval);
2475 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2479 /*********************************************************************
2481 * Function : client_send_cookie
2483 * Description : Handle the "cookie" header properly. Called from `sed'.
2484 * If cookie is accepted, add it to the cookie_list,
2485 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2488 * 1 : csp = Current client state (buffers, headers, etc...)
2489 * 2 : header = On input, pointer to header to modify.
2490 * On output, pointer to the modified header, or NULL
2491 * to remove the header. This function frees the
2492 * original string if necessary.
2494 * Returns : JB_ERR_OK on success, or
2495 * JB_ERR_MEMORY on out-of-memory error.
2497 *********************************************************************/
2498 jb_err client_send_cookie(struct client_state *csp, char **header)
2500 jb_err result = JB_ERR_OK;
2502 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2504 /* strlen("cookie: ") == 8 */
2505 result = enlist(csp->cookie_list, *header + 8);
2509 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2513 * Always remove the cookie here. The cookie header
2514 * will be sent at the end of the header.
2522 /*********************************************************************
2524 * Function : client_x_forwarded
2526 * Description : Handle the "x-forwarded-for" config setting properly,
2527 * also used in the add_client_headers list. Called from `sed'.
2530 * 1 : csp = Current client state (buffers, headers, etc...)
2531 * 2 : header = On input, pointer to header to modify.
2532 * On output, pointer to the modified header, or NULL
2533 * to remove the header. This function frees the
2534 * original string if necessary.
2536 * Returns : JB_ERR_OK on success, or
2537 * JB_ERR_MEMORY on out-of-memory error.
2539 *********************************************************************/
2540 jb_err client_x_forwarded(struct client_state *csp, char **header)
2542 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2544 /* Save it so we can re-add it later */
2545 freez(csp->x_forwarded);
2546 csp->x_forwarded = *header;
2549 * Always set *header = NULL, since this information
2550 * will be sent at the end of the header.
2557 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2564 /*********************************************************************
2566 * Function : client_max_forwards
2568 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2569 * from the value of the Max-Forwards header field.
2572 * 1 : csp = Current client state (buffers, headers, etc...)
2573 * 2 : header = On input, pointer to header to modify.
2574 * On output, pointer to the modified header, or NULL
2575 * to remove the header. This function frees the
2576 * original string if necessary.
2578 * Returns : JB_ERR_OK on success, or
2579 * JB_ERR_MEMORY on out-of-memory error.
2581 *********************************************************************/
2582 jb_err client_max_forwards(struct client_state *csp, char **header)
2584 unsigned int max_forwards;
2586 if ((0 == strcmpic(csp->http->gpc, "trace"))
2587 || (0 == strcmpic(csp->http->gpc, "options")))
2589 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2591 if (max_forwards-- >= 1)
2593 sprintf(*header, "Max-Forwards: %u", max_forwards);
2594 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2598 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2607 /*********************************************************************
2609 * Function : client_host
2611 * Description : If the request URI did not contain host and
2612 * port information, parse and evaluate the Host
2615 * Also, kill ill-formed HOST: headers as sent by
2616 * Apple's iTunes software when used with a proxy.
2619 * 1 : csp = Current client state (buffers, headers, etc...)
2620 * 2 : header = On input, pointer to header to modify.
2621 * On output, pointer to the modified header, or NULL
2622 * to remove the header. This function frees the
2623 * original string if necessary.
2625 * Returns : JB_ERR_OK on success, or
2626 * JB_ERR_MEMORY on out-of-memory error.
2628 *********************************************************************/
2629 jb_err client_host(struct client_state *csp, char **header)
2634 * If the header field name is all upper-case, chances are that it's
2635 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2636 * not a problem -- they are regenerated later.
2638 if ((*header)[1] == 'O')
2640 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2645 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2646 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2649 if (NULL == (p = strdup((*header)+6)))
2651 return JB_ERR_MEMORY;
2654 if (NULL == (q = strdup(p)))
2657 return JB_ERR_MEMORY;
2660 freez(csp->http->hostport);
2661 csp->http->hostport = p;
2662 freez(csp->http->host);
2663 csp->http->host = q;
2664 q = strchr(csp->http->host, ':');
2667 /* Terminate hostname and evaluate port string */
2669 csp->http->port = atoi(q);
2673 csp->http->port = csp->http->ssl ? 443 : 80;
2676 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2677 csp->http->hostport, csp->http->host, csp->http->port);
2683 /*********************************************************************
2685 * Function : client_if_modified_since
2687 * Description : Remove or modify the If-Modified-Since header.
2690 * 1 : csp = Current client state (buffers, headers, etc...)
2691 * 2 : header = On input, pointer to header to modify.
2692 * On output, pointer to the modified header, or NULL
2693 * to remove the header. This function frees the
2694 * original string if necessary.
2696 * Returns : JB_ERR_OK on success, or
2697 * JB_ERR_MEMORY on out-of-memory error.
2699 *********************************************************************/
2700 jb_err client_if_modified_since(struct client_state *csp, char **header)
2703 #ifdef HAVE_GMTIME_R
2706 struct tm *timeptr = NULL;
2710 long int hours, minutes, seconds;
2714 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2717 * The client got an error message because of a temporary problem,
2718 * the problem is gone and the client now tries to revalidate our
2719 * error message on the real server. The revalidation would always
2720 * end with the transmission of the whole document and there is
2721 * no need to expose the bogus If-Modified-Since header.
2723 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2726 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2728 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2730 if ((0 == strcmpic(newval, "block")))
2732 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2735 else /* add random value */
2737 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2739 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2744 rtime = strtol(newval, &endptr, 0);
2747 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2748 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2755 rtime = pick_from_range(rtime);
2759 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2762 tm += rtime * (negative ? -1 : 1);
2763 #ifdef HAVE_GMTIME_R
2764 timeptr = gmtime_r(&tm, &gmt);
2765 #elif FEATURE_PTHREAD
2766 pthread_mutex_lock(&gmtime_mutex);
2767 timeptr = gmtime(&tm);
2768 pthread_mutex_unlock(&gmtime_mutex);
2770 timeptr = gmtime(&tm);
2772 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2775 *header = strdup("If-Modified-Since: ");
2776 string_append(header, newheader);
2778 if (*header == NULL)
2780 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2781 return JB_ERR_MEMORY;
2784 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2786 hours = rtime / 3600;
2787 minutes = rtime / 60 % 60;
2788 seconds = rtime % 60;
2790 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2791 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2792 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2801 /*********************************************************************
2803 * Function : client_if_none_match
2805 * Description : Remove the If-None-Match header.
2808 * 1 : csp = Current client state (buffers, headers, etc...)
2809 * 2 : header = On input, pointer to header to modify.
2810 * On output, pointer to the modified header, or NULL
2811 * to remove the header. This function frees the
2812 * original string if necessary.
2814 * Returns : JB_ERR_OK on success, or
2815 * JB_ERR_MEMORY on out-of-memory error.
2817 *********************************************************************/
2818 jb_err client_if_none_match(struct client_state *csp, char **header)
2820 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2822 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2829 /*********************************************************************
2831 * Function : client_x_filter
2833 * Description : Disables filtering if the client set "X-Filter: No".
2834 * Called from `sed'.
2837 * 1 : csp = Current client state (buffers, headers, etc...)
2838 * 2 : header = On input, pointer to header to modify.
2839 * On output, pointer to the modified header, or NULL
2840 * to remove the header. This function frees the
2841 * original string if necessary.
2843 * Returns : JB_ERR_OK on success
2845 *********************************************************************/
2846 jb_err client_x_filter(struct client_state *csp, char **header)
2848 if ( 0 == strcmpic(*header, "X-Filter: No"))
2850 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2852 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2856 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2858 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to fetch without filtering!");
2862 csp->content_type = CT_TABOO;
2863 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
2864 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
2865 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
2867 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2874 /* the following functions add headers directly to the header list */
2876 /*********************************************************************
2878 * Function : client_host_adder
2880 * Description : Adds the Host: header field if it is missing.
2881 * Called from `sed'.
2884 * 1 : csp = Current client state (buffers, headers, etc...)
2886 * Returns : JB_ERR_OK on success, or
2887 * JB_ERR_MEMORY on out-of-memory error.
2889 *********************************************************************/
2890 jb_err client_host_adder(struct client_state *csp)
2895 if ( !csp->http->hostport || !*(csp->http->hostport))
2901 * remove 'user:pass@' from 'proto://user:pass@host'
2903 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2909 p = csp->http->hostport;
2912 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2913 err = enlist_unique_header(csp->headers, "Host", p);
2919 /*********************************************************************
2921 * Function : client_cookie_adder
2923 * Description : Used in the add_client_headers list. Called from `sed'.
2926 * 1 : csp = Current client state (buffers, headers, etc...)
2928 * Returns : JB_ERR_OK on success, or
2929 * JB_ERR_MEMORY on out-of-memory error.
2931 *********************************************************************/
2932 jb_err client_cookie_adder(struct client_state *csp)
2934 struct list_entry *lst;
2936 struct list_entry *list1 = csp->cookie_list->first;
2937 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2938 int first_cookie = 1;
2941 if ((list1 == NULL) && (list2 == NULL))
2947 tmp = strdup("Cookie: ");
2949 for (lst = list1; lst ; lst = lst->next)
2957 string_append(&tmp, "; ");
2959 string_append(&tmp, lst->str);
2962 for (lst = list2; lst ; lst = lst->next)
2970 string_append(&tmp, "; ");
2972 string_join(&tmp, cookie_encode(lst->str));
2977 return JB_ERR_MEMORY;
2980 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2981 err = enlist(csp->headers, tmp);
2987 /*********************************************************************
2989 * Function : client_accept_encoding_adder
2991 * Description : Add an Accept-Encoding header to the client's request
2992 * that disables compression if the action applies, and
2993 * the header is not already there. Called from `sed'.
2994 * Note: For HTTP/1.0, the absence of the header is enough.
2997 * 1 : csp = Current client state (buffers, headers, etc...)
2999 * Returns : JB_ERR_OK on success, or
3000 * JB_ERR_MEMORY on out-of-memory error.
3002 *********************************************************************/
3003 jb_err client_accept_encoding_adder(struct client_state *csp)
3005 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3006 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3008 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3015 /*********************************************************************
3017 * Function : client_xtra_adder
3019 * Description : Used in the add_client_headers list. Called from `sed'.
3022 * 1 : csp = Current client state (buffers, headers, etc...)
3024 * Returns : JB_ERR_OK on success, or
3025 * JB_ERR_MEMORY on out-of-memory error.
3027 *********************************************************************/
3028 jb_err client_xtra_adder(struct client_state *csp)
3030 struct list_entry *lst;
3033 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3034 lst ; lst = lst->next)
3036 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3037 err = enlist(csp->headers, lst->str);
3049 /*********************************************************************
3051 * Function : client_x_forwarded_adder
3053 * Description : Used in the add_client_headers list. Called from `sed'.
3056 * 1 : csp = Current client state (buffers, headers, etc...)
3058 * Returns : JB_ERR_OK on success, or
3059 * JB_ERR_MEMORY on out-of-memory error.
3061 *********************************************************************/
3062 jb_err client_x_forwarded_adder(struct client_state *csp)
3067 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3072 if (csp->x_forwarded)
3074 p = strdup(csp->x_forwarded);
3075 string_append(&p, ", ");
3079 p = strdup("X-Forwarded-For: ");
3081 string_append(&p, csp->ip_addr_str);
3085 return JB_ERR_MEMORY;
3088 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3089 err = enlist(csp->headers, p);
3096 /*********************************************************************
3098 * Function : connection_close_adder
3100 * Description : Adds a "Connection: close" header to csp->headers
3101 * as a temporary fix for the needed but missing HTTP/1.1
3102 * support. Called from `sed'.
3103 * FIXME: This whole function shouldn't be neccessary!
3106 * 1 : csp = Current client state (buffers, headers, etc...)
3108 * Returns : JB_ERR_OK on success, or
3109 * JB_ERR_MEMORY on out-of-memory error.
3111 *********************************************************************/
3112 jb_err connection_close_adder(struct client_state *csp)
3114 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3115 return enlist(csp->headers, "Connection: close");
3119 /*********************************************************************
3121 * Function : server_http
3123 * Description : - Save the HTTP Status into csp->http->status
3124 * - Set CT_TABOO to prevent filtering if the answer
3125 * is a partial range (HTTP status 206)
3126 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3130 * 1 : csp = Current client state (buffers, headers, etc...)
3131 * 2 : header = On input, pointer to header to modify.
3132 * On output, pointer to the modified header, or NULL
3133 * to remove the header. This function frees the
3134 * original string if necessary.
3136 * Returns : JB_ERR_OK on success, or
3137 * JB_ERR_MEMORY on out-of-memory error.
3139 *********************************************************************/
3140 jb_err server_http(struct client_state *csp, char **header)
3142 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3143 if (csp->http->status == 206)
3145 csp->content_type = CT_TABOO;
3148 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3151 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3158 /*********************************************************************
3160 * Function : server_set_cookie
3162 * Description : Handle the server "cookie" header properly.
3163 * Log cookie to the jar file. Then "crunch" it,
3164 * or accept it. Called from `sed'.
3167 * 1 : csp = Current client state (buffers, headers, etc...)
3168 * 2 : header = On input, pointer to header to modify.
3169 * On output, pointer to the modified header, or NULL
3170 * to remove the header. This function frees the
3171 * original string if necessary.
3173 * Returns : JB_ERR_OK on success, or
3174 * JB_ERR_MEMORY on out-of-memory error.
3176 *********************************************************************/
3177 jb_err server_set_cookie(struct client_state *csp, char **header)
3179 #ifdef FEATURE_COOKIE_JAR
3180 if (csp->config->jar)
3183 * Write timestamp into outbuf.
3185 * Complex because not all OSs have tm_gmtoff or
3186 * the %z field in strftime()
3188 char tempbuf[ BUFFER_SIZE ];
3192 #ifdef HAVE_LOCALTIME_R
3193 tm_now = *localtime_r(&now, &tm_now);
3194 #elif FEATURE_PTHREAD
3195 pthread_mutex_lock(&localtime_mutex);
3196 tm_now = *localtime (&now);
3197 pthread_mutex_unlock(&localtime_mutex);
3199 tm_now = *localtime (&now);
3201 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3203 /* strlen("set-cookie: ") = 12 */
3204 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3206 #endif /* def FEATURE_COOKIE_JAR */
3208 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3210 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
3211 return crumble(csp, header);
3213 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3215 /* Flag whether or not to log a message */
3218 /* A variable to store the tag we're working on */
3221 /* Skip "Set-Cookie:" (11 characters) in header */
3222 cur_tag = *header + 11;
3224 /* skip whitespace between "Set-Cookie:" and value */
3225 while (*cur_tag && ijb_isspace(*cur_tag))
3230 /* Loop through each tag in the cookie */
3234 char *next_tag = strchr(cur_tag, ';');
3235 if (next_tag != NULL)
3237 /* Skip the ';' character itself */
3240 /* skip whitespace ";" and start of tag */
3241 while (*next_tag && ijb_isspace(*next_tag))
3248 /* "Next tag" is the end of the string */
3249 next_tag = cur_tag + strlen(cur_tag);
3252 /* Is this the "Expires" tag? */
3253 if (strncmpic(cur_tag, "expires=", 8) == 0)
3255 /* Delete the tag by copying the rest of the string over it.
3256 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3257 * since the behaviour of strcpy is undefined for overlapping
3260 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3262 /* That changed the header, need to issue a log message */
3265 /* Note that the next tag has now been moved to *cur_tag,
3266 * so we do not need to update the cur_tag pointer.
3271 /* Move on to next cookie tag */
3278 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
3286 #ifdef FEATURE_FORCE_LOAD
3287 /*********************************************************************
3289 * Function : strclean
3291 * Description : In-Situ-Eliminate all occurances of substring in
3295 * 1 : string = string to clean
3296 * 2 : substring = substring to eliminate
3298 * Returns : Number of eliminations
3300 *********************************************************************/
3301 int strclean(const char *string, const char *substring)
3307 len = strlen(substring);
3309 while((pos = strstr(string, substring)) != NULL)
3316 while (*p++ != '\0');
3323 #endif /* def FEATURE_FORCE_LOAD */
3325 /*********************************************************************
3327 * Function : parse_header_time
3329 * Description : Transforms time inside a HTTP header into
3330 * the usual time format.
3333 * 1 : header = header to parse
3334 * 2 : tm = storage for the resulting time in seconds
3336 * Returns : Time struct containing the header time, or
3337 * NULL in case of a parsing problems.
3339 *********************************************************************/
3340 struct tm *parse_header_time(char *header, time_t *tm) {
3344 struct tm * timeptr;
3347 * Initializing gmt to prevent time zone offsets.
3349 * While this is only necessary on some platforms
3350 * (mingw32 for example), I don't know how to
3351 * detect these automatically and doing it everywhere
3355 #ifdef HAVE_LOCALTIME_R
3356 gmt = *localtime_r(tm, &gmt);
3357 #elif FEATURE_PTHREAD
3358 pthread_mutex_lock(&localtime_mutex);
3359 gmt = *localtime(tm);
3360 pthread_mutex_unlock(&localtime_mutex);
3362 gmt = *localtime(tm);
3365 /* Skipping header name */
3366 timestring = strstr(header, ": ");
3367 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)
3380 /*********************************************************************
3382 * Function : get_destination_from_headers
3384 * Description : Parse the "Host:" header to get the request's destination.
3385 * Only needed if the client's request was forcefully
3386 * redirected into Privoxy.
3388 * Code mainly copied from client_host() which is currently
3389 * run too late for this purpose.
3392 * 1 : headers = List of headers (one of them hopefully being
3393 * the "Host:" header)
3394 * 2 : http = storage for the result (host, port and hostport).
3396 * Returns : JB_ERR_MEMORY in case of memory problems,
3397 * JB_ERR_PARSE if the host header couldn't be found,
3398 * JB_ERR_OK otherwise.
3400 *********************************************************************/
3401 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3407 host = get_header_value(headers, "Host:");
3411 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3412 return JB_ERR_PARSE;
3415 if (NULL == (p = strdup((host))))
3417 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3418 return JB_ERR_MEMORY;
3421 if (NULL == (q = strdup(p)))
3424 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3425 return JB_ERR_MEMORY;
3428 freez(http->hostport);
3432 q = strchr(http->host, ':');
3435 /* Terminate hostname and evaluate port string */
3437 http->port = atoi(q);
3441 http->port = http->ssl ? 443 : 80;
3444 /* Rebuild request URL */
3446 http->url = strdup(http->ssl ? "https://" : "http://");
3447 string_append(&http->url, http->hostport);
3448 string_append(&http->url, http->path);
3449 if (http->url == NULL)
3451 return JB_ERR_MEMORY;
3454 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",