1 const char parsers_rcs[] = "$Id: parsers.c,v 1.92 2007/03/05 13:25:32 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2007 the SourceForge
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
48 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
49 * - Handle "Cookie:" and "Connection:" headers a bit smarter
50 * (don't crunch them just to recreate them later on).
51 * - Add another non-standard time format for the cookie
52 * expiration date detection.
53 * - Fix a valgrind warning.
55 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
56 * Improve cookie expiration date detection.
58 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
59 * Don't run server_content_length() the first time
60 * sed() parses server headers; only adjust the
61 * Content-Length header if the page was modified.
63 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
64 * Fix log messages regarding the cookie time format
65 * (cookie and request URL were mixed up).
67 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
68 * - Let decompress_iob()
69 * - not corrupt the content if decompression fails
70 * early. (the first byte(s) were lost).
71 * - use pointer arithmetics with defined outcome for
73 * - Use a different kludge to remember a failed decompression.
75 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
76 * Search for Max-Forwards headers case-insensitive,
77 * don't generate the "501 unsupported" message for invalid
78 * Max-Forwards values and don't increase negative ones.
80 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
81 * - Let server_set_cookie() check the expiration date
82 * of cookies and don't touch the ones that are already
83 * expired. Fixes problems with low quality web applications
84 * as described in BR 932612.
86 * - Adjust comment in client_max_forwards to reality;
87 * remove invalid Max-Forwards headers.
89 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
90 * Stop filter_header() from unintentionally removing
91 * empty header lines that were enlisted by the continue
94 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
95 * - Repeat the request URL before logging any headers.
96 * Makes reading the log easier in case of simultaneous requests.
97 * - If there are more than one Content-Type headers in one request,
98 * use the first one and remove the others.
99 * - Remove "newval" variable in server_content_type().
100 * It's only used once.
102 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
103 * Correct a cast, check inflateEnd() exit code
104 * to see if we have to, replace sprintf calls
107 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
108 * Integrate a modified version of Wil Mahan's
109 * zlib patch (PR #895531).
111 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
112 * Skip empty filter files in filter_header()
113 * but don't ignore the ones that come afterwards.
114 * Fixes BR 1619208, this time for real.
116 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
117 * Reverted parts of my last commit
118 * to keep error handling working.
120 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
121 * Fixed gcc43 conversion warnings.
123 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
124 * Bringing back the "useless" localtime() call
125 * I removed in revision 1.67. On some platforms
126 * it's necessary to prevent time zone offsets.
128 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
129 * Rebuild request URL in get_destination_from_headers()
130 * to make sure redirect{pcrs command} works as expected
131 * for intercepted requests.
133 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
134 * Added get_destination_from_headers().
136 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
137 * Make pthread mutex locking more generic. Instead of
138 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
139 * and use mutex locking unless there is an _r function
140 * available. Better safe than sorry.
142 * Fixes "./configure --disable-pthread" and should result
143 * in less threading-related problems on pthread-using platforms,
144 * but it still doesn't fix BR#1122404.
146 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
147 * The special header "X-Filter: No" now disables
148 * header filtering as well.
150 * Revision 1.73 2006/09/23 13:26:38 roro
151 * Replace TABs by spaces in source code.
153 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
154 * Don't print a log message every time filter_headers is
155 * entered or left. It only creates noise without any real
158 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
159 * Fix +hide-if-modified-since{-n}.
161 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
162 * Have hide-if-modified-since interpret the random
163 * range value as minutes instead of hours. Allows
164 * more fine-grained configuration.
166 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
167 * Always have parse_header_time return a pointer
168 * that actual makes sense, even though we currently
169 * only need it to detect problems.
171 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
172 * Added config option enable-remote-http-toggle
173 * to specify if Privoxy should recognize special
174 * headers (currently only X-Filter) to change its
175 * behaviour. Disabled by default.
177 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
178 * After filtering de-chunked instances, remove
179 * "Transfer-Encoding" header entirely instead of changing
180 * it to "Transfer-Encoding: identity", which is invalid.
181 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
183 * Don't use localtime in parse_header_time. An empty time struct
184 * is good enough, it gets overwritten by strptime anyway.
186 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
187 * Use gmtime_r if available, fallback to gmtime with mutex
188 * protection for MacOSX and use vanilla gmtime for the rest.
190 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
191 * Changed client_referrer to use the right type (size_t) for
192 * hostlenght and to shorten the temporary referrer string with
193 * '\0' instead of adding a useless line break.
195 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
196 * - Back to timegm() using GnuPG's replacement if necessary.
197 * Using mktime() and localtime() could add a on hour offset if
198 * the randomize factor was big enough to lead to a summer/wintertime
201 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
203 * - Moved randomization code into pick_from_range().
205 * - Changed parse_header_time definition.
206 * time_t isn't guaranteed to be signed and
207 * if it isn't, -1 isn't available as error code.
208 * Changed some variable types in client_if_modified_since()
209 * because of the same reason.
211 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
212 * OS/2 compilation compatibility fixups
214 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
215 * Changed include from strptime.c to strptime.h
217 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
218 * Split filter-headers{} into filter-client-headers{}
219 * and filter-server-headers{}.
220 * Added parse_header_time() to share some code.
221 * Replaced timegm() with mktime().
223 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
224 * Windows service integration
226 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
227 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
229 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
230 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
231 * with what was really the latest development (the v_3_0_branch branch)
233 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
234 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
236 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
237 * Add the ability to check jpeg images for invalid
238 * lengths of comment blocks. Defensive strategy
239 * against the exploit:
240 * Microsoft Security Bulletin MS04-028
241 * Buffer Overrun in JPEG Processing (GDI+) Could
242 * Allow Code Execution (833987)
243 * Enabled with +inspect-jpegs in actions files.
245 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
246 * Excluded text/plain objects from filtering. This fixes a
247 * couple of client-crashing, download corruption and
248 * Privoxy performance issues, whose root cause lies in
249 * web servers labelling content of unknown type as text/plain.
251 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
252 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
254 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
255 * Completing the previous change
257 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
258 * Added temporary workaround for bug in PHP < 4.2.3
260 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
261 * 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.
263 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
264 * Fix typo: supressed -> suppressed
266 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
267 * Improved cookie logging
269 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
270 * Added basic support for OPTIONS and TRACE HTTP methods:
271 * - New parser function client_max_forwards which decrements
272 * the Max-Forwards HTTP header field of OPTIONS and TRACE
273 * requests by one before forwarding
274 * - New parser function client_host which extracts the host
275 * and port information from the HTTP header field if the
276 * request URI was not absolute
277 * - Don't crumble and re-add the Host: header, but only generate
278 * and append if missing
280 * Revision 1.56 2002/05/12 15:34:22 jongfoster
281 * Fixing typo in a comment
283 * Revision 1.55 2002/05/08 16:01:07 oes
284 * Optimized add_to_iob:
285 * - Use realloc instead of malloc(), memcpy(), free()
286 * - Expand to powers of two if possible, to get
287 * O(log n) reallocs instead of O(n).
288 * - Moved check for buffer limit here from chat
289 * - Report failure via returncode
291 * Revision 1.54 2002/04/02 15:03:16 oes
292 * Tiny code cosmetics
294 * Revision 1.53 2002/03/26 22:29:55 swa
295 * we have a new homepage!
297 * Revision 1.52 2002/03/24 13:25:43 swa
298 * name change related issues
300 * Revision 1.51 2002/03/13 00:27:05 jongfoster
303 * Revision 1.50 2002/03/12 01:45:35 oes
304 * More verbose logging
306 * Revision 1.49 2002/03/09 20:03:52 jongfoster
307 * - Making various functions return int rather than size_t.
308 * (Undoing a recent change). Since size_t is unsigned on
309 * Windows, functions like read_socket that return -1 on
310 * error cannot return a size_t.
312 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
313 * crashes, and also frequently caused JB to jump to 100%
314 * CPU and stay there. (Because it thought it had just
315 * read ((unsigned)-1) == 4Gb of data...)
317 * - The signature of write_socket has changed, it now simply
318 * returns success=0/failure=nonzero.
320 * - Trying to get rid of a few warnings --with-debug on
321 * Windows, I've introduced a new type "jb_socket". This is
322 * used for the socket file descriptors. On Windows, this
323 * is SOCKET (a typedef for unsigned). Everywhere else, it's
324 * an int. The error value can't be -1 any more, so it's
325 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
326 * Windows it maps to the #define INVALID_SOCKET.)
328 * - The signature of bind_port has changed.
330 * Revision 1.48 2002/03/07 03:46:53 oes
331 * Fixed compiler warnings etc
333 * Revision 1.47 2002/02/20 23:15:13 jongfoster
334 * Parsing functions now handle out-of-memory gracefully by returning
337 * Revision 1.46 2002/01/17 21:03:47 jongfoster
338 * Moving all our URL and URL pattern parsing code to urlmatch.c.
340 * Revision 1.45 2002/01/09 14:33:03 oes
341 * Added support for localtime_r.
343 * Revision 1.44 2001/12/14 01:22:54 steudten
344 * Remove 'user:pass@' from 'proto://user:pass@host' for the
345 * new added header 'Host: ..'. (See Req ID 491818)
347 * Revision 1.43 2001/11/23 00:26:38 jongfoster
348 * Fixing two really stupid errors in my previous commit
350 * Revision 1.42 2001/11/22 21:59:30 jongfoster
351 * Adding code to handle +no-cookies-keep
353 * Revision 1.41 2001/11/05 23:43:05 steudten
354 * Add time+date to log files.
356 * Revision 1.40 2001/10/26 20:13:09 jongfoster
357 * ctype.h is needed in Windows, too.
359 * Revision 1.39 2001/10/26 17:40:04 oes
360 * Introduced get_header_value()
361 * Removed http->user_agent, csp->referrer and csp->accept_types
362 * Removed client_accept()
364 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
365 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
366 * threads to call select() simultaneously. So, it's time to do a real, live,
367 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
368 * (native). Both versions will work, but using __OS2__ offers multi-threading.
370 * Revision 1.37 2001/10/23 21:36:02 jongfoster
371 * Documenting sed()'s error behaviou (doc change only)
373 * Revision 1.36 2001/10/13 12:51:51 joergs
374 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
375 * force-load), instead crumble Host: and add it (again) in client_host_adder
376 * (in case we get a HTTP/1.0 request without Host: header and forward it to
377 * a HTTP/1.1 server/proxy).
379 * Revision 1.35 2001/10/09 22:39:21 jongfoster
380 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
383 * Revision 1.34 2001/10/07 18:50:55 oes
384 * Added server_content_encoding, renamed server_transfer_encoding
386 * Revision 1.33 2001/10/07 18:04:49 oes
387 * Changed server_http11 to server_http and its pattern to "HTTP".
388 * Additional functionality: it now saves the HTTP status into
389 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
391 * Revision 1.32 2001/10/07 15:43:28 oes
392 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
393 * client_te and client_accept_encoding_adder, triggered by the new
394 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
395 * changed to allow only identity and chunked, and the TE header is
396 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
398 * parse_http_request no longer does anything than parsing. The rewriting
399 * of http->cmd and version mangling are gone. It now also recognizes
400 * the put and delete methods and saves the url in http->url. Removed
403 * renamed content_type and content_length to have the server_ prefix
405 * server_content_type now only works if csp->content_type != CT_TABOO
407 * added server_transfer_encoding, which
408 * - Sets CT_TABOO to prohibit filtering if encoding compresses
409 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
410 * - Change from "chunked" to "identity" if body was chunked
411 * but has been de-chunked for filtering.
413 * added server_content_md5 which crunches any Content-MD5 headers
414 * if the body was modified.
416 * made server_http11 conditional on +downgrade action
418 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
420 * Revision 1.31 2001/10/05 14:25:02 oes
421 * Crumble Keep-Alive from Server
423 * Revision 1.30 2001/09/29 12:56:03 joergs
424 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
426 * Revision 1.29 2001/09/24 21:09:24 jongfoster
427 * Fixing 2 memory leaks that Guy spotted, where the paramater to
428 * enlist() was not being free()d.
430 * Revision 1.28 2001/09/22 16:32:28 jongfoster
431 * Removing unused #includes.
433 * Revision 1.27 2001/09/20 15:45:25 steudten
435 * add casting from size_t to int for printf()
436 * remove local variable shadow s2
438 * Revision 1.26 2001/09/16 17:05:14 jongfoster
439 * Removing unused #include showarg.h
441 * Revision 1.25 2001/09/16 13:21:27 jongfoster
442 * Changes to use new list functions.
444 * Revision 1.24 2001/09/13 23:05:50 jongfoster
445 * Changing the string paramater to the header parsers a "const".
447 * Revision 1.23 2001/09/12 18:08:19 steudten
449 * In parse_http_request() header rewriting miss the host value, so
450 * from http://www.mydomain.com the result was just " / " not
451 * http://www.mydomain.com/ in case we forward.
453 * Revision 1.22 2001/09/10 10:58:53 oes
454 * Silenced compiler warnings
456 * Revision 1.21 2001/07/31 14:46:00 oes
457 * - Persistant connections now suppressed
458 * - sed() no longer appends empty header to csp->headers
460 * Revision 1.20 2001/07/30 22:08:36 jongfoster
461 * Tidying up #defines:
462 * - All feature #defines are now of the form FEATURE_xxx
463 * - Permanently turned off WIN_GUI_EDIT
464 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
466 * Revision 1.19 2001/07/25 17:21:54 oes
467 * client_uagent now saves copy of User-Agent: header value
469 * Revision 1.18 2001/07/13 14:02:46 oes
470 * - Included fix to repair broken HTTP requests that
471 * don't contain a path, not even '/'.
472 * - Removed all #ifdef PCRS
473 * - content_type now always inspected and classified as
474 * text, gif or other.
475 * - formatting / comments
477 * Revision 1.17 2001/06/29 21:45:41 oes
478 * Indentation, CRLF->LF, Tab-> Space
480 * Revision 1.16 2001/06/29 13:32:42 oes
482 * - Adapted free_http_request
483 * - Removed logentry from cancelled commit
485 * Revision 1.15 2001/06/03 19:12:38 oes
486 * deleted const struct interceptors
488 * Revision 1.14 2001/06/01 18:49:17 jongfoster
489 * Replaced "list_share" with "list" - the tiny memory gain was not
490 * worth the extra complexity.
492 * Revision 1.13 2001/05/31 21:30:33 jongfoster
493 * Removed list code - it's now in list.[ch]
494 * Renamed "permission" to "action", and changed many features
495 * to use the actions file rather than the global config.
497 * Revision 1.12 2001/05/31 17:33:13 oes
501 * Revision 1.11 2001/05/29 20:11:19 joergs
502 * '/ * inside comment' warning removed.
504 * Revision 1.10 2001/05/29 09:50:24 jongfoster
505 * Unified blocklist/imagelist/permissionslist.
506 * File format is still under discussion, but the internal changes
509 * Also modified interceptor behaviour:
510 * - We now intercept all URLs beginning with one of the following
511 * prefixes (and *only* these prefixes):
513 * * http://ijbswa.sf.net/config/
514 * * http://ijbswa.sourceforge.net/config/
515 * - New interceptors "home page" - go to http://i.j.b/ to see it.
516 * - Internal changes so that intercepted and fast redirect pages
517 * are not replaced with an image.
518 * - Interceptors now have the option to send a binary page direct
519 * to the client. (i.e. ijb-send-banner uses this)
520 * - Implemented show-url-info interceptor. (Which is why I needed
521 * the above interceptors changes - a typical URL is
522 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
523 * The previous mechanism would not have intercepted that, and
524 * if it had been intercepted then it then it would have replaced
527 * Revision 1.9 2001/05/28 17:26:33 jongfoster
528 * Fixing segfault if last header was crunched.
529 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
530 * can use the cross-platform sprintf() instead.)
532 * Revision 1.8 2001/05/27 22:17:04 oes
534 * - re_process_buffer no longer writes the modified buffer
535 * to the client, which was very ugly. It now returns the
536 * buffer, which it is then written by chat.
538 * - content_length now adjusts the Content-Length: header
539 * for modified documents rather than crunch()ing it.
540 * (Length info in csp->content_length, which is 0 for
541 * unmodified documents)
543 * - For this to work, sed() is called twice when filtering.
545 * Revision 1.7 2001/05/27 13:19:06 oes
546 * Patched Joergs solution for the content-length in.
548 * Revision 1.6 2001/05/26 13:39:32 jongfoster
549 * Only crunches Content-Length header if applying RE filtering.
550 * Without this fix, Microsoft Windows Update wouldn't work.
552 * Revision 1.5 2001/05/26 00:28:36 jongfoster
553 * Automatic reloading of config file.
554 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
555 * Most of the global variables have been moved to a new
556 * struct configuration_spec, accessed through csp->config->globalname
557 * Most of the globals remaining are used by the Win32 GUI.
559 * Revision 1.4 2001/05/22 18:46:04 oes
561 * - Enabled filtering banners by size rather than URL
562 * by adding patterns that replace all standard banner
563 * sizes with the "Junkbuster" gif to the re_filterfile
565 * - Enabled filtering WebBugs by providing a pattern
566 * which kills all 1x1 images
568 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
569 * which is selected by the (nonstandard and therefore
570 * capital) letter 'U' in the option string.
571 * It causes the quantifiers to be ungreedy by default.
572 * Appending a ? turns back to greedy (!).
574 * - Added a new interceptor ijb-send-banner, which
575 * sends back the "Junkbuster" gif. Without imagelist or
576 * MSIE detection support, or if tinygif = 1, or the
577 * URL isn't recognized as an imageurl, a lame HTML
578 * explanation is sent instead.
580 * - Added new feature, which permits blocking remote
581 * script redirects and firing back a local redirect
583 * The feature is conditionally compiled, i.e. it
584 * can be disabled with --disable-fast-redirects,
585 * plus it must be activated by a "fast-redirects"
586 * line in the config file, has its own log level
587 * and of course wants to be displayed by show-proxy-args
588 * Note: Boy, all the #ifdefs in 1001 locations and
589 * all the fumbling with configure.in and acconfig.h
590 * were *way* more work than the feature itself :-(
592 * - Because a generic redirect template was needed for
593 * this, tinygif = 3 now uses the same.
595 * - Moved GIFs, and other static HTTP response templates
600 * - Removed some >400 CRs again (Jon, you really worked
603 * Revision 1.3 2001/05/20 01:21:20 jongfoster
604 * Version 2.9.4 checkin.
605 * - Merged popupfile and cookiefile, and added control over PCRS
606 * filtering, in new "permissionsfile".
607 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
608 * file error you now get a message box (in the Win32 GUI) rather
609 * than the program exiting with no explanation.
610 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
612 * - Removed tabs from "config"
613 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
614 * - Bumped up version number.
616 * Revision 1.2 2001/05/17 23:02:36 oes
617 * - Made referrer option accept 'L' as a substitute for '§'
619 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
620 * Initial import of version 2.9.3 source tree
623 *********************************************************************/
630 #include <sys/types.h>
643 #if !defined(_WIN32) && !defined(__OS2__)
649 #ifdef FEATURE_PTHREAD
651 /* jcc.h is for mutex semapores only */
652 #endif /* def FEATURE_PTHREAD */
658 #include "jbsockets.h"
659 #include "miscutil.h"
662 #ifndef HAVE_STRPTIME
663 #include "strptime.h"
666 const char parsers_h_rcs[] = PARSERS_H_VERSION;
668 /* Fix a problem with Solaris. There should be no effect on other
670 * Solaris's isspace() is a macro which uses it's argument directly
671 * as an array index. Therefore we need to make sure that high-bit
672 * characters generate +ve values, and ideally we also want to make
673 * the argument match the declared parameter type of "int".
675 * Why did they write a character function that can't take a simple
676 * "char" argument? Doh!
678 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
679 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
682 const struct parsers client_patterns[] = {
683 { "referer:", 8, client_referrer },
684 { "user-agent:", 11, client_uagent },
685 { "ua-", 3, client_ua },
686 { "from:", 5, client_from },
687 { "cookie:", 7, client_send_cookie },
688 { "x-forwarded-for:", 16, client_x_forwarded },
689 { "Accept-Encoding:", 16, client_accept_encoding },
690 { "TE:", 3, client_te },
691 { "Host:", 5, client_host },
692 { "if-modified-since:", 18, client_if_modified_since },
693 { "Keep-Alive:", 11, crumble },
694 { "connection:", 11, connection },
695 { "proxy-connection:", 17, crumble },
696 { "max-forwards:", 13, client_max_forwards },
697 { "Accept-Language:", 16, client_accept_language },
698 { "if-none-match:", 14, client_if_none_match },
699 { "X-Filter:", 9, client_x_filter },
700 { "*", 0, crunch_client_header },
701 { "*", 0, filter_header },
705 const struct parsers server_patterns[] = {
706 { "HTTP", 4, server_http },
707 { "set-cookie:", 11, server_set_cookie },
708 { "connection:", 11, connection },
709 { "Content-Type:", 13, server_content_type },
710 { "Content-MD5:", 12, server_content_md5 },
711 { "Content-Encoding:", 17, server_content_encoding },
712 { "Transfer-Encoding:", 18, server_transfer_coding },
713 { "Keep-Alive:", 11, crumble },
714 { "content-disposition:", 20, server_content_disposition },
715 { "Last-Modified:", 14, server_last_modified },
716 { "*", 0, crunch_server_header },
717 { "*", 0, filter_header },
721 const struct parsers server_patterns_light[] = {
722 { "Content-Length:", 15, server_content_length },
723 { "Transfer-Encoding:", 18, server_transfer_coding },
725 { "Content-Encoding:", 17, server_content_encoding },
726 #endif /* def FEATURE_ZLIB */
730 const add_header_func_ptr add_client_headers[] = {
733 client_x_forwarded_adder,
735 /* Temporarily disabled: client_accept_encoding_adder, */
736 connection_close_adder,
741 const add_header_func_ptr add_server_headers[] = {
742 connection_close_adder,
746 /*********************************************************************
748 * Function : flush_socket
750 * Description : Write any pending "buffered" content.
753 * 1 : fd = file descriptor of the socket to read
754 * 2 : csp = Current client state (buffers, headers, etc...)
756 * Returns : On success, the number of bytes written are returned (zero
757 * indicates nothing was written). On error, -1 is returned,
758 * and errno is set appropriately. If count is zero and the
759 * file descriptor refers to a regular file, 0 will be
760 * returned without causing any other effect. For a special
761 * file, the results are not portable.
763 *********************************************************************/
764 int flush_socket(jb_socket fd, struct client_state *csp)
766 struct iob *iob = csp->iob;
767 int len = iob->eod - iob->cur;
774 if (write_socket(fd, iob->cur, (size_t)len))
778 iob->eod = iob->cur = iob->buf;
784 /*********************************************************************
786 * Function : add_to_iob
788 * Description : Add content to the buffered page, expanding the
789 * buffer if necessary.
792 * 1 : csp = Current client state (buffers, headers, etc...)
793 * 2 : buf = holds the content to be added to the page
794 * 3 : n = number of bytes to be added
796 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
797 * or buffer limit reached.
799 *********************************************************************/
800 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
802 struct iob *iob = csp->iob;
803 size_t used, offset, need, want;
806 if (n <= 0) return JB_ERR_OK;
808 used = (size_t)(iob->eod - iob->buf);
809 offset = (size_t)(iob->cur - iob->buf);
810 need = used + (size_t)n + 1;
813 * If the buffer can't hold the new data, extend it first.
814 * Use the next power of two if possible, else use the actual need.
816 if (need > csp->config->buffer_limit)
818 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
819 return JB_ERR_MEMORY;
822 if (need > iob->size)
824 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
826 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
830 else if (NULL != (p = (char *)realloc(iob->buf, need)))
836 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
837 return JB_ERR_MEMORY;
840 /* Update the iob pointers */
841 iob->cur = p + offset;
846 /* copy the new data into the iob buffer */
847 memcpy(iob->eod, buf, (size_t)n);
849 /* point to the end of the data */
852 /* null terminate == cheap insurance */
861 /*********************************************************************
863 * Function : decompress_iob
865 * Description : Decompress buffered page, expanding the
866 * buffer as necessary. csp->iob->cur
867 * should point to the the beginning of the
868 * compressed data block.
871 * 1 : csp = Current client state (buffers, headers, etc...)
873 * Returns : JB_ERR_OK on success,
874 * JB_ERR_MEMORY if out-of-memory limit reached, and
875 * JB_ERR_COMPRESS if error decompressing buffer.
877 *********************************************************************/
878 jb_err decompress_iob(struct client_state *csp)
880 char *buf; /* new, uncompressed buffer */
881 char *cur; /* Current iob position (to keep the original
882 * iob->cur unmodified if we return early) */
883 size_t bufsize; /* allocated size of the new buffer */
884 size_t skip_size; /* Number of bytes at the beginning of the iob
885 that we should NOT decompress. */
886 int status; /* return status of the inflate() call */
887 z_stream zstr; /* used by calls to zlib */
889 assert(csp->iob->cur - csp->iob->buf > 0);
890 assert(csp->iob->eod - csp->iob->cur > 0);
892 bufsize = csp->iob->size;
893 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
900 * This is to protect the parsing of gzipped data,
901 * but it should(?) be valid for deflated data also.
903 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
904 return JB_ERR_COMPRESS;
907 if (csp->content_type & CT_GZIP)
910 * Our task is slightly complicated by the facts that data
911 * compressed by gzip does not include a zlib header, and
912 * that there is no easily accessible interface in zlib to
913 * handle a gzip header. We strip off the gzip header by
914 * hand, and later inform zlib not to expect a header.
918 * Strip off the gzip header. Please see RFC 1952 for more
919 * explanation of the appropriate fields.
921 if ((*cur++ != (char)0x1f)
922 || (*cur++ != (char)0x8b)
923 || (*cur++ != Z_DEFLATED))
925 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
926 return JB_ERR_COMPRESS;
932 * XXX: These magic numbers should be replaced
933 * with macros to give a better idea what they do.
937 /* The gzip header has reserved bits set; bail out. */
938 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
939 return JB_ERR_COMPRESS;
943 /* Skip extra fields if necessary. */
947 * Skip a given number of bytes, specified
948 * as a 16-bit little-endian value.
951 * XXX: This code used to be:
953 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
955 * which I had to change into:
957 * cur += *cur++ + (*cur++ << 8);
959 * at which point gcc43 finally noticed that the value
960 * of cur is undefined (it depends on which of the
961 * summands is evaluated first).
963 * I haven't come across a site where this
964 * code is actually executed yet, but I hope
969 skip_bytes = *cur++ << 8;
971 assert(skip_bytes == *csp->iob->cur-2 + ((*csp->iob->cur-1) << 8));
974 * The number of bytes to skip should be positive
975 * and we'd like to stay in the buffer.
977 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
979 log_error (LOG_LEVEL_ERROR,
980 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
982 return JB_ERR_COMPRESS;
984 log_error (LOG_LEVEL_INFO,
985 "Skipping %d bytes for gzip compression. Does this sound right?",
990 /* Skip the filename if necessary. */
993 /* A null-terminated string follows. */
997 /* Skip the comment if necessary. */
1003 /* Skip the CRC if necessary. */
1010 else if (csp->content_type & CT_DEFLATE)
1013 * XXX: The debug level should be lowered
1014 * before the next stable release.
1016 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1018 * In theory (that is, according to RFC 1950), deflate-compressed
1019 * data should begin with a two-byte zlib header and have an
1020 * adler32 checksum at the end. It seems that in practice only
1021 * the raw compressed data is sent. Note that this means that
1022 * we are not RFC 1950-compliant here, but the advantage is that
1023 * this actually works. :)
1025 * We add a dummy null byte to tell zlib where the data ends,
1026 * and later inform it not to expect a header.
1028 * Fortunately, add_to_iob() has thoughtfully null-terminated
1029 * the buffer; we can just increment the end pointer to include
1036 log_error (LOG_LEVEL_ERROR,
1037 "Unable to determine compression format for decompression");
1038 return JB_ERR_COMPRESS;
1041 /* Set up the fields required by zlib. */
1042 zstr.next_in = (Bytef *)cur;
1043 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1044 zstr.zalloc = Z_NULL;
1045 zstr.zfree = Z_NULL;
1046 zstr.opaque = Z_NULL;
1049 * Passing -MAX_WBITS to inflateInit2 tells the library
1050 * that there is no zlib header.
1052 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1054 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1055 return JB_ERR_COMPRESS;
1059 * Next, we allocate new storage for the inflated data.
1060 * We don't modify the existing iob yet, so in case there
1061 * is error in decompression we can recover gracefully.
1063 buf = zalloc (bufsize);
1066 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1067 return JB_ERR_MEMORY;
1070 assert(bufsize >= skip_size);
1071 memcpy(buf, csp->iob->buf, skip_size);
1072 zstr.avail_out = bufsize - skip_size;
1073 zstr.next_out = (Bytef *)buf + skip_size;
1075 /* Try to decompress the whole stream in one shot. */
1076 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1078 /* We need to allocate more memory for the output buffer. */
1080 char *tmpbuf; /* used for realloc'ing the buffer */
1081 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1084 * If zlib wants more data then there's a problem, because
1085 * the complete compressed file should have been buffered.
1087 if (0 == zstr.avail_in)
1089 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1090 return JB_ERR_COMPRESS;
1094 * If we tried the limit and still didn't have enough
1095 * memory, just give up.
1097 if (bufsize == csp->config->buffer_limit)
1099 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1100 return JB_ERR_MEMORY;
1103 /* Try doubling the buffer size each time. */
1106 /* Don't exceed the buffer limit. */
1107 if (bufsize > csp->config->buffer_limit)
1109 bufsize = csp->config->buffer_limit;
1112 /* Try to allocate the new buffer. */
1113 tmpbuf = realloc(buf, bufsize);
1116 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1118 return JB_ERR_MEMORY;
1122 char *oldnext_out = (char *)zstr.next_out;
1125 * Update the fields for inflate() to use the new
1126 * buffer, which may be in a location different from
1129 zstr.avail_out += bufsize - oldbufsize;
1130 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1133 * Compare with an uglier method of calculating these values
1134 * that doesn't require the extra oldbufsize variable.
1136 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1137 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1138 assert(zstr.avail_out > 0);
1144 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1146 log_error(LOG_LEVEL_ERROR,
1147 "Inconsistent stream state after decompression: %s", zstr.msg);
1149 * XXX: Intentionally no return.
1151 * According to zlib.h, Z_STREAM_ERROR is returned
1152 * "if the stream state was inconsistent".
1154 * I assume in this case inflate()'s status
1155 * would also be something different than Z_STREAM_END
1156 * so this check should be redundant, but lets see.
1160 if (status != Z_STREAM_END)
1162 /* We failed to decompress the stream. */
1163 log_error(LOG_LEVEL_ERROR,
1164 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1165 return JB_ERR_COMPRESS;
1169 * Finally, we can actually update the iob, since the
1170 * decompression was successful. First, free the old
1173 freez(csp->iob->buf);
1175 /* Now, update the iob to use the new buffer. */
1176 csp->iob->buf = buf;
1177 csp->iob->cur = csp->iob->buf + skip_size;
1178 csp->iob->eod = (char *)zstr.next_out;
1179 csp->iob->size = bufsize;
1182 * Make sure the new uncompressed iob obeys some minimal
1183 * consistency conditions.
1185 if ((csp->iob->buf < csp->iob->cur)
1186 && (csp->iob->cur <= csp->iob->eod)
1187 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1189 char t = csp->iob->cur[100];
1190 csp->iob->cur[100] = '\0';
1192 * XXX: The debug level should be lowered
1193 * before the next stable release.
1195 log_error(LOG_LEVEL_INFO, "Sucessfully decompressed: %s", csp->iob->cur);
1196 csp->iob->cur[100] = t;
1201 /* It seems that zlib did something weird. */
1202 log_error(LOG_LEVEL_ERROR,
1203 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1204 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1205 csp->iob->eod, csp->iob->buf + csp->iob->size);
1206 return JB_ERR_COMPRESS;
1210 #endif /* defined(FEATURE_ZLIB) */
1213 /*********************************************************************
1215 * Function : get_header
1217 * Description : This (odd) routine will parse the csp->iob
1220 * 1 : csp = Current client state (buffers, headers, etc...)
1222 * Returns : Any one of the following:
1224 * 1) a pointer to a dynamically allocated string that contains a header line
1225 * 2) NULL indicating that the end of the header was reached
1226 * 3) "" indicating that the end of the iob was reached before finding
1227 * a complete header line.
1229 *********************************************************************/
1230 char *get_header(struct client_state *csp)
1236 if ((iob->cur == NULL)
1237 || ((p = strchr(iob->cur, '\n')) == NULL))
1239 return(""); /* couldn't find a complete header */
1244 ret = strdup(iob->cur);
1247 /* FIXME No way to handle error properly */
1248 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1253 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1255 /* is this a blank line (i.e. the end of the header) ? */
1267 /*********************************************************************
1269 * Function : get_header_value
1271 * Description : Get the value of a given header from a chained list
1272 * of header lines or return NULL if no such header is
1273 * present in the list.
1276 * 1 : header_list = pointer to list
1277 * 2 : header_name = string with name of header to look for.
1278 * Trailing colon required, capitalization
1281 * Returns : NULL if not found, else value of header
1283 *********************************************************************/
1284 char *get_header_value(const struct list *header_list, const char *header_name)
1286 struct list_entry *cur_entry;
1290 assert(header_list);
1291 assert(header_name);
1292 length = strlen(header_name);
1294 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1298 if (!strncmpic(cur_entry->str, header_name, length))
1301 * Found: return pointer to start of value
1303 ret = (char *) (cur_entry->str + length);
1304 while (*ret && ijb_isspace(*ret)) ret++;
1317 /*********************************************************************
1321 * Description : add, delete or modify lines in the HTTP header streams.
1322 * On entry, it receives a linked list of headers space
1323 * that was allocated dynamically (both the list nodes
1324 * and the header contents).
1326 * As a side effect it frees the space used by the original
1330 * 1 : pats = list of patterns to match against headers
1331 * 2 : more_headers = list of functions to add more
1332 * headers (client or server)
1333 * 3 : csp = Current client state (buffers, headers, etc...)
1335 * Returns : Single pointer to a fully formed header, or NULL
1336 * on out-of-memory error.
1338 *********************************************************************/
1339 char *sed(const struct parsers pats[],
1340 const add_header_func_ptr more_headers[],
1341 struct client_state *csp)
1343 struct list_entry *p;
1344 const struct parsers *v;
1345 const add_header_func_ptr *f;
1346 jb_err err = JB_ERR_OK;
1350 * If filtering is enabled, sed is run twice,
1351 * but most of the work needs to be done only once.
1353 first_run = (more_headers != NULL ) ? 1 : 0;
1355 if (first_run) /* Parse and print */
1357 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1358 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1360 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1362 /* Header crunch()ed in previous run? -> ignore */
1363 if (p->str == NULL) continue;
1365 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
1367 /* Does the current parser handle this header? */
1368 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1370 err = v->parser(csp, (char **)&(p->str));
1374 /* place any additional headers on the csp->headers list */
1375 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1380 else /* Parse only */
1383 * The second run is only needed if the body was modified
1384 * and the content-lenght has changed.
1386 if (strncmpic(csp->http->cmd, "HEAD", 4))
1388 /*XXX: Code duplication */
1389 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1391 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1393 /* Header crunch()ed in previous run? -> ignore */
1394 if (p->str == NULL) continue;
1396 /* Does the current parser handle this header? */
1397 if (strncmpic(p->str, v->str, v->len) == 0)
1399 err = v->parser(csp, (char **)&(p->str));
1406 if (err != JB_ERR_OK)
1411 return list_to_text(csp->headers);
1415 /* here begins the family of parser functions that reformat header lines */
1417 /*********************************************************************
1419 * Function : filter_header
1421 * Description : Executes all text substitutions from all applying
1422 * +(server|client)-header-filter actions on the header.
1423 * Most of the code was copied from pcrs_filter_response,
1424 * including the rather short variable names
1427 * 1 : csp = Current client state (buffers, headers, etc...)
1428 * 2 : header = On input, pointer to header to modify.
1429 * On output, pointer to the modified header, or NULL
1430 * to remove the header. This function frees the
1431 * original string if necessary.
1433 * Returns : JB_ERR_OK on success and always succeeds
1435 *********************************************************************/
1436 jb_err filter_header(struct client_state *csp, char **header)
1440 size_t size = strlen(*header);
1442 char *newheader = NULL;
1445 struct file_list *fl;
1446 struct re_filterfile_spec *b;
1447 struct list_entry *filtername;
1449 int i, found_filters = 0;
1450 int wanted_filter_type;
1451 int multi_action_index;
1453 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1455 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1456 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1460 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1461 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1465 * Need to check the set of re_filterfiles...
1467 for (i = 0; i < MAX_AF_FILES; i++)
1480 if (0 == found_filters)
1482 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1486 for (i = 0; i < MAX_AF_FILES; i++)
1489 if ((NULL == fl) || (NULL == fl->f))
1492 * Either there are no filter files
1493 * left, or this filter file just
1494 * contains no valid filters.
1496 * Continue to be sure we don't miss
1497 * valid filter files that are chained
1498 * after empty or invalid ones.
1503 * For all applying +filter actions, look if a filter by that
1504 * name exists and if yes, execute its pcrs_joblist on the
1507 for (b = fl->f; b; b = b->next)
1509 if (b->type != wanted_filter_type)
1511 /* Skip other filter types */
1515 for (filtername = csp->action->multi[multi_action_index]->first;
1516 filtername ; filtername = filtername->next)
1518 if (strcmp(b->name, filtername->str) == 0)
1520 int current_hits = 0;
1522 if ( NULL == b->joblist )
1524 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1528 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1529 *header, size, b->name);
1531 /* Apply all jobs from the joblist */
1532 for (job = b->joblist; NULL != job; job = job->next)
1534 matches = pcrs_execute(job, *header, size, &newheader, &size);
1537 current_hits += matches;
1538 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1540 *header = newheader;
1542 else if ( 0 == matches )
1544 /* Filter doesn't change header */
1550 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1551 *header, b->name, pcrs_strerror(matches));
1552 if( newheader != NULL)
1554 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1559 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1560 hits += current_hits;
1567 * Additionally checking for hits is important because if
1568 * the continue hack is triggered, server headers can
1569 * arrive empty to separate multiple heads from each other.
1571 if ((0 == size) && hits)
1573 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1581 /*********************************************************************
1583 * Function : connection
1585 * Description : Makes sure that the value of the Connection: header
1586 * is "close" and signals connection_close_adder
1590 * 1 : csp = Current client state (buffers, headers, etc...)
1591 * 2 : header = On input, pointer to header to modify.
1592 * On output, pointer to the modified header, or NULL
1593 * to remove the header. This function frees the
1594 * original string if necessary.
1596 * Returns : JB_ERR_OK on success, or
1597 * JB_ERR_MEMORY on out-of-memory error.
1599 *********************************************************************/
1600 jb_err connection(struct client_state *csp, char **header)
1602 char *old_header = *header;
1604 /* Do we have a 'Connection: close' header? */
1605 if (strcmpic(*header, "Connection: close"))
1607 /* No, create one */
1608 *header = strdup("Connection: close");
1611 return JB_ERR_MEMORY;
1613 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1617 /* Signal connection_close_adder() to return early. */
1618 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1620 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
1624 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
1631 /*********************************************************************
1633 * Function : crumble
1635 * Description : This is called if a header matches a pattern to "crunch"
1638 * 1 : csp = Current client state (buffers, headers, etc...)
1639 * 2 : header = On input, pointer to header to modify.
1640 * On output, pointer to the modified header, or NULL
1641 * to remove the header. This function frees the
1642 * original string if necessary.
1644 * Returns : JB_ERR_OK on success, or
1645 * JB_ERR_MEMORY on out-of-memory error.
1647 *********************************************************************/
1648 jb_err crumble(struct client_state *csp, char **header)
1650 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1655 /*********************************************************************
1657 * Function : crunch_server_header
1659 * Description : Crunch server header if it matches a string supplied by the
1660 * user. Called from `sed'.
1663 * 1 : csp = Current client state (buffers, headers, etc...)
1664 * 2 : header = On input, pointer to header to modify.
1665 * On output, pointer to the modified header, or NULL
1666 * to remove the header. This function frees the
1667 * original string if necessary.
1669 * Returns : JB_ERR_OK on success and always succeeds
1671 *********************************************************************/
1672 jb_err crunch_server_header(struct client_state *csp, char **header)
1674 const char *crunch_pattern;
1676 /* Do we feel like crunching? */
1677 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1679 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1681 /* Is the current header the lucky one? */
1682 if (strstr(*header, crunch_pattern))
1684 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1693 /*********************************************************************
1695 * Function : server_content_type
1697 * Description : Set the content-type for filterable types (text/.*,
1698 * .*xml.*, javascript and image/gif) unless filtering has been
1699 * forbidden (CT_TABOO) while parsing earlier headers.
1700 * NOTE: Since text/plain is commonly used by web servers
1701 * for files whose correct type is unknown, we don't
1702 * set CT_TEXT for it.
1705 * 1 : csp = Current client state (buffers, headers, etc...)
1706 * 2 : header = On input, pointer to header to modify.
1707 * On output, pointer to the modified header, or NULL
1708 * to remove the header. This function frees the
1709 * original string if necessary.
1711 * Returns : JB_ERR_OK on success, or
1712 * JB_ERR_MEMORY on out-of-memory error.
1714 *********************************************************************/
1715 jb_err server_content_type(struct client_state *csp, char **header)
1717 /* Remove header if it isn't the first Content-Type header */
1718 if(csp->content_type && (csp->content_type != CT_TABOO))
1721 * Another, slightly slower, way to see if
1722 * we already parsed another Content-Type header.
1724 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1726 log_error(LOG_LEVEL_ERROR,
1727 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1734 if (!(csp->content_type & CT_TABOO))
1736 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1737 || strstr(*header, "xml")
1738 || strstr(*header, "application/x-javascript"))
1740 csp->content_type |= CT_TEXT;
1742 else if (strstr(*header, " image/gif"))
1744 csp->content_type |= CT_GIF;
1746 else if (strstr(*header, " image/jpeg"))
1748 csp->content_type |= CT_JPEG;
1752 csp->content_type = 0;
1756 * Are we enabling text mode by force?
1758 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1761 * Do we really have to?
1763 if (csp->content_type & CT_TEXT)
1765 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1769 csp->content_type |= CT_TEXT;
1770 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1774 * Are we messing with the content type?
1776 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1779 * Make sure the user doesn't accidently
1780 * change the content type of binary documents.
1782 if (csp->content_type & CT_TEXT)
1785 *header = strdup("Content-Type: ");
1786 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1790 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1791 return JB_ERR_MEMORY;
1793 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1797 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1798 "Enable force-text-mode if you know what you're doing.", *header);
1805 /*********************************************************************
1807 * Function : server_transfer_coding
1809 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1810 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1811 * - Remove header if body was chunked but has been
1812 * de-chunked for filtering.
1815 * 1 : csp = Current client state (buffers, headers, etc...)
1816 * 2 : header = On input, pointer to header to modify.
1817 * On output, pointer to the modified header, or NULL
1818 * to remove the header. This function frees the
1819 * original string if necessary.
1821 * Returns : JB_ERR_OK on success, or
1822 * JB_ERR_MEMORY on out-of-memory error.
1824 *********************************************************************/
1825 jb_err server_transfer_coding(struct client_state *csp, char **header)
1828 * Turn off pcrs and gif filtering if body compressed
1830 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1834 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1836 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1837 csp->http->cmd, *header);
1838 #endif /* def FEATURE_ZLIB */
1839 csp->content_type = CT_TABOO;
1843 * Raise flag if body chunked
1845 if (strstr(*header, "chunked"))
1847 csp->flags |= CSP_FLAG_CHUNKED;
1850 * If the body was modified, it has been de-chunked first
1851 * and the header must be removed.
1853 * FIXME: If there is more than one transfer encoding,
1854 * only the "chunked" part should be removed here.
1856 if (csp->flags & CSP_FLAG_MODIFIED)
1858 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1867 /*********************************************************************
1869 * Function : server_content_encoding
1871 * Description : This function is run twice for each request,
1872 * unless FEATURE_ZLIB and filtering are disabled.
1874 * The first run is used to check if the content
1875 * is compressed, if FEATURE_ZLIB is disabled
1876 * filtering is then disabled as well, if FEATURE_ZLIB
1877 * is enabled the content is marked for decompression.
1879 * The second run is used to remove the Content-Encoding
1880 * header if the decompression was successful.
1883 * 1 : csp = Current client state (buffers, headers, etc...)
1884 * 2 : header = On input, pointer to header to modify.
1885 * On output, pointer to the modified header, or NULL
1886 * to remove the header. This function frees the
1887 * original string if necessary.
1889 * Returns : JB_ERR_OK on success, or
1890 * JB_ERR_MEMORY on out-of-memory error.
1892 *********************************************************************/
1893 jb_err server_content_encoding(struct client_state *csp, char **header)
1896 if ((csp->flags & CSP_FLAG_MODIFIED)
1897 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1900 * We successfully decompressed the content,
1901 * and have to clean the header now, so the
1902 * client no longer expects compressed data..
1904 * XXX: There is a difference between cleaning
1905 * and removing it completely.
1907 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1910 else if (strstr(*header, "gzip"))
1912 /* Mark for gzip decompression */
1913 csp->content_type |= CT_GZIP;
1915 else if (strstr(*header, "deflate"))
1917 /* Mark for zlib decompression */
1918 csp->content_type |= CT_DEFLATE;
1920 else if (strstr(*header, "compress"))
1923 * We can't decompress this; therefore we can't filter
1926 csp->content_type |= CT_TABOO;
1928 #else /* !defined(FEATURE_ZLIB) */
1929 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1932 * Body is compressed, turn off pcrs and gif filtering.
1934 csp->content_type |= CT_TABOO;
1936 #endif /* !defined(FEATURE_ZLIB) */
1943 /*********************************************************************
1945 * Function : server_content_length
1947 * Description : Adjust Content-Length header if we modified
1951 * 1 : csp = Current client state (buffers, headers, etc...)
1952 * 2 : header = On input, pointer to header to modify.
1953 * On output, pointer to the modified header, or NULL
1954 * to remove the header. This function frees the
1955 * original string if necessary.
1957 * Returns : JB_ERR_OK on success, or
1958 * JB_ERR_MEMORY on out-of-memory error.
1960 *********************************************************************/
1961 jb_err server_content_length(struct client_state *csp, char **header)
1963 const size_t max_header_length = 80;
1965 /* Regenerate header if the content was modified. */
1966 if (csp->flags & CSP_FLAG_MODIFIED)
1969 *header = (char *) zalloc(max_header_length);
1970 if (*header == NULL)
1972 return JB_ERR_MEMORY;
1975 snprintf(*header, max_header_length, "Content-Length: %d",
1976 (int)csp->content_length);
1977 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
1978 (int)csp->content_length);
1985 /*********************************************************************
1987 * Function : server_content_md5
1989 * Description : Crumble any Content-MD5 headers if the document was
1990 * modified. FIXME: Should we re-compute instead?
1993 * 1 : csp = Current client state (buffers, headers, etc...)
1994 * 2 : header = On input, pointer to header to modify.
1995 * On output, pointer to the modified header, or NULL
1996 * to remove the header. This function frees the
1997 * original string if necessary.
1999 * Returns : JB_ERR_OK on success, or
2000 * JB_ERR_MEMORY on out-of-memory error.
2002 *********************************************************************/
2003 jb_err server_content_md5(struct client_state *csp, char **header)
2005 if (csp->flags & CSP_FLAG_MODIFIED)
2007 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2014 /*********************************************************************
2016 * Function : server_content_disposition
2018 * Description : If enabled, blocks or modifies the "content-disposition" header.
2019 * Called from `sed'.
2022 * 1 : csp = Current client state (buffers, headers, etc...)
2023 * 2 : header = On input, pointer to header to modify.
2024 * On output, pointer to the modified header, or NULL
2025 * to remove the header. This function frees the
2026 * original string if necessary.
2028 * Returns : JB_ERR_OK on success, or
2029 * JB_ERR_MEMORY on out-of-memory error.
2031 *********************************************************************/
2032 jb_err server_content_disposition(struct client_state *csp, char **header)
2037 * Are we messing with the content-disposition header?
2039 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2045 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2047 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2050 * Blocking content-disposition header
2052 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2059 * Replacing content-disposition header
2062 *header = strdup("content-disposition: ");
2063 string_append(header, newval);
2065 if (*header == NULL)
2067 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2071 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2074 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2077 /*********************************************************************
2079 * Function : server_last_modified
2081 * Description : Changes Last-Modified header to the actual date
2082 * to help hide-if-modified-since.
2083 * Called from `sed'.
2086 * 1 : csp = Current client state (buffers, headers, etc...)
2087 * 2 : header = On input, pointer to header to modify.
2088 * On output, pointer to the modified header, or NULL
2089 * to remove the header. This function frees the
2090 * original string if necessary.
2092 * Returns : JB_ERR_OK on success, or
2093 * JB_ERR_MEMORY on out-of-memory error.
2095 *********************************************************************/
2096 jb_err server_last_modified(struct client_state *csp, char **header)
2099 char buf[BUFFER_SIZE];
2102 #ifdef HAVE_GMTIME_R
2105 struct tm *timeptr = NULL;
2106 time_t now, last_modified;
2108 long int days, hours, minutes, seconds;
2111 * Are we messing with the Last-Modified header?
2113 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2119 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2121 if (0 == strcmpic(newval, "block") )
2124 * Blocking Last-Modified header. Useless but why not.
2126 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2130 else if (0 == strcmpic(newval, "reset-to-request-time"))
2133 * Setting Last-Modified Header to now.
2135 get_http_time(0, buf);
2137 *header = strdup("Last-Modified: ");
2138 string_append(header, buf);
2140 if (*header == NULL)
2142 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2146 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2149 else if (0 == strcmpic(newval, "randomize"))
2151 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2153 #ifdef HAVE_GMTIME_R
2154 timeptr = gmtime_r(&now, &gmt);
2155 #elif FEATURE_PTHREAD
2156 pthread_mutex_lock(&gmtime_mutex);
2157 timeptr = gmtime(&now);
2158 pthread_mutex_unlock(&gmtime_mutex);
2160 timeptr = gmtime(&now);
2162 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
2164 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2169 rtime = (long int)difftime(now, last_modified);
2172 rtime = pick_from_range(rtime);
2173 last_modified += rtime;
2174 #ifdef HAVE_GMTIME_R
2175 timeptr = gmtime_r(&last_modified, &gmt);
2176 #elif FEATURE_PTHREAD
2177 pthread_mutex_lock(&gmtime_mutex);
2178 timeptr = gmtime(&last_modified);
2179 pthread_mutex_unlock(&gmtime_mutex);
2181 timeptr = gmtime(&last_modified);
2183 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2185 *header = strdup("Last-Modified: ");
2186 string_append(header, newheader);
2188 if (*header == NULL)
2190 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2191 return JB_ERR_MEMORY;
2194 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2196 days = rtime / (3600 * 24);
2197 hours = rtime / 3600 % 24;
2198 minutes = rtime / 60 % 60;
2199 seconds = rtime % 60;
2201 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2202 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2203 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2208 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2217 /*********************************************************************
2219 * Function : client_accept_encoding
2221 * Description : Rewrite the client's Accept-Encoding header so that
2222 * if doesn't allow compression, if the action applies.
2223 * Note: For HTTP/1.0 the absence of the header is enough.
2226 * 1 : csp = Current client state (buffers, headers, etc...)
2227 * 2 : header = On input, pointer to header to modify.
2228 * On output, pointer to the modified header, or NULL
2229 * to remove the header. This function frees the
2230 * original string if necessary.
2232 * Returns : JB_ERR_OK on success, or
2233 * JB_ERR_MEMORY on out-of-memory error.
2235 *********************************************************************/
2236 jb_err client_accept_encoding(struct client_state *csp, char **header)
2238 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2240 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2244 /* Temporarily disable the correct behaviour to
2245 * work around a PHP bug.
2247 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2249 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2250 * if (*header == NULL)
2252 * return JB_ERR_MEMORY;
2263 /*********************************************************************
2265 * Function : client_te
2267 * Description : Rewrite the client's TE header so that
2268 * if doesn't allow compression, if the action applies.
2271 * 1 : csp = Current client state (buffers, headers, etc...)
2272 * 2 : header = On input, pointer to header to modify.
2273 * On output, pointer to the modified header, or NULL
2274 * to remove the header. This function frees the
2275 * original string if necessary.
2277 * Returns : JB_ERR_OK on success, or
2278 * JB_ERR_MEMORY on out-of-memory error.
2280 *********************************************************************/
2281 jb_err client_te(struct client_state *csp, char **header)
2283 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2286 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2292 /*********************************************************************
2294 * Function : client_referrer
2296 * Description : Handle the "referer" config setting properly.
2297 * Called from `sed'.
2300 * 1 : csp = Current client state (buffers, headers, etc...)
2301 * 2 : header = On input, pointer to header to modify.
2302 * On output, pointer to the modified header, or NULL
2303 * to remove the header. This function frees the
2304 * original string if necessary.
2306 * Returns : JB_ERR_OK on success, or
2307 * JB_ERR_MEMORY on out-of-memory error.
2309 *********************************************************************/
2310 jb_err client_referrer(struct client_state *csp, char **header)
2317 #ifdef FEATURE_FORCE_LOAD
2318 /* Since the referrer can include the prefix even
2319 * if the request itself is non-forced, we must
2320 * clean it unconditionally
2322 strclean(*header, FORCE_PREFIX);
2323 #endif /* def FEATURE_FORCE_LOAD */
2326 * Are we sending referer?
2328 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2333 newval = csp->action->string[ACTION_STRING_REFERER];
2335 if ((0 != strcmpic(newval, "conditional-block")))
2339 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2344 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2347 else if (0 == strcmpic(newval, "conditional-block"))
2350 * Block referer if host has changed.
2353 if (NULL == (host = strdup(csp->http->hostport)))
2356 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2357 return JB_ERR_MEMORY;
2359 if (NULL == (referer = strdup(*header)))
2363 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2364 return JB_ERR_MEMORY;
2366 hostlenght = strlen(host);
2367 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2369 /*Shorten referer to make sure the referer is blocked
2370 *if www.example.org/www.example.com-shall-see-the-referer/
2371 *links to www.example.com/
2373 referer[hostlenght+17] = '\0';
2375 if ( 0 == strstr(referer, host)) /*Host has changed*/
2377 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2382 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2388 else if (0 != strcmpic(newval, "forge"))
2391 * We have a specific (fixed) referer we want to send.
2393 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2395 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2397 *header = strdup("Referer: ");
2398 string_append(header, newval);
2399 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2401 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2406 * Forge a referer as http://[hostname:port of REQUEST]/
2407 * to fool stupid checks for in-site links
2410 *header = strdup("Referer: http://");
2411 string_append(header, csp->http->hostport);
2412 string_append(header, "/");
2413 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2415 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2419 /*********************************************************************
2421 * Function : client_accept_language
2423 * Description : Handle the "Accept-Language" config setting properly.
2424 * Called from `sed'.
2427 * 1 : csp = Current client state (buffers, headers, etc...)
2428 * 2 : header = On input, pointer to header to modify.
2429 * On output, pointer to the modified header, or NULL
2430 * to remove the header. This function frees the
2431 * original string if necessary.
2433 * Returns : JB_ERR_OK on success, or
2434 * JB_ERR_MEMORY on out-of-memory error.
2436 *********************************************************************/
2437 jb_err client_accept_language(struct client_state *csp, char **header)
2442 * Are we messing with the Accept-Language?
2444 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2446 /*I don't think so*/
2450 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2452 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2455 * Blocking Accept-Language header
2457 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2464 * Replacing Accept-Language header
2467 *header = strdup("Accept-Language: ");
2468 string_append(header, newval);
2470 if (*header == NULL)
2472 log_error(LOG_LEVEL_ERROR,
2473 "Insufficent memory. Accept-Language header crunched without replacement.");
2477 log_error(LOG_LEVEL_HEADER,
2478 "Accept-Language header crunched and replaced with: %s", *header);
2481 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2484 /*********************************************************************
2486 * Function : crunch_client_header
2488 * Description : Crunch client header if it matches a string supplied by the
2489 * user. Called from `sed'.
2492 * 1 : csp = Current client state (buffers, headers, etc...)
2493 * 2 : header = On input, pointer to header to modify.
2494 * On output, pointer to the modified header, or NULL
2495 * to remove the header. This function frees the
2496 * original string if necessary.
2498 * Returns : JB_ERR_OK on success and always succeeds
2500 *********************************************************************/
2501 jb_err crunch_client_header(struct client_state *csp, char **header)
2503 const char *crunch_pattern;
2505 /* Do we feel like crunching? */
2506 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2508 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2510 /* Is the current header the lucky one? */
2511 if (strstr(*header, crunch_pattern))
2513 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2521 /*********************************************************************
2523 * Function : client_uagent
2525 * Description : Handle the "user-agent" config setting properly
2526 * and remember its original value to enable browser
2527 * bug workarounds. Called from `sed'.
2530 * 1 : csp = Current client state (buffers, headers, etc...)
2531 * 2 : header = On input, pointer to header to modify.
2532 * On output, pointer to the modified header, or NULL
2533 * to remove the header. This function frees the
2534 * original string if necessary.
2536 * Returns : JB_ERR_OK on success, or
2537 * JB_ERR_MEMORY on out-of-memory error.
2539 *********************************************************************/
2540 jb_err client_uagent(struct client_state *csp, char **header)
2544 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2549 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2556 *header = strdup("User-Agent: ");
2557 string_append(header, newval);
2559 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2561 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2564 /*********************************************************************
2566 * Function : client_ua
2568 * Description : Handle "ua-" headers properly. Called from `sed'.
2571 * 1 : csp = Current client state (buffers, headers, etc...)
2572 * 2 : header = On input, pointer to header to modify.
2573 * On output, pointer to the modified header, or NULL
2574 * to remove the header. This function frees the
2575 * original string if necessary.
2577 * Returns : JB_ERR_OK on success, or
2578 * JB_ERR_MEMORY on out-of-memory error.
2580 *********************************************************************/
2581 jb_err client_ua(struct client_state *csp, char **header)
2583 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2585 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2593 /*********************************************************************
2595 * Function : client_from
2597 * Description : Handle the "from" config setting properly.
2598 * Called from `sed'.
2601 * 1 : csp = Current client state (buffers, headers, etc...)
2602 * 2 : header = On input, pointer to header to modify.
2603 * On output, pointer to the modified header, or NULL
2604 * to remove the header. This function frees the
2605 * original string if necessary.
2607 * Returns : JB_ERR_OK on success, or
2608 * JB_ERR_MEMORY on out-of-memory error.
2610 *********************************************************************/
2611 jb_err client_from(struct client_state *csp, char **header)
2615 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2622 newval = csp->action->string[ACTION_STRING_FROM];
2625 * Are we blocking the e-mail address?
2627 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2629 log_error(LOG_LEVEL_HEADER, "crunched From!");
2633 log_error(LOG_LEVEL_HEADER, " modified");
2635 *header = strdup("From: ");
2636 string_append(header, newval);
2638 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2642 /*********************************************************************
2644 * Function : client_send_cookie
2646 * Description : Crunches the "cookie" header if necessary.
2647 * Called from `sed'.
2649 * XXX: Stupid name, doesn't send squat.
2652 * 1 : csp = Current client state (buffers, headers, etc...)
2653 * 2 : header = On input, pointer to header to modify.
2654 * On output, pointer to the modified header, or NULL
2655 * to remove the header. This function frees the
2656 * original string if necessary.
2658 * Returns : JB_ERR_OK on success, or
2659 * JB_ERR_MEMORY on out-of-memory error.
2661 *********************************************************************/
2662 jb_err client_send_cookie(struct client_state *csp, char **header)
2664 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2666 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2674 /*********************************************************************
2676 * Function : client_x_forwarded
2678 * Description : Handle the "x-forwarded-for" config setting properly,
2679 * also used in the add_client_headers list. Called from `sed'.
2682 * 1 : csp = Current client state (buffers, headers, etc...)
2683 * 2 : header = On input, pointer to header to modify.
2684 * On output, pointer to the modified header, or NULL
2685 * to remove the header. This function frees the
2686 * original string if necessary.
2688 * Returns : JB_ERR_OK on success, or
2689 * JB_ERR_MEMORY on out-of-memory error.
2691 *********************************************************************/
2692 jb_err client_x_forwarded(struct client_state *csp, char **header)
2694 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2696 /* Save it so we can re-add it later */
2697 freez(csp->x_forwarded);
2698 csp->x_forwarded = *header;
2701 * Always set *header = NULL, since this information
2702 * will be sent at the end of the header.
2709 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2716 /*********************************************************************
2718 * Function : client_max_forwards
2720 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2721 * from the value of the Max-Forwards header field.
2724 * 1 : csp = Current client state (buffers, headers, etc...)
2725 * 2 : header = On input, pointer to header to modify.
2726 * On output, pointer to the modified header, or NULL
2727 * to remove the header. This function frees the
2728 * original string if necessary.
2730 * Returns : JB_ERR_OK on success, or
2731 * JB_ERR_MEMORY on out-of-memory error.
2733 *********************************************************************/
2734 jb_err client_max_forwards(struct client_state *csp, char **header)
2738 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2739 (0 == strcmpic(csp->http->gpc, "options")))
2741 assert(*(*header+12) == ':');
2742 if (1 == sscanf(*header+12, ": %u", &max_forwards))
2744 if (max_forwards > 0)
2746 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
2747 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
2748 csp->http->gpc, max_forwards);
2750 else if (max_forwards < 0)
2752 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2758 * Not supposed to be reached. direct_response() which
2759 * was already called earlier in chat() should have
2760 * intercepted the request.
2762 log_error(LOG_LEVEL_ERROR,
2763 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2764 assert(max_forwards != 0);
2769 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2778 /*********************************************************************
2780 * Function : client_host
2782 * Description : If the request URI did not contain host and
2783 * port information, parse and evaluate the Host
2786 * Also, kill ill-formed HOST: headers as sent by
2787 * Apple's iTunes software when used with a proxy.
2790 * 1 : csp = Current client state (buffers, headers, etc...)
2791 * 2 : header = On input, pointer to header to modify.
2792 * On output, pointer to the modified header, or NULL
2793 * to remove the header. This function frees the
2794 * original string if necessary.
2796 * Returns : JB_ERR_OK on success, or
2797 * JB_ERR_MEMORY on out-of-memory error.
2799 *********************************************************************/
2800 jb_err client_host(struct client_state *csp, char **header)
2805 * If the header field name is all upper-case, chances are that it's
2806 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2807 * not a problem -- they are regenerated later.
2809 if ((*header)[1] == 'O')
2811 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2816 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2817 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2820 if (NULL == (p = strdup((*header)+6)))
2822 return JB_ERR_MEMORY;
2825 if (NULL == (q = strdup(p)))
2828 return JB_ERR_MEMORY;
2831 freez(csp->http->hostport);
2832 csp->http->hostport = p;
2833 freez(csp->http->host);
2834 csp->http->host = q;
2835 q = strchr(csp->http->host, ':');
2838 /* Terminate hostname and evaluate port string */
2840 csp->http->port = atoi(q);
2844 csp->http->port = csp->http->ssl ? 443 : 80;
2847 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2848 csp->http->hostport, csp->http->host, csp->http->port);
2851 /* Signal client_host_adder() to return right away */
2852 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
2857 /*********************************************************************
2859 * Function : client_if_modified_since
2861 * Description : Remove or modify the If-Modified-Since header.
2864 * 1 : csp = Current client state (buffers, headers, etc...)
2865 * 2 : header = On input, pointer to header to modify.
2866 * On output, pointer to the modified header, or NULL
2867 * to remove the header. This function frees the
2868 * original string if necessary.
2870 * Returns : JB_ERR_OK on success, or
2871 * JB_ERR_MEMORY on out-of-memory error.
2873 *********************************************************************/
2874 jb_err client_if_modified_since(struct client_state *csp, char **header)
2877 #ifdef HAVE_GMTIME_R
2880 struct tm *timeptr = NULL;
2884 long int hours, minutes, seconds;
2888 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2891 * The client got an error message because of a temporary problem,
2892 * the problem is gone and the client now tries to revalidate our
2893 * error message on the real server. The revalidation would always
2894 * end with the transmission of the whole document and there is
2895 * no need to expose the bogus If-Modified-Since header.
2897 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2900 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2902 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2904 if ((0 == strcmpic(newval, "block")))
2906 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2909 else /* add random value */
2911 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2913 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2918 rtime = strtol(newval, &endptr, 0);
2921 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2922 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2929 rtime = pick_from_range(rtime);
2933 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2936 tm += rtime * (negative ? -1 : 1);
2937 #ifdef HAVE_GMTIME_R
2938 timeptr = gmtime_r(&tm, &gmt);
2939 #elif FEATURE_PTHREAD
2940 pthread_mutex_lock(&gmtime_mutex);
2941 timeptr = gmtime(&tm);
2942 pthread_mutex_unlock(&gmtime_mutex);
2944 timeptr = gmtime(&tm);
2946 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2949 *header = strdup("If-Modified-Since: ");
2950 string_append(header, newheader);
2952 if (*header == NULL)
2954 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2955 return JB_ERR_MEMORY;
2958 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2960 hours = rtime / 3600;
2961 minutes = rtime / 60 % 60;
2962 seconds = rtime % 60;
2964 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2965 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2966 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2975 /*********************************************************************
2977 * Function : client_if_none_match
2979 * Description : Remove the If-None-Match header.
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, or
2989 * JB_ERR_MEMORY on out-of-memory error.
2991 *********************************************************************/
2992 jb_err client_if_none_match(struct client_state *csp, char **header)
2994 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2996 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3003 /*********************************************************************
3005 * Function : client_x_filter
3007 * Description : Disables filtering if the client set "X-Filter: No".
3008 * Called from `sed'.
3011 * 1 : csp = Current client state (buffers, headers, etc...)
3012 * 2 : header = On input, pointer to header to modify.
3013 * On output, pointer to the modified header, or NULL
3014 * to remove the header. This function frees the
3015 * original string if necessary.
3017 * Returns : JB_ERR_OK on success
3019 *********************************************************************/
3020 jb_err client_x_filter(struct client_state *csp, char **header)
3022 if ( 0 == strcmpic(*header, "X-Filter: No"))
3024 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3026 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3030 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3032 log_error(LOG_LEVEL_HEADER,
3033 "force-text-mode overruled the client's request to fetch without filtering!");
3037 csp->content_type = CT_TABOO;
3038 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
3039 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
3040 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3042 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3049 /* the following functions add headers directly to the header list */
3051 /*********************************************************************
3053 * Function : client_host_adder
3055 * Description : Adds the Host: header field if it is missing.
3056 * Called from `sed'.
3059 * 1 : csp = Current client state (buffers, headers, etc...)
3061 * Returns : JB_ERR_OK on success, or
3062 * JB_ERR_MEMORY on out-of-memory error.
3064 *********************************************************************/
3065 jb_err client_host_adder(struct client_state *csp)
3070 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3072 /* Header already set by the client, nothing to do. */
3076 if ( !csp->http->hostport || !*(csp->http->hostport))
3078 /* XXX: When does this happen and why is it OK? */
3079 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3084 * remove 'user:pass@' from 'proto://user:pass@host'
3086 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3092 p = csp->http->hostport;
3095 /* XXX: Just add it, we already made sure that it will be unique */
3096 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3097 err = enlist_unique_header(csp->headers, "Host", p);
3103 /*********************************************************************
3105 * Function : client_cookie_adder
3107 * Description : Used in the add_client_headers list. Called from `sed'.
3109 * XXX: Remove csp->cookie_list which is no longer used.
3112 * 1 : csp = Current client state (buffers, headers, etc...)
3114 * Returns : JB_ERR_OK on success, or
3115 * JB_ERR_MEMORY on out-of-memory error.
3117 *********************************************************************/
3118 jb_err client_cookie_adder(struct client_state *csp)
3120 struct list_entry *lst;
3122 struct list_entry *list1 = csp->cookie_list->first;
3123 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
3124 int first_cookie = 1;
3127 if ((list1 == NULL) && (list2 == NULL))
3133 tmp = strdup("Cookie: ");
3135 for (lst = list1; lst ; lst = lst->next)
3143 string_append(&tmp, "; ");
3145 string_append(&tmp, lst->str);
3148 for (lst = list2; lst ; lst = lst->next)
3156 string_append(&tmp, "; ");
3158 string_join(&tmp, cookie_encode(lst->str));
3163 return JB_ERR_MEMORY;
3166 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3167 err = enlist(csp->headers, tmp);
3173 /*********************************************************************
3175 * Function : client_accept_encoding_adder
3177 * Description : Add an Accept-Encoding header to the client's request
3178 * that disables compression if the action applies, and
3179 * the header is not already there. Called from `sed'.
3180 * Note: For HTTP/1.0, the absence of the header is enough.
3183 * 1 : csp = Current client state (buffers, headers, etc...)
3185 * Returns : JB_ERR_OK on success, or
3186 * JB_ERR_MEMORY on out-of-memory error.
3188 *********************************************************************/
3189 jb_err client_accept_encoding_adder(struct client_state *csp)
3191 assert(0); /* Not in use */
3193 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3194 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3196 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3203 /*********************************************************************
3205 * Function : client_xtra_adder
3207 * Description : Used in the add_client_headers list. Called from `sed'.
3210 * 1 : csp = Current client state (buffers, headers, etc...)
3212 * Returns : JB_ERR_OK on success, or
3213 * JB_ERR_MEMORY on out-of-memory error.
3215 *********************************************************************/
3216 jb_err client_xtra_adder(struct client_state *csp)
3218 struct list_entry *lst;
3221 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3222 lst ; lst = lst->next)
3224 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3225 err = enlist(csp->headers, lst->str);
3237 /*********************************************************************
3239 * Function : client_x_forwarded_adder
3241 * Description : Used in the add_client_headers list. Called from `sed'.
3244 * 1 : csp = Current client state (buffers, headers, etc...)
3246 * Returns : JB_ERR_OK on success, or
3247 * JB_ERR_MEMORY on out-of-memory error.
3249 *********************************************************************/
3250 jb_err client_x_forwarded_adder(struct client_state *csp)
3255 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3260 if (csp->x_forwarded)
3262 p = strdup(csp->x_forwarded);
3263 string_append(&p, ", ");
3267 p = strdup("X-Forwarded-For: ");
3269 string_append(&p, csp->ip_addr_str);
3273 return JB_ERR_MEMORY;
3276 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3277 err = enlist(csp->headers, p);
3284 /*********************************************************************
3286 * Function : connection_close_adder
3288 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3289 * support. Adds a "Connection: close" header to csp->headers
3290 * unless the header was already present. Called from `sed'.
3292 * FIXME: This whole function shouldn't be neccessary!
3295 * 1 : csp = Current client state (buffers, headers, etc...)
3297 * Returns : JB_ERR_OK on success, or
3298 * JB_ERR_MEMORY on out-of-memory error.
3300 *********************************************************************/
3301 jb_err connection_close_adder(struct client_state *csp)
3303 const unsigned int flags = csp->flags;
3306 * Return right away if
3308 * - we're parsing server headers and the server header
3309 * "Connection: close" is already set, or if
3311 * - we're parsing client headers and the client header
3312 * "Connection: close" is already set.
3314 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3315 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3316 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3317 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3322 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3324 return enlist(csp->headers, "Connection: close");
3328 /*********************************************************************
3330 * Function : server_http
3332 * Description : - Save the HTTP Status into csp->http->status
3333 * - Set CT_TABOO to prevent filtering if the answer
3334 * is a partial range (HTTP status 206)
3335 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3339 * 1 : csp = Current client state (buffers, headers, etc...)
3340 * 2 : header = On input, pointer to header to modify.
3341 * On output, pointer to the modified header, or NULL
3342 * to remove the header. This function frees the
3343 * original string if necessary.
3345 * Returns : JB_ERR_OK on success, or
3346 * JB_ERR_MEMORY on out-of-memory error.
3348 *********************************************************************/
3349 jb_err server_http(struct client_state *csp, char **header)
3351 /* Signal that were now parsing server headers. */
3352 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
3354 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3355 if (csp->http->status == 206)
3357 csp->content_type = CT_TABOO;
3360 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3363 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3370 /*********************************************************************
3372 * Function : server_set_cookie
3374 * Description : Handle the server "cookie" header properly.
3375 * Log cookie to the jar file. Then "crunch",
3376 * accept or rewrite it to a session cookie.
3377 * Called from `sed'.
3379 * TODO: Allow the user to specify a new expiration
3380 * time to cause the cookie to expire even before the
3381 * browser is closed.
3384 * 1 : csp = Current client state (buffers, headers, etc...)
3385 * 2 : header = On input, pointer to header to modify.
3386 * On output, pointer to the modified header, or NULL
3387 * to remove the header. This function frees the
3388 * original string if necessary.
3390 * Returns : JB_ERR_OK on success, or
3391 * JB_ERR_MEMORY on out-of-memory error.
3393 *********************************************************************/
3394 jb_err server_set_cookie(struct client_state *csp, char **header)
3399 struct tm tm_cookie;
3402 #ifdef FEATURE_COOKIE_JAR
3403 if (csp->config->jar)
3406 * Write timestamp into outbuf.
3408 * Complex because not all OSs have tm_gmtoff or
3409 * the %z field in strftime()
3411 char tempbuf[ BUFFER_SIZE ];
3413 #ifdef HAVE_LOCALTIME_R
3414 tm_now = *localtime_r(&now, &tm_now);
3415 #elif FEATURE_PTHREAD
3416 pthread_mutex_lock(&localtime_mutex);
3417 tm_now = *localtime (&now);
3418 pthread_mutex_unlock(&localtime_mutex);
3420 tm_now = *localtime (&now);
3422 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3424 /* strlen("set-cookie: ") = 12 */
3425 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3427 #endif /* def FEATURE_COOKIE_JAR */
3429 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3431 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
3432 return crumble(csp, header);
3434 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3436 /* Flag whether or not to log a message */
3439 /* A variable to store the tag we're working on */
3442 /* Skip "Set-Cookie:" (11 characters) in header */
3443 cur_tag = *header + 11;
3445 /* skip whitespace between "Set-Cookie:" and value */
3446 while (*cur_tag && ijb_isspace(*cur_tag))
3451 /* Loop through each tag in the cookie */
3455 char *next_tag = strchr(cur_tag, ';');
3456 if (next_tag != NULL)
3458 /* Skip the ';' character itself */
3461 /* skip whitespace ";" and start of tag */
3462 while (*next_tag && ijb_isspace(*next_tag))
3469 /* "Next tag" is the end of the string */
3470 next_tag = cur_tag + strlen(cur_tag);
3474 * Check the expiration date to see
3475 * if the cookie is still valid, if yes,
3476 * rewrite it to a session cookie.
3478 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3481 const char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3482 memset(&tm_cookie, 0, sizeof(tm_cookie));
3484 * Try the valid time formats we know about.
3486 * XXX: This should be moved to parse_header_time().
3488 * XXX: Maybe the log messages should be removed
3489 * for the next stable release. They just exist to
3490 * see which time format gets the most hits and
3491 * should be checked for first.
3493 if (NULL != (match = strptime(expiration_date, "%a, %e-%b-%y %H:%M:%S ", &tm_cookie)))
3495 /* 22-Feb-2008 12:01:18 GMT */
3496 log_error(LOG_LEVEL_HEADER,
3497 "cookie \'%s\' send by %s appears to be using time format 1.",
3498 *header, csp->http->url);
3500 else if (NULL != (match = strptime(expiration_date, "%A, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3502 /* Tue, 02-Jun-2037 20:00:00 GMT */
3503 log_error(LOG_LEVEL_HEADER,
3504 "cookie \'%s\' send by %s appears to be using time format 2.",
3505 *header, csp->http->url);
3507 else if (NULL != (match = strptime(expiration_date, "%a, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3509 /* Tuesday, 02-Jun-2037 20:00:00 GMT */
3511 * On FreeBSD this is never reached because it's handled
3512 * by "format 2" as well. I am, however, not sure if all
3513 * strptime() implementations behave that way.
3515 log_error(LOG_LEVEL_HEADER,
3516 "cookie \'%s\' send by %s appears to be using time format 3.",
3517 *header, csp->http->url);
3519 else if (NULL != (match = strptime(expiration_date, "%a, %e %b %Y %H:%M:%S ", &tm_cookie)))
3521 /* Fri, 22 Feb 2008 19:20:05 GMT */
3522 log_error(LOG_LEVEL_HEADER,
3523 "cookie \'%s\' send by %s appears to be using time format 4.",
3524 *header, csp->http->url);
3526 else if (NULL != (match = strptime(expiration_date, "%A %b %e %H:%M:%S %Y", &tm_cookie)))
3528 /* Thu Mar 08 23:00:00 2007 GMT */
3529 log_error(LOG_LEVEL_HEADER,
3530 "cookie \'%s\' send by %s appears to be using time format 5.",
3531 *header, csp->http->url);
3534 /* Did any of them match? */
3538 * Nope, treat it as if it was still valid.
3540 * XXX: Should we remove the whole cookie instead?
3542 log_error(LOG_LEVEL_ERROR,
3543 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3544 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3550 * Yes. Check if the cookie is still valid.
3552 * If the cookie is already expired it's probably
3553 * a delete cookie and even if it isn't, the browser
3554 * will discard it anyway.
3558 * XXX: timegm() isn't available on some AmigaOS
3559 * versions and our replacement doesn't work.
3561 * Our options are to either:
3563 * - disable session-cookies-only completely if timegm
3566 * - to simply remove all expired tags, like it has
3567 * been done until Privoxy 3.0.6 and to live with
3568 * the consequence that it can cause login/logout
3569 * problems on servers that don't validate their
3570 * input properly, or
3572 * - to replace it with mktime in which
3573 * case there is a slight chance of valid cookies
3574 * passing as already expired.
3576 * This is the way it's currently done and it's not
3577 * as bad as it sounds. If the missing GMT offset is
3578 * enough to change the result of the expiration check
3579 * the cookie will be only valid for a few hours
3580 * anyway, which in many cases will be shorter
3581 * than a browser session.
3583 cookie_time = timegm(&tm_cookie);
3584 if (cookie_time - now < 0)
3586 log_error(LOG_LEVEL_HEADER,
3587 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3588 /* Just in case some clown sets more then one expiration date */
3594 * Still valid, delete expiration date by copying
3595 * the rest of the string over it.
3597 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3598 * since the behaviour of strcpy is undefined for overlapping
3601 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3603 /* That changed the header, need to issue a log message */
3607 * Note that the next tag has now been moved to *cur_tag,
3608 * so we do not need to update the cur_tag pointer.
3616 /* Move on to next cookie tag */
3623 assert(NULL != *header);
3624 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3633 #ifdef FEATURE_FORCE_LOAD
3634 /*********************************************************************
3636 * Function : strclean
3638 * Description : In-Situ-Eliminate all occurances of substring in
3642 * 1 : string = string to clean
3643 * 2 : substring = substring to eliminate
3645 * Returns : Number of eliminations
3647 *********************************************************************/
3648 int strclean(const char *string, const char *substring)
3654 len = strlen(substring);
3656 while((pos = strstr(string, substring)) != NULL)
3663 while (*p++ != '\0');
3670 #endif /* def FEATURE_FORCE_LOAD */
3672 /*********************************************************************
3674 * Function : parse_header_time
3676 * Description : Transforms time inside a HTTP header into
3677 * the usual time format.
3680 * 1 : header = header to parse
3681 * 2 : tm = storage for the resulting time in seconds
3683 * Returns : Time struct containing the header time, or
3684 * NULL in case of a parsing problems.
3686 *********************************************************************/
3687 struct tm *parse_header_time(char *header, time_t *tm) {
3691 struct tm * timeptr;
3694 * Initializing gmt to prevent time zone offsets.
3696 * While this is only necessary on some platforms
3697 * (mingw32 for example), I don't know how to
3698 * detect these automatically and doing it everywhere
3702 #ifdef HAVE_LOCALTIME_R
3703 gmt = *localtime_r(tm, &gmt);
3704 #elif FEATURE_PTHREAD
3705 pthread_mutex_lock(&localtime_mutex);
3706 gmt = *localtime(tm);
3707 pthread_mutex_unlock(&localtime_mutex);
3709 gmt = *localtime(tm);
3712 /* Skipping header name */
3713 timestring = strstr(header, ": ");
3714 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)
3727 /*********************************************************************
3729 * Function : get_destination_from_headers
3731 * Description : Parse the "Host:" header to get the request's destination.
3732 * Only needed if the client's request was forcefully
3733 * redirected into Privoxy.
3735 * Code mainly copied from client_host() which is currently
3736 * run too late for this purpose.
3739 * 1 : headers = List of headers (one of them hopefully being
3740 * the "Host:" header)
3741 * 2 : http = storage for the result (host, port and hostport).
3743 * Returns : JB_ERR_MEMORY in case of memory problems,
3744 * JB_ERR_PARSE if the host header couldn't be found,
3745 * JB_ERR_OK otherwise.
3747 *********************************************************************/
3748 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3754 host = get_header_value(headers, "Host:");
3758 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3759 return JB_ERR_PARSE;
3762 if (NULL == (p = strdup((host))))
3764 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3765 return JB_ERR_MEMORY;
3768 if (NULL == (q = strdup(p)))
3771 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3772 return JB_ERR_MEMORY;
3775 freez(http->hostport);
3779 q = strchr(http->host, ':');
3782 /* Terminate hostname and evaluate port string */
3784 http->port = atoi(q);
3788 http->port = http->ssl ? 443 : 80;
3791 /* Rebuild request URL */
3793 http->url = strdup(http->ssl ? "https://" : "http://");
3794 string_append(&http->url, http->hostport);
3795 string_append(&http->url, http->path);
3796 if (http->url == NULL)
3798 return JB_ERR_MEMORY;
3801 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",