1 const char parsers_rcs[] = "$Id: parsers.c,v 1.94 2007/03/21 12:23:53 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2007 the SourceForge
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
48 * - Add better protection against malicious gzip headers.
49 * - Stop logging the first hundred bytes of decompressed content.
50 * It looks like it's working and there is always debug 16.
51 * - Log the content size after decompression in decompress_iob()
52 * instead of pcrs_filter_response().
54 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
55 * - Use dedicated header filter actions instead of abusing "filter".
56 * Replace "filter-client-headers" and "filter-client-headers"
57 * with "server-header-filter" and "client-header-filter".
58 * - Remove filter_client_header() and filter_client_header(),
59 * filter_header() now checks the shiny new
60 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
62 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
63 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
64 * - Handle "Cookie:" and "Connection:" headers a bit smarter
65 * (don't crunch them just to recreate them later on).
66 * - Add another non-standard time format for the cookie
67 * expiration date detection.
68 * - Fix a valgrind warning.
70 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
71 * Improve cookie expiration date detection.
73 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
74 * Don't run server_content_length() the first time
75 * sed() parses server headers; only adjust the
76 * Content-Length header if the page was modified.
78 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
79 * Fix log messages regarding the cookie time format
80 * (cookie and request URL were mixed up).
82 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
83 * - Let decompress_iob()
84 * - not corrupt the content if decompression fails
85 * early. (the first byte(s) were lost).
86 * - use pointer arithmetics with defined outcome for
88 * - Use a different kludge to remember a failed decompression.
90 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
91 * Search for Max-Forwards headers case-insensitive,
92 * don't generate the "501 unsupported" message for invalid
93 * Max-Forwards values and don't increase negative ones.
95 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
96 * - Let server_set_cookie() check the expiration date
97 * of cookies and don't touch the ones that are already
98 * expired. Fixes problems with low quality web applications
99 * as described in BR 932612.
101 * - Adjust comment in client_max_forwards to reality;
102 * remove invalid Max-Forwards headers.
104 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
105 * Stop filter_header() from unintentionally removing
106 * empty header lines that were enlisted by the continue
109 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
110 * - Repeat the request URL before logging any headers.
111 * Makes reading the log easier in case of simultaneous requests.
112 * - If there are more than one Content-Type headers in one request,
113 * use the first one and remove the others.
114 * - Remove "newval" variable in server_content_type().
115 * It's only used once.
117 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
118 * Correct a cast, check inflateEnd() exit code
119 * to see if we have to, replace sprintf calls
122 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
123 * Integrate a modified version of Wil Mahan's
124 * zlib patch (PR #895531).
126 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
127 * Skip empty filter files in filter_header()
128 * but don't ignore the ones that come afterwards.
129 * Fixes BR 1619208, this time for real.
131 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
132 * Reverted parts of my last commit
133 * to keep error handling working.
135 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
136 * Fixed gcc43 conversion warnings.
138 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
139 * Bringing back the "useless" localtime() call
140 * I removed in revision 1.67. On some platforms
141 * it's necessary to prevent time zone offsets.
143 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
144 * Rebuild request URL in get_destination_from_headers()
145 * to make sure redirect{pcrs command} works as expected
146 * for intercepted requests.
148 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
149 * Added get_destination_from_headers().
151 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
152 * Make pthread mutex locking more generic. Instead of
153 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
154 * and use mutex locking unless there is an _r function
155 * available. Better safe than sorry.
157 * Fixes "./configure --disable-pthread" and should result
158 * in less threading-related problems on pthread-using platforms,
159 * but it still doesn't fix BR#1122404.
161 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
162 * The special header "X-Filter: No" now disables
163 * header filtering as well.
165 * Revision 1.73 2006/09/23 13:26:38 roro
166 * Replace TABs by spaces in source code.
168 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
169 * Don't print a log message every time filter_headers is
170 * entered or left. It only creates noise without any real
173 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
174 * Fix +hide-if-modified-since{-n}.
176 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
177 * Have hide-if-modified-since interpret the random
178 * range value as minutes instead of hours. Allows
179 * more fine-grained configuration.
181 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
182 * Always have parse_header_time return a pointer
183 * that actual makes sense, even though we currently
184 * only need it to detect problems.
186 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
187 * Added config option enable-remote-http-toggle
188 * to specify if Privoxy should recognize special
189 * headers (currently only X-Filter) to change its
190 * behaviour. Disabled by default.
192 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
193 * After filtering de-chunked instances, remove
194 * "Transfer-Encoding" header entirely instead of changing
195 * it to "Transfer-Encoding: identity", which is invalid.
196 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
198 * Don't use localtime in parse_header_time. An empty time struct
199 * is good enough, it gets overwritten by strptime anyway.
201 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
202 * Use gmtime_r if available, fallback to gmtime with mutex
203 * protection for MacOSX and use vanilla gmtime for the rest.
205 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
206 * Changed client_referrer to use the right type (size_t) for
207 * hostlenght and to shorten the temporary referrer string with
208 * '\0' instead of adding a useless line break.
210 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
211 * - Back to timegm() using GnuPG's replacement if necessary.
212 * Using mktime() and localtime() could add a on hour offset if
213 * the randomize factor was big enough to lead to a summer/wintertime
216 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
218 * - Moved randomization code into pick_from_range().
220 * - Changed parse_header_time definition.
221 * time_t isn't guaranteed to be signed and
222 * if it isn't, -1 isn't available as error code.
223 * Changed some variable types in client_if_modified_since()
224 * because of the same reason.
226 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
227 * OS/2 compilation compatibility fixups
229 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
230 * Changed include from strptime.c to strptime.h
232 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
233 * Split filter-headers{} into filter-client-headers{}
234 * and filter-server-headers{}.
235 * Added parse_header_time() to share some code.
236 * Replaced timegm() with mktime().
238 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
239 * Windows service integration
241 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
242 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
244 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
245 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
246 * with what was really the latest development (the v_3_0_branch branch)
248 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
249 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
251 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
252 * Add the ability to check jpeg images for invalid
253 * lengths of comment blocks. Defensive strategy
254 * against the exploit:
255 * Microsoft Security Bulletin MS04-028
256 * Buffer Overrun in JPEG Processing (GDI+) Could
257 * Allow Code Execution (833987)
258 * Enabled with +inspect-jpegs in actions files.
260 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
261 * Excluded text/plain objects from filtering. This fixes a
262 * couple of client-crashing, download corruption and
263 * Privoxy performance issues, whose root cause lies in
264 * web servers labelling content of unknown type as text/plain.
266 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
267 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
269 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
270 * Completing the previous change
272 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
273 * Added temporary workaround for bug in PHP < 4.2.3
275 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
276 * 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.
278 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
279 * Fix typo: supressed -> suppressed
281 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
282 * Improved cookie logging
284 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
285 * Added basic support for OPTIONS and TRACE HTTP methods:
286 * - New parser function client_max_forwards which decrements
287 * the Max-Forwards HTTP header field of OPTIONS and TRACE
288 * requests by one before forwarding
289 * - New parser function client_host which extracts the host
290 * and port information from the HTTP header field if the
291 * request URI was not absolute
292 * - Don't crumble and re-add the Host: header, but only generate
293 * and append if missing
295 * Revision 1.56 2002/05/12 15:34:22 jongfoster
296 * Fixing typo in a comment
298 * Revision 1.55 2002/05/08 16:01:07 oes
299 * Optimized add_to_iob:
300 * - Use realloc instead of malloc(), memcpy(), free()
301 * - Expand to powers of two if possible, to get
302 * O(log n) reallocs instead of O(n).
303 * - Moved check for buffer limit here from chat
304 * - Report failure via returncode
306 * Revision 1.54 2002/04/02 15:03:16 oes
307 * Tiny code cosmetics
309 * Revision 1.53 2002/03/26 22:29:55 swa
310 * we have a new homepage!
312 * Revision 1.52 2002/03/24 13:25:43 swa
313 * name change related issues
315 * Revision 1.51 2002/03/13 00:27:05 jongfoster
318 * Revision 1.50 2002/03/12 01:45:35 oes
319 * More verbose logging
321 * Revision 1.49 2002/03/09 20:03:52 jongfoster
322 * - Making various functions return int rather than size_t.
323 * (Undoing a recent change). Since size_t is unsigned on
324 * Windows, functions like read_socket that return -1 on
325 * error cannot return a size_t.
327 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
328 * crashes, and also frequently caused JB to jump to 100%
329 * CPU and stay there. (Because it thought it had just
330 * read ((unsigned)-1) == 4Gb of data...)
332 * - The signature of write_socket has changed, it now simply
333 * returns success=0/failure=nonzero.
335 * - Trying to get rid of a few warnings --with-debug on
336 * Windows, I've introduced a new type "jb_socket". This is
337 * used for the socket file descriptors. On Windows, this
338 * is SOCKET (a typedef for unsigned). Everywhere else, it's
339 * an int. The error value can't be -1 any more, so it's
340 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
341 * Windows it maps to the #define INVALID_SOCKET.)
343 * - The signature of bind_port has changed.
345 * Revision 1.48 2002/03/07 03:46:53 oes
346 * Fixed compiler warnings etc
348 * Revision 1.47 2002/02/20 23:15:13 jongfoster
349 * Parsing functions now handle out-of-memory gracefully by returning
352 * Revision 1.46 2002/01/17 21:03:47 jongfoster
353 * Moving all our URL and URL pattern parsing code to urlmatch.c.
355 * Revision 1.45 2002/01/09 14:33:03 oes
356 * Added support for localtime_r.
358 * Revision 1.44 2001/12/14 01:22:54 steudten
359 * Remove 'user:pass@' from 'proto://user:pass@host' for the
360 * new added header 'Host: ..'. (See Req ID 491818)
362 * Revision 1.43 2001/11/23 00:26:38 jongfoster
363 * Fixing two really stupid errors in my previous commit
365 * Revision 1.42 2001/11/22 21:59:30 jongfoster
366 * Adding code to handle +no-cookies-keep
368 * Revision 1.41 2001/11/05 23:43:05 steudten
369 * Add time+date to log files.
371 * Revision 1.40 2001/10/26 20:13:09 jongfoster
372 * ctype.h is needed in Windows, too.
374 * Revision 1.39 2001/10/26 17:40:04 oes
375 * Introduced get_header_value()
376 * Removed http->user_agent, csp->referrer and csp->accept_types
377 * Removed client_accept()
379 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
380 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
381 * threads to call select() simultaneously. So, it's time to do a real, live,
382 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
383 * (native). Both versions will work, but using __OS2__ offers multi-threading.
385 * Revision 1.37 2001/10/23 21:36:02 jongfoster
386 * Documenting sed()'s error behaviou (doc change only)
388 * Revision 1.36 2001/10/13 12:51:51 joergs
389 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
390 * force-load), instead crumble Host: and add it (again) in client_host_adder
391 * (in case we get a HTTP/1.0 request without Host: header and forward it to
392 * a HTTP/1.1 server/proxy).
394 * Revision 1.35 2001/10/09 22:39:21 jongfoster
395 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
398 * Revision 1.34 2001/10/07 18:50:55 oes
399 * Added server_content_encoding, renamed server_transfer_encoding
401 * Revision 1.33 2001/10/07 18:04:49 oes
402 * Changed server_http11 to server_http and its pattern to "HTTP".
403 * Additional functionality: it now saves the HTTP status into
404 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
406 * Revision 1.32 2001/10/07 15:43:28 oes
407 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
408 * client_te and client_accept_encoding_adder, triggered by the new
409 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
410 * changed to allow only identity and chunked, and the TE header is
411 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
413 * parse_http_request no longer does anything than parsing. The rewriting
414 * of http->cmd and version mangling are gone. It now also recognizes
415 * the put and delete methods and saves the url in http->url. Removed
418 * renamed content_type and content_length to have the server_ prefix
420 * server_content_type now only works if csp->content_type != CT_TABOO
422 * added server_transfer_encoding, which
423 * - Sets CT_TABOO to prohibit filtering if encoding compresses
424 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
425 * - Change from "chunked" to "identity" if body was chunked
426 * but has been de-chunked for filtering.
428 * added server_content_md5 which crunches any Content-MD5 headers
429 * if the body was modified.
431 * made server_http11 conditional on +downgrade action
433 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
435 * Revision 1.31 2001/10/05 14:25:02 oes
436 * Crumble Keep-Alive from Server
438 * Revision 1.30 2001/09/29 12:56:03 joergs
439 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
441 * Revision 1.29 2001/09/24 21:09:24 jongfoster
442 * Fixing 2 memory leaks that Guy spotted, where the paramater to
443 * enlist() was not being free()d.
445 * Revision 1.28 2001/09/22 16:32:28 jongfoster
446 * Removing unused #includes.
448 * Revision 1.27 2001/09/20 15:45:25 steudten
450 * add casting from size_t to int for printf()
451 * remove local variable shadow s2
453 * Revision 1.26 2001/09/16 17:05:14 jongfoster
454 * Removing unused #include showarg.h
456 * Revision 1.25 2001/09/16 13:21:27 jongfoster
457 * Changes to use new list functions.
459 * Revision 1.24 2001/09/13 23:05:50 jongfoster
460 * Changing the string paramater to the header parsers a "const".
462 * Revision 1.23 2001/09/12 18:08:19 steudten
464 * In parse_http_request() header rewriting miss the host value, so
465 * from http://www.mydomain.com the result was just " / " not
466 * http://www.mydomain.com/ in case we forward.
468 * Revision 1.22 2001/09/10 10:58:53 oes
469 * Silenced compiler warnings
471 * Revision 1.21 2001/07/31 14:46:00 oes
472 * - Persistant connections now suppressed
473 * - sed() no longer appends empty header to csp->headers
475 * Revision 1.20 2001/07/30 22:08:36 jongfoster
476 * Tidying up #defines:
477 * - All feature #defines are now of the form FEATURE_xxx
478 * - Permanently turned off WIN_GUI_EDIT
479 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
481 * Revision 1.19 2001/07/25 17:21:54 oes
482 * client_uagent now saves copy of User-Agent: header value
484 * Revision 1.18 2001/07/13 14:02:46 oes
485 * - Included fix to repair broken HTTP requests that
486 * don't contain a path, not even '/'.
487 * - Removed all #ifdef PCRS
488 * - content_type now always inspected and classified as
489 * text, gif or other.
490 * - formatting / comments
492 * Revision 1.17 2001/06/29 21:45:41 oes
493 * Indentation, CRLF->LF, Tab-> Space
495 * Revision 1.16 2001/06/29 13:32:42 oes
497 * - Adapted free_http_request
498 * - Removed logentry from cancelled commit
500 * Revision 1.15 2001/06/03 19:12:38 oes
501 * deleted const struct interceptors
503 * Revision 1.14 2001/06/01 18:49:17 jongfoster
504 * Replaced "list_share" with "list" - the tiny memory gain was not
505 * worth the extra complexity.
507 * Revision 1.13 2001/05/31 21:30:33 jongfoster
508 * Removed list code - it's now in list.[ch]
509 * Renamed "permission" to "action", and changed many features
510 * to use the actions file rather than the global config.
512 * Revision 1.12 2001/05/31 17:33:13 oes
516 * Revision 1.11 2001/05/29 20:11:19 joergs
517 * '/ * inside comment' warning removed.
519 * Revision 1.10 2001/05/29 09:50:24 jongfoster
520 * Unified blocklist/imagelist/permissionslist.
521 * File format is still under discussion, but the internal changes
524 * Also modified interceptor behaviour:
525 * - We now intercept all URLs beginning with one of the following
526 * prefixes (and *only* these prefixes):
528 * * http://ijbswa.sf.net/config/
529 * * http://ijbswa.sourceforge.net/config/
530 * - New interceptors "home page" - go to http://i.j.b/ to see it.
531 * - Internal changes so that intercepted and fast redirect pages
532 * are not replaced with an image.
533 * - Interceptors now have the option to send a binary page direct
534 * to the client. (i.e. ijb-send-banner uses this)
535 * - Implemented show-url-info interceptor. (Which is why I needed
536 * the above interceptors changes - a typical URL is
537 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
538 * The previous mechanism would not have intercepted that, and
539 * if it had been intercepted then it then it would have replaced
542 * Revision 1.9 2001/05/28 17:26:33 jongfoster
543 * Fixing segfault if last header was crunched.
544 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
545 * can use the cross-platform sprintf() instead.)
547 * Revision 1.8 2001/05/27 22:17:04 oes
549 * - re_process_buffer no longer writes the modified buffer
550 * to the client, which was very ugly. It now returns the
551 * buffer, which it is then written by chat.
553 * - content_length now adjusts the Content-Length: header
554 * for modified documents rather than crunch()ing it.
555 * (Length info in csp->content_length, which is 0 for
556 * unmodified documents)
558 * - For this to work, sed() is called twice when filtering.
560 * Revision 1.7 2001/05/27 13:19:06 oes
561 * Patched Joergs solution for the content-length in.
563 * Revision 1.6 2001/05/26 13:39:32 jongfoster
564 * Only crunches Content-Length header if applying RE filtering.
565 * Without this fix, Microsoft Windows Update wouldn't work.
567 * Revision 1.5 2001/05/26 00:28:36 jongfoster
568 * Automatic reloading of config file.
569 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
570 * Most of the global variables have been moved to a new
571 * struct configuration_spec, accessed through csp->config->globalname
572 * Most of the globals remaining are used by the Win32 GUI.
574 * Revision 1.4 2001/05/22 18:46:04 oes
576 * - Enabled filtering banners by size rather than URL
577 * by adding patterns that replace all standard banner
578 * sizes with the "Junkbuster" gif to the re_filterfile
580 * - Enabled filtering WebBugs by providing a pattern
581 * which kills all 1x1 images
583 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
584 * which is selected by the (nonstandard and therefore
585 * capital) letter 'U' in the option string.
586 * It causes the quantifiers to be ungreedy by default.
587 * Appending a ? turns back to greedy (!).
589 * - Added a new interceptor ijb-send-banner, which
590 * sends back the "Junkbuster" gif. Without imagelist or
591 * MSIE detection support, or if tinygif = 1, or the
592 * URL isn't recognized as an imageurl, a lame HTML
593 * explanation is sent instead.
595 * - Added new feature, which permits blocking remote
596 * script redirects and firing back a local redirect
598 * The feature is conditionally compiled, i.e. it
599 * can be disabled with --disable-fast-redirects,
600 * plus it must be activated by a "fast-redirects"
601 * line in the config file, has its own log level
602 * and of course wants to be displayed by show-proxy-args
603 * Note: Boy, all the #ifdefs in 1001 locations and
604 * all the fumbling with configure.in and acconfig.h
605 * were *way* more work than the feature itself :-(
607 * - Because a generic redirect template was needed for
608 * this, tinygif = 3 now uses the same.
610 * - Moved GIFs, and other static HTTP response templates
615 * - Removed some >400 CRs again (Jon, you really worked
618 * Revision 1.3 2001/05/20 01:21:20 jongfoster
619 * Version 2.9.4 checkin.
620 * - Merged popupfile and cookiefile, and added control over PCRS
621 * filtering, in new "permissionsfile".
622 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
623 * file error you now get a message box (in the Win32 GUI) rather
624 * than the program exiting with no explanation.
625 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
627 * - Removed tabs from "config"
628 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
629 * - Bumped up version number.
631 * Revision 1.2 2001/05/17 23:02:36 oes
632 * - Made referrer option accept 'L' as a substitute for '§'
634 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
635 * Initial import of version 2.9.3 source tree
638 *********************************************************************/
645 #include <sys/types.h>
655 * Convince GNU's libc to provide a strptime prototype.
658 #endif /*__GLIBC__ */
665 #if !defined(_WIN32) && !defined(__OS2__)
671 #ifdef FEATURE_PTHREAD
673 /* jcc.h is for mutex semapores only */
674 #endif /* def FEATURE_PTHREAD */
680 #include "jbsockets.h"
681 #include "miscutil.h"
684 #ifndef HAVE_STRPTIME
685 #include "strptime.h"
688 const char parsers_h_rcs[] = PARSERS_H_VERSION;
690 /* Fix a problem with Solaris. There should be no effect on other
692 * Solaris's isspace() is a macro which uses it's argument directly
693 * as an array index. Therefore we need to make sure that high-bit
694 * characters generate +ve values, and ideally we also want to make
695 * the argument match the declared parameter type of "int".
697 * Why did they write a character function that can't take a simple
698 * "char" argument? Doh!
700 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
701 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
704 const struct parsers client_patterns[] = {
705 { "referer:", 8, client_referrer },
706 { "user-agent:", 11, client_uagent },
707 { "ua-", 3, client_ua },
708 { "from:", 5, client_from },
709 { "cookie:", 7, client_send_cookie },
710 { "x-forwarded-for:", 16, client_x_forwarded },
711 { "Accept-Encoding:", 16, client_accept_encoding },
712 { "TE:", 3, client_te },
713 { "Host:", 5, client_host },
714 { "if-modified-since:", 18, client_if_modified_since },
715 { "Keep-Alive:", 11, crumble },
716 { "connection:", 11, connection },
717 { "proxy-connection:", 17, crumble },
718 { "max-forwards:", 13, client_max_forwards },
719 { "Accept-Language:", 16, client_accept_language },
720 { "if-none-match:", 14, client_if_none_match },
721 { "X-Filter:", 9, client_x_filter },
722 { "*", 0, crunch_client_header },
723 { "*", 0, filter_header },
727 const struct parsers server_patterns[] = {
728 { "HTTP", 4, server_http },
729 { "set-cookie:", 11, server_set_cookie },
730 { "connection:", 11, connection },
731 { "Content-Type:", 13, server_content_type },
732 { "Content-MD5:", 12, server_content_md5 },
733 { "Content-Encoding:", 17, server_content_encoding },
734 { "Transfer-Encoding:", 18, server_transfer_coding },
735 { "Keep-Alive:", 11, crumble },
736 { "content-disposition:", 20, server_content_disposition },
737 { "Last-Modified:", 14, server_last_modified },
738 { "*", 0, crunch_server_header },
739 { "*", 0, filter_header },
743 const struct parsers server_patterns_light[] = {
744 { "Content-Length:", 15, server_content_length },
745 { "Transfer-Encoding:", 18, server_transfer_coding },
747 { "Content-Encoding:", 17, server_content_encoding },
748 #endif /* def FEATURE_ZLIB */
752 const add_header_func_ptr add_client_headers[] = {
755 client_x_forwarded_adder,
757 /* Temporarily disabled: client_accept_encoding_adder, */
758 connection_close_adder,
763 const add_header_func_ptr add_server_headers[] = {
764 connection_close_adder,
768 /*********************************************************************
770 * Function : flush_socket
772 * Description : Write any pending "buffered" content.
775 * 1 : fd = file descriptor of the socket to read
776 * 2 : csp = Current client state (buffers, headers, etc...)
778 * Returns : On success, the number of bytes written are returned (zero
779 * indicates nothing was written). On error, -1 is returned,
780 * and errno is set appropriately. If count is zero and the
781 * file descriptor refers to a regular file, 0 will be
782 * returned without causing any other effect. For a special
783 * file, the results are not portable.
785 *********************************************************************/
786 int flush_socket(jb_socket fd, struct client_state *csp)
788 struct iob *iob = csp->iob;
789 int len = iob->eod - iob->cur;
796 if (write_socket(fd, iob->cur, (size_t)len))
800 iob->eod = iob->cur = iob->buf;
806 /*********************************************************************
808 * Function : add_to_iob
810 * Description : Add content to the buffered page, expanding the
811 * buffer if necessary.
814 * 1 : csp = Current client state (buffers, headers, etc...)
815 * 2 : buf = holds the content to be added to the page
816 * 3 : n = number of bytes to be added
818 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
819 * or buffer limit reached.
821 *********************************************************************/
822 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
824 struct iob *iob = csp->iob;
825 size_t used, offset, need, want;
828 if (n <= 0) return JB_ERR_OK;
830 used = (size_t)(iob->eod - iob->buf);
831 offset = (size_t)(iob->cur - iob->buf);
832 need = used + (size_t)n + 1;
835 * If the buffer can't hold the new data, extend it first.
836 * Use the next power of two if possible, else use the actual need.
838 if (need > csp->config->buffer_limit)
840 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
841 return JB_ERR_MEMORY;
844 if (need > iob->size)
846 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
848 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
852 else if (NULL != (p = (char *)realloc(iob->buf, need)))
858 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
859 return JB_ERR_MEMORY;
862 /* Update the iob pointers */
863 iob->cur = p + offset;
868 /* copy the new data into the iob buffer */
869 memcpy(iob->eod, buf, (size_t)n);
871 /* point to the end of the data */
874 /* null terminate == cheap insurance */
883 /*********************************************************************
885 * Function : decompress_iob
887 * Description : Decompress buffered page, expanding the
888 * buffer as necessary. csp->iob->cur
889 * should point to the the beginning of the
890 * compressed data block.
893 * 1 : csp = Current client state (buffers, headers, etc...)
895 * Returns : JB_ERR_OK on success,
896 * JB_ERR_MEMORY if out-of-memory limit reached, and
897 * JB_ERR_COMPRESS if error decompressing buffer.
899 *********************************************************************/
900 jb_err decompress_iob(struct client_state *csp)
902 char *buf; /* new, uncompressed buffer */
903 char *cur; /* Current iob position (to keep the original
904 * iob->cur unmodified if we return early) */
905 size_t bufsize; /* allocated size of the new buffer */
906 size_t old_size; /* Content size before decompression */
907 size_t skip_size; /* Number of bytes at the beginning of the iob
908 that we should NOT decompress. */
909 int status; /* return status of the inflate() call */
910 z_stream zstr; /* used by calls to zlib */
912 assert(csp->iob->cur - csp->iob->buf > 0);
913 assert(csp->iob->eod - csp->iob->cur > 0);
915 bufsize = csp->iob->size;
916 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
917 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
924 * This is to protect the parsing of gzipped data,
925 * but it should(?) be valid for deflated data also.
927 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
928 return JB_ERR_COMPRESS;
931 if (csp->content_type & CT_GZIP)
934 * Our task is slightly complicated by the facts that data
935 * compressed by gzip does not include a zlib header, and
936 * that there is no easily accessible interface in zlib to
937 * handle a gzip header. We strip off the gzip header by
938 * hand, and later inform zlib not to expect a header.
942 * Strip off the gzip header. Please see RFC 1952 for more
943 * explanation of the appropriate fields.
945 if ((*cur++ != (char)0x1f)
946 || (*cur++ != (char)0x8b)
947 || (*cur++ != Z_DEFLATED))
949 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
950 return JB_ERR_COMPRESS;
956 * XXX: These magic numbers should be replaced
957 * with macros to give a better idea what they do.
961 /* The gzip header has reserved bits set; bail out. */
962 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
963 return JB_ERR_COMPRESS;
967 /* Skip extra fields if necessary. */
971 * Skip a given number of bytes, specified
972 * as a 16-bit little-endian value.
975 * XXX: This code used to be:
977 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
979 * which I had to change into:
981 * cur += *cur++ + (*cur++ << 8);
983 * at which point gcc43 finally noticed that the value
984 * of cur is undefined (it depends on which of the
985 * summands is evaluated first).
987 * I haven't come across a site where this
988 * code is actually executed yet, but I hope
993 skip_bytes = *cur++ << 8;
995 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
998 * The number of bytes to skip should be positive
999 * and we'd like to stay in the buffer.
1001 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1003 log_error (LOG_LEVEL_ERROR,
1004 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1006 return JB_ERR_COMPRESS;
1008 log_error (LOG_LEVEL_INFO,
1009 "Skipping %d bytes for gzip compression. Does this sound right?",
1014 /* Skip the filename if necessary. */
1017 /* A null-terminated string is supposed to follow. */
1018 while (*cur++ && (cur < csp->iob->eod));
1022 /* Skip the comment if necessary. */
1025 /* A null-terminated string is supposed to follow. */
1026 while (*cur++ && (cur < csp->iob->eod));
1029 /* Skip the CRC if necessary. */
1035 if (cur >= csp->iob->eod)
1038 * If the current position pointer reached or passed
1039 * the buffer end, we were obviously tricked to skip
1042 log_error (LOG_LEVEL_ERROR,
1043 "Malformed gzip header detected. Aborting decompression.");
1044 return JB_ERR_COMPRESS;
1048 else if (csp->content_type & CT_DEFLATE)
1051 * XXX: The debug level should be lowered
1052 * before the next stable release.
1054 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1056 * In theory (that is, according to RFC 1950), deflate-compressed
1057 * data should begin with a two-byte zlib header and have an
1058 * adler32 checksum at the end. It seems that in practice only
1059 * the raw compressed data is sent. Note that this means that
1060 * we are not RFC 1950-compliant here, but the advantage is that
1061 * this actually works. :)
1063 * We add a dummy null byte to tell zlib where the data ends,
1064 * and later inform it not to expect a header.
1066 * Fortunately, add_to_iob() has thoughtfully null-terminated
1067 * the buffer; we can just increment the end pointer to include
1074 log_error (LOG_LEVEL_ERROR,
1075 "Unable to determine compression format for decompression");
1076 return JB_ERR_COMPRESS;
1079 /* Set up the fields required by zlib. */
1080 zstr.next_in = (Bytef *)cur;
1081 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1082 zstr.zalloc = Z_NULL;
1083 zstr.zfree = Z_NULL;
1084 zstr.opaque = Z_NULL;
1087 * Passing -MAX_WBITS to inflateInit2 tells the library
1088 * that there is no zlib header.
1090 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1092 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1093 return JB_ERR_COMPRESS;
1097 * Next, we allocate new storage for the inflated data.
1098 * We don't modify the existing iob yet, so in case there
1099 * is error in decompression we can recover gracefully.
1101 buf = zalloc (bufsize);
1104 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1105 return JB_ERR_MEMORY;
1108 assert(bufsize >= skip_size);
1109 memcpy(buf, csp->iob->buf, skip_size);
1110 zstr.avail_out = bufsize - skip_size;
1111 zstr.next_out = (Bytef *)buf + skip_size;
1113 /* Try to decompress the whole stream in one shot. */
1114 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1116 /* We need to allocate more memory for the output buffer. */
1118 char *tmpbuf; /* used for realloc'ing the buffer */
1119 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1122 * If zlib wants more data then there's a problem, because
1123 * the complete compressed file should have been buffered.
1125 if (0 == zstr.avail_in)
1127 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1128 return JB_ERR_COMPRESS;
1132 * If we tried the limit and still didn't have enough
1133 * memory, just give up.
1135 if (bufsize == csp->config->buffer_limit)
1137 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1138 return JB_ERR_MEMORY;
1141 /* Try doubling the buffer size each time. */
1144 /* Don't exceed the buffer limit. */
1145 if (bufsize > csp->config->buffer_limit)
1147 bufsize = csp->config->buffer_limit;
1150 /* Try to allocate the new buffer. */
1151 tmpbuf = realloc(buf, bufsize);
1154 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1156 return JB_ERR_MEMORY;
1160 char *oldnext_out = (char *)zstr.next_out;
1163 * Update the fields for inflate() to use the new
1164 * buffer, which may be in a location different from
1167 zstr.avail_out += bufsize - oldbufsize;
1168 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1171 * Compare with an uglier method of calculating these values
1172 * that doesn't require the extra oldbufsize variable.
1174 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1175 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1176 assert(zstr.avail_out > 0);
1182 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1184 log_error(LOG_LEVEL_ERROR,
1185 "Inconsistent stream state after decompression: %s", zstr.msg);
1187 * XXX: Intentionally no return.
1189 * According to zlib.h, Z_STREAM_ERROR is returned
1190 * "if the stream state was inconsistent".
1192 * I assume in this case inflate()'s status
1193 * would also be something different than Z_STREAM_END
1194 * so this check should be redundant, but lets see.
1198 if (status != Z_STREAM_END)
1200 /* We failed to decompress the stream. */
1201 log_error(LOG_LEVEL_ERROR,
1202 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1203 return JB_ERR_COMPRESS;
1207 * Finally, we can actually update the iob, since the
1208 * decompression was successful. First, free the old
1211 freez(csp->iob->buf);
1213 /* Now, update the iob to use the new buffer. */
1214 csp->iob->buf = buf;
1215 csp->iob->cur = csp->iob->buf + skip_size;
1216 csp->iob->eod = (char *)zstr.next_out;
1217 csp->iob->size = bufsize;
1220 * Make sure the new uncompressed iob obeys some minimal
1221 * consistency conditions.
1223 if ((csp->iob->buf < csp->iob->cur)
1224 && (csp->iob->cur <= csp->iob->eod)
1225 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1227 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1230 log_error(LOG_LEVEL_RE_FILTER,
1231 "Decompression successful. Old size: %d, new size: %d.",
1232 old_size, new_size);
1236 /* zlib thinks this is OK, so lets do the same. */
1237 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1242 /* It seems that zlib did something weird. */
1243 log_error(LOG_LEVEL_ERROR,
1244 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1245 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1246 csp->iob->eod, csp->iob->buf + csp->iob->size);
1247 return JB_ERR_COMPRESS;
1253 #endif /* defined(FEATURE_ZLIB) */
1256 /*********************************************************************
1258 * Function : get_header
1260 * Description : This (odd) routine will parse the csp->iob
1263 * 1 : csp = Current client state (buffers, headers, etc...)
1265 * Returns : Any one of the following:
1267 * 1) a pointer to a dynamically allocated string that contains a header line
1268 * 2) NULL indicating that the end of the header was reached
1269 * 3) "" indicating that the end of the iob was reached before finding
1270 * a complete header line.
1272 *********************************************************************/
1273 char *get_header(struct client_state *csp)
1279 if ((iob->cur == NULL)
1280 || ((p = strchr(iob->cur, '\n')) == NULL))
1282 return(""); /* couldn't find a complete header */
1287 ret = strdup(iob->cur);
1290 /* FIXME No way to handle error properly */
1291 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1296 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1298 /* is this a blank line (i.e. the end of the header) ? */
1310 /*********************************************************************
1312 * Function : get_header_value
1314 * Description : Get the value of a given header from a chained list
1315 * of header lines or return NULL if no such header is
1316 * present in the list.
1319 * 1 : header_list = pointer to list
1320 * 2 : header_name = string with name of header to look for.
1321 * Trailing colon required, capitalization
1324 * Returns : NULL if not found, else value of header
1326 *********************************************************************/
1327 char *get_header_value(const struct list *header_list, const char *header_name)
1329 struct list_entry *cur_entry;
1333 assert(header_list);
1334 assert(header_name);
1335 length = strlen(header_name);
1337 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1341 if (!strncmpic(cur_entry->str, header_name, length))
1344 * Found: return pointer to start of value
1346 ret = (char *) (cur_entry->str + length);
1347 while (*ret && ijb_isspace(*ret)) ret++;
1360 /*********************************************************************
1364 * Description : add, delete or modify lines in the HTTP header streams.
1365 * On entry, it receives a linked list of headers space
1366 * that was allocated dynamically (both the list nodes
1367 * and the header contents).
1369 * As a side effect it frees the space used by the original
1373 * 1 : pats = list of patterns to match against headers
1374 * 2 : more_headers = list of functions to add more
1375 * headers (client or server)
1376 * 3 : csp = Current client state (buffers, headers, etc...)
1378 * Returns : Single pointer to a fully formed header, or NULL
1379 * on out-of-memory error.
1381 *********************************************************************/
1382 char *sed(const struct parsers pats[],
1383 const add_header_func_ptr more_headers[],
1384 struct client_state *csp)
1386 struct list_entry *p;
1387 const struct parsers *v;
1388 const add_header_func_ptr *f;
1389 jb_err err = JB_ERR_OK;
1393 * If filtering is enabled, sed is run twice,
1394 * but most of the work needs to be done only once.
1396 first_run = (more_headers != NULL ) ? 1 : 0;
1398 if (first_run) /* Parse and print */
1400 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1401 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1403 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1405 /* Header crunch()ed in previous run? -> ignore */
1406 if (p->str == NULL) continue;
1408 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
1410 /* Does the current parser handle this header? */
1411 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1413 err = v->parser(csp, (char **)&(p->str));
1417 /* place any additional headers on the csp->headers list */
1418 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1423 else /* Parse only */
1426 * The second run is only needed if the body was modified
1427 * and the content-lenght has changed.
1429 if (strncmpic(csp->http->cmd, "HEAD", 4))
1431 /*XXX: Code duplication */
1432 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1434 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1436 /* Header crunch()ed in previous run? -> ignore */
1437 if (p->str == NULL) continue;
1439 /* Does the current parser handle this header? */
1440 if (strncmpic(p->str, v->str, v->len) == 0)
1442 err = v->parser(csp, (char **)&(p->str));
1449 if (err != JB_ERR_OK)
1454 return list_to_text(csp->headers);
1458 /* here begins the family of parser functions that reformat header lines */
1460 /*********************************************************************
1462 * Function : filter_header
1464 * Description : Executes all text substitutions from all applying
1465 * +(server|client)-header-filter actions on the header.
1466 * Most of the code was copied from pcrs_filter_response,
1467 * including the rather short variable names
1470 * 1 : csp = Current client state (buffers, headers, etc...)
1471 * 2 : header = On input, pointer to header to modify.
1472 * On output, pointer to the modified header, or NULL
1473 * to remove the header. This function frees the
1474 * original string if necessary.
1476 * Returns : JB_ERR_OK on success and always succeeds
1478 *********************************************************************/
1479 jb_err filter_header(struct client_state *csp, char **header)
1483 size_t size = strlen(*header);
1485 char *newheader = NULL;
1488 struct file_list *fl;
1489 struct re_filterfile_spec *b;
1490 struct list_entry *filtername;
1492 int i, found_filters = 0;
1493 int wanted_filter_type;
1494 int multi_action_index;
1496 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1498 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1499 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1503 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1504 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1508 * Need to check the set of re_filterfiles...
1510 for (i = 0; i < MAX_AF_FILES; i++)
1523 if (0 == found_filters)
1525 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1529 for (i = 0; i < MAX_AF_FILES; i++)
1532 if ((NULL == fl) || (NULL == fl->f))
1535 * Either there are no filter files
1536 * left, or this filter file just
1537 * contains no valid filters.
1539 * Continue to be sure we don't miss
1540 * valid filter files that are chained
1541 * after empty or invalid ones.
1546 * For all applying +filter actions, look if a filter by that
1547 * name exists and if yes, execute its pcrs_joblist on the
1550 for (b = fl->f; b; b = b->next)
1552 if (b->type != wanted_filter_type)
1554 /* Skip other filter types */
1558 for (filtername = csp->action->multi[multi_action_index]->first;
1559 filtername ; filtername = filtername->next)
1561 if (strcmp(b->name, filtername->str) == 0)
1563 int current_hits = 0;
1565 if ( NULL == b->joblist )
1567 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1571 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1572 *header, size, b->name);
1574 /* Apply all jobs from the joblist */
1575 for (job = b->joblist; NULL != job; job = job->next)
1577 matches = pcrs_execute(job, *header, size, &newheader, &size);
1580 current_hits += matches;
1581 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1583 *header = newheader;
1585 else if ( 0 == matches )
1587 /* Filter doesn't change header */
1593 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1594 *header, b->name, pcrs_strerror(matches));
1595 if( newheader != NULL)
1597 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1602 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1603 hits += current_hits;
1610 * Additionally checking for hits is important because if
1611 * the continue hack is triggered, server headers can
1612 * arrive empty to separate multiple heads from each other.
1614 if ((0 == size) && hits)
1616 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1624 /*********************************************************************
1626 * Function : connection
1628 * Description : Makes sure that the value of the Connection: header
1629 * is "close" and signals connection_close_adder
1633 * 1 : csp = Current client state (buffers, headers, etc...)
1634 * 2 : header = On input, pointer to header to modify.
1635 * On output, pointer to the modified header, or NULL
1636 * to remove the header. This function frees the
1637 * original string if necessary.
1639 * Returns : JB_ERR_OK on success, or
1640 * JB_ERR_MEMORY on out-of-memory error.
1642 *********************************************************************/
1643 jb_err connection(struct client_state *csp, char **header)
1645 char *old_header = *header;
1647 /* Do we have a 'Connection: close' header? */
1648 if (strcmpic(*header, "Connection: close"))
1650 /* No, create one */
1651 *header = strdup("Connection: close");
1654 return JB_ERR_MEMORY;
1656 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1660 /* Signal connection_close_adder() to return early. */
1661 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1663 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
1667 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
1674 /*********************************************************************
1676 * Function : crumble
1678 * Description : This is called if a header matches a pattern to "crunch"
1681 * 1 : csp = Current client state (buffers, headers, etc...)
1682 * 2 : header = On input, pointer to header to modify.
1683 * On output, pointer to the modified header, or NULL
1684 * to remove the header. This function frees the
1685 * original string if necessary.
1687 * Returns : JB_ERR_OK on success, or
1688 * JB_ERR_MEMORY on out-of-memory error.
1690 *********************************************************************/
1691 jb_err crumble(struct client_state *csp, char **header)
1693 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1698 /*********************************************************************
1700 * Function : crunch_server_header
1702 * Description : Crunch server header if it matches a string supplied by the
1703 * user. Called from `sed'.
1706 * 1 : csp = Current client state (buffers, headers, etc...)
1707 * 2 : header = On input, pointer to header to modify.
1708 * On output, pointer to the modified header, or NULL
1709 * to remove the header. This function frees the
1710 * original string if necessary.
1712 * Returns : JB_ERR_OK on success and always succeeds
1714 *********************************************************************/
1715 jb_err crunch_server_header(struct client_state *csp, char **header)
1717 const char *crunch_pattern;
1719 /* Do we feel like crunching? */
1720 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1722 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1724 /* Is the current header the lucky one? */
1725 if (strstr(*header, crunch_pattern))
1727 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1736 /*********************************************************************
1738 * Function : server_content_type
1740 * Description : Set the content-type for filterable types (text/.*,
1741 * .*xml.*, javascript and image/gif) unless filtering has been
1742 * forbidden (CT_TABOO) while parsing earlier headers.
1743 * NOTE: Since text/plain is commonly used by web servers
1744 * for files whose correct type is unknown, we don't
1745 * set CT_TEXT for it.
1748 * 1 : csp = Current client state (buffers, headers, etc...)
1749 * 2 : header = On input, pointer to header to modify.
1750 * On output, pointer to the modified header, or NULL
1751 * to remove the header. This function frees the
1752 * original string if necessary.
1754 * Returns : JB_ERR_OK on success, or
1755 * JB_ERR_MEMORY on out-of-memory error.
1757 *********************************************************************/
1758 jb_err server_content_type(struct client_state *csp, char **header)
1760 /* Remove header if it isn't the first Content-Type header */
1761 if(csp->content_type && (csp->content_type != CT_TABOO))
1764 * Another, slightly slower, way to see if
1765 * we already parsed another Content-Type header.
1767 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1769 log_error(LOG_LEVEL_ERROR,
1770 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1777 if (!(csp->content_type & CT_TABOO))
1779 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1780 || strstr(*header, "xml")
1781 || strstr(*header, "application/x-javascript"))
1783 csp->content_type |= CT_TEXT;
1785 else if (strstr(*header, " image/gif"))
1787 csp->content_type |= CT_GIF;
1789 else if (strstr(*header, " image/jpeg"))
1791 csp->content_type |= CT_JPEG;
1795 csp->content_type = 0;
1799 * Are we enabling text mode by force?
1801 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1804 * Do we really have to?
1806 if (csp->content_type & CT_TEXT)
1808 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1812 csp->content_type |= CT_TEXT;
1813 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1817 * Are we messing with the content type?
1819 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1822 * Make sure the user doesn't accidently
1823 * change the content type of binary documents.
1825 if (csp->content_type & CT_TEXT)
1828 *header = strdup("Content-Type: ");
1829 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1833 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1834 return JB_ERR_MEMORY;
1836 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1840 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1841 "Enable force-text-mode if you know what you're doing.", *header);
1848 /*********************************************************************
1850 * Function : server_transfer_coding
1852 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1853 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1854 * - Remove header if body was chunked but has been
1855 * de-chunked for filtering.
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_transfer_coding(struct client_state *csp, char **header)
1871 * Turn off pcrs and gif filtering if body compressed
1873 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1877 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1879 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1880 csp->http->cmd, *header);
1881 #endif /* def FEATURE_ZLIB */
1882 csp->content_type = CT_TABOO;
1886 * Raise flag if body chunked
1888 if (strstr(*header, "chunked"))
1890 csp->flags |= CSP_FLAG_CHUNKED;
1893 * If the body was modified, it has been de-chunked first
1894 * and the header must be removed.
1896 * FIXME: If there is more than one transfer encoding,
1897 * only the "chunked" part should be removed here.
1899 if (csp->flags & CSP_FLAG_MODIFIED)
1901 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1910 /*********************************************************************
1912 * Function : server_content_encoding
1914 * Description : This function is run twice for each request,
1915 * unless FEATURE_ZLIB and filtering are disabled.
1917 * The first run is used to check if the content
1918 * is compressed, if FEATURE_ZLIB is disabled
1919 * filtering is then disabled as well, if FEATURE_ZLIB
1920 * is enabled the content is marked for decompression.
1922 * The second run is used to remove the Content-Encoding
1923 * header if the decompression was successful.
1926 * 1 : csp = Current client state (buffers, headers, etc...)
1927 * 2 : header = On input, pointer to header to modify.
1928 * On output, pointer to the modified header, or NULL
1929 * to remove the header. This function frees the
1930 * original string if necessary.
1932 * Returns : JB_ERR_OK on success, or
1933 * JB_ERR_MEMORY on out-of-memory error.
1935 *********************************************************************/
1936 jb_err server_content_encoding(struct client_state *csp, char **header)
1939 if ((csp->flags & CSP_FLAG_MODIFIED)
1940 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1943 * We successfully decompressed the content,
1944 * and have to clean the header now, so the
1945 * client no longer expects compressed data..
1947 * XXX: There is a difference between cleaning
1948 * and removing it completely.
1950 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1953 else if (strstr(*header, "gzip"))
1955 /* Mark for gzip decompression */
1956 csp->content_type |= CT_GZIP;
1958 else if (strstr(*header, "deflate"))
1960 /* Mark for zlib decompression */
1961 csp->content_type |= CT_DEFLATE;
1963 else if (strstr(*header, "compress"))
1966 * We can't decompress this; therefore we can't filter
1969 csp->content_type |= CT_TABOO;
1971 #else /* !defined(FEATURE_ZLIB) */
1972 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1975 * Body is compressed, turn off pcrs and gif filtering.
1977 csp->content_type |= CT_TABOO;
1979 #endif /* !defined(FEATURE_ZLIB) */
1986 /*********************************************************************
1988 * Function : server_content_length
1990 * Description : Adjust Content-Length header if we modified
1994 * 1 : csp = Current client state (buffers, headers, etc...)
1995 * 2 : header = On input, pointer to header to modify.
1996 * On output, pointer to the modified header, or NULL
1997 * to remove the header. This function frees the
1998 * original string if necessary.
2000 * Returns : JB_ERR_OK on success, or
2001 * JB_ERR_MEMORY on out-of-memory error.
2003 *********************************************************************/
2004 jb_err server_content_length(struct client_state *csp, char **header)
2006 const size_t max_header_length = 80;
2008 /* Regenerate header if the content was modified. */
2009 if (csp->flags & CSP_FLAG_MODIFIED)
2012 *header = (char *) zalloc(max_header_length);
2013 if (*header == NULL)
2015 return JB_ERR_MEMORY;
2018 snprintf(*header, max_header_length, "Content-Length: %d",
2019 (int)csp->content_length);
2020 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2021 (int)csp->content_length);
2028 /*********************************************************************
2030 * Function : server_content_md5
2032 * Description : Crumble any Content-MD5 headers if the document was
2033 * modified. FIXME: Should we re-compute instead?
2036 * 1 : csp = Current client state (buffers, headers, etc...)
2037 * 2 : header = On input, pointer to header to modify.
2038 * On output, pointer to the modified header, or NULL
2039 * to remove the header. This function frees the
2040 * original string if necessary.
2042 * Returns : JB_ERR_OK on success, or
2043 * JB_ERR_MEMORY on out-of-memory error.
2045 *********************************************************************/
2046 jb_err server_content_md5(struct client_state *csp, char **header)
2048 if (csp->flags & CSP_FLAG_MODIFIED)
2050 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2057 /*********************************************************************
2059 * Function : server_content_disposition
2061 * Description : If enabled, blocks or modifies the "content-disposition" header.
2062 * Called from `sed'.
2065 * 1 : csp = Current client state (buffers, headers, etc...)
2066 * 2 : header = On input, pointer to header to modify.
2067 * On output, pointer to the modified header, or NULL
2068 * to remove the header. This function frees the
2069 * original string if necessary.
2071 * Returns : JB_ERR_OK on success, or
2072 * JB_ERR_MEMORY on out-of-memory error.
2074 *********************************************************************/
2075 jb_err server_content_disposition(struct client_state *csp, char **header)
2080 * Are we messing with the content-disposition header?
2082 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2088 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2090 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2093 * Blocking content-disposition header
2095 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2102 * Replacing content-disposition header
2105 *header = strdup("content-disposition: ");
2106 string_append(header, newval);
2108 if (*header == NULL)
2110 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2114 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2117 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2120 /*********************************************************************
2122 * Function : server_last_modified
2124 * Description : Changes Last-Modified header to the actual date
2125 * to help hide-if-modified-since.
2126 * Called from `sed'.
2129 * 1 : csp = Current client state (buffers, headers, etc...)
2130 * 2 : header = On input, pointer to header to modify.
2131 * On output, pointer to the modified header, or NULL
2132 * to remove the header. This function frees the
2133 * original string if necessary.
2135 * Returns : JB_ERR_OK on success, or
2136 * JB_ERR_MEMORY on out-of-memory error.
2138 *********************************************************************/
2139 jb_err server_last_modified(struct client_state *csp, char **header)
2142 char buf[BUFFER_SIZE];
2145 #ifdef HAVE_GMTIME_R
2148 struct tm *timeptr = NULL;
2149 time_t now, last_modified;
2151 long int days, hours, minutes, seconds;
2154 * Are we messing with the Last-Modified header?
2156 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2162 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2164 if (0 == strcmpic(newval, "block") )
2167 * Blocking Last-Modified header. Useless but why not.
2169 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2173 else if (0 == strcmpic(newval, "reset-to-request-time"))
2176 * Setting Last-Modified Header to now.
2178 get_http_time(0, buf);
2180 *header = strdup("Last-Modified: ");
2181 string_append(header, buf);
2183 if (*header == NULL)
2185 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2189 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2192 else if (0 == strcmpic(newval, "randomize"))
2194 const char *header_time = *header + sizeof("Last-Modified:");
2196 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2198 #ifdef HAVE_GMTIME_R
2199 timeptr = gmtime_r(&now, &gmt);
2200 #elif FEATURE_PTHREAD
2201 pthread_mutex_lock(&gmtime_mutex);
2202 timeptr = gmtime(&now);
2203 pthread_mutex_unlock(&gmtime_mutex);
2205 timeptr = gmtime(&now);
2207 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2209 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2214 rtime = (long int)difftime(now, last_modified);
2217 rtime = pick_from_range(rtime);
2218 last_modified += rtime;
2219 #ifdef HAVE_GMTIME_R
2220 timeptr = gmtime_r(&last_modified, &gmt);
2221 #elif FEATURE_PTHREAD
2222 pthread_mutex_lock(&gmtime_mutex);
2223 timeptr = gmtime(&last_modified);
2224 pthread_mutex_unlock(&gmtime_mutex);
2226 timeptr = gmtime(&last_modified);
2228 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2230 *header = strdup("Last-Modified: ");
2231 string_append(header, newheader);
2233 if (*header == NULL)
2235 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2236 return JB_ERR_MEMORY;
2239 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2241 days = rtime / (3600 * 24);
2242 hours = rtime / 3600 % 24;
2243 minutes = rtime / 60 % 60;
2244 seconds = rtime % 60;
2246 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2247 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2248 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2253 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2262 /*********************************************************************
2264 * Function : client_accept_encoding
2266 * Description : Rewrite the client's Accept-Encoding header so that
2267 * if doesn't allow compression, if the action applies.
2268 * Note: For HTTP/1.0 the absence of the header is enough.
2271 * 1 : csp = Current client state (buffers, headers, etc...)
2272 * 2 : header = On input, pointer to header to modify.
2273 * On output, pointer to the modified header, or NULL
2274 * to remove the header. This function frees the
2275 * original string if necessary.
2277 * Returns : JB_ERR_OK on success, or
2278 * JB_ERR_MEMORY on out-of-memory error.
2280 *********************************************************************/
2281 jb_err client_accept_encoding(struct client_state *csp, char **header)
2283 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2285 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2289 /* Temporarily disable the correct behaviour to
2290 * work around a PHP bug.
2292 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2294 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2295 * if (*header == NULL)
2297 * return JB_ERR_MEMORY;
2308 /*********************************************************************
2310 * Function : client_te
2312 * Description : Rewrite the client's TE header so that
2313 * if doesn't allow compression, if the action applies.
2316 * 1 : csp = Current client state (buffers, headers, etc...)
2317 * 2 : header = On input, pointer to header to modify.
2318 * On output, pointer to the modified header, or NULL
2319 * to remove the header. This function frees the
2320 * original string if necessary.
2322 * Returns : JB_ERR_OK on success, or
2323 * JB_ERR_MEMORY on out-of-memory error.
2325 *********************************************************************/
2326 jb_err client_te(struct client_state *csp, char **header)
2328 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2331 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2337 /*********************************************************************
2339 * Function : client_referrer
2341 * Description : Handle the "referer" config setting properly.
2342 * Called from `sed'.
2345 * 1 : csp = Current client state (buffers, headers, etc...)
2346 * 2 : header = On input, pointer to header to modify.
2347 * On output, pointer to the modified header, or NULL
2348 * to remove the header. This function frees the
2349 * original string if necessary.
2351 * Returns : JB_ERR_OK on success, or
2352 * JB_ERR_MEMORY on out-of-memory error.
2354 *********************************************************************/
2355 jb_err client_referrer(struct client_state *csp, char **header)
2362 #ifdef FEATURE_FORCE_LOAD
2363 /* Since the referrer can include the prefix even
2364 * if the request itself is non-forced, we must
2365 * clean it unconditionally
2367 strclean(*header, FORCE_PREFIX);
2368 #endif /* def FEATURE_FORCE_LOAD */
2371 * Are we sending referer?
2373 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2378 newval = csp->action->string[ACTION_STRING_REFERER];
2380 if ((0 != strcmpic(newval, "conditional-block")))
2384 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2389 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2392 else if (0 == strcmpic(newval, "conditional-block"))
2395 * Block referer if host has changed.
2398 if (NULL == (host = strdup(csp->http->hostport)))
2401 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2402 return JB_ERR_MEMORY;
2404 if (NULL == (referer = strdup(*header)))
2408 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2409 return JB_ERR_MEMORY;
2411 hostlenght = strlen(host);
2412 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2414 /*Shorten referer to make sure the referer is blocked
2415 *if www.example.org/www.example.com-shall-see-the-referer/
2416 *links to www.example.com/
2418 referer[hostlenght+17] = '\0';
2420 if ( 0 == strstr(referer, host)) /*Host has changed*/
2422 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2427 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2433 else if (0 != strcmpic(newval, "forge"))
2436 * We have a specific (fixed) referer we want to send.
2438 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2440 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2442 *header = strdup("Referer: ");
2443 string_append(header, newval);
2444 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2446 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2451 * Forge a referer as http://[hostname:port of REQUEST]/
2452 * to fool stupid checks for in-site links
2455 *header = strdup("Referer: http://");
2456 string_append(header, csp->http->hostport);
2457 string_append(header, "/");
2458 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2460 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2464 /*********************************************************************
2466 * Function : client_accept_language
2468 * Description : Handle the "Accept-Language" config setting properly.
2469 * Called from `sed'.
2472 * 1 : csp = Current client state (buffers, headers, etc...)
2473 * 2 : header = On input, pointer to header to modify.
2474 * On output, pointer to the modified header, or NULL
2475 * to remove the header. This function frees the
2476 * original string if necessary.
2478 * Returns : JB_ERR_OK on success, or
2479 * JB_ERR_MEMORY on out-of-memory error.
2481 *********************************************************************/
2482 jb_err client_accept_language(struct client_state *csp, char **header)
2487 * Are we messing with the Accept-Language?
2489 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2491 /*I don't think so*/
2495 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2497 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2500 * Blocking Accept-Language header
2502 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2509 * Replacing Accept-Language header
2512 *header = strdup("Accept-Language: ");
2513 string_append(header, newval);
2515 if (*header == NULL)
2517 log_error(LOG_LEVEL_ERROR,
2518 "Insufficent memory. Accept-Language header crunched without replacement.");
2522 log_error(LOG_LEVEL_HEADER,
2523 "Accept-Language header crunched and replaced with: %s", *header);
2526 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2529 /*********************************************************************
2531 * Function : crunch_client_header
2533 * Description : Crunch client header if it matches a string supplied by the
2534 * user. Called from `sed'.
2537 * 1 : csp = Current client state (buffers, headers, etc...)
2538 * 2 : header = On input, pointer to header to modify.
2539 * On output, pointer to the modified header, or NULL
2540 * to remove the header. This function frees the
2541 * original string if necessary.
2543 * Returns : JB_ERR_OK on success and always succeeds
2545 *********************************************************************/
2546 jb_err crunch_client_header(struct client_state *csp, char **header)
2548 const char *crunch_pattern;
2550 /* Do we feel like crunching? */
2551 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2553 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2555 /* Is the current header the lucky one? */
2556 if (strstr(*header, crunch_pattern))
2558 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2566 /*********************************************************************
2568 * Function : client_uagent
2570 * Description : Handle the "user-agent" config setting properly
2571 * and remember its original value to enable browser
2572 * bug workarounds. Called from `sed'.
2575 * 1 : csp = Current client state (buffers, headers, etc...)
2576 * 2 : header = On input, pointer to header to modify.
2577 * On output, pointer to the modified header, or NULL
2578 * to remove the header. This function frees the
2579 * original string if necessary.
2581 * Returns : JB_ERR_OK on success, or
2582 * JB_ERR_MEMORY on out-of-memory error.
2584 *********************************************************************/
2585 jb_err client_uagent(struct client_state *csp, char **header)
2589 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2594 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2601 *header = strdup("User-Agent: ");
2602 string_append(header, newval);
2604 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2606 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2609 /*********************************************************************
2611 * Function : client_ua
2613 * Description : Handle "ua-" headers properly. Called from `sed'.
2616 * 1 : csp = Current client state (buffers, headers, etc...)
2617 * 2 : header = On input, pointer to header to modify.
2618 * On output, pointer to the modified header, or NULL
2619 * to remove the header. This function frees the
2620 * original string if necessary.
2622 * Returns : JB_ERR_OK on success, or
2623 * JB_ERR_MEMORY on out-of-memory error.
2625 *********************************************************************/
2626 jb_err client_ua(struct client_state *csp, char **header)
2628 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2630 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2638 /*********************************************************************
2640 * Function : client_from
2642 * Description : Handle the "from" config setting properly.
2643 * Called from `sed'.
2646 * 1 : csp = Current client state (buffers, headers, etc...)
2647 * 2 : header = On input, pointer to header to modify.
2648 * On output, pointer to the modified header, or NULL
2649 * to remove the header. This function frees the
2650 * original string if necessary.
2652 * Returns : JB_ERR_OK on success, or
2653 * JB_ERR_MEMORY on out-of-memory error.
2655 *********************************************************************/
2656 jb_err client_from(struct client_state *csp, char **header)
2660 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2667 newval = csp->action->string[ACTION_STRING_FROM];
2670 * Are we blocking the e-mail address?
2672 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2674 log_error(LOG_LEVEL_HEADER, "crunched From!");
2678 log_error(LOG_LEVEL_HEADER, " modified");
2680 *header = strdup("From: ");
2681 string_append(header, newval);
2683 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2687 /*********************************************************************
2689 * Function : client_send_cookie
2691 * Description : Crunches the "cookie" header if necessary.
2692 * Called from `sed'.
2694 * XXX: Stupid name, doesn't send squat.
2697 * 1 : csp = Current client state (buffers, headers, etc...)
2698 * 2 : header = On input, pointer to header to modify.
2699 * On output, pointer to the modified header, or NULL
2700 * to remove the header. This function frees the
2701 * original string if necessary.
2703 * Returns : JB_ERR_OK on success, or
2704 * JB_ERR_MEMORY on out-of-memory error.
2706 *********************************************************************/
2707 jb_err client_send_cookie(struct client_state *csp, char **header)
2709 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2711 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2719 /*********************************************************************
2721 * Function : client_x_forwarded
2723 * Description : Handle the "x-forwarded-for" config setting properly,
2724 * also used in the add_client_headers list. Called from `sed'.
2727 * 1 : csp = Current client state (buffers, headers, etc...)
2728 * 2 : header = On input, pointer to header to modify.
2729 * On output, pointer to the modified header, or NULL
2730 * to remove the header. This function frees the
2731 * original string if necessary.
2733 * Returns : JB_ERR_OK on success, or
2734 * JB_ERR_MEMORY on out-of-memory error.
2736 *********************************************************************/
2737 jb_err client_x_forwarded(struct client_state *csp, char **header)
2739 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2741 /* Save it so we can re-add it later */
2742 freez(csp->x_forwarded);
2743 csp->x_forwarded = *header;
2746 * Always set *header = NULL, since this information
2747 * will be sent at the end of the header.
2754 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2761 /*********************************************************************
2763 * Function : client_max_forwards
2765 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2766 * from the value of the Max-Forwards header field.
2769 * 1 : csp = Current client state (buffers, headers, etc...)
2770 * 2 : header = On input, pointer to header to modify.
2771 * On output, pointer to the modified header, or NULL
2772 * to remove the header. This function frees the
2773 * original string if necessary.
2775 * Returns : JB_ERR_OK on success, or
2776 * JB_ERR_MEMORY on out-of-memory error.
2778 *********************************************************************/
2779 jb_err client_max_forwards(struct client_state *csp, char **header)
2783 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2784 (0 == strcmpic(csp->http->gpc, "options")))
2786 assert(*(*header+12) == ':');
2787 if (1 == sscanf(*header+12, ": %u", &max_forwards))
2789 if (max_forwards > 0)
2791 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
2792 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
2793 csp->http->gpc, max_forwards);
2795 else if (max_forwards < 0)
2797 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2803 * Not supposed to be reached. direct_response() which
2804 * was already called earlier in chat() should have
2805 * intercepted the request.
2807 log_error(LOG_LEVEL_ERROR,
2808 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2809 assert(max_forwards != 0);
2814 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2823 /*********************************************************************
2825 * Function : client_host
2827 * Description : If the request URI did not contain host and
2828 * port information, parse and evaluate the Host
2831 * Also, kill ill-formed HOST: headers as sent by
2832 * Apple's iTunes software when used with a proxy.
2835 * 1 : csp = Current client state (buffers, headers, etc...)
2836 * 2 : header = On input, pointer to header to modify.
2837 * On output, pointer to the modified header, or NULL
2838 * to remove the header. This function frees the
2839 * original string if necessary.
2841 * Returns : JB_ERR_OK on success, or
2842 * JB_ERR_MEMORY on out-of-memory error.
2844 *********************************************************************/
2845 jb_err client_host(struct client_state *csp, char **header)
2850 * If the header field name is all upper-case, chances are that it's
2851 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2852 * not a problem -- they are regenerated later.
2854 if ((*header)[1] == 'O')
2856 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2861 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2862 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2865 if (NULL == (p = strdup((*header)+6)))
2867 return JB_ERR_MEMORY;
2870 if (NULL == (q = strdup(p)))
2873 return JB_ERR_MEMORY;
2876 freez(csp->http->hostport);
2877 csp->http->hostport = p;
2878 freez(csp->http->host);
2879 csp->http->host = q;
2880 q = strchr(csp->http->host, ':');
2883 /* Terminate hostname and evaluate port string */
2885 csp->http->port = atoi(q);
2889 csp->http->port = csp->http->ssl ? 443 : 80;
2892 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2893 csp->http->hostport, csp->http->host, csp->http->port);
2896 /* Signal client_host_adder() to return right away */
2897 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
2902 /*********************************************************************
2904 * Function : client_if_modified_since
2906 * Description : Remove or modify the If-Modified-Since header.
2909 * 1 : csp = Current client state (buffers, headers, etc...)
2910 * 2 : header = On input, pointer to header to modify.
2911 * On output, pointer to the modified header, or NULL
2912 * to remove the header. This function frees the
2913 * original string if necessary.
2915 * Returns : JB_ERR_OK on success, or
2916 * JB_ERR_MEMORY on out-of-memory error.
2918 *********************************************************************/
2919 jb_err client_if_modified_since(struct client_state *csp, char **header)
2922 #ifdef HAVE_GMTIME_R
2925 struct tm *timeptr = NULL;
2929 long int hours, minutes, seconds;
2933 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2936 * The client got an error message because of a temporary problem,
2937 * the problem is gone and the client now tries to revalidate our
2938 * error message on the real server. The revalidation would always
2939 * end with the transmission of the whole document and there is
2940 * no need to expose the bogus If-Modified-Since header.
2942 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2945 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2947 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2949 if ((0 == strcmpic(newval, "block")))
2951 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2954 else /* add random value */
2956 const char *header_time = *header + sizeof("If-Modified-Since:");
2958 if (JB_ERR_OK != parse_header_time(header_time, &tm))
2960 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2965 rtime = strtol(newval, &endptr, 0);
2968 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2969 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2976 rtime = pick_from_range(rtime);
2980 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2983 tm += rtime * (negative ? -1 : 1);
2984 #ifdef HAVE_GMTIME_R
2985 timeptr = gmtime_r(&tm, &gmt);
2986 #elif FEATURE_PTHREAD
2987 pthread_mutex_lock(&gmtime_mutex);
2988 timeptr = gmtime(&tm);
2989 pthread_mutex_unlock(&gmtime_mutex);
2991 timeptr = gmtime(&tm);
2993 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2996 *header = strdup("If-Modified-Since: ");
2997 string_append(header, newheader);
2999 if (*header == NULL)
3001 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3002 return JB_ERR_MEMORY;
3005 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3007 hours = rtime / 3600;
3008 minutes = rtime / 60 % 60;
3009 seconds = rtime % 60;
3011 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3012 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3013 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3022 /*********************************************************************
3024 * Function : client_if_none_match
3026 * Description : Remove the If-None-Match header.
3029 * 1 : csp = Current client state (buffers, headers, etc...)
3030 * 2 : header = On input, pointer to header to modify.
3031 * On output, pointer to the modified header, or NULL
3032 * to remove the header. This function frees the
3033 * original string if necessary.
3035 * Returns : JB_ERR_OK on success, or
3036 * JB_ERR_MEMORY on out-of-memory error.
3038 *********************************************************************/
3039 jb_err client_if_none_match(struct client_state *csp, char **header)
3041 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3043 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3050 /*********************************************************************
3052 * Function : client_x_filter
3054 * Description : Disables filtering if the client set "X-Filter: No".
3055 * Called from `sed'.
3058 * 1 : csp = Current client state (buffers, headers, etc...)
3059 * 2 : header = On input, pointer to header to modify.
3060 * On output, pointer to the modified header, or NULL
3061 * to remove the header. This function frees the
3062 * original string if necessary.
3064 * Returns : JB_ERR_OK on success
3066 *********************************************************************/
3067 jb_err client_x_filter(struct client_state *csp, char **header)
3069 if ( 0 == strcmpic(*header, "X-Filter: No"))
3071 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3073 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3077 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3079 log_error(LOG_LEVEL_HEADER,
3080 "force-text-mode overruled the client's request to fetch without filtering!");
3084 csp->content_type = CT_TABOO;
3085 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
3086 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
3087 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3089 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3096 /* the following functions add headers directly to the header list */
3098 /*********************************************************************
3100 * Function : client_host_adder
3102 * Description : Adds the Host: header field if it is missing.
3103 * Called from `sed'.
3106 * 1 : csp = Current client state (buffers, headers, etc...)
3108 * Returns : JB_ERR_OK on success, or
3109 * JB_ERR_MEMORY on out-of-memory error.
3111 *********************************************************************/
3112 jb_err client_host_adder(struct client_state *csp)
3117 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3119 /* Header already set by the client, nothing to do. */
3123 if ( !csp->http->hostport || !*(csp->http->hostport))
3125 /* XXX: When does this happen and why is it OK? */
3126 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3131 * remove 'user:pass@' from 'proto://user:pass@host'
3133 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3139 p = csp->http->hostport;
3142 /* XXX: Just add it, we already made sure that it will be unique */
3143 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3144 err = enlist_unique_header(csp->headers, "Host", p);
3150 /*********************************************************************
3152 * Function : client_cookie_adder
3154 * Description : Used in the add_client_headers list. Called from `sed'.
3156 * XXX: Remove csp->cookie_list which is no longer used.
3159 * 1 : csp = Current client state (buffers, headers, etc...)
3161 * Returns : JB_ERR_OK on success, or
3162 * JB_ERR_MEMORY on out-of-memory error.
3164 *********************************************************************/
3165 jb_err client_cookie_adder(struct client_state *csp)
3167 struct list_entry *lst;
3169 struct list_entry *list1 = csp->cookie_list->first;
3170 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
3171 int first_cookie = 1;
3174 if ((list1 == NULL) && (list2 == NULL))
3180 tmp = strdup("Cookie: ");
3182 for (lst = list1; lst ; lst = lst->next)
3190 string_append(&tmp, "; ");
3192 string_append(&tmp, lst->str);
3195 for (lst = list2; lst ; lst = lst->next)
3203 string_append(&tmp, "; ");
3205 string_join(&tmp, cookie_encode(lst->str));
3210 return JB_ERR_MEMORY;
3213 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3214 err = enlist(csp->headers, tmp);
3220 /*********************************************************************
3222 * Function : client_accept_encoding_adder
3224 * Description : Add an Accept-Encoding header to the client's request
3225 * that disables compression if the action applies, and
3226 * the header is not already there. Called from `sed'.
3227 * Note: For HTTP/1.0, the absence of the header is enough.
3230 * 1 : csp = Current client state (buffers, headers, etc...)
3232 * Returns : JB_ERR_OK on success, or
3233 * JB_ERR_MEMORY on out-of-memory error.
3235 *********************************************************************/
3236 jb_err client_accept_encoding_adder(struct client_state *csp)
3238 assert(0); /* Not in use */
3240 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3241 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3243 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3250 /*********************************************************************
3252 * Function : client_xtra_adder
3254 * Description : Used in the add_client_headers list. Called from `sed'.
3257 * 1 : csp = Current client state (buffers, headers, etc...)
3259 * Returns : JB_ERR_OK on success, or
3260 * JB_ERR_MEMORY on out-of-memory error.
3262 *********************************************************************/
3263 jb_err client_xtra_adder(struct client_state *csp)
3265 struct list_entry *lst;
3268 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3269 lst ; lst = lst->next)
3271 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3272 err = enlist(csp->headers, lst->str);
3284 /*********************************************************************
3286 * Function : client_x_forwarded_adder
3288 * Description : Used in the add_client_headers list. Called from `sed'.
3291 * 1 : csp = Current client state (buffers, headers, etc...)
3293 * Returns : JB_ERR_OK on success, or
3294 * JB_ERR_MEMORY on out-of-memory error.
3296 *********************************************************************/
3297 jb_err client_x_forwarded_adder(struct client_state *csp)
3302 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3307 if (csp->x_forwarded)
3309 p = strdup(csp->x_forwarded);
3310 string_append(&p, ", ");
3314 p = strdup("X-Forwarded-For: ");
3316 string_append(&p, csp->ip_addr_str);
3320 return JB_ERR_MEMORY;
3323 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3324 err = enlist(csp->headers, p);
3331 /*********************************************************************
3333 * Function : connection_close_adder
3335 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3336 * support. Adds a "Connection: close" header to csp->headers
3337 * unless the header was already present. Called from `sed'.
3339 * FIXME: This whole function shouldn't be neccessary!
3342 * 1 : csp = Current client state (buffers, headers, etc...)
3344 * Returns : JB_ERR_OK on success, or
3345 * JB_ERR_MEMORY on out-of-memory error.
3347 *********************************************************************/
3348 jb_err connection_close_adder(struct client_state *csp)
3350 const unsigned int flags = csp->flags;
3353 * Return right away if
3355 * - we're parsing server headers and the server header
3356 * "Connection: close" is already set, or if
3358 * - we're parsing client headers and the client header
3359 * "Connection: close" is already set.
3361 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3362 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3363 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3364 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3369 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3371 return enlist(csp->headers, "Connection: close");
3375 /*********************************************************************
3377 * Function : server_http
3379 * Description : - Save the HTTP Status into csp->http->status
3380 * - Set CT_TABOO to prevent filtering if the answer
3381 * is a partial range (HTTP status 206)
3382 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3386 * 1 : csp = Current client state (buffers, headers, etc...)
3387 * 2 : header = On input, pointer to header to modify.
3388 * On output, pointer to the modified header, or NULL
3389 * to remove the header. This function frees the
3390 * original string if necessary.
3392 * Returns : JB_ERR_OK on success, or
3393 * JB_ERR_MEMORY on out-of-memory error.
3395 *********************************************************************/
3396 jb_err server_http(struct client_state *csp, char **header)
3398 /* Signal that were now parsing server headers. */
3399 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
3401 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3402 if (csp->http->status == 206)
3404 csp->content_type = CT_TABOO;
3407 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3410 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3417 /*********************************************************************
3419 * Function : server_set_cookie
3421 * Description : Handle the server "cookie" header properly.
3422 * Log cookie to the jar file. Then "crunch",
3423 * accept or rewrite it to a session cookie.
3424 * Called from `sed'.
3426 * TODO: Allow the user to specify a new expiration
3427 * time to cause the cookie to expire even before the
3428 * browser is closed.
3431 * 1 : csp = Current client state (buffers, headers, etc...)
3432 * 2 : header = On input, pointer to header to modify.
3433 * On output, pointer to the modified header, or NULL
3434 * to remove the header. This function frees the
3435 * original string if necessary.
3437 * Returns : JB_ERR_OK on success, or
3438 * JB_ERR_MEMORY on out-of-memory error.
3440 *********************************************************************/
3441 jb_err server_set_cookie(struct client_state *csp, char **header)
3448 #ifdef FEATURE_COOKIE_JAR
3449 if (csp->config->jar)
3452 * Write timestamp into outbuf.
3454 * Complex because not all OSs have tm_gmtoff or
3455 * the %z field in strftime()
3457 char tempbuf[ BUFFER_SIZE ];
3459 #ifdef HAVE_LOCALTIME_R
3460 tm_now = *localtime_r(&now, &tm_now);
3461 #elif FEATURE_PTHREAD
3462 pthread_mutex_lock(&localtime_mutex);
3463 tm_now = *localtime (&now);
3464 pthread_mutex_unlock(&localtime_mutex);
3466 tm_now = *localtime (&now);
3468 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3470 /* strlen("set-cookie: ") = 12 */
3471 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3473 #endif /* def FEATURE_COOKIE_JAR */
3475 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3477 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3480 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3482 /* Flag whether or not to log a message */
3485 /* A variable to store the tag we're working on */
3488 /* Skip "Set-Cookie:" (11 characters) in header */
3489 cur_tag = *header + 11;
3491 /* skip whitespace between "Set-Cookie:" and value */
3492 while (*cur_tag && ijb_isspace(*cur_tag))
3497 /* Loop through each tag in the cookie */
3501 char *next_tag = strchr(cur_tag, ';');
3502 if (next_tag != NULL)
3504 /* Skip the ';' character itself */
3507 /* skip whitespace ";" and start of tag */
3508 while (*next_tag && ijb_isspace(*next_tag))
3515 /* "Next tag" is the end of the string */
3516 next_tag = cur_tag + strlen(cur_tag);
3520 * Check the expiration date to see
3521 * if the cookie is still valid, if yes,
3522 * rewrite it to a session cookie.
3524 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3526 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3528 /* Did we detect the date properly? */
3529 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3532 * Nope, treat it as if it was still valid.
3534 * XXX: Should we remove the whole cookie instead?
3536 log_error(LOG_LEVEL_ERROR,
3537 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3538 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3544 * Yes. Check if the cookie is still valid.
3546 * If the cookie is already expired it's probably
3547 * a delete cookie and even if it isn't, the browser
3548 * will discard it anyway.
3552 * XXX: timegm() isn't available on some AmigaOS
3553 * versions and our replacement doesn't work.
3555 * Our options are to either:
3557 * - disable session-cookies-only completely if timegm
3560 * - to simply remove all expired tags, like it has
3561 * been done until Privoxy 3.0.6 and to live with
3562 * the consequence that it can cause login/logout
3563 * problems on servers that don't validate their
3564 * input properly, or
3566 * - to replace it with mktime in which
3567 * case there is a slight chance of valid cookies
3568 * passing as already expired.
3570 * This is the way it's currently done and it's not
3571 * as bad as it sounds. If the missing GMT offset is
3572 * enough to change the result of the expiration check
3573 * the cookie will be only valid for a few hours
3574 * anyway, which in many cases will be shorter
3575 * than a browser session.
3577 if (cookie_time - now < 0)
3579 log_error(LOG_LEVEL_HEADER,
3580 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3581 /* Just in case some clown sets more then one expiration date */
3587 * Still valid, delete expiration date by copying
3588 * the rest of the string over it.
3590 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3591 * since the behaviour of strcpy is undefined for overlapping
3594 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3596 /* That changed the header, need to issue a log message */
3600 * Note that the next tag has now been moved to *cur_tag,
3601 * so we do not need to update the cur_tag pointer.
3609 /* Move on to next cookie tag */
3616 assert(NULL != *header);
3617 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3626 #ifdef FEATURE_FORCE_LOAD
3627 /*********************************************************************
3629 * Function : strclean
3631 * Description : In-Situ-Eliminate all occurances of substring in
3635 * 1 : string = string to clean
3636 * 2 : substring = substring to eliminate
3638 * Returns : Number of eliminations
3640 *********************************************************************/
3641 int strclean(const char *string, const char *substring)
3647 len = strlen(substring);
3649 while((pos = strstr(string, substring)) != NULL)
3656 while (*p++ != '\0');
3663 #endif /* def FEATURE_FORCE_LOAD */
3665 /*********************************************************************
3667 * Function : parse_header_time
3669 * Description : Parses time formats used in HTTP header strings
3670 * to get the numerical respresentation.
3673 * 1 : header_time = HTTP header time as string.
3674 * 2 : result = storage for header_time in seconds
3676 * Returns : JB_ERR_OK if the time format was recognized, or
3677 * JB_ERR_PARSE otherwise.
3679 *********************************************************************/
3680 jb_err parse_header_time(const char *header_time, time_t *result)
3685 * Zero out gmt to prevent time zone offsets.
3687 * While this is only necessary on some platforms
3688 * (mingw32 for example), I don't know how to
3689 * detect these automatically and doing it everywhere
3692 memset(&gmt, 0, sizeof(gmt));
3694 /* Tue, 02 Jun 2037 20:00:00 */
3695 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3696 /* Tue, 02-Jun-2037 20:00:00 */
3697 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3698 /* Tue, 02-Jun-37 20:00:00 */
3699 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3700 /* Tuesday, 02-Jun-2037 20:00:00 */
3701 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3702 /* Tuesday Jun 02 20:00:00 2037 */
3703 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3705 return JB_ERR_PARSE;
3708 *result = timegm(&gmt);
3714 /*********************************************************************
3716 * Function : get_destination_from_headers
3718 * Description : Parse the "Host:" header to get the request's destination.
3719 * Only needed if the client's request was forcefully
3720 * redirected into Privoxy.
3722 * Code mainly copied from client_host() which is currently
3723 * run too late for this purpose.
3726 * 1 : headers = List of headers (one of them hopefully being
3727 * the "Host:" header)
3728 * 2 : http = storage for the result (host, port and hostport).
3730 * Returns : JB_ERR_MEMORY in case of memory problems,
3731 * JB_ERR_PARSE if the host header couldn't be found,
3732 * JB_ERR_OK otherwise.
3734 *********************************************************************/
3735 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3741 host = get_header_value(headers, "Host:");
3745 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3746 return JB_ERR_PARSE;
3749 if (NULL == (p = strdup((host))))
3751 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3752 return JB_ERR_MEMORY;
3755 if (NULL == (q = strdup(p)))
3758 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3759 return JB_ERR_MEMORY;
3762 freez(http->hostport);
3766 q = strchr(http->host, ':');
3769 /* Terminate hostname and evaluate port string */
3771 http->port = atoi(q);
3775 http->port = http->ssl ? 443 : 80;
3778 /* Rebuild request URL */
3780 http->url = strdup(http->ssl ? "https://" : "http://");
3781 string_append(&http->url, http->hostport);
3782 string_append(&http->url, http->path);
3783 if (http->url == NULL)
3785 return JB_ERR_MEMORY;
3788 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",