1 const char parsers_rcs[] = "$Id: parsers.c,v 1.91 2007/02/24 12:27: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_server_header'
14 * `filter_client_header', `filter_header', `crunch_server_header',
15 * `server_content_encoding', `server_content_disposition',
16 * `server_last_modified', `client_accept_language',
17 * `crunch_client_header', `client_if_modified_since',
18 * `client_if_none_match', `get_destination_from_headers',
19 * `parse_header_time' and `server_set_cookie'.
21 * Copyright : Written by and Copyright (C) 2001-2007 the SourceForge
22 * Privoxy team. http://www.privoxy.org/
24 * Based on the Internet Junkbuster originally written
25 * by and Copyright (C) 1997 Anonymous Coders and
26 * Junkbusters Corporation. http://www.junkbusters.com
28 * This program is free software; you can redistribute it
29 * and/or modify it under the terms of the GNU General
30 * Public License as published by the Free Software
31 * Foundation; either version 2 of the License, or (at
32 * your option) any later version.
34 * This program is distributed in the hope that it will
35 * be useful, but WITHOUT ANY WARRANTY; without even the
36 * implied warranty of MERCHANTABILITY or FITNESS FOR A
37 * PARTICULAR PURPOSE. See the GNU General Public
38 * License for more details.
40 * The GNU General Public License should be included with
41 * this file. If not, you can view it at
42 * http://www.gnu.org/copyleft/gpl.html
43 * or write to the Free Software Foundation, Inc., 59
44 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
48 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
49 * Improve cookie expiration date detection.
51 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
52 * Don't run server_content_length() the first time
53 * sed() parses server headers; only adjust the
54 * Content-Length header if the page was modified.
56 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
57 * Fix log messages regarding the cookie time format
58 * (cookie and request URL were mixed up).
60 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
61 * - Let decompress_iob()
62 * - not corrupt the content if decompression fails
63 * early. (the first byte(s) were lost).
64 * - use pointer arithmetics with defined outcome for
66 * - Use a different kludge to remember a failed decompression.
68 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
69 * Search for Max-Forwards headers case-insensitive,
70 * don't generate the "501 unsupported" message for invalid
71 * Max-Forwards values and don't increase negative ones.
73 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
74 * - Let server_set_cookie() check the expiration date
75 * of cookies and don't touch the ones that are already
76 * expired. Fixes problems with low quality web applications
77 * as described in BR 932612.
79 * - Adjust comment in client_max_forwards to reality;
80 * remove invalid Max-Forwards headers.
82 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
83 * Stop filter_header() from unintentionally removing
84 * empty header lines that were enlisted by the continue
87 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
88 * - Repeat the request URL before logging any headers.
89 * Makes reading the log easier in case of simultaneous requests.
90 * - If there are more than one Content-Type headers in one request,
91 * use the first one and remove the others.
92 * - Remove "newval" variable in server_content_type().
93 * It's only used once.
95 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
96 * Correct a cast, check inflateEnd() exit code
97 * to see if we have to, replace sprintf calls
100 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
101 * Integrate a modified version of Wil Mahan's
102 * zlib patch (PR #895531).
104 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
105 * Skip empty filter files in filter_header()
106 * but don't ignore the ones that come afterwards.
107 * Fixes BR 1619208, this time for real.
109 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
110 * Reverted parts of my last commit
111 * to keep error handling working.
113 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
114 * Fixed gcc43 conversion warnings.
116 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
117 * Bringing back the "useless" localtime() call
118 * I removed in revision 1.67. On some platforms
119 * it's necessary to prevent time zone offsets.
121 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
122 * Rebuild request URL in get_destination_from_headers()
123 * to make sure redirect{pcrs command} works as expected
124 * for intercepted requests.
126 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
127 * Added get_destination_from_headers().
129 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
130 * Make pthread mutex locking more generic. Instead of
131 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
132 * and use mutex locking unless there is an _r function
133 * available. Better safe than sorry.
135 * Fixes "./configure --disable-pthread" and should result
136 * in less threading-related problems on pthread-using platforms,
137 * but it still doesn't fix BR#1122404.
139 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
140 * The special header "X-Filter: No" now disables
141 * header filtering as well.
143 * Revision 1.73 2006/09/23 13:26:38 roro
144 * Replace TABs by spaces in source code.
146 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
147 * Don't print a log message every time filter_headers is
148 * entered or left. It only creates noise without any real
151 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
152 * Fix +hide-if-modified-since{-n}.
154 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
155 * Have hide-if-modified-since interpret the random
156 * range value as minutes instead of hours. Allows
157 * more fine-grained configuration.
159 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
160 * Always have parse_header_time return a pointer
161 * that actual makes sense, even though we currently
162 * only need it to detect problems.
164 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
165 * Added config option enable-remote-http-toggle
166 * to specify if Privoxy should recognize special
167 * headers (currently only X-Filter) to change its
168 * behaviour. Disabled by default.
170 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
171 * After filtering de-chunked instances, remove
172 * "Transfer-Encoding" header entirely instead of changing
173 * it to "Transfer-Encoding: identity", which is invalid.
174 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
176 * Don't use localtime in parse_header_time. An empty time struct
177 * is good enough, it gets overwritten by strptime anyway.
179 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
180 * Use gmtime_r if available, fallback to gmtime with mutex
181 * protection for MacOSX and use vanilla gmtime for the rest.
183 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
184 * Changed client_referrer to use the right type (size_t) for
185 * hostlenght and to shorten the temporary referrer string with
186 * '\0' instead of adding a useless line break.
188 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
189 * - Back to timegm() using GnuPG's replacement if necessary.
190 * Using mktime() and localtime() could add a on hour offset if
191 * the randomize factor was big enough to lead to a summer/wintertime
194 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
196 * - Moved randomization code into pick_from_range().
198 * - Changed parse_header_time definition.
199 * time_t isn't guaranteed to be signed and
200 * if it isn't, -1 isn't available as error code.
201 * Changed some variable types in client_if_modified_since()
202 * because of the same reason.
204 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
205 * OS/2 compilation compatibility fixups
207 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
208 * Changed include from strptime.c to strptime.h
210 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
211 * Split filter-headers{} into filter-client-headers{}
212 * and filter-server-headers{}.
213 * Added parse_header_time() to share some code.
214 * Replaced timegm() with mktime().
216 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
217 * Windows service integration
219 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
220 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
222 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
223 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
224 * with what was really the latest development (the v_3_0_branch branch)
226 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
227 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
229 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
230 * Add the ability to check jpeg images for invalid
231 * lengths of comment blocks. Defensive strategy
232 * against the exploit:
233 * Microsoft Security Bulletin MS04-028
234 * Buffer Overrun in JPEG Processing (GDI+) Could
235 * Allow Code Execution (833987)
236 * Enabled with +inspect-jpegs in actions files.
238 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
239 * Excluded text/plain objects from filtering. This fixes a
240 * couple of client-crashing, download corruption and
241 * Privoxy performance issues, whose root cause lies in
242 * web servers labelling content of unknown type as text/plain.
244 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
245 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
247 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
248 * Completing the previous change
250 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
251 * Added temporary workaround for bug in PHP < 4.2.3
253 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
254 * 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.
256 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
257 * Fix typo: supressed -> suppressed
259 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
260 * Improved cookie logging
262 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
263 * Added basic support for OPTIONS and TRACE HTTP methods:
264 * - New parser function client_max_forwards which decrements
265 * the Max-Forwards HTTP header field of OPTIONS and TRACE
266 * requests by one before forwarding
267 * - New parser function client_host which extracts the host
268 * and port information from the HTTP header field if the
269 * request URI was not absolute
270 * - Don't crumble and re-add the Host: header, but only generate
271 * and append if missing
273 * Revision 1.56 2002/05/12 15:34:22 jongfoster
274 * Fixing typo in a comment
276 * Revision 1.55 2002/05/08 16:01:07 oes
277 * Optimized add_to_iob:
278 * - Use realloc instead of malloc(), memcpy(), free()
279 * - Expand to powers of two if possible, to get
280 * O(log n) reallocs instead of O(n).
281 * - Moved check for buffer limit here from chat
282 * - Report failure via returncode
284 * Revision 1.54 2002/04/02 15:03:16 oes
285 * Tiny code cosmetics
287 * Revision 1.53 2002/03/26 22:29:55 swa
288 * we have a new homepage!
290 * Revision 1.52 2002/03/24 13:25:43 swa
291 * name change related issues
293 * Revision 1.51 2002/03/13 00:27:05 jongfoster
296 * Revision 1.50 2002/03/12 01:45:35 oes
297 * More verbose logging
299 * Revision 1.49 2002/03/09 20:03:52 jongfoster
300 * - Making various functions return int rather than size_t.
301 * (Undoing a recent change). Since size_t is unsigned on
302 * Windows, functions like read_socket that return -1 on
303 * error cannot return a size_t.
305 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
306 * crashes, and also frequently caused JB to jump to 100%
307 * CPU and stay there. (Because it thought it had just
308 * read ((unsigned)-1) == 4Gb of data...)
310 * - The signature of write_socket has changed, it now simply
311 * returns success=0/failure=nonzero.
313 * - Trying to get rid of a few warnings --with-debug on
314 * Windows, I've introduced a new type "jb_socket". This is
315 * used for the socket file descriptors. On Windows, this
316 * is SOCKET (a typedef for unsigned). Everywhere else, it's
317 * an int. The error value can't be -1 any more, so it's
318 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
319 * Windows it maps to the #define INVALID_SOCKET.)
321 * - The signature of bind_port has changed.
323 * Revision 1.48 2002/03/07 03:46:53 oes
324 * Fixed compiler warnings etc
326 * Revision 1.47 2002/02/20 23:15:13 jongfoster
327 * Parsing functions now handle out-of-memory gracefully by returning
330 * Revision 1.46 2002/01/17 21:03:47 jongfoster
331 * Moving all our URL and URL pattern parsing code to urlmatch.c.
333 * Revision 1.45 2002/01/09 14:33:03 oes
334 * Added support for localtime_r.
336 * Revision 1.44 2001/12/14 01:22:54 steudten
337 * Remove 'user:pass@' from 'proto://user:pass@host' for the
338 * new added header 'Host: ..'. (See Req ID 491818)
340 * Revision 1.43 2001/11/23 00:26:38 jongfoster
341 * Fixing two really stupid errors in my previous commit
343 * Revision 1.42 2001/11/22 21:59:30 jongfoster
344 * Adding code to handle +no-cookies-keep
346 * Revision 1.41 2001/11/05 23:43:05 steudten
347 * Add time+date to log files.
349 * Revision 1.40 2001/10/26 20:13:09 jongfoster
350 * ctype.h is needed in Windows, too.
352 * Revision 1.39 2001/10/26 17:40:04 oes
353 * Introduced get_header_value()
354 * Removed http->user_agent, csp->referrer and csp->accept_types
355 * Removed client_accept()
357 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
358 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
359 * threads to call select() simultaneously. So, it's time to do a real, live,
360 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
361 * (native). Both versions will work, but using __OS2__ offers multi-threading.
363 * Revision 1.37 2001/10/23 21:36:02 jongfoster
364 * Documenting sed()'s error behaviou (doc change only)
366 * Revision 1.36 2001/10/13 12:51:51 joergs
367 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
368 * force-load), instead crumble Host: and add it (again) in client_host_adder
369 * (in case we get a HTTP/1.0 request without Host: header and forward it to
370 * a HTTP/1.1 server/proxy).
372 * Revision 1.35 2001/10/09 22:39:21 jongfoster
373 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
376 * Revision 1.34 2001/10/07 18:50:55 oes
377 * Added server_content_encoding, renamed server_transfer_encoding
379 * Revision 1.33 2001/10/07 18:04:49 oes
380 * Changed server_http11 to server_http and its pattern to "HTTP".
381 * Additional functionality: it now saves the HTTP status into
382 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
384 * Revision 1.32 2001/10/07 15:43:28 oes
385 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
386 * client_te and client_accept_encoding_adder, triggered by the new
387 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
388 * changed to allow only identity and chunked, and the TE header is
389 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
391 * parse_http_request no longer does anything than parsing. The rewriting
392 * of http->cmd and version mangling are gone. It now also recognizes
393 * the put and delete methods and saves the url in http->url. Removed
396 * renamed content_type and content_length to have the server_ prefix
398 * server_content_type now only works if csp->content_type != CT_TABOO
400 * added server_transfer_encoding, which
401 * - Sets CT_TABOO to prohibit filtering if encoding compresses
402 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
403 * - Change from "chunked" to "identity" if body was chunked
404 * but has been de-chunked for filtering.
406 * added server_content_md5 which crunches any Content-MD5 headers
407 * if the body was modified.
409 * made server_http11 conditional on +downgrade action
411 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
413 * Revision 1.31 2001/10/05 14:25:02 oes
414 * Crumble Keep-Alive from Server
416 * Revision 1.30 2001/09/29 12:56:03 joergs
417 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
419 * Revision 1.29 2001/09/24 21:09:24 jongfoster
420 * Fixing 2 memory leaks that Guy spotted, where the paramater to
421 * enlist() was not being free()d.
423 * Revision 1.28 2001/09/22 16:32:28 jongfoster
424 * Removing unused #includes.
426 * Revision 1.27 2001/09/20 15:45:25 steudten
428 * add casting from size_t to int for printf()
429 * remove local variable shadow s2
431 * Revision 1.26 2001/09/16 17:05:14 jongfoster
432 * Removing unused #include showarg.h
434 * Revision 1.25 2001/09/16 13:21:27 jongfoster
435 * Changes to use new list functions.
437 * Revision 1.24 2001/09/13 23:05:50 jongfoster
438 * Changing the string paramater to the header parsers a "const".
440 * Revision 1.23 2001/09/12 18:08:19 steudten
442 * In parse_http_request() header rewriting miss the host value, so
443 * from http://www.mydomain.com the result was just " / " not
444 * http://www.mydomain.com/ in case we forward.
446 * Revision 1.22 2001/09/10 10:58:53 oes
447 * Silenced compiler warnings
449 * Revision 1.21 2001/07/31 14:46:00 oes
450 * - Persistant connections now suppressed
451 * - sed() no longer appends empty header to csp->headers
453 * Revision 1.20 2001/07/30 22:08:36 jongfoster
454 * Tidying up #defines:
455 * - All feature #defines are now of the form FEATURE_xxx
456 * - Permanently turned off WIN_GUI_EDIT
457 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
459 * Revision 1.19 2001/07/25 17:21:54 oes
460 * client_uagent now saves copy of User-Agent: header value
462 * Revision 1.18 2001/07/13 14:02:46 oes
463 * - Included fix to repair broken HTTP requests that
464 * don't contain a path, not even '/'.
465 * - Removed all #ifdef PCRS
466 * - content_type now always inspected and classified as
467 * text, gif or other.
468 * - formatting / comments
470 * Revision 1.17 2001/06/29 21:45:41 oes
471 * Indentation, CRLF->LF, Tab-> Space
473 * Revision 1.16 2001/06/29 13:32:42 oes
475 * - Adapted free_http_request
476 * - Removed logentry from cancelled commit
478 * Revision 1.15 2001/06/03 19:12:38 oes
479 * deleted const struct interceptors
481 * Revision 1.14 2001/06/01 18:49:17 jongfoster
482 * Replaced "list_share" with "list" - the tiny memory gain was not
483 * worth the extra complexity.
485 * Revision 1.13 2001/05/31 21:30:33 jongfoster
486 * Removed list code - it's now in list.[ch]
487 * Renamed "permission" to "action", and changed many features
488 * to use the actions file rather than the global config.
490 * Revision 1.12 2001/05/31 17:33:13 oes
494 * Revision 1.11 2001/05/29 20:11:19 joergs
495 * '/ * inside comment' warning removed.
497 * Revision 1.10 2001/05/29 09:50:24 jongfoster
498 * Unified blocklist/imagelist/permissionslist.
499 * File format is still under discussion, but the internal changes
502 * Also modified interceptor behaviour:
503 * - We now intercept all URLs beginning with one of the following
504 * prefixes (and *only* these prefixes):
506 * * http://ijbswa.sf.net/config/
507 * * http://ijbswa.sourceforge.net/config/
508 * - New interceptors "home page" - go to http://i.j.b/ to see it.
509 * - Internal changes so that intercepted and fast redirect pages
510 * are not replaced with an image.
511 * - Interceptors now have the option to send a binary page direct
512 * to the client. (i.e. ijb-send-banner uses this)
513 * - Implemented show-url-info interceptor. (Which is why I needed
514 * the above interceptors changes - a typical URL is
515 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
516 * The previous mechanism would not have intercepted that, and
517 * if it had been intercepted then it then it would have replaced
520 * Revision 1.9 2001/05/28 17:26:33 jongfoster
521 * Fixing segfault if last header was crunched.
522 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
523 * can use the cross-platform sprintf() instead.)
525 * Revision 1.8 2001/05/27 22:17:04 oes
527 * - re_process_buffer no longer writes the modified buffer
528 * to the client, which was very ugly. It now returns the
529 * buffer, which it is then written by chat.
531 * - content_length now adjusts the Content-Length: header
532 * for modified documents rather than crunch()ing it.
533 * (Length info in csp->content_length, which is 0 for
534 * unmodified documents)
536 * - For this to work, sed() is called twice when filtering.
538 * Revision 1.7 2001/05/27 13:19:06 oes
539 * Patched Joergs solution for the content-length in.
541 * Revision 1.6 2001/05/26 13:39:32 jongfoster
542 * Only crunches Content-Length header if applying RE filtering.
543 * Without this fix, Microsoft Windows Update wouldn't work.
545 * Revision 1.5 2001/05/26 00:28:36 jongfoster
546 * Automatic reloading of config file.
547 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
548 * Most of the global variables have been moved to a new
549 * struct configuration_spec, accessed through csp->config->globalname
550 * Most of the globals remaining are used by the Win32 GUI.
552 * Revision 1.4 2001/05/22 18:46:04 oes
554 * - Enabled filtering banners by size rather than URL
555 * by adding patterns that replace all standard banner
556 * sizes with the "Junkbuster" gif to the re_filterfile
558 * - Enabled filtering WebBugs by providing a pattern
559 * which kills all 1x1 images
561 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
562 * which is selected by the (nonstandard and therefore
563 * capital) letter 'U' in the option string.
564 * It causes the quantifiers to be ungreedy by default.
565 * Appending a ? turns back to greedy (!).
567 * - Added a new interceptor ijb-send-banner, which
568 * sends back the "Junkbuster" gif. Without imagelist or
569 * MSIE detection support, or if tinygif = 1, or the
570 * URL isn't recognized as an imageurl, a lame HTML
571 * explanation is sent instead.
573 * - Added new feature, which permits blocking remote
574 * script redirects and firing back a local redirect
576 * The feature is conditionally compiled, i.e. it
577 * can be disabled with --disable-fast-redirects,
578 * plus it must be activated by a "fast-redirects"
579 * line in the config file, has its own log level
580 * and of course wants to be displayed by show-proxy-args
581 * Note: Boy, all the #ifdefs in 1001 locations and
582 * all the fumbling with configure.in and acconfig.h
583 * were *way* more work than the feature itself :-(
585 * - Because a generic redirect template was needed for
586 * this, tinygif = 3 now uses the same.
588 * - Moved GIFs, and other static HTTP response templates
593 * - Removed some >400 CRs again (Jon, you really worked
596 * Revision 1.3 2001/05/20 01:21:20 jongfoster
597 * Version 2.9.4 checkin.
598 * - Merged popupfile and cookiefile, and added control over PCRS
599 * filtering, in new "permissionsfile".
600 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
601 * file error you now get a message box (in the Win32 GUI) rather
602 * than the program exiting with no explanation.
603 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
605 * - Removed tabs from "config"
606 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
607 * - Bumped up version number.
609 * Revision 1.2 2001/05/17 23:02:36 oes
610 * - Made referrer option accept 'L' as a substitute for '§'
612 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
613 * Initial import of version 2.9.3 source tree
616 *********************************************************************/
623 #include <sys/types.h>
636 #if !defined(_WIN32) && !defined(__OS2__)
642 #ifdef FEATURE_PTHREAD
644 /* jcc.h is for mutex semapores only */
645 #endif /* def FEATURE_PTHREAD */
651 #include "jbsockets.h"
652 #include "miscutil.h"
655 #ifndef HAVE_STRPTIME
656 #include "strptime.h"
659 const char parsers_h_rcs[] = PARSERS_H_VERSION;
661 /* Fix a problem with Solaris. There should be no effect on other
663 * Solaris's isspace() is a macro which uses it's argument directly
664 * as an array index. Therefore we need to make sure that high-bit
665 * characters generate +ve values, and ideally we also want to make
666 * the argument match the declared parameter type of "int".
668 * Why did they write a character function that can't take a simple
669 * "char" argument? Doh!
671 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
672 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
675 const struct parsers client_patterns[] = {
676 { "referer:", 8, client_referrer },
677 { "user-agent:", 11, client_uagent },
678 { "ua-", 3, client_ua },
679 { "from:", 5, client_from },
680 { "cookie:", 7, client_send_cookie },
681 { "x-forwarded-for:", 16, client_x_forwarded },
682 { "Accept-Encoding:", 16, client_accept_encoding },
683 { "TE:", 3, client_te },
684 { "Host:", 5, client_host },
685 { "if-modified-since:", 18, client_if_modified_since },
686 { "Keep-Alive:", 11, crumble },
687 { "connection:", 11, connection },
688 { "proxy-connection:", 17, crumble },
689 { "max-forwards:", 13, client_max_forwards },
690 { "Accept-Language:", 16, client_accept_language },
691 { "if-none-match:", 14, client_if_none_match },
692 { "X-Filter:", 9, client_x_filter },
693 { "*", 0, crunch_client_header },
694 { "*", 0, filter_client_header },
698 const struct parsers server_patterns[] = {
699 { "HTTP", 4, server_http },
700 { "set-cookie:", 11, server_set_cookie },
701 { "connection:", 11, connection },
702 { "Content-Type:", 13, server_content_type },
703 { "Content-MD5:", 12, server_content_md5 },
704 { "Content-Encoding:", 17, server_content_encoding },
705 { "Transfer-Encoding:", 18, server_transfer_coding },
706 { "Keep-Alive:", 11, crumble },
707 { "content-disposition:", 20, server_content_disposition },
708 { "Last-Modified:", 14, server_last_modified },
709 { "*", 0, crunch_server_header },
710 { "*", 0, filter_server_header },
714 const struct parsers server_patterns_light[] = {
715 { "Content-Length:", 15, server_content_length },
716 { "Transfer-Encoding:", 18, server_transfer_coding },
718 { "Content-Encoding:", 17, server_content_encoding },
719 #endif /* def FEATURE_ZLIB */
723 const add_header_func_ptr add_client_headers[] = {
726 client_x_forwarded_adder,
728 /* Temporarily disabled: client_accept_encoding_adder, */
729 connection_close_adder,
734 const add_header_func_ptr add_server_headers[] = {
735 connection_close_adder,
739 /*********************************************************************
741 * Function : flush_socket
743 * Description : Write any pending "buffered" content.
746 * 1 : fd = file descriptor of the socket to read
747 * 2 : csp = Current client state (buffers, headers, etc...)
749 * Returns : On success, the number of bytes written are returned (zero
750 * indicates nothing was written). On error, -1 is returned,
751 * and errno is set appropriately. If count is zero and the
752 * file descriptor refers to a regular file, 0 will be
753 * returned without causing any other effect. For a special
754 * file, the results are not portable.
756 *********************************************************************/
757 int flush_socket(jb_socket fd, struct client_state *csp)
759 struct iob *iob = csp->iob;
760 int len = iob->eod - iob->cur;
767 if (write_socket(fd, iob->cur, (size_t)len))
771 iob->eod = iob->cur = iob->buf;
777 /*********************************************************************
779 * Function : add_to_iob
781 * Description : Add content to the buffered page, expanding the
782 * buffer if necessary.
785 * 1 : csp = Current client state (buffers, headers, etc...)
786 * 2 : buf = holds the content to be added to the page
787 * 3 : n = number of bytes to be added
789 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
790 * or buffer limit reached.
792 *********************************************************************/
793 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
795 struct iob *iob = csp->iob;
796 size_t used, offset, need, want;
799 if (n <= 0) return JB_ERR_OK;
801 used = (size_t)(iob->eod - iob->buf);
802 offset = (size_t)(iob->cur - iob->buf);
803 need = used + (size_t)n + 1;
806 * If the buffer can't hold the new data, extend it first.
807 * Use the next power of two if possible, else use the actual need.
809 if (need > csp->config->buffer_limit)
811 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
812 return JB_ERR_MEMORY;
815 if (need > iob->size)
817 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
819 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
823 else if (NULL != (p = (char *)realloc(iob->buf, need)))
829 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
830 return JB_ERR_MEMORY;
833 /* Update the iob pointers */
834 iob->cur = p + offset;
839 /* copy the new data into the iob buffer */
840 memcpy(iob->eod, buf, (size_t)n);
842 /* point to the end of the data */
845 /* null terminate == cheap insurance */
854 /*********************************************************************
856 * Function : decompress_iob
858 * Description : Decompress buffered page, expanding the
859 * buffer as necessary. csp->iob->cur
860 * should point to the the beginning of the
861 * compressed data block.
864 * 1 : csp = Current client state (buffers, headers, etc...)
866 * Returns : JB_ERR_OK on success,
867 * JB_ERR_MEMORY if out-of-memory limit reached, and
868 * JB_ERR_COMPRESS if error decompressing buffer.
870 *********************************************************************/
871 jb_err decompress_iob(struct client_state *csp)
873 char *buf; /* new, uncompressed buffer */
874 char *cur; /* Current iob position (to keep the original
875 * iob->cur unmodified if we return early) */
876 size_t bufsize; /* allocated size of the new buffer */
877 size_t skip_size; /* Number of bytes at the beginning of the iob
878 that we should NOT decompress. */
879 int status; /* return status of the inflate() call */
880 z_stream zstr; /* used by calls to zlib */
882 bufsize = csp->iob->size;
883 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
890 * This is to protect the parsing of gzipped data,
891 * but it should(?) be valid for deflated data also.
893 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
894 return JB_ERR_COMPRESS;
897 if (csp->content_type & CT_GZIP)
900 * Our task is slightly complicated by the facts that data
901 * compressed by gzip does not include a zlib header, and
902 * that there is no easily accessible interface in zlib to
903 * handle a gzip header. We strip off the gzip header by
904 * hand, and later inform zlib not to expect a header.
908 * Strip off the gzip header. Please see RFC 1952 for more
909 * explanation of the appropriate fields.
911 if ((*cur++ != (char)0x1f)
912 || (*cur++ != (char)0x8b)
913 || (*cur++ != Z_DEFLATED))
915 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
916 return JB_ERR_COMPRESS;
922 * XXX: These magic numbers should be replaced
923 * with macros to give a better idea what they do.
927 /* The gzip header has reserved bits set; bail out. */
928 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
929 return JB_ERR_COMPRESS;
933 /* Skip extra fields if necessary. */
937 * Skip a given number of bytes, specified
938 * as a 16-bit little-endian value.
941 * XXX: This code used to be:
943 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
945 * which I had to change into:
947 * cur += *cur++ + (*cur++ << 8);
949 * at which point gcc43 finally noticed that the value
950 * of cur is undefined (it depends on which of the
951 * summands is evaluated first).
953 * I haven't come across a site where this
954 * code is actually executed yet, but I hope
959 skip_bytes = *cur++ << 8;
961 assert(skip_bytes == *csp->iob->cur-2 + ((*csp->iob->cur-1) << 8));
964 * The number of bytes to skip should be positive
965 * and we'd like to stay in the buffer.
967 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
969 log_error (LOG_LEVEL_ERROR,
970 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
972 return JB_ERR_COMPRESS;
974 log_error (LOG_LEVEL_INFO,
975 "Skipping %d bytes for gzip compression. Does this sound right?",
980 /* Skip the filename if necessary. */
983 /* A null-terminated string follows. */
987 /* Skip the comment if necessary. */
993 /* Skip the CRC if necessary. */
1000 else if (csp->content_type & CT_DEFLATE)
1003 * XXX: The debug level should be lowered
1004 * before the next stable release.
1006 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1008 * In theory (that is, according to RFC 1950), deflate-compressed
1009 * data should begin with a two-byte zlib header and have an
1010 * adler32 checksum at the end. It seems that in practice only
1011 * the raw compressed data is sent. Note that this means that
1012 * we are not RFC 1950-compliant here, but the advantage is that
1013 * this actually works. :)
1015 * We add a dummy null byte to tell zlib where the data ends,
1016 * and later inform it not to expect a header.
1018 * Fortunately, add_to_iob() has thoughtfully null-terminated
1019 * the buffer; we can just increment the end pointer to include
1026 log_error (LOG_LEVEL_ERROR,
1027 "Unable to determine compression format for decompression");
1028 return JB_ERR_COMPRESS;
1031 /* Set up the fields required by zlib. */
1032 zstr.next_in = (Bytef *)cur;
1033 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1034 zstr.zalloc = Z_NULL;
1035 zstr.zfree = Z_NULL;
1036 zstr.opaque = Z_NULL;
1039 * Passing -MAX_WBITS to inflateInit2 tells the library
1040 * that there is no zlib header.
1042 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1044 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1045 return JB_ERR_COMPRESS;
1049 * Next, we allocate new storage for the inflated data.
1050 * We don't modify the existing iob yet, so in case there
1051 * is error in decompression we can recover gracefully.
1053 buf = zalloc (bufsize);
1056 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1057 return JB_ERR_MEMORY;
1060 assert(bufsize >= skip_size);
1061 memcpy(buf, csp->iob->buf, skip_size);
1062 zstr.avail_out = bufsize - skip_size;
1063 zstr.next_out = (Bytef *)buf + skip_size;
1065 /* Try to decompress the whole stream in one shot. */
1066 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1068 /* We need to allocate more memory for the output buffer. */
1070 char *tmpbuf; /* used for realloc'ing the buffer */
1071 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1074 * If zlib wants more data then there's a problem, because
1075 * the complete compressed file should have been buffered.
1077 if (0 == zstr.avail_in)
1079 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1080 return JB_ERR_COMPRESS;
1084 * If we tried the limit and still didn't have enough
1085 * memory, just give up.
1087 if (bufsize == csp->config->buffer_limit)
1089 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1090 return JB_ERR_MEMORY;
1093 /* Try doubling the buffer size each time. */
1096 /* Don't exceed the buffer limit. */
1097 if (bufsize > csp->config->buffer_limit)
1099 bufsize = csp->config->buffer_limit;
1102 /* Try to allocate the new buffer. */
1103 tmpbuf = realloc(buf, bufsize);
1106 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1108 return JB_ERR_MEMORY;
1112 char *oldnext_out = (char *)zstr.next_out;
1115 * Update the fields for inflate() to use the new
1116 * buffer, which may be in a location different from
1119 zstr.avail_out += bufsize - oldbufsize;
1120 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1123 * Compare with an uglier method of calculating these values
1124 * that doesn't require the extra oldbufsize variable.
1126 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1127 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1128 assert(zstr.avail_out > 0);
1134 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1136 log_error(LOG_LEVEL_ERROR,
1137 "Inconsistent stream state after decompression: %s", zstr.msg);
1139 * XXX: Intentionally no return.
1141 * According to zlib.h, Z_STREAM_ERROR is returned
1142 * "if the stream state was inconsistent".
1144 * I assume in this case inflate()'s status
1145 * would also be something different than Z_STREAM_END
1146 * so this check should be redundant, but lets see.
1150 if (status != Z_STREAM_END)
1152 /* We failed to decompress the stream. */
1153 log_error(LOG_LEVEL_ERROR,
1154 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1155 return JB_ERR_COMPRESS;
1159 * Finally, we can actually update the iob, since the
1160 * decompression was successful. First, free the old
1163 freez(csp->iob->buf);
1165 /* Now, update the iob to use the new buffer. */
1166 csp->iob->buf = buf;
1167 csp->iob->cur = csp->iob->buf + skip_size;
1168 csp->iob->eod = (char *)zstr.next_out;
1169 csp->iob->size = bufsize;
1172 * Make sure the new uncompressed iob obeys some minimal
1173 * consistency conditions.
1175 if ((csp->iob->buf < csp->iob->cur)
1176 && (csp->iob->cur <= csp->iob->eod)
1177 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1179 char t = csp->iob->cur[100];
1180 csp->iob->cur[100] = '\0';
1182 * XXX: The debug level should be lowered
1183 * before the next stable release.
1185 log_error(LOG_LEVEL_INFO, "Sucessfully decompressed: %s", csp->iob->cur);
1186 csp->iob->cur[100] = t;
1191 /* It seems that zlib did something weird. */
1192 log_error(LOG_LEVEL_ERROR,
1193 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1194 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1195 csp->iob->eod, csp->iob->buf + csp->iob->size);
1196 return JB_ERR_COMPRESS;
1200 #endif /* defined(FEATURE_ZLIB) */
1203 /*********************************************************************
1205 * Function : get_header
1207 * Description : This (odd) routine will parse the csp->iob
1210 * 1 : csp = Current client state (buffers, headers, etc...)
1212 * Returns : Any one of the following:
1214 * 1) a pointer to a dynamically allocated string that contains a header line
1215 * 2) NULL indicating that the end of the header was reached
1216 * 3) "" indicating that the end of the iob was reached before finding
1217 * a complete header line.
1219 *********************************************************************/
1220 char *get_header(struct client_state *csp)
1226 if ((iob->cur == NULL)
1227 || ((p = strchr(iob->cur, '\n')) == NULL))
1229 return(""); /* couldn't find a complete header */
1234 ret = strdup(iob->cur);
1237 /* FIXME No way to handle error properly */
1238 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1243 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1245 /* is this a blank line (i.e. the end of the header) ? */
1257 /*********************************************************************
1259 * Function : get_header_value
1261 * Description : Get the value of a given header from a chained list
1262 * of header lines or return NULL if no such header is
1263 * present in the list.
1266 * 1 : header_list = pointer to list
1267 * 2 : header_name = string with name of header to look for.
1268 * Trailing colon required, capitalization
1271 * Returns : NULL if not found, else value of header
1273 *********************************************************************/
1274 char *get_header_value(const struct list *header_list, const char *header_name)
1276 struct list_entry *cur_entry;
1280 assert(header_list);
1281 assert(header_name);
1282 length = strlen(header_name);
1284 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1288 if (!strncmpic(cur_entry->str, header_name, length))
1291 * Found: return pointer to start of value
1293 ret = (char *) (cur_entry->str + length);
1294 while (*ret && ijb_isspace(*ret)) ret++;
1307 /*********************************************************************
1311 * Description : add, delete or modify lines in the HTTP header streams.
1312 * On entry, it receives a linked list of headers space
1313 * that was allocated dynamically (both the list nodes
1314 * and the header contents).
1316 * As a side effect it frees the space used by the original
1320 * 1 : pats = list of patterns to match against headers
1321 * 2 : more_headers = list of functions to add more
1322 * headers (client or server)
1323 * 3 : csp = Current client state (buffers, headers, etc...)
1325 * Returns : Single pointer to a fully formed header, or NULL
1326 * on out-of-memory error.
1328 *********************************************************************/
1329 char *sed(const struct parsers pats[],
1330 const add_header_func_ptr more_headers[],
1331 struct client_state *csp)
1333 struct list_entry *p;
1334 const struct parsers *v;
1335 const add_header_func_ptr *f;
1336 jb_err err = JB_ERR_OK;
1340 * If filtering is enabled, sed is run twice,
1341 * but most of the work needs to be done only once.
1343 first_run = (more_headers != NULL ) ? 1 : 0;
1345 if (first_run) /* Parse and print */
1347 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1348 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1350 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1352 /* Header crunch()ed in previous run? -> ignore */
1353 if (p->str == NULL) continue;
1355 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
1357 /* Does the current parser handle this header? */
1358 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1360 err = v->parser(csp, (char **)&(p->str));
1364 /* place any additional headers on the csp->headers list */
1365 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1370 else /* Parse only */
1373 * The second run is only needed if the body was modified
1374 * and the content-lenght has changed.
1376 if (strncmpic(csp->http->cmd, "HEAD", 4))
1378 /*XXX: Code duplication */
1379 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1381 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1383 /* Header crunch()ed in previous run? -> ignore */
1384 if (p->str == NULL) continue;
1386 /* Does the current parser handle this header? */
1387 if (strncmpic(p->str, v->str, v->len) == 0)
1389 err = v->parser(csp, (char **)&(p->str));
1396 if (err != JB_ERR_OK)
1401 return list_to_text(csp->headers);
1405 /* here begins the family of parser functions that reformat header lines */
1407 /*********************************************************************
1409 * Function : filter_server_header
1411 * Description : Checks if server header filtering is enabled.
1412 * If it is, filter_header is called to do the work.
1415 * 1 : csp = Current client state (buffers, headers, etc...)
1416 * 2 : header = On input, pointer to header to modify.
1417 * On output, pointer to the modified header, or NULL
1418 * to remove the header. This function frees the
1419 * original string if necessary.
1421 * Returns : JB_ERR_OK on success and always succeeds
1423 *********************************************************************/
1424 jb_err filter_server_header(struct client_state *csp, char **header)
1426 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
1428 filter_header(csp, header);
1433 /*********************************************************************
1435 * Function : filter_client_header
1437 * Description : Checks if client header filtering is enabled.
1438 * If it is, filter_header is called to do the work.
1441 * 1 : csp = Current client state (buffers, headers, etc...)
1442 * 2 : header = On input, pointer to header to modify.
1443 * On output, pointer to the modified header, or NULL
1444 * to remove the header. This function frees the
1445 * original string if necessary.
1447 * Returns : JB_ERR_OK on success and always succeeds
1449 *********************************************************************/
1450 jb_err filter_client_header(struct client_state *csp, char **header)
1452 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
1454 filter_header(csp, header);
1459 /*********************************************************************
1461 * Function : filter_header
1463 * Description : Executes all text substitutions from all applying
1464 * +filter actions on the header.
1465 * Most of the code was copied from pcrs_filter_response,
1466 * including the rather short variable names
1469 * 1 : csp = Current client state (buffers, headers, etc...)
1470 * 2 : header = On input, pointer to header to modify.
1471 * On output, pointer to the modified header, or NULL
1472 * to remove the header. This function frees the
1473 * original string if necessary.
1475 * Returns : JB_ERR_OK on success and always succeeds
1477 *********************************************************************/
1478 jb_err filter_header(struct client_state *csp, char **header)
1482 size_t size = strlen(*header);
1484 char *newheader = NULL;
1487 struct file_list *fl;
1488 struct re_filterfile_spec *b;
1489 struct list_entry *filtername;
1491 int i, found_filters = 0;
1494 * Need to check the set of re_filterfiles...
1496 for (i = 0; i < MAX_AF_FILES; i++)
1509 if (0 == found_filters)
1511 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1515 for (i = 0; i < MAX_AF_FILES; i++)
1518 if ((NULL == fl) || (NULL == fl->f))
1521 * Either there are no filter files
1522 * left, or this filter file just
1523 * contains no valid filters.
1525 * Continue to be sure we don't miss
1526 * valid filter files that are chained
1527 * after empty or invalid ones.
1532 * For all applying +filter actions, look if a filter by that
1533 * name exists and if yes, execute its pcrs_joblist on the
1536 for (b = fl->f; b; b = b->next)
1538 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1539 filtername ; filtername = filtername->next)
1541 if (strcmp(b->name, filtername->str) == 0)
1543 int current_hits = 0;
1545 if ( NULL == b->joblist )
1547 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1551 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1552 *header, size, b->name);
1554 /* Apply all jobs from the joblist */
1555 for (job = b->joblist; NULL != job; job = job->next)
1557 matches = pcrs_execute(job, *header, size, &newheader, &size);
1560 current_hits += matches;
1561 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1563 *header = newheader;
1565 else if ( 0 == matches )
1567 /* Filter doesn't change header */
1573 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1574 *header, b->name, pcrs_strerror(matches));
1575 if( newheader != NULL)
1577 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1582 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1583 hits += current_hits;
1590 * Additionally checking for hits is important because if
1591 * the continue hack is triggered, server headers can
1592 * arrive empty to separate multiple heads from each other.
1594 if ((0 == size) && hits)
1596 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1604 /*********************************************************************
1606 * Function : connection
1608 * Description : Makes sure that the value of the Connection: header
1609 * is "close" and signals connection_close_adder
1613 * 1 : csp = Current client state (buffers, headers, etc...)
1614 * 2 : header = On input, pointer to header to modify.
1615 * On output, pointer to the modified header, or NULL
1616 * to remove the header. This function frees the
1617 * original string if necessary.
1619 * Returns : JB_ERR_OK on success, or
1620 * JB_ERR_MEMORY on out-of-memory error.
1622 *********************************************************************/
1623 jb_err connection(struct client_state *csp, char **header)
1625 char *old_header = *header;
1627 /* Do we have a 'Connection: close' header? */
1628 if (strcmpic(*header, "Connection: close"))
1630 /* No, create one */
1631 *header = strdup("Connection: close");
1634 return JB_ERR_MEMORY;
1636 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1640 /* Signal connection_close_adder() to return early. */
1641 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1643 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
1647 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
1654 /*********************************************************************
1656 * Function : crumble
1658 * Description : This is called if a header matches a pattern to "crunch"
1661 * 1 : csp = Current client state (buffers, headers, etc...)
1662 * 2 : header = On input, pointer to header to modify.
1663 * On output, pointer to the modified header, or NULL
1664 * to remove the header. This function frees the
1665 * original string if necessary.
1667 * Returns : JB_ERR_OK on success, or
1668 * JB_ERR_MEMORY on out-of-memory error.
1670 *********************************************************************/
1671 jb_err crumble(struct client_state *csp, char **header)
1673 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1678 /*********************************************************************
1680 * Function : crunch_server_header
1682 * Description : Crunch server header if it matches a string supplied by the
1683 * user. Called from `sed'.
1686 * 1 : csp = Current client state (buffers, headers, etc...)
1687 * 2 : header = On input, pointer to header to modify.
1688 * On output, pointer to the modified header, or NULL
1689 * to remove the header. This function frees the
1690 * original string if necessary.
1692 * Returns : JB_ERR_OK on success and always succeeds
1694 *********************************************************************/
1695 jb_err crunch_server_header(struct client_state *csp, char **header)
1697 const char *crunch_pattern;
1699 /* Do we feel like crunching? */
1700 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1702 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1704 /* Is the current header the lucky one? */
1705 if (strstr(*header, crunch_pattern))
1707 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1716 /*********************************************************************
1718 * Function : server_content_type
1720 * Description : Set the content-type for filterable types (text/.*,
1721 * .*xml.*, javascript and image/gif) unless filtering has been
1722 * forbidden (CT_TABOO) while parsing earlier headers.
1723 * NOTE: Since text/plain is commonly used by web servers
1724 * for files whose correct type is unknown, we don't
1725 * set CT_TEXT for it.
1728 * 1 : csp = Current client state (buffers, headers, etc...)
1729 * 2 : header = On input, pointer to header to modify.
1730 * On output, pointer to the modified header, or NULL
1731 * to remove the header. This function frees the
1732 * original string if necessary.
1734 * Returns : JB_ERR_OK on success, or
1735 * JB_ERR_MEMORY on out-of-memory error.
1737 *********************************************************************/
1738 jb_err server_content_type(struct client_state *csp, char **header)
1740 /* Remove header if it isn't the first Content-Type header */
1741 if(csp->content_type && (csp->content_type != CT_TABOO))
1744 * Another, slightly slower, way to see if
1745 * we already parsed another Content-Type header.
1747 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1749 log_error(LOG_LEVEL_ERROR,
1750 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1757 if (!(csp->content_type & CT_TABOO))
1759 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1760 || strstr(*header, "xml")
1761 || strstr(*header, "application/x-javascript"))
1763 csp->content_type |= CT_TEXT;
1765 else if (strstr(*header, " image/gif"))
1767 csp->content_type |= CT_GIF;
1769 else if (strstr(*header, " image/jpeg"))
1771 csp->content_type |= CT_JPEG;
1775 csp->content_type = 0;
1779 * Are we enabling text mode by force?
1781 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1784 * Do we really have to?
1786 if (csp->content_type & CT_TEXT)
1788 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1792 csp->content_type |= CT_TEXT;
1793 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1797 * Are we messing with the content type?
1799 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1802 * Make sure the user doesn't accidently
1803 * change the content type of binary documents.
1805 if (csp->content_type & CT_TEXT)
1808 *header = strdup("Content-Type: ");
1809 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1813 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1814 return JB_ERR_MEMORY;
1816 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1820 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1821 "Enable force-text-mode if you know what you're doing.", *header);
1828 /*********************************************************************
1830 * Function : server_transfer_coding
1832 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1833 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1834 * - Remove header if body was chunked but has been
1835 * de-chunked for filtering.
1838 * 1 : csp = Current client state (buffers, headers, etc...)
1839 * 2 : header = On input, pointer to header to modify.
1840 * On output, pointer to the modified header, or NULL
1841 * to remove the header. This function frees the
1842 * original string if necessary.
1844 * Returns : JB_ERR_OK on success, or
1845 * JB_ERR_MEMORY on out-of-memory error.
1847 *********************************************************************/
1848 jb_err server_transfer_coding(struct client_state *csp, char **header)
1851 * Turn off pcrs and gif filtering if body compressed
1853 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1857 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1859 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1860 csp->http->cmd, *header);
1861 #endif /* def FEATURE_ZLIB */
1862 csp->content_type = CT_TABOO;
1866 * Raise flag if body chunked
1868 if (strstr(*header, "chunked"))
1870 csp->flags |= CSP_FLAG_CHUNKED;
1873 * If the body was modified, it has been de-chunked first
1874 * and the header must be removed.
1876 * FIXME: If there is more than one transfer encoding,
1877 * only the "chunked" part should be removed here.
1879 if (csp->flags & CSP_FLAG_MODIFIED)
1881 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1890 /*********************************************************************
1892 * Function : server_content_encoding
1894 * Description : This function is run twice for each request,
1895 * unless FEATURE_ZLIB and filtering are disabled.
1897 * The first run is used to check if the content
1898 * is compressed, if FEATURE_ZLIB is disabled
1899 * filtering is then disabled as well, if FEATURE_ZLIB
1900 * is enabled the content is marked for decompression.
1902 * The second run is used to remove the Content-Encoding
1903 * header if the decompression was successful.
1906 * 1 : csp = Current client state (buffers, headers, etc...)
1907 * 2 : header = On input, pointer to header to modify.
1908 * On output, pointer to the modified header, or NULL
1909 * to remove the header. This function frees the
1910 * original string if necessary.
1912 * Returns : JB_ERR_OK on success, or
1913 * JB_ERR_MEMORY on out-of-memory error.
1915 *********************************************************************/
1916 jb_err server_content_encoding(struct client_state *csp, char **header)
1919 if ((csp->flags & CSP_FLAG_MODIFIED)
1920 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1923 * We successfully decompressed the content,
1924 * and have to clean the header now, so the
1925 * client no longer expects compressed data..
1927 * XXX: There is a difference between cleaning
1928 * and removing it completely.
1930 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1933 else if (strstr(*header, "gzip"))
1935 /* Mark for gzip decompression */
1936 csp->content_type |= CT_GZIP;
1938 else if (strstr(*header, "deflate"))
1940 /* Mark for zlib decompression */
1941 csp->content_type |= CT_DEFLATE;
1943 else if (strstr(*header, "compress"))
1946 * We can't decompress this; therefore we can't filter
1949 csp->content_type |= CT_TABOO;
1951 #else /* !defined(FEATURE_ZLIB) */
1952 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1955 * Body is compressed, turn off pcrs and gif filtering.
1957 csp->content_type |= CT_TABOO;
1959 #endif /* !defined(FEATURE_ZLIB) */
1966 /*********************************************************************
1968 * Function : server_content_length
1970 * Description : Adjust Content-Length header if we modified
1974 * 1 : csp = Current client state (buffers, headers, etc...)
1975 * 2 : header = On input, pointer to header to modify.
1976 * On output, pointer to the modified header, or NULL
1977 * to remove the header. This function frees the
1978 * original string if necessary.
1980 * Returns : JB_ERR_OK on success, or
1981 * JB_ERR_MEMORY on out-of-memory error.
1983 *********************************************************************/
1984 jb_err server_content_length(struct client_state *csp, char **header)
1986 const size_t max_header_length = 80;
1988 /* Regenerate header if the content was modified. */
1989 if (csp->flags & CSP_FLAG_MODIFIED)
1992 *header = (char *) zalloc(max_header_length);
1993 if (*header == NULL)
1995 return JB_ERR_MEMORY;
1998 snprintf(*header, max_header_length, "Content-Length: %d",
1999 (int)csp->content_length);
2000 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2001 (int)csp->content_length);
2008 /*********************************************************************
2010 * Function : server_content_md5
2012 * Description : Crumble any Content-MD5 headers if the document was
2013 * modified. FIXME: Should we re-compute instead?
2016 * 1 : csp = Current client state (buffers, headers, etc...)
2017 * 2 : header = On input, pointer to header to modify.
2018 * On output, pointer to the modified header, or NULL
2019 * to remove the header. This function frees the
2020 * original string if necessary.
2022 * Returns : JB_ERR_OK on success, or
2023 * JB_ERR_MEMORY on out-of-memory error.
2025 *********************************************************************/
2026 jb_err server_content_md5(struct client_state *csp, char **header)
2028 if (csp->flags & CSP_FLAG_MODIFIED)
2030 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2037 /*********************************************************************
2039 * Function : server_content_disposition
2041 * Description : If enabled, blocks or modifies the "content-disposition" header.
2042 * Called from `sed'.
2045 * 1 : csp = Current client state (buffers, headers, etc...)
2046 * 2 : header = On input, pointer to header to modify.
2047 * On output, pointer to the modified header, or NULL
2048 * to remove the header. This function frees the
2049 * original string if necessary.
2051 * Returns : JB_ERR_OK on success, or
2052 * JB_ERR_MEMORY on out-of-memory error.
2054 *********************************************************************/
2055 jb_err server_content_disposition(struct client_state *csp, char **header)
2060 * Are we messing with the content-disposition header?
2062 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2068 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2070 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2073 * Blocking content-disposition header
2075 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2082 * Replacing content-disposition header
2085 *header = strdup("content-disposition: ");
2086 string_append(header, newval);
2088 if (*header == NULL)
2090 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2094 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2097 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2100 /*********************************************************************
2102 * Function : server_last_modified
2104 * Description : Changes Last-Modified header to the actual date
2105 * to help hide-if-modified-since.
2106 * Called from `sed'.
2109 * 1 : csp = Current client state (buffers, headers, etc...)
2110 * 2 : header = On input, pointer to header to modify.
2111 * On output, pointer to the modified header, or NULL
2112 * to remove the header. This function frees the
2113 * original string if necessary.
2115 * Returns : JB_ERR_OK on success, or
2116 * JB_ERR_MEMORY on out-of-memory error.
2118 *********************************************************************/
2119 jb_err server_last_modified(struct client_state *csp, char **header)
2122 char buf[BUFFER_SIZE];
2125 #ifdef HAVE_GMTIME_R
2128 struct tm *timeptr = NULL;
2129 time_t now, last_modified;
2131 long int days, hours, minutes, seconds;
2134 * Are we messing with the Last-Modified header?
2136 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2142 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2144 if (0 == strcmpic(newval, "block") )
2147 * Blocking Last-Modified header. Useless but why not.
2149 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2153 else if (0 == strcmpic(newval, "reset-to-request-time"))
2156 * Setting Last-Modified Header to now.
2158 get_http_time(0, buf);
2160 *header = strdup("Last-Modified: ");
2161 string_append(header, buf);
2163 if (*header == NULL)
2165 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2169 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2172 else if (0 == strcmpic(newval, "randomize"))
2174 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2176 #ifdef HAVE_GMTIME_R
2177 timeptr = gmtime_r(&now, &gmt);
2178 #elif FEATURE_PTHREAD
2179 pthread_mutex_lock(&gmtime_mutex);
2180 timeptr = gmtime(&now);
2181 pthread_mutex_unlock(&gmtime_mutex);
2183 timeptr = gmtime(&now);
2185 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
2187 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2192 rtime = (long int)difftime(now, last_modified);
2195 rtime = pick_from_range(rtime);
2196 last_modified += rtime;
2197 #ifdef HAVE_GMTIME_R
2198 timeptr = gmtime_r(&last_modified, &gmt);
2199 #elif FEATURE_PTHREAD
2200 pthread_mutex_lock(&gmtime_mutex);
2201 timeptr = gmtime(&last_modified);
2202 pthread_mutex_unlock(&gmtime_mutex);
2204 timeptr = gmtime(&last_modified);
2206 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2208 *header = strdup("Last-Modified: ");
2209 string_append(header, newheader);
2211 if (*header == NULL)
2213 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2214 return JB_ERR_MEMORY;
2217 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2219 days = rtime / (3600 * 24);
2220 hours = rtime / 3600 % 24;
2221 minutes = rtime / 60 % 60;
2222 seconds = rtime % 60;
2224 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2225 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2226 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2231 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2240 /*********************************************************************
2242 * Function : client_accept_encoding
2244 * Description : Rewrite the client's Accept-Encoding header so that
2245 * if doesn't allow compression, if the action applies.
2246 * Note: For HTTP/1.0 the absence of the header is enough.
2249 * 1 : csp = Current client state (buffers, headers, etc...)
2250 * 2 : header = On input, pointer to header to modify.
2251 * On output, pointer to the modified header, or NULL
2252 * to remove the header. This function frees the
2253 * original string if necessary.
2255 * Returns : JB_ERR_OK on success, or
2256 * JB_ERR_MEMORY on out-of-memory error.
2258 *********************************************************************/
2259 jb_err client_accept_encoding(struct client_state *csp, char **header)
2261 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2263 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2267 /* Temporarily disable the correct behaviour to
2268 * work around a PHP bug.
2270 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2272 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2273 * if (*header == NULL)
2275 * return JB_ERR_MEMORY;
2286 /*********************************************************************
2288 * Function : client_te
2290 * Description : Rewrite the client's TE header so that
2291 * if doesn't allow compression, if the action applies.
2294 * 1 : csp = Current client state (buffers, headers, etc...)
2295 * 2 : header = On input, pointer to header to modify.
2296 * On output, pointer to the modified header, or NULL
2297 * to remove the header. This function frees the
2298 * original string if necessary.
2300 * Returns : JB_ERR_OK on success, or
2301 * JB_ERR_MEMORY on out-of-memory error.
2303 *********************************************************************/
2304 jb_err client_te(struct client_state *csp, char **header)
2306 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2309 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2315 /*********************************************************************
2317 * Function : client_referrer
2319 * Description : Handle the "referer" config setting properly.
2320 * Called from `sed'.
2323 * 1 : csp = Current client state (buffers, headers, etc...)
2324 * 2 : header = On input, pointer to header to modify.
2325 * On output, pointer to the modified header, or NULL
2326 * to remove the header. This function frees the
2327 * original string if necessary.
2329 * Returns : JB_ERR_OK on success, or
2330 * JB_ERR_MEMORY on out-of-memory error.
2332 *********************************************************************/
2333 jb_err client_referrer(struct client_state *csp, char **header)
2340 #ifdef FEATURE_FORCE_LOAD
2341 /* Since the referrer can include the prefix even
2342 * if the request itself is non-forced, we must
2343 * clean it unconditionally
2345 strclean(*header, FORCE_PREFIX);
2346 #endif /* def FEATURE_FORCE_LOAD */
2349 * Are we sending referer?
2351 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2356 newval = csp->action->string[ACTION_STRING_REFERER];
2358 if ((0 != strcmpic(newval, "conditional-block")))
2362 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2367 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2370 else if (0 == strcmpic(newval, "conditional-block"))
2373 * Block referer if host has changed.
2376 if (NULL == (host = strdup(csp->http->hostport)))
2379 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2380 return JB_ERR_MEMORY;
2382 if (NULL == (referer = strdup(*header)))
2386 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2387 return JB_ERR_MEMORY;
2389 hostlenght = strlen(host);
2390 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2392 /*Shorten referer to make sure the referer is blocked
2393 *if www.example.org/www.example.com-shall-see-the-referer/
2394 *links to www.example.com/
2396 referer[hostlenght+17] = '\0';
2398 if ( 0 == strstr(referer, host)) /*Host has changed*/
2400 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2405 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2411 else if (0 != strcmpic(newval, "forge"))
2414 * We have a specific (fixed) referer we want to send.
2416 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2418 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2420 *header = strdup("Referer: ");
2421 string_append(header, newval);
2422 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2424 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2429 * Forge a referer as http://[hostname:port of REQUEST]/
2430 * to fool stupid checks for in-site links
2433 *header = strdup("Referer: http://");
2434 string_append(header, csp->http->hostport);
2435 string_append(header, "/");
2436 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2438 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2442 /*********************************************************************
2444 * Function : client_accept_language
2446 * Description : Handle the "Accept-Language" config setting properly.
2447 * Called from `sed'.
2450 * 1 : csp = Current client state (buffers, headers, etc...)
2451 * 2 : header = On input, pointer to header to modify.
2452 * On output, pointer to the modified header, or NULL
2453 * to remove the header. This function frees the
2454 * original string if necessary.
2456 * Returns : JB_ERR_OK on success, or
2457 * JB_ERR_MEMORY on out-of-memory error.
2459 *********************************************************************/
2460 jb_err client_accept_language(struct client_state *csp, char **header)
2465 * Are we messing with the Accept-Language?
2467 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2469 /*I don't think so*/
2473 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2475 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2478 * Blocking Accept-Language header
2480 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2487 * Replacing Accept-Language header
2490 *header = strdup("Accept-Language: ");
2491 string_append(header, newval);
2493 if (*header == NULL)
2495 log_error(LOG_LEVEL_ERROR,
2496 "Insufficent memory. Accept-Language header crunched without replacement.");
2500 log_error(LOG_LEVEL_HEADER,
2501 "Accept-Language header crunched and replaced with: %s", *header);
2504 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2507 /*********************************************************************
2509 * Function : crunch_client_header
2511 * Description : Crunch client header if it matches a string supplied by the
2512 * user. Called from `sed'.
2515 * 1 : csp = Current client state (buffers, headers, etc...)
2516 * 2 : header = On input, pointer to header to modify.
2517 * On output, pointer to the modified header, or NULL
2518 * to remove the header. This function frees the
2519 * original string if necessary.
2521 * Returns : JB_ERR_OK on success and always succeeds
2523 *********************************************************************/
2524 jb_err crunch_client_header(struct client_state *csp, char **header)
2526 const char *crunch_pattern;
2528 /* Do we feel like crunching? */
2529 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2531 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2533 /* Is the current header the lucky one? */
2534 if (strstr(*header, crunch_pattern))
2536 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2544 /*********************************************************************
2546 * Function : client_uagent
2548 * Description : Handle the "user-agent" config setting properly
2549 * and remember its original value to enable browser
2550 * bug workarounds. Called from `sed'.
2553 * 1 : csp = Current client state (buffers, headers, etc...)
2554 * 2 : header = On input, pointer to header to modify.
2555 * On output, pointer to the modified header, or NULL
2556 * to remove the header. This function frees the
2557 * original string if necessary.
2559 * Returns : JB_ERR_OK on success, or
2560 * JB_ERR_MEMORY on out-of-memory error.
2562 *********************************************************************/
2563 jb_err client_uagent(struct client_state *csp, char **header)
2567 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2572 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2579 *header = strdup("User-Agent: ");
2580 string_append(header, newval);
2582 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2584 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2587 /*********************************************************************
2589 * Function : client_ua
2591 * Description : Handle "ua-" headers properly. Called from `sed'.
2594 * 1 : csp = Current client state (buffers, headers, etc...)
2595 * 2 : header = On input, pointer to header to modify.
2596 * On output, pointer to the modified header, or NULL
2597 * to remove the header. This function frees the
2598 * original string if necessary.
2600 * Returns : JB_ERR_OK on success, or
2601 * JB_ERR_MEMORY on out-of-memory error.
2603 *********************************************************************/
2604 jb_err client_ua(struct client_state *csp, char **header)
2606 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2608 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2616 /*********************************************************************
2618 * Function : client_from
2620 * Description : Handle the "from" config setting properly.
2621 * Called from `sed'.
2624 * 1 : csp = Current client state (buffers, headers, etc...)
2625 * 2 : header = On input, pointer to header to modify.
2626 * On output, pointer to the modified header, or NULL
2627 * to remove the header. This function frees the
2628 * original string if necessary.
2630 * Returns : JB_ERR_OK on success, or
2631 * JB_ERR_MEMORY on out-of-memory error.
2633 *********************************************************************/
2634 jb_err client_from(struct client_state *csp, char **header)
2638 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2645 newval = csp->action->string[ACTION_STRING_FROM];
2648 * Are we blocking the e-mail address?
2650 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2652 log_error(LOG_LEVEL_HEADER, "crunched From!");
2656 log_error(LOG_LEVEL_HEADER, " modified");
2658 *header = strdup("From: ");
2659 string_append(header, newval);
2661 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2665 /*********************************************************************
2667 * Function : client_send_cookie
2669 * Description : Crunches the "cookie" header if necessary.
2670 * Called from `sed'.
2672 * XXX: Stupid name, doesn't send squat.
2675 * 1 : csp = Current client state (buffers, headers, etc...)
2676 * 2 : header = On input, pointer to header to modify.
2677 * On output, pointer to the modified header, or NULL
2678 * to remove the header. This function frees the
2679 * original string if necessary.
2681 * Returns : JB_ERR_OK on success, or
2682 * JB_ERR_MEMORY on out-of-memory error.
2684 *********************************************************************/
2685 jb_err client_send_cookie(struct client_state *csp, char **header)
2687 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2689 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2697 /*********************************************************************
2699 * Function : client_x_forwarded
2701 * Description : Handle the "x-forwarded-for" config setting properly,
2702 * also used in the add_client_headers list. Called from `sed'.
2705 * 1 : csp = Current client state (buffers, headers, etc...)
2706 * 2 : header = On input, pointer to header to modify.
2707 * On output, pointer to the modified header, or NULL
2708 * to remove the header. This function frees the
2709 * original string if necessary.
2711 * Returns : JB_ERR_OK on success, or
2712 * JB_ERR_MEMORY on out-of-memory error.
2714 *********************************************************************/
2715 jb_err client_x_forwarded(struct client_state *csp, char **header)
2717 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2719 /* Save it so we can re-add it later */
2720 freez(csp->x_forwarded);
2721 csp->x_forwarded = *header;
2724 * Always set *header = NULL, since this information
2725 * will be sent at the end of the header.
2732 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2739 /*********************************************************************
2741 * Function : client_max_forwards
2743 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2744 * from the value of the Max-Forwards header field.
2747 * 1 : csp = Current client state (buffers, headers, etc...)
2748 * 2 : header = On input, pointer to header to modify.
2749 * On output, pointer to the modified header, or NULL
2750 * to remove the header. This function frees the
2751 * original string if necessary.
2753 * Returns : JB_ERR_OK on success, or
2754 * JB_ERR_MEMORY on out-of-memory error.
2756 *********************************************************************/
2757 jb_err client_max_forwards(struct client_state *csp, char **header)
2761 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2762 (0 == strcmpic(csp->http->gpc, "options")))
2764 assert(*(*header+12) == ':');
2765 if (1 == sscanf(*header+12, ": %u", &max_forwards))
2767 if (max_forwards > 0)
2769 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
2770 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
2771 csp->http->gpc, max_forwards);
2773 else if (max_forwards < 0)
2775 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2781 * Not supposed to be reached. direct_response() which
2782 * was already called earlier in chat() should have
2783 * intercepted the request.
2785 log_error(LOG_LEVEL_ERROR,
2786 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2787 assert(max_forwards != 0);
2792 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2801 /*********************************************************************
2803 * Function : client_host
2805 * Description : If the request URI did not contain host and
2806 * port information, parse and evaluate the Host
2809 * Also, kill ill-formed HOST: headers as sent by
2810 * Apple's iTunes software when used with a proxy.
2813 * 1 : csp = Current client state (buffers, headers, etc...)
2814 * 2 : header = On input, pointer to header to modify.
2815 * On output, pointer to the modified header, or NULL
2816 * to remove the header. This function frees the
2817 * original string if necessary.
2819 * Returns : JB_ERR_OK on success, or
2820 * JB_ERR_MEMORY on out-of-memory error.
2822 *********************************************************************/
2823 jb_err client_host(struct client_state *csp, char **header)
2828 * If the header field name is all upper-case, chances are that it's
2829 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2830 * not a problem -- they are regenerated later.
2832 if ((*header)[1] == 'O')
2834 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2839 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2840 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2843 if (NULL == (p = strdup((*header)+6)))
2845 return JB_ERR_MEMORY;
2848 if (NULL == (q = strdup(p)))
2851 return JB_ERR_MEMORY;
2854 freez(csp->http->hostport);
2855 csp->http->hostport = p;
2856 freez(csp->http->host);
2857 csp->http->host = q;
2858 q = strchr(csp->http->host, ':');
2861 /* Terminate hostname and evaluate port string */
2863 csp->http->port = atoi(q);
2867 csp->http->port = csp->http->ssl ? 443 : 80;
2870 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2871 csp->http->hostport, csp->http->host, csp->http->port);
2874 /* Signal client_host_adder() to return right away */
2875 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
2880 /*********************************************************************
2882 * Function : client_if_modified_since
2884 * Description : Remove or modify the If-Modified-Since header.
2887 * 1 : csp = Current client state (buffers, headers, etc...)
2888 * 2 : header = On input, pointer to header to modify.
2889 * On output, pointer to the modified header, or NULL
2890 * to remove the header. This function frees the
2891 * original string if necessary.
2893 * Returns : JB_ERR_OK on success, or
2894 * JB_ERR_MEMORY on out-of-memory error.
2896 *********************************************************************/
2897 jb_err client_if_modified_since(struct client_state *csp, char **header)
2900 #ifdef HAVE_GMTIME_R
2903 struct tm *timeptr = NULL;
2907 long int hours, minutes, seconds;
2911 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2914 * The client got an error message because of a temporary problem,
2915 * the problem is gone and the client now tries to revalidate our
2916 * error message on the real server. The revalidation would always
2917 * end with the transmission of the whole document and there is
2918 * no need to expose the bogus If-Modified-Since header.
2920 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2923 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2925 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2927 if ((0 == strcmpic(newval, "block")))
2929 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2932 else /* add random value */
2934 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2936 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2941 rtime = strtol(newval, &endptr, 0);
2944 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2945 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2952 rtime = pick_from_range(rtime);
2956 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2959 tm += rtime * (negative ? -1 : 1);
2960 #ifdef HAVE_GMTIME_R
2961 timeptr = gmtime_r(&tm, &gmt);
2962 #elif FEATURE_PTHREAD
2963 pthread_mutex_lock(&gmtime_mutex);
2964 timeptr = gmtime(&tm);
2965 pthread_mutex_unlock(&gmtime_mutex);
2967 timeptr = gmtime(&tm);
2969 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2972 *header = strdup("If-Modified-Since: ");
2973 string_append(header, newheader);
2975 if (*header == NULL)
2977 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2978 return JB_ERR_MEMORY;
2981 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2983 hours = rtime / 3600;
2984 minutes = rtime / 60 % 60;
2985 seconds = rtime % 60;
2987 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2988 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2989 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2998 /*********************************************************************
3000 * Function : client_if_none_match
3002 * Description : Remove the If-None-Match header.
3005 * 1 : csp = Current client state (buffers, headers, etc...)
3006 * 2 : header = On input, pointer to header to modify.
3007 * On output, pointer to the modified header, or NULL
3008 * to remove the header. This function frees the
3009 * original string if necessary.
3011 * Returns : JB_ERR_OK on success, or
3012 * JB_ERR_MEMORY on out-of-memory error.
3014 *********************************************************************/
3015 jb_err client_if_none_match(struct client_state *csp, char **header)
3017 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3019 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3026 /*********************************************************************
3028 * Function : client_x_filter
3030 * Description : Disables filtering if the client set "X-Filter: No".
3031 * Called from `sed'.
3034 * 1 : csp = Current client state (buffers, headers, etc...)
3035 * 2 : header = On input, pointer to header to modify.
3036 * On output, pointer to the modified header, or NULL
3037 * to remove the header. This function frees the
3038 * original string if necessary.
3040 * Returns : JB_ERR_OK on success
3042 *********************************************************************/
3043 jb_err client_x_filter(struct client_state *csp, char **header)
3045 if ( 0 == strcmpic(*header, "X-Filter: No"))
3047 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3049 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3053 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3055 log_error(LOG_LEVEL_HEADER,
3056 "force-text-mode overruled the client's request to fetch without filtering!");
3060 csp->content_type = CT_TABOO;
3061 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
3062 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
3063 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3065 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3072 /* the following functions add headers directly to the header list */
3074 /*********************************************************************
3076 * Function : client_host_adder
3078 * Description : Adds the Host: header field if it is missing.
3079 * Called from `sed'.
3082 * 1 : csp = Current client state (buffers, headers, etc...)
3084 * Returns : JB_ERR_OK on success, or
3085 * JB_ERR_MEMORY on out-of-memory error.
3087 *********************************************************************/
3088 jb_err client_host_adder(struct client_state *csp)
3093 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3095 /* Header already set by the client, nothing to do. */
3099 if ( !csp->http->hostport || !*(csp->http->hostport))
3101 /* XXX: When does this happen and why is it OK? */
3102 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3107 * remove 'user:pass@' from 'proto://user:pass@host'
3109 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3115 p = csp->http->hostport;
3118 /* XXX: Just add it, we already made sure that it will be unique */
3119 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3120 err = enlist_unique_header(csp->headers, "Host", p);
3126 /*********************************************************************
3128 * Function : client_cookie_adder
3130 * Description : Used in the add_client_headers list. Called from `sed'.
3132 * XXX: Remove csp->cookie_list which is no longer used.
3135 * 1 : csp = Current client state (buffers, headers, etc...)
3137 * Returns : JB_ERR_OK on success, or
3138 * JB_ERR_MEMORY on out-of-memory error.
3140 *********************************************************************/
3141 jb_err client_cookie_adder(struct client_state *csp)
3143 struct list_entry *lst;
3145 struct list_entry *list1 = csp->cookie_list->first;
3146 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
3147 int first_cookie = 1;
3150 if ((list1 == NULL) && (list2 == NULL))
3156 tmp = strdup("Cookie: ");
3158 for (lst = list1; lst ; lst = lst->next)
3166 string_append(&tmp, "; ");
3168 string_append(&tmp, lst->str);
3171 for (lst = list2; lst ; lst = lst->next)
3179 string_append(&tmp, "; ");
3181 string_join(&tmp, cookie_encode(lst->str));
3186 return JB_ERR_MEMORY;
3189 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3190 err = enlist(csp->headers, tmp);
3196 /*********************************************************************
3198 * Function : client_accept_encoding_adder
3200 * Description : Add an Accept-Encoding header to the client's request
3201 * that disables compression if the action applies, and
3202 * the header is not already there. Called from `sed'.
3203 * Note: For HTTP/1.0, the absence of the header is enough.
3206 * 1 : csp = Current client state (buffers, headers, etc...)
3208 * Returns : JB_ERR_OK on success, or
3209 * JB_ERR_MEMORY on out-of-memory error.
3211 *********************************************************************/
3212 jb_err client_accept_encoding_adder(struct client_state *csp)
3214 assert(0); /* Not in use */
3216 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3217 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3219 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3226 /*********************************************************************
3228 * Function : client_xtra_adder
3230 * Description : Used in the add_client_headers list. Called from `sed'.
3233 * 1 : csp = Current client state (buffers, headers, etc...)
3235 * Returns : JB_ERR_OK on success, or
3236 * JB_ERR_MEMORY on out-of-memory error.
3238 *********************************************************************/
3239 jb_err client_xtra_adder(struct client_state *csp)
3241 struct list_entry *lst;
3244 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3245 lst ; lst = lst->next)
3247 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3248 err = enlist(csp->headers, lst->str);
3260 /*********************************************************************
3262 * Function : client_x_forwarded_adder
3264 * Description : Used in the add_client_headers list. Called from `sed'.
3267 * 1 : csp = Current client state (buffers, headers, etc...)
3269 * Returns : JB_ERR_OK on success, or
3270 * JB_ERR_MEMORY on out-of-memory error.
3272 *********************************************************************/
3273 jb_err client_x_forwarded_adder(struct client_state *csp)
3278 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3283 if (csp->x_forwarded)
3285 p = strdup(csp->x_forwarded);
3286 string_append(&p, ", ");
3290 p = strdup("X-Forwarded-For: ");
3292 string_append(&p, csp->ip_addr_str);
3296 return JB_ERR_MEMORY;
3299 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3300 err = enlist(csp->headers, p);
3307 /*********************************************************************
3309 * Function : connection_close_adder
3311 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3312 * support. Adds a "Connection: close" header to csp->headers
3313 * unless the header was already present. Called from `sed'.
3315 * FIXME: This whole function shouldn't be neccessary!
3318 * 1 : csp = Current client state (buffers, headers, etc...)
3320 * Returns : JB_ERR_OK on success, or
3321 * JB_ERR_MEMORY on out-of-memory error.
3323 *********************************************************************/
3324 jb_err connection_close_adder(struct client_state *csp)
3326 const unsigned int flags = csp->flags;
3329 * Return right away if
3331 * - we're parsing server headers and the server header
3332 * "Connection: close" is already set, or if
3334 * - we're parsing client headers and the client header
3335 * "Connection: close" is already set.
3337 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3338 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3339 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3340 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3345 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3347 return enlist(csp->headers, "Connection: close");
3351 /*********************************************************************
3353 * Function : server_http
3355 * Description : - Save the HTTP Status into csp->http->status
3356 * - Set CT_TABOO to prevent filtering if the answer
3357 * is a partial range (HTTP status 206)
3358 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3362 * 1 : csp = Current client state (buffers, headers, etc...)
3363 * 2 : header = On input, pointer to header to modify.
3364 * On output, pointer to the modified header, or NULL
3365 * to remove the header. This function frees the
3366 * original string if necessary.
3368 * Returns : JB_ERR_OK on success, or
3369 * JB_ERR_MEMORY on out-of-memory error.
3371 *********************************************************************/
3372 jb_err server_http(struct client_state *csp, char **header)
3374 /* Signal that were now parsing server headers. */
3375 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
3377 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3378 if (csp->http->status == 206)
3380 csp->content_type = CT_TABOO;
3383 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3386 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3393 /*********************************************************************
3395 * Function : server_set_cookie
3397 * Description : Handle the server "cookie" header properly.
3398 * Log cookie to the jar file. Then "crunch",
3399 * accept or rewrite it to a session cookie.
3400 * Called from `sed'.
3402 * TODO: Allow the user to specify a new expiration
3403 * time to cause the cookie to expire even before the
3404 * browser is closed.
3407 * 1 : csp = Current client state (buffers, headers, etc...)
3408 * 2 : header = On input, pointer to header to modify.
3409 * On output, pointer to the modified header, or NULL
3410 * to remove the header. This function frees the
3411 * original string if necessary.
3413 * Returns : JB_ERR_OK on success, or
3414 * JB_ERR_MEMORY on out-of-memory error.
3416 *********************************************************************/
3417 jb_err server_set_cookie(struct client_state *csp, char **header)
3422 struct tm tm_cookie;
3425 #ifdef FEATURE_COOKIE_JAR
3426 if (csp->config->jar)
3429 * Write timestamp into outbuf.
3431 * Complex because not all OSs have tm_gmtoff or
3432 * the %z field in strftime()
3434 char tempbuf[ BUFFER_SIZE ];
3436 #ifdef HAVE_LOCALTIME_R
3437 tm_now = *localtime_r(&now, &tm_now);
3438 #elif FEATURE_PTHREAD
3439 pthread_mutex_lock(&localtime_mutex);
3440 tm_now = *localtime (&now);
3441 pthread_mutex_unlock(&localtime_mutex);
3443 tm_now = *localtime (&now);
3445 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3447 /* strlen("set-cookie: ") = 12 */
3448 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3450 #endif /* def FEATURE_COOKIE_JAR */
3452 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3454 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
3455 return crumble(csp, header);
3457 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3459 /* Flag whether or not to log a message */
3462 /* A variable to store the tag we're working on */
3465 /* Skip "Set-Cookie:" (11 characters) in header */
3466 cur_tag = *header + 11;
3468 /* skip whitespace between "Set-Cookie:" and value */
3469 while (*cur_tag && ijb_isspace(*cur_tag))
3474 /* Loop through each tag in the cookie */
3478 char *next_tag = strchr(cur_tag, ';');
3479 if (next_tag != NULL)
3481 /* Skip the ';' character itself */
3484 /* skip whitespace ";" and start of tag */
3485 while (*next_tag && ijb_isspace(*next_tag))
3492 /* "Next tag" is the end of the string */
3493 next_tag = cur_tag + strlen(cur_tag);
3497 * Check the expiration date to see
3498 * if the cookie is still valid, if yes,
3499 * rewrite it to a session cookie.
3501 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3504 const char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3505 memset(&tm_cookie, 0, sizeof(tm_cookie));
3507 * Try the valid time formats we know about.
3509 * XXX: This should be moved to parse_header_time().
3511 * XXX: Maybe the log messages should be removed
3512 * for the next stable release. They just exist to
3513 * see which time format gets the most hits and
3514 * should be checked for first.
3516 if (NULL != (match = strptime(expiration_date, "%a, %e-%b-%y %H:%M:%S ", &tm_cookie)))
3518 /* 22-Feb-2008 12:01:18 GMT */
3519 log_error(LOG_LEVEL_HEADER,
3520 "cookie \'%s\' send by %s appears to be using time format 1.",
3521 *header, csp->http->url);
3523 else if (NULL != (match = strptime(expiration_date, "%A, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3525 /* Tue, 02-Jun-2037 20:00:00 GMT */
3526 log_error(LOG_LEVEL_HEADER,
3527 "cookie \'%s\' send by %s appears to be using time format 2.",
3528 *header, csp->http->url);
3530 else if (NULL != (match = strptime(expiration_date, "%a, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3532 /* Tuesday, 02-Jun-2037 20:00:00 GMT */
3534 * On FreeBSD this is never reached because it's handled
3535 * by "format 2" as well. I am, however, not sure if all
3536 * strptime() implementations behave that way.
3538 log_error(LOG_LEVEL_HEADER,
3539 "cookie \'%s\' send by %s appears to be using time format 3.",
3540 *header, csp->http->url);
3542 else if (NULL != (match = strptime(expiration_date, "%a, %e %b %Y %H:%M:%S ", &tm_cookie)))
3544 /* Fri, 22 Feb 2008 19:20:05 GMT */
3545 log_error(LOG_LEVEL_HEADER,
3546 "cookie \'%s\' send by %s appears to be using time format 4.",
3547 *header, csp->http->url);
3549 else if (NULL != (match = strptime(expiration_date, "%A %b %e %H:%M:%S %Y", &tm_cookie)))
3551 /* Thu Mar 08 23:00:00 2007 GMT */
3552 log_error(LOG_LEVEL_HEADER,
3553 "cookie \'%s\' send by %s appears to be using time format 5.",
3554 *header, csp->http->url);
3557 /* Did any of them match? */
3561 * Nope, treat it as if it was still valid.
3563 * XXX: Should we remove the whole cookie instead?
3565 log_error(LOG_LEVEL_ERROR,
3566 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3567 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3573 * Yes. Check if the cookie is still valid.
3575 * If the cookie is already expired it's probably
3576 * a delete cookie and even if it isn't, the browser
3577 * will discard it anyway.
3581 * XXX: timegm() isn't available on some AmigaOS
3582 * versions and our replacement doesn't work.
3584 * Our options are to either:
3586 * - disable session-cookies-only completely if timegm
3589 * - to simply remove all expired tags, like it has
3590 * been done until Privoxy 3.0.6 and to live with
3591 * the consequence that it can cause login/logout
3592 * problems on servers that don't validate their
3593 * input properly, or
3595 * - to replace it with mktime in which
3596 * case there is a slight chance of valid cookies
3597 * passing as already expired.
3599 * This is the way it's currently done and it's not
3600 * as bad as it sounds. If the missing GMT offset is
3601 * enough to change the result of the expiration check
3602 * the cookie will be only valid for a few hours
3603 * anyway, which in many cases will be shorter
3604 * than a browser session.
3606 cookie_time = timegm(&tm_cookie);
3607 if (cookie_time - now < 0)
3609 log_error(LOG_LEVEL_HEADER,
3610 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3611 /* Just in case some clown sets more then one expiration date */
3617 * Still valid, delete expiration date by copying
3618 * the rest of the string over it.
3620 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3621 * since the behaviour of strcpy is undefined for overlapping
3624 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3626 /* That changed the header, need to issue a log message */
3630 * Note that the next tag has now been moved to *cur_tag,
3631 * so we do not need to update the cur_tag pointer.
3639 /* Move on to next cookie tag */
3646 assert(NULL != *header);
3647 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3656 #ifdef FEATURE_FORCE_LOAD
3657 /*********************************************************************
3659 * Function : strclean
3661 * Description : In-Situ-Eliminate all occurances of substring in
3665 * 1 : string = string to clean
3666 * 2 : substring = substring to eliminate
3668 * Returns : Number of eliminations
3670 *********************************************************************/
3671 int strclean(const char *string, const char *substring)
3677 len = strlen(substring);
3679 while((pos = strstr(string, substring)) != NULL)
3686 while (*p++ != '\0');
3693 #endif /* def FEATURE_FORCE_LOAD */
3695 /*********************************************************************
3697 * Function : parse_header_time
3699 * Description : Transforms time inside a HTTP header into
3700 * the usual time format.
3703 * 1 : header = header to parse
3704 * 2 : tm = storage for the resulting time in seconds
3706 * Returns : Time struct containing the header time, or
3707 * NULL in case of a parsing problems.
3709 *********************************************************************/
3710 struct tm *parse_header_time(char *header, time_t *tm) {
3714 struct tm * timeptr;
3717 * Initializing gmt to prevent time zone offsets.
3719 * While this is only necessary on some platforms
3720 * (mingw32 for example), I don't know how to
3721 * detect these automatically and doing it everywhere
3725 #ifdef HAVE_LOCALTIME_R
3726 gmt = *localtime_r(tm, &gmt);
3727 #elif FEATURE_PTHREAD
3728 pthread_mutex_lock(&localtime_mutex);
3729 gmt = *localtime(tm);
3730 pthread_mutex_unlock(&localtime_mutex);
3732 gmt = *localtime(tm);
3735 /* Skipping header name */
3736 timestring = strstr(header, ": ");
3737 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)
3750 /*********************************************************************
3752 * Function : get_destination_from_headers
3754 * Description : Parse the "Host:" header to get the request's destination.
3755 * Only needed if the client's request was forcefully
3756 * redirected into Privoxy.
3758 * Code mainly copied from client_host() which is currently
3759 * run too late for this purpose.
3762 * 1 : headers = List of headers (one of them hopefully being
3763 * the "Host:" header)
3764 * 2 : http = storage for the result (host, port and hostport).
3766 * Returns : JB_ERR_MEMORY in case of memory problems,
3767 * JB_ERR_PARSE if the host header couldn't be found,
3768 * JB_ERR_OK otherwise.
3770 *********************************************************************/
3771 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3777 host = get_header_value(headers, "Host:");
3781 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3782 return JB_ERR_PARSE;
3785 if (NULL == (p = strdup((host))))
3787 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3788 return JB_ERR_MEMORY;
3791 if (NULL == (q = strdup(p)))
3794 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3795 return JB_ERR_MEMORY;
3798 freez(http->hostport);
3802 q = strchr(http->host, ':');
3805 /* Terminate hostname and evaluate port string */
3807 http->port = atoi(q);
3811 http->port = http->ssl ? 443 : 80;
3814 /* Rebuild request URL */
3816 http->url = strdup(http->ssl ? "https://" : "http://");
3817 string_append(&http->url, http->hostport);
3818 string_append(&http->url, http->path);
3819 if (http->url == NULL)
3821 return JB_ERR_MEMORY;
3824 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",