1 const char parsers_rcs[] = "$Id: parsers.c,v 1.87 2007/01/31 16:21:38 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.87 2007/01/31 16:21:38 fabiankeil
49 * Search for Max-Forwards headers case-insensitive,
50 * don't generate the "501 unsupported" message for invalid
51 * Max-Forwards values and don't increase negative ones.
53 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
54 * - Let server_set_cookie() check the expiration date
55 * of cookies and don't touch the ones that are already
56 * expired. Fixes problems with low quality web applications
57 * as described in BR 932612.
59 * - Adjust comment in client_max_forwards to reality;
60 * remove invalid Max-Forwards headers.
62 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
63 * Stop filter_header() from unintentionally removing
64 * empty header lines that were enlisted by the continue
67 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
68 * - Repeat the request URL before logging any headers.
69 * Makes reading the log easier in case of simultaneous requests.
70 * - If there are more than one Content-Type headers in one request,
71 * use the first one and remove the others.
72 * - Remove "newval" variable in server_content_type().
73 * It's only used once.
75 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
76 * Correct a cast, check inflateEnd() exit code
77 * to see if we have to, replace sprintf calls
80 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
81 * Integrate a modified version of Wil Mahan's
82 * zlib patch (PR #895531).
84 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
85 * Skip empty filter files in filter_header()
86 * but don't ignore the ones that come afterwards.
87 * Fixes BR 1619208, this time for real.
89 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
90 * Reverted parts of my last commit
91 * to keep error handling working.
93 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
94 * Fixed gcc43 conversion warnings.
96 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
97 * Bringing back the "useless" localtime() call
98 * I removed in revision 1.67. On some platforms
99 * it's necessary to prevent time zone offsets.
101 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
102 * Rebuild request URL in get_destination_from_headers()
103 * to make sure redirect{pcrs command} works as expected
104 * for intercepted requests.
106 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
107 * Added get_destination_from_headers().
109 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
110 * Make pthread mutex locking more generic. Instead of
111 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
112 * and use mutex locking unless there is an _r function
113 * available. Better safe than sorry.
115 * Fixes "./configure --disable-pthread" and should result
116 * in less threading-related problems on pthread-using platforms,
117 * but it still doesn't fix BR#1122404.
119 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
120 * The special header "X-Filter: No" now disables
121 * header filtering as well.
123 * Revision 1.73 2006/09/23 13:26:38 roro
124 * Replace TABs by spaces in source code.
126 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
127 * Don't print a log message every time filter_headers is
128 * entered or left. It only creates noise without any real
131 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
132 * Fix +hide-if-modified-since{-n}.
134 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
135 * Have hide-if-modified-since interpret the random
136 * range value as minutes instead of hours. Allows
137 * more fine-grained configuration.
139 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
140 * Always have parse_header_time return a pointer
141 * that actual makes sense, even though we currently
142 * only need it to detect problems.
144 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
145 * Added config option enable-remote-http-toggle
146 * to specify if Privoxy should recognize special
147 * headers (currently only X-Filter) to change its
148 * behaviour. Disabled by default.
150 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
151 * After filtering de-chunked instances, remove
152 * "Transfer-Encoding" header entirely instead of changing
153 * it to "Transfer-Encoding: identity", which is invalid.
154 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
156 * Don't use localtime in parse_header_time. An empty time struct
157 * is good enough, it gets overwritten by strptime anyway.
159 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
160 * Use gmtime_r if available, fallback to gmtime with mutex
161 * protection for MacOSX and use vanilla gmtime for the rest.
163 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
164 * Changed client_referrer to use the right type (size_t) for
165 * hostlenght and to shorten the temporary referrer string with
166 * '\0' instead of adding a useless line break.
168 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
169 * - Back to timegm() using GnuPG's replacement if necessary.
170 * Using mktime() and localtime() could add a on hour offset if
171 * the randomize factor was big enough to lead to a summer/wintertime
174 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
176 * - Moved randomization code into pick_from_range().
178 * - Changed parse_header_time definition.
179 * time_t isn't guaranteed to be signed and
180 * if it isn't, -1 isn't available as error code.
181 * Changed some variable types in client_if_modified_since()
182 * because of the same reason.
184 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
185 * OS/2 compilation compatibility fixups
187 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
188 * Changed include from strptime.c to strptime.h
190 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
191 * Split filter-headers{} into filter-client-headers{}
192 * and filter-server-headers{}.
193 * Added parse_header_time() to share some code.
194 * Replaced timegm() with mktime().
196 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
197 * Windows service integration
199 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
200 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
202 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
203 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
204 * with what was really the latest development (the v_3_0_branch branch)
206 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
207 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
209 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
210 * Add the ability to check jpeg images for invalid
211 * lengths of comment blocks. Defensive strategy
212 * against the exploit:
213 * Microsoft Security Bulletin MS04-028
214 * Buffer Overrun in JPEG Processing (GDI+) Could
215 * Allow Code Execution (833987)
216 * Enabled with +inspect-jpegs in actions files.
218 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
219 * Excluded text/plain objects from filtering. This fixes a
220 * couple of client-crashing, download corruption and
221 * Privoxy performance issues, whose root cause lies in
222 * web servers labelling content of unknown type as text/plain.
224 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
225 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
227 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
228 * Completing the previous change
230 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
231 * Added temporary workaround for bug in PHP < 4.2.3
233 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
234 * 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.
236 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
237 * Fix typo: supressed -> suppressed
239 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
240 * Improved cookie logging
242 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
243 * Added basic support for OPTIONS and TRACE HTTP methods:
244 * - New parser function client_max_forwards which decrements
245 * the Max-Forwards HTTP header field of OPTIONS and TRACE
246 * requests by one before forwarding
247 * - New parser function client_host which extracts the host
248 * and port information from the HTTP header field if the
249 * request URI was not absolute
250 * - Don't crumble and re-add the Host: header, but only generate
251 * and append if missing
253 * Revision 1.56 2002/05/12 15:34:22 jongfoster
254 * Fixing typo in a comment
256 * Revision 1.55 2002/05/08 16:01:07 oes
257 * Optimized add_to_iob:
258 * - Use realloc instead of malloc(), memcpy(), free()
259 * - Expand to powers of two if possible, to get
260 * O(log n) reallocs instead of O(n).
261 * - Moved check for buffer limit here from chat
262 * - Report failure via returncode
264 * Revision 1.54 2002/04/02 15:03:16 oes
265 * Tiny code cosmetics
267 * Revision 1.53 2002/03/26 22:29:55 swa
268 * we have a new homepage!
270 * Revision 1.52 2002/03/24 13:25:43 swa
271 * name change related issues
273 * Revision 1.51 2002/03/13 00:27:05 jongfoster
276 * Revision 1.50 2002/03/12 01:45:35 oes
277 * More verbose logging
279 * Revision 1.49 2002/03/09 20:03:52 jongfoster
280 * - Making various functions return int rather than size_t.
281 * (Undoing a recent change). Since size_t is unsigned on
282 * Windows, functions like read_socket that return -1 on
283 * error cannot return a size_t.
285 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
286 * crashes, and also frequently caused JB to jump to 100%
287 * CPU and stay there. (Because it thought it had just
288 * read ((unsigned)-1) == 4Gb of data...)
290 * - The signature of write_socket has changed, it now simply
291 * returns success=0/failure=nonzero.
293 * - Trying to get rid of a few warnings --with-debug on
294 * Windows, I've introduced a new type "jb_socket". This is
295 * used for the socket file descriptors. On Windows, this
296 * is SOCKET (a typedef for unsigned). Everywhere else, it's
297 * an int. The error value can't be -1 any more, so it's
298 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
299 * Windows it maps to the #define INVALID_SOCKET.)
301 * - The signature of bind_port has changed.
303 * Revision 1.48 2002/03/07 03:46:53 oes
304 * Fixed compiler warnings etc
306 * Revision 1.47 2002/02/20 23:15:13 jongfoster
307 * Parsing functions now handle out-of-memory gracefully by returning
310 * Revision 1.46 2002/01/17 21:03:47 jongfoster
311 * Moving all our URL and URL pattern parsing code to urlmatch.c.
313 * Revision 1.45 2002/01/09 14:33:03 oes
314 * Added support for localtime_r.
316 * Revision 1.44 2001/12/14 01:22:54 steudten
317 * Remove 'user:pass@' from 'proto://user:pass@host' for the
318 * new added header 'Host: ..'. (See Req ID 491818)
320 * Revision 1.43 2001/11/23 00:26:38 jongfoster
321 * Fixing two really stupid errors in my previous commit
323 * Revision 1.42 2001/11/22 21:59:30 jongfoster
324 * Adding code to handle +no-cookies-keep
326 * Revision 1.41 2001/11/05 23:43:05 steudten
327 * Add time+date to log files.
329 * Revision 1.40 2001/10/26 20:13:09 jongfoster
330 * ctype.h is needed in Windows, too.
332 * Revision 1.39 2001/10/26 17:40:04 oes
333 * Introduced get_header_value()
334 * Removed http->user_agent, csp->referrer and csp->accept_types
335 * Removed client_accept()
337 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
338 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
339 * threads to call select() simultaneously. So, it's time to do a real, live,
340 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
341 * (native). Both versions will work, but using __OS2__ offers multi-threading.
343 * Revision 1.37 2001/10/23 21:36:02 jongfoster
344 * Documenting sed()'s error behaviou (doc change only)
346 * Revision 1.36 2001/10/13 12:51:51 joergs
347 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
348 * force-load), instead crumble Host: and add it (again) in client_host_adder
349 * (in case we get a HTTP/1.0 request without Host: header and forward it to
350 * a HTTP/1.1 server/proxy).
352 * Revision 1.35 2001/10/09 22:39:21 jongfoster
353 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
356 * Revision 1.34 2001/10/07 18:50:55 oes
357 * Added server_content_encoding, renamed server_transfer_encoding
359 * Revision 1.33 2001/10/07 18:04:49 oes
360 * Changed server_http11 to server_http and its pattern to "HTTP".
361 * Additional functionality: it now saves the HTTP status into
362 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
364 * Revision 1.32 2001/10/07 15:43:28 oes
365 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
366 * client_te and client_accept_encoding_adder, triggered by the new
367 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
368 * changed to allow only identity and chunked, and the TE header is
369 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
371 * parse_http_request no longer does anything than parsing. The rewriting
372 * of http->cmd and version mangling are gone. It now also recognizes
373 * the put and delete methods and saves the url in http->url. Removed
376 * renamed content_type and content_length to have the server_ prefix
378 * server_content_type now only works if csp->content_type != CT_TABOO
380 * added server_transfer_encoding, which
381 * - Sets CT_TABOO to prohibit filtering if encoding compresses
382 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
383 * - Change from "chunked" to "identity" if body was chunked
384 * but has been de-chunked for filtering.
386 * added server_content_md5 which crunches any Content-MD5 headers
387 * if the body was modified.
389 * made server_http11 conditional on +downgrade action
391 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
393 * Revision 1.31 2001/10/05 14:25:02 oes
394 * Crumble Keep-Alive from Server
396 * Revision 1.30 2001/09/29 12:56:03 joergs
397 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
399 * Revision 1.29 2001/09/24 21:09:24 jongfoster
400 * Fixing 2 memory leaks that Guy spotted, where the paramater to
401 * enlist() was not being free()d.
403 * Revision 1.28 2001/09/22 16:32:28 jongfoster
404 * Removing unused #includes.
406 * Revision 1.27 2001/09/20 15:45:25 steudten
408 * add casting from size_t to int for printf()
409 * remove local variable shadow s2
411 * Revision 1.26 2001/09/16 17:05:14 jongfoster
412 * Removing unused #include showarg.h
414 * Revision 1.25 2001/09/16 13:21:27 jongfoster
415 * Changes to use new list functions.
417 * Revision 1.24 2001/09/13 23:05:50 jongfoster
418 * Changing the string paramater to the header parsers a "const".
420 * Revision 1.23 2001/09/12 18:08:19 steudten
422 * In parse_http_request() header rewriting miss the host value, so
423 * from http://www.mydomain.com the result was just " / " not
424 * http://www.mydomain.com/ in case we forward.
426 * Revision 1.22 2001/09/10 10:58:53 oes
427 * Silenced compiler warnings
429 * Revision 1.21 2001/07/31 14:46:00 oes
430 * - Persistant connections now suppressed
431 * - sed() no longer appends empty header to csp->headers
433 * Revision 1.20 2001/07/30 22:08:36 jongfoster
434 * Tidying up #defines:
435 * - All feature #defines are now of the form FEATURE_xxx
436 * - Permanently turned off WIN_GUI_EDIT
437 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
439 * Revision 1.19 2001/07/25 17:21:54 oes
440 * client_uagent now saves copy of User-Agent: header value
442 * Revision 1.18 2001/07/13 14:02:46 oes
443 * - Included fix to repair broken HTTP requests that
444 * don't contain a path, not even '/'.
445 * - Removed all #ifdef PCRS
446 * - content_type now always inspected and classified as
447 * text, gif or other.
448 * - formatting / comments
450 * Revision 1.17 2001/06/29 21:45:41 oes
451 * Indentation, CRLF->LF, Tab-> Space
453 * Revision 1.16 2001/06/29 13:32:42 oes
455 * - Adapted free_http_request
456 * - Removed logentry from cancelled commit
458 * Revision 1.15 2001/06/03 19:12:38 oes
459 * deleted const struct interceptors
461 * Revision 1.14 2001/06/01 18:49:17 jongfoster
462 * Replaced "list_share" with "list" - the tiny memory gain was not
463 * worth the extra complexity.
465 * Revision 1.13 2001/05/31 21:30:33 jongfoster
466 * Removed list code - it's now in list.[ch]
467 * Renamed "permission" to "action", and changed many features
468 * to use the actions file rather than the global config.
470 * Revision 1.12 2001/05/31 17:33:13 oes
474 * Revision 1.11 2001/05/29 20:11:19 joergs
475 * '/ * inside comment' warning removed.
477 * Revision 1.10 2001/05/29 09:50:24 jongfoster
478 * Unified blocklist/imagelist/permissionslist.
479 * File format is still under discussion, but the internal changes
482 * Also modified interceptor behaviour:
483 * - We now intercept all URLs beginning with one of the following
484 * prefixes (and *only* these prefixes):
486 * * http://ijbswa.sf.net/config/
487 * * http://ijbswa.sourceforge.net/config/
488 * - New interceptors "home page" - go to http://i.j.b/ to see it.
489 * - Internal changes so that intercepted and fast redirect pages
490 * are not replaced with an image.
491 * - Interceptors now have the option to send a binary page direct
492 * to the client. (i.e. ijb-send-banner uses this)
493 * - Implemented show-url-info interceptor. (Which is why I needed
494 * the above interceptors changes - a typical URL is
495 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
496 * The previous mechanism would not have intercepted that, and
497 * if it had been intercepted then it then it would have replaced
500 * Revision 1.9 2001/05/28 17:26:33 jongfoster
501 * Fixing segfault if last header was crunched.
502 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
503 * can use the cross-platform sprintf() instead.)
505 * Revision 1.8 2001/05/27 22:17:04 oes
507 * - re_process_buffer no longer writes the modified buffer
508 * to the client, which was very ugly. It now returns the
509 * buffer, which it is then written by chat.
511 * - content_length now adjusts the Content-Length: header
512 * for modified documents rather than crunch()ing it.
513 * (Length info in csp->content_length, which is 0 for
514 * unmodified documents)
516 * - For this to work, sed() is called twice when filtering.
518 * Revision 1.7 2001/05/27 13:19:06 oes
519 * Patched Joergs solution for the content-length in.
521 * Revision 1.6 2001/05/26 13:39:32 jongfoster
522 * Only crunches Content-Length header if applying RE filtering.
523 * Without this fix, Microsoft Windows Update wouldn't work.
525 * Revision 1.5 2001/05/26 00:28:36 jongfoster
526 * Automatic reloading of config file.
527 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
528 * Most of the global variables have been moved to a new
529 * struct configuration_spec, accessed through csp->config->globalname
530 * Most of the globals remaining are used by the Win32 GUI.
532 * Revision 1.4 2001/05/22 18:46:04 oes
534 * - Enabled filtering banners by size rather than URL
535 * by adding patterns that replace all standard banner
536 * sizes with the "Junkbuster" gif to the re_filterfile
538 * - Enabled filtering WebBugs by providing a pattern
539 * which kills all 1x1 images
541 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
542 * which is selected by the (nonstandard and therefore
543 * capital) letter 'U' in the option string.
544 * It causes the quantifiers to be ungreedy by default.
545 * Appending a ? turns back to greedy (!).
547 * - Added a new interceptor ijb-send-banner, which
548 * sends back the "Junkbuster" gif. Without imagelist or
549 * MSIE detection support, or if tinygif = 1, or the
550 * URL isn't recognized as an imageurl, a lame HTML
551 * explanation is sent instead.
553 * - Added new feature, which permits blocking remote
554 * script redirects and firing back a local redirect
556 * The feature is conditionally compiled, i.e. it
557 * can be disabled with --disable-fast-redirects,
558 * plus it must be activated by a "fast-redirects"
559 * line in the config file, has its own log level
560 * and of course wants to be displayed by show-proxy-args
561 * Note: Boy, all the #ifdefs in 1001 locations and
562 * all the fumbling with configure.in and acconfig.h
563 * were *way* more work than the feature itself :-(
565 * - Because a generic redirect template was needed for
566 * this, tinygif = 3 now uses the same.
568 * - Moved GIFs, and other static HTTP response templates
573 * - Removed some >400 CRs again (Jon, you really worked
576 * Revision 1.3 2001/05/20 01:21:20 jongfoster
577 * Version 2.9.4 checkin.
578 * - Merged popupfile and cookiefile, and added control over PCRS
579 * filtering, in new "permissionsfile".
580 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
581 * file error you now get a message box (in the Win32 GUI) rather
582 * than the program exiting with no explanation.
583 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
585 * - Removed tabs from "config"
586 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
587 * - Bumped up version number.
589 * Revision 1.2 2001/05/17 23:02:36 oes
590 * - Made referrer option accept 'L' as a substitute for '§'
592 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
593 * Initial import of version 2.9.3 source tree
596 *********************************************************************/
603 #include <sys/types.h>
616 #if !defined(_WIN32) && !defined(__OS2__)
622 #ifdef FEATURE_PTHREAD
624 /* jcc.h is for mutex semapores only */
625 #endif /* def FEATURE_PTHREAD */
631 #include "jbsockets.h"
632 #include "miscutil.h"
635 #ifndef HAVE_STRPTIME
636 #include "strptime.h"
639 const char parsers_h_rcs[] = PARSERS_H_VERSION;
641 /* Fix a problem with Solaris. There should be no effect on other
643 * Solaris's isspace() is a macro which uses it's argument directly
644 * as an array index. Therefore we need to make sure that high-bit
645 * characters generate +ve values, and ideally we also want to make
646 * the argument match the declared parameter type of "int".
648 * Why did they write a character function that can't take a simple
649 * "char" argument? Doh!
651 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
652 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
655 const struct parsers client_patterns[] = {
656 { "referer:", 8, client_referrer },
657 { "user-agent:", 11, client_uagent },
658 { "ua-", 3, client_ua },
659 { "from:", 5, client_from },
660 { "cookie:", 7, client_send_cookie },
661 { "x-forwarded-for:", 16, client_x_forwarded },
662 { "Accept-Encoding:", 16, client_accept_encoding },
663 { "TE:", 3, client_te },
664 { "Host:", 5, client_host },
665 { "if-modified-since:", 18, client_if_modified_since },
666 { "Keep-Alive:", 11, crumble },
667 { "connection:", 11, crumble },
668 { "proxy-connection:", 17, crumble },
669 { "max-forwards:", 13, client_max_forwards },
670 { "Accept-Language:", 16, client_accept_language },
671 { "if-none-match:", 14, client_if_none_match },
672 { "X-Filter:", 9, client_x_filter },
673 { "*", 0, crunch_client_header },
674 { "*", 0, filter_client_header },
678 const struct parsers server_patterns[] = {
679 { "HTTP", 4, server_http },
680 { "set-cookie:", 11, server_set_cookie },
681 { "connection:", 11, crumble },
682 { "Content-Type:", 13, server_content_type },
683 { "Content-Length:", 15, server_content_length },
684 { "Content-MD5:", 12, server_content_md5 },
685 { "Content-Encoding:", 17, server_content_encoding },
686 { "Transfer-Encoding:", 18, server_transfer_coding },
687 { "Keep-Alive:", 11, crumble },
688 { "content-disposition:", 20, server_content_disposition },
689 { "Last-Modified:", 14, server_last_modified },
690 { "*", 0, crunch_server_header },
691 { "*", 0, filter_server_header },
695 const struct parsers server_patterns_light[] = {
696 { "Content-Length:", 15, server_content_length },
697 { "Transfer-Encoding:", 18, server_transfer_coding },
699 { "Content-Encoding:", 17, server_content_encoding },
700 #endif /* def FEATURE_ZLIB */
704 const add_header_func_ptr add_client_headers[] = {
707 client_x_forwarded_adder,
709 /* Temporarily disabled: client_accept_encoding_adder, */
710 connection_close_adder,
715 const add_header_func_ptr add_server_headers[] = {
716 connection_close_adder,
720 /*********************************************************************
722 * Function : flush_socket
724 * Description : Write any pending "buffered" content.
727 * 1 : fd = file descriptor of the socket to read
728 * 2 : csp = Current client state (buffers, headers, etc...)
730 * Returns : On success, the number of bytes written are returned (zero
731 * indicates nothing was written). On error, -1 is returned,
732 * and errno is set appropriately. If count is zero and the
733 * file descriptor refers to a regular file, 0 will be
734 * returned without causing any other effect. For a special
735 * file, the results are not portable.
737 *********************************************************************/
738 int flush_socket(jb_socket fd, struct client_state *csp)
740 struct iob *iob = csp->iob;
741 int len = iob->eod - iob->cur;
748 if (write_socket(fd, iob->cur, (size_t)len))
752 iob->eod = iob->cur = iob->buf;
758 /*********************************************************************
760 * Function : add_to_iob
762 * Description : Add content to the buffered page, expanding the
763 * buffer if necessary.
766 * 1 : csp = Current client state (buffers, headers, etc...)
767 * 2 : buf = holds the content to be added to the page
768 * 3 : n = number of bytes to be added
770 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
771 * or buffer limit reached.
773 *********************************************************************/
774 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
776 struct iob *iob = csp->iob;
777 size_t used, offset, need, want;
780 if (n <= 0) return JB_ERR_OK;
782 used = (size_t)(iob->eod - iob->buf);
783 offset = (size_t)(iob->cur - iob->buf);
784 need = used + (size_t)n + 1;
787 * If the buffer can't hold the new data, extend it first.
788 * Use the next power of two if possible, else use the actual need.
790 if (need > csp->config->buffer_limit)
792 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
793 return JB_ERR_MEMORY;
796 if (need > iob->size)
798 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
800 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
804 else if (NULL != (p = (char *)realloc(iob->buf, need)))
810 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
811 return JB_ERR_MEMORY;
814 /* Update the iob pointers */
815 iob->cur = p + offset;
820 /* copy the new data into the iob buffer */
821 memcpy(iob->eod, buf, (size_t)n);
823 /* point to the end of the data */
826 /* null terminate == cheap insurance */
835 /*********************************************************************
837 * Function : decompress_iob
839 * Description : Decompress buffered page, expanding the
840 * buffer as necessary. csp->iob->cur
841 * should point to the the beginning of the
842 * compressed data block.
845 * 1 : csp = Current client state (buffers, headers, etc...)
847 * Returns : JB_ERR_OK on success,
848 * JB_ERR_MEMORY if out-of-memory limit reached, and
849 * JB_ERR_COMPRESS if error decompressing buffer.
851 *********************************************************************/
852 jb_err decompress_iob(struct client_state *csp)
854 char *buf; /* new, uncompressed buffer */
855 char *cur; /* Current iob position (to keep the original
856 * iob->cur unmodified if we return early) */
857 size_t bufsize; /* allocated size of the new buffer */
858 size_t skip_size; /* Number of bytes at the beginning of the iob
859 that we should NOT decompress. */
860 int status; /* return status of the inflate() call */
861 z_stream zstr; /* used by calls to zlib */
863 bufsize = csp->iob->size;
864 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
871 * This is to protect the parsing of gzipped data,
872 * but it should(?) be valid for deflated data also.
874 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
875 return JB_ERR_COMPRESS;
878 if (csp->content_type & CT_GZIP)
881 * Our task is slightly complicated by the facts that data
882 * compressed by gzip does not include a zlib header, and
883 * that there is no easily accessible interface in zlib to
884 * handle a gzip header. We strip off the gzip header by
885 * hand, and later inform zlib not to expect a header.
889 * Strip off the gzip header. Please see RFC 1952 for more
890 * explanation of the appropriate fields.
892 if ((*cur++ != (char)0x1f)
893 || (*cur++ != (char)0x8b)
894 || (*cur++ != Z_DEFLATED))
896 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
897 return JB_ERR_COMPRESS;
903 * XXX: These magic numbers should be replaced
904 * with macros to give a better idea what they do.
908 /* The gzip header has reserved bits set; bail out. */
909 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
910 return JB_ERR_COMPRESS;
914 /* Skip extra fields if necessary. */
918 * Skip a given number of bytes, specified
919 * as a 16-bit little-endian value.
922 * XXX: This code used to be:
924 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
926 * which I had to change into:
928 * cur += *cur++ + (*cur++ << 8);
930 * at which point gcc43 finally noticed that the value
931 * of cur is undefined (it depends on which of the
932 * summands is evaluated first).
934 * I haven't come across a site where this
935 * code is actually executed yet, but I hope
940 skip_bytes = *cur++ << 8;
942 assert(skip_bytes == *csp->iob->cur-2 + ((*csp->iob->cur-1) << 8));
945 * The number of bytes to skip should be positive
946 * and we'd like to stay in the buffer.
948 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
950 log_error (LOG_LEVEL_ERROR,
951 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
953 return JB_ERR_COMPRESS;
955 log_error (LOG_LEVEL_INFO,
956 "Skipping %d bytes for gzip compression. Does this sound right?",
961 /* Skip the filename if necessary. */
964 /* A null-terminated string follows. */
968 /* Skip the comment if necessary. */
974 /* Skip the CRC if necessary. */
981 else if (csp->content_type & CT_DEFLATE)
984 * XXX: The debug level should be lowered
985 * before the next stable release.
987 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
989 * In theory (that is, according to RFC 1950), deflate-compressed
990 * data should begin with a two-byte zlib header and have an
991 * adler32 checksum at the end. It seems that in practice only
992 * the raw compressed data is sent. Note that this means that
993 * we are not RFC 1950-compliant here, but the advantage is that
994 * this actually works. :)
996 * We add a dummy null byte to tell zlib where the data ends,
997 * and later inform it not to expect a header.
999 * Fortunately, add_to_iob() has thoughtfully null-terminated
1000 * the buffer; we can just increment the end pointer to include
1007 log_error (LOG_LEVEL_ERROR,
1008 "Unable to determine compression format for decompression");
1009 return JB_ERR_COMPRESS;
1012 /* Set up the fields required by zlib. */
1013 zstr.next_in = (Bytef *)cur;
1014 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1015 zstr.zalloc = Z_NULL;
1016 zstr.zfree = Z_NULL;
1017 zstr.opaque = Z_NULL;
1020 * Passing -MAX_WBITS to inflateInit2 tells the library
1021 * that there is no zlib header.
1023 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1025 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1026 return JB_ERR_COMPRESS;
1030 * Next, we allocate new storage for the inflated data.
1031 * We don't modify the existing iob yet, so in case there
1032 * is error in decompression we can recover gracefully.
1034 buf = zalloc (bufsize);
1037 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1038 return JB_ERR_MEMORY;
1041 assert(bufsize >= skip_size);
1042 memcpy(buf, csp->iob->buf, skip_size);
1043 zstr.avail_out = bufsize - skip_size;
1044 zstr.next_out = (Bytef *)buf + skip_size;
1046 /* Try to decompress the whole stream in one shot. */
1047 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1049 /* We need to allocate more memory for the output buffer. */
1051 char *tmpbuf; /* used for realloc'ing the buffer */
1052 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1055 * If zlib wants more data then there's a problem, because
1056 * the complete compressed file should have been buffered.
1058 if (0 == zstr.avail_in)
1060 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1061 return JB_ERR_COMPRESS;
1065 * If we tried the limit and still didn't have enough
1066 * memory, just give up.
1068 if (bufsize == csp->config->buffer_limit)
1070 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1071 return JB_ERR_MEMORY;
1074 /* Try doubling the buffer size each time. */
1077 /* Don't exceed the buffer limit. */
1078 if (bufsize > csp->config->buffer_limit)
1080 bufsize = csp->config->buffer_limit;
1083 /* Try to allocate the new buffer. */
1084 tmpbuf = realloc(buf, bufsize);
1087 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1089 return JB_ERR_MEMORY;
1093 char *oldnext_out = (char *)zstr.next_out;
1096 * Update the fields for inflate() to use the new
1097 * buffer, which may be in a location different from
1100 zstr.avail_out += bufsize - oldbufsize;
1101 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1104 * Compare with an uglier method of calculating these values
1105 * that doesn't require the extra oldbufsize variable.
1107 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1108 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1109 assert(zstr.avail_out > 0);
1115 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1117 log_error(LOG_LEVEL_ERROR,
1118 "Inconsistent stream state after decompression: %s", zstr.msg);
1120 * XXX: Intentionally no return.
1122 * According to zlib.h, Z_STREAM_ERROR is returned
1123 * "if the stream state was inconsistent".
1125 * I assume in this case inflate()'s status
1126 * would also be something different than Z_STREAM_END
1127 * so this check should be redundant, but lets see.
1131 if (status != Z_STREAM_END)
1133 /* We failed to decompress the stream. */
1134 log_error(LOG_LEVEL_ERROR,
1135 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1136 return JB_ERR_COMPRESS;
1140 * Finally, we can actually update the iob, since the
1141 * decompression was successful. First, free the old
1144 freez(csp->iob->buf);
1146 /* Now, update the iob to use the new buffer. */
1147 csp->iob->buf = buf;
1148 csp->iob->cur = csp->iob->buf + skip_size;
1149 csp->iob->eod = (char *)zstr.next_out;
1150 csp->iob->size = bufsize;
1153 * Make sure the new uncompressed iob obeys some minimal
1154 * consistency conditions.
1156 if ((csp->iob->buf < csp->iob->cur)
1157 && (csp->iob->cur <= csp->iob->eod)
1158 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1160 char t = csp->iob->cur[100];
1161 csp->iob->cur[100] = '\0';
1163 * XXX: The debug level should be lowered
1164 * before the next stable release.
1166 log_error(LOG_LEVEL_INFO, "Sucessfully decompressed: %s", csp->iob->cur);
1167 csp->iob->cur[100] = t;
1172 /* It seems that zlib did something weird. */
1173 log_error(LOG_LEVEL_ERROR,
1174 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1175 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1176 csp->iob->eod, csp->iob->buf + csp->iob->size);
1177 return JB_ERR_COMPRESS;
1181 #endif /* defined(FEATURE_ZLIB) */
1184 /*********************************************************************
1186 * Function : get_header
1188 * Description : This (odd) routine will parse the csp->iob
1191 * 1 : csp = Current client state (buffers, headers, etc...)
1193 * Returns : Any one of the following:
1195 * 1) a pointer to a dynamically allocated string that contains a header line
1196 * 2) NULL indicating that the end of the header was reached
1197 * 3) "" indicating that the end of the iob was reached before finding
1198 * a complete header line.
1200 *********************************************************************/
1201 char *get_header(struct client_state *csp)
1207 if ((iob->cur == NULL)
1208 || ((p = strchr(iob->cur, '\n')) == NULL))
1210 return(""); /* couldn't find a complete header */
1215 ret = strdup(iob->cur);
1218 /* FIXME No way to handle error properly */
1219 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1224 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1226 /* is this a blank line (i.e. the end of the header) ? */
1238 /*********************************************************************
1240 * Function : get_header_value
1242 * Description : Get the value of a given header from a chained list
1243 * of header lines or return NULL if no such header is
1244 * present in the list.
1247 * 1 : header_list = pointer to list
1248 * 2 : header_name = string with name of header to look for.
1249 * Trailing colon required, capitalization
1252 * Returns : NULL if not found, else value of header
1254 *********************************************************************/
1255 char *get_header_value(const struct list *header_list, const char *header_name)
1257 struct list_entry *cur_entry;
1261 assert(header_list);
1262 assert(header_name);
1263 length = strlen(header_name);
1265 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1269 if (!strncmpic(cur_entry->str, header_name, length))
1272 * Found: return pointer to start of value
1274 ret = (char *) (cur_entry->str + length);
1275 while (*ret && ijb_isspace(*ret)) ret++;
1288 /*********************************************************************
1292 * Description : add, delete or modify lines in the HTTP header streams.
1293 * On entry, it receives a linked list of headers space
1294 * that was allocated dynamically (both the list nodes
1295 * and the header contents).
1297 * As a side effect it frees the space used by the original
1301 * 1 : pats = list of patterns to match against headers
1302 * 2 : more_headers = list of functions to add more
1303 * headers (client or server)
1304 * 3 : csp = Current client state (buffers, headers, etc...)
1306 * Returns : Single pointer to a fully formed header, or NULL
1307 * on out-of-memory error.
1309 *********************************************************************/
1310 char *sed(const struct parsers pats[],
1311 const add_header_func_ptr more_headers[],
1312 struct client_state *csp)
1314 struct list_entry *p;
1315 const struct parsers *v;
1316 const add_header_func_ptr *f;
1317 jb_err err = JB_ERR_OK;
1321 * If filtering is enabled, sed is run twice,
1322 * but most of the work needs to be done only once.
1324 first_run = (more_headers != NULL ) ? 1 : 0;
1326 if (first_run) /* Parse and print */
1328 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1329 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1331 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1333 /* Header crunch()ed in previous run? -> ignore */
1334 if (p->str == NULL) continue;
1336 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
1338 /* Does the current parser handle this header? */
1339 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1341 err = v->parser(csp, (char **)&(p->str));
1345 /* place any additional headers on the csp->headers list */
1346 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1351 else /* Parse only */
1354 * The second run is only needed if the body was modified
1355 * and the content-lenght has changed.
1357 if (strncmpic(csp->http->cmd, "HEAD", 4))
1359 /*XXX: Code duplication */
1360 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1362 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1364 /* Header crunch()ed in previous run? -> ignore */
1365 if (p->str == NULL) continue;
1367 /* Does the current parser handle this header? */
1368 if (strncmpic(p->str, v->str, v->len) == 0)
1370 err = v->parser(csp, (char **)&(p->str));
1377 if (err != JB_ERR_OK)
1382 return list_to_text(csp->headers);
1386 /* here begins the family of parser functions that reformat header lines */
1388 /*********************************************************************
1390 * Function : filter_server_header
1392 * Description : Checks if server header filtering is enabled.
1393 * If it is, filter_header is called to do the work.
1396 * 1 : csp = Current client state (buffers, headers, etc...)
1397 * 2 : header = On input, pointer to header to modify.
1398 * On output, pointer to the modified header, or NULL
1399 * to remove the header. This function frees the
1400 * original string if necessary.
1402 * Returns : JB_ERR_OK on success and always succeeds
1404 *********************************************************************/
1405 jb_err filter_server_header(struct client_state *csp, char **header)
1407 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
1409 filter_header(csp, header);
1414 /*********************************************************************
1416 * Function : filter_client_header
1418 * Description : Checks if client header filtering is enabled.
1419 * If it is, filter_header is called to do the work.
1422 * 1 : csp = Current client state (buffers, headers, etc...)
1423 * 2 : header = On input, pointer to header to modify.
1424 * On output, pointer to the modified header, or NULL
1425 * to remove the header. This function frees the
1426 * original string if necessary.
1428 * Returns : JB_ERR_OK on success and always succeeds
1430 *********************************************************************/
1431 jb_err filter_client_header(struct client_state *csp, char **header)
1433 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
1435 filter_header(csp, header);
1440 /*********************************************************************
1442 * Function : filter_header
1444 * Description : Executes all text substitutions from all applying
1445 * +filter actions on the header.
1446 * Most of the code was copied from pcrs_filter_response,
1447 * including the rather short variable names
1450 * 1 : csp = Current client state (buffers, headers, etc...)
1451 * 2 : header = On input, pointer to header to modify.
1452 * On output, pointer to the modified header, or NULL
1453 * to remove the header. This function frees the
1454 * original string if necessary.
1456 * Returns : JB_ERR_OK on success and always succeeds
1458 *********************************************************************/
1459 jb_err filter_header(struct client_state *csp, char **header)
1463 size_t size = strlen(*header);
1465 char *newheader = NULL;
1468 struct file_list *fl;
1469 struct re_filterfile_spec *b;
1470 struct list_entry *filtername;
1472 int i, found_filters = 0;
1475 * Need to check the set of re_filterfiles...
1477 for (i = 0; i < MAX_AF_FILES; i++)
1490 if (0 == found_filters)
1492 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1496 for (i = 0; i < MAX_AF_FILES; i++)
1499 if ((NULL == fl) || (NULL == fl->f))
1502 * Either there are no filter files
1503 * left, or this filter file just
1504 * contains no valid filters.
1506 * Continue to be sure we don't miss
1507 * valid filter files that are chained
1508 * after empty or invalid ones.
1513 * For all applying +filter actions, look if a filter by that
1514 * name exists and if yes, execute its pcrs_joblist on the
1517 for (b = fl->f; b; b = b->next)
1519 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1520 filtername ; filtername = filtername->next)
1522 if (strcmp(b->name, filtername->str) == 0)
1524 int current_hits = 0;
1526 if ( NULL == b->joblist )
1528 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1532 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1533 *header, size, b->name);
1535 /* Apply all jobs from the joblist */
1536 for (job = b->joblist; NULL != job; job = job->next)
1538 matches = pcrs_execute(job, *header, size, &newheader, &size);
1541 current_hits += matches;
1542 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1544 *header = newheader;
1546 else if ( 0 == matches )
1548 /* Filter doesn't change header */
1554 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1555 *header, b->name, pcrs_strerror(matches));
1556 if( newheader != NULL)
1558 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1563 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1564 hits += current_hits;
1571 * Additionally checking for hits is important because if
1572 * the continue hack is triggered, server headers can
1573 * arrive empty to separate multiple heads from each other.
1575 if ((0 == size) && hits)
1577 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1585 /*********************************************************************
1587 * Function : crumble
1589 * Description : This is called if a header matches a pattern to "crunch"
1592 * 1 : csp = Current client state (buffers, headers, etc...)
1593 * 2 : header = On input, pointer to header to modify.
1594 * On output, pointer to the modified header, or NULL
1595 * to remove the header. This function frees the
1596 * original string if necessary.
1598 * Returns : JB_ERR_OK on success, or
1599 * JB_ERR_MEMORY on out-of-memory error.
1601 *********************************************************************/
1602 jb_err crumble(struct client_state *csp, char **header)
1604 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1609 /*********************************************************************
1611 * Function : crunch_server_header
1613 * Description : Crunch server header if it matches a string supplied by the
1614 * user. Called from `sed'.
1617 * 1 : csp = Current client state (buffers, headers, etc...)
1618 * 2 : header = On input, pointer to header to modify.
1619 * On output, pointer to the modified header, or NULL
1620 * to remove the header. This function frees the
1621 * original string if necessary.
1623 * Returns : JB_ERR_OK on success and always succeeds
1625 *********************************************************************/
1626 jb_err crunch_server_header(struct client_state *csp, char **header)
1628 const char *crunch_pattern;
1629 /*Is there a header to crunch*/
1631 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1633 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1635 /*Is the current header the lucky one?*/
1636 if (strstr(*header, crunch_pattern))
1638 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1647 /*********************************************************************
1649 * Function : server_content_type
1651 * Description : Set the content-type for filterable types (text/.*,
1652 * .*xml.*, javascript and image/gif) unless filtering has been
1653 * forbidden (CT_TABOO) while parsing earlier headers.
1654 * NOTE: Since text/plain is commonly used by web servers
1655 * for files whose correct type is unknown, we don't
1656 * set CT_TEXT for it.
1659 * 1 : csp = Current client state (buffers, headers, etc...)
1660 * 2 : header = On input, pointer to header to modify.
1661 * On output, pointer to the modified header, or NULL
1662 * to remove the header. This function frees the
1663 * original string if necessary.
1665 * Returns : JB_ERR_OK on success, or
1666 * JB_ERR_MEMORY on out-of-memory error.
1668 *********************************************************************/
1669 jb_err server_content_type(struct client_state *csp, char **header)
1671 /* Remove header if it isn't the first Content-Type header */
1672 if(csp->content_type && (csp->content_type != CT_TABOO))
1675 * Another, slightly slower, way to see if
1676 * we already parsed another Content-Type header.
1678 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1680 log_error(LOG_LEVEL_ERROR,
1681 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1688 if (!(csp->content_type & CT_TABOO))
1690 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1691 || strstr(*header, "xml")
1692 || strstr(*header, "application/x-javascript"))
1694 csp->content_type |= CT_TEXT;
1696 else if (strstr(*header, " image/gif"))
1698 csp->content_type |= CT_GIF;
1700 else if (strstr(*header, " image/jpeg"))
1702 csp->content_type |= CT_JPEG;
1706 csp->content_type = 0;
1710 * Are we enabling text mode by force?
1712 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1715 * Do we really have to?
1717 if (csp->content_type & CT_TEXT)
1719 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1723 csp->content_type |= CT_TEXT;
1724 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1728 * Are we messing with the content type?
1730 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1733 * Make sure the user doesn't accidently
1734 * change the content type of binary documents.
1736 if (csp->content_type & CT_TEXT)
1739 *header = strdup("Content-Type: ");
1740 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1744 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1745 return JB_ERR_MEMORY;
1747 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1751 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1752 "Enable force-text-mode if you know what you're doing.", *header);
1759 /*********************************************************************
1761 * Function : server_transfer_coding
1763 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1764 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1765 * - Remove header if body was chunked but has been
1766 * de-chunked for filtering.
1769 * 1 : csp = Current client state (buffers, headers, etc...)
1770 * 2 : header = On input, pointer to header to modify.
1771 * On output, pointer to the modified header, or NULL
1772 * to remove the header. This function frees the
1773 * original string if necessary.
1775 * Returns : JB_ERR_OK on success, or
1776 * JB_ERR_MEMORY on out-of-memory error.
1778 *********************************************************************/
1779 jb_err server_transfer_coding(struct client_state *csp, char **header)
1782 * Turn off pcrs and gif filtering if body compressed
1784 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1788 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1790 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1791 csp->http->cmd, *header);
1792 #endif /* def FEATURE_ZLIB */
1793 csp->content_type = CT_TABOO;
1797 * Raise flag if body chunked
1799 if (strstr(*header, "chunked"))
1801 csp->flags |= CSP_FLAG_CHUNKED;
1804 * If the body was modified, it has been de-chunked first
1805 * and the header must be removed.
1807 * FIXME: If there is more than one transfer encoding,
1808 * only the "chunked" part should be removed here.
1810 if (csp->flags & CSP_FLAG_MODIFIED)
1812 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1821 /*********************************************************************
1823 * Function : server_content_encoding
1825 * Description : This function is run twice for each request,
1826 * unless FEATURE_ZLIB and filtering are disabled.
1828 * The first run is used to check if the content
1829 * is compressed, if FEATURE_ZLIB is disabled
1830 * filtering is then disabled as well, if FEATURE_ZLIB
1831 * is enabled the content is marked for decompression.
1833 * The second run is used to remove the Content-Encoding
1834 * header if the decompression was successful.
1837 * 1 : csp = Current client state (buffers, headers, etc...)
1838 * 2 : header = On input, pointer to header to modify.
1839 * On output, pointer to the modified header, or NULL
1840 * to remove the header. This function frees the
1841 * original string if necessary.
1843 * Returns : JB_ERR_OK on success, or
1844 * JB_ERR_MEMORY on out-of-memory error.
1846 *********************************************************************/
1847 jb_err server_content_encoding(struct client_state *csp, char **header)
1850 if ((csp->flags & CSP_FLAG_MODIFIED)
1851 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1854 * We successfully decompressed the content,
1855 * and have to clean the header now, so the
1856 * client no longer expects compressed data..
1858 * XXX: There is a difference between cleaning
1859 * and removing it completely.
1861 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1864 else if (strstr(*header, "gzip"))
1866 /* Mark for gzip decompression */
1867 csp->content_type |= CT_GZIP;
1869 else if (strstr(*header, "deflate"))
1871 /* Mark for zlib decompression */
1872 csp->content_type |= CT_DEFLATE;
1874 else if (strstr(*header, "compress"))
1877 * We can't decompress this; therefore we can't filter
1880 csp->content_type |= CT_TABOO;
1882 #else /* !defined(FEATURE_ZLIB) */
1883 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1886 * Body is compressed, turn off pcrs and gif filtering.
1888 csp->content_type |= CT_TABOO;
1890 #endif /* !defined(FEATURE_ZLIB) */
1897 /*********************************************************************
1899 * Function : server_content_length
1901 * Description : Adjust Content-Length header if we modified
1905 * 1 : csp = Current client state (buffers, headers, etc...)
1906 * 2 : header = On input, pointer to header to modify.
1907 * On output, pointer to the modified header, or NULL
1908 * to remove the header. This function frees the
1909 * original string if necessary.
1911 * Returns : JB_ERR_OK on success, or
1912 * JB_ERR_MEMORY on out-of-memory error.
1914 *********************************************************************/
1915 jb_err server_content_length(struct client_state *csp, char **header)
1917 const size_t max_header_length = 80;
1918 if (csp->content_length != 0) /* Content length could have been modified */
1921 * XXX: Shouldn't we check if csp->content_length
1922 * is different than the original value?
1925 *header = (char *) zalloc(max_header_length);
1926 if (*header == NULL)
1928 return JB_ERR_MEMORY;
1931 snprintf(*header, max_header_length, "Content-Length: %d",
1932 (int)csp->content_length);
1933 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
1934 (int)csp->content_length);
1941 /*********************************************************************
1943 * Function : server_content_md5
1945 * Description : Crumble any Content-MD5 headers if the document was
1946 * modified. FIXME: Should we re-compute instead?
1949 * 1 : csp = Current client state (buffers, headers, etc...)
1950 * 2 : header = On input, pointer to header to modify.
1951 * On output, pointer to the modified header, or NULL
1952 * to remove the header. This function frees the
1953 * original string if necessary.
1955 * Returns : JB_ERR_OK on success, or
1956 * JB_ERR_MEMORY on out-of-memory error.
1958 *********************************************************************/
1959 jb_err server_content_md5(struct client_state *csp, char **header)
1961 if (csp->flags & CSP_FLAG_MODIFIED)
1963 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1970 /*********************************************************************
1972 * Function : server_content_disposition
1974 * Description : If enabled, blocks or modifies the "content-disposition" header.
1975 * Called from `sed'.
1978 * 1 : csp = Current client state (buffers, headers, etc...)
1979 * 2 : header = On input, pointer to header to modify.
1980 * On output, pointer to the modified header, or NULL
1981 * to remove the header. This function frees the
1982 * original string if necessary.
1984 * Returns : JB_ERR_OK on success, or
1985 * JB_ERR_MEMORY on out-of-memory error.
1987 *********************************************************************/
1988 jb_err server_content_disposition(struct client_state *csp, char **header)
1993 * Are we messing with the content-disposition header?
1995 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2001 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2003 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2006 * Blocking content-disposition header
2008 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2015 * Replacing content-disposition header
2018 *header = strdup("content-disposition: ");
2019 string_append(header, newval);
2021 if (*header == NULL)
2023 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2027 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2030 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2033 /*********************************************************************
2035 * Function : server_last_modified
2037 * Description : Changes Last-Modified header to the actual date
2038 * to help hide-if-modified-since.
2039 * Called from `sed'.
2042 * 1 : csp = Current client state (buffers, headers, etc...)
2043 * 2 : header = On input, pointer to header to modify.
2044 * On output, pointer to the modified header, or NULL
2045 * to remove the header. This function frees the
2046 * original string if necessary.
2048 * Returns : JB_ERR_OK on success, or
2049 * JB_ERR_MEMORY on out-of-memory error.
2051 *********************************************************************/
2052 jb_err server_last_modified(struct client_state *csp, char **header)
2055 char buf[BUFFER_SIZE];
2058 #ifdef HAVE_GMTIME_R
2061 struct tm *timeptr = NULL;
2062 time_t now, last_modified;
2064 long int days, hours, minutes, seconds;
2067 * Are we messing with the Last-Modified header?
2069 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2075 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2077 if (0 == strcmpic(newval, "block") )
2080 * Blocking Last-Modified header. Useless but why not.
2082 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2086 else if (0 == strcmpic(newval, "reset-to-request-time"))
2089 * Setting Last-Modified Header to now.
2091 get_http_time(0, buf);
2093 *header = strdup("Last-Modified: ");
2094 string_append(header, buf);
2096 if (*header == NULL)
2098 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2102 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2105 else if (0 == strcmpic(newval, "randomize"))
2107 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2109 #ifdef HAVE_GMTIME_R
2110 timeptr = gmtime_r(&now, &gmt);
2111 #elif FEATURE_PTHREAD
2112 pthread_mutex_lock(&gmtime_mutex);
2113 timeptr = gmtime(&now);
2114 pthread_mutex_unlock(&gmtime_mutex);
2116 timeptr = gmtime(&now);
2118 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
2120 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2125 rtime = (long int)difftime(now, last_modified);
2128 rtime = pick_from_range(rtime);
2129 last_modified += rtime;
2130 #ifdef HAVE_GMTIME_R
2131 timeptr = gmtime_r(&last_modified, &gmt);
2132 #elif FEATURE_PTHREAD
2133 pthread_mutex_lock(&gmtime_mutex);
2134 timeptr = gmtime(&last_modified);
2135 pthread_mutex_unlock(&gmtime_mutex);
2137 timeptr = gmtime(&last_modified);
2139 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2141 *header = strdup("Last-Modified: ");
2142 string_append(header, newheader);
2144 if (*header == NULL)
2146 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2147 return JB_ERR_MEMORY;
2150 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2152 days = rtime / (3600 * 24);
2153 hours = rtime / 3600 % 24;
2154 minutes = rtime / 60 % 60;
2155 seconds = rtime % 60;
2157 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2158 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2159 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2164 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2172 /*********************************************************************
2174 * Function : client_accept_encoding
2176 * Description : Rewrite the client's Accept-Encoding header so that
2177 * if doesn't allow compression, if the action applies.
2178 * Note: For HTTP/1.0 the absence of the header is enough.
2181 * 1 : csp = Current client state (buffers, headers, etc...)
2182 * 2 : header = On input, pointer to header to modify.
2183 * On output, pointer to the modified header, or NULL
2184 * to remove the header. This function frees the
2185 * original string if necessary.
2187 * Returns : JB_ERR_OK on success, or
2188 * JB_ERR_MEMORY on out-of-memory error.
2190 *********************************************************************/
2191 jb_err client_accept_encoding(struct client_state *csp, char **header)
2193 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2195 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2199 /* Temporarily disable the correct behaviour to
2200 * work around a PHP bug.
2202 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2204 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2205 * if (*header == NULL)
2207 * return JB_ERR_MEMORY;
2218 /*********************************************************************
2220 * Function : client_te
2222 * Description : Rewrite the client's TE header so that
2223 * if doesn't allow compression, if the action applies.
2226 * 1 : csp = Current client state (buffers, headers, etc...)
2227 * 2 : header = On input, pointer to header to modify.
2228 * On output, pointer to the modified header, or NULL
2229 * to remove the header. This function frees the
2230 * original string if necessary.
2232 * Returns : JB_ERR_OK on success, or
2233 * JB_ERR_MEMORY on out-of-memory error.
2235 *********************************************************************/
2236 jb_err client_te(struct client_state *csp, char **header)
2238 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2241 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2247 /*********************************************************************
2249 * Function : client_referrer
2251 * Description : Handle the "referer" config setting properly.
2252 * Called from `sed'.
2255 * 1 : csp = Current client state (buffers, headers, etc...)
2256 * 2 : header = On input, pointer to header to modify.
2257 * On output, pointer to the modified header, or NULL
2258 * to remove the header. This function frees the
2259 * original string if necessary.
2261 * Returns : JB_ERR_OK on success, or
2262 * JB_ERR_MEMORY on out-of-memory error.
2264 *********************************************************************/
2265 jb_err client_referrer(struct client_state *csp, char **header)
2272 #ifdef FEATURE_FORCE_LOAD
2273 /* Since the referrer can include the prefix even
2274 * if the request itself is non-forced, we must
2275 * clean it unconditionally
2277 strclean(*header, FORCE_PREFIX);
2278 #endif /* def FEATURE_FORCE_LOAD */
2281 * Are we sending referer?
2283 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2288 newval = csp->action->string[ACTION_STRING_REFERER];
2290 if ((0 != strcmpic(newval, "conditional-block")))
2294 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2299 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2302 else if (0 == strcmpic(newval, "conditional-block"))
2305 * Block referer if host has changed.
2308 if (NULL == (host = strdup(csp->http->hostport)))
2311 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2312 return JB_ERR_MEMORY;
2314 if (NULL == (referer = strdup(*header)))
2318 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2319 return JB_ERR_MEMORY;
2321 hostlenght = strlen(host);
2322 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2324 /*Shorten referer to make sure the referer is blocked
2325 *if www.example.org/www.example.com-shall-see-the-referer/
2326 *links to www.example.com/
2328 referer[hostlenght+17] = '\0';
2330 if ( 0 == strstr(referer, host)) /*Host has changed*/
2332 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2337 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2343 else if (0 != strcmpic(newval, "forge"))
2346 * We have a specific (fixed) referer we want to send.
2348 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2350 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2352 *header = strdup("Referer: ");
2353 string_append(header, newval);
2354 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2356 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2361 * Forge a referer as http://[hostname:port of REQUEST]/
2362 * to fool stupid checks for in-site links
2365 *header = strdup("Referer: http://");
2366 string_append(header, csp->http->hostport);
2367 string_append(header, "/");
2368 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2370 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2374 /*********************************************************************
2376 * Function : client_accept_language
2378 * Description : Handle the "Accept-Language" config setting properly.
2379 * Called from `sed'.
2382 * 1 : csp = Current client state (buffers, headers, etc...)
2383 * 2 : header = On input, pointer to header to modify.
2384 * On output, pointer to the modified header, or NULL
2385 * to remove the header. This function frees the
2386 * original string if necessary.
2388 * Returns : JB_ERR_OK on success, or
2389 * JB_ERR_MEMORY on out-of-memory error.
2391 *********************************************************************/
2392 jb_err client_accept_language(struct client_state *csp, char **header)
2397 * Are we messing with the Accept-Language?
2399 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2401 /*I don't think so*/
2405 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2407 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2410 * Blocking Accept-Language header
2412 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2419 * Replacing Accept-Language header
2422 *header = strdup("Accept-Language: ");
2423 string_append(header, newval);
2425 if (*header == NULL)
2427 log_error(LOG_LEVEL_ERROR,
2428 "Insufficent memory. Accept-Language header crunched without replacement.");
2432 log_error(LOG_LEVEL_HEADER,
2433 "Accept-Language header crunched and replaced with: %s", *header);
2436 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2439 /*********************************************************************
2441 * Function : crunch_client_header
2443 * Description : Crunch client header if it matches a string supplied by the
2444 * user. Called from `sed'.
2447 * 1 : csp = Current client state (buffers, headers, etc...)
2448 * 2 : header = On input, pointer to header to modify.
2449 * On output, pointer to the modified header, or NULL
2450 * to remove the header. This function frees the
2451 * original string if necessary.
2453 * Returns : JB_ERR_OK on success and always succeeds
2455 *********************************************************************/
2456 jb_err crunch_client_header(struct client_state *csp, char **header)
2458 const char *crunch_pattern;
2459 /*Is there a header to crunch*/
2461 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2463 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2465 /*Is the current header the lucky one?*/
2466 if (strstr(*header, crunch_pattern))
2468 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2476 /*********************************************************************
2478 * Function : client_uagent
2480 * Description : Handle the "user-agent" config setting properly
2481 * and remember its original value to enable browser
2482 * bug workarounds. Called from `sed'.
2485 * 1 : csp = Current client state (buffers, headers, etc...)
2486 * 2 : header = On input, pointer to header to modify.
2487 * On output, pointer to the modified header, or NULL
2488 * to remove the header. This function frees the
2489 * original string if necessary.
2491 * Returns : JB_ERR_OK on success, or
2492 * JB_ERR_MEMORY on out-of-memory error.
2494 *********************************************************************/
2495 jb_err client_uagent(struct client_state *csp, char **header)
2499 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2504 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2511 *header = strdup("User-Agent: ");
2512 string_append(header, newval);
2514 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2516 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2519 /*********************************************************************
2521 * Function : client_ua
2523 * Description : Handle "ua-" headers properly. Called from `sed'.
2526 * 1 : csp = Current client state (buffers, headers, etc...)
2527 * 2 : header = On input, pointer to header to modify.
2528 * On output, pointer to the modified header, or NULL
2529 * to remove the header. This function frees the
2530 * original string if necessary.
2532 * Returns : JB_ERR_OK on success, or
2533 * JB_ERR_MEMORY on out-of-memory error.
2535 *********************************************************************/
2536 jb_err client_ua(struct client_state *csp, char **header)
2538 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2540 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2548 /*********************************************************************
2550 * Function : client_from
2552 * Description : Handle the "from" config setting properly.
2553 * Called from `sed'.
2556 * 1 : csp = Current client state (buffers, headers, etc...)
2557 * 2 : header = On input, pointer to header to modify.
2558 * On output, pointer to the modified header, or NULL
2559 * to remove the header. This function frees the
2560 * original string if necessary.
2562 * Returns : JB_ERR_OK on success, or
2563 * JB_ERR_MEMORY on out-of-memory error.
2565 *********************************************************************/
2566 jb_err client_from(struct client_state *csp, char **header)
2570 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2577 newval = csp->action->string[ACTION_STRING_FROM];
2580 * Are we blocking the e-mail address?
2582 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2584 log_error(LOG_LEVEL_HEADER, "crunched From!");
2588 log_error(LOG_LEVEL_HEADER, " modified");
2590 *header = strdup("From: ");
2591 string_append(header, newval);
2593 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2597 /*********************************************************************
2599 * Function : client_send_cookie
2601 * Description : Handle the "cookie" header properly. Called from `sed'.
2602 * If cookie is accepted, add it to the cookie_list,
2603 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2606 * 1 : csp = Current client state (buffers, headers, etc...)
2607 * 2 : header = On input, pointer to header to modify.
2608 * On output, pointer to the modified header, or NULL
2609 * to remove the header. This function frees the
2610 * original string if necessary.
2612 * Returns : JB_ERR_OK on success, or
2613 * JB_ERR_MEMORY on out-of-memory error.
2615 *********************************************************************/
2616 jb_err client_send_cookie(struct client_state *csp, char **header)
2618 jb_err result = JB_ERR_OK;
2620 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2622 /* strlen("cookie: ") == 8 */
2623 result = enlist(csp->cookie_list, *header + 8);
2627 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2631 * Always remove the cookie here. The cookie header
2632 * will be sent at the end of the header.
2640 /*********************************************************************
2642 * Function : client_x_forwarded
2644 * Description : Handle the "x-forwarded-for" config setting properly,
2645 * also used in the add_client_headers list. Called from `sed'.
2648 * 1 : csp = Current client state (buffers, headers, etc...)
2649 * 2 : header = On input, pointer to header to modify.
2650 * On output, pointer to the modified header, or NULL
2651 * to remove the header. This function frees the
2652 * original string if necessary.
2654 * Returns : JB_ERR_OK on success, or
2655 * JB_ERR_MEMORY on out-of-memory error.
2657 *********************************************************************/
2658 jb_err client_x_forwarded(struct client_state *csp, char **header)
2660 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2662 /* Save it so we can re-add it later */
2663 freez(csp->x_forwarded);
2664 csp->x_forwarded = *header;
2667 * Always set *header = NULL, since this information
2668 * will be sent at the end of the header.
2675 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2682 /*********************************************************************
2684 * Function : client_max_forwards
2686 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2687 * from the value of the Max-Forwards header field.
2690 * 1 : csp = Current client state (buffers, headers, etc...)
2691 * 2 : header = On input, pointer to header to modify.
2692 * On output, pointer to the modified header, or NULL
2693 * to remove the header. This function frees the
2694 * original string if necessary.
2696 * Returns : JB_ERR_OK on success, or
2697 * JB_ERR_MEMORY on out-of-memory error.
2699 *********************************************************************/
2700 jb_err client_max_forwards(struct client_state *csp, char **header)
2704 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2705 (0 == strcmpic(csp->http->gpc, "options")))
2707 assert(*(*header+12) == ':');
2708 if (1 == sscanf(*header+12, ": %u", &max_forwards))
2710 if (max_forwards > 0)
2712 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
2713 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
2714 csp->http->gpc, max_forwards);
2716 else if (max_forwards < 0)
2718 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2724 * Not supposed to be reached. direct_response() which
2725 * was already called earlier in chat() should have
2726 * intercepted the request.
2728 log_error(LOG_LEVEL_ERROR,
2729 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2730 assert(max_forwards != 0);
2735 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2744 /*********************************************************************
2746 * Function : client_host
2748 * Description : If the request URI did not contain host and
2749 * port information, parse and evaluate the Host
2752 * Also, kill ill-formed HOST: headers as sent by
2753 * Apple's iTunes software when used with a proxy.
2756 * 1 : csp = Current client state (buffers, headers, etc...)
2757 * 2 : header = On input, pointer to header to modify.
2758 * On output, pointer to the modified header, or NULL
2759 * to remove the header. This function frees the
2760 * original string if necessary.
2762 * Returns : JB_ERR_OK on success, or
2763 * JB_ERR_MEMORY on out-of-memory error.
2765 *********************************************************************/
2766 jb_err client_host(struct client_state *csp, char **header)
2771 * If the header field name is all upper-case, chances are that it's
2772 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2773 * not a problem -- they are regenerated later.
2775 if ((*header)[1] == 'O')
2777 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2782 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2783 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2786 if (NULL == (p = strdup((*header)+6)))
2788 return JB_ERR_MEMORY;
2791 if (NULL == (q = strdup(p)))
2794 return JB_ERR_MEMORY;
2797 freez(csp->http->hostport);
2798 csp->http->hostport = p;
2799 freez(csp->http->host);
2800 csp->http->host = q;
2801 q = strchr(csp->http->host, ':');
2804 /* Terminate hostname and evaluate port string */
2806 csp->http->port = atoi(q);
2810 csp->http->port = csp->http->ssl ? 443 : 80;
2813 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2814 csp->http->hostport, csp->http->host, csp->http->port);
2820 /*********************************************************************
2822 * Function : client_if_modified_since
2824 * Description : Remove or modify the If-Modified-Since header.
2827 * 1 : csp = Current client state (buffers, headers, etc...)
2828 * 2 : header = On input, pointer to header to modify.
2829 * On output, pointer to the modified header, or NULL
2830 * to remove the header. This function frees the
2831 * original string if necessary.
2833 * Returns : JB_ERR_OK on success, or
2834 * JB_ERR_MEMORY on out-of-memory error.
2836 *********************************************************************/
2837 jb_err client_if_modified_since(struct client_state *csp, char **header)
2840 #ifdef HAVE_GMTIME_R
2843 struct tm *timeptr = NULL;
2847 long int hours, minutes, seconds;
2851 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2854 * The client got an error message because of a temporary problem,
2855 * the problem is gone and the client now tries to revalidate our
2856 * error message on the real server. The revalidation would always
2857 * end with the transmission of the whole document and there is
2858 * no need to expose the bogus If-Modified-Since header.
2860 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2863 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2865 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2867 if ((0 == strcmpic(newval, "block")))
2869 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2872 else /* add random value */
2874 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2876 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2881 rtime = strtol(newval, &endptr, 0);
2884 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2885 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2892 rtime = pick_from_range(rtime);
2896 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2899 tm += rtime * (negative ? -1 : 1);
2900 #ifdef HAVE_GMTIME_R
2901 timeptr = gmtime_r(&tm, &gmt);
2902 #elif FEATURE_PTHREAD
2903 pthread_mutex_lock(&gmtime_mutex);
2904 timeptr = gmtime(&tm);
2905 pthread_mutex_unlock(&gmtime_mutex);
2907 timeptr = gmtime(&tm);
2909 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2912 *header = strdup("If-Modified-Since: ");
2913 string_append(header, newheader);
2915 if (*header == NULL)
2917 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2918 return JB_ERR_MEMORY;
2921 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2923 hours = rtime / 3600;
2924 minutes = rtime / 60 % 60;
2925 seconds = rtime % 60;
2927 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2928 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2929 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2938 /*********************************************************************
2940 * Function : client_if_none_match
2942 * Description : Remove the If-None-Match header.
2945 * 1 : csp = Current client state (buffers, headers, etc...)
2946 * 2 : header = On input, pointer to header to modify.
2947 * On output, pointer to the modified header, or NULL
2948 * to remove the header. This function frees the
2949 * original string if necessary.
2951 * Returns : JB_ERR_OK on success, or
2952 * JB_ERR_MEMORY on out-of-memory error.
2954 *********************************************************************/
2955 jb_err client_if_none_match(struct client_state *csp, char **header)
2957 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2959 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2966 /*********************************************************************
2968 * Function : client_x_filter
2970 * Description : Disables filtering if the client set "X-Filter: No".
2971 * Called from `sed'.
2974 * 1 : csp = Current client state (buffers, headers, etc...)
2975 * 2 : header = On input, pointer to header to modify.
2976 * On output, pointer to the modified header, or NULL
2977 * to remove the header. This function frees the
2978 * original string if necessary.
2980 * Returns : JB_ERR_OK on success
2982 *********************************************************************/
2983 jb_err client_x_filter(struct client_state *csp, char **header)
2985 if ( 0 == strcmpic(*header, "X-Filter: No"))
2987 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2989 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2993 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2995 log_error(LOG_LEVEL_HEADER,
2996 "force-text-mode overruled the client's request to fetch without filtering!");
3000 csp->content_type = CT_TABOO;
3001 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
3002 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
3003 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3005 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3012 /* the following functions add headers directly to the header list */
3014 /*********************************************************************
3016 * Function : client_host_adder
3018 * Description : Adds the Host: header field if it is missing.
3019 * Called from `sed'.
3022 * 1 : csp = Current client state (buffers, headers, etc...)
3024 * Returns : JB_ERR_OK on success, or
3025 * JB_ERR_MEMORY on out-of-memory error.
3027 *********************************************************************/
3028 jb_err client_host_adder(struct client_state *csp)
3033 if ( !csp->http->hostport || !*(csp->http->hostport))
3039 * remove 'user:pass@' from 'proto://user:pass@host'
3041 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3047 p = csp->http->hostport;
3050 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3051 err = enlist_unique_header(csp->headers, "Host", p);
3057 /*********************************************************************
3059 * Function : client_cookie_adder
3061 * Description : Used in the add_client_headers list. Called from `sed'.
3064 * 1 : csp = Current client state (buffers, headers, etc...)
3066 * Returns : JB_ERR_OK on success, or
3067 * JB_ERR_MEMORY on out-of-memory error.
3069 *********************************************************************/
3070 jb_err client_cookie_adder(struct client_state *csp)
3072 struct list_entry *lst;
3074 struct list_entry *list1 = csp->cookie_list->first;
3075 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
3076 int first_cookie = 1;
3079 if ((list1 == NULL) && (list2 == NULL))
3085 tmp = strdup("Cookie: ");
3087 for (lst = list1; lst ; lst = lst->next)
3095 string_append(&tmp, "; ");
3097 string_append(&tmp, lst->str);
3100 for (lst = list2; lst ; lst = lst->next)
3108 string_append(&tmp, "; ");
3110 string_join(&tmp, cookie_encode(lst->str));
3115 return JB_ERR_MEMORY;
3118 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3119 err = enlist(csp->headers, tmp);
3125 /*********************************************************************
3127 * Function : client_accept_encoding_adder
3129 * Description : Add an Accept-Encoding header to the client's request
3130 * that disables compression if the action applies, and
3131 * the header is not already there. Called from `sed'.
3132 * Note: For HTTP/1.0, the absence of the header is enough.
3135 * 1 : csp = Current client state (buffers, headers, etc...)
3137 * Returns : JB_ERR_OK on success, or
3138 * JB_ERR_MEMORY on out-of-memory error.
3140 *********************************************************************/
3141 jb_err client_accept_encoding_adder(struct client_state *csp)
3143 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3144 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3146 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3153 /*********************************************************************
3155 * Function : client_xtra_adder
3157 * Description : Used in the add_client_headers list. Called from `sed'.
3160 * 1 : csp = Current client state (buffers, headers, etc...)
3162 * Returns : JB_ERR_OK on success, or
3163 * JB_ERR_MEMORY on out-of-memory error.
3165 *********************************************************************/
3166 jb_err client_xtra_adder(struct client_state *csp)
3168 struct list_entry *lst;
3171 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3172 lst ; lst = lst->next)
3174 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3175 err = enlist(csp->headers, lst->str);
3187 /*********************************************************************
3189 * Function : client_x_forwarded_adder
3191 * Description : Used in the add_client_headers list. Called from `sed'.
3194 * 1 : csp = Current client state (buffers, headers, etc...)
3196 * Returns : JB_ERR_OK on success, or
3197 * JB_ERR_MEMORY on out-of-memory error.
3199 *********************************************************************/
3200 jb_err client_x_forwarded_adder(struct client_state *csp)
3205 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3210 if (csp->x_forwarded)
3212 p = strdup(csp->x_forwarded);
3213 string_append(&p, ", ");
3217 p = strdup("X-Forwarded-For: ");
3219 string_append(&p, csp->ip_addr_str);
3223 return JB_ERR_MEMORY;
3226 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3227 err = enlist(csp->headers, p);
3234 /*********************************************************************
3236 * Function : connection_close_adder
3238 * Description : Adds a "Connection: close" header to csp->headers
3239 * as a temporary fix for the needed but missing HTTP/1.1
3240 * support. Called from `sed'.
3241 * FIXME: This whole function shouldn't be neccessary!
3244 * 1 : csp = Current client state (buffers, headers, etc...)
3246 * Returns : JB_ERR_OK on success, or
3247 * JB_ERR_MEMORY on out-of-memory error.
3249 *********************************************************************/
3250 jb_err connection_close_adder(struct client_state *csp)
3252 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3253 return enlist(csp->headers, "Connection: close");
3257 /*********************************************************************
3259 * Function : server_http
3261 * Description : - Save the HTTP Status into csp->http->status
3262 * - Set CT_TABOO to prevent filtering if the answer
3263 * is a partial range (HTTP status 206)
3264 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3268 * 1 : csp = Current client state (buffers, headers, etc...)
3269 * 2 : header = On input, pointer to header to modify.
3270 * On output, pointer to the modified header, or NULL
3271 * to remove the header. This function frees the
3272 * original string if necessary.
3274 * Returns : JB_ERR_OK on success, or
3275 * JB_ERR_MEMORY on out-of-memory error.
3277 *********************************************************************/
3278 jb_err server_http(struct client_state *csp, char **header)
3280 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3281 if (csp->http->status == 206)
3283 csp->content_type = CT_TABOO;
3286 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3289 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3296 /*********************************************************************
3298 * Function : server_set_cookie
3300 * Description : Handle the server "cookie" header properly.
3301 * Log cookie to the jar file. Then "crunch",
3302 * accept or rewrite it to a session cookie.
3303 * Called from `sed'.
3305 * TODO: Allow the user to specify a new expiration
3306 * time to cause the cookie to expire even before the
3307 * browser is closed.
3310 * 1 : csp = Current client state (buffers, headers, etc...)
3311 * 2 : header = On input, pointer to header to modify.
3312 * On output, pointer to the modified header, or NULL
3313 * to remove the header. This function frees the
3314 * original string if necessary.
3316 * Returns : JB_ERR_OK on success, or
3317 * JB_ERR_MEMORY on out-of-memory error.
3319 *********************************************************************/
3320 jb_err server_set_cookie(struct client_state *csp, char **header)
3325 struct tm tm_cookie;
3328 #ifdef FEATURE_COOKIE_JAR
3329 if (csp->config->jar)
3332 * Write timestamp into outbuf.
3334 * Complex because not all OSs have tm_gmtoff or
3335 * the %z field in strftime()
3337 char tempbuf[ BUFFER_SIZE ];
3339 #ifdef HAVE_LOCALTIME_R
3340 tm_now = *localtime_r(&now, &tm_now);
3341 #elif FEATURE_PTHREAD
3342 pthread_mutex_lock(&localtime_mutex);
3343 tm_now = *localtime (&now);
3344 pthread_mutex_unlock(&localtime_mutex);
3346 tm_now = *localtime (&now);
3348 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3350 /* strlen("set-cookie: ") = 12 */
3351 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3353 #endif /* def FEATURE_COOKIE_JAR */
3355 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3357 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
3358 return crumble(csp, header);
3360 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3362 /* Flag whether or not to log a message */
3365 /* A variable to store the tag we're working on */
3368 /* Skip "Set-Cookie:" (11 characters) in header */
3369 cur_tag = *header + 11;
3371 /* skip whitespace between "Set-Cookie:" and value */
3372 while (*cur_tag && ijb_isspace(*cur_tag))
3377 /* Loop through each tag in the cookie */
3381 char *next_tag = strchr(cur_tag, ';');
3382 if (next_tag != NULL)
3384 /* Skip the ';' character itself */
3387 /* skip whitespace ";" and start of tag */
3388 while (*next_tag && ijb_isspace(*next_tag))
3395 /* "Next tag" is the end of the string */
3396 next_tag = cur_tag + strlen(cur_tag);
3400 * Check the expiration date to see
3401 * if the cookie is still valid, if yes,
3402 * rewrite it to a session cookie.
3404 if (strncmpic(cur_tag, "expires=", 8) == 0)
3408 * Try the valid time formats we know about.
3410 * XXX: Maybe the log messages should be removed
3411 * for the next stable release. They just exist to
3412 * see which time format gets the most hits and
3413 * should be checked for first.
3415 if (NULL != (match = strptime(cur_tag, "expires=%a, %e-%b-%y %H:%M:%S ", &tm_cookie)))
3417 log_error(LOG_LEVEL_HEADER,
3418 "cookie \'%s\' send by %s appears to be using time format 1.",
3419 csp->http->url, *header);
3421 else if (NULL != (match = strptime(cur_tag, "expires=%A, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3423 log_error(LOG_LEVEL_HEADER,
3424 "cookie \'%s\' send by %s appears to be using time format 2.",
3425 csp->http->url, *header);
3428 else if (NULL != (match = strptime(cur_tag, "expires=%a, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3430 log_error(LOG_LEVEL_HEADER,
3431 "cookie \'%s\' send by %s appears to be using time format 3.",
3432 csp->http->url, *header);
3435 /* Did any of them match? */
3439 * Nope, treat it as if it was still valid.
3441 * XXX: Should we remove the whole cookie instead?
3443 log_error(LOG_LEVEL_ERROR,
3444 "Can't parse %s. Unsupported time format?", cur_tag);
3445 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3451 * Yes. Check if the cookie is still valid.
3453 * If the cookie is already expired it's probably
3454 * a delete cookie and even if it isn't, the browser
3455 * will discard it anyway.
3459 * XXX: timegm() isn't available on some AmigaOS
3460 * versions and our replacement doesn't work.
3462 * Our options are to either:
3464 * - disable session-cookies-only completely if timegm
3467 * - to simply remove all expired tags, like it has
3468 * been done until Privoxy 3.0.6 and to live with
3469 * the consequence that it can cause login/logout
3470 * problems on servers that don't validate their
3471 * input properly, or
3473 * - to replace it with mktime in which
3474 * case there is a slight chance of valid cookies
3475 * passing as already expired.
3477 * This is the way it's currently done and it's not
3478 * as bad as it sounds. If the missing GMT offset is
3479 * enough to change the result of the expiration check
3480 * the cookie will be only valid for a few hours
3481 * anyway, which in many cases will be shorter
3482 * than a browser session.
3484 cookie_time = timegm(&tm_cookie);
3485 if (cookie_time - now < 0)
3487 log_error(LOG_LEVEL_HEADER,
3488 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3489 /* Just in case some clown sets more then one expiration date */
3494 log_error(LOG_LEVEL_HEADER,
3495 "Cookie \'%s\' is still valid and has to be rewritten.", *header);
3498 * Delete the tag by copying the rest of the string over it.
3499 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3500 * since the behaviour of strcpy is undefined for overlapping
3503 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3505 /* That changed the header, need to issue a log message */
3509 * Note that the next tag has now been moved to *cur_tag,
3510 * so we do not need to update the cur_tag pointer.
3518 /* Move on to next cookie tag */
3525 assert(NULL != *header);
3526 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3535 #ifdef FEATURE_FORCE_LOAD
3536 /*********************************************************************
3538 * Function : strclean
3540 * Description : In-Situ-Eliminate all occurances of substring in
3544 * 1 : string = string to clean
3545 * 2 : substring = substring to eliminate
3547 * Returns : Number of eliminations
3549 *********************************************************************/
3550 int strclean(const char *string, const char *substring)
3556 len = strlen(substring);
3558 while((pos = strstr(string, substring)) != NULL)
3565 while (*p++ != '\0');
3572 #endif /* def FEATURE_FORCE_LOAD */
3574 /*********************************************************************
3576 * Function : parse_header_time
3578 * Description : Transforms time inside a HTTP header into
3579 * the usual time format.
3582 * 1 : header = header to parse
3583 * 2 : tm = storage for the resulting time in seconds
3585 * Returns : Time struct containing the header time, or
3586 * NULL in case of a parsing problems.
3588 *********************************************************************/
3589 struct tm *parse_header_time(char *header, time_t *tm) {
3593 struct tm * timeptr;
3596 * Initializing gmt to prevent time zone offsets.
3598 * While this is only necessary on some platforms
3599 * (mingw32 for example), I don't know how to
3600 * detect these automatically and doing it everywhere
3604 #ifdef HAVE_LOCALTIME_R
3605 gmt = *localtime_r(tm, &gmt);
3606 #elif FEATURE_PTHREAD
3607 pthread_mutex_lock(&localtime_mutex);
3608 gmt = *localtime(tm);
3609 pthread_mutex_unlock(&localtime_mutex);
3611 gmt = *localtime(tm);
3614 /* Skipping header name */
3615 timestring = strstr(header, ": ");
3616 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)
3629 /*********************************************************************
3631 * Function : get_destination_from_headers
3633 * Description : Parse the "Host:" header to get the request's destination.
3634 * Only needed if the client's request was forcefully
3635 * redirected into Privoxy.
3637 * Code mainly copied from client_host() which is currently
3638 * run too late for this purpose.
3641 * 1 : headers = List of headers (one of them hopefully being
3642 * the "Host:" header)
3643 * 2 : http = storage for the result (host, port and hostport).
3645 * Returns : JB_ERR_MEMORY in case of memory problems,
3646 * JB_ERR_PARSE if the host header couldn't be found,
3647 * JB_ERR_OK otherwise.
3649 *********************************************************************/
3650 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3656 host = get_header_value(headers, "Host:");
3660 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3661 return JB_ERR_PARSE;
3664 if (NULL == (p = strdup((host))))
3666 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3667 return JB_ERR_MEMORY;
3670 if (NULL == (q = strdup(p)))
3673 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3674 return JB_ERR_MEMORY;
3677 freez(http->hostport);
3681 q = strchr(http->host, ':');
3684 /* Terminate hostname and evaluate port string */
3686 http->port = atoi(q);
3690 http->port = http->ssl ? 443 : 80;
3693 /* Rebuild request URL */
3695 http->url = strdup(http->ssl ? "https://" : "http://");
3696 string_append(&http->url, http->hostport);
3697 string_append(&http->url, http->path);
3698 if (http->url == NULL)
3700 return JB_ERR_MEMORY;
3703 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",