1 const char parsers_rcs[] = "$Id: parsers.c,v 1.88 2007/02/07 11:27:12 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_server_header'
14 * `filter_client_header', `filter_header', `crunch_server_header',
15 * `server_content_encoding', `server_content_disposition',
16 * `server_last_modified', `client_accept_language',
17 * `crunch_client_header', `client_if_modified_since',
18 * `client_if_none_match', `get_destination_from_headers',
19 * `parse_header_time' and `server_set_cookie'.
21 * Copyright : Written by and Copyright (C) 2001-2007 the SourceForge
22 * Privoxy team. http://www.privoxy.org/
24 * Based on the Internet Junkbuster originally written
25 * by and Copyright (C) 1997 Anonymous Coders and
26 * Junkbusters Corporation. http://www.junkbusters.com
28 * This program is free software; you can redistribute it
29 * and/or modify it under the terms of the GNU General
30 * Public License as published by the Free Software
31 * Foundation; either version 2 of the License, or (at
32 * your option) any later version.
34 * This program is distributed in the hope that it will
35 * be useful, but WITHOUT ANY WARRANTY; without even the
36 * implied warranty of MERCHANTABILITY or FITNESS FOR A
37 * PARTICULAR PURPOSE. See the GNU General Public
38 * License for more details.
40 * The GNU General Public License should be included with
41 * this file. If not, you can view it at
42 * http://www.gnu.org/copyleft/gpl.html
43 * or write to the Free Software Foundation, Inc., 59
44 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
48 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
49 * - Let decompress_iob()
50 * - not corrupt the content if decompression fails
51 * early. (the first byte(s) were lost).
52 * - use pointer arithmetics with defined outcome for
54 * - Use a different kludge to remember a failed decompression.
56 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
57 * Search for Max-Forwards headers case-insensitive,
58 * don't generate the "501 unsupported" message for invalid
59 * Max-Forwards values and don't increase negative ones.
61 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
62 * - Let server_set_cookie() check the expiration date
63 * of cookies and don't touch the ones that are already
64 * expired. Fixes problems with low quality web applications
65 * as described in BR 932612.
67 * - Adjust comment in client_max_forwards to reality;
68 * remove invalid Max-Forwards headers.
70 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
71 * Stop filter_header() from unintentionally removing
72 * empty header lines that were enlisted by the continue
75 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
76 * - Repeat the request URL before logging any headers.
77 * Makes reading the log easier in case of simultaneous requests.
78 * - If there are more than one Content-Type headers in one request,
79 * use the first one and remove the others.
80 * - Remove "newval" variable in server_content_type().
81 * It's only used once.
83 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
84 * Correct a cast, check inflateEnd() exit code
85 * to see if we have to, replace sprintf calls
88 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
89 * Integrate a modified version of Wil Mahan's
90 * zlib patch (PR #895531).
92 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
93 * Skip empty filter files in filter_header()
94 * but don't ignore the ones that come afterwards.
95 * Fixes BR 1619208, this time for real.
97 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
98 * Reverted parts of my last commit
99 * to keep error handling working.
101 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
102 * Fixed gcc43 conversion warnings.
104 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
105 * Bringing back the "useless" localtime() call
106 * I removed in revision 1.67. On some platforms
107 * it's necessary to prevent time zone offsets.
109 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
110 * Rebuild request URL in get_destination_from_headers()
111 * to make sure redirect{pcrs command} works as expected
112 * for intercepted requests.
114 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
115 * Added get_destination_from_headers().
117 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
118 * Make pthread mutex locking more generic. Instead of
119 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
120 * and use mutex locking unless there is an _r function
121 * available. Better safe than sorry.
123 * Fixes "./configure --disable-pthread" and should result
124 * in less threading-related problems on pthread-using platforms,
125 * but it still doesn't fix BR#1122404.
127 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
128 * The special header "X-Filter: No" now disables
129 * header filtering as well.
131 * Revision 1.73 2006/09/23 13:26:38 roro
132 * Replace TABs by spaces in source code.
134 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
135 * Don't print a log message every time filter_headers is
136 * entered or left. It only creates noise without any real
139 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
140 * Fix +hide-if-modified-since{-n}.
142 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
143 * Have hide-if-modified-since interpret the random
144 * range value as minutes instead of hours. Allows
145 * more fine-grained configuration.
147 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
148 * Always have parse_header_time return a pointer
149 * that actual makes sense, even though we currently
150 * only need it to detect problems.
152 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
153 * Added config option enable-remote-http-toggle
154 * to specify if Privoxy should recognize special
155 * headers (currently only X-Filter) to change its
156 * behaviour. Disabled by default.
158 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
159 * After filtering de-chunked instances, remove
160 * "Transfer-Encoding" header entirely instead of changing
161 * it to "Transfer-Encoding: identity", which is invalid.
162 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
164 * Don't use localtime in parse_header_time. An empty time struct
165 * is good enough, it gets overwritten by strptime anyway.
167 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
168 * Use gmtime_r if available, fallback to gmtime with mutex
169 * protection for MacOSX and use vanilla gmtime for the rest.
171 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
172 * Changed client_referrer to use the right type (size_t) for
173 * hostlenght and to shorten the temporary referrer string with
174 * '\0' instead of adding a useless line break.
176 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
177 * - Back to timegm() using GnuPG's replacement if necessary.
178 * Using mktime() and localtime() could add a on hour offset if
179 * the randomize factor was big enough to lead to a summer/wintertime
182 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
184 * - Moved randomization code into pick_from_range().
186 * - Changed parse_header_time definition.
187 * time_t isn't guaranteed to be signed and
188 * if it isn't, -1 isn't available as error code.
189 * Changed some variable types in client_if_modified_since()
190 * because of the same reason.
192 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
193 * OS/2 compilation compatibility fixups
195 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
196 * Changed include from strptime.c to strptime.h
198 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
199 * Split filter-headers{} into filter-client-headers{}
200 * and filter-server-headers{}.
201 * Added parse_header_time() to share some code.
202 * Replaced timegm() with mktime().
204 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
205 * Windows service integration
207 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
208 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
210 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
211 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
212 * with what was really the latest development (the v_3_0_branch branch)
214 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
215 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
217 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
218 * Add the ability to check jpeg images for invalid
219 * lengths of comment blocks. Defensive strategy
220 * against the exploit:
221 * Microsoft Security Bulletin MS04-028
222 * Buffer Overrun in JPEG Processing (GDI+) Could
223 * Allow Code Execution (833987)
224 * Enabled with +inspect-jpegs in actions files.
226 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
227 * Excluded text/plain objects from filtering. This fixes a
228 * couple of client-crashing, download corruption and
229 * Privoxy performance issues, whose root cause lies in
230 * web servers labelling content of unknown type as text/plain.
232 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
233 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
235 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
236 * Completing the previous change
238 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
239 * Added temporary workaround for bug in PHP < 4.2.3
241 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
242 * 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.
244 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
245 * Fix typo: supressed -> suppressed
247 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
248 * Improved cookie logging
250 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
251 * Added basic support for OPTIONS and TRACE HTTP methods:
252 * - New parser function client_max_forwards which decrements
253 * the Max-Forwards HTTP header field of OPTIONS and TRACE
254 * requests by one before forwarding
255 * - New parser function client_host which extracts the host
256 * and port information from the HTTP header field if the
257 * request URI was not absolute
258 * - Don't crumble and re-add the Host: header, but only generate
259 * and append if missing
261 * Revision 1.56 2002/05/12 15:34:22 jongfoster
262 * Fixing typo in a comment
264 * Revision 1.55 2002/05/08 16:01:07 oes
265 * Optimized add_to_iob:
266 * - Use realloc instead of malloc(), memcpy(), free()
267 * - Expand to powers of two if possible, to get
268 * O(log n) reallocs instead of O(n).
269 * - Moved check for buffer limit here from chat
270 * - Report failure via returncode
272 * Revision 1.54 2002/04/02 15:03:16 oes
273 * Tiny code cosmetics
275 * Revision 1.53 2002/03/26 22:29:55 swa
276 * we have a new homepage!
278 * Revision 1.52 2002/03/24 13:25:43 swa
279 * name change related issues
281 * Revision 1.51 2002/03/13 00:27:05 jongfoster
284 * Revision 1.50 2002/03/12 01:45:35 oes
285 * More verbose logging
287 * Revision 1.49 2002/03/09 20:03:52 jongfoster
288 * - Making various functions return int rather than size_t.
289 * (Undoing a recent change). Since size_t is unsigned on
290 * Windows, functions like read_socket that return -1 on
291 * error cannot return a size_t.
293 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
294 * crashes, and also frequently caused JB to jump to 100%
295 * CPU and stay there. (Because it thought it had just
296 * read ((unsigned)-1) == 4Gb of data...)
298 * - The signature of write_socket has changed, it now simply
299 * returns success=0/failure=nonzero.
301 * - Trying to get rid of a few warnings --with-debug on
302 * Windows, I've introduced a new type "jb_socket". This is
303 * used for the socket file descriptors. On Windows, this
304 * is SOCKET (a typedef for unsigned). Everywhere else, it's
305 * an int. The error value can't be -1 any more, so it's
306 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
307 * Windows it maps to the #define INVALID_SOCKET.)
309 * - The signature of bind_port has changed.
311 * Revision 1.48 2002/03/07 03:46:53 oes
312 * Fixed compiler warnings etc
314 * Revision 1.47 2002/02/20 23:15:13 jongfoster
315 * Parsing functions now handle out-of-memory gracefully by returning
318 * Revision 1.46 2002/01/17 21:03:47 jongfoster
319 * Moving all our URL and URL pattern parsing code to urlmatch.c.
321 * Revision 1.45 2002/01/09 14:33:03 oes
322 * Added support for localtime_r.
324 * Revision 1.44 2001/12/14 01:22:54 steudten
325 * Remove 'user:pass@' from 'proto://user:pass@host' for the
326 * new added header 'Host: ..'. (See Req ID 491818)
328 * Revision 1.43 2001/11/23 00:26:38 jongfoster
329 * Fixing two really stupid errors in my previous commit
331 * Revision 1.42 2001/11/22 21:59:30 jongfoster
332 * Adding code to handle +no-cookies-keep
334 * Revision 1.41 2001/11/05 23:43:05 steudten
335 * Add time+date to log files.
337 * Revision 1.40 2001/10/26 20:13:09 jongfoster
338 * ctype.h is needed in Windows, too.
340 * Revision 1.39 2001/10/26 17:40:04 oes
341 * Introduced get_header_value()
342 * Removed http->user_agent, csp->referrer and csp->accept_types
343 * Removed client_accept()
345 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
346 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
347 * threads to call select() simultaneously. So, it's time to do a real, live,
348 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
349 * (native). Both versions will work, but using __OS2__ offers multi-threading.
351 * Revision 1.37 2001/10/23 21:36:02 jongfoster
352 * Documenting sed()'s error behaviou (doc change only)
354 * Revision 1.36 2001/10/13 12:51:51 joergs
355 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
356 * force-load), instead crumble Host: and add it (again) in client_host_adder
357 * (in case we get a HTTP/1.0 request without Host: header and forward it to
358 * a HTTP/1.1 server/proxy).
360 * Revision 1.35 2001/10/09 22:39:21 jongfoster
361 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
364 * Revision 1.34 2001/10/07 18:50:55 oes
365 * Added server_content_encoding, renamed server_transfer_encoding
367 * Revision 1.33 2001/10/07 18:04:49 oes
368 * Changed server_http11 to server_http and its pattern to "HTTP".
369 * Additional functionality: it now saves the HTTP status into
370 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
372 * Revision 1.32 2001/10/07 15:43:28 oes
373 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
374 * client_te and client_accept_encoding_adder, triggered by the new
375 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
376 * changed to allow only identity and chunked, and the TE header is
377 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
379 * parse_http_request no longer does anything than parsing. The rewriting
380 * of http->cmd and version mangling are gone. It now also recognizes
381 * the put and delete methods and saves the url in http->url. Removed
384 * renamed content_type and content_length to have the server_ prefix
386 * server_content_type now only works if csp->content_type != CT_TABOO
388 * added server_transfer_encoding, which
389 * - Sets CT_TABOO to prohibit filtering if encoding compresses
390 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
391 * - Change from "chunked" to "identity" if body was chunked
392 * but has been de-chunked for filtering.
394 * added server_content_md5 which crunches any Content-MD5 headers
395 * if the body was modified.
397 * made server_http11 conditional on +downgrade action
399 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
401 * Revision 1.31 2001/10/05 14:25:02 oes
402 * Crumble Keep-Alive from Server
404 * Revision 1.30 2001/09/29 12:56:03 joergs
405 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
407 * Revision 1.29 2001/09/24 21:09:24 jongfoster
408 * Fixing 2 memory leaks that Guy spotted, where the paramater to
409 * enlist() was not being free()d.
411 * Revision 1.28 2001/09/22 16:32:28 jongfoster
412 * Removing unused #includes.
414 * Revision 1.27 2001/09/20 15:45:25 steudten
416 * add casting from size_t to int for printf()
417 * remove local variable shadow s2
419 * Revision 1.26 2001/09/16 17:05:14 jongfoster
420 * Removing unused #include showarg.h
422 * Revision 1.25 2001/09/16 13:21:27 jongfoster
423 * Changes to use new list functions.
425 * Revision 1.24 2001/09/13 23:05:50 jongfoster
426 * Changing the string paramater to the header parsers a "const".
428 * Revision 1.23 2001/09/12 18:08:19 steudten
430 * In parse_http_request() header rewriting miss the host value, so
431 * from http://www.mydomain.com the result was just " / " not
432 * http://www.mydomain.com/ in case we forward.
434 * Revision 1.22 2001/09/10 10:58:53 oes
435 * Silenced compiler warnings
437 * Revision 1.21 2001/07/31 14:46:00 oes
438 * - Persistant connections now suppressed
439 * - sed() no longer appends empty header to csp->headers
441 * Revision 1.20 2001/07/30 22:08:36 jongfoster
442 * Tidying up #defines:
443 * - All feature #defines are now of the form FEATURE_xxx
444 * - Permanently turned off WIN_GUI_EDIT
445 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
447 * Revision 1.19 2001/07/25 17:21:54 oes
448 * client_uagent now saves copy of User-Agent: header value
450 * Revision 1.18 2001/07/13 14:02:46 oes
451 * - Included fix to repair broken HTTP requests that
452 * don't contain a path, not even '/'.
453 * - Removed all #ifdef PCRS
454 * - content_type now always inspected and classified as
455 * text, gif or other.
456 * - formatting / comments
458 * Revision 1.17 2001/06/29 21:45:41 oes
459 * Indentation, CRLF->LF, Tab-> Space
461 * Revision 1.16 2001/06/29 13:32:42 oes
463 * - Adapted free_http_request
464 * - Removed logentry from cancelled commit
466 * Revision 1.15 2001/06/03 19:12:38 oes
467 * deleted const struct interceptors
469 * Revision 1.14 2001/06/01 18:49:17 jongfoster
470 * Replaced "list_share" with "list" - the tiny memory gain was not
471 * worth the extra complexity.
473 * Revision 1.13 2001/05/31 21:30:33 jongfoster
474 * Removed list code - it's now in list.[ch]
475 * Renamed "permission" to "action", and changed many features
476 * to use the actions file rather than the global config.
478 * Revision 1.12 2001/05/31 17:33:13 oes
482 * Revision 1.11 2001/05/29 20:11:19 joergs
483 * '/ * inside comment' warning removed.
485 * Revision 1.10 2001/05/29 09:50:24 jongfoster
486 * Unified blocklist/imagelist/permissionslist.
487 * File format is still under discussion, but the internal changes
490 * Also modified interceptor behaviour:
491 * - We now intercept all URLs beginning with one of the following
492 * prefixes (and *only* these prefixes):
494 * * http://ijbswa.sf.net/config/
495 * * http://ijbswa.sourceforge.net/config/
496 * - New interceptors "home page" - go to http://i.j.b/ to see it.
497 * - Internal changes so that intercepted and fast redirect pages
498 * are not replaced with an image.
499 * - Interceptors now have the option to send a binary page direct
500 * to the client. (i.e. ijb-send-banner uses this)
501 * - Implemented show-url-info interceptor. (Which is why I needed
502 * the above interceptors changes - a typical URL is
503 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
504 * The previous mechanism would not have intercepted that, and
505 * if it had been intercepted then it then it would have replaced
508 * Revision 1.9 2001/05/28 17:26:33 jongfoster
509 * Fixing segfault if last header was crunched.
510 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
511 * can use the cross-platform sprintf() instead.)
513 * Revision 1.8 2001/05/27 22:17:04 oes
515 * - re_process_buffer no longer writes the modified buffer
516 * to the client, which was very ugly. It now returns the
517 * buffer, which it is then written by chat.
519 * - content_length now adjusts the Content-Length: header
520 * for modified documents rather than crunch()ing it.
521 * (Length info in csp->content_length, which is 0 for
522 * unmodified documents)
524 * - For this to work, sed() is called twice when filtering.
526 * Revision 1.7 2001/05/27 13:19:06 oes
527 * Patched Joergs solution for the content-length in.
529 * Revision 1.6 2001/05/26 13:39:32 jongfoster
530 * Only crunches Content-Length header if applying RE filtering.
531 * Without this fix, Microsoft Windows Update wouldn't work.
533 * Revision 1.5 2001/05/26 00:28:36 jongfoster
534 * Automatic reloading of config file.
535 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
536 * Most of the global variables have been moved to a new
537 * struct configuration_spec, accessed through csp->config->globalname
538 * Most of the globals remaining are used by the Win32 GUI.
540 * Revision 1.4 2001/05/22 18:46:04 oes
542 * - Enabled filtering banners by size rather than URL
543 * by adding patterns that replace all standard banner
544 * sizes with the "Junkbuster" gif to the re_filterfile
546 * - Enabled filtering WebBugs by providing a pattern
547 * which kills all 1x1 images
549 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
550 * which is selected by the (nonstandard and therefore
551 * capital) letter 'U' in the option string.
552 * It causes the quantifiers to be ungreedy by default.
553 * Appending a ? turns back to greedy (!).
555 * - Added a new interceptor ijb-send-banner, which
556 * sends back the "Junkbuster" gif. Without imagelist or
557 * MSIE detection support, or if tinygif = 1, or the
558 * URL isn't recognized as an imageurl, a lame HTML
559 * explanation is sent instead.
561 * - Added new feature, which permits blocking remote
562 * script redirects and firing back a local redirect
564 * The feature is conditionally compiled, i.e. it
565 * can be disabled with --disable-fast-redirects,
566 * plus it must be activated by a "fast-redirects"
567 * line in the config file, has its own log level
568 * and of course wants to be displayed by show-proxy-args
569 * Note: Boy, all the #ifdefs in 1001 locations and
570 * all the fumbling with configure.in and acconfig.h
571 * were *way* more work than the feature itself :-(
573 * - Because a generic redirect template was needed for
574 * this, tinygif = 3 now uses the same.
576 * - Moved GIFs, and other static HTTP response templates
581 * - Removed some >400 CRs again (Jon, you really worked
584 * Revision 1.3 2001/05/20 01:21:20 jongfoster
585 * Version 2.9.4 checkin.
586 * - Merged popupfile and cookiefile, and added control over PCRS
587 * filtering, in new "permissionsfile".
588 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
589 * file error you now get a message box (in the Win32 GUI) rather
590 * than the program exiting with no explanation.
591 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
593 * - Removed tabs from "config"
594 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
595 * - Bumped up version number.
597 * Revision 1.2 2001/05/17 23:02:36 oes
598 * - Made referrer option accept 'L' as a substitute for '§'
600 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
601 * Initial import of version 2.9.3 source tree
604 *********************************************************************/
611 #include <sys/types.h>
624 #if !defined(_WIN32) && !defined(__OS2__)
630 #ifdef FEATURE_PTHREAD
632 /* jcc.h is for mutex semapores only */
633 #endif /* def FEATURE_PTHREAD */
639 #include "jbsockets.h"
640 #include "miscutil.h"
643 #ifndef HAVE_STRPTIME
644 #include "strptime.h"
647 const char parsers_h_rcs[] = PARSERS_H_VERSION;
649 /* Fix a problem with Solaris. There should be no effect on other
651 * Solaris's isspace() is a macro which uses it's argument directly
652 * as an array index. Therefore we need to make sure that high-bit
653 * characters generate +ve values, and ideally we also want to make
654 * the argument match the declared parameter type of "int".
656 * Why did they write a character function that can't take a simple
657 * "char" argument? Doh!
659 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
660 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
663 const struct parsers client_patterns[] = {
664 { "referer:", 8, client_referrer },
665 { "user-agent:", 11, client_uagent },
666 { "ua-", 3, client_ua },
667 { "from:", 5, client_from },
668 { "cookie:", 7, client_send_cookie },
669 { "x-forwarded-for:", 16, client_x_forwarded },
670 { "Accept-Encoding:", 16, client_accept_encoding },
671 { "TE:", 3, client_te },
672 { "Host:", 5, client_host },
673 { "if-modified-since:", 18, client_if_modified_since },
674 { "Keep-Alive:", 11, crumble },
675 { "connection:", 11, crumble },
676 { "proxy-connection:", 17, crumble },
677 { "max-forwards:", 13, client_max_forwards },
678 { "Accept-Language:", 16, client_accept_language },
679 { "if-none-match:", 14, client_if_none_match },
680 { "X-Filter:", 9, client_x_filter },
681 { "*", 0, crunch_client_header },
682 { "*", 0, filter_client_header },
686 const struct parsers server_patterns[] = {
687 { "HTTP", 4, server_http },
688 { "set-cookie:", 11, server_set_cookie },
689 { "connection:", 11, crumble },
690 { "Content-Type:", 13, server_content_type },
691 { "Content-Length:", 15, server_content_length },
692 { "Content-MD5:", 12, server_content_md5 },
693 { "Content-Encoding:", 17, server_content_encoding },
694 { "Transfer-Encoding:", 18, server_transfer_coding },
695 { "Keep-Alive:", 11, crumble },
696 { "content-disposition:", 20, server_content_disposition },
697 { "Last-Modified:", 14, server_last_modified },
698 { "*", 0, crunch_server_header },
699 { "*", 0, filter_server_header },
703 const struct parsers server_patterns_light[] = {
704 { "Content-Length:", 15, server_content_length },
705 { "Transfer-Encoding:", 18, server_transfer_coding },
707 { "Content-Encoding:", 17, server_content_encoding },
708 #endif /* def FEATURE_ZLIB */
712 const add_header_func_ptr add_client_headers[] = {
715 client_x_forwarded_adder,
717 /* Temporarily disabled: client_accept_encoding_adder, */
718 connection_close_adder,
723 const add_header_func_ptr add_server_headers[] = {
724 connection_close_adder,
728 /*********************************************************************
730 * Function : flush_socket
732 * Description : Write any pending "buffered" content.
735 * 1 : fd = file descriptor of the socket to read
736 * 2 : csp = Current client state (buffers, headers, etc...)
738 * Returns : On success, the number of bytes written are returned (zero
739 * indicates nothing was written). On error, -1 is returned,
740 * and errno is set appropriately. If count is zero and the
741 * file descriptor refers to a regular file, 0 will be
742 * returned without causing any other effect. For a special
743 * file, the results are not portable.
745 *********************************************************************/
746 int flush_socket(jb_socket fd, struct client_state *csp)
748 struct iob *iob = csp->iob;
749 int len = iob->eod - iob->cur;
756 if (write_socket(fd, iob->cur, (size_t)len))
760 iob->eod = iob->cur = iob->buf;
766 /*********************************************************************
768 * Function : add_to_iob
770 * Description : Add content to the buffered page, expanding the
771 * buffer if necessary.
774 * 1 : csp = Current client state (buffers, headers, etc...)
775 * 2 : buf = holds the content to be added to the page
776 * 3 : n = number of bytes to be added
778 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
779 * or buffer limit reached.
781 *********************************************************************/
782 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
784 struct iob *iob = csp->iob;
785 size_t used, offset, need, want;
788 if (n <= 0) return JB_ERR_OK;
790 used = (size_t)(iob->eod - iob->buf);
791 offset = (size_t)(iob->cur - iob->buf);
792 need = used + (size_t)n + 1;
795 * If the buffer can't hold the new data, extend it first.
796 * Use the next power of two if possible, else use the actual need.
798 if (need > csp->config->buffer_limit)
800 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
801 return JB_ERR_MEMORY;
804 if (need > iob->size)
806 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
808 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
812 else if (NULL != (p = (char *)realloc(iob->buf, need)))
818 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
819 return JB_ERR_MEMORY;
822 /* Update the iob pointers */
823 iob->cur = p + offset;
828 /* copy the new data into the iob buffer */
829 memcpy(iob->eod, buf, (size_t)n);
831 /* point to the end of the data */
834 /* null terminate == cheap insurance */
843 /*********************************************************************
845 * Function : decompress_iob
847 * Description : Decompress buffered page, expanding the
848 * buffer as necessary. csp->iob->cur
849 * should point to the the beginning of the
850 * compressed data block.
853 * 1 : csp = Current client state (buffers, headers, etc...)
855 * Returns : JB_ERR_OK on success,
856 * JB_ERR_MEMORY if out-of-memory limit reached, and
857 * JB_ERR_COMPRESS if error decompressing buffer.
859 *********************************************************************/
860 jb_err decompress_iob(struct client_state *csp)
862 char *buf; /* new, uncompressed buffer */
863 char *cur; /* Current iob position (to keep the original
864 * iob->cur unmodified if we return early) */
865 size_t bufsize; /* allocated size of the new buffer */
866 size_t skip_size; /* Number of bytes at the beginning of the iob
867 that we should NOT decompress. */
868 int status; /* return status of the inflate() call */
869 z_stream zstr; /* used by calls to zlib */
871 bufsize = csp->iob->size;
872 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
879 * This is to protect the parsing of gzipped data,
880 * but it should(?) be valid for deflated data also.
882 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
883 return JB_ERR_COMPRESS;
886 if (csp->content_type & CT_GZIP)
889 * Our task is slightly complicated by the facts that data
890 * compressed by gzip does not include a zlib header, and
891 * that there is no easily accessible interface in zlib to
892 * handle a gzip header. We strip off the gzip header by
893 * hand, and later inform zlib not to expect a header.
897 * Strip off the gzip header. Please see RFC 1952 for more
898 * explanation of the appropriate fields.
900 if ((*cur++ != (char)0x1f)
901 || (*cur++ != (char)0x8b)
902 || (*cur++ != Z_DEFLATED))
904 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
905 return JB_ERR_COMPRESS;
911 * XXX: These magic numbers should be replaced
912 * with macros to give a better idea what they do.
916 /* The gzip header has reserved bits set; bail out. */
917 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
918 return JB_ERR_COMPRESS;
922 /* Skip extra fields if necessary. */
926 * Skip a given number of bytes, specified
927 * as a 16-bit little-endian value.
930 * XXX: This code used to be:
932 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
934 * which I had to change into:
936 * cur += *cur++ + (*cur++ << 8);
938 * at which point gcc43 finally noticed that the value
939 * of cur is undefined (it depends on which of the
940 * summands is evaluated first).
942 * I haven't come across a site where this
943 * code is actually executed yet, but I hope
948 skip_bytes = *cur++ << 8;
950 assert(skip_bytes == *csp->iob->cur-2 + ((*csp->iob->cur-1) << 8));
953 * The number of bytes to skip should be positive
954 * and we'd like to stay in the buffer.
956 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
958 log_error (LOG_LEVEL_ERROR,
959 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
961 return JB_ERR_COMPRESS;
963 log_error (LOG_LEVEL_INFO,
964 "Skipping %d bytes for gzip compression. Does this sound right?",
969 /* Skip the filename if necessary. */
972 /* A null-terminated string follows. */
976 /* Skip the comment if necessary. */
982 /* Skip the CRC if necessary. */
989 else if (csp->content_type & CT_DEFLATE)
992 * XXX: The debug level should be lowered
993 * before the next stable release.
995 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
997 * In theory (that is, according to RFC 1950), deflate-compressed
998 * data should begin with a two-byte zlib header and have an
999 * adler32 checksum at the end. It seems that in practice only
1000 * the raw compressed data is sent. Note that this means that
1001 * we are not RFC 1950-compliant here, but the advantage is that
1002 * this actually works. :)
1004 * We add a dummy null byte to tell zlib where the data ends,
1005 * and later inform it not to expect a header.
1007 * Fortunately, add_to_iob() has thoughtfully null-terminated
1008 * the buffer; we can just increment the end pointer to include
1015 log_error (LOG_LEVEL_ERROR,
1016 "Unable to determine compression format for decompression");
1017 return JB_ERR_COMPRESS;
1020 /* Set up the fields required by zlib. */
1021 zstr.next_in = (Bytef *)cur;
1022 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1023 zstr.zalloc = Z_NULL;
1024 zstr.zfree = Z_NULL;
1025 zstr.opaque = Z_NULL;
1028 * Passing -MAX_WBITS to inflateInit2 tells the library
1029 * that there is no zlib header.
1031 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1033 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1034 return JB_ERR_COMPRESS;
1038 * Next, we allocate new storage for the inflated data.
1039 * We don't modify the existing iob yet, so in case there
1040 * is error in decompression we can recover gracefully.
1042 buf = zalloc (bufsize);
1045 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1046 return JB_ERR_MEMORY;
1049 assert(bufsize >= skip_size);
1050 memcpy(buf, csp->iob->buf, skip_size);
1051 zstr.avail_out = bufsize - skip_size;
1052 zstr.next_out = (Bytef *)buf + skip_size;
1054 /* Try to decompress the whole stream in one shot. */
1055 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1057 /* We need to allocate more memory for the output buffer. */
1059 char *tmpbuf; /* used for realloc'ing the buffer */
1060 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1063 * If zlib wants more data then there's a problem, because
1064 * the complete compressed file should have been buffered.
1066 if (0 == zstr.avail_in)
1068 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1069 return JB_ERR_COMPRESS;
1073 * If we tried the limit and still didn't have enough
1074 * memory, just give up.
1076 if (bufsize == csp->config->buffer_limit)
1078 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1079 return JB_ERR_MEMORY;
1082 /* Try doubling the buffer size each time. */
1085 /* Don't exceed the buffer limit. */
1086 if (bufsize > csp->config->buffer_limit)
1088 bufsize = csp->config->buffer_limit;
1091 /* Try to allocate the new buffer. */
1092 tmpbuf = realloc(buf, bufsize);
1095 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1097 return JB_ERR_MEMORY;
1101 char *oldnext_out = (char *)zstr.next_out;
1104 * Update the fields for inflate() to use the new
1105 * buffer, which may be in a location different from
1108 zstr.avail_out += bufsize - oldbufsize;
1109 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1112 * Compare with an uglier method of calculating these values
1113 * that doesn't require the extra oldbufsize variable.
1115 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1116 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1117 assert(zstr.avail_out > 0);
1123 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1125 log_error(LOG_LEVEL_ERROR,
1126 "Inconsistent stream state after decompression: %s", zstr.msg);
1128 * XXX: Intentionally no return.
1130 * According to zlib.h, Z_STREAM_ERROR is returned
1131 * "if the stream state was inconsistent".
1133 * I assume in this case inflate()'s status
1134 * would also be something different than Z_STREAM_END
1135 * so this check should be redundant, but lets see.
1139 if (status != Z_STREAM_END)
1141 /* We failed to decompress the stream. */
1142 log_error(LOG_LEVEL_ERROR,
1143 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1144 return JB_ERR_COMPRESS;
1148 * Finally, we can actually update the iob, since the
1149 * decompression was successful. First, free the old
1152 freez(csp->iob->buf);
1154 /* Now, update the iob to use the new buffer. */
1155 csp->iob->buf = buf;
1156 csp->iob->cur = csp->iob->buf + skip_size;
1157 csp->iob->eod = (char *)zstr.next_out;
1158 csp->iob->size = bufsize;
1161 * Make sure the new uncompressed iob obeys some minimal
1162 * consistency conditions.
1164 if ((csp->iob->buf < csp->iob->cur)
1165 && (csp->iob->cur <= csp->iob->eod)
1166 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1168 char t = csp->iob->cur[100];
1169 csp->iob->cur[100] = '\0';
1171 * XXX: The debug level should be lowered
1172 * before the next stable release.
1174 log_error(LOG_LEVEL_INFO, "Sucessfully decompressed: %s", csp->iob->cur);
1175 csp->iob->cur[100] = t;
1180 /* It seems that zlib did something weird. */
1181 log_error(LOG_LEVEL_ERROR,
1182 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1183 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1184 csp->iob->eod, csp->iob->buf + csp->iob->size);
1185 return JB_ERR_COMPRESS;
1189 #endif /* defined(FEATURE_ZLIB) */
1192 /*********************************************************************
1194 * Function : get_header
1196 * Description : This (odd) routine will parse the csp->iob
1199 * 1 : csp = Current client state (buffers, headers, etc...)
1201 * Returns : Any one of the following:
1203 * 1) a pointer to a dynamically allocated string that contains a header line
1204 * 2) NULL indicating that the end of the header was reached
1205 * 3) "" indicating that the end of the iob was reached before finding
1206 * a complete header line.
1208 *********************************************************************/
1209 char *get_header(struct client_state *csp)
1215 if ((iob->cur == NULL)
1216 || ((p = strchr(iob->cur, '\n')) == NULL))
1218 return(""); /* couldn't find a complete header */
1223 ret = strdup(iob->cur);
1226 /* FIXME No way to handle error properly */
1227 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1232 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1234 /* is this a blank line (i.e. the end of the header) ? */
1246 /*********************************************************************
1248 * Function : get_header_value
1250 * Description : Get the value of a given header from a chained list
1251 * of header lines or return NULL if no such header is
1252 * present in the list.
1255 * 1 : header_list = pointer to list
1256 * 2 : header_name = string with name of header to look for.
1257 * Trailing colon required, capitalization
1260 * Returns : NULL if not found, else value of header
1262 *********************************************************************/
1263 char *get_header_value(const struct list *header_list, const char *header_name)
1265 struct list_entry *cur_entry;
1269 assert(header_list);
1270 assert(header_name);
1271 length = strlen(header_name);
1273 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1277 if (!strncmpic(cur_entry->str, header_name, length))
1280 * Found: return pointer to start of value
1282 ret = (char *) (cur_entry->str + length);
1283 while (*ret && ijb_isspace(*ret)) ret++;
1296 /*********************************************************************
1300 * Description : add, delete or modify lines in the HTTP header streams.
1301 * On entry, it receives a linked list of headers space
1302 * that was allocated dynamically (both the list nodes
1303 * and the header contents).
1305 * As a side effect it frees the space used by the original
1309 * 1 : pats = list of patterns to match against headers
1310 * 2 : more_headers = list of functions to add more
1311 * headers (client or server)
1312 * 3 : csp = Current client state (buffers, headers, etc...)
1314 * Returns : Single pointer to a fully formed header, or NULL
1315 * on out-of-memory error.
1317 *********************************************************************/
1318 char *sed(const struct parsers pats[],
1319 const add_header_func_ptr more_headers[],
1320 struct client_state *csp)
1322 struct list_entry *p;
1323 const struct parsers *v;
1324 const add_header_func_ptr *f;
1325 jb_err err = JB_ERR_OK;
1329 * If filtering is enabled, sed is run twice,
1330 * but most of the work needs to be done only once.
1332 first_run = (more_headers != NULL ) ? 1 : 0;
1334 if (first_run) /* Parse and print */
1336 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1337 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1339 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1341 /* Header crunch()ed in previous run? -> ignore */
1342 if (p->str == NULL) continue;
1344 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
1346 /* Does the current parser handle this header? */
1347 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1349 err = v->parser(csp, (char **)&(p->str));
1353 /* place any additional headers on the csp->headers list */
1354 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1359 else /* Parse only */
1362 * The second run is only needed if the body was modified
1363 * and the content-lenght has changed.
1365 if (strncmpic(csp->http->cmd, "HEAD", 4))
1367 /*XXX: Code duplication */
1368 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1370 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1372 /* Header crunch()ed in previous run? -> ignore */
1373 if (p->str == NULL) continue;
1375 /* Does the current parser handle this header? */
1376 if (strncmpic(p->str, v->str, v->len) == 0)
1378 err = v->parser(csp, (char **)&(p->str));
1385 if (err != JB_ERR_OK)
1390 return list_to_text(csp->headers);
1394 /* here begins the family of parser functions that reformat header lines */
1396 /*********************************************************************
1398 * Function : filter_server_header
1400 * Description : Checks if server header filtering is enabled.
1401 * If it is, filter_header is called to do the work.
1404 * 1 : csp = Current client state (buffers, headers, etc...)
1405 * 2 : header = On input, pointer to header to modify.
1406 * On output, pointer to the modified header, or NULL
1407 * to remove the header. This function frees the
1408 * original string if necessary.
1410 * Returns : JB_ERR_OK on success and always succeeds
1412 *********************************************************************/
1413 jb_err filter_server_header(struct client_state *csp, char **header)
1415 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
1417 filter_header(csp, header);
1422 /*********************************************************************
1424 * Function : filter_client_header
1426 * Description : Checks if client header filtering is enabled.
1427 * If it is, filter_header is called to do the work.
1430 * 1 : csp = Current client state (buffers, headers, etc...)
1431 * 2 : header = On input, pointer to header to modify.
1432 * On output, pointer to the modified header, or NULL
1433 * to remove the header. This function frees the
1434 * original string if necessary.
1436 * Returns : JB_ERR_OK on success and always succeeds
1438 *********************************************************************/
1439 jb_err filter_client_header(struct client_state *csp, char **header)
1441 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
1443 filter_header(csp, header);
1448 /*********************************************************************
1450 * Function : filter_header
1452 * Description : Executes all text substitutions from all applying
1453 * +filter actions on the header.
1454 * Most of the code was copied from pcrs_filter_response,
1455 * including the rather short variable names
1458 * 1 : csp = Current client state (buffers, headers, etc...)
1459 * 2 : header = On input, pointer to header to modify.
1460 * On output, pointer to the modified header, or NULL
1461 * to remove the header. This function frees the
1462 * original string if necessary.
1464 * Returns : JB_ERR_OK on success and always succeeds
1466 *********************************************************************/
1467 jb_err filter_header(struct client_state *csp, char **header)
1471 size_t size = strlen(*header);
1473 char *newheader = NULL;
1476 struct file_list *fl;
1477 struct re_filterfile_spec *b;
1478 struct list_entry *filtername;
1480 int i, found_filters = 0;
1483 * Need to check the set of re_filterfiles...
1485 for (i = 0; i < MAX_AF_FILES; i++)
1498 if (0 == found_filters)
1500 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1504 for (i = 0; i < MAX_AF_FILES; i++)
1507 if ((NULL == fl) || (NULL == fl->f))
1510 * Either there are no filter files
1511 * left, or this filter file just
1512 * contains no valid filters.
1514 * Continue to be sure we don't miss
1515 * valid filter files that are chained
1516 * after empty or invalid ones.
1521 * For all applying +filter actions, look if a filter by that
1522 * name exists and if yes, execute its pcrs_joblist on the
1525 for (b = fl->f; b; b = b->next)
1527 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1528 filtername ; filtername = filtername->next)
1530 if (strcmp(b->name, filtername->str) == 0)
1532 int current_hits = 0;
1534 if ( NULL == b->joblist )
1536 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1540 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1541 *header, size, b->name);
1543 /* Apply all jobs from the joblist */
1544 for (job = b->joblist; NULL != job; job = job->next)
1546 matches = pcrs_execute(job, *header, size, &newheader, &size);
1549 current_hits += matches;
1550 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1552 *header = newheader;
1554 else if ( 0 == matches )
1556 /* Filter doesn't change header */
1562 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1563 *header, b->name, pcrs_strerror(matches));
1564 if( newheader != NULL)
1566 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1571 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1572 hits += current_hits;
1579 * Additionally checking for hits is important because if
1580 * the continue hack is triggered, server headers can
1581 * arrive empty to separate multiple heads from each other.
1583 if ((0 == size) && hits)
1585 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1593 /*********************************************************************
1595 * Function : crumble
1597 * Description : This is called if a header matches a pattern to "crunch"
1600 * 1 : csp = Current client state (buffers, headers, etc...)
1601 * 2 : header = On input, pointer to header to modify.
1602 * On output, pointer to the modified header, or NULL
1603 * to remove the header. This function frees the
1604 * original string if necessary.
1606 * Returns : JB_ERR_OK on success, or
1607 * JB_ERR_MEMORY on out-of-memory error.
1609 *********************************************************************/
1610 jb_err crumble(struct client_state *csp, char **header)
1612 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1617 /*********************************************************************
1619 * Function : crunch_server_header
1621 * Description : Crunch server header if it matches a string supplied by the
1622 * user. Called from `sed'.
1625 * 1 : csp = Current client state (buffers, headers, etc...)
1626 * 2 : header = On input, pointer to header to modify.
1627 * On output, pointer to the modified header, or NULL
1628 * to remove the header. This function frees the
1629 * original string if necessary.
1631 * Returns : JB_ERR_OK on success and always succeeds
1633 *********************************************************************/
1634 jb_err crunch_server_header(struct client_state *csp, char **header)
1636 const char *crunch_pattern;
1637 /*Is there a header to crunch*/
1639 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1641 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1643 /*Is the current header the lucky one?*/
1644 if (strstr(*header, crunch_pattern))
1646 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1655 /*********************************************************************
1657 * Function : server_content_type
1659 * Description : Set the content-type for filterable types (text/.*,
1660 * .*xml.*, javascript and image/gif) unless filtering has been
1661 * forbidden (CT_TABOO) while parsing earlier headers.
1662 * NOTE: Since text/plain is commonly used by web servers
1663 * for files whose correct type is unknown, we don't
1664 * set CT_TEXT for it.
1667 * 1 : csp = Current client state (buffers, headers, etc...)
1668 * 2 : header = On input, pointer to header to modify.
1669 * On output, pointer to the modified header, or NULL
1670 * to remove the header. This function frees the
1671 * original string if necessary.
1673 * Returns : JB_ERR_OK on success, or
1674 * JB_ERR_MEMORY on out-of-memory error.
1676 *********************************************************************/
1677 jb_err server_content_type(struct client_state *csp, char **header)
1679 /* Remove header if it isn't the first Content-Type header */
1680 if(csp->content_type && (csp->content_type != CT_TABOO))
1683 * Another, slightly slower, way to see if
1684 * we already parsed another Content-Type header.
1686 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1688 log_error(LOG_LEVEL_ERROR,
1689 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1696 if (!(csp->content_type & CT_TABOO))
1698 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1699 || strstr(*header, "xml")
1700 || strstr(*header, "application/x-javascript"))
1702 csp->content_type |= CT_TEXT;
1704 else if (strstr(*header, " image/gif"))
1706 csp->content_type |= CT_GIF;
1708 else if (strstr(*header, " image/jpeg"))
1710 csp->content_type |= CT_JPEG;
1714 csp->content_type = 0;
1718 * Are we enabling text mode by force?
1720 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1723 * Do we really have to?
1725 if (csp->content_type & CT_TEXT)
1727 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1731 csp->content_type |= CT_TEXT;
1732 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1736 * Are we messing with the content type?
1738 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1741 * Make sure the user doesn't accidently
1742 * change the content type of binary documents.
1744 if (csp->content_type & CT_TEXT)
1747 *header = strdup("Content-Type: ");
1748 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1752 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1753 return JB_ERR_MEMORY;
1755 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1759 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1760 "Enable force-text-mode if you know what you're doing.", *header);
1767 /*********************************************************************
1769 * Function : server_transfer_coding
1771 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1772 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1773 * - Remove header if body was chunked but has been
1774 * de-chunked for filtering.
1777 * 1 : csp = Current client state (buffers, headers, etc...)
1778 * 2 : header = On input, pointer to header to modify.
1779 * On output, pointer to the modified header, or NULL
1780 * to remove the header. This function frees the
1781 * original string if necessary.
1783 * Returns : JB_ERR_OK on success, or
1784 * JB_ERR_MEMORY on out-of-memory error.
1786 *********************************************************************/
1787 jb_err server_transfer_coding(struct client_state *csp, char **header)
1790 * Turn off pcrs and gif filtering if body compressed
1792 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1796 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1798 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1799 csp->http->cmd, *header);
1800 #endif /* def FEATURE_ZLIB */
1801 csp->content_type = CT_TABOO;
1805 * Raise flag if body chunked
1807 if (strstr(*header, "chunked"))
1809 csp->flags |= CSP_FLAG_CHUNKED;
1812 * If the body was modified, it has been de-chunked first
1813 * and the header must be removed.
1815 * FIXME: If there is more than one transfer encoding,
1816 * only the "chunked" part should be removed here.
1818 if (csp->flags & CSP_FLAG_MODIFIED)
1820 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1829 /*********************************************************************
1831 * Function : server_content_encoding
1833 * Description : This function is run twice for each request,
1834 * unless FEATURE_ZLIB and filtering are disabled.
1836 * The first run is used to check if the content
1837 * is compressed, if FEATURE_ZLIB is disabled
1838 * filtering is then disabled as well, if FEATURE_ZLIB
1839 * is enabled the content is marked for decompression.
1841 * The second run is used to remove the Content-Encoding
1842 * header if the decompression was successful.
1845 * 1 : csp = Current client state (buffers, headers, etc...)
1846 * 2 : header = On input, pointer to header to modify.
1847 * On output, pointer to the modified header, or NULL
1848 * to remove the header. This function frees the
1849 * original string if necessary.
1851 * Returns : JB_ERR_OK on success, or
1852 * JB_ERR_MEMORY on out-of-memory error.
1854 *********************************************************************/
1855 jb_err server_content_encoding(struct client_state *csp, char **header)
1858 if ((csp->flags & CSP_FLAG_MODIFIED)
1859 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1862 * We successfully decompressed the content,
1863 * and have to clean the header now, so the
1864 * client no longer expects compressed data..
1866 * XXX: There is a difference between cleaning
1867 * and removing it completely.
1869 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1872 else if (strstr(*header, "gzip"))
1874 /* Mark for gzip decompression */
1875 csp->content_type |= CT_GZIP;
1877 else if (strstr(*header, "deflate"))
1879 /* Mark for zlib decompression */
1880 csp->content_type |= CT_DEFLATE;
1882 else if (strstr(*header, "compress"))
1885 * We can't decompress this; therefore we can't filter
1888 csp->content_type |= CT_TABOO;
1890 #else /* !defined(FEATURE_ZLIB) */
1891 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1894 * Body is compressed, turn off pcrs and gif filtering.
1896 csp->content_type |= CT_TABOO;
1898 #endif /* !defined(FEATURE_ZLIB) */
1905 /*********************************************************************
1907 * Function : server_content_length
1909 * Description : Adjust Content-Length header if we modified
1913 * 1 : csp = Current client state (buffers, headers, etc...)
1914 * 2 : header = On input, pointer to header to modify.
1915 * On output, pointer to the modified header, or NULL
1916 * to remove the header. This function frees the
1917 * original string if necessary.
1919 * Returns : JB_ERR_OK on success, or
1920 * JB_ERR_MEMORY on out-of-memory error.
1922 *********************************************************************/
1923 jb_err server_content_length(struct client_state *csp, char **header)
1925 const size_t max_header_length = 80;
1926 if (csp->content_length != 0) /* Content length could have been modified */
1929 * XXX: Shouldn't we check if csp->content_length
1930 * is different than the original value?
1933 *header = (char *) zalloc(max_header_length);
1934 if (*header == NULL)
1936 return JB_ERR_MEMORY;
1939 snprintf(*header, max_header_length, "Content-Length: %d",
1940 (int)csp->content_length);
1941 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
1942 (int)csp->content_length);
1949 /*********************************************************************
1951 * Function : server_content_md5
1953 * Description : Crumble any Content-MD5 headers if the document was
1954 * modified. FIXME: Should we re-compute instead?
1957 * 1 : csp = Current client state (buffers, headers, etc...)
1958 * 2 : header = On input, pointer to header to modify.
1959 * On output, pointer to the modified header, or NULL
1960 * to remove the header. This function frees the
1961 * original string if necessary.
1963 * Returns : JB_ERR_OK on success, or
1964 * JB_ERR_MEMORY on out-of-memory error.
1966 *********************************************************************/
1967 jb_err server_content_md5(struct client_state *csp, char **header)
1969 if (csp->flags & CSP_FLAG_MODIFIED)
1971 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1978 /*********************************************************************
1980 * Function : server_content_disposition
1982 * Description : If enabled, blocks or modifies the "content-disposition" header.
1983 * Called from `sed'.
1986 * 1 : csp = Current client state (buffers, headers, etc...)
1987 * 2 : header = On input, pointer to header to modify.
1988 * On output, pointer to the modified header, or NULL
1989 * to remove the header. This function frees the
1990 * original string if necessary.
1992 * Returns : JB_ERR_OK on success, or
1993 * JB_ERR_MEMORY on out-of-memory error.
1995 *********************************************************************/
1996 jb_err server_content_disposition(struct client_state *csp, char **header)
2001 * Are we messing with the content-disposition header?
2003 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2009 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2011 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2014 * Blocking content-disposition header
2016 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2023 * Replacing content-disposition header
2026 *header = strdup("content-disposition: ");
2027 string_append(header, newval);
2029 if (*header == NULL)
2031 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2035 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2038 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2041 /*********************************************************************
2043 * Function : server_last_modified
2045 * Description : Changes Last-Modified header to the actual date
2046 * to help hide-if-modified-since.
2047 * Called from `sed'.
2050 * 1 : csp = Current client state (buffers, headers, etc...)
2051 * 2 : header = On input, pointer to header to modify.
2052 * On output, pointer to the modified header, or NULL
2053 * to remove the header. This function frees the
2054 * original string if necessary.
2056 * Returns : JB_ERR_OK on success, or
2057 * JB_ERR_MEMORY on out-of-memory error.
2059 *********************************************************************/
2060 jb_err server_last_modified(struct client_state *csp, char **header)
2063 char buf[BUFFER_SIZE];
2066 #ifdef HAVE_GMTIME_R
2069 struct tm *timeptr = NULL;
2070 time_t now, last_modified;
2072 long int days, hours, minutes, seconds;
2075 * Are we messing with the Last-Modified header?
2077 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2083 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2085 if (0 == strcmpic(newval, "block") )
2088 * Blocking Last-Modified header. Useless but why not.
2090 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2094 else if (0 == strcmpic(newval, "reset-to-request-time"))
2097 * Setting Last-Modified Header to now.
2099 get_http_time(0, buf);
2101 *header = strdup("Last-Modified: ");
2102 string_append(header, buf);
2104 if (*header == NULL)
2106 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2110 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2113 else if (0 == strcmpic(newval, "randomize"))
2115 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2117 #ifdef HAVE_GMTIME_R
2118 timeptr = gmtime_r(&now, &gmt);
2119 #elif FEATURE_PTHREAD
2120 pthread_mutex_lock(&gmtime_mutex);
2121 timeptr = gmtime(&now);
2122 pthread_mutex_unlock(&gmtime_mutex);
2124 timeptr = gmtime(&now);
2126 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
2128 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2133 rtime = (long int)difftime(now, last_modified);
2136 rtime = pick_from_range(rtime);
2137 last_modified += rtime;
2138 #ifdef HAVE_GMTIME_R
2139 timeptr = gmtime_r(&last_modified, &gmt);
2140 #elif FEATURE_PTHREAD
2141 pthread_mutex_lock(&gmtime_mutex);
2142 timeptr = gmtime(&last_modified);
2143 pthread_mutex_unlock(&gmtime_mutex);
2145 timeptr = gmtime(&last_modified);
2147 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2149 *header = strdup("Last-Modified: ");
2150 string_append(header, newheader);
2152 if (*header == NULL)
2154 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2155 return JB_ERR_MEMORY;
2158 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2160 days = rtime / (3600 * 24);
2161 hours = rtime / 3600 % 24;
2162 minutes = rtime / 60 % 60;
2163 seconds = rtime % 60;
2165 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2166 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2167 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2172 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2180 /*********************************************************************
2182 * Function : client_accept_encoding
2184 * Description : Rewrite the client's Accept-Encoding header so that
2185 * if doesn't allow compression, if the action applies.
2186 * Note: For HTTP/1.0 the absence of the header is enough.
2189 * 1 : csp = Current client state (buffers, headers, etc...)
2190 * 2 : header = On input, pointer to header to modify.
2191 * On output, pointer to the modified header, or NULL
2192 * to remove the header. This function frees the
2193 * original string if necessary.
2195 * Returns : JB_ERR_OK on success, or
2196 * JB_ERR_MEMORY on out-of-memory error.
2198 *********************************************************************/
2199 jb_err client_accept_encoding(struct client_state *csp, char **header)
2201 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2203 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2207 /* Temporarily disable the correct behaviour to
2208 * work around a PHP bug.
2210 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2212 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2213 * if (*header == NULL)
2215 * return JB_ERR_MEMORY;
2226 /*********************************************************************
2228 * Function : client_te
2230 * Description : Rewrite the client's TE header so that
2231 * if doesn't allow compression, if the action applies.
2234 * 1 : csp = Current client state (buffers, headers, etc...)
2235 * 2 : header = On input, pointer to header to modify.
2236 * On output, pointer to the modified header, or NULL
2237 * to remove the header. This function frees the
2238 * original string if necessary.
2240 * Returns : JB_ERR_OK on success, or
2241 * JB_ERR_MEMORY on out-of-memory error.
2243 *********************************************************************/
2244 jb_err client_te(struct client_state *csp, char **header)
2246 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2249 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2255 /*********************************************************************
2257 * Function : client_referrer
2259 * Description : Handle the "referer" config setting properly.
2260 * Called from `sed'.
2263 * 1 : csp = Current client state (buffers, headers, etc...)
2264 * 2 : header = On input, pointer to header to modify.
2265 * On output, pointer to the modified header, or NULL
2266 * to remove the header. This function frees the
2267 * original string if necessary.
2269 * Returns : JB_ERR_OK on success, or
2270 * JB_ERR_MEMORY on out-of-memory error.
2272 *********************************************************************/
2273 jb_err client_referrer(struct client_state *csp, char **header)
2280 #ifdef FEATURE_FORCE_LOAD
2281 /* Since the referrer can include the prefix even
2282 * if the request itself is non-forced, we must
2283 * clean it unconditionally
2285 strclean(*header, FORCE_PREFIX);
2286 #endif /* def FEATURE_FORCE_LOAD */
2289 * Are we sending referer?
2291 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2296 newval = csp->action->string[ACTION_STRING_REFERER];
2298 if ((0 != strcmpic(newval, "conditional-block")))
2302 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2307 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2310 else if (0 == strcmpic(newval, "conditional-block"))
2313 * Block referer if host has changed.
2316 if (NULL == (host = strdup(csp->http->hostport)))
2319 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2320 return JB_ERR_MEMORY;
2322 if (NULL == (referer = strdup(*header)))
2326 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2327 return JB_ERR_MEMORY;
2329 hostlenght = strlen(host);
2330 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2332 /*Shorten referer to make sure the referer is blocked
2333 *if www.example.org/www.example.com-shall-see-the-referer/
2334 *links to www.example.com/
2336 referer[hostlenght+17] = '\0';
2338 if ( 0 == strstr(referer, host)) /*Host has changed*/
2340 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2345 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2351 else if (0 != strcmpic(newval, "forge"))
2354 * We have a specific (fixed) referer we want to send.
2356 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2358 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2360 *header = strdup("Referer: ");
2361 string_append(header, newval);
2362 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2364 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2369 * Forge a referer as http://[hostname:port of REQUEST]/
2370 * to fool stupid checks for in-site links
2373 *header = strdup("Referer: http://");
2374 string_append(header, csp->http->hostport);
2375 string_append(header, "/");
2376 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2378 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2382 /*********************************************************************
2384 * Function : client_accept_language
2386 * Description : Handle the "Accept-Language" config setting properly.
2387 * Called from `sed'.
2390 * 1 : csp = Current client state (buffers, headers, etc...)
2391 * 2 : header = On input, pointer to header to modify.
2392 * On output, pointer to the modified header, or NULL
2393 * to remove the header. This function frees the
2394 * original string if necessary.
2396 * Returns : JB_ERR_OK on success, or
2397 * JB_ERR_MEMORY on out-of-memory error.
2399 *********************************************************************/
2400 jb_err client_accept_language(struct client_state *csp, char **header)
2405 * Are we messing with the Accept-Language?
2407 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2409 /*I don't think so*/
2413 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2415 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2418 * Blocking Accept-Language header
2420 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2427 * Replacing Accept-Language header
2430 *header = strdup("Accept-Language: ");
2431 string_append(header, newval);
2433 if (*header == NULL)
2435 log_error(LOG_LEVEL_ERROR,
2436 "Insufficent memory. Accept-Language header crunched without replacement.");
2440 log_error(LOG_LEVEL_HEADER,
2441 "Accept-Language header crunched and replaced with: %s", *header);
2444 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2447 /*********************************************************************
2449 * Function : crunch_client_header
2451 * Description : Crunch client header if it matches a string supplied by the
2452 * user. Called from `sed'.
2455 * 1 : csp = Current client state (buffers, headers, etc...)
2456 * 2 : header = On input, pointer to header to modify.
2457 * On output, pointer to the modified header, or NULL
2458 * to remove the header. This function frees the
2459 * original string if necessary.
2461 * Returns : JB_ERR_OK on success and always succeeds
2463 *********************************************************************/
2464 jb_err crunch_client_header(struct client_state *csp, char **header)
2466 const char *crunch_pattern;
2467 /*Is there a header to crunch*/
2469 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2471 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2473 /*Is the current header the lucky one?*/
2474 if (strstr(*header, crunch_pattern))
2476 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2484 /*********************************************************************
2486 * Function : client_uagent
2488 * Description : Handle the "user-agent" config setting properly
2489 * and remember its original value to enable browser
2490 * bug workarounds. Called from `sed'.
2493 * 1 : csp = Current client state (buffers, headers, etc...)
2494 * 2 : header = On input, pointer to header to modify.
2495 * On output, pointer to the modified header, or NULL
2496 * to remove the header. This function frees the
2497 * original string if necessary.
2499 * Returns : JB_ERR_OK on success, or
2500 * JB_ERR_MEMORY on out-of-memory error.
2502 *********************************************************************/
2503 jb_err client_uagent(struct client_state *csp, char **header)
2507 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2512 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2519 *header = strdup("User-Agent: ");
2520 string_append(header, newval);
2522 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2524 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2527 /*********************************************************************
2529 * Function : client_ua
2531 * Description : Handle "ua-" headers properly. Called from `sed'.
2534 * 1 : csp = Current client state (buffers, headers, etc...)
2535 * 2 : header = On input, pointer to header to modify.
2536 * On output, pointer to the modified header, or NULL
2537 * to remove the header. This function frees the
2538 * original string if necessary.
2540 * Returns : JB_ERR_OK on success, or
2541 * JB_ERR_MEMORY on out-of-memory error.
2543 *********************************************************************/
2544 jb_err client_ua(struct client_state *csp, char **header)
2546 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2548 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2556 /*********************************************************************
2558 * Function : client_from
2560 * Description : Handle the "from" config setting properly.
2561 * Called from `sed'.
2564 * 1 : csp = Current client state (buffers, headers, etc...)
2565 * 2 : header = On input, pointer to header to modify.
2566 * On output, pointer to the modified header, or NULL
2567 * to remove the header. This function frees the
2568 * original string if necessary.
2570 * Returns : JB_ERR_OK on success, or
2571 * JB_ERR_MEMORY on out-of-memory error.
2573 *********************************************************************/
2574 jb_err client_from(struct client_state *csp, char **header)
2578 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2585 newval = csp->action->string[ACTION_STRING_FROM];
2588 * Are we blocking the e-mail address?
2590 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2592 log_error(LOG_LEVEL_HEADER, "crunched From!");
2596 log_error(LOG_LEVEL_HEADER, " modified");
2598 *header = strdup("From: ");
2599 string_append(header, newval);
2601 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2605 /*********************************************************************
2607 * Function : client_send_cookie
2609 * Description : Handle the "cookie" header properly. Called from `sed'.
2610 * If cookie is accepted, add it to the cookie_list,
2611 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2614 * 1 : csp = Current client state (buffers, headers, etc...)
2615 * 2 : header = On input, pointer to header to modify.
2616 * On output, pointer to the modified header, or NULL
2617 * to remove the header. This function frees the
2618 * original string if necessary.
2620 * Returns : JB_ERR_OK on success, or
2621 * JB_ERR_MEMORY on out-of-memory error.
2623 *********************************************************************/
2624 jb_err client_send_cookie(struct client_state *csp, char **header)
2626 jb_err result = JB_ERR_OK;
2628 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2630 /* strlen("cookie: ") == 8 */
2631 result = enlist(csp->cookie_list, *header + 8);
2635 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2639 * Always remove the cookie here. The cookie header
2640 * will be sent at the end of the header.
2648 /*********************************************************************
2650 * Function : client_x_forwarded
2652 * Description : Handle the "x-forwarded-for" config setting properly,
2653 * also used in the add_client_headers list. Called from `sed'.
2656 * 1 : csp = Current client state (buffers, headers, etc...)
2657 * 2 : header = On input, pointer to header to modify.
2658 * On output, pointer to the modified header, or NULL
2659 * to remove the header. This function frees the
2660 * original string if necessary.
2662 * Returns : JB_ERR_OK on success, or
2663 * JB_ERR_MEMORY on out-of-memory error.
2665 *********************************************************************/
2666 jb_err client_x_forwarded(struct client_state *csp, char **header)
2668 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2670 /* Save it so we can re-add it later */
2671 freez(csp->x_forwarded);
2672 csp->x_forwarded = *header;
2675 * Always set *header = NULL, since this information
2676 * will be sent at the end of the header.
2683 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2690 /*********************************************************************
2692 * Function : client_max_forwards
2694 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2695 * from the value of the Max-Forwards header field.
2698 * 1 : csp = Current client state (buffers, headers, etc...)
2699 * 2 : header = On input, pointer to header to modify.
2700 * On output, pointer to the modified header, or NULL
2701 * to remove the header. This function frees the
2702 * original string if necessary.
2704 * Returns : JB_ERR_OK on success, or
2705 * JB_ERR_MEMORY on out-of-memory error.
2707 *********************************************************************/
2708 jb_err client_max_forwards(struct client_state *csp, char **header)
2712 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2713 (0 == strcmpic(csp->http->gpc, "options")))
2715 assert(*(*header+12) == ':');
2716 if (1 == sscanf(*header+12, ": %u", &max_forwards))
2718 if (max_forwards > 0)
2720 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
2721 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
2722 csp->http->gpc, max_forwards);
2724 else if (max_forwards < 0)
2726 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2732 * Not supposed to be reached. direct_response() which
2733 * was already called earlier in chat() should have
2734 * intercepted the request.
2736 log_error(LOG_LEVEL_ERROR,
2737 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2738 assert(max_forwards != 0);
2743 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2752 /*********************************************************************
2754 * Function : client_host
2756 * Description : If the request URI did not contain host and
2757 * port information, parse and evaluate the Host
2760 * Also, kill ill-formed HOST: headers as sent by
2761 * Apple's iTunes software when used with a proxy.
2764 * 1 : csp = Current client state (buffers, headers, etc...)
2765 * 2 : header = On input, pointer to header to modify.
2766 * On output, pointer to the modified header, or NULL
2767 * to remove the header. This function frees the
2768 * original string if necessary.
2770 * Returns : JB_ERR_OK on success, or
2771 * JB_ERR_MEMORY on out-of-memory error.
2773 *********************************************************************/
2774 jb_err client_host(struct client_state *csp, char **header)
2779 * If the header field name is all upper-case, chances are that it's
2780 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2781 * not a problem -- they are regenerated later.
2783 if ((*header)[1] == 'O')
2785 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2790 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2791 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2794 if (NULL == (p = strdup((*header)+6)))
2796 return JB_ERR_MEMORY;
2799 if (NULL == (q = strdup(p)))
2802 return JB_ERR_MEMORY;
2805 freez(csp->http->hostport);
2806 csp->http->hostport = p;
2807 freez(csp->http->host);
2808 csp->http->host = q;
2809 q = strchr(csp->http->host, ':');
2812 /* Terminate hostname and evaluate port string */
2814 csp->http->port = atoi(q);
2818 csp->http->port = csp->http->ssl ? 443 : 80;
2821 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2822 csp->http->hostport, csp->http->host, csp->http->port);
2828 /*********************************************************************
2830 * Function : client_if_modified_since
2832 * Description : Remove or modify the If-Modified-Since header.
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_if_modified_since(struct client_state *csp, char **header)
2848 #ifdef HAVE_GMTIME_R
2851 struct tm *timeptr = NULL;
2855 long int hours, minutes, seconds;
2859 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2862 * The client got an error message because of a temporary problem,
2863 * the problem is gone and the client now tries to revalidate our
2864 * error message on the real server. The revalidation would always
2865 * end with the transmission of the whole document and there is
2866 * no need to expose the bogus If-Modified-Since header.
2868 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2871 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2873 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2875 if ((0 == strcmpic(newval, "block")))
2877 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2880 else /* add random value */
2882 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2884 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2889 rtime = strtol(newval, &endptr, 0);
2892 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2893 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2900 rtime = pick_from_range(rtime);
2904 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2907 tm += rtime * (negative ? -1 : 1);
2908 #ifdef HAVE_GMTIME_R
2909 timeptr = gmtime_r(&tm, &gmt);
2910 #elif FEATURE_PTHREAD
2911 pthread_mutex_lock(&gmtime_mutex);
2912 timeptr = gmtime(&tm);
2913 pthread_mutex_unlock(&gmtime_mutex);
2915 timeptr = gmtime(&tm);
2917 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2920 *header = strdup("If-Modified-Since: ");
2921 string_append(header, newheader);
2923 if (*header == NULL)
2925 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2926 return JB_ERR_MEMORY;
2929 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2931 hours = rtime / 3600;
2932 minutes = rtime / 60 % 60;
2933 seconds = rtime % 60;
2935 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2936 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2937 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2946 /*********************************************************************
2948 * Function : client_if_none_match
2950 * Description : Remove the If-None-Match header.
2953 * 1 : csp = Current client state (buffers, headers, etc...)
2954 * 2 : header = On input, pointer to header to modify.
2955 * On output, pointer to the modified header, or NULL
2956 * to remove the header. This function frees the
2957 * original string if necessary.
2959 * Returns : JB_ERR_OK on success, or
2960 * JB_ERR_MEMORY on out-of-memory error.
2962 *********************************************************************/
2963 jb_err client_if_none_match(struct client_state *csp, char **header)
2965 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2967 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2974 /*********************************************************************
2976 * Function : client_x_filter
2978 * Description : Disables filtering if the client set "X-Filter: No".
2979 * Called from `sed'.
2982 * 1 : csp = Current client state (buffers, headers, etc...)
2983 * 2 : header = On input, pointer to header to modify.
2984 * On output, pointer to the modified header, or NULL
2985 * to remove the header. This function frees the
2986 * original string if necessary.
2988 * Returns : JB_ERR_OK on success
2990 *********************************************************************/
2991 jb_err client_x_filter(struct client_state *csp, char **header)
2993 if ( 0 == strcmpic(*header, "X-Filter: No"))
2995 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2997 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3001 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3003 log_error(LOG_LEVEL_HEADER,
3004 "force-text-mode overruled the client's request to fetch without filtering!");
3008 csp->content_type = CT_TABOO;
3009 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
3010 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
3011 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3013 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3020 /* the following functions add headers directly to the header list */
3022 /*********************************************************************
3024 * Function : client_host_adder
3026 * Description : Adds the Host: header field if it is missing.
3027 * Called from `sed'.
3030 * 1 : csp = Current client state (buffers, headers, etc...)
3032 * Returns : JB_ERR_OK on success, or
3033 * JB_ERR_MEMORY on out-of-memory error.
3035 *********************************************************************/
3036 jb_err client_host_adder(struct client_state *csp)
3041 if ( !csp->http->hostport || !*(csp->http->hostport))
3047 * remove 'user:pass@' from 'proto://user:pass@host'
3049 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3055 p = csp->http->hostport;
3058 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3059 err = enlist_unique_header(csp->headers, "Host", p);
3065 /*********************************************************************
3067 * Function : client_cookie_adder
3069 * Description : Used in the add_client_headers list. Called from `sed'.
3072 * 1 : csp = Current client state (buffers, headers, etc...)
3074 * Returns : JB_ERR_OK on success, or
3075 * JB_ERR_MEMORY on out-of-memory error.
3077 *********************************************************************/
3078 jb_err client_cookie_adder(struct client_state *csp)
3080 struct list_entry *lst;
3082 struct list_entry *list1 = csp->cookie_list->first;
3083 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
3084 int first_cookie = 1;
3087 if ((list1 == NULL) && (list2 == NULL))
3093 tmp = strdup("Cookie: ");
3095 for (lst = list1; lst ; lst = lst->next)
3103 string_append(&tmp, "; ");
3105 string_append(&tmp, lst->str);
3108 for (lst = list2; lst ; lst = lst->next)
3116 string_append(&tmp, "; ");
3118 string_join(&tmp, cookie_encode(lst->str));
3123 return JB_ERR_MEMORY;
3126 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3127 err = enlist(csp->headers, tmp);
3133 /*********************************************************************
3135 * Function : client_accept_encoding_adder
3137 * Description : Add an Accept-Encoding header to the client's request
3138 * that disables compression if the action applies, and
3139 * the header is not already there. Called from `sed'.
3140 * Note: For HTTP/1.0, the absence of the header is enough.
3143 * 1 : csp = Current client state (buffers, headers, etc...)
3145 * Returns : JB_ERR_OK on success, or
3146 * JB_ERR_MEMORY on out-of-memory error.
3148 *********************************************************************/
3149 jb_err client_accept_encoding_adder(struct client_state *csp)
3151 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3152 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3154 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3161 /*********************************************************************
3163 * Function : client_xtra_adder
3165 * Description : Used in the add_client_headers list. Called from `sed'.
3168 * 1 : csp = Current client state (buffers, headers, etc...)
3170 * Returns : JB_ERR_OK on success, or
3171 * JB_ERR_MEMORY on out-of-memory error.
3173 *********************************************************************/
3174 jb_err client_xtra_adder(struct client_state *csp)
3176 struct list_entry *lst;
3179 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3180 lst ; lst = lst->next)
3182 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3183 err = enlist(csp->headers, lst->str);
3195 /*********************************************************************
3197 * Function : client_x_forwarded_adder
3199 * Description : Used in the add_client_headers list. Called from `sed'.
3202 * 1 : csp = Current client state (buffers, headers, etc...)
3204 * Returns : JB_ERR_OK on success, or
3205 * JB_ERR_MEMORY on out-of-memory error.
3207 *********************************************************************/
3208 jb_err client_x_forwarded_adder(struct client_state *csp)
3213 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3218 if (csp->x_forwarded)
3220 p = strdup(csp->x_forwarded);
3221 string_append(&p, ", ");
3225 p = strdup("X-Forwarded-For: ");
3227 string_append(&p, csp->ip_addr_str);
3231 return JB_ERR_MEMORY;
3234 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3235 err = enlist(csp->headers, p);
3242 /*********************************************************************
3244 * Function : connection_close_adder
3246 * Description : Adds a "Connection: close" header to csp->headers
3247 * as a temporary fix for the needed but missing HTTP/1.1
3248 * support. Called from `sed'.
3249 * FIXME: This whole function shouldn't be neccessary!
3252 * 1 : csp = Current client state (buffers, headers, etc...)
3254 * Returns : JB_ERR_OK on success, or
3255 * JB_ERR_MEMORY on out-of-memory error.
3257 *********************************************************************/
3258 jb_err connection_close_adder(struct client_state *csp)
3260 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3261 return enlist(csp->headers, "Connection: close");
3265 /*********************************************************************
3267 * Function : server_http
3269 * Description : - Save the HTTP Status into csp->http->status
3270 * - Set CT_TABOO to prevent filtering if the answer
3271 * is a partial range (HTTP status 206)
3272 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3276 * 1 : csp = Current client state (buffers, headers, etc...)
3277 * 2 : header = On input, pointer to header to modify.
3278 * On output, pointer to the modified header, or NULL
3279 * to remove the header. This function frees the
3280 * original string if necessary.
3282 * Returns : JB_ERR_OK on success, or
3283 * JB_ERR_MEMORY on out-of-memory error.
3285 *********************************************************************/
3286 jb_err server_http(struct client_state *csp, char **header)
3288 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3289 if (csp->http->status == 206)
3291 csp->content_type = CT_TABOO;
3294 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3297 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3304 /*********************************************************************
3306 * Function : server_set_cookie
3308 * Description : Handle the server "cookie" header properly.
3309 * Log cookie to the jar file. Then "crunch",
3310 * accept or rewrite it to a session cookie.
3311 * Called from `sed'.
3313 * TODO: Allow the user to specify a new expiration
3314 * time to cause the cookie to expire even before the
3315 * browser is closed.
3318 * 1 : csp = Current client state (buffers, headers, etc...)
3319 * 2 : header = On input, pointer to header to modify.
3320 * On output, pointer to the modified header, or NULL
3321 * to remove the header. This function frees the
3322 * original string if necessary.
3324 * Returns : JB_ERR_OK on success, or
3325 * JB_ERR_MEMORY on out-of-memory error.
3327 *********************************************************************/
3328 jb_err server_set_cookie(struct client_state *csp, char **header)
3333 struct tm tm_cookie;
3336 #ifdef FEATURE_COOKIE_JAR
3337 if (csp->config->jar)
3340 * Write timestamp into outbuf.
3342 * Complex because not all OSs have tm_gmtoff or
3343 * the %z field in strftime()
3345 char tempbuf[ BUFFER_SIZE ];
3347 #ifdef HAVE_LOCALTIME_R
3348 tm_now = *localtime_r(&now, &tm_now);
3349 #elif FEATURE_PTHREAD
3350 pthread_mutex_lock(&localtime_mutex);
3351 tm_now = *localtime (&now);
3352 pthread_mutex_unlock(&localtime_mutex);
3354 tm_now = *localtime (&now);
3356 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3358 /* strlen("set-cookie: ") = 12 */
3359 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3361 #endif /* def FEATURE_COOKIE_JAR */
3363 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3365 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
3366 return crumble(csp, header);
3368 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3370 /* Flag whether or not to log a message */
3373 /* A variable to store the tag we're working on */
3376 /* Skip "Set-Cookie:" (11 characters) in header */
3377 cur_tag = *header + 11;
3379 /* skip whitespace between "Set-Cookie:" and value */
3380 while (*cur_tag && ijb_isspace(*cur_tag))
3385 /* Loop through each tag in the cookie */
3389 char *next_tag = strchr(cur_tag, ';');
3390 if (next_tag != NULL)
3392 /* Skip the ';' character itself */
3395 /* skip whitespace ";" and start of tag */
3396 while (*next_tag && ijb_isspace(*next_tag))
3403 /* "Next tag" is the end of the string */
3404 next_tag = cur_tag + strlen(cur_tag);
3408 * Check the expiration date to see
3409 * if the cookie is still valid, if yes,
3410 * rewrite it to a session cookie.
3412 if (strncmpic(cur_tag, "expires=", 8) == 0)
3416 * Try the valid time formats we know about.
3418 * XXX: Maybe the log messages should be removed
3419 * for the next stable release. They just exist to
3420 * see which time format gets the most hits and
3421 * should be checked for first.
3423 if (NULL != (match = strptime(cur_tag, "expires=%a, %e-%b-%y %H:%M:%S ", &tm_cookie)))
3425 log_error(LOG_LEVEL_HEADER,
3426 "cookie \'%s\' send by %s appears to be using time format 1.",
3427 *header, csp->http->url);
3429 else if (NULL != (match = strptime(cur_tag, "expires=%A, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3431 log_error(LOG_LEVEL_HEADER,
3432 "cookie \'%s\' send by %s appears to be using time format 2.",
3433 *header, csp->http->url);
3436 else if (NULL != (match = strptime(cur_tag, "expires=%a, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3438 log_error(LOG_LEVEL_HEADER,
3439 "cookie \'%s\' send by %s appears to be using time format 3.",
3440 *header, csp->http->url);
3443 /* Did any of them match? */
3447 * Nope, treat it as if it was still valid.
3449 * XXX: Should we remove the whole cookie instead?
3451 log_error(LOG_LEVEL_ERROR,
3452 "Can't parse %s. Unsupported time format?", cur_tag);
3453 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3459 * Yes. Check if the cookie is still valid.
3461 * If the cookie is already expired it's probably
3462 * a delete cookie and even if it isn't, the browser
3463 * will discard it anyway.
3467 * XXX: timegm() isn't available on some AmigaOS
3468 * versions and our replacement doesn't work.
3470 * Our options are to either:
3472 * - disable session-cookies-only completely if timegm
3475 * - to simply remove all expired tags, like it has
3476 * been done until Privoxy 3.0.6 and to live with
3477 * the consequence that it can cause login/logout
3478 * problems on servers that don't validate their
3479 * input properly, or
3481 * - to replace it with mktime in which
3482 * case there is a slight chance of valid cookies
3483 * passing as already expired.
3485 * This is the way it's currently done and it's not
3486 * as bad as it sounds. If the missing GMT offset is
3487 * enough to change the result of the expiration check
3488 * the cookie will be only valid for a few hours
3489 * anyway, which in many cases will be shorter
3490 * than a browser session.
3492 cookie_time = timegm(&tm_cookie);
3493 if (cookie_time - now < 0)
3495 log_error(LOG_LEVEL_HEADER,
3496 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3497 /* Just in case some clown sets more then one expiration date */
3502 log_error(LOG_LEVEL_HEADER,
3503 "Cookie \'%s\' is still valid and has to be rewritten.", *header);
3506 * Delete the tag by copying the rest of the string over it.
3507 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3508 * since the behaviour of strcpy is undefined for overlapping
3511 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3513 /* That changed the header, need to issue a log message */
3517 * Note that the next tag has now been moved to *cur_tag,
3518 * so we do not need to update the cur_tag pointer.
3526 /* Move on to next cookie tag */
3533 assert(NULL != *header);
3534 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3543 #ifdef FEATURE_FORCE_LOAD
3544 /*********************************************************************
3546 * Function : strclean
3548 * Description : In-Situ-Eliminate all occurances of substring in
3552 * 1 : string = string to clean
3553 * 2 : substring = substring to eliminate
3555 * Returns : Number of eliminations
3557 *********************************************************************/
3558 int strclean(const char *string, const char *substring)
3564 len = strlen(substring);
3566 while((pos = strstr(string, substring)) != NULL)
3573 while (*p++ != '\0');
3580 #endif /* def FEATURE_FORCE_LOAD */
3582 /*********************************************************************
3584 * Function : parse_header_time
3586 * Description : Transforms time inside a HTTP header into
3587 * the usual time format.
3590 * 1 : header = header to parse
3591 * 2 : tm = storage for the resulting time in seconds
3593 * Returns : Time struct containing the header time, or
3594 * NULL in case of a parsing problems.
3596 *********************************************************************/
3597 struct tm *parse_header_time(char *header, time_t *tm) {
3601 struct tm * timeptr;
3604 * Initializing gmt to prevent time zone offsets.
3606 * While this is only necessary on some platforms
3607 * (mingw32 for example), I don't know how to
3608 * detect these automatically and doing it everywhere
3612 #ifdef HAVE_LOCALTIME_R
3613 gmt = *localtime_r(tm, &gmt);
3614 #elif FEATURE_PTHREAD
3615 pthread_mutex_lock(&localtime_mutex);
3616 gmt = *localtime(tm);
3617 pthread_mutex_unlock(&localtime_mutex);
3619 gmt = *localtime(tm);
3622 /* Skipping header name */
3623 timestring = strstr(header, ": ");
3624 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)
3637 /*********************************************************************
3639 * Function : get_destination_from_headers
3641 * Description : Parse the "Host:" header to get the request's destination.
3642 * Only needed if the client's request was forcefully
3643 * redirected into Privoxy.
3645 * Code mainly copied from client_host() which is currently
3646 * run too late for this purpose.
3649 * 1 : headers = List of headers (one of them hopefully being
3650 * the "Host:" header)
3651 * 2 : http = storage for the result (host, port and hostport).
3653 * Returns : JB_ERR_MEMORY in case of memory problems,
3654 * JB_ERR_PARSE if the host header couldn't be found,
3655 * JB_ERR_OK otherwise.
3657 *********************************************************************/
3658 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3664 host = get_header_value(headers, "Host:");
3668 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3669 return JB_ERR_PARSE;
3672 if (NULL == (p = strdup((host))))
3674 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3675 return JB_ERR_MEMORY;
3678 if (NULL == (q = strdup(p)))
3681 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3682 return JB_ERR_MEMORY;
3685 freez(http->hostport);
3689 q = strchr(http->host, ':');
3692 /* Terminate hostname and evaluate port string */
3694 http->port = atoi(q);
3698 http->port = http->ssl ? 443 : 80;
3701 /* Rebuild request URL */
3703 http->url = strdup(http->ssl ? "https://" : "http://");
3704 string_append(&http->url, http->hostport);
3705 string_append(&http->url, http->path);
3706 if (http->url == NULL)
3708 return JB_ERR_MEMORY;
3711 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",