1 const char parsers_rcs[] = "$Id: parsers.c,v 1.89 2007/02/07 16:52:11 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.89 2007/02/07 16:52:11 fabiankeil
49 * Fix log messages regarding the cookie time format
50 * (cookie and request URL were mixed up).
52 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
53 * - Let decompress_iob()
54 * - not corrupt the content if decompression fails
55 * early. (the first byte(s) were lost).
56 * - use pointer arithmetics with defined outcome for
58 * - Use a different kludge to remember a failed decompression.
60 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
61 * Search for Max-Forwards headers case-insensitive,
62 * don't generate the "501 unsupported" message for invalid
63 * Max-Forwards values and don't increase negative ones.
65 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
66 * - Let server_set_cookie() check the expiration date
67 * of cookies and don't touch the ones that are already
68 * expired. Fixes problems with low quality web applications
69 * as described in BR 932612.
71 * - Adjust comment in client_max_forwards to reality;
72 * remove invalid Max-Forwards headers.
74 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
75 * Stop filter_header() from unintentionally removing
76 * empty header lines that were enlisted by the continue
79 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
80 * - Repeat the request URL before logging any headers.
81 * Makes reading the log easier in case of simultaneous requests.
82 * - If there are more than one Content-Type headers in one request,
83 * use the first one and remove the others.
84 * - Remove "newval" variable in server_content_type().
85 * It's only used once.
87 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
88 * Correct a cast, check inflateEnd() exit code
89 * to see if we have to, replace sprintf calls
92 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
93 * Integrate a modified version of Wil Mahan's
94 * zlib patch (PR #895531).
96 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
97 * Skip empty filter files in filter_header()
98 * but don't ignore the ones that come afterwards.
99 * Fixes BR 1619208, this time for real.
101 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
102 * Reverted parts of my last commit
103 * to keep error handling working.
105 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
106 * Fixed gcc43 conversion warnings.
108 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
109 * Bringing back the "useless" localtime() call
110 * I removed in revision 1.67. On some platforms
111 * it's necessary to prevent time zone offsets.
113 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
114 * Rebuild request URL in get_destination_from_headers()
115 * to make sure redirect{pcrs command} works as expected
116 * for intercepted requests.
118 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
119 * Added get_destination_from_headers().
121 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
122 * Make pthread mutex locking more generic. Instead of
123 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
124 * and use mutex locking unless there is an _r function
125 * available. Better safe than sorry.
127 * Fixes "./configure --disable-pthread" and should result
128 * in less threading-related problems on pthread-using platforms,
129 * but it still doesn't fix BR#1122404.
131 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
132 * The special header "X-Filter: No" now disables
133 * header filtering as well.
135 * Revision 1.73 2006/09/23 13:26:38 roro
136 * Replace TABs by spaces in source code.
138 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
139 * Don't print a log message every time filter_headers is
140 * entered or left. It only creates noise without any real
143 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
144 * Fix +hide-if-modified-since{-n}.
146 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
147 * Have hide-if-modified-since interpret the random
148 * range value as minutes instead of hours. Allows
149 * more fine-grained configuration.
151 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
152 * Always have parse_header_time return a pointer
153 * that actual makes sense, even though we currently
154 * only need it to detect problems.
156 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
157 * Added config option enable-remote-http-toggle
158 * to specify if Privoxy should recognize special
159 * headers (currently only X-Filter) to change its
160 * behaviour. Disabled by default.
162 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
163 * After filtering de-chunked instances, remove
164 * "Transfer-Encoding" header entirely instead of changing
165 * it to "Transfer-Encoding: identity", which is invalid.
166 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
168 * Don't use localtime in parse_header_time. An empty time struct
169 * is good enough, it gets overwritten by strptime anyway.
171 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
172 * Use gmtime_r if available, fallback to gmtime with mutex
173 * protection for MacOSX and use vanilla gmtime for the rest.
175 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
176 * Changed client_referrer to use the right type (size_t) for
177 * hostlenght and to shorten the temporary referrer string with
178 * '\0' instead of adding a useless line break.
180 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
181 * - Back to timegm() using GnuPG's replacement if necessary.
182 * Using mktime() and localtime() could add a on hour offset if
183 * the randomize factor was big enough to lead to a summer/wintertime
186 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
188 * - Moved randomization code into pick_from_range().
190 * - Changed parse_header_time definition.
191 * time_t isn't guaranteed to be signed and
192 * if it isn't, -1 isn't available as error code.
193 * Changed some variable types in client_if_modified_since()
194 * because of the same reason.
196 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
197 * OS/2 compilation compatibility fixups
199 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
200 * Changed include from strptime.c to strptime.h
202 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
203 * Split filter-headers{} into filter-client-headers{}
204 * and filter-server-headers{}.
205 * Added parse_header_time() to share some code.
206 * Replaced timegm() with mktime().
208 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
209 * Windows service integration
211 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
212 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
214 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
215 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
216 * with what was really the latest development (the v_3_0_branch branch)
218 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
219 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
221 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
222 * Add the ability to check jpeg images for invalid
223 * lengths of comment blocks. Defensive strategy
224 * against the exploit:
225 * Microsoft Security Bulletin MS04-028
226 * Buffer Overrun in JPEG Processing (GDI+) Could
227 * Allow Code Execution (833987)
228 * Enabled with +inspect-jpegs in actions files.
230 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
231 * Excluded text/plain objects from filtering. This fixes a
232 * couple of client-crashing, download corruption and
233 * Privoxy performance issues, whose root cause lies in
234 * web servers labelling content of unknown type as text/plain.
236 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
237 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
239 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
240 * Completing the previous change
242 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
243 * Added temporary workaround for bug in PHP < 4.2.3
245 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
246 * 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.
248 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
249 * Fix typo: supressed -> suppressed
251 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
252 * Improved cookie logging
254 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
255 * Added basic support for OPTIONS and TRACE HTTP methods:
256 * - New parser function client_max_forwards which decrements
257 * the Max-Forwards HTTP header field of OPTIONS and TRACE
258 * requests by one before forwarding
259 * - New parser function client_host which extracts the host
260 * and port information from the HTTP header field if the
261 * request URI was not absolute
262 * - Don't crumble and re-add the Host: header, but only generate
263 * and append if missing
265 * Revision 1.56 2002/05/12 15:34:22 jongfoster
266 * Fixing typo in a comment
268 * Revision 1.55 2002/05/08 16:01:07 oes
269 * Optimized add_to_iob:
270 * - Use realloc instead of malloc(), memcpy(), free()
271 * - Expand to powers of two if possible, to get
272 * O(log n) reallocs instead of O(n).
273 * - Moved check for buffer limit here from chat
274 * - Report failure via returncode
276 * Revision 1.54 2002/04/02 15:03:16 oes
277 * Tiny code cosmetics
279 * Revision 1.53 2002/03/26 22:29:55 swa
280 * we have a new homepage!
282 * Revision 1.52 2002/03/24 13:25:43 swa
283 * name change related issues
285 * Revision 1.51 2002/03/13 00:27:05 jongfoster
288 * Revision 1.50 2002/03/12 01:45:35 oes
289 * More verbose logging
291 * Revision 1.49 2002/03/09 20:03:52 jongfoster
292 * - Making various functions return int rather than size_t.
293 * (Undoing a recent change). Since size_t is unsigned on
294 * Windows, functions like read_socket that return -1 on
295 * error cannot return a size_t.
297 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
298 * crashes, and also frequently caused JB to jump to 100%
299 * CPU and stay there. (Because it thought it had just
300 * read ((unsigned)-1) == 4Gb of data...)
302 * - The signature of write_socket has changed, it now simply
303 * returns success=0/failure=nonzero.
305 * - Trying to get rid of a few warnings --with-debug on
306 * Windows, I've introduced a new type "jb_socket". This is
307 * used for the socket file descriptors. On Windows, this
308 * is SOCKET (a typedef for unsigned). Everywhere else, it's
309 * an int. The error value can't be -1 any more, so it's
310 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
311 * Windows it maps to the #define INVALID_SOCKET.)
313 * - The signature of bind_port has changed.
315 * Revision 1.48 2002/03/07 03:46:53 oes
316 * Fixed compiler warnings etc
318 * Revision 1.47 2002/02/20 23:15:13 jongfoster
319 * Parsing functions now handle out-of-memory gracefully by returning
322 * Revision 1.46 2002/01/17 21:03:47 jongfoster
323 * Moving all our URL and URL pattern parsing code to urlmatch.c.
325 * Revision 1.45 2002/01/09 14:33:03 oes
326 * Added support for localtime_r.
328 * Revision 1.44 2001/12/14 01:22:54 steudten
329 * Remove 'user:pass@' from 'proto://user:pass@host' for the
330 * new added header 'Host: ..'. (See Req ID 491818)
332 * Revision 1.43 2001/11/23 00:26:38 jongfoster
333 * Fixing two really stupid errors in my previous commit
335 * Revision 1.42 2001/11/22 21:59:30 jongfoster
336 * Adding code to handle +no-cookies-keep
338 * Revision 1.41 2001/11/05 23:43:05 steudten
339 * Add time+date to log files.
341 * Revision 1.40 2001/10/26 20:13:09 jongfoster
342 * ctype.h is needed in Windows, too.
344 * Revision 1.39 2001/10/26 17:40:04 oes
345 * Introduced get_header_value()
346 * Removed http->user_agent, csp->referrer and csp->accept_types
347 * Removed client_accept()
349 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
350 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
351 * threads to call select() simultaneously. So, it's time to do a real, live,
352 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
353 * (native). Both versions will work, but using __OS2__ offers multi-threading.
355 * Revision 1.37 2001/10/23 21:36:02 jongfoster
356 * Documenting sed()'s error behaviou (doc change only)
358 * Revision 1.36 2001/10/13 12:51:51 joergs
359 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
360 * force-load), instead crumble Host: and add it (again) in client_host_adder
361 * (in case we get a HTTP/1.0 request without Host: header and forward it to
362 * a HTTP/1.1 server/proxy).
364 * Revision 1.35 2001/10/09 22:39:21 jongfoster
365 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
368 * Revision 1.34 2001/10/07 18:50:55 oes
369 * Added server_content_encoding, renamed server_transfer_encoding
371 * Revision 1.33 2001/10/07 18:04:49 oes
372 * Changed server_http11 to server_http and its pattern to "HTTP".
373 * Additional functionality: it now saves the HTTP status into
374 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
376 * Revision 1.32 2001/10/07 15:43:28 oes
377 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
378 * client_te and client_accept_encoding_adder, triggered by the new
379 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
380 * changed to allow only identity and chunked, and the TE header is
381 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
383 * parse_http_request no longer does anything than parsing. The rewriting
384 * of http->cmd and version mangling are gone. It now also recognizes
385 * the put and delete methods and saves the url in http->url. Removed
388 * renamed content_type and content_length to have the server_ prefix
390 * server_content_type now only works if csp->content_type != CT_TABOO
392 * added server_transfer_encoding, which
393 * - Sets CT_TABOO to prohibit filtering if encoding compresses
394 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
395 * - Change from "chunked" to "identity" if body was chunked
396 * but has been de-chunked for filtering.
398 * added server_content_md5 which crunches any Content-MD5 headers
399 * if the body was modified.
401 * made server_http11 conditional on +downgrade action
403 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
405 * Revision 1.31 2001/10/05 14:25:02 oes
406 * Crumble Keep-Alive from Server
408 * Revision 1.30 2001/09/29 12:56:03 joergs
409 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
411 * Revision 1.29 2001/09/24 21:09:24 jongfoster
412 * Fixing 2 memory leaks that Guy spotted, where the paramater to
413 * enlist() was not being free()d.
415 * Revision 1.28 2001/09/22 16:32:28 jongfoster
416 * Removing unused #includes.
418 * Revision 1.27 2001/09/20 15:45:25 steudten
420 * add casting from size_t to int for printf()
421 * remove local variable shadow s2
423 * Revision 1.26 2001/09/16 17:05:14 jongfoster
424 * Removing unused #include showarg.h
426 * Revision 1.25 2001/09/16 13:21:27 jongfoster
427 * Changes to use new list functions.
429 * Revision 1.24 2001/09/13 23:05:50 jongfoster
430 * Changing the string paramater to the header parsers a "const".
432 * Revision 1.23 2001/09/12 18:08:19 steudten
434 * In parse_http_request() header rewriting miss the host value, so
435 * from http://www.mydomain.com the result was just " / " not
436 * http://www.mydomain.com/ in case we forward.
438 * Revision 1.22 2001/09/10 10:58:53 oes
439 * Silenced compiler warnings
441 * Revision 1.21 2001/07/31 14:46:00 oes
442 * - Persistant connections now suppressed
443 * - sed() no longer appends empty header to csp->headers
445 * Revision 1.20 2001/07/30 22:08:36 jongfoster
446 * Tidying up #defines:
447 * - All feature #defines are now of the form FEATURE_xxx
448 * - Permanently turned off WIN_GUI_EDIT
449 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
451 * Revision 1.19 2001/07/25 17:21:54 oes
452 * client_uagent now saves copy of User-Agent: header value
454 * Revision 1.18 2001/07/13 14:02:46 oes
455 * - Included fix to repair broken HTTP requests that
456 * don't contain a path, not even '/'.
457 * - Removed all #ifdef PCRS
458 * - content_type now always inspected and classified as
459 * text, gif or other.
460 * - formatting / comments
462 * Revision 1.17 2001/06/29 21:45:41 oes
463 * Indentation, CRLF->LF, Tab-> Space
465 * Revision 1.16 2001/06/29 13:32:42 oes
467 * - Adapted free_http_request
468 * - Removed logentry from cancelled commit
470 * Revision 1.15 2001/06/03 19:12:38 oes
471 * deleted const struct interceptors
473 * Revision 1.14 2001/06/01 18:49:17 jongfoster
474 * Replaced "list_share" with "list" - the tiny memory gain was not
475 * worth the extra complexity.
477 * Revision 1.13 2001/05/31 21:30:33 jongfoster
478 * Removed list code - it's now in list.[ch]
479 * Renamed "permission" to "action", and changed many features
480 * to use the actions file rather than the global config.
482 * Revision 1.12 2001/05/31 17:33:13 oes
486 * Revision 1.11 2001/05/29 20:11:19 joergs
487 * '/ * inside comment' warning removed.
489 * Revision 1.10 2001/05/29 09:50:24 jongfoster
490 * Unified blocklist/imagelist/permissionslist.
491 * File format is still under discussion, but the internal changes
494 * Also modified interceptor behaviour:
495 * - We now intercept all URLs beginning with one of the following
496 * prefixes (and *only* these prefixes):
498 * * http://ijbswa.sf.net/config/
499 * * http://ijbswa.sourceforge.net/config/
500 * - New interceptors "home page" - go to http://i.j.b/ to see it.
501 * - Internal changes so that intercepted and fast redirect pages
502 * are not replaced with an image.
503 * - Interceptors now have the option to send a binary page direct
504 * to the client. (i.e. ijb-send-banner uses this)
505 * - Implemented show-url-info interceptor. (Which is why I needed
506 * the above interceptors changes - a typical URL is
507 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
508 * The previous mechanism would not have intercepted that, and
509 * if it had been intercepted then it then it would have replaced
512 * Revision 1.9 2001/05/28 17:26:33 jongfoster
513 * Fixing segfault if last header was crunched.
514 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
515 * can use the cross-platform sprintf() instead.)
517 * Revision 1.8 2001/05/27 22:17:04 oes
519 * - re_process_buffer no longer writes the modified buffer
520 * to the client, which was very ugly. It now returns the
521 * buffer, which it is then written by chat.
523 * - content_length now adjusts the Content-Length: header
524 * for modified documents rather than crunch()ing it.
525 * (Length info in csp->content_length, which is 0 for
526 * unmodified documents)
528 * - For this to work, sed() is called twice when filtering.
530 * Revision 1.7 2001/05/27 13:19:06 oes
531 * Patched Joergs solution for the content-length in.
533 * Revision 1.6 2001/05/26 13:39:32 jongfoster
534 * Only crunches Content-Length header if applying RE filtering.
535 * Without this fix, Microsoft Windows Update wouldn't work.
537 * Revision 1.5 2001/05/26 00:28:36 jongfoster
538 * Automatic reloading of config file.
539 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
540 * Most of the global variables have been moved to a new
541 * struct configuration_spec, accessed through csp->config->globalname
542 * Most of the globals remaining are used by the Win32 GUI.
544 * Revision 1.4 2001/05/22 18:46:04 oes
546 * - Enabled filtering banners by size rather than URL
547 * by adding patterns that replace all standard banner
548 * sizes with the "Junkbuster" gif to the re_filterfile
550 * - Enabled filtering WebBugs by providing a pattern
551 * which kills all 1x1 images
553 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
554 * which is selected by the (nonstandard and therefore
555 * capital) letter 'U' in the option string.
556 * It causes the quantifiers to be ungreedy by default.
557 * Appending a ? turns back to greedy (!).
559 * - Added a new interceptor ijb-send-banner, which
560 * sends back the "Junkbuster" gif. Without imagelist or
561 * MSIE detection support, or if tinygif = 1, or the
562 * URL isn't recognized as an imageurl, a lame HTML
563 * explanation is sent instead.
565 * - Added new feature, which permits blocking remote
566 * script redirects and firing back a local redirect
568 * The feature is conditionally compiled, i.e. it
569 * can be disabled with --disable-fast-redirects,
570 * plus it must be activated by a "fast-redirects"
571 * line in the config file, has its own log level
572 * and of course wants to be displayed by show-proxy-args
573 * Note: Boy, all the #ifdefs in 1001 locations and
574 * all the fumbling with configure.in and acconfig.h
575 * were *way* more work than the feature itself :-(
577 * - Because a generic redirect template was needed for
578 * this, tinygif = 3 now uses the same.
580 * - Moved GIFs, and other static HTTP response templates
585 * - Removed some >400 CRs again (Jon, you really worked
588 * Revision 1.3 2001/05/20 01:21:20 jongfoster
589 * Version 2.9.4 checkin.
590 * - Merged popupfile and cookiefile, and added control over PCRS
591 * filtering, in new "permissionsfile".
592 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
593 * file error you now get a message box (in the Win32 GUI) rather
594 * than the program exiting with no explanation.
595 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
597 * - Removed tabs from "config"
598 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
599 * - Bumped up version number.
601 * Revision 1.2 2001/05/17 23:02:36 oes
602 * - Made referrer option accept 'L' as a substitute for '§'
604 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
605 * Initial import of version 2.9.3 source tree
608 *********************************************************************/
615 #include <sys/types.h>
628 #if !defined(_WIN32) && !defined(__OS2__)
634 #ifdef FEATURE_PTHREAD
636 /* jcc.h is for mutex semapores only */
637 #endif /* def FEATURE_PTHREAD */
643 #include "jbsockets.h"
644 #include "miscutil.h"
647 #ifndef HAVE_STRPTIME
648 #include "strptime.h"
651 const char parsers_h_rcs[] = PARSERS_H_VERSION;
653 /* Fix a problem with Solaris. There should be no effect on other
655 * Solaris's isspace() is a macro which uses it's argument directly
656 * as an array index. Therefore we need to make sure that high-bit
657 * characters generate +ve values, and ideally we also want to make
658 * the argument match the declared parameter type of "int".
660 * Why did they write a character function that can't take a simple
661 * "char" argument? Doh!
663 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
664 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
667 const struct parsers client_patterns[] = {
668 { "referer:", 8, client_referrer },
669 { "user-agent:", 11, client_uagent },
670 { "ua-", 3, client_ua },
671 { "from:", 5, client_from },
672 { "cookie:", 7, client_send_cookie },
673 { "x-forwarded-for:", 16, client_x_forwarded },
674 { "Accept-Encoding:", 16, client_accept_encoding },
675 { "TE:", 3, client_te },
676 { "Host:", 5, client_host },
677 { "if-modified-since:", 18, client_if_modified_since },
678 { "Keep-Alive:", 11, crumble },
679 { "connection:", 11, crumble },
680 { "proxy-connection:", 17, crumble },
681 { "max-forwards:", 13, client_max_forwards },
682 { "Accept-Language:", 16, client_accept_language },
683 { "if-none-match:", 14, client_if_none_match },
684 { "X-Filter:", 9, client_x_filter },
685 { "*", 0, crunch_client_header },
686 { "*", 0, filter_client_header },
690 const struct parsers server_patterns[] = {
691 { "HTTP", 4, server_http },
692 { "set-cookie:", 11, server_set_cookie },
693 { "connection:", 11, crumble },
694 { "Content-Type:", 13, server_content_type },
695 { "Content-MD5:", 12, server_content_md5 },
696 { "Content-Encoding:", 17, server_content_encoding },
697 { "Transfer-Encoding:", 18, server_transfer_coding },
698 { "Keep-Alive:", 11, crumble },
699 { "content-disposition:", 20, server_content_disposition },
700 { "Last-Modified:", 14, server_last_modified },
701 { "*", 0, crunch_server_header },
702 { "*", 0, filter_server_header },
706 const struct parsers server_patterns_light[] = {
707 { "Content-Length:", 15, server_content_length },
708 { "Transfer-Encoding:", 18, server_transfer_coding },
710 { "Content-Encoding:", 17, server_content_encoding },
711 #endif /* def FEATURE_ZLIB */
715 const add_header_func_ptr add_client_headers[] = {
718 client_x_forwarded_adder,
720 /* Temporarily disabled: client_accept_encoding_adder, */
721 connection_close_adder,
726 const add_header_func_ptr add_server_headers[] = {
727 connection_close_adder,
731 /*********************************************************************
733 * Function : flush_socket
735 * Description : Write any pending "buffered" content.
738 * 1 : fd = file descriptor of the socket to read
739 * 2 : csp = Current client state (buffers, headers, etc...)
741 * Returns : On success, the number of bytes written are returned (zero
742 * indicates nothing was written). On error, -1 is returned,
743 * and errno is set appropriately. If count is zero and the
744 * file descriptor refers to a regular file, 0 will be
745 * returned without causing any other effect. For a special
746 * file, the results are not portable.
748 *********************************************************************/
749 int flush_socket(jb_socket fd, struct client_state *csp)
751 struct iob *iob = csp->iob;
752 int len = iob->eod - iob->cur;
759 if (write_socket(fd, iob->cur, (size_t)len))
763 iob->eod = iob->cur = iob->buf;
769 /*********************************************************************
771 * Function : add_to_iob
773 * Description : Add content to the buffered page, expanding the
774 * buffer if necessary.
777 * 1 : csp = Current client state (buffers, headers, etc...)
778 * 2 : buf = holds the content to be added to the page
779 * 3 : n = number of bytes to be added
781 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
782 * or buffer limit reached.
784 *********************************************************************/
785 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
787 struct iob *iob = csp->iob;
788 size_t used, offset, need, want;
791 if (n <= 0) return JB_ERR_OK;
793 used = (size_t)(iob->eod - iob->buf);
794 offset = (size_t)(iob->cur - iob->buf);
795 need = used + (size_t)n + 1;
798 * If the buffer can't hold the new data, extend it first.
799 * Use the next power of two if possible, else use the actual need.
801 if (need > csp->config->buffer_limit)
803 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
804 return JB_ERR_MEMORY;
807 if (need > iob->size)
809 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
811 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
815 else if (NULL != (p = (char *)realloc(iob->buf, need)))
821 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
822 return JB_ERR_MEMORY;
825 /* Update the iob pointers */
826 iob->cur = p + offset;
831 /* copy the new data into the iob buffer */
832 memcpy(iob->eod, buf, (size_t)n);
834 /* point to the end of the data */
837 /* null terminate == cheap insurance */
846 /*********************************************************************
848 * Function : decompress_iob
850 * Description : Decompress buffered page, expanding the
851 * buffer as necessary. csp->iob->cur
852 * should point to the the beginning of the
853 * compressed data block.
856 * 1 : csp = Current client state (buffers, headers, etc...)
858 * Returns : JB_ERR_OK on success,
859 * JB_ERR_MEMORY if out-of-memory limit reached, and
860 * JB_ERR_COMPRESS if error decompressing buffer.
862 *********************************************************************/
863 jb_err decompress_iob(struct client_state *csp)
865 char *buf; /* new, uncompressed buffer */
866 char *cur; /* Current iob position (to keep the original
867 * iob->cur unmodified if we return early) */
868 size_t bufsize; /* allocated size of the new buffer */
869 size_t skip_size; /* Number of bytes at the beginning of the iob
870 that we should NOT decompress. */
871 int status; /* return status of the inflate() call */
872 z_stream zstr; /* used by calls to zlib */
874 bufsize = csp->iob->size;
875 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
882 * This is to protect the parsing of gzipped data,
883 * but it should(?) be valid for deflated data also.
885 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
886 return JB_ERR_COMPRESS;
889 if (csp->content_type & CT_GZIP)
892 * Our task is slightly complicated by the facts that data
893 * compressed by gzip does not include a zlib header, and
894 * that there is no easily accessible interface in zlib to
895 * handle a gzip header. We strip off the gzip header by
896 * hand, and later inform zlib not to expect a header.
900 * Strip off the gzip header. Please see RFC 1952 for more
901 * explanation of the appropriate fields.
903 if ((*cur++ != (char)0x1f)
904 || (*cur++ != (char)0x8b)
905 || (*cur++ != Z_DEFLATED))
907 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
908 return JB_ERR_COMPRESS;
914 * XXX: These magic numbers should be replaced
915 * with macros to give a better idea what they do.
919 /* The gzip header has reserved bits set; bail out. */
920 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
921 return JB_ERR_COMPRESS;
925 /* Skip extra fields if necessary. */
929 * Skip a given number of bytes, specified
930 * as a 16-bit little-endian value.
933 * XXX: This code used to be:
935 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
937 * which I had to change into:
939 * cur += *cur++ + (*cur++ << 8);
941 * at which point gcc43 finally noticed that the value
942 * of cur is undefined (it depends on which of the
943 * summands is evaluated first).
945 * I haven't come across a site where this
946 * code is actually executed yet, but I hope
951 skip_bytes = *cur++ << 8;
953 assert(skip_bytes == *csp->iob->cur-2 + ((*csp->iob->cur-1) << 8));
956 * The number of bytes to skip should be positive
957 * and we'd like to stay in the buffer.
959 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
961 log_error (LOG_LEVEL_ERROR,
962 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
964 return JB_ERR_COMPRESS;
966 log_error (LOG_LEVEL_INFO,
967 "Skipping %d bytes for gzip compression. Does this sound right?",
972 /* Skip the filename if necessary. */
975 /* A null-terminated string follows. */
979 /* Skip the comment if necessary. */
985 /* Skip the CRC if necessary. */
992 else if (csp->content_type & CT_DEFLATE)
995 * XXX: The debug level should be lowered
996 * before the next stable release.
998 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1000 * In theory (that is, according to RFC 1950), deflate-compressed
1001 * data should begin with a two-byte zlib header and have an
1002 * adler32 checksum at the end. It seems that in practice only
1003 * the raw compressed data is sent. Note that this means that
1004 * we are not RFC 1950-compliant here, but the advantage is that
1005 * this actually works. :)
1007 * We add a dummy null byte to tell zlib where the data ends,
1008 * and later inform it not to expect a header.
1010 * Fortunately, add_to_iob() has thoughtfully null-terminated
1011 * the buffer; we can just increment the end pointer to include
1018 log_error (LOG_LEVEL_ERROR,
1019 "Unable to determine compression format for decompression");
1020 return JB_ERR_COMPRESS;
1023 /* Set up the fields required by zlib. */
1024 zstr.next_in = (Bytef *)cur;
1025 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1026 zstr.zalloc = Z_NULL;
1027 zstr.zfree = Z_NULL;
1028 zstr.opaque = Z_NULL;
1031 * Passing -MAX_WBITS to inflateInit2 tells the library
1032 * that there is no zlib header.
1034 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1036 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1037 return JB_ERR_COMPRESS;
1041 * Next, we allocate new storage for the inflated data.
1042 * We don't modify the existing iob yet, so in case there
1043 * is error in decompression we can recover gracefully.
1045 buf = zalloc (bufsize);
1048 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1049 return JB_ERR_MEMORY;
1052 assert(bufsize >= skip_size);
1053 memcpy(buf, csp->iob->buf, skip_size);
1054 zstr.avail_out = bufsize - skip_size;
1055 zstr.next_out = (Bytef *)buf + skip_size;
1057 /* Try to decompress the whole stream in one shot. */
1058 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1060 /* We need to allocate more memory for the output buffer. */
1062 char *tmpbuf; /* used for realloc'ing the buffer */
1063 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1066 * If zlib wants more data then there's a problem, because
1067 * the complete compressed file should have been buffered.
1069 if (0 == zstr.avail_in)
1071 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1072 return JB_ERR_COMPRESS;
1076 * If we tried the limit and still didn't have enough
1077 * memory, just give up.
1079 if (bufsize == csp->config->buffer_limit)
1081 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1082 return JB_ERR_MEMORY;
1085 /* Try doubling the buffer size each time. */
1088 /* Don't exceed the buffer limit. */
1089 if (bufsize > csp->config->buffer_limit)
1091 bufsize = csp->config->buffer_limit;
1094 /* Try to allocate the new buffer. */
1095 tmpbuf = realloc(buf, bufsize);
1098 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1100 return JB_ERR_MEMORY;
1104 char *oldnext_out = (char *)zstr.next_out;
1107 * Update the fields for inflate() to use the new
1108 * buffer, which may be in a location different from
1111 zstr.avail_out += bufsize - oldbufsize;
1112 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1115 * Compare with an uglier method of calculating these values
1116 * that doesn't require the extra oldbufsize variable.
1118 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1119 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1120 assert(zstr.avail_out > 0);
1126 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1128 log_error(LOG_LEVEL_ERROR,
1129 "Inconsistent stream state after decompression: %s", zstr.msg);
1131 * XXX: Intentionally no return.
1133 * According to zlib.h, Z_STREAM_ERROR is returned
1134 * "if the stream state was inconsistent".
1136 * I assume in this case inflate()'s status
1137 * would also be something different than Z_STREAM_END
1138 * so this check should be redundant, but lets see.
1142 if (status != Z_STREAM_END)
1144 /* We failed to decompress the stream. */
1145 log_error(LOG_LEVEL_ERROR,
1146 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1147 return JB_ERR_COMPRESS;
1151 * Finally, we can actually update the iob, since the
1152 * decompression was successful. First, free the old
1155 freez(csp->iob->buf);
1157 /* Now, update the iob to use the new buffer. */
1158 csp->iob->buf = buf;
1159 csp->iob->cur = csp->iob->buf + skip_size;
1160 csp->iob->eod = (char *)zstr.next_out;
1161 csp->iob->size = bufsize;
1164 * Make sure the new uncompressed iob obeys some minimal
1165 * consistency conditions.
1167 if ((csp->iob->buf < csp->iob->cur)
1168 && (csp->iob->cur <= csp->iob->eod)
1169 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1171 char t = csp->iob->cur[100];
1172 csp->iob->cur[100] = '\0';
1174 * XXX: The debug level should be lowered
1175 * before the next stable release.
1177 log_error(LOG_LEVEL_INFO, "Sucessfully decompressed: %s", csp->iob->cur);
1178 csp->iob->cur[100] = t;
1183 /* It seems that zlib did something weird. */
1184 log_error(LOG_LEVEL_ERROR,
1185 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1186 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1187 csp->iob->eod, csp->iob->buf + csp->iob->size);
1188 return JB_ERR_COMPRESS;
1192 #endif /* defined(FEATURE_ZLIB) */
1195 /*********************************************************************
1197 * Function : get_header
1199 * Description : This (odd) routine will parse the csp->iob
1202 * 1 : csp = Current client state (buffers, headers, etc...)
1204 * Returns : Any one of the following:
1206 * 1) a pointer to a dynamically allocated string that contains a header line
1207 * 2) NULL indicating that the end of the header was reached
1208 * 3) "" indicating that the end of the iob was reached before finding
1209 * a complete header line.
1211 *********************************************************************/
1212 char *get_header(struct client_state *csp)
1218 if ((iob->cur == NULL)
1219 || ((p = strchr(iob->cur, '\n')) == NULL))
1221 return(""); /* couldn't find a complete header */
1226 ret = strdup(iob->cur);
1229 /* FIXME No way to handle error properly */
1230 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1235 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1237 /* is this a blank line (i.e. the end of the header) ? */
1249 /*********************************************************************
1251 * Function : get_header_value
1253 * Description : Get the value of a given header from a chained list
1254 * of header lines or return NULL if no such header is
1255 * present in the list.
1258 * 1 : header_list = pointer to list
1259 * 2 : header_name = string with name of header to look for.
1260 * Trailing colon required, capitalization
1263 * Returns : NULL if not found, else value of header
1265 *********************************************************************/
1266 char *get_header_value(const struct list *header_list, const char *header_name)
1268 struct list_entry *cur_entry;
1272 assert(header_list);
1273 assert(header_name);
1274 length = strlen(header_name);
1276 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1280 if (!strncmpic(cur_entry->str, header_name, length))
1283 * Found: return pointer to start of value
1285 ret = (char *) (cur_entry->str + length);
1286 while (*ret && ijb_isspace(*ret)) ret++;
1299 /*********************************************************************
1303 * Description : add, delete or modify lines in the HTTP header streams.
1304 * On entry, it receives a linked list of headers space
1305 * that was allocated dynamically (both the list nodes
1306 * and the header contents).
1308 * As a side effect it frees the space used by the original
1312 * 1 : pats = list of patterns to match against headers
1313 * 2 : more_headers = list of functions to add more
1314 * headers (client or server)
1315 * 3 : csp = Current client state (buffers, headers, etc...)
1317 * Returns : Single pointer to a fully formed header, or NULL
1318 * on out-of-memory error.
1320 *********************************************************************/
1321 char *sed(const struct parsers pats[],
1322 const add_header_func_ptr more_headers[],
1323 struct client_state *csp)
1325 struct list_entry *p;
1326 const struct parsers *v;
1327 const add_header_func_ptr *f;
1328 jb_err err = JB_ERR_OK;
1332 * If filtering is enabled, sed is run twice,
1333 * but most of the work needs to be done only once.
1335 first_run = (more_headers != NULL ) ? 1 : 0;
1337 if (first_run) /* Parse and print */
1339 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1340 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1342 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1344 /* Header crunch()ed in previous run? -> ignore */
1345 if (p->str == NULL) continue;
1347 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
1349 /* Does the current parser handle this header? */
1350 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1352 err = v->parser(csp, (char **)&(p->str));
1356 /* place any additional headers on the csp->headers list */
1357 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1362 else /* Parse only */
1365 * The second run is only needed if the body was modified
1366 * and the content-lenght has changed.
1368 if (strncmpic(csp->http->cmd, "HEAD", 4))
1370 /*XXX: Code duplication */
1371 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1373 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1375 /* Header crunch()ed in previous run? -> ignore */
1376 if (p->str == NULL) continue;
1378 /* Does the current parser handle this header? */
1379 if (strncmpic(p->str, v->str, v->len) == 0)
1381 err = v->parser(csp, (char **)&(p->str));
1388 if (err != JB_ERR_OK)
1393 return list_to_text(csp->headers);
1397 /* here begins the family of parser functions that reformat header lines */
1399 /*********************************************************************
1401 * Function : filter_server_header
1403 * Description : Checks if server header filtering is enabled.
1404 * If it is, filter_header is called to do the work.
1407 * 1 : csp = Current client state (buffers, headers, etc...)
1408 * 2 : header = On input, pointer to header to modify.
1409 * On output, pointer to the modified header, or NULL
1410 * to remove the header. This function frees the
1411 * original string if necessary.
1413 * Returns : JB_ERR_OK on success and always succeeds
1415 *********************************************************************/
1416 jb_err filter_server_header(struct client_state *csp, char **header)
1418 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
1420 filter_header(csp, header);
1425 /*********************************************************************
1427 * Function : filter_client_header
1429 * Description : Checks if client header filtering is enabled.
1430 * If it is, filter_header is called to do the work.
1433 * 1 : csp = Current client state (buffers, headers, etc...)
1434 * 2 : header = On input, pointer to header to modify.
1435 * On output, pointer to the modified header, or NULL
1436 * to remove the header. This function frees the
1437 * original string if necessary.
1439 * Returns : JB_ERR_OK on success and always succeeds
1441 *********************************************************************/
1442 jb_err filter_client_header(struct client_state *csp, char **header)
1444 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
1446 filter_header(csp, header);
1451 /*********************************************************************
1453 * Function : filter_header
1455 * Description : Executes all text substitutions from all applying
1456 * +filter actions on the header.
1457 * Most of the code was copied from pcrs_filter_response,
1458 * including the rather short variable names
1461 * 1 : csp = Current client state (buffers, headers, etc...)
1462 * 2 : header = On input, pointer to header to modify.
1463 * On output, pointer to the modified header, or NULL
1464 * to remove the header. This function frees the
1465 * original string if necessary.
1467 * Returns : JB_ERR_OK on success and always succeeds
1469 *********************************************************************/
1470 jb_err filter_header(struct client_state *csp, char **header)
1474 size_t size = strlen(*header);
1476 char *newheader = NULL;
1479 struct file_list *fl;
1480 struct re_filterfile_spec *b;
1481 struct list_entry *filtername;
1483 int i, found_filters = 0;
1486 * Need to check the set of re_filterfiles...
1488 for (i = 0; i < MAX_AF_FILES; i++)
1501 if (0 == found_filters)
1503 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1507 for (i = 0; i < MAX_AF_FILES; i++)
1510 if ((NULL == fl) || (NULL == fl->f))
1513 * Either there are no filter files
1514 * left, or this filter file just
1515 * contains no valid filters.
1517 * Continue to be sure we don't miss
1518 * valid filter files that are chained
1519 * after empty or invalid ones.
1524 * For all applying +filter actions, look if a filter by that
1525 * name exists and if yes, execute its pcrs_joblist on the
1528 for (b = fl->f; b; b = b->next)
1530 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1531 filtername ; filtername = filtername->next)
1533 if (strcmp(b->name, filtername->str) == 0)
1535 int current_hits = 0;
1537 if ( NULL == b->joblist )
1539 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1543 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1544 *header, size, b->name);
1546 /* Apply all jobs from the joblist */
1547 for (job = b->joblist; NULL != job; job = job->next)
1549 matches = pcrs_execute(job, *header, size, &newheader, &size);
1552 current_hits += matches;
1553 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1555 *header = newheader;
1557 else if ( 0 == matches )
1559 /* Filter doesn't change header */
1565 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1566 *header, b->name, pcrs_strerror(matches));
1567 if( newheader != NULL)
1569 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1574 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1575 hits += current_hits;
1582 * Additionally checking for hits is important because if
1583 * the continue hack is triggered, server headers can
1584 * arrive empty to separate multiple heads from each other.
1586 if ((0 == size) && hits)
1588 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1596 /*********************************************************************
1598 * Function : crumble
1600 * Description : This is called if a header matches a pattern to "crunch"
1603 * 1 : csp = Current client state (buffers, headers, etc...)
1604 * 2 : header = On input, pointer to header to modify.
1605 * On output, pointer to the modified header, or NULL
1606 * to remove the header. This function frees the
1607 * original string if necessary.
1609 * Returns : JB_ERR_OK on success, or
1610 * JB_ERR_MEMORY on out-of-memory error.
1612 *********************************************************************/
1613 jb_err crumble(struct client_state *csp, char **header)
1615 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1620 /*********************************************************************
1622 * Function : crunch_server_header
1624 * Description : Crunch server header if it matches a string supplied by the
1625 * user. Called from `sed'.
1628 * 1 : csp = Current client state (buffers, headers, etc...)
1629 * 2 : header = On input, pointer to header to modify.
1630 * On output, pointer to the modified header, or NULL
1631 * to remove the header. This function frees the
1632 * original string if necessary.
1634 * Returns : JB_ERR_OK on success and always succeeds
1636 *********************************************************************/
1637 jb_err crunch_server_header(struct client_state *csp, char **header)
1639 const char *crunch_pattern;
1640 /*Is there a header to crunch*/
1642 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1644 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1646 /*Is the current header the lucky one?*/
1647 if (strstr(*header, crunch_pattern))
1649 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1658 /*********************************************************************
1660 * Function : server_content_type
1662 * Description : Set the content-type for filterable types (text/.*,
1663 * .*xml.*, javascript and image/gif) unless filtering has been
1664 * forbidden (CT_TABOO) while parsing earlier headers.
1665 * NOTE: Since text/plain is commonly used by web servers
1666 * for files whose correct type is unknown, we don't
1667 * set CT_TEXT for it.
1670 * 1 : csp = Current client state (buffers, headers, etc...)
1671 * 2 : header = On input, pointer to header to modify.
1672 * On output, pointer to the modified header, or NULL
1673 * to remove the header. This function frees the
1674 * original string if necessary.
1676 * Returns : JB_ERR_OK on success, or
1677 * JB_ERR_MEMORY on out-of-memory error.
1679 *********************************************************************/
1680 jb_err server_content_type(struct client_state *csp, char **header)
1682 /* Remove header if it isn't the first Content-Type header */
1683 if(csp->content_type && (csp->content_type != CT_TABOO))
1686 * Another, slightly slower, way to see if
1687 * we already parsed another Content-Type header.
1689 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1691 log_error(LOG_LEVEL_ERROR,
1692 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1699 if (!(csp->content_type & CT_TABOO))
1701 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1702 || strstr(*header, "xml")
1703 || strstr(*header, "application/x-javascript"))
1705 csp->content_type |= CT_TEXT;
1707 else if (strstr(*header, " image/gif"))
1709 csp->content_type |= CT_GIF;
1711 else if (strstr(*header, " image/jpeg"))
1713 csp->content_type |= CT_JPEG;
1717 csp->content_type = 0;
1721 * Are we enabling text mode by force?
1723 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1726 * Do we really have to?
1728 if (csp->content_type & CT_TEXT)
1730 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1734 csp->content_type |= CT_TEXT;
1735 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1739 * Are we messing with the content type?
1741 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1744 * Make sure the user doesn't accidently
1745 * change the content type of binary documents.
1747 if (csp->content_type & CT_TEXT)
1750 *header = strdup("Content-Type: ");
1751 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1755 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1756 return JB_ERR_MEMORY;
1758 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1762 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1763 "Enable force-text-mode if you know what you're doing.", *header);
1770 /*********************************************************************
1772 * Function : server_transfer_coding
1774 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1775 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1776 * - Remove header if body was chunked but has been
1777 * de-chunked for filtering.
1780 * 1 : csp = Current client state (buffers, headers, etc...)
1781 * 2 : header = On input, pointer to header to modify.
1782 * On output, pointer to the modified header, or NULL
1783 * to remove the header. This function frees the
1784 * original string if necessary.
1786 * Returns : JB_ERR_OK on success, or
1787 * JB_ERR_MEMORY on out-of-memory error.
1789 *********************************************************************/
1790 jb_err server_transfer_coding(struct client_state *csp, char **header)
1793 * Turn off pcrs and gif filtering if body compressed
1795 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1799 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1801 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1802 csp->http->cmd, *header);
1803 #endif /* def FEATURE_ZLIB */
1804 csp->content_type = CT_TABOO;
1808 * Raise flag if body chunked
1810 if (strstr(*header, "chunked"))
1812 csp->flags |= CSP_FLAG_CHUNKED;
1815 * If the body was modified, it has been de-chunked first
1816 * and the header must be removed.
1818 * FIXME: If there is more than one transfer encoding,
1819 * only the "chunked" part should be removed here.
1821 if (csp->flags & CSP_FLAG_MODIFIED)
1823 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1832 /*********************************************************************
1834 * Function : server_content_encoding
1836 * Description : This function is run twice for each request,
1837 * unless FEATURE_ZLIB and filtering are disabled.
1839 * The first run is used to check if the content
1840 * is compressed, if FEATURE_ZLIB is disabled
1841 * filtering is then disabled as well, if FEATURE_ZLIB
1842 * is enabled the content is marked for decompression.
1844 * The second run is used to remove the Content-Encoding
1845 * header if the decompression was successful.
1848 * 1 : csp = Current client state (buffers, headers, etc...)
1849 * 2 : header = On input, pointer to header to modify.
1850 * On output, pointer to the modified header, or NULL
1851 * to remove the header. This function frees the
1852 * original string if necessary.
1854 * Returns : JB_ERR_OK on success, or
1855 * JB_ERR_MEMORY on out-of-memory error.
1857 *********************************************************************/
1858 jb_err server_content_encoding(struct client_state *csp, char **header)
1861 if ((csp->flags & CSP_FLAG_MODIFIED)
1862 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1865 * We successfully decompressed the content,
1866 * and have to clean the header now, so the
1867 * client no longer expects compressed data..
1869 * XXX: There is a difference between cleaning
1870 * and removing it completely.
1872 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1875 else if (strstr(*header, "gzip"))
1877 /* Mark for gzip decompression */
1878 csp->content_type |= CT_GZIP;
1880 else if (strstr(*header, "deflate"))
1882 /* Mark for zlib decompression */
1883 csp->content_type |= CT_DEFLATE;
1885 else if (strstr(*header, "compress"))
1888 * We can't decompress this; therefore we can't filter
1891 csp->content_type |= CT_TABOO;
1893 #else /* !defined(FEATURE_ZLIB) */
1894 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1897 * Body is compressed, turn off pcrs and gif filtering.
1899 csp->content_type |= CT_TABOO;
1901 #endif /* !defined(FEATURE_ZLIB) */
1908 /*********************************************************************
1910 * Function : server_content_length
1912 * Description : Adjust Content-Length header if we modified
1916 * 1 : csp = Current client state (buffers, headers, etc...)
1917 * 2 : header = On input, pointer to header to modify.
1918 * On output, pointer to the modified header, or NULL
1919 * to remove the header. This function frees the
1920 * original string if necessary.
1922 * Returns : JB_ERR_OK on success, or
1923 * JB_ERR_MEMORY on out-of-memory error.
1925 *********************************************************************/
1926 jb_err server_content_length(struct client_state *csp, char **header)
1928 const size_t max_header_length = 80;
1930 /* Regenerate header if the content was modified. */
1931 if (csp->flags & CSP_FLAG_MODIFIED)
1934 *header = (char *) zalloc(max_header_length);
1935 if (*header == NULL)
1937 return JB_ERR_MEMORY;
1940 snprintf(*header, max_header_length, "Content-Length: %d",
1941 (int)csp->content_length);
1942 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
1943 (int)csp->content_length);
1950 /*********************************************************************
1952 * Function : server_content_md5
1954 * Description : Crumble any Content-MD5 headers if the document was
1955 * modified. FIXME: Should we re-compute instead?
1958 * 1 : csp = Current client state (buffers, headers, etc...)
1959 * 2 : header = On input, pointer to header to modify.
1960 * On output, pointer to the modified header, or NULL
1961 * to remove the header. This function frees the
1962 * original string if necessary.
1964 * Returns : JB_ERR_OK on success, or
1965 * JB_ERR_MEMORY on out-of-memory error.
1967 *********************************************************************/
1968 jb_err server_content_md5(struct client_state *csp, char **header)
1970 if (csp->flags & CSP_FLAG_MODIFIED)
1972 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1979 /*********************************************************************
1981 * Function : server_content_disposition
1983 * Description : If enabled, blocks or modifies the "content-disposition" header.
1984 * Called from `sed'.
1987 * 1 : csp = Current client state (buffers, headers, etc...)
1988 * 2 : header = On input, pointer to header to modify.
1989 * On output, pointer to the modified header, or NULL
1990 * to remove the header. This function frees the
1991 * original string if necessary.
1993 * Returns : JB_ERR_OK on success, or
1994 * JB_ERR_MEMORY on out-of-memory error.
1996 *********************************************************************/
1997 jb_err server_content_disposition(struct client_state *csp, char **header)
2002 * Are we messing with the content-disposition header?
2004 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2010 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2012 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2015 * Blocking content-disposition header
2017 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2024 * Replacing content-disposition header
2027 *header = strdup("content-disposition: ");
2028 string_append(header, newval);
2030 if (*header == NULL)
2032 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2036 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2039 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2042 /*********************************************************************
2044 * Function : server_last_modified
2046 * Description : Changes Last-Modified header to the actual date
2047 * to help hide-if-modified-since.
2048 * Called from `sed'.
2051 * 1 : csp = Current client state (buffers, headers, etc...)
2052 * 2 : header = On input, pointer to header to modify.
2053 * On output, pointer to the modified header, or NULL
2054 * to remove the header. This function frees the
2055 * original string if necessary.
2057 * Returns : JB_ERR_OK on success, or
2058 * JB_ERR_MEMORY on out-of-memory error.
2060 *********************************************************************/
2061 jb_err server_last_modified(struct client_state *csp, char **header)
2064 char buf[BUFFER_SIZE];
2067 #ifdef HAVE_GMTIME_R
2070 struct tm *timeptr = NULL;
2071 time_t now, last_modified;
2073 long int days, hours, minutes, seconds;
2076 * Are we messing with the Last-Modified header?
2078 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2084 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2086 if (0 == strcmpic(newval, "block") )
2089 * Blocking Last-Modified header. Useless but why not.
2091 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2095 else if (0 == strcmpic(newval, "reset-to-request-time"))
2098 * Setting Last-Modified Header to now.
2100 get_http_time(0, buf);
2102 *header = strdup("Last-Modified: ");
2103 string_append(header, buf);
2105 if (*header == NULL)
2107 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2111 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2114 else if (0 == strcmpic(newval, "randomize"))
2116 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2118 #ifdef HAVE_GMTIME_R
2119 timeptr = gmtime_r(&now, &gmt);
2120 #elif FEATURE_PTHREAD
2121 pthread_mutex_lock(&gmtime_mutex);
2122 timeptr = gmtime(&now);
2123 pthread_mutex_unlock(&gmtime_mutex);
2125 timeptr = gmtime(&now);
2127 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
2129 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2134 rtime = (long int)difftime(now, last_modified);
2137 rtime = pick_from_range(rtime);
2138 last_modified += rtime;
2139 #ifdef HAVE_GMTIME_R
2140 timeptr = gmtime_r(&last_modified, &gmt);
2141 #elif FEATURE_PTHREAD
2142 pthread_mutex_lock(&gmtime_mutex);
2143 timeptr = gmtime(&last_modified);
2144 pthread_mutex_unlock(&gmtime_mutex);
2146 timeptr = gmtime(&last_modified);
2148 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2150 *header = strdup("Last-Modified: ");
2151 string_append(header, newheader);
2153 if (*header == NULL)
2155 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2156 return JB_ERR_MEMORY;
2159 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2161 days = rtime / (3600 * 24);
2162 hours = rtime / 3600 % 24;
2163 minutes = rtime / 60 % 60;
2164 seconds = rtime % 60;
2166 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2167 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2168 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2173 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2181 /*********************************************************************
2183 * Function : client_accept_encoding
2185 * Description : Rewrite the client's Accept-Encoding header so that
2186 * if doesn't allow compression, if the action applies.
2187 * Note: For HTTP/1.0 the absence of the header is enough.
2190 * 1 : csp = Current client state (buffers, headers, etc...)
2191 * 2 : header = On input, pointer to header to modify.
2192 * On output, pointer to the modified header, or NULL
2193 * to remove the header. This function frees the
2194 * original string if necessary.
2196 * Returns : JB_ERR_OK on success, or
2197 * JB_ERR_MEMORY on out-of-memory error.
2199 *********************************************************************/
2200 jb_err client_accept_encoding(struct client_state *csp, char **header)
2202 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2204 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2208 /* Temporarily disable the correct behaviour to
2209 * work around a PHP bug.
2211 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2213 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2214 * if (*header == NULL)
2216 * return JB_ERR_MEMORY;
2227 /*********************************************************************
2229 * Function : client_te
2231 * Description : Rewrite the client's TE header so that
2232 * if doesn't allow compression, if the action applies.
2235 * 1 : csp = Current client state (buffers, headers, etc...)
2236 * 2 : header = On input, pointer to header to modify.
2237 * On output, pointer to the modified header, or NULL
2238 * to remove the header. This function frees the
2239 * original string if necessary.
2241 * Returns : JB_ERR_OK on success, or
2242 * JB_ERR_MEMORY on out-of-memory error.
2244 *********************************************************************/
2245 jb_err client_te(struct client_state *csp, char **header)
2247 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2250 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2256 /*********************************************************************
2258 * Function : client_referrer
2260 * Description : Handle the "referer" config setting properly.
2261 * Called from `sed'.
2264 * 1 : csp = Current client state (buffers, headers, etc...)
2265 * 2 : header = On input, pointer to header to modify.
2266 * On output, pointer to the modified header, or NULL
2267 * to remove the header. This function frees the
2268 * original string if necessary.
2270 * Returns : JB_ERR_OK on success, or
2271 * JB_ERR_MEMORY on out-of-memory error.
2273 *********************************************************************/
2274 jb_err client_referrer(struct client_state *csp, char **header)
2281 #ifdef FEATURE_FORCE_LOAD
2282 /* Since the referrer can include the prefix even
2283 * if the request itself is non-forced, we must
2284 * clean it unconditionally
2286 strclean(*header, FORCE_PREFIX);
2287 #endif /* def FEATURE_FORCE_LOAD */
2290 * Are we sending referer?
2292 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2297 newval = csp->action->string[ACTION_STRING_REFERER];
2299 if ((0 != strcmpic(newval, "conditional-block")))
2303 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2308 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2311 else if (0 == strcmpic(newval, "conditional-block"))
2314 * Block referer if host has changed.
2317 if (NULL == (host = strdup(csp->http->hostport)))
2320 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2321 return JB_ERR_MEMORY;
2323 if (NULL == (referer = strdup(*header)))
2327 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2328 return JB_ERR_MEMORY;
2330 hostlenght = strlen(host);
2331 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2333 /*Shorten referer to make sure the referer is blocked
2334 *if www.example.org/www.example.com-shall-see-the-referer/
2335 *links to www.example.com/
2337 referer[hostlenght+17] = '\0';
2339 if ( 0 == strstr(referer, host)) /*Host has changed*/
2341 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2346 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2352 else if (0 != strcmpic(newval, "forge"))
2355 * We have a specific (fixed) referer we want to send.
2357 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2359 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2361 *header = strdup("Referer: ");
2362 string_append(header, newval);
2363 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2365 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2370 * Forge a referer as http://[hostname:port of REQUEST]/
2371 * to fool stupid checks for in-site links
2374 *header = strdup("Referer: http://");
2375 string_append(header, csp->http->hostport);
2376 string_append(header, "/");
2377 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2379 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2383 /*********************************************************************
2385 * Function : client_accept_language
2387 * Description : Handle the "Accept-Language" config setting properly.
2388 * Called from `sed'.
2391 * 1 : csp = Current client state (buffers, headers, etc...)
2392 * 2 : header = On input, pointer to header to modify.
2393 * On output, pointer to the modified header, or NULL
2394 * to remove the header. This function frees the
2395 * original string if necessary.
2397 * Returns : JB_ERR_OK on success, or
2398 * JB_ERR_MEMORY on out-of-memory error.
2400 *********************************************************************/
2401 jb_err client_accept_language(struct client_state *csp, char **header)
2406 * Are we messing with the Accept-Language?
2408 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2410 /*I don't think so*/
2414 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2416 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2419 * Blocking Accept-Language header
2421 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2428 * Replacing Accept-Language header
2431 *header = strdup("Accept-Language: ");
2432 string_append(header, newval);
2434 if (*header == NULL)
2436 log_error(LOG_LEVEL_ERROR,
2437 "Insufficent memory. Accept-Language header crunched without replacement.");
2441 log_error(LOG_LEVEL_HEADER,
2442 "Accept-Language header crunched and replaced with: %s", *header);
2445 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2448 /*********************************************************************
2450 * Function : crunch_client_header
2452 * Description : Crunch client header if it matches a string supplied by the
2453 * user. Called from `sed'.
2456 * 1 : csp = Current client state (buffers, headers, etc...)
2457 * 2 : header = On input, pointer to header to modify.
2458 * On output, pointer to the modified header, or NULL
2459 * to remove the header. This function frees the
2460 * original string if necessary.
2462 * Returns : JB_ERR_OK on success and always succeeds
2464 *********************************************************************/
2465 jb_err crunch_client_header(struct client_state *csp, char **header)
2467 const char *crunch_pattern;
2468 /*Is there a header to crunch*/
2470 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2472 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2474 /*Is the current header the lucky one?*/
2475 if (strstr(*header, crunch_pattern))
2477 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2485 /*********************************************************************
2487 * Function : client_uagent
2489 * Description : Handle the "user-agent" config setting properly
2490 * and remember its original value to enable browser
2491 * bug workarounds. Called from `sed'.
2494 * 1 : csp = Current client state (buffers, headers, etc...)
2495 * 2 : header = On input, pointer to header to modify.
2496 * On output, pointer to the modified header, or NULL
2497 * to remove the header. This function frees the
2498 * original string if necessary.
2500 * Returns : JB_ERR_OK on success, or
2501 * JB_ERR_MEMORY on out-of-memory error.
2503 *********************************************************************/
2504 jb_err client_uagent(struct client_state *csp, char **header)
2508 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2513 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2520 *header = strdup("User-Agent: ");
2521 string_append(header, newval);
2523 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2525 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2528 /*********************************************************************
2530 * Function : client_ua
2532 * Description : Handle "ua-" headers properly. Called from `sed'.
2535 * 1 : csp = Current client state (buffers, headers, etc...)
2536 * 2 : header = On input, pointer to header to modify.
2537 * On output, pointer to the modified header, or NULL
2538 * to remove the header. This function frees the
2539 * original string if necessary.
2541 * Returns : JB_ERR_OK on success, or
2542 * JB_ERR_MEMORY on out-of-memory error.
2544 *********************************************************************/
2545 jb_err client_ua(struct client_state *csp, char **header)
2547 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2549 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2557 /*********************************************************************
2559 * Function : client_from
2561 * Description : Handle the "from" config setting properly.
2562 * Called from `sed'.
2565 * 1 : csp = Current client state (buffers, headers, etc...)
2566 * 2 : header = On input, pointer to header to modify.
2567 * On output, pointer to the modified header, or NULL
2568 * to remove the header. This function frees the
2569 * original string if necessary.
2571 * Returns : JB_ERR_OK on success, or
2572 * JB_ERR_MEMORY on out-of-memory error.
2574 *********************************************************************/
2575 jb_err client_from(struct client_state *csp, char **header)
2579 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2586 newval = csp->action->string[ACTION_STRING_FROM];
2589 * Are we blocking the e-mail address?
2591 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2593 log_error(LOG_LEVEL_HEADER, "crunched From!");
2597 log_error(LOG_LEVEL_HEADER, " modified");
2599 *header = strdup("From: ");
2600 string_append(header, newval);
2602 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2606 /*********************************************************************
2608 * Function : client_send_cookie
2610 * Description : Handle the "cookie" header properly. Called from `sed'.
2611 * If cookie is accepted, add it to the cookie_list,
2612 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2615 * 1 : csp = Current client state (buffers, headers, etc...)
2616 * 2 : header = On input, pointer to header to modify.
2617 * On output, pointer to the modified header, or NULL
2618 * to remove the header. This function frees the
2619 * original string if necessary.
2621 * Returns : JB_ERR_OK on success, or
2622 * JB_ERR_MEMORY on out-of-memory error.
2624 *********************************************************************/
2625 jb_err client_send_cookie(struct client_state *csp, char **header)
2627 jb_err result = JB_ERR_OK;
2629 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2631 /* strlen("cookie: ") == 8 */
2632 result = enlist(csp->cookie_list, *header + 8);
2636 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2640 * Always remove the cookie here. The cookie header
2641 * will be sent at the end of the header.
2649 /*********************************************************************
2651 * Function : client_x_forwarded
2653 * Description : Handle the "x-forwarded-for" config setting properly,
2654 * also used in the add_client_headers list. Called from `sed'.
2657 * 1 : csp = Current client state (buffers, headers, etc...)
2658 * 2 : header = On input, pointer to header to modify.
2659 * On output, pointer to the modified header, or NULL
2660 * to remove the header. This function frees the
2661 * original string if necessary.
2663 * Returns : JB_ERR_OK on success, or
2664 * JB_ERR_MEMORY on out-of-memory error.
2666 *********************************************************************/
2667 jb_err client_x_forwarded(struct client_state *csp, char **header)
2669 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2671 /* Save it so we can re-add it later */
2672 freez(csp->x_forwarded);
2673 csp->x_forwarded = *header;
2676 * Always set *header = NULL, since this information
2677 * will be sent at the end of the header.
2684 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2691 /*********************************************************************
2693 * Function : client_max_forwards
2695 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2696 * from the value of the Max-Forwards header field.
2699 * 1 : csp = Current client state (buffers, headers, etc...)
2700 * 2 : header = On input, pointer to header to modify.
2701 * On output, pointer to the modified header, or NULL
2702 * to remove the header. This function frees the
2703 * original string if necessary.
2705 * Returns : JB_ERR_OK on success, or
2706 * JB_ERR_MEMORY on out-of-memory error.
2708 *********************************************************************/
2709 jb_err client_max_forwards(struct client_state *csp, char **header)
2713 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2714 (0 == strcmpic(csp->http->gpc, "options")))
2716 assert(*(*header+12) == ':');
2717 if (1 == sscanf(*header+12, ": %u", &max_forwards))
2719 if (max_forwards > 0)
2721 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
2722 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
2723 csp->http->gpc, max_forwards);
2725 else if (max_forwards < 0)
2727 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2733 * Not supposed to be reached. direct_response() which
2734 * was already called earlier in chat() should have
2735 * intercepted the request.
2737 log_error(LOG_LEVEL_ERROR,
2738 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2739 assert(max_forwards != 0);
2744 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2753 /*********************************************************************
2755 * Function : client_host
2757 * Description : If the request URI did not contain host and
2758 * port information, parse and evaluate the Host
2761 * Also, kill ill-formed HOST: headers as sent by
2762 * Apple's iTunes software when used with a proxy.
2765 * 1 : csp = Current client state (buffers, headers, etc...)
2766 * 2 : header = On input, pointer to header to modify.
2767 * On output, pointer to the modified header, or NULL
2768 * to remove the header. This function frees the
2769 * original string if necessary.
2771 * Returns : JB_ERR_OK on success, or
2772 * JB_ERR_MEMORY on out-of-memory error.
2774 *********************************************************************/
2775 jb_err client_host(struct client_state *csp, char **header)
2780 * If the header field name is all upper-case, chances are that it's
2781 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2782 * not a problem -- they are regenerated later.
2784 if ((*header)[1] == 'O')
2786 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2791 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2792 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2795 if (NULL == (p = strdup((*header)+6)))
2797 return JB_ERR_MEMORY;
2800 if (NULL == (q = strdup(p)))
2803 return JB_ERR_MEMORY;
2806 freez(csp->http->hostport);
2807 csp->http->hostport = p;
2808 freez(csp->http->host);
2809 csp->http->host = q;
2810 q = strchr(csp->http->host, ':');
2813 /* Terminate hostname and evaluate port string */
2815 csp->http->port = atoi(q);
2819 csp->http->port = csp->http->ssl ? 443 : 80;
2822 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2823 csp->http->hostport, csp->http->host, csp->http->port);
2829 /*********************************************************************
2831 * Function : client_if_modified_since
2833 * Description : Remove or modify the If-Modified-Since header.
2836 * 1 : csp = Current client state (buffers, headers, etc...)
2837 * 2 : header = On input, pointer to header to modify.
2838 * On output, pointer to the modified header, or NULL
2839 * to remove the header. This function frees the
2840 * original string if necessary.
2842 * Returns : JB_ERR_OK on success, or
2843 * JB_ERR_MEMORY on out-of-memory error.
2845 *********************************************************************/
2846 jb_err client_if_modified_since(struct client_state *csp, char **header)
2849 #ifdef HAVE_GMTIME_R
2852 struct tm *timeptr = NULL;
2856 long int hours, minutes, seconds;
2860 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2863 * The client got an error message because of a temporary problem,
2864 * the problem is gone and the client now tries to revalidate our
2865 * error message on the real server. The revalidation would always
2866 * end with the transmission of the whole document and there is
2867 * no need to expose the bogus If-Modified-Since header.
2869 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2872 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2874 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2876 if ((0 == strcmpic(newval, "block")))
2878 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2881 else /* add random value */
2883 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2885 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2890 rtime = strtol(newval, &endptr, 0);
2893 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2894 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2901 rtime = pick_from_range(rtime);
2905 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2908 tm += rtime * (negative ? -1 : 1);
2909 #ifdef HAVE_GMTIME_R
2910 timeptr = gmtime_r(&tm, &gmt);
2911 #elif FEATURE_PTHREAD
2912 pthread_mutex_lock(&gmtime_mutex);
2913 timeptr = gmtime(&tm);
2914 pthread_mutex_unlock(&gmtime_mutex);
2916 timeptr = gmtime(&tm);
2918 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2921 *header = strdup("If-Modified-Since: ");
2922 string_append(header, newheader);
2924 if (*header == NULL)
2926 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2927 return JB_ERR_MEMORY;
2930 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2932 hours = rtime / 3600;
2933 minutes = rtime / 60 % 60;
2934 seconds = rtime % 60;
2936 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2937 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2938 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2947 /*********************************************************************
2949 * Function : client_if_none_match
2951 * Description : Remove the If-None-Match header.
2954 * 1 : csp = Current client state (buffers, headers, etc...)
2955 * 2 : header = On input, pointer to header to modify.
2956 * On output, pointer to the modified header, or NULL
2957 * to remove the header. This function frees the
2958 * original string if necessary.
2960 * Returns : JB_ERR_OK on success, or
2961 * JB_ERR_MEMORY on out-of-memory error.
2963 *********************************************************************/
2964 jb_err client_if_none_match(struct client_state *csp, char **header)
2966 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2968 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2975 /*********************************************************************
2977 * Function : client_x_filter
2979 * Description : Disables filtering if the client set "X-Filter: No".
2980 * Called from `sed'.
2983 * 1 : csp = Current client state (buffers, headers, etc...)
2984 * 2 : header = On input, pointer to header to modify.
2985 * On output, pointer to the modified header, or NULL
2986 * to remove the header. This function frees the
2987 * original string if necessary.
2989 * Returns : JB_ERR_OK on success
2991 *********************************************************************/
2992 jb_err client_x_filter(struct client_state *csp, char **header)
2994 if ( 0 == strcmpic(*header, "X-Filter: No"))
2996 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2998 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3002 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3004 log_error(LOG_LEVEL_HEADER,
3005 "force-text-mode overruled the client's request to fetch without filtering!");
3009 csp->content_type = CT_TABOO;
3010 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
3011 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
3012 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3014 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3021 /* the following functions add headers directly to the header list */
3023 /*********************************************************************
3025 * Function : client_host_adder
3027 * Description : Adds the Host: header field if it is missing.
3028 * Called from `sed'.
3031 * 1 : csp = Current client state (buffers, headers, etc...)
3033 * Returns : JB_ERR_OK on success, or
3034 * JB_ERR_MEMORY on out-of-memory error.
3036 *********************************************************************/
3037 jb_err client_host_adder(struct client_state *csp)
3042 if ( !csp->http->hostport || !*(csp->http->hostport))
3048 * remove 'user:pass@' from 'proto://user:pass@host'
3050 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3056 p = csp->http->hostport;
3059 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3060 err = enlist_unique_header(csp->headers, "Host", p);
3066 /*********************************************************************
3068 * Function : client_cookie_adder
3070 * Description : Used in the add_client_headers list. Called from `sed'.
3073 * 1 : csp = Current client state (buffers, headers, etc...)
3075 * Returns : JB_ERR_OK on success, or
3076 * JB_ERR_MEMORY on out-of-memory error.
3078 *********************************************************************/
3079 jb_err client_cookie_adder(struct client_state *csp)
3081 struct list_entry *lst;
3083 struct list_entry *list1 = csp->cookie_list->first;
3084 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
3085 int first_cookie = 1;
3088 if ((list1 == NULL) && (list2 == NULL))
3094 tmp = strdup("Cookie: ");
3096 for (lst = list1; lst ; lst = lst->next)
3104 string_append(&tmp, "; ");
3106 string_append(&tmp, lst->str);
3109 for (lst = list2; lst ; lst = lst->next)
3117 string_append(&tmp, "; ");
3119 string_join(&tmp, cookie_encode(lst->str));
3124 return JB_ERR_MEMORY;
3127 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3128 err = enlist(csp->headers, tmp);
3134 /*********************************************************************
3136 * Function : client_accept_encoding_adder
3138 * Description : Add an Accept-Encoding header to the client's request
3139 * that disables compression if the action applies, and
3140 * the header is not already there. Called from `sed'.
3141 * Note: For HTTP/1.0, the absence of the header is enough.
3144 * 1 : csp = Current client state (buffers, headers, etc...)
3146 * Returns : JB_ERR_OK on success, or
3147 * JB_ERR_MEMORY on out-of-memory error.
3149 *********************************************************************/
3150 jb_err client_accept_encoding_adder(struct client_state *csp)
3152 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3153 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3155 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3162 /*********************************************************************
3164 * Function : client_xtra_adder
3166 * Description : Used in the add_client_headers list. Called from `sed'.
3169 * 1 : csp = Current client state (buffers, headers, etc...)
3171 * Returns : JB_ERR_OK on success, or
3172 * JB_ERR_MEMORY on out-of-memory error.
3174 *********************************************************************/
3175 jb_err client_xtra_adder(struct client_state *csp)
3177 struct list_entry *lst;
3180 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3181 lst ; lst = lst->next)
3183 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3184 err = enlist(csp->headers, lst->str);
3196 /*********************************************************************
3198 * Function : client_x_forwarded_adder
3200 * Description : Used in the add_client_headers list. Called from `sed'.
3203 * 1 : csp = Current client state (buffers, headers, etc...)
3205 * Returns : JB_ERR_OK on success, or
3206 * JB_ERR_MEMORY on out-of-memory error.
3208 *********************************************************************/
3209 jb_err client_x_forwarded_adder(struct client_state *csp)
3214 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3219 if (csp->x_forwarded)
3221 p = strdup(csp->x_forwarded);
3222 string_append(&p, ", ");
3226 p = strdup("X-Forwarded-For: ");
3228 string_append(&p, csp->ip_addr_str);
3232 return JB_ERR_MEMORY;
3235 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3236 err = enlist(csp->headers, p);
3243 /*********************************************************************
3245 * Function : connection_close_adder
3247 * Description : Adds a "Connection: close" header to csp->headers
3248 * as a temporary fix for the needed but missing HTTP/1.1
3249 * support. Called from `sed'.
3250 * FIXME: This whole function shouldn't be neccessary!
3253 * 1 : csp = Current client state (buffers, headers, etc...)
3255 * Returns : JB_ERR_OK on success, or
3256 * JB_ERR_MEMORY on out-of-memory error.
3258 *********************************************************************/
3259 jb_err connection_close_adder(struct client_state *csp)
3261 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3262 return enlist(csp->headers, "Connection: close");
3266 /*********************************************************************
3268 * Function : server_http
3270 * Description : - Save the HTTP Status into csp->http->status
3271 * - Set CT_TABOO to prevent filtering if the answer
3272 * is a partial range (HTTP status 206)
3273 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3277 * 1 : csp = Current client state (buffers, headers, etc...)
3278 * 2 : header = On input, pointer to header to modify.
3279 * On output, pointer to the modified header, or NULL
3280 * to remove the header. This function frees the
3281 * original string if necessary.
3283 * Returns : JB_ERR_OK on success, or
3284 * JB_ERR_MEMORY on out-of-memory error.
3286 *********************************************************************/
3287 jb_err server_http(struct client_state *csp, char **header)
3289 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3290 if (csp->http->status == 206)
3292 csp->content_type = CT_TABOO;
3295 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3298 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3305 /*********************************************************************
3307 * Function : server_set_cookie
3309 * Description : Handle the server "cookie" header properly.
3310 * Log cookie to the jar file. Then "crunch",
3311 * accept or rewrite it to a session cookie.
3312 * Called from `sed'.
3314 * TODO: Allow the user to specify a new expiration
3315 * time to cause the cookie to expire even before the
3316 * browser is closed.
3319 * 1 : csp = Current client state (buffers, headers, etc...)
3320 * 2 : header = On input, pointer to header to modify.
3321 * On output, pointer to the modified header, or NULL
3322 * to remove the header. This function frees the
3323 * original string if necessary.
3325 * Returns : JB_ERR_OK on success, or
3326 * JB_ERR_MEMORY on out-of-memory error.
3328 *********************************************************************/
3329 jb_err server_set_cookie(struct client_state *csp, char **header)
3334 struct tm tm_cookie;
3337 #ifdef FEATURE_COOKIE_JAR
3338 if (csp->config->jar)
3341 * Write timestamp into outbuf.
3343 * Complex because not all OSs have tm_gmtoff or
3344 * the %z field in strftime()
3346 char tempbuf[ BUFFER_SIZE ];
3348 #ifdef HAVE_LOCALTIME_R
3349 tm_now = *localtime_r(&now, &tm_now);
3350 #elif FEATURE_PTHREAD
3351 pthread_mutex_lock(&localtime_mutex);
3352 tm_now = *localtime (&now);
3353 pthread_mutex_unlock(&localtime_mutex);
3355 tm_now = *localtime (&now);
3357 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3359 /* strlen("set-cookie: ") = 12 */
3360 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3362 #endif /* def FEATURE_COOKIE_JAR */
3364 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3366 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
3367 return crumble(csp, header);
3369 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3371 /* Flag whether or not to log a message */
3374 /* A variable to store the tag we're working on */
3377 /* Skip "Set-Cookie:" (11 characters) in header */
3378 cur_tag = *header + 11;
3380 /* skip whitespace between "Set-Cookie:" and value */
3381 while (*cur_tag && ijb_isspace(*cur_tag))
3386 /* Loop through each tag in the cookie */
3390 char *next_tag = strchr(cur_tag, ';');
3391 if (next_tag != NULL)
3393 /* Skip the ';' character itself */
3396 /* skip whitespace ";" and start of tag */
3397 while (*next_tag && ijb_isspace(*next_tag))
3404 /* "Next tag" is the end of the string */
3405 next_tag = cur_tag + strlen(cur_tag);
3409 * Check the expiration date to see
3410 * if the cookie is still valid, if yes,
3411 * rewrite it to a session cookie.
3413 if (strncmpic(cur_tag, "expires=", 8) == 0)
3417 * Try the valid time formats we know about.
3419 * XXX: Maybe the log messages should be removed
3420 * for the next stable release. They just exist to
3421 * see which time format gets the most hits and
3422 * should be checked for first.
3424 if (NULL != (match = strptime(cur_tag, "expires=%a, %e-%b-%y %H:%M:%S ", &tm_cookie)))
3426 log_error(LOG_LEVEL_HEADER,
3427 "cookie \'%s\' send by %s appears to be using time format 1.",
3428 *header, csp->http->url);
3430 else if (NULL != (match = strptime(cur_tag, "expires=%A, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3432 log_error(LOG_LEVEL_HEADER,
3433 "cookie \'%s\' send by %s appears to be using time format 2.",
3434 *header, csp->http->url);
3437 else if (NULL != (match = strptime(cur_tag, "expires=%a, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3439 log_error(LOG_LEVEL_HEADER,
3440 "cookie \'%s\' send by %s appears to be using time format 3.",
3441 *header, csp->http->url);
3444 /* Did any of them match? */
3448 * Nope, treat it as if it was still valid.
3450 * XXX: Should we remove the whole cookie instead?
3452 log_error(LOG_LEVEL_ERROR,
3453 "Can't parse %s. Unsupported time format?", cur_tag);
3454 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3460 * Yes. Check if the cookie is still valid.
3462 * If the cookie is already expired it's probably
3463 * a delete cookie and even if it isn't, the browser
3464 * will discard it anyway.
3468 * XXX: timegm() isn't available on some AmigaOS
3469 * versions and our replacement doesn't work.
3471 * Our options are to either:
3473 * - disable session-cookies-only completely if timegm
3476 * - to simply remove all expired tags, like it has
3477 * been done until Privoxy 3.0.6 and to live with
3478 * the consequence that it can cause login/logout
3479 * problems on servers that don't validate their
3480 * input properly, or
3482 * - to replace it with mktime in which
3483 * case there is a slight chance of valid cookies
3484 * passing as already expired.
3486 * This is the way it's currently done and it's not
3487 * as bad as it sounds. If the missing GMT offset is
3488 * enough to change the result of the expiration check
3489 * the cookie will be only valid for a few hours
3490 * anyway, which in many cases will be shorter
3491 * than a browser session.
3493 cookie_time = timegm(&tm_cookie);
3494 if (cookie_time - now < 0)
3496 log_error(LOG_LEVEL_HEADER,
3497 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3498 /* Just in case some clown sets more then one expiration date */
3503 log_error(LOG_LEVEL_HEADER,
3504 "Cookie \'%s\' is still valid and has to be rewritten.", *header);
3507 * Delete the tag by copying the rest of the string over it.
3508 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3509 * since the behaviour of strcpy is undefined for overlapping
3512 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3514 /* That changed the header, need to issue a log message */
3518 * Note that the next tag has now been moved to *cur_tag,
3519 * so we do not need to update the cur_tag pointer.
3527 /* Move on to next cookie tag */
3534 assert(NULL != *header);
3535 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3544 #ifdef FEATURE_FORCE_LOAD
3545 /*********************************************************************
3547 * Function : strclean
3549 * Description : In-Situ-Eliminate all occurances of substring in
3553 * 1 : string = string to clean
3554 * 2 : substring = substring to eliminate
3556 * Returns : Number of eliminations
3558 *********************************************************************/
3559 int strclean(const char *string, const char *substring)
3565 len = strlen(substring);
3567 while((pos = strstr(string, substring)) != NULL)
3574 while (*p++ != '\0');
3581 #endif /* def FEATURE_FORCE_LOAD */
3583 /*********************************************************************
3585 * Function : parse_header_time
3587 * Description : Transforms time inside a HTTP header into
3588 * the usual time format.
3591 * 1 : header = header to parse
3592 * 2 : tm = storage for the resulting time in seconds
3594 * Returns : Time struct containing the header time, or
3595 * NULL in case of a parsing problems.
3597 *********************************************************************/
3598 struct tm *parse_header_time(char *header, time_t *tm) {
3602 struct tm * timeptr;
3605 * Initializing gmt to prevent time zone offsets.
3607 * While this is only necessary on some platforms
3608 * (mingw32 for example), I don't know how to
3609 * detect these automatically and doing it everywhere
3613 #ifdef HAVE_LOCALTIME_R
3614 gmt = *localtime_r(tm, &gmt);
3615 #elif FEATURE_PTHREAD
3616 pthread_mutex_lock(&localtime_mutex);
3617 gmt = *localtime(tm);
3618 pthread_mutex_unlock(&localtime_mutex);
3620 gmt = *localtime(tm);
3623 /* Skipping header name */
3624 timestring = strstr(header, ": ");
3625 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)
3638 /*********************************************************************
3640 * Function : get_destination_from_headers
3642 * Description : Parse the "Host:" header to get the request's destination.
3643 * Only needed if the client's request was forcefully
3644 * redirected into Privoxy.
3646 * Code mainly copied from client_host() which is currently
3647 * run too late for this purpose.
3650 * 1 : headers = List of headers (one of them hopefully being
3651 * the "Host:" header)
3652 * 2 : http = storage for the result (host, port and hostport).
3654 * Returns : JB_ERR_MEMORY in case of memory problems,
3655 * JB_ERR_PARSE if the host header couldn't be found,
3656 * JB_ERR_OK otherwise.
3658 *********************************************************************/
3659 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3665 host = get_header_value(headers, "Host:");
3669 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3670 return JB_ERR_PARSE;
3673 if (NULL == (p = strdup((host))))
3675 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3676 return JB_ERR_MEMORY;
3679 if (NULL == (q = strdup(p)))
3682 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3683 return JB_ERR_MEMORY;
3686 freez(http->hostport);
3690 q = strchr(http->host, ':');
3693 /* Terminate hostname and evaluate port string */
3695 http->port = atoi(q);
3699 http->port = http->ssl ? 443 : 80;
3702 /* Rebuild request URL */
3704 http->url = strdup(http->ssl ? "https://" : "http://");
3705 string_append(&http->url, http->hostport);
3706 string_append(&http->url, http->path);
3707 if (http->url == NULL)
3709 return JB_ERR_MEMORY;
3712 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",