1 const char parsers_rcs[] = "$Id: parsers.c,v 1.82 2007/01/01 19:36:37 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.82 2007/01/01 19:36:37 fabiankeil
49 * Integrate a modified version of Wil Mahan's
50 * zlib patch (PR #895531).
52 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
53 * Skip empty filter files in filter_header()
54 * but don't ignore the ones that come afterwards.
55 * Fixes BR 1619208, this time for real.
57 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
58 * Reverted parts of my last commit
59 * to keep error handling working.
61 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
62 * Fixed gcc43 conversion warnings.
64 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
65 * Bringing back the "useless" localtime() call
66 * I removed in revision 1.67. On some platforms
67 * it's necessary to prevent time zone offsets.
69 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
70 * Rebuild request URL in get_destination_from_headers()
71 * to make sure redirect{pcrs command} works as expected
72 * for intercepted requests.
74 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
75 * Added get_destination_from_headers().
77 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
78 * Make pthread mutex locking more generic. Instead of
79 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
80 * and use mutex locking unless there is an _r function
81 * available. Better safe than sorry.
83 * Fixes "./configure --disable-pthread" and should result
84 * in less threading-related problems on pthread-using platforms,
85 * but it still doesn't fix BR#1122404.
87 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
88 * The special header "X-Filter: No" now disables
89 * header filtering as well.
91 * Revision 1.73 2006/09/23 13:26:38 roro
92 * Replace TABs by spaces in source code.
94 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
95 * Don't print a log message every time filter_headers is
96 * entered or left. It only creates noise without any real
99 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
100 * Fix +hide-if-modified-since{-n}.
102 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
103 * Have hide-if-modified-since interpret the random
104 * range value as minutes instead of hours. Allows
105 * more fine-grained configuration.
107 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
108 * Always have parse_header_time return a pointer
109 * that actual makes sense, even though we currently
110 * only need it to detect problems.
112 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
113 * Added config option enable-remote-http-toggle
114 * to specify if Privoxy should recognize special
115 * headers (currently only X-Filter) to change its
116 * behaviour. Disabled by default.
118 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
119 * After filtering de-chunked instances, remove
120 * "Transfer-Encoding" header entirely instead of changing
121 * it to "Transfer-Encoding: identity", which is invalid.
122 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
124 * Don't use localtime in parse_header_time. An empty time struct
125 * is good enough, it gets overwritten by strptime anyway.
127 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
128 * Use gmtime_r if available, fallback to gmtime with mutex
129 * protection for MacOSX and use vanilla gmtime for the rest.
131 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
132 * Changed client_referrer to use the right type (size_t) for
133 * hostlenght and to shorten the temporary referrer string with
134 * '\0' instead of adding a useless line break.
136 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
137 * - Back to timegm() using GnuPG's replacement if necessary.
138 * Using mktime() and localtime() could add a on hour offset if
139 * the randomize factor was big enough to lead to a summer/wintertime
142 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
144 * - Moved randomization code into pick_from_range().
146 * - Changed parse_header_time definition.
147 * time_t isn't guaranteed to be signed and
148 * if it isn't, -1 isn't available as error code.
149 * Changed some variable types in client_if_modified_since()
150 * because of the same reason.
152 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
153 * OS/2 compilation compatibility fixups
155 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
156 * Changed include from strptime.c to strptime.h
158 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
159 * Split filter-headers{} into filter-client-headers{}
160 * and filter-server-headers{}.
161 * Added parse_header_time() to share some code.
162 * Replaced timegm() with mktime().
164 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
165 * Windows service integration
167 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
168 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
170 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
171 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
172 * with what was really the latest development (the v_3_0_branch branch)
174 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
175 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
177 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
178 * Add the ability to check jpeg images for invalid
179 * lengths of comment blocks. Defensive strategy
180 * against the exploit:
181 * Microsoft Security Bulletin MS04-028
182 * Buffer Overrun in JPEG Processing (GDI+) Could
183 * Allow Code Execution (833987)
184 * Enabled with +inspect-jpegs in actions files.
186 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
187 * Excluded text/plain objects from filtering. This fixes a
188 * couple of client-crashing, download corruption and
189 * Privoxy performance issues, whose root cause lies in
190 * web servers labelling content of unknown type as text/plain.
192 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
193 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
195 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
196 * Completing the previous change
198 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
199 * Added temporary workaround for bug in PHP < 4.2.3
201 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
202 * 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.
204 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
205 * Fix typo: supressed -> suppressed
207 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
208 * Improved cookie logging
210 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
211 * Added basic support for OPTIONS and TRACE HTTP methods:
212 * - New parser function client_max_forwards which decrements
213 * the Max-Forwards HTTP header field of OPTIONS and TRACE
214 * requests by one before forwarding
215 * - New parser function client_host which extracts the host
216 * and port information from the HTTP header field if the
217 * request URI was not absolute
218 * - Don't crumble and re-add the Host: header, but only generate
219 * and append if missing
221 * Revision 1.56 2002/05/12 15:34:22 jongfoster
222 * Fixing typo in a comment
224 * Revision 1.55 2002/05/08 16:01:07 oes
225 * Optimized add_to_iob:
226 * - Use realloc instead of malloc(), memcpy(), free()
227 * - Expand to powers of two if possible, to get
228 * O(log n) reallocs instead of O(n).
229 * - Moved check for buffer limit here from chat
230 * - Report failure via returncode
232 * Revision 1.54 2002/04/02 15:03:16 oes
233 * Tiny code cosmetics
235 * Revision 1.53 2002/03/26 22:29:55 swa
236 * we have a new homepage!
238 * Revision 1.52 2002/03/24 13:25:43 swa
239 * name change related issues
241 * Revision 1.51 2002/03/13 00:27:05 jongfoster
244 * Revision 1.50 2002/03/12 01:45:35 oes
245 * More verbose logging
247 * Revision 1.49 2002/03/09 20:03:52 jongfoster
248 * - Making various functions return int rather than size_t.
249 * (Undoing a recent change). Since size_t is unsigned on
250 * Windows, functions like read_socket that return -1 on
251 * error cannot return a size_t.
253 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
254 * crashes, and also frequently caused JB to jump to 100%
255 * CPU and stay there. (Because it thought it had just
256 * read ((unsigned)-1) == 4Gb of data...)
258 * - The signature of write_socket has changed, it now simply
259 * returns success=0/failure=nonzero.
261 * - Trying to get rid of a few warnings --with-debug on
262 * Windows, I've introduced a new type "jb_socket". This is
263 * used for the socket file descriptors. On Windows, this
264 * is SOCKET (a typedef for unsigned). Everywhere else, it's
265 * an int. The error value can't be -1 any more, so it's
266 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
267 * Windows it maps to the #define INVALID_SOCKET.)
269 * - The signature of bind_port has changed.
271 * Revision 1.48 2002/03/07 03:46:53 oes
272 * Fixed compiler warnings etc
274 * Revision 1.47 2002/02/20 23:15:13 jongfoster
275 * Parsing functions now handle out-of-memory gracefully by returning
278 * Revision 1.46 2002/01/17 21:03:47 jongfoster
279 * Moving all our URL and URL pattern parsing code to urlmatch.c.
281 * Revision 1.45 2002/01/09 14:33:03 oes
282 * Added support for localtime_r.
284 * Revision 1.44 2001/12/14 01:22:54 steudten
285 * Remove 'user:pass@' from 'proto://user:pass@host' for the
286 * new added header 'Host: ..'. (See Req ID 491818)
288 * Revision 1.43 2001/11/23 00:26:38 jongfoster
289 * Fixing two really stupid errors in my previous commit
291 * Revision 1.42 2001/11/22 21:59:30 jongfoster
292 * Adding code to handle +no-cookies-keep
294 * Revision 1.41 2001/11/05 23:43:05 steudten
295 * Add time+date to log files.
297 * Revision 1.40 2001/10/26 20:13:09 jongfoster
298 * ctype.h is needed in Windows, too.
300 * Revision 1.39 2001/10/26 17:40:04 oes
301 * Introduced get_header_value()
302 * Removed http->user_agent, csp->referrer and csp->accept_types
303 * Removed client_accept()
305 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
306 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
307 * threads to call select() simultaneously. So, it's time to do a real, live,
308 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
309 * (native). Both versions will work, but using __OS2__ offers multi-threading.
311 * Revision 1.37 2001/10/23 21:36:02 jongfoster
312 * Documenting sed()'s error behaviou (doc change only)
314 * Revision 1.36 2001/10/13 12:51:51 joergs
315 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
316 * force-load), instead crumble Host: and add it (again) in client_host_adder
317 * (in case we get a HTTP/1.0 request without Host: header and forward it to
318 * a HTTP/1.1 server/proxy).
320 * Revision 1.35 2001/10/09 22:39:21 jongfoster
321 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
324 * Revision 1.34 2001/10/07 18:50:55 oes
325 * Added server_content_encoding, renamed server_transfer_encoding
327 * Revision 1.33 2001/10/07 18:04:49 oes
328 * Changed server_http11 to server_http and its pattern to "HTTP".
329 * Additional functionality: it now saves the HTTP status into
330 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
332 * Revision 1.32 2001/10/07 15:43:28 oes
333 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
334 * client_te and client_accept_encoding_adder, triggered by the new
335 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
336 * changed to allow only identity and chunked, and the TE header is
337 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
339 * parse_http_request no longer does anything than parsing. The rewriting
340 * of http->cmd and version mangling are gone. It now also recognizes
341 * the put and delete methods and saves the url in http->url. Removed
344 * renamed content_type and content_length to have the server_ prefix
346 * server_content_type now only works if csp->content_type != CT_TABOO
348 * added server_transfer_encoding, which
349 * - Sets CT_TABOO to prohibit filtering if encoding compresses
350 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
351 * - Change from "chunked" to "identity" if body was chunked
352 * but has been de-chunked for filtering.
354 * added server_content_md5 which crunches any Content-MD5 headers
355 * if the body was modified.
357 * made server_http11 conditional on +downgrade action
359 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
361 * Revision 1.31 2001/10/05 14:25:02 oes
362 * Crumble Keep-Alive from Server
364 * Revision 1.30 2001/09/29 12:56:03 joergs
365 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
367 * Revision 1.29 2001/09/24 21:09:24 jongfoster
368 * Fixing 2 memory leaks that Guy spotted, where the paramater to
369 * enlist() was not being free()d.
371 * Revision 1.28 2001/09/22 16:32:28 jongfoster
372 * Removing unused #includes.
374 * Revision 1.27 2001/09/20 15:45:25 steudten
376 * add casting from size_t to int for printf()
377 * remove local variable shadow s2
379 * Revision 1.26 2001/09/16 17:05:14 jongfoster
380 * Removing unused #include showarg.h
382 * Revision 1.25 2001/09/16 13:21:27 jongfoster
383 * Changes to use new list functions.
385 * Revision 1.24 2001/09/13 23:05:50 jongfoster
386 * Changing the string paramater to the header parsers a "const".
388 * Revision 1.23 2001/09/12 18:08:19 steudten
390 * In parse_http_request() header rewriting miss the host value, so
391 * from http://www.mydomain.com the result was just " / " not
392 * http://www.mydomain.com/ in case we forward.
394 * Revision 1.22 2001/09/10 10:58:53 oes
395 * Silenced compiler warnings
397 * Revision 1.21 2001/07/31 14:46:00 oes
398 * - Persistant connections now suppressed
399 * - sed() no longer appends empty header to csp->headers
401 * Revision 1.20 2001/07/30 22:08:36 jongfoster
402 * Tidying up #defines:
403 * - All feature #defines are now of the form FEATURE_xxx
404 * - Permanently turned off WIN_GUI_EDIT
405 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
407 * Revision 1.19 2001/07/25 17:21:54 oes
408 * client_uagent now saves copy of User-Agent: header value
410 * Revision 1.18 2001/07/13 14:02:46 oes
411 * - Included fix to repair broken HTTP requests that
412 * don't contain a path, not even '/'.
413 * - Removed all #ifdef PCRS
414 * - content_type now always inspected and classified as
415 * text, gif or other.
416 * - formatting / comments
418 * Revision 1.17 2001/06/29 21:45:41 oes
419 * Indentation, CRLF->LF, Tab-> Space
421 * Revision 1.16 2001/06/29 13:32:42 oes
423 * - Adapted free_http_request
424 * - Removed logentry from cancelled commit
426 * Revision 1.15 2001/06/03 19:12:38 oes
427 * deleted const struct interceptors
429 * Revision 1.14 2001/06/01 18:49:17 jongfoster
430 * Replaced "list_share" with "list" - the tiny memory gain was not
431 * worth the extra complexity.
433 * Revision 1.13 2001/05/31 21:30:33 jongfoster
434 * Removed list code - it's now in list.[ch]
435 * Renamed "permission" to "action", and changed many features
436 * to use the actions file rather than the global config.
438 * Revision 1.12 2001/05/31 17:33:13 oes
442 * Revision 1.11 2001/05/29 20:11:19 joergs
443 * '/ * inside comment' warning removed.
445 * Revision 1.10 2001/05/29 09:50:24 jongfoster
446 * Unified blocklist/imagelist/permissionslist.
447 * File format is still under discussion, but the internal changes
450 * Also modified interceptor behaviour:
451 * - We now intercept all URLs beginning with one of the following
452 * prefixes (and *only* these prefixes):
454 * * http://ijbswa.sf.net/config/
455 * * http://ijbswa.sourceforge.net/config/
456 * - New interceptors "home page" - go to http://i.j.b/ to see it.
457 * - Internal changes so that intercepted and fast redirect pages
458 * are not replaced with an image.
459 * - Interceptors now have the option to send a binary page direct
460 * to the client. (i.e. ijb-send-banner uses this)
461 * - Implemented show-url-info interceptor. (Which is why I needed
462 * the above interceptors changes - a typical URL is
463 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
464 * The previous mechanism would not have intercepted that, and
465 * if it had been intercepted then it then it would have replaced
468 * Revision 1.9 2001/05/28 17:26:33 jongfoster
469 * Fixing segfault if last header was crunched.
470 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
471 * can use the cross-platform sprintf() instead.)
473 * Revision 1.8 2001/05/27 22:17:04 oes
475 * - re_process_buffer no longer writes the modified buffer
476 * to the client, which was very ugly. It now returns the
477 * buffer, which it is then written by chat.
479 * - content_length now adjusts the Content-Length: header
480 * for modified documents rather than crunch()ing it.
481 * (Length info in csp->content_length, which is 0 for
482 * unmodified documents)
484 * - For this to work, sed() is called twice when filtering.
486 * Revision 1.7 2001/05/27 13:19:06 oes
487 * Patched Joergs solution for the content-length in.
489 * Revision 1.6 2001/05/26 13:39:32 jongfoster
490 * Only crunches Content-Length header if applying RE filtering.
491 * Without this fix, Microsoft Windows Update wouldn't work.
493 * Revision 1.5 2001/05/26 00:28:36 jongfoster
494 * Automatic reloading of config file.
495 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
496 * Most of the global variables have been moved to a new
497 * struct configuration_spec, accessed through csp->config->globalname
498 * Most of the globals remaining are used by the Win32 GUI.
500 * Revision 1.4 2001/05/22 18:46:04 oes
502 * - Enabled filtering banners by size rather than URL
503 * by adding patterns that replace all standard banner
504 * sizes with the "Junkbuster" gif to the re_filterfile
506 * - Enabled filtering WebBugs by providing a pattern
507 * which kills all 1x1 images
509 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
510 * which is selected by the (nonstandard and therefore
511 * capital) letter 'U' in the option string.
512 * It causes the quantifiers to be ungreedy by default.
513 * Appending a ? turns back to greedy (!).
515 * - Added a new interceptor ijb-send-banner, which
516 * sends back the "Junkbuster" gif. Without imagelist or
517 * MSIE detection support, or if tinygif = 1, or the
518 * URL isn't recognized as an imageurl, a lame HTML
519 * explanation is sent instead.
521 * - Added new feature, which permits blocking remote
522 * script redirects and firing back a local redirect
524 * The feature is conditionally compiled, i.e. it
525 * can be disabled with --disable-fast-redirects,
526 * plus it must be activated by a "fast-redirects"
527 * line in the config file, has its own log level
528 * and of course wants to be displayed by show-proxy-args
529 * Note: Boy, all the #ifdefs in 1001 locations and
530 * all the fumbling with configure.in and acconfig.h
531 * were *way* more work than the feature itself :-(
533 * - Because a generic redirect template was needed for
534 * this, tinygif = 3 now uses the same.
536 * - Moved GIFs, and other static HTTP response templates
541 * - Removed some >400 CRs again (Jon, you really worked
544 * Revision 1.3 2001/05/20 01:21:20 jongfoster
545 * Version 2.9.4 checkin.
546 * - Merged popupfile and cookiefile, and added control over PCRS
547 * filtering, in new "permissionsfile".
548 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
549 * file error you now get a message box (in the Win32 GUI) rather
550 * than the program exiting with no explanation.
551 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
553 * - Removed tabs from "config"
554 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
555 * - Bumped up version number.
557 * Revision 1.2 2001/05/17 23:02:36 oes
558 * - Made referrer option accept 'L' as a substitute for '§'
560 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
561 * Initial import of version 2.9.3 source tree
564 *********************************************************************/
571 #include <sys/types.h>
584 #if !defined(_WIN32) && !defined(__OS2__)
590 #ifdef FEATURE_PTHREAD
592 /* jcc.h is for mutex semapores only */
593 #endif /* def FEATURE_PTHREAD */
599 #include "jbsockets.h"
600 #include "miscutil.h"
603 #ifndef HAVE_STRPTIME
604 #include "strptime.h"
607 const char parsers_h_rcs[] = PARSERS_H_VERSION;
609 /* Fix a problem with Solaris. There should be no effect on other
611 * Solaris's isspace() is a macro which uses it's argument directly
612 * as an array index. Therefore we need to make sure that high-bit
613 * characters generate +ve values, and ideally we also want to make
614 * the argument match the declared parameter type of "int".
616 * Why did they write a character function that can't take a simple
617 * "char" argument? Doh!
619 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
620 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
623 const struct parsers client_patterns[] = {
624 { "referer:", 8, client_referrer },
625 { "user-agent:", 11, client_uagent },
626 { "ua-", 3, client_ua },
627 { "from:", 5, client_from },
628 { "cookie:", 7, client_send_cookie },
629 { "x-forwarded-for:", 16, client_x_forwarded },
630 { "Accept-Encoding:", 16, client_accept_encoding },
631 { "TE:", 3, client_te },
632 { "Host:", 5, client_host },
633 { "if-modified-since:", 18, client_if_modified_since },
634 { "Keep-Alive:", 11, crumble },
635 { "connection:", 11, crumble },
636 { "proxy-connection:", 17, crumble },
637 { "max-forwards:", 13, client_max_forwards },
638 { "Accept-Language:", 16, client_accept_language },
639 { "if-none-match:", 14, client_if_none_match },
640 { "X-Filter:", 9, client_x_filter },
641 { "*", 0, crunch_client_header },
642 { "*", 0, filter_client_header },
646 const struct parsers server_patterns[] = {
647 { "HTTP", 4, server_http },
648 { "set-cookie:", 11, server_set_cookie },
649 { "connection:", 11, crumble },
650 { "Content-Type:", 13, server_content_type },
651 { "Content-Length:", 15, server_content_length },
652 { "Content-MD5:", 12, server_content_md5 },
653 { "Content-Encoding:", 17, server_content_encoding },
654 { "Transfer-Encoding:", 18, server_transfer_coding },
655 { "Keep-Alive:", 11, crumble },
656 { "content-disposition:", 20, server_content_disposition },
657 { "Last-Modified:", 14, server_last_modified },
658 { "*", 0, crunch_server_header },
659 { "*", 0, filter_server_header },
663 const struct parsers server_patterns_light[] = {
664 { "Content-Length:", 15, server_content_length },
665 { "Transfer-Encoding:", 18, server_transfer_coding },
667 { "Content-Encoding:", 17, server_content_encoding },
668 #endif /* def FEATURE_ZLIB */
672 const add_header_func_ptr add_client_headers[] = {
675 client_x_forwarded_adder,
677 /* Temporarily disabled: client_accept_encoding_adder, */
678 connection_close_adder,
683 const add_header_func_ptr add_server_headers[] = {
684 connection_close_adder,
688 /*********************************************************************
690 * Function : flush_socket
692 * Description : Write any pending "buffered" content.
695 * 1 : fd = file descriptor of the socket to read
696 * 2 : csp = Current client state (buffers, headers, etc...)
698 * Returns : On success, the number of bytes written are returned (zero
699 * indicates nothing was written). On error, -1 is returned,
700 * and errno is set appropriately. If count is zero and the
701 * file descriptor refers to a regular file, 0 will be
702 * returned without causing any other effect. For a special
703 * file, the results are not portable.
705 *********************************************************************/
706 int flush_socket(jb_socket fd, struct client_state *csp)
708 struct iob *iob = csp->iob;
709 int len = iob->eod - iob->cur;
716 if (write_socket(fd, iob->cur, (size_t)len))
720 iob->eod = iob->cur = iob->buf;
726 /*********************************************************************
728 * Function : add_to_iob
730 * Description : Add content to the buffered page, expanding the
731 * buffer if necessary.
734 * 1 : csp = Current client state (buffers, headers, etc...)
735 * 2 : buf = holds the content to be added to the page
736 * 3 : n = number of bytes to be added
738 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
739 * or buffer limit reached.
741 *********************************************************************/
742 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
744 struct iob *iob = csp->iob;
745 size_t used, offset, need, want;
748 if (n <= 0) return JB_ERR_OK;
750 used = (size_t)(iob->eod - iob->buf);
751 offset = (size_t)(iob->cur - iob->buf);
752 need = used + (size_t)n + 1;
755 * If the buffer can't hold the new data, extend it first.
756 * Use the next power of two if possible, else use the actual need.
758 if (need > csp->config->buffer_limit)
760 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
761 return JB_ERR_MEMORY;
764 if (need > iob->size)
766 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
768 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
772 else if (NULL != (p = (char *)realloc(iob->buf, need)))
778 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
779 return JB_ERR_MEMORY;
782 /* Update the iob pointers */
783 iob->cur = p + offset;
788 /* copy the new data into the iob buffer */
789 memcpy(iob->eod, buf, (size_t)n);
791 /* point to the end of the data */
794 /* null terminate == cheap insurance */
803 /*********************************************************************
805 * Function : decompress_iob
807 * Description : Decompress buffered page, expanding the
808 * buffer as necessary. csp->iob->cur
809 * should point to the the beginning of the
810 * compressed data block.
813 * 1 : csp = Current client state (buffers, headers, etc...)
815 * Returns : JB_ERR_OK on success,
816 * JB_ERR_MEMORY if out-of-memory limit reached, and
817 * JB_ERR_COMPRESS if error decompressing buffer.
819 *********************************************************************/
820 jb_err decompress_iob(struct client_state *csp)
822 char *buf; /* new, uncompressed buffer */
823 size_t bufsize; /* allocated size of the new buffer */
824 size_t skip_size; /* Number of bytes at the beginning of the iob
825 that we should NOT decompress. */
826 int status; /* return status of the inflate() call */
827 z_stream zstr; /* used by calls to zlib */
829 bufsize = csp->iob->size;
830 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
835 * This is to protect the parsing of gzipped data,
836 * but it should(?) be valid for deflated data also.
838 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
839 return JB_ERR_COMPRESS;
842 if (csp->content_type & CT_GZIP)
845 * Our task is slightly complicated by the facts that data
846 * compressed by gzip does not include a zlib header, and
847 * that there is no easily accessible interface in zlib to
848 * handle a gzip header. We strip off the gzip header by
849 * hand, and later inform zlib not to expect a header.
853 * Strip off the gzip header. Please see RFC 1952 for more
854 * explanation of the appropriate fields.
856 if ((*csp->iob->cur++ != (char)0x1f)
857 || (*csp->iob->cur++ != (char)0x8b)
858 || (*csp->iob->cur++ != Z_DEFLATED))
860 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
861 return JB_ERR_COMPRESS;
865 int flags = *csp->iob->cur++;
867 * XXX: These magic numbers should be replaced
868 * with macros to give a better idea what they do.
872 /* The gzip header has reserved bits set; bail out. */
873 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
874 return JB_ERR_COMPRESS;
878 /* Skip extra fields if necessary. */
882 * Skip a given number of bytes, specified
883 * as a 16-bit little-endian value.
885 csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
888 /* Skip the filename if necessary. */
891 /* A null-terminated string follows. */
892 while (*csp->iob->cur++);
895 /* Skip the comment if necessary. */
898 while (*csp->iob->cur++);
901 /* Skip the CRC if necessary. */
908 else if (csp->content_type & CT_DEFLATE)
911 * XXX: The debug level should be lowered
912 * before the next stable release.
914 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *csp->iob->cur);
916 * In theory (that is, according to RFC 1950), deflate-compressed
917 * data should begin with a two-byte zlib header and have an
918 * adler32 checksum at the end. It seems that in practice only
919 * the raw compressed data is sent. Note that this means that
920 * we are not RFC 1950-compliant here, but the advantage is that
921 * this actually works. :)
923 * We add a dummy null byte to tell zlib where the data ends,
924 * and later inform it not to expect a header.
926 * Fortunately, add_to_iob() has thoughtfully null-terminated
927 * the buffer; we can just increment the end pointer to include
934 log_error (LOG_LEVEL_ERROR,
935 "Unable to determine compression format for decompression");
936 return JB_ERR_COMPRESS;
939 /* Set up the fields required by zlib. */
940 zstr.next_in = (Bytef *)csp->iob->cur;
941 zstr.avail_in = (unsigned int)(csp->iob->eod - csp->iob->cur);
942 zstr.zalloc = Z_NULL;
944 zstr.opaque = Z_NULL;
947 * Passing -MAX_WBITS to inflateInit2 tells the library
948 * that there is no zlib header.
950 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
952 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
953 return JB_ERR_COMPRESS;
957 * Next, we allocate new storage for the inflated data.
958 * We don't modify the existing iob yet, so in case there
959 * is error in decompression we can recover gracefully.
961 buf = zalloc (bufsize);
964 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
965 return JB_ERR_MEMORY;
968 assert(bufsize >= skip_size);
969 memcpy(buf, csp->iob->buf, skip_size);
970 zstr.avail_out = bufsize - skip_size;
971 zstr.next_out = (Bytef *)buf + skip_size;
973 /* Try to decompress the whole stream in one shot. */
974 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
976 /* We need to allocate more memory for the output buffer. */
978 char *tmpbuf; /* used for realloc'ing the buffer */
979 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
982 * If zlib wants more data then there's a problem, because
983 * the complete compressed file should have been buffered.
985 if (0 == zstr.avail_in)
987 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
988 return JB_ERR_COMPRESS;
992 * If we tried the limit and still didn't have enough
993 * memory, just give up.
995 if (bufsize == csp->config->buffer_limit)
997 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
998 return JB_ERR_MEMORY;
1001 /* Try doubling the buffer size each time. */
1004 /* Don't exceed the buffer limit. */
1005 if (bufsize > csp->config->buffer_limit)
1007 bufsize = csp->config->buffer_limit;
1010 /* Try to allocate the new buffer. */
1011 tmpbuf = realloc(buf, bufsize);
1014 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1016 return JB_ERR_MEMORY;
1020 char *oldnext_out = (char *)zstr.next_out;
1023 * Update the fields for inflate() to use the new
1024 * buffer, which may be in a location different from
1027 zstr.avail_out += bufsize - oldbufsize;
1028 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1031 * Compare with an uglier method of calculating these values
1032 * that doesn't require the extra oldbufsize variable.
1034 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1035 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1036 assert(zstr.avail_out > 0);
1042 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1044 log_error(LOG_LEVEL_ERROR,
1045 "Inconsistent stream state after decompression: %s", zstr.msg);
1047 * XXX: Intentionally no return.
1049 * According to zlib.h, Z_STREAM_ERROR is returned
1050 * "if the stream state was inconsistent".
1052 * I assume in this case inflate()'s status
1053 * would also be something different than Z_STREAM_END
1054 * so this check should be redundant, but lets see.
1058 if (status != Z_STREAM_END)
1060 /* We failed to decompress the stream. */
1061 log_error(LOG_LEVEL_ERROR,
1062 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1063 return JB_ERR_COMPRESS;
1067 * Finally, we can actually update the iob, since the
1068 * decompression was successful. First, free the old
1071 freez(csp->iob->buf);
1073 /* Now, update the iob to use the new buffer. */
1074 csp->iob->buf = buf;
1075 csp->iob->cur = csp->iob->buf + skip_size;
1076 csp->iob->eod = (char *)zstr.next_out;
1077 csp->iob->size = bufsize;
1080 * Make sure the new uncompressed iob obeys some minimal
1081 * consistency conditions.
1083 if ((csp->iob->buf < csp->iob->cur)
1084 && (csp->iob->cur <= csp->iob->eod)
1085 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1087 char t = csp->iob->cur[100];
1088 csp->iob->cur[100] = '\0';
1090 * XXX: The debug level should be lowered
1091 * before the next stable release.
1093 log_error(LOG_LEVEL_INFO, "Sucessfully decompressed: %s", csp->iob->cur);
1094 csp->iob->cur[100] = t;
1099 /* It seems that zlib did something weird. */
1100 log_error(LOG_LEVEL_ERROR,
1101 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1102 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1103 csp->iob->eod, csp->iob->buf + csp->iob->size);
1104 return JB_ERR_COMPRESS;
1108 #endif /* defined(FEATURE_ZLIB) */
1111 /*********************************************************************
1113 * Function : get_header
1115 * Description : This (odd) routine will parse the csp->iob
1118 * 1 : csp = Current client state (buffers, headers, etc...)
1120 * Returns : Any one of the following:
1122 * 1) a pointer to a dynamically allocated string that contains a header line
1123 * 2) NULL indicating that the end of the header was reached
1124 * 3) "" indicating that the end of the iob was reached before finding
1125 * a complete header line.
1127 *********************************************************************/
1128 char *get_header(struct client_state *csp)
1134 if ((iob->cur == NULL)
1135 || ((p = strchr(iob->cur, '\n')) == NULL))
1137 return(""); /* couldn't find a complete header */
1142 ret = strdup(iob->cur);
1145 /* FIXME No way to handle error properly */
1146 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1151 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1153 /* is this a blank line (i.e. the end of the header) ? */
1165 /*********************************************************************
1167 * Function : get_header_value
1169 * Description : Get the value of a given header from a chained list
1170 * of header lines or return NULL if no such header is
1171 * present in the list.
1174 * 1 : header_list = pointer to list
1175 * 2 : header_name = string with name of header to look for.
1176 * Trailing colon required, capitalization
1179 * Returns : NULL if not found, else value of header
1181 *********************************************************************/
1182 char *get_header_value(const struct list *header_list, const char *header_name)
1184 struct list_entry *cur_entry;
1188 assert(header_list);
1189 assert(header_name);
1190 length = strlen(header_name);
1192 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1196 if (!strncmpic(cur_entry->str, header_name, length))
1199 * Found: return pointer to start of value
1201 ret = (char *) (cur_entry->str + length);
1202 while (*ret && ijb_isspace(*ret)) ret++;
1215 /*********************************************************************
1219 * Description : add, delete or modify lines in the HTTP header streams.
1220 * On entry, it receives a linked list of headers space
1221 * that was allocated dynamically (both the list nodes
1222 * and the header contents).
1224 * As a side effect it frees the space used by the original
1228 * 1 : pats = list of patterns to match against headers
1229 * 2 : more_headers = list of functions to add more
1230 * headers (client or server)
1231 * 3 : csp = Current client state (buffers, headers, etc...)
1233 * Returns : Single pointer to a fully formed header, or NULL
1234 * on out-of-memory error.
1236 *********************************************************************/
1237 char *sed(const struct parsers pats[],
1238 const add_header_func_ptr more_headers[],
1239 struct client_state *csp)
1241 struct list_entry *p;
1242 const struct parsers *v;
1243 const add_header_func_ptr *f;
1244 jb_err err = JB_ERR_OK;
1248 * If filtering is enabled, sed is run twice,
1249 * but most of the work needs to be done only once.
1251 first_run = (more_headers != NULL ) ? 1 : 0;
1253 if (first_run) /* Parse and print */
1255 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1257 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1259 /* Header crunch()ed in previous run? -> ignore */
1260 if (p->str == NULL) continue;
1262 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
1264 /* Does the current parser handle this header? */
1265 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1267 err = v->parser(csp, (char **)&(p->str));
1271 /* place any additional headers on the csp->headers list */
1272 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1277 else /* Parse only */
1280 * The second run is only needed if the body was modified
1281 * and the content-lenght has changed.
1283 if (strncmpic(csp->http->cmd, "HEAD", 4))
1285 /*XXX: Code duplication */
1286 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1288 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1290 /* Header crunch()ed in previous run? -> ignore */
1291 if (p->str == NULL) continue;
1293 /* Does the current parser handle this header? */
1294 if (strncmpic(p->str, v->str, v->len) == 0)
1296 err = v->parser(csp, (char **)&(p->str));
1303 if (err != JB_ERR_OK)
1308 return list_to_text(csp->headers);
1312 /* here begins the family of parser functions that reformat header lines */
1314 /*********************************************************************
1316 * Function : filter_server_header
1318 * Description : Checks if server header filtering is enabled.
1319 * If it is, filter_header is called to do the work.
1322 * 1 : csp = Current client state (buffers, headers, etc...)
1323 * 2 : header = On input, pointer to header to modify.
1324 * On output, pointer to the modified header, or NULL
1325 * to remove the header. This function frees the
1326 * original string if necessary.
1328 * Returns : JB_ERR_OK on success and always succeeds
1330 *********************************************************************/
1331 jb_err filter_server_header(struct client_state *csp, char **header)
1333 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
1335 filter_header(csp, header);
1340 /*********************************************************************
1342 * Function : filter_client_header
1344 * Description : Checks if client header filtering is enabled.
1345 * If it is, filter_header is called to do the work.
1348 * 1 : csp = Current client state (buffers, headers, etc...)
1349 * 2 : header = On input, pointer to header to modify.
1350 * On output, pointer to the modified header, or NULL
1351 * to remove the header. This function frees the
1352 * original string if necessary.
1354 * Returns : JB_ERR_OK on success and always succeeds
1356 *********************************************************************/
1357 jb_err filter_client_header(struct client_state *csp, char **header)
1359 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
1361 filter_header(csp, header);
1366 /*********************************************************************
1368 * Function : filter_header
1370 * Description : Executes all text substitutions from all applying
1371 * +filter actions on the header.
1372 * Most of the code was copied from pcrs_filter_response,
1373 * including the rather short variable names
1376 * 1 : csp = Current client state (buffers, headers, etc...)
1377 * 2 : header = On input, pointer to header to modify.
1378 * On output, pointer to the modified header, or NULL
1379 * to remove the header. This function frees the
1380 * original string if necessary.
1382 * Returns : JB_ERR_OK on success and always succeeds
1384 *********************************************************************/
1385 jb_err filter_header(struct client_state *csp, char **header)
1389 size_t size = strlen(*header);
1391 char *newheader = NULL;
1394 struct file_list *fl;
1395 struct re_filterfile_spec *b;
1396 struct list_entry *filtername;
1398 int i, found_filters = 0;
1401 * Need to check the set of re_filterfiles...
1403 for (i = 0; i < MAX_AF_FILES; i++)
1416 if (0 == found_filters)
1418 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1422 for (i = 0; i < MAX_AF_FILES; i++)
1425 if ((NULL == fl) || (NULL == fl->f))
1428 * Either there are no filter files
1429 * left, or this filter file just
1430 * contains no valid filters.
1432 * Continue to be sure we don't miss
1433 * valid filter files that are chained
1434 * after empty or invalid ones.
1439 * For all applying +filter actions, look if a filter by that
1440 * name exists and if yes, execute its pcrs_joblist on the
1443 for (b = fl->f; b; b = b->next)
1445 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1446 filtername ; filtername = filtername->next)
1448 if (strcmp(b->name, filtername->str) == 0)
1450 int current_hits = 0;
1452 if ( NULL == b->joblist )
1454 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1458 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1459 *header, size, b->name);
1461 /* Apply all jobs from the joblist */
1462 for (job = b->joblist; NULL != job; job = job->next)
1464 matches = pcrs_execute(job, *header, size, &newheader, &size);
1467 current_hits += matches;
1468 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1470 *header = newheader;
1472 else if ( 0 == matches )
1474 /* Filter doesn't change header */
1480 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1481 *header, b->name, pcrs_strerror(matches));
1482 if( newheader != NULL)
1484 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1489 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1490 hits += current_hits;
1498 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1506 /*********************************************************************
1508 * Function : crumble
1510 * Description : This is called if a header matches a pattern to "crunch"
1513 * 1 : csp = Current client state (buffers, headers, etc...)
1514 * 2 : header = On input, pointer to header to modify.
1515 * On output, pointer to the modified header, or NULL
1516 * to remove the header. This function frees the
1517 * original string if necessary.
1519 * Returns : JB_ERR_OK on success, or
1520 * JB_ERR_MEMORY on out-of-memory error.
1522 *********************************************************************/
1523 jb_err crumble(struct client_state *csp, char **header)
1525 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1530 /*********************************************************************
1532 * Function : crunch_server_header
1534 * Description : Crunch server header if it matches a string supplied by the
1535 * user. Called from `sed'.
1538 * 1 : csp = Current client state (buffers, headers, etc...)
1539 * 2 : header = On input, pointer to header to modify.
1540 * On output, pointer to the modified header, or NULL
1541 * to remove the header. This function frees the
1542 * original string if necessary.
1544 * Returns : JB_ERR_OK on success and always succeeds
1546 *********************************************************************/
1547 jb_err crunch_server_header(struct client_state *csp, char **header)
1549 const char *crunch_pattern;
1550 /*Is there a header to crunch*/
1552 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1554 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1556 /*Is the current header the lucky one?*/
1557 if (strstr(*header, crunch_pattern))
1559 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1566 /*********************************************************************
1568 * Function : server_content_type
1570 * Description : Set the content-type for filterable types (text/.*,
1571 * javascript and image/gif) unless filtering has been
1572 * forbidden (CT_TABOO) while parsing earlier headers.
1573 * NOTE: Since text/plain is commonly used by web servers
1574 * for files whose correct type is unknown, we don't
1575 * set CT_TEXT for it.
1578 * 1 : csp = Current client state (buffers, headers, etc...)
1579 * 2 : header = On input, pointer to header to modify.
1580 * On output, pointer to the modified header, or NULL
1581 * to remove the header. This function frees the
1582 * original string if necessary.
1584 * Returns : JB_ERR_OK on success, or
1585 * JB_ERR_MEMORY on out-of-memory error.
1587 *********************************************************************/
1588 jb_err server_content_type(struct client_state *csp, char **header)
1592 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1594 assert(!csp->content_type || (csp->content_type == CT_TABOO));
1596 if (!(csp->content_type & CT_TABOO))
1598 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1599 || strstr(*header, "xml")
1600 || strstr(*header, "application/x-javascript"))
1602 csp->content_type |= CT_TEXT;
1604 else if (strstr(*header, " image/gif"))
1606 csp->content_type |= CT_GIF;
1608 else if (strstr(*header, " image/jpeg"))
1610 csp->content_type |= CT_JPEG;
1614 csp->content_type = 0;
1618 * Are we enabling text mode by force?
1620 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1623 * Do we really have to?
1625 if (csp->content_type & CT_TEXT)
1627 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1631 csp->content_type |= CT_TEXT;
1632 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1636 * Are we messing with the content type?
1638 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1641 * Make sure the user doesn't accidently
1642 * change the content type of binary documents.
1644 if (csp->content_type & CT_TEXT)
1647 *header = strdup("Content-Type: ");
1648 string_append(header, newval);
1652 log_error(LOG_LEVEL_HEADER,
1653 "Insufficient memory. Content-Type crunched without replacement!");
1654 return JB_ERR_MEMORY;
1656 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1660 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1661 "Enable force-text-mode if you know what you're doing.", *header);
1668 /*********************************************************************
1670 * Function : server_transfer_coding
1672 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1673 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1674 * - Remove header if body was chunked but has been
1675 * de-chunked for filtering.
1678 * 1 : csp = Current client state (buffers, headers, etc...)
1679 * 2 : header = On input, pointer to header to modify.
1680 * On output, pointer to the modified header, or NULL
1681 * to remove the header. This function frees the
1682 * original string if necessary.
1684 * Returns : JB_ERR_OK on success, or
1685 * JB_ERR_MEMORY on out-of-memory error.
1687 *********************************************************************/
1688 jb_err server_transfer_coding(struct client_state *csp, char **header)
1691 * Turn off pcrs and gif filtering if body compressed
1693 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1697 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1699 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1700 csp->http->cmd, *header);
1701 #endif /* def FEATURE_ZLIB */
1702 csp->content_type = CT_TABOO;
1706 * Raise flag if body chunked
1708 if (strstr(*header, "chunked"))
1710 csp->flags |= CSP_FLAG_CHUNKED;
1713 * If the body was modified, it has been de-chunked first
1714 * and the header must be removed.
1716 * FIXME: If there is more than one transfer encoding,
1717 * only the "chunked" part should be removed here.
1719 if (csp->flags & CSP_FLAG_MODIFIED)
1721 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1730 /*********************************************************************
1732 * Function : server_content_encoding
1734 * Description : This function is run twice for each request,
1735 * unless FEATURE_ZLIB and filtering are disabled.
1737 * The first run is used to check if the content
1738 * is compressed, if FEATURE_ZLIB is disabled
1739 * filtering is then disabled as well, if FEATURE_ZLIB
1740 * is enabled the content is marked for decompression.
1742 * The second run is used to remove the Content-Encoding
1743 * header if the decompression was successful.
1746 * 1 : csp = Current client state (buffers, headers, etc...)
1747 * 2 : header = On input, pointer to header to modify.
1748 * On output, pointer to the modified header, or NULL
1749 * to remove the header. This function frees the
1750 * original string if necessary.
1752 * Returns : JB_ERR_OK on success, or
1753 * JB_ERR_MEMORY on out-of-memory error.
1755 *********************************************************************/
1756 jb_err server_content_encoding(struct client_state *csp, char **header)
1759 /* XXX: Why would we modify the content if it was taboo? */
1760 if ((csp->flags & CSP_FLAG_MODIFIED) && !(csp->content_type & CT_TABOO))
1763 * We successfully decompressed the content,
1764 * and have to clean the header now, so the
1765 * client no longer expects compressed data..
1767 * XXX: There is a difference between cleaning
1768 * and removing it completely.
1770 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1773 else if (strstr(*header, "gzip"))
1775 /* Mark for gzip decompression */
1776 csp->content_type |= CT_GZIP;
1778 else if (strstr(*header, "deflate"))
1780 /* Mark for zlib decompression */
1781 csp->content_type |= CT_DEFLATE;
1783 else if (strstr(*header, "compress"))
1786 * We can't decompress this; therefore we can't filter
1789 csp->content_type |= CT_TABOO;
1791 #else /* !defined(FEATURE_ZLIB) */
1792 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1795 * Body is compressed, turn off pcrs and gif filtering.
1797 csp->content_type |= CT_TABOO;
1799 #endif /* !defined(FEATURE_ZLIB) */
1806 /*********************************************************************
1808 * Function : server_content_length
1810 * Description : Adjust Content-Length header if we modified
1814 * 1 : csp = Current client state (buffers, headers, etc...)
1815 * 2 : header = On input, pointer to header to modify.
1816 * On output, pointer to the modified header, or NULL
1817 * to remove the header. This function frees the
1818 * original string if necessary.
1820 * Returns : JB_ERR_OK on success, or
1821 * JB_ERR_MEMORY on out-of-memory error.
1823 *********************************************************************/
1824 jb_err server_content_length(struct client_state *csp, char **header)
1826 const size_t max_header_length = 80;
1827 if (csp->content_length != 0) /* Content length could have been modified */
1830 * XXX: Shouldn't we check if csp->content_length
1831 * is different than the original value?
1834 *header = (char *) zalloc(max_header_length);
1835 if (*header == NULL)
1837 return JB_ERR_MEMORY;
1840 snprintf(*header, max_header_length, "Content-Length: %d",
1841 (int)csp->content_length);
1842 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
1843 (int)csp->content_length);
1850 /*********************************************************************
1852 * Function : server_content_md5
1854 * Description : Crumble any Content-MD5 headers if the document was
1855 * modified. FIXME: Should we re-compute instead?
1858 * 1 : csp = Current client state (buffers, headers, etc...)
1859 * 2 : header = On input, pointer to header to modify.
1860 * On output, pointer to the modified header, or NULL
1861 * to remove the header. This function frees the
1862 * original string if necessary.
1864 * Returns : JB_ERR_OK on success, or
1865 * JB_ERR_MEMORY on out-of-memory error.
1867 *********************************************************************/
1868 jb_err server_content_md5(struct client_state *csp, char **header)
1870 if (csp->flags & CSP_FLAG_MODIFIED)
1872 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1879 /*********************************************************************
1881 * Function : server_content_disposition
1883 * Description : If enabled, blocks or modifies the "content-disposition" header.
1884 * Called from `sed'.
1887 * 1 : csp = Current client state (buffers, headers, etc...)
1888 * 2 : header = On input, pointer to header to modify.
1889 * On output, pointer to the modified header, or NULL
1890 * to remove the header. This function frees the
1891 * original string if necessary.
1893 * Returns : JB_ERR_OK on success, or
1894 * JB_ERR_MEMORY on out-of-memory error.
1896 *********************************************************************/
1897 jb_err server_content_disposition(struct client_state *csp, char **header)
1902 * Are we messing with the content-disposition header?
1904 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1910 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1912 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1915 * Blocking content-disposition header
1917 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1924 * Replacing content-disposition header
1927 *header = strdup("content-disposition: ");
1928 string_append(header, newval);
1930 if (*header == NULL)
1932 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1936 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1939 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1942 /*********************************************************************
1944 * Function : server_last_modified
1946 * Description : Changes Last-Modified header to the actual date
1947 * to help hide-if-modified-since.
1948 * Called from `sed'.
1951 * 1 : csp = Current client state (buffers, headers, etc...)
1952 * 2 : header = On input, pointer to header to modify.
1953 * On output, pointer to the modified header, or NULL
1954 * to remove the header. This function frees the
1955 * original string if necessary.
1957 * Returns : JB_ERR_OK on success, or
1958 * JB_ERR_MEMORY on out-of-memory error.
1960 *********************************************************************/
1961 jb_err server_last_modified(struct client_state *csp, char **header)
1964 char buf[BUFFER_SIZE];
1967 #ifdef HAVE_GMTIME_R
1970 struct tm *timeptr = NULL;
1971 time_t now, last_modified;
1973 long int days, hours, minutes, seconds;
1976 * Are we messing with the Last-Modified header?
1978 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1984 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1986 if (0 == strcmpic(newval, "block") )
1989 * Blocking Last-Modified header. Useless but why not.
1991 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1995 else if (0 == strcmpic(newval, "reset-to-request-time"))
1998 * Setting Last-Modified Header to now.
2000 get_http_time(0, buf);
2002 *header = strdup("Last-Modified: ");
2003 string_append(header, buf);
2005 if (*header == NULL)
2007 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2011 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2014 else if (0 == strcmpic(newval, "randomize"))
2016 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2018 #ifdef HAVE_GMTIME_R
2019 timeptr = gmtime_r(&now, &gmt);
2020 #elif FEATURE_PTHREAD
2021 pthread_mutex_lock(&gmtime_mutex);
2022 timeptr = gmtime(&now);
2023 pthread_mutex_unlock(&gmtime_mutex);
2025 timeptr = gmtime(&now);
2027 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
2029 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2034 rtime = (long int)difftime(now, last_modified);
2037 rtime = pick_from_range(rtime);
2038 last_modified += rtime;
2039 #ifdef HAVE_GMTIME_R
2040 timeptr = gmtime_r(&last_modified, &gmt);
2041 #elif FEATURE_PTHREAD
2042 pthread_mutex_lock(&gmtime_mutex);
2043 timeptr = gmtime(&last_modified);
2044 pthread_mutex_unlock(&gmtime_mutex);
2046 timeptr = gmtime(&last_modified);
2048 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2050 *header = strdup("Last-Modified: ");
2051 string_append(header, newheader);
2053 if (*header == NULL)
2055 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2056 return JB_ERR_MEMORY;
2059 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2061 days = rtime / (3600 * 24);
2062 hours = rtime / 3600 % 24;
2063 minutes = rtime / 60 % 60;
2064 seconds = rtime % 60;
2066 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2067 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2068 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2073 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2081 /*********************************************************************
2083 * Function : client_accept_encoding
2085 * Description : Rewrite the client's Accept-Encoding header so that
2086 * if doesn't allow compression, if the action applies.
2087 * Note: For HTTP/1.0 the absence of the header is enough.
2090 * 1 : csp = Current client state (buffers, headers, etc...)
2091 * 2 : header = On input, pointer to header to modify.
2092 * On output, pointer to the modified header, or NULL
2093 * to remove the header. This function frees the
2094 * original string if necessary.
2096 * Returns : JB_ERR_OK on success, or
2097 * JB_ERR_MEMORY on out-of-memory error.
2099 *********************************************************************/
2100 jb_err client_accept_encoding(struct client_state *csp, char **header)
2102 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2104 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2108 /* Temporarily disable the correct behaviour to
2109 * work around a PHP bug.
2111 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2113 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2114 * if (*header == NULL)
2116 * return JB_ERR_MEMORY;
2127 /*********************************************************************
2129 * Function : client_te
2131 * Description : Rewrite the client's TE header so that
2132 * if doesn't allow compression, if the action applies.
2135 * 1 : csp = Current client state (buffers, headers, etc...)
2136 * 2 : header = On input, pointer to header to modify.
2137 * On output, pointer to the modified header, or NULL
2138 * to remove the header. This function frees the
2139 * original string if necessary.
2141 * Returns : JB_ERR_OK on success, or
2142 * JB_ERR_MEMORY on out-of-memory error.
2144 *********************************************************************/
2145 jb_err client_te(struct client_state *csp, char **header)
2147 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2150 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2156 /*********************************************************************
2158 * Function : client_referrer
2160 * Description : Handle the "referer" config setting properly.
2161 * Called from `sed'.
2164 * 1 : csp = Current client state (buffers, headers, etc...)
2165 * 2 : header = On input, pointer to header to modify.
2166 * On output, pointer to the modified header, or NULL
2167 * to remove the header. This function frees the
2168 * original string if necessary.
2170 * Returns : JB_ERR_OK on success, or
2171 * JB_ERR_MEMORY on out-of-memory error.
2173 *********************************************************************/
2174 jb_err client_referrer(struct client_state *csp, char **header)
2181 #ifdef FEATURE_FORCE_LOAD
2182 /* Since the referrer can include the prefix even
2183 * if the request itself is non-forced, we must
2184 * clean it unconditionally
2186 strclean(*header, FORCE_PREFIX);
2187 #endif /* def FEATURE_FORCE_LOAD */
2190 * Are we sending referer?
2192 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2197 newval = csp->action->string[ACTION_STRING_REFERER];
2199 if ((0 != strcmpic(newval, "conditional-block")))
2203 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2208 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2211 else if (0 == strcmpic(newval, "conditional-block"))
2214 * Block referer if host has changed.
2217 if (NULL == (host = strdup(csp->http->hostport)))
2220 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2221 return JB_ERR_MEMORY;
2223 if (NULL == (referer = strdup(*header)))
2227 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2228 return JB_ERR_MEMORY;
2230 hostlenght = strlen(host);
2231 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2233 /*Shorten referer to make sure the referer is blocked
2234 *if www.example.org/www.example.com-shall-see-the-referer/
2235 *links to www.example.com/
2237 referer[hostlenght+17] = '\0';
2239 if ( 0 == strstr(referer, host)) /*Host has changed*/
2241 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2246 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2252 else if (0 != strcmpic(newval, "forge"))
2255 * We have a specific (fixed) referer we want to send.
2257 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2259 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2261 *header = strdup("Referer: ");
2262 string_append(header, newval);
2263 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2265 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2270 * Forge a referer as http://[hostname:port of REQUEST]/
2271 * to fool stupid checks for in-site links
2274 *header = strdup("Referer: http://");
2275 string_append(header, csp->http->hostport);
2276 string_append(header, "/");
2277 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2279 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2283 /*********************************************************************
2285 * Function : client_accept_language
2287 * Description : Handle the "Accept-Language" config setting properly.
2288 * Called from `sed'.
2291 * 1 : csp = Current client state (buffers, headers, etc...)
2292 * 2 : header = On input, pointer to header to modify.
2293 * On output, pointer to the modified header, or NULL
2294 * to remove the header. This function frees the
2295 * original string if necessary.
2297 * Returns : JB_ERR_OK on success, or
2298 * JB_ERR_MEMORY on out-of-memory error.
2300 *********************************************************************/
2301 jb_err client_accept_language(struct client_state *csp, char **header)
2306 * Are we messing with the Accept-Language?
2308 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2310 /*I don't think so*/
2314 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2316 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2319 * Blocking Accept-Language header
2321 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2328 * Replacing Accept-Language header
2331 *header = strdup("Accept-Language: ");
2332 string_append(header, newval);
2334 if (*header == NULL)
2336 log_error(LOG_LEVEL_ERROR,
2337 "Insufficent memory. Accept-Language header crunched without replacement.");
2341 log_error(LOG_LEVEL_HEADER,
2342 "Accept-Language header crunched and replaced with: %s", *header);
2345 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2348 /*********************************************************************
2350 * Function : crunch_client_header
2352 * Description : Crunch client header if it matches a string supplied by the
2353 * user. Called from `sed'.
2356 * 1 : csp = Current client state (buffers, headers, etc...)
2357 * 2 : header = On input, pointer to header to modify.
2358 * On output, pointer to the modified header, or NULL
2359 * to remove the header. This function frees the
2360 * original string if necessary.
2362 * Returns : JB_ERR_OK on success and always succeeds
2364 *********************************************************************/
2365 jb_err crunch_client_header(struct client_state *csp, char **header)
2367 const char *crunch_pattern;
2368 /*Is there a header to crunch*/
2370 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2372 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2374 /*Is the current header the lucky one?*/
2375 if (strstr(*header, crunch_pattern))
2377 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2385 /*********************************************************************
2387 * Function : client_uagent
2389 * Description : Handle the "user-agent" config setting properly
2390 * and remember its original value to enable browser
2391 * bug workarounds. Called from `sed'.
2394 * 1 : csp = Current client state (buffers, headers, etc...)
2395 * 2 : header = On input, pointer to header to modify.
2396 * On output, pointer to the modified header, or NULL
2397 * to remove the header. This function frees the
2398 * original string if necessary.
2400 * Returns : JB_ERR_OK on success, or
2401 * JB_ERR_MEMORY on out-of-memory error.
2403 *********************************************************************/
2404 jb_err client_uagent(struct client_state *csp, char **header)
2408 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2413 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2420 *header = strdup("User-Agent: ");
2421 string_append(header, newval);
2423 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2425 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2428 /*********************************************************************
2430 * Function : client_ua
2432 * Description : Handle "ua-" headers properly. Called from `sed'.
2435 * 1 : csp = Current client state (buffers, headers, etc...)
2436 * 2 : header = On input, pointer to header to modify.
2437 * On output, pointer to the modified header, or NULL
2438 * to remove the header. This function frees the
2439 * original string if necessary.
2441 * Returns : JB_ERR_OK on success, or
2442 * JB_ERR_MEMORY on out-of-memory error.
2444 *********************************************************************/
2445 jb_err client_ua(struct client_state *csp, char **header)
2447 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2449 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2457 /*********************************************************************
2459 * Function : client_from
2461 * Description : Handle the "from" config setting properly.
2462 * Called from `sed'.
2465 * 1 : csp = Current client state (buffers, headers, etc...)
2466 * 2 : header = On input, pointer to header to modify.
2467 * On output, pointer to the modified header, or NULL
2468 * to remove the header. This function frees the
2469 * original string if necessary.
2471 * Returns : JB_ERR_OK on success, or
2472 * JB_ERR_MEMORY on out-of-memory error.
2474 *********************************************************************/
2475 jb_err client_from(struct client_state *csp, char **header)
2479 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2486 newval = csp->action->string[ACTION_STRING_FROM];
2489 * Are we blocking the e-mail address?
2491 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2493 log_error(LOG_LEVEL_HEADER, "crunched From!");
2497 log_error(LOG_LEVEL_HEADER, " modified");
2499 *header = strdup("From: ");
2500 string_append(header, newval);
2502 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2506 /*********************************************************************
2508 * Function : client_send_cookie
2510 * Description : Handle the "cookie" header properly. Called from `sed'.
2511 * If cookie is accepted, add it to the cookie_list,
2512 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2515 * 1 : csp = Current client state (buffers, headers, etc...)
2516 * 2 : header = On input, pointer to header to modify.
2517 * On output, pointer to the modified header, or NULL
2518 * to remove the header. This function frees the
2519 * original string if necessary.
2521 * Returns : JB_ERR_OK on success, or
2522 * JB_ERR_MEMORY on out-of-memory error.
2524 *********************************************************************/
2525 jb_err client_send_cookie(struct client_state *csp, char **header)
2527 jb_err result = JB_ERR_OK;
2529 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2531 /* strlen("cookie: ") == 8 */
2532 result = enlist(csp->cookie_list, *header + 8);
2536 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2540 * Always remove the cookie here. The cookie header
2541 * will be sent at the end of the header.
2549 /*********************************************************************
2551 * Function : client_x_forwarded
2553 * Description : Handle the "x-forwarded-for" config setting properly,
2554 * also used in the add_client_headers list. Called from `sed'.
2557 * 1 : csp = Current client state (buffers, headers, etc...)
2558 * 2 : header = On input, pointer to header to modify.
2559 * On output, pointer to the modified header, or NULL
2560 * to remove the header. This function frees the
2561 * original string if necessary.
2563 * Returns : JB_ERR_OK on success, or
2564 * JB_ERR_MEMORY on out-of-memory error.
2566 *********************************************************************/
2567 jb_err client_x_forwarded(struct client_state *csp, char **header)
2569 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2571 /* Save it so we can re-add it later */
2572 freez(csp->x_forwarded);
2573 csp->x_forwarded = *header;
2576 * Always set *header = NULL, since this information
2577 * will be sent at the end of the header.
2584 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2591 /*********************************************************************
2593 * Function : client_max_forwards
2595 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2596 * from the value of the Max-Forwards header field.
2599 * 1 : csp = Current client state (buffers, headers, etc...)
2600 * 2 : header = On input, pointer to header to modify.
2601 * On output, pointer to the modified header, or NULL
2602 * to remove the header. This function frees the
2603 * original string if necessary.
2605 * Returns : JB_ERR_OK on success, or
2606 * JB_ERR_MEMORY on out-of-memory error.
2608 *********************************************************************/
2609 jb_err client_max_forwards(struct client_state *csp, char **header)
2611 unsigned int max_forwards;
2613 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2614 (0 == strcmpic(csp->http->gpc, "options")))
2616 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2618 if (max_forwards-- > 0)
2620 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", max_forwards);
2621 log_error(LOG_LEVEL_HEADER, "Max-Forwards header for %s request replaced with: %s",
2622 csp->http->gpc, *header);
2626 /* FIXME: Follow spec and intercept the request. */
2627 log_error(LOG_LEVEL_ERROR,
2628 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2637 /*********************************************************************
2639 * Function : client_host
2641 * Description : If the request URI did not contain host and
2642 * port information, parse and evaluate the Host
2645 * Also, kill ill-formed HOST: headers as sent by
2646 * Apple's iTunes software when used with a proxy.
2649 * 1 : csp = Current client state (buffers, headers, etc...)
2650 * 2 : header = On input, pointer to header to modify.
2651 * On output, pointer to the modified header, or NULL
2652 * to remove the header. This function frees the
2653 * original string if necessary.
2655 * Returns : JB_ERR_OK on success, or
2656 * JB_ERR_MEMORY on out-of-memory error.
2658 *********************************************************************/
2659 jb_err client_host(struct client_state *csp, char **header)
2664 * If the header field name is all upper-case, chances are that it's
2665 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2666 * not a problem -- they are regenerated later.
2668 if ((*header)[1] == 'O')
2670 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2675 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2676 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2679 if (NULL == (p = strdup((*header)+6)))
2681 return JB_ERR_MEMORY;
2684 if (NULL == (q = strdup(p)))
2687 return JB_ERR_MEMORY;
2690 freez(csp->http->hostport);
2691 csp->http->hostport = p;
2692 freez(csp->http->host);
2693 csp->http->host = q;
2694 q = strchr(csp->http->host, ':');
2697 /* Terminate hostname and evaluate port string */
2699 csp->http->port = atoi(q);
2703 csp->http->port = csp->http->ssl ? 443 : 80;
2706 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2707 csp->http->hostport, csp->http->host, csp->http->port);
2713 /*********************************************************************
2715 * Function : client_if_modified_since
2717 * Description : Remove or modify the If-Modified-Since header.
2720 * 1 : csp = Current client state (buffers, headers, etc...)
2721 * 2 : header = On input, pointer to header to modify.
2722 * On output, pointer to the modified header, or NULL
2723 * to remove the header. This function frees the
2724 * original string if necessary.
2726 * Returns : JB_ERR_OK on success, or
2727 * JB_ERR_MEMORY on out-of-memory error.
2729 *********************************************************************/
2730 jb_err client_if_modified_since(struct client_state *csp, char **header)
2733 #ifdef HAVE_GMTIME_R
2736 struct tm *timeptr = NULL;
2740 long int hours, minutes, seconds;
2744 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2747 * The client got an error message because of a temporary problem,
2748 * the problem is gone and the client now tries to revalidate our
2749 * error message on the real server. The revalidation would always
2750 * end with the transmission of the whole document and there is
2751 * no need to expose the bogus If-Modified-Since header.
2753 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2756 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2758 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2760 if ((0 == strcmpic(newval, "block")))
2762 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2765 else /* add random value */
2767 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2769 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2774 rtime = strtol(newval, &endptr, 0);
2777 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2778 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2785 rtime = pick_from_range(rtime);
2789 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2792 tm += rtime * (negative ? -1 : 1);
2793 #ifdef HAVE_GMTIME_R
2794 timeptr = gmtime_r(&tm, &gmt);
2795 #elif FEATURE_PTHREAD
2796 pthread_mutex_lock(&gmtime_mutex);
2797 timeptr = gmtime(&tm);
2798 pthread_mutex_unlock(&gmtime_mutex);
2800 timeptr = gmtime(&tm);
2802 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2805 *header = strdup("If-Modified-Since: ");
2806 string_append(header, newheader);
2808 if (*header == NULL)
2810 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2811 return JB_ERR_MEMORY;
2814 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2816 hours = rtime / 3600;
2817 minutes = rtime / 60 % 60;
2818 seconds = rtime % 60;
2820 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2821 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2822 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2831 /*********************************************************************
2833 * Function : client_if_none_match
2835 * Description : Remove the If-None-Match header.
2838 * 1 : csp = Current client state (buffers, headers, etc...)
2839 * 2 : header = On input, pointer to header to modify.
2840 * On output, pointer to the modified header, or NULL
2841 * to remove the header. This function frees the
2842 * original string if necessary.
2844 * Returns : JB_ERR_OK on success, or
2845 * JB_ERR_MEMORY on out-of-memory error.
2847 *********************************************************************/
2848 jb_err client_if_none_match(struct client_state *csp, char **header)
2850 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2852 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2859 /*********************************************************************
2861 * Function : client_x_filter
2863 * Description : Disables filtering if the client set "X-Filter: No".
2864 * Called from `sed'.
2867 * 1 : csp = Current client state (buffers, headers, etc...)
2868 * 2 : header = On input, pointer to header to modify.
2869 * On output, pointer to the modified header, or NULL
2870 * to remove the header. This function frees the
2871 * original string if necessary.
2873 * Returns : JB_ERR_OK on success
2875 *********************************************************************/
2876 jb_err client_x_filter(struct client_state *csp, char **header)
2878 if ( 0 == strcmpic(*header, "X-Filter: No"))
2880 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2882 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2886 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2888 log_error(LOG_LEVEL_HEADER,
2889 "force-text-mode overruled the client's request to fetch without filtering!");
2893 csp->content_type = CT_TABOO;
2894 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
2895 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
2896 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
2898 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2905 /* the following functions add headers directly to the header list */
2907 /*********************************************************************
2909 * Function : client_host_adder
2911 * Description : Adds the Host: header field if it is missing.
2912 * Called from `sed'.
2915 * 1 : csp = Current client state (buffers, headers, etc...)
2917 * Returns : JB_ERR_OK on success, or
2918 * JB_ERR_MEMORY on out-of-memory error.
2920 *********************************************************************/
2921 jb_err client_host_adder(struct client_state *csp)
2926 if ( !csp->http->hostport || !*(csp->http->hostport))
2932 * remove 'user:pass@' from 'proto://user:pass@host'
2934 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2940 p = csp->http->hostport;
2943 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2944 err = enlist_unique_header(csp->headers, "Host", p);
2950 /*********************************************************************
2952 * Function : client_cookie_adder
2954 * Description : Used in the add_client_headers list. Called from `sed'.
2957 * 1 : csp = Current client state (buffers, headers, etc...)
2959 * Returns : JB_ERR_OK on success, or
2960 * JB_ERR_MEMORY on out-of-memory error.
2962 *********************************************************************/
2963 jb_err client_cookie_adder(struct client_state *csp)
2965 struct list_entry *lst;
2967 struct list_entry *list1 = csp->cookie_list->first;
2968 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2969 int first_cookie = 1;
2972 if ((list1 == NULL) && (list2 == NULL))
2978 tmp = strdup("Cookie: ");
2980 for (lst = list1; lst ; lst = lst->next)
2988 string_append(&tmp, "; ");
2990 string_append(&tmp, lst->str);
2993 for (lst = list2; lst ; lst = lst->next)
3001 string_append(&tmp, "; ");
3003 string_join(&tmp, cookie_encode(lst->str));
3008 return JB_ERR_MEMORY;
3011 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3012 err = enlist(csp->headers, tmp);
3018 /*********************************************************************
3020 * Function : client_accept_encoding_adder
3022 * Description : Add an Accept-Encoding header to the client's request
3023 * that disables compression if the action applies, and
3024 * the header is not already there. Called from `sed'.
3025 * Note: For HTTP/1.0, the absence of the header is enough.
3028 * 1 : csp = Current client state (buffers, headers, etc...)
3030 * Returns : JB_ERR_OK on success, or
3031 * JB_ERR_MEMORY on out-of-memory error.
3033 *********************************************************************/
3034 jb_err client_accept_encoding_adder(struct client_state *csp)
3036 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3037 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3039 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3046 /*********************************************************************
3048 * Function : client_xtra_adder
3050 * Description : Used in the add_client_headers list. Called from `sed'.
3053 * 1 : csp = Current client state (buffers, headers, etc...)
3055 * Returns : JB_ERR_OK on success, or
3056 * JB_ERR_MEMORY on out-of-memory error.
3058 *********************************************************************/
3059 jb_err client_xtra_adder(struct client_state *csp)
3061 struct list_entry *lst;
3064 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3065 lst ; lst = lst->next)
3067 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3068 err = enlist(csp->headers, lst->str);
3080 /*********************************************************************
3082 * Function : client_x_forwarded_adder
3084 * Description : Used in the add_client_headers list. Called from `sed'.
3087 * 1 : csp = Current client state (buffers, headers, etc...)
3089 * Returns : JB_ERR_OK on success, or
3090 * JB_ERR_MEMORY on out-of-memory error.
3092 *********************************************************************/
3093 jb_err client_x_forwarded_adder(struct client_state *csp)
3098 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3103 if (csp->x_forwarded)
3105 p = strdup(csp->x_forwarded);
3106 string_append(&p, ", ");
3110 p = strdup("X-Forwarded-For: ");
3112 string_append(&p, csp->ip_addr_str);
3116 return JB_ERR_MEMORY;
3119 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3120 err = enlist(csp->headers, p);
3127 /*********************************************************************
3129 * Function : connection_close_adder
3131 * Description : Adds a "Connection: close" header to csp->headers
3132 * as a temporary fix for the needed but missing HTTP/1.1
3133 * support. Called from `sed'.
3134 * FIXME: This whole function shouldn't be neccessary!
3137 * 1 : csp = Current client state (buffers, headers, etc...)
3139 * Returns : JB_ERR_OK on success, or
3140 * JB_ERR_MEMORY on out-of-memory error.
3142 *********************************************************************/
3143 jb_err connection_close_adder(struct client_state *csp)
3145 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3146 return enlist(csp->headers, "Connection: close");
3150 /*********************************************************************
3152 * Function : server_http
3154 * Description : - Save the HTTP Status into csp->http->status
3155 * - Set CT_TABOO to prevent filtering if the answer
3156 * is a partial range (HTTP status 206)
3157 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3161 * 1 : csp = Current client state (buffers, headers, etc...)
3162 * 2 : header = On input, pointer to header to modify.
3163 * On output, pointer to the modified header, or NULL
3164 * to remove the header. This function frees the
3165 * original string if necessary.
3167 * Returns : JB_ERR_OK on success, or
3168 * JB_ERR_MEMORY on out-of-memory error.
3170 *********************************************************************/
3171 jb_err server_http(struct client_state *csp, char **header)
3173 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3174 if (csp->http->status == 206)
3176 csp->content_type = CT_TABOO;
3179 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3182 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3189 /*********************************************************************
3191 * Function : server_set_cookie
3193 * Description : Handle the server "cookie" header properly.
3194 * Log cookie to the jar file. Then "crunch" it,
3195 * or accept it. Called from `sed'.
3198 * 1 : csp = Current client state (buffers, headers, etc...)
3199 * 2 : header = On input, pointer to header to modify.
3200 * On output, pointer to the modified header, or NULL
3201 * to remove the header. This function frees the
3202 * original string if necessary.
3204 * Returns : JB_ERR_OK on success, or
3205 * JB_ERR_MEMORY on out-of-memory error.
3207 *********************************************************************/
3208 jb_err server_set_cookie(struct client_state *csp, char **header)
3210 #ifdef FEATURE_COOKIE_JAR
3211 if (csp->config->jar)
3214 * Write timestamp into outbuf.
3216 * Complex because not all OSs have tm_gmtoff or
3217 * the %z field in strftime()
3219 char tempbuf[ BUFFER_SIZE ];
3223 #ifdef HAVE_LOCALTIME_R
3224 tm_now = *localtime_r(&now, &tm_now);
3225 #elif FEATURE_PTHREAD
3226 pthread_mutex_lock(&localtime_mutex);
3227 tm_now = *localtime (&now);
3228 pthread_mutex_unlock(&localtime_mutex);
3230 tm_now = *localtime (&now);
3232 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3234 /* strlen("set-cookie: ") = 12 */
3235 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3237 #endif /* def FEATURE_COOKIE_JAR */
3239 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3241 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
3242 return crumble(csp, header);
3244 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3246 /* Flag whether or not to log a message */
3249 /* A variable to store the tag we're working on */
3252 /* Skip "Set-Cookie:" (11 characters) in header */
3253 cur_tag = *header + 11;
3255 /* skip whitespace between "Set-Cookie:" and value */
3256 while (*cur_tag && ijb_isspace(*cur_tag))
3261 /* Loop through each tag in the cookie */
3265 char *next_tag = strchr(cur_tag, ';');
3266 if (next_tag != NULL)
3268 /* Skip the ';' character itself */
3271 /* skip whitespace ";" and start of tag */
3272 while (*next_tag && ijb_isspace(*next_tag))
3279 /* "Next tag" is the end of the string */
3280 next_tag = cur_tag + strlen(cur_tag);
3283 /* Is this the "Expires" tag? */
3284 if (strncmpic(cur_tag, "expires=", 8) == 0)
3286 /* Delete the tag by copying the rest of the string over it.
3287 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3288 * since the behaviour of strcpy is undefined for overlapping
3291 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3293 /* That changed the header, need to issue a log message */
3296 /* Note that the next tag has now been moved to *cur_tag,
3297 * so we do not need to update the cur_tag pointer.
3302 /* Move on to next cookie tag */
3309 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
3317 #ifdef FEATURE_FORCE_LOAD
3318 /*********************************************************************
3320 * Function : strclean
3322 * Description : In-Situ-Eliminate all occurances of substring in
3326 * 1 : string = string to clean
3327 * 2 : substring = substring to eliminate
3329 * Returns : Number of eliminations
3331 *********************************************************************/
3332 int strclean(const char *string, const char *substring)
3338 len = strlen(substring);
3340 while((pos = strstr(string, substring)) != NULL)
3347 while (*p++ != '\0');
3354 #endif /* def FEATURE_FORCE_LOAD */
3356 /*********************************************************************
3358 * Function : parse_header_time
3360 * Description : Transforms time inside a HTTP header into
3361 * the usual time format.
3364 * 1 : header = header to parse
3365 * 2 : tm = storage for the resulting time in seconds
3367 * Returns : Time struct containing the header time, or
3368 * NULL in case of a parsing problems.
3370 *********************************************************************/
3371 struct tm *parse_header_time(char *header, time_t *tm) {
3375 struct tm * timeptr;
3378 * Initializing gmt to prevent time zone offsets.
3380 * While this is only necessary on some platforms
3381 * (mingw32 for example), I don't know how to
3382 * detect these automatically and doing it everywhere
3386 #ifdef HAVE_LOCALTIME_R
3387 gmt = *localtime_r(tm, &gmt);
3388 #elif FEATURE_PTHREAD
3389 pthread_mutex_lock(&localtime_mutex);
3390 gmt = *localtime(tm);
3391 pthread_mutex_unlock(&localtime_mutex);
3393 gmt = *localtime(tm);
3396 /* Skipping header name */
3397 timestring = strstr(header, ": ");
3398 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)
3411 /*********************************************************************
3413 * Function : get_destination_from_headers
3415 * Description : Parse the "Host:" header to get the request's destination.
3416 * Only needed if the client's request was forcefully
3417 * redirected into Privoxy.
3419 * Code mainly copied from client_host() which is currently
3420 * run too late for this purpose.
3423 * 1 : headers = List of headers (one of them hopefully being
3424 * the "Host:" header)
3425 * 2 : http = storage for the result (host, port and hostport).
3427 * Returns : JB_ERR_MEMORY in case of memory problems,
3428 * JB_ERR_PARSE if the host header couldn't be found,
3429 * JB_ERR_OK otherwise.
3431 *********************************************************************/
3432 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3438 host = get_header_value(headers, "Host:");
3442 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3443 return JB_ERR_PARSE;
3446 if (NULL == (p = strdup((host))))
3448 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3449 return JB_ERR_MEMORY;
3452 if (NULL == (q = strdup(p)))
3455 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3456 return JB_ERR_MEMORY;
3459 freez(http->hostport);
3463 q = strchr(http->host, ':');
3466 /* Terminate hostname and evaluate port string */
3468 http->port = atoi(q);
3472 http->port = http->ssl ? 443 : 80;
3475 /* Rebuild request URL */
3477 http->url = strdup(http->ssl ? "https://" : "http://");
3478 string_append(&http->url, http->hostport);
3479 string_append(&http->url, http->path);
3480 if (http->url == NULL)
3482 return JB_ERR_MEMORY;
3485 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",