1 const char parsers_rcs[] = "$Id: parsers.c,v 1.85 2007/01/26 15:33:46 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.85 2007/01/26 15:33:46 fabiankeil
49 * Stop filter_header() from unintentionally removing
50 * empty header lines that were enlisted by the continue
53 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
54 * - Repeat the request URL before logging any headers.
55 * Makes reading the log easier in case of simultaneous requests.
56 * - If there are more than one Content-Type headers in one request,
57 * use the first one and remove the others.
58 * - Remove "newval" variable in server_content_type().
59 * It's only used once.
61 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
62 * Correct a cast, check inflateEnd() exit code
63 * to see if we have to, replace sprintf calls
66 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
67 * Integrate a modified version of Wil Mahan's
68 * zlib patch (PR #895531).
70 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
71 * Skip empty filter files in filter_header()
72 * but don't ignore the ones that come afterwards.
73 * Fixes BR 1619208, this time for real.
75 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
76 * Reverted parts of my last commit
77 * to keep error handling working.
79 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
80 * Fixed gcc43 conversion warnings.
82 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
83 * Bringing back the "useless" localtime() call
84 * I removed in revision 1.67. On some platforms
85 * it's necessary to prevent time zone offsets.
87 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
88 * Rebuild request URL in get_destination_from_headers()
89 * to make sure redirect{pcrs command} works as expected
90 * for intercepted requests.
92 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
93 * Added get_destination_from_headers().
95 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
96 * Make pthread mutex locking more generic. Instead of
97 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
98 * and use mutex locking unless there is an _r function
99 * available. Better safe than sorry.
101 * Fixes "./configure --disable-pthread" and should result
102 * in less threading-related problems on pthread-using platforms,
103 * but it still doesn't fix BR#1122404.
105 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
106 * The special header "X-Filter: No" now disables
107 * header filtering as well.
109 * Revision 1.73 2006/09/23 13:26:38 roro
110 * Replace TABs by spaces in source code.
112 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
113 * Don't print a log message every time filter_headers is
114 * entered or left. It only creates noise without any real
117 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
118 * Fix +hide-if-modified-since{-n}.
120 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
121 * Have hide-if-modified-since interpret the random
122 * range value as minutes instead of hours. Allows
123 * more fine-grained configuration.
125 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
126 * Always have parse_header_time return a pointer
127 * that actual makes sense, even though we currently
128 * only need it to detect problems.
130 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
131 * Added config option enable-remote-http-toggle
132 * to specify if Privoxy should recognize special
133 * headers (currently only X-Filter) to change its
134 * behaviour. Disabled by default.
136 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
137 * After filtering de-chunked instances, remove
138 * "Transfer-Encoding" header entirely instead of changing
139 * it to "Transfer-Encoding: identity", which is invalid.
140 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
142 * Don't use localtime in parse_header_time. An empty time struct
143 * is good enough, it gets overwritten by strptime anyway.
145 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
146 * Use gmtime_r if available, fallback to gmtime with mutex
147 * protection for MacOSX and use vanilla gmtime for the rest.
149 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
150 * Changed client_referrer to use the right type (size_t) for
151 * hostlenght and to shorten the temporary referrer string with
152 * '\0' instead of adding a useless line break.
154 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
155 * - Back to timegm() using GnuPG's replacement if necessary.
156 * Using mktime() and localtime() could add a on hour offset if
157 * the randomize factor was big enough to lead to a summer/wintertime
160 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
162 * - Moved randomization code into pick_from_range().
164 * - Changed parse_header_time definition.
165 * time_t isn't guaranteed to be signed and
166 * if it isn't, -1 isn't available as error code.
167 * Changed some variable types in client_if_modified_since()
168 * because of the same reason.
170 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
171 * OS/2 compilation compatibility fixups
173 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
174 * Changed include from strptime.c to strptime.h
176 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
177 * Split filter-headers{} into filter-client-headers{}
178 * and filter-server-headers{}.
179 * Added parse_header_time() to share some code.
180 * Replaced timegm() with mktime().
182 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
183 * Windows service integration
185 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
186 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
188 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
189 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
190 * with what was really the latest development (the v_3_0_branch branch)
192 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
193 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
195 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
196 * Add the ability to check jpeg images for invalid
197 * lengths of comment blocks. Defensive strategy
198 * against the exploit:
199 * Microsoft Security Bulletin MS04-028
200 * Buffer Overrun in JPEG Processing (GDI+) Could
201 * Allow Code Execution (833987)
202 * Enabled with +inspect-jpegs in actions files.
204 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
205 * Excluded text/plain objects from filtering. This fixes a
206 * couple of client-crashing, download corruption and
207 * Privoxy performance issues, whose root cause lies in
208 * web servers labelling content of unknown type as text/plain.
210 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
211 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
213 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
214 * Completing the previous change
216 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
217 * Added temporary workaround for bug in PHP < 4.2.3
219 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
220 * 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.
222 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
223 * Fix typo: supressed -> suppressed
225 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
226 * Improved cookie logging
228 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
229 * Added basic support for OPTIONS and TRACE HTTP methods:
230 * - New parser function client_max_forwards which decrements
231 * the Max-Forwards HTTP header field of OPTIONS and TRACE
232 * requests by one before forwarding
233 * - New parser function client_host which extracts the host
234 * and port information from the HTTP header field if the
235 * request URI was not absolute
236 * - Don't crumble and re-add the Host: header, but only generate
237 * and append if missing
239 * Revision 1.56 2002/05/12 15:34:22 jongfoster
240 * Fixing typo in a comment
242 * Revision 1.55 2002/05/08 16:01:07 oes
243 * Optimized add_to_iob:
244 * - Use realloc instead of malloc(), memcpy(), free()
245 * - Expand to powers of two if possible, to get
246 * O(log n) reallocs instead of O(n).
247 * - Moved check for buffer limit here from chat
248 * - Report failure via returncode
250 * Revision 1.54 2002/04/02 15:03:16 oes
251 * Tiny code cosmetics
253 * Revision 1.53 2002/03/26 22:29:55 swa
254 * we have a new homepage!
256 * Revision 1.52 2002/03/24 13:25:43 swa
257 * name change related issues
259 * Revision 1.51 2002/03/13 00:27:05 jongfoster
262 * Revision 1.50 2002/03/12 01:45:35 oes
263 * More verbose logging
265 * Revision 1.49 2002/03/09 20:03:52 jongfoster
266 * - Making various functions return int rather than size_t.
267 * (Undoing a recent change). Since size_t is unsigned on
268 * Windows, functions like read_socket that return -1 on
269 * error cannot return a size_t.
271 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
272 * crashes, and also frequently caused JB to jump to 100%
273 * CPU and stay there. (Because it thought it had just
274 * read ((unsigned)-1) == 4Gb of data...)
276 * - The signature of write_socket has changed, it now simply
277 * returns success=0/failure=nonzero.
279 * - Trying to get rid of a few warnings --with-debug on
280 * Windows, I've introduced a new type "jb_socket". This is
281 * used for the socket file descriptors. On Windows, this
282 * is SOCKET (a typedef for unsigned). Everywhere else, it's
283 * an int. The error value can't be -1 any more, so it's
284 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
285 * Windows it maps to the #define INVALID_SOCKET.)
287 * - The signature of bind_port has changed.
289 * Revision 1.48 2002/03/07 03:46:53 oes
290 * Fixed compiler warnings etc
292 * Revision 1.47 2002/02/20 23:15:13 jongfoster
293 * Parsing functions now handle out-of-memory gracefully by returning
296 * Revision 1.46 2002/01/17 21:03:47 jongfoster
297 * Moving all our URL and URL pattern parsing code to urlmatch.c.
299 * Revision 1.45 2002/01/09 14:33:03 oes
300 * Added support for localtime_r.
302 * Revision 1.44 2001/12/14 01:22:54 steudten
303 * Remove 'user:pass@' from 'proto://user:pass@host' for the
304 * new added header 'Host: ..'. (See Req ID 491818)
306 * Revision 1.43 2001/11/23 00:26:38 jongfoster
307 * Fixing two really stupid errors in my previous commit
309 * Revision 1.42 2001/11/22 21:59:30 jongfoster
310 * Adding code to handle +no-cookies-keep
312 * Revision 1.41 2001/11/05 23:43:05 steudten
313 * Add time+date to log files.
315 * Revision 1.40 2001/10/26 20:13:09 jongfoster
316 * ctype.h is needed in Windows, too.
318 * Revision 1.39 2001/10/26 17:40:04 oes
319 * Introduced get_header_value()
320 * Removed http->user_agent, csp->referrer and csp->accept_types
321 * Removed client_accept()
323 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
324 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
325 * threads to call select() simultaneously. So, it's time to do a real, live,
326 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
327 * (native). Both versions will work, but using __OS2__ offers multi-threading.
329 * Revision 1.37 2001/10/23 21:36:02 jongfoster
330 * Documenting sed()'s error behaviou (doc change only)
332 * Revision 1.36 2001/10/13 12:51:51 joergs
333 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
334 * force-load), instead crumble Host: and add it (again) in client_host_adder
335 * (in case we get a HTTP/1.0 request without Host: header and forward it to
336 * a HTTP/1.1 server/proxy).
338 * Revision 1.35 2001/10/09 22:39:21 jongfoster
339 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
342 * Revision 1.34 2001/10/07 18:50:55 oes
343 * Added server_content_encoding, renamed server_transfer_encoding
345 * Revision 1.33 2001/10/07 18:04:49 oes
346 * Changed server_http11 to server_http and its pattern to "HTTP".
347 * Additional functionality: it now saves the HTTP status into
348 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
350 * Revision 1.32 2001/10/07 15:43:28 oes
351 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
352 * client_te and client_accept_encoding_adder, triggered by the new
353 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
354 * changed to allow only identity and chunked, and the TE header is
355 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
357 * parse_http_request no longer does anything than parsing. The rewriting
358 * of http->cmd and version mangling are gone. It now also recognizes
359 * the put and delete methods and saves the url in http->url. Removed
362 * renamed content_type and content_length to have the server_ prefix
364 * server_content_type now only works if csp->content_type != CT_TABOO
366 * added server_transfer_encoding, which
367 * - Sets CT_TABOO to prohibit filtering if encoding compresses
368 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
369 * - Change from "chunked" to "identity" if body was chunked
370 * but has been de-chunked for filtering.
372 * added server_content_md5 which crunches any Content-MD5 headers
373 * if the body was modified.
375 * made server_http11 conditional on +downgrade action
377 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
379 * Revision 1.31 2001/10/05 14:25:02 oes
380 * Crumble Keep-Alive from Server
382 * Revision 1.30 2001/09/29 12:56:03 joergs
383 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
385 * Revision 1.29 2001/09/24 21:09:24 jongfoster
386 * Fixing 2 memory leaks that Guy spotted, where the paramater to
387 * enlist() was not being free()d.
389 * Revision 1.28 2001/09/22 16:32:28 jongfoster
390 * Removing unused #includes.
392 * Revision 1.27 2001/09/20 15:45:25 steudten
394 * add casting from size_t to int for printf()
395 * remove local variable shadow s2
397 * Revision 1.26 2001/09/16 17:05:14 jongfoster
398 * Removing unused #include showarg.h
400 * Revision 1.25 2001/09/16 13:21:27 jongfoster
401 * Changes to use new list functions.
403 * Revision 1.24 2001/09/13 23:05:50 jongfoster
404 * Changing the string paramater to the header parsers a "const".
406 * Revision 1.23 2001/09/12 18:08:19 steudten
408 * In parse_http_request() header rewriting miss the host value, so
409 * from http://www.mydomain.com the result was just " / " not
410 * http://www.mydomain.com/ in case we forward.
412 * Revision 1.22 2001/09/10 10:58:53 oes
413 * Silenced compiler warnings
415 * Revision 1.21 2001/07/31 14:46:00 oes
416 * - Persistant connections now suppressed
417 * - sed() no longer appends empty header to csp->headers
419 * Revision 1.20 2001/07/30 22:08:36 jongfoster
420 * Tidying up #defines:
421 * - All feature #defines are now of the form FEATURE_xxx
422 * - Permanently turned off WIN_GUI_EDIT
423 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
425 * Revision 1.19 2001/07/25 17:21:54 oes
426 * client_uagent now saves copy of User-Agent: header value
428 * Revision 1.18 2001/07/13 14:02:46 oes
429 * - Included fix to repair broken HTTP requests that
430 * don't contain a path, not even '/'.
431 * - Removed all #ifdef PCRS
432 * - content_type now always inspected and classified as
433 * text, gif or other.
434 * - formatting / comments
436 * Revision 1.17 2001/06/29 21:45:41 oes
437 * Indentation, CRLF->LF, Tab-> Space
439 * Revision 1.16 2001/06/29 13:32:42 oes
441 * - Adapted free_http_request
442 * - Removed logentry from cancelled commit
444 * Revision 1.15 2001/06/03 19:12:38 oes
445 * deleted const struct interceptors
447 * Revision 1.14 2001/06/01 18:49:17 jongfoster
448 * Replaced "list_share" with "list" - the tiny memory gain was not
449 * worth the extra complexity.
451 * Revision 1.13 2001/05/31 21:30:33 jongfoster
452 * Removed list code - it's now in list.[ch]
453 * Renamed "permission" to "action", and changed many features
454 * to use the actions file rather than the global config.
456 * Revision 1.12 2001/05/31 17:33:13 oes
460 * Revision 1.11 2001/05/29 20:11:19 joergs
461 * '/ * inside comment' warning removed.
463 * Revision 1.10 2001/05/29 09:50:24 jongfoster
464 * Unified blocklist/imagelist/permissionslist.
465 * File format is still under discussion, but the internal changes
468 * Also modified interceptor behaviour:
469 * - We now intercept all URLs beginning with one of the following
470 * prefixes (and *only* these prefixes):
472 * * http://ijbswa.sf.net/config/
473 * * http://ijbswa.sourceforge.net/config/
474 * - New interceptors "home page" - go to http://i.j.b/ to see it.
475 * - Internal changes so that intercepted and fast redirect pages
476 * are not replaced with an image.
477 * - Interceptors now have the option to send a binary page direct
478 * to the client. (i.e. ijb-send-banner uses this)
479 * - Implemented show-url-info interceptor. (Which is why I needed
480 * the above interceptors changes - a typical URL is
481 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
482 * The previous mechanism would not have intercepted that, and
483 * if it had been intercepted then it then it would have replaced
486 * Revision 1.9 2001/05/28 17:26:33 jongfoster
487 * Fixing segfault if last header was crunched.
488 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
489 * can use the cross-platform sprintf() instead.)
491 * Revision 1.8 2001/05/27 22:17:04 oes
493 * - re_process_buffer no longer writes the modified buffer
494 * to the client, which was very ugly. It now returns the
495 * buffer, which it is then written by chat.
497 * - content_length now adjusts the Content-Length: header
498 * for modified documents rather than crunch()ing it.
499 * (Length info in csp->content_length, which is 0 for
500 * unmodified documents)
502 * - For this to work, sed() is called twice when filtering.
504 * Revision 1.7 2001/05/27 13:19:06 oes
505 * Patched Joergs solution for the content-length in.
507 * Revision 1.6 2001/05/26 13:39:32 jongfoster
508 * Only crunches Content-Length header if applying RE filtering.
509 * Without this fix, Microsoft Windows Update wouldn't work.
511 * Revision 1.5 2001/05/26 00:28:36 jongfoster
512 * Automatic reloading of config file.
513 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
514 * Most of the global variables have been moved to a new
515 * struct configuration_spec, accessed through csp->config->globalname
516 * Most of the globals remaining are used by the Win32 GUI.
518 * Revision 1.4 2001/05/22 18:46:04 oes
520 * - Enabled filtering banners by size rather than URL
521 * by adding patterns that replace all standard banner
522 * sizes with the "Junkbuster" gif to the re_filterfile
524 * - Enabled filtering WebBugs by providing a pattern
525 * which kills all 1x1 images
527 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
528 * which is selected by the (nonstandard and therefore
529 * capital) letter 'U' in the option string.
530 * It causes the quantifiers to be ungreedy by default.
531 * Appending a ? turns back to greedy (!).
533 * - Added a new interceptor ijb-send-banner, which
534 * sends back the "Junkbuster" gif. Without imagelist or
535 * MSIE detection support, or if tinygif = 1, or the
536 * URL isn't recognized as an imageurl, a lame HTML
537 * explanation is sent instead.
539 * - Added new feature, which permits blocking remote
540 * script redirects and firing back a local redirect
542 * The feature is conditionally compiled, i.e. it
543 * can be disabled with --disable-fast-redirects,
544 * plus it must be activated by a "fast-redirects"
545 * line in the config file, has its own log level
546 * and of course wants to be displayed by show-proxy-args
547 * Note: Boy, all the #ifdefs in 1001 locations and
548 * all the fumbling with configure.in and acconfig.h
549 * were *way* more work than the feature itself :-(
551 * - Because a generic redirect template was needed for
552 * this, tinygif = 3 now uses the same.
554 * - Moved GIFs, and other static HTTP response templates
559 * - Removed some >400 CRs again (Jon, you really worked
562 * Revision 1.3 2001/05/20 01:21:20 jongfoster
563 * Version 2.9.4 checkin.
564 * - Merged popupfile and cookiefile, and added control over PCRS
565 * filtering, in new "permissionsfile".
566 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
567 * file error you now get a message box (in the Win32 GUI) rather
568 * than the program exiting with no explanation.
569 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
571 * - Removed tabs from "config"
572 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
573 * - Bumped up version number.
575 * Revision 1.2 2001/05/17 23:02:36 oes
576 * - Made referrer option accept 'L' as a substitute for '§'
578 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
579 * Initial import of version 2.9.3 source tree
582 *********************************************************************/
589 #include <sys/types.h>
602 #if !defined(_WIN32) && !defined(__OS2__)
608 #ifdef FEATURE_PTHREAD
610 /* jcc.h is for mutex semapores only */
611 #endif /* def FEATURE_PTHREAD */
617 #include "jbsockets.h"
618 #include "miscutil.h"
621 #ifndef HAVE_STRPTIME
622 #include "strptime.h"
625 const char parsers_h_rcs[] = PARSERS_H_VERSION;
627 /* Fix a problem with Solaris. There should be no effect on other
629 * Solaris's isspace() is a macro which uses it's argument directly
630 * as an array index. Therefore we need to make sure that high-bit
631 * characters generate +ve values, and ideally we also want to make
632 * the argument match the declared parameter type of "int".
634 * Why did they write a character function that can't take a simple
635 * "char" argument? Doh!
637 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
638 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
641 const struct parsers client_patterns[] = {
642 { "referer:", 8, client_referrer },
643 { "user-agent:", 11, client_uagent },
644 { "ua-", 3, client_ua },
645 { "from:", 5, client_from },
646 { "cookie:", 7, client_send_cookie },
647 { "x-forwarded-for:", 16, client_x_forwarded },
648 { "Accept-Encoding:", 16, client_accept_encoding },
649 { "TE:", 3, client_te },
650 { "Host:", 5, client_host },
651 { "if-modified-since:", 18, client_if_modified_since },
652 { "Keep-Alive:", 11, crumble },
653 { "connection:", 11, crumble },
654 { "proxy-connection:", 17, crumble },
655 { "max-forwards:", 13, client_max_forwards },
656 { "Accept-Language:", 16, client_accept_language },
657 { "if-none-match:", 14, client_if_none_match },
658 { "X-Filter:", 9, client_x_filter },
659 { "*", 0, crunch_client_header },
660 { "*", 0, filter_client_header },
664 const struct parsers server_patterns[] = {
665 { "HTTP", 4, server_http },
666 { "set-cookie:", 11, server_set_cookie },
667 { "connection:", 11, crumble },
668 { "Content-Type:", 13, server_content_type },
669 { "Content-Length:", 15, server_content_length },
670 { "Content-MD5:", 12, server_content_md5 },
671 { "Content-Encoding:", 17, server_content_encoding },
672 { "Transfer-Encoding:", 18, server_transfer_coding },
673 { "Keep-Alive:", 11, crumble },
674 { "content-disposition:", 20, server_content_disposition },
675 { "Last-Modified:", 14, server_last_modified },
676 { "*", 0, crunch_server_header },
677 { "*", 0, filter_server_header },
681 const struct parsers server_patterns_light[] = {
682 { "Content-Length:", 15, server_content_length },
683 { "Transfer-Encoding:", 18, server_transfer_coding },
685 { "Content-Encoding:", 17, server_content_encoding },
686 #endif /* def FEATURE_ZLIB */
690 const add_header_func_ptr add_client_headers[] = {
693 client_x_forwarded_adder,
695 /* Temporarily disabled: client_accept_encoding_adder, */
696 connection_close_adder,
701 const add_header_func_ptr add_server_headers[] = {
702 connection_close_adder,
706 /*********************************************************************
708 * Function : flush_socket
710 * Description : Write any pending "buffered" content.
713 * 1 : fd = file descriptor of the socket to read
714 * 2 : csp = Current client state (buffers, headers, etc...)
716 * Returns : On success, the number of bytes written are returned (zero
717 * indicates nothing was written). On error, -1 is returned,
718 * and errno is set appropriately. If count is zero and the
719 * file descriptor refers to a regular file, 0 will be
720 * returned without causing any other effect. For a special
721 * file, the results are not portable.
723 *********************************************************************/
724 int flush_socket(jb_socket fd, struct client_state *csp)
726 struct iob *iob = csp->iob;
727 int len = iob->eod - iob->cur;
734 if (write_socket(fd, iob->cur, (size_t)len))
738 iob->eod = iob->cur = iob->buf;
744 /*********************************************************************
746 * Function : add_to_iob
748 * Description : Add content to the buffered page, expanding the
749 * buffer if necessary.
752 * 1 : csp = Current client state (buffers, headers, etc...)
753 * 2 : buf = holds the content to be added to the page
754 * 3 : n = number of bytes to be added
756 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
757 * or buffer limit reached.
759 *********************************************************************/
760 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
762 struct iob *iob = csp->iob;
763 size_t used, offset, need, want;
766 if (n <= 0) return JB_ERR_OK;
768 used = (size_t)(iob->eod - iob->buf);
769 offset = (size_t)(iob->cur - iob->buf);
770 need = used + (size_t)n + 1;
773 * If the buffer can't hold the new data, extend it first.
774 * Use the next power of two if possible, else use the actual need.
776 if (need > csp->config->buffer_limit)
778 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
779 return JB_ERR_MEMORY;
782 if (need > iob->size)
784 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
786 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
790 else if (NULL != (p = (char *)realloc(iob->buf, need)))
796 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
797 return JB_ERR_MEMORY;
800 /* Update the iob pointers */
801 iob->cur = p + offset;
806 /* copy the new data into the iob buffer */
807 memcpy(iob->eod, buf, (size_t)n);
809 /* point to the end of the data */
812 /* null terminate == cheap insurance */
821 /*********************************************************************
823 * Function : decompress_iob
825 * Description : Decompress buffered page, expanding the
826 * buffer as necessary. csp->iob->cur
827 * should point to the the beginning of the
828 * compressed data block.
831 * 1 : csp = Current client state (buffers, headers, etc...)
833 * Returns : JB_ERR_OK on success,
834 * JB_ERR_MEMORY if out-of-memory limit reached, and
835 * JB_ERR_COMPRESS if error decompressing buffer.
837 *********************************************************************/
838 jb_err decompress_iob(struct client_state *csp)
840 char *buf; /* new, uncompressed buffer */
841 size_t bufsize; /* allocated size of the new buffer */
842 size_t skip_size; /* Number of bytes at the beginning of the iob
843 that we should NOT decompress. */
844 int status; /* return status of the inflate() call */
845 z_stream zstr; /* used by calls to zlib */
847 bufsize = csp->iob->size;
848 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
853 * This is to protect the parsing of gzipped data,
854 * but it should(?) be valid for deflated data also.
856 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
857 return JB_ERR_COMPRESS;
860 if (csp->content_type & CT_GZIP)
863 * Our task is slightly complicated by the facts that data
864 * compressed by gzip does not include a zlib header, and
865 * that there is no easily accessible interface in zlib to
866 * handle a gzip header. We strip off the gzip header by
867 * hand, and later inform zlib not to expect a header.
871 * Strip off the gzip header. Please see RFC 1952 for more
872 * explanation of the appropriate fields.
874 if ((*csp->iob->cur++ != (char)0x1f)
875 || (*csp->iob->cur++ != (char)0x8b)
876 || (*csp->iob->cur++ != Z_DEFLATED))
878 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
879 return JB_ERR_COMPRESS;
883 int flags = *csp->iob->cur++;
885 * XXX: These magic numbers should be replaced
886 * with macros to give a better idea what they do.
890 /* The gzip header has reserved bits set; bail out. */
891 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
892 return JB_ERR_COMPRESS;
896 /* Skip extra fields if necessary. */
900 * Skip a given number of bytes, specified
901 * as a 16-bit little-endian value.
903 csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
906 /* Skip the filename if necessary. */
909 /* A null-terminated string follows. */
910 while (*csp->iob->cur++);
913 /* Skip the comment if necessary. */
916 while (*csp->iob->cur++);
919 /* Skip the CRC if necessary. */
926 else if (csp->content_type & CT_DEFLATE)
929 * XXX: The debug level should be lowered
930 * before the next stable release.
932 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *csp->iob->cur);
934 * In theory (that is, according to RFC 1950), deflate-compressed
935 * data should begin with a two-byte zlib header and have an
936 * adler32 checksum at the end. It seems that in practice only
937 * the raw compressed data is sent. Note that this means that
938 * we are not RFC 1950-compliant here, but the advantage is that
939 * this actually works. :)
941 * We add a dummy null byte to tell zlib where the data ends,
942 * and later inform it not to expect a header.
944 * Fortunately, add_to_iob() has thoughtfully null-terminated
945 * the buffer; we can just increment the end pointer to include
952 log_error (LOG_LEVEL_ERROR,
953 "Unable to determine compression format for decompression");
954 return JB_ERR_COMPRESS;
957 /* Set up the fields required by zlib. */
958 zstr.next_in = (Bytef *)csp->iob->cur;
959 zstr.avail_in = (unsigned int)(csp->iob->eod - csp->iob->cur);
960 zstr.zalloc = Z_NULL;
962 zstr.opaque = Z_NULL;
965 * Passing -MAX_WBITS to inflateInit2 tells the library
966 * that there is no zlib header.
968 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
970 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
971 return JB_ERR_COMPRESS;
975 * Next, we allocate new storage for the inflated data.
976 * We don't modify the existing iob yet, so in case there
977 * is error in decompression we can recover gracefully.
979 buf = zalloc (bufsize);
982 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
983 return JB_ERR_MEMORY;
986 assert(bufsize >= skip_size);
987 memcpy(buf, csp->iob->buf, skip_size);
988 zstr.avail_out = bufsize - skip_size;
989 zstr.next_out = (Bytef *)buf + skip_size;
991 /* Try to decompress the whole stream in one shot. */
992 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
994 /* We need to allocate more memory for the output buffer. */
996 char *tmpbuf; /* used for realloc'ing the buffer */
997 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1000 * If zlib wants more data then there's a problem, because
1001 * the complete compressed file should have been buffered.
1003 if (0 == zstr.avail_in)
1005 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1006 return JB_ERR_COMPRESS;
1010 * If we tried the limit and still didn't have enough
1011 * memory, just give up.
1013 if (bufsize == csp->config->buffer_limit)
1015 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1016 return JB_ERR_MEMORY;
1019 /* Try doubling the buffer size each time. */
1022 /* Don't exceed the buffer limit. */
1023 if (bufsize > csp->config->buffer_limit)
1025 bufsize = csp->config->buffer_limit;
1028 /* Try to allocate the new buffer. */
1029 tmpbuf = realloc(buf, bufsize);
1032 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1034 return JB_ERR_MEMORY;
1038 char *oldnext_out = (char *)zstr.next_out;
1041 * Update the fields for inflate() to use the new
1042 * buffer, which may be in a location different from
1045 zstr.avail_out += bufsize - oldbufsize;
1046 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1049 * Compare with an uglier method of calculating these values
1050 * that doesn't require the extra oldbufsize variable.
1052 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1053 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1054 assert(zstr.avail_out > 0);
1060 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1062 log_error(LOG_LEVEL_ERROR,
1063 "Inconsistent stream state after decompression: %s", zstr.msg);
1065 * XXX: Intentionally no return.
1067 * According to zlib.h, Z_STREAM_ERROR is returned
1068 * "if the stream state was inconsistent".
1070 * I assume in this case inflate()'s status
1071 * would also be something different than Z_STREAM_END
1072 * so this check should be redundant, but lets see.
1076 if (status != Z_STREAM_END)
1078 /* We failed to decompress the stream. */
1079 log_error(LOG_LEVEL_ERROR,
1080 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1081 return JB_ERR_COMPRESS;
1085 * Finally, we can actually update the iob, since the
1086 * decompression was successful. First, free the old
1089 freez(csp->iob->buf);
1091 /* Now, update the iob to use the new buffer. */
1092 csp->iob->buf = buf;
1093 csp->iob->cur = csp->iob->buf + skip_size;
1094 csp->iob->eod = (char *)zstr.next_out;
1095 csp->iob->size = bufsize;
1098 * Make sure the new uncompressed iob obeys some minimal
1099 * consistency conditions.
1101 if ((csp->iob->buf < csp->iob->cur)
1102 && (csp->iob->cur <= csp->iob->eod)
1103 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1105 char t = csp->iob->cur[100];
1106 csp->iob->cur[100] = '\0';
1108 * XXX: The debug level should be lowered
1109 * before the next stable release.
1111 log_error(LOG_LEVEL_INFO, "Sucessfully decompressed: %s", csp->iob->cur);
1112 csp->iob->cur[100] = t;
1117 /* It seems that zlib did something weird. */
1118 log_error(LOG_LEVEL_ERROR,
1119 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1120 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1121 csp->iob->eod, csp->iob->buf + csp->iob->size);
1122 return JB_ERR_COMPRESS;
1126 #endif /* defined(FEATURE_ZLIB) */
1129 /*********************************************************************
1131 * Function : get_header
1133 * Description : This (odd) routine will parse the csp->iob
1136 * 1 : csp = Current client state (buffers, headers, etc...)
1138 * Returns : Any one of the following:
1140 * 1) a pointer to a dynamically allocated string that contains a header line
1141 * 2) NULL indicating that the end of the header was reached
1142 * 3) "" indicating that the end of the iob was reached before finding
1143 * a complete header line.
1145 *********************************************************************/
1146 char *get_header(struct client_state *csp)
1152 if ((iob->cur == NULL)
1153 || ((p = strchr(iob->cur, '\n')) == NULL))
1155 return(""); /* couldn't find a complete header */
1160 ret = strdup(iob->cur);
1163 /* FIXME No way to handle error properly */
1164 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1169 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1171 /* is this a blank line (i.e. the end of the header) ? */
1183 /*********************************************************************
1185 * Function : get_header_value
1187 * Description : Get the value of a given header from a chained list
1188 * of header lines or return NULL if no such header is
1189 * present in the list.
1192 * 1 : header_list = pointer to list
1193 * 2 : header_name = string with name of header to look for.
1194 * Trailing colon required, capitalization
1197 * Returns : NULL if not found, else value of header
1199 *********************************************************************/
1200 char *get_header_value(const struct list *header_list, const char *header_name)
1202 struct list_entry *cur_entry;
1206 assert(header_list);
1207 assert(header_name);
1208 length = strlen(header_name);
1210 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1214 if (!strncmpic(cur_entry->str, header_name, length))
1217 * Found: return pointer to start of value
1219 ret = (char *) (cur_entry->str + length);
1220 while (*ret && ijb_isspace(*ret)) ret++;
1233 /*********************************************************************
1237 * Description : add, delete or modify lines in the HTTP header streams.
1238 * On entry, it receives a linked list of headers space
1239 * that was allocated dynamically (both the list nodes
1240 * and the header contents).
1242 * As a side effect it frees the space used by the original
1246 * 1 : pats = list of patterns to match against headers
1247 * 2 : more_headers = list of functions to add more
1248 * headers (client or server)
1249 * 3 : csp = Current client state (buffers, headers, etc...)
1251 * Returns : Single pointer to a fully formed header, or NULL
1252 * on out-of-memory error.
1254 *********************************************************************/
1255 char *sed(const struct parsers pats[],
1256 const add_header_func_ptr more_headers[],
1257 struct client_state *csp)
1259 struct list_entry *p;
1260 const struct parsers *v;
1261 const add_header_func_ptr *f;
1262 jb_err err = JB_ERR_OK;
1266 * If filtering is enabled, sed is run twice,
1267 * but most of the work needs to be done only once.
1269 first_run = (more_headers != NULL ) ? 1 : 0;
1271 if (first_run) /* Parse and print */
1273 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1274 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1276 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1278 /* Header crunch()ed in previous run? -> ignore */
1279 if (p->str == NULL) continue;
1281 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
1283 /* Does the current parser handle this header? */
1284 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1286 err = v->parser(csp, (char **)&(p->str));
1290 /* place any additional headers on the csp->headers list */
1291 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1296 else /* Parse only */
1299 * The second run is only needed if the body was modified
1300 * and the content-lenght has changed.
1302 if (strncmpic(csp->http->cmd, "HEAD", 4))
1304 /*XXX: Code duplication */
1305 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1307 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1309 /* Header crunch()ed in previous run? -> ignore */
1310 if (p->str == NULL) continue;
1312 /* Does the current parser handle this header? */
1313 if (strncmpic(p->str, v->str, v->len) == 0)
1315 err = v->parser(csp, (char **)&(p->str));
1322 if (err != JB_ERR_OK)
1327 return list_to_text(csp->headers);
1331 /* here begins the family of parser functions that reformat header lines */
1333 /*********************************************************************
1335 * Function : filter_server_header
1337 * Description : Checks if server header filtering is enabled.
1338 * If it is, filter_header is called to do the work.
1341 * 1 : csp = Current client state (buffers, headers, etc...)
1342 * 2 : header = On input, pointer to header to modify.
1343 * On output, pointer to the modified header, or NULL
1344 * to remove the header. This function frees the
1345 * original string if necessary.
1347 * Returns : JB_ERR_OK on success and always succeeds
1349 *********************************************************************/
1350 jb_err filter_server_header(struct client_state *csp, char **header)
1352 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
1354 filter_header(csp, header);
1359 /*********************************************************************
1361 * Function : filter_client_header
1363 * Description : Checks if client header filtering is enabled.
1364 * If it is, filter_header is called to do the work.
1367 * 1 : csp = Current client state (buffers, headers, etc...)
1368 * 2 : header = On input, pointer to header to modify.
1369 * On output, pointer to the modified header, or NULL
1370 * to remove the header. This function frees the
1371 * original string if necessary.
1373 * Returns : JB_ERR_OK on success and always succeeds
1375 *********************************************************************/
1376 jb_err filter_client_header(struct client_state *csp, char **header)
1378 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
1380 filter_header(csp, header);
1385 /*********************************************************************
1387 * Function : filter_header
1389 * Description : Executes all text substitutions from all applying
1390 * +filter actions on the header.
1391 * Most of the code was copied from pcrs_filter_response,
1392 * including the rather short variable names
1395 * 1 : csp = Current client state (buffers, headers, etc...)
1396 * 2 : header = On input, pointer to header to modify.
1397 * On output, pointer to the modified header, or NULL
1398 * to remove the header. This function frees the
1399 * original string if necessary.
1401 * Returns : JB_ERR_OK on success and always succeeds
1403 *********************************************************************/
1404 jb_err filter_header(struct client_state *csp, char **header)
1408 size_t size = strlen(*header);
1410 char *newheader = NULL;
1413 struct file_list *fl;
1414 struct re_filterfile_spec *b;
1415 struct list_entry *filtername;
1417 int i, found_filters = 0;
1420 * Need to check the set of re_filterfiles...
1422 for (i = 0; i < MAX_AF_FILES; i++)
1435 if (0 == found_filters)
1437 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1441 for (i = 0; i < MAX_AF_FILES; i++)
1444 if ((NULL == fl) || (NULL == fl->f))
1447 * Either there are no filter files
1448 * left, or this filter file just
1449 * contains no valid filters.
1451 * Continue to be sure we don't miss
1452 * valid filter files that are chained
1453 * after empty or invalid ones.
1458 * For all applying +filter actions, look if a filter by that
1459 * name exists and if yes, execute its pcrs_joblist on the
1462 for (b = fl->f; b; b = b->next)
1464 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1465 filtername ; filtername = filtername->next)
1467 if (strcmp(b->name, filtername->str) == 0)
1469 int current_hits = 0;
1471 if ( NULL == b->joblist )
1473 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1477 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1478 *header, size, b->name);
1480 /* Apply all jobs from the joblist */
1481 for (job = b->joblist; NULL != job; job = job->next)
1483 matches = pcrs_execute(job, *header, size, &newheader, &size);
1486 current_hits += matches;
1487 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1489 *header = newheader;
1491 else if ( 0 == matches )
1493 /* Filter doesn't change header */
1499 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1500 *header, b->name, pcrs_strerror(matches));
1501 if( newheader != NULL)
1503 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1508 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1509 hits += current_hits;
1516 * Additionally checking for hits is important because if
1517 * the continue hack is triggered, server headers can
1518 * arrive empty to separate multiple heads from each other.
1520 if ((0 == size) && hits)
1522 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1530 /*********************************************************************
1532 * Function : crumble
1534 * Description : This is called if a header matches a pattern to "crunch"
1537 * 1 : csp = Current client state (buffers, headers, etc...)
1538 * 2 : header = On input, pointer to header to modify.
1539 * On output, pointer to the modified header, or NULL
1540 * to remove the header. This function frees the
1541 * original string if necessary.
1543 * Returns : JB_ERR_OK on success, or
1544 * JB_ERR_MEMORY on out-of-memory error.
1546 *********************************************************************/
1547 jb_err crumble(struct client_state *csp, char **header)
1549 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1554 /*********************************************************************
1556 * Function : crunch_server_header
1558 * Description : Crunch server header if it matches a string supplied by the
1559 * user. Called from `sed'.
1562 * 1 : csp = Current client state (buffers, headers, etc...)
1563 * 2 : header = On input, pointer to header to modify.
1564 * On output, pointer to the modified header, or NULL
1565 * to remove the header. This function frees the
1566 * original string if necessary.
1568 * Returns : JB_ERR_OK on success and always succeeds
1570 *********************************************************************/
1571 jb_err crunch_server_header(struct client_state *csp, char **header)
1573 const char *crunch_pattern;
1574 /*Is there a header to crunch*/
1576 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1578 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1580 /*Is the current header the lucky one?*/
1581 if (strstr(*header, crunch_pattern))
1583 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1592 /*********************************************************************
1594 * Function : server_content_type
1596 * Description : Set the content-type for filterable types (text/.*,
1597 * .*xml.*, javascript and image/gif) unless filtering has been
1598 * forbidden (CT_TABOO) while parsing earlier headers.
1599 * NOTE: Since text/plain is commonly used by web servers
1600 * for files whose correct type is unknown, we don't
1601 * set CT_TEXT for it.
1604 * 1 : csp = Current client state (buffers, headers, etc...)
1605 * 2 : header = On input, pointer to header to modify.
1606 * On output, pointer to the modified header, or NULL
1607 * to remove the header. This function frees the
1608 * original string if necessary.
1610 * Returns : JB_ERR_OK on success, or
1611 * JB_ERR_MEMORY on out-of-memory error.
1613 *********************************************************************/
1614 jb_err server_content_type(struct client_state *csp, char **header)
1616 /* Remove header if it isn't the first Content-Type header */
1617 if(csp->content_type && (csp->content_type != CT_TABOO))
1620 * Another, slightly slower, way to see if
1621 * we already parsed another Content-Type header.
1623 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1625 log_error(LOG_LEVEL_ERROR,
1626 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1633 if (!(csp->content_type & CT_TABOO))
1635 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1636 || strstr(*header, "xml")
1637 || strstr(*header, "application/x-javascript"))
1639 csp->content_type |= CT_TEXT;
1641 else if (strstr(*header, " image/gif"))
1643 csp->content_type |= CT_GIF;
1645 else if (strstr(*header, " image/jpeg"))
1647 csp->content_type |= CT_JPEG;
1651 csp->content_type = 0;
1655 * Are we enabling text mode by force?
1657 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1660 * Do we really have to?
1662 if (csp->content_type & CT_TEXT)
1664 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1668 csp->content_type |= CT_TEXT;
1669 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1673 * Are we messing with the content type?
1675 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1678 * Make sure the user doesn't accidently
1679 * change the content type of binary documents.
1681 if (csp->content_type & CT_TEXT)
1684 *header = strdup("Content-Type: ");
1685 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1689 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1690 return JB_ERR_MEMORY;
1692 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1696 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1697 "Enable force-text-mode if you know what you're doing.", *header);
1704 /*********************************************************************
1706 * Function : server_transfer_coding
1708 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1709 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1710 * - Remove header if body was chunked but has been
1711 * de-chunked for filtering.
1714 * 1 : csp = Current client state (buffers, headers, etc...)
1715 * 2 : header = On input, pointer to header to modify.
1716 * On output, pointer to the modified header, or NULL
1717 * to remove the header. This function frees the
1718 * original string if necessary.
1720 * Returns : JB_ERR_OK on success, or
1721 * JB_ERR_MEMORY on out-of-memory error.
1723 *********************************************************************/
1724 jb_err server_transfer_coding(struct client_state *csp, char **header)
1727 * Turn off pcrs and gif filtering if body compressed
1729 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1733 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1735 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1736 csp->http->cmd, *header);
1737 #endif /* def FEATURE_ZLIB */
1738 csp->content_type = CT_TABOO;
1742 * Raise flag if body chunked
1744 if (strstr(*header, "chunked"))
1746 csp->flags |= CSP_FLAG_CHUNKED;
1749 * If the body was modified, it has been de-chunked first
1750 * and the header must be removed.
1752 * FIXME: If there is more than one transfer encoding,
1753 * only the "chunked" part should be removed here.
1755 if (csp->flags & CSP_FLAG_MODIFIED)
1757 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1766 /*********************************************************************
1768 * Function : server_content_encoding
1770 * Description : This function is run twice for each request,
1771 * unless FEATURE_ZLIB and filtering are disabled.
1773 * The first run is used to check if the content
1774 * is compressed, if FEATURE_ZLIB is disabled
1775 * filtering is then disabled as well, if FEATURE_ZLIB
1776 * is enabled the content is marked for decompression.
1778 * The second run is used to remove the Content-Encoding
1779 * header if the decompression was successful.
1782 * 1 : csp = Current client state (buffers, headers, etc...)
1783 * 2 : header = On input, pointer to header to modify.
1784 * On output, pointer to the modified header, or NULL
1785 * to remove the header. This function frees the
1786 * original string if necessary.
1788 * Returns : JB_ERR_OK on success, or
1789 * JB_ERR_MEMORY on out-of-memory error.
1791 *********************************************************************/
1792 jb_err server_content_encoding(struct client_state *csp, char **header)
1795 /* XXX: Why would we modify the content if it was taboo? */
1796 if ((csp->flags & CSP_FLAG_MODIFIED) && !(csp->content_type & CT_TABOO))
1799 * We successfully decompressed the content,
1800 * and have to clean the header now, so the
1801 * client no longer expects compressed data..
1803 * XXX: There is a difference between cleaning
1804 * and removing it completely.
1806 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1809 else if (strstr(*header, "gzip"))
1811 /* Mark for gzip decompression */
1812 csp->content_type |= CT_GZIP;
1814 else if (strstr(*header, "deflate"))
1816 /* Mark for zlib decompression */
1817 csp->content_type |= CT_DEFLATE;
1819 else if (strstr(*header, "compress"))
1822 * We can't decompress this; therefore we can't filter
1825 csp->content_type |= CT_TABOO;
1827 #else /* !defined(FEATURE_ZLIB) */
1828 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1831 * Body is compressed, turn off pcrs and gif filtering.
1833 csp->content_type |= CT_TABOO;
1835 #endif /* !defined(FEATURE_ZLIB) */
1842 /*********************************************************************
1844 * Function : server_content_length
1846 * Description : Adjust Content-Length header if we modified
1850 * 1 : csp = Current client state (buffers, headers, etc...)
1851 * 2 : header = On input, pointer to header to modify.
1852 * On output, pointer to the modified header, or NULL
1853 * to remove the header. This function frees the
1854 * original string if necessary.
1856 * Returns : JB_ERR_OK on success, or
1857 * JB_ERR_MEMORY on out-of-memory error.
1859 *********************************************************************/
1860 jb_err server_content_length(struct client_state *csp, char **header)
1862 const size_t max_header_length = 80;
1863 if (csp->content_length != 0) /* Content length could have been modified */
1866 * XXX: Shouldn't we check if csp->content_length
1867 * is different than the original value?
1870 *header = (char *) zalloc(max_header_length);
1871 if (*header == NULL)
1873 return JB_ERR_MEMORY;
1876 snprintf(*header, max_header_length, "Content-Length: %d",
1877 (int)csp->content_length);
1878 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
1879 (int)csp->content_length);
1886 /*********************************************************************
1888 * Function : server_content_md5
1890 * Description : Crumble any Content-MD5 headers if the document was
1891 * modified. FIXME: Should we re-compute instead?
1894 * 1 : csp = Current client state (buffers, headers, etc...)
1895 * 2 : header = On input, pointer to header to modify.
1896 * On output, pointer to the modified header, or NULL
1897 * to remove the header. This function frees the
1898 * original string if necessary.
1900 * Returns : JB_ERR_OK on success, or
1901 * JB_ERR_MEMORY on out-of-memory error.
1903 *********************************************************************/
1904 jb_err server_content_md5(struct client_state *csp, char **header)
1906 if (csp->flags & CSP_FLAG_MODIFIED)
1908 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1915 /*********************************************************************
1917 * Function : server_content_disposition
1919 * Description : If enabled, blocks or modifies the "content-disposition" header.
1920 * Called from `sed'.
1923 * 1 : csp = Current client state (buffers, headers, etc...)
1924 * 2 : header = On input, pointer to header to modify.
1925 * On output, pointer to the modified header, or NULL
1926 * to remove the header. This function frees the
1927 * original string if necessary.
1929 * Returns : JB_ERR_OK on success, or
1930 * JB_ERR_MEMORY on out-of-memory error.
1932 *********************************************************************/
1933 jb_err server_content_disposition(struct client_state *csp, char **header)
1938 * Are we messing with the content-disposition header?
1940 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1946 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1948 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1951 * Blocking content-disposition header
1953 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1960 * Replacing content-disposition header
1963 *header = strdup("content-disposition: ");
1964 string_append(header, newval);
1966 if (*header == NULL)
1968 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1972 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1975 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1978 /*********************************************************************
1980 * Function : server_last_modified
1982 * Description : Changes Last-Modified header to the actual date
1983 * to help hide-if-modified-since.
1984 * Called from `sed'.
1987 * 1 : csp = Current client state (buffers, headers, etc...)
1988 * 2 : header = On input, pointer to header to modify.
1989 * On output, pointer to the modified header, or NULL
1990 * to remove the header. This function frees the
1991 * original string if necessary.
1993 * Returns : JB_ERR_OK on success, or
1994 * JB_ERR_MEMORY on out-of-memory error.
1996 *********************************************************************/
1997 jb_err server_last_modified(struct client_state *csp, char **header)
2000 char buf[BUFFER_SIZE];
2003 #ifdef HAVE_GMTIME_R
2006 struct tm *timeptr = NULL;
2007 time_t now, last_modified;
2009 long int days, hours, minutes, seconds;
2012 * Are we messing with the Last-Modified header?
2014 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2020 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2022 if (0 == strcmpic(newval, "block") )
2025 * Blocking Last-Modified header. Useless but why not.
2027 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2031 else if (0 == strcmpic(newval, "reset-to-request-time"))
2034 * Setting Last-Modified Header to now.
2036 get_http_time(0, buf);
2038 *header = strdup("Last-Modified: ");
2039 string_append(header, buf);
2041 if (*header == NULL)
2043 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2047 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2050 else if (0 == strcmpic(newval, "randomize"))
2052 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2054 #ifdef HAVE_GMTIME_R
2055 timeptr = gmtime_r(&now, &gmt);
2056 #elif FEATURE_PTHREAD
2057 pthread_mutex_lock(&gmtime_mutex);
2058 timeptr = gmtime(&now);
2059 pthread_mutex_unlock(&gmtime_mutex);
2061 timeptr = gmtime(&now);
2063 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
2065 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2070 rtime = (long int)difftime(now, last_modified);
2073 rtime = pick_from_range(rtime);
2074 last_modified += rtime;
2075 #ifdef HAVE_GMTIME_R
2076 timeptr = gmtime_r(&last_modified, &gmt);
2077 #elif FEATURE_PTHREAD
2078 pthread_mutex_lock(&gmtime_mutex);
2079 timeptr = gmtime(&last_modified);
2080 pthread_mutex_unlock(&gmtime_mutex);
2082 timeptr = gmtime(&last_modified);
2084 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2086 *header = strdup("Last-Modified: ");
2087 string_append(header, newheader);
2089 if (*header == NULL)
2091 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2092 return JB_ERR_MEMORY;
2095 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2097 days = rtime / (3600 * 24);
2098 hours = rtime / 3600 % 24;
2099 minutes = rtime / 60 % 60;
2100 seconds = rtime % 60;
2102 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2103 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2104 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2109 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2117 /*********************************************************************
2119 * Function : client_accept_encoding
2121 * Description : Rewrite the client's Accept-Encoding header so that
2122 * if doesn't allow compression, if the action applies.
2123 * Note: For HTTP/1.0 the absence of the header is enough.
2126 * 1 : csp = Current client state (buffers, headers, etc...)
2127 * 2 : header = On input, pointer to header to modify.
2128 * On output, pointer to the modified header, or NULL
2129 * to remove the header. This function frees the
2130 * original string if necessary.
2132 * Returns : JB_ERR_OK on success, or
2133 * JB_ERR_MEMORY on out-of-memory error.
2135 *********************************************************************/
2136 jb_err client_accept_encoding(struct client_state *csp, char **header)
2138 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2140 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2144 /* Temporarily disable the correct behaviour to
2145 * work around a PHP bug.
2147 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2149 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2150 * if (*header == NULL)
2152 * return JB_ERR_MEMORY;
2163 /*********************************************************************
2165 * Function : client_te
2167 * Description : Rewrite the client's TE header so that
2168 * if doesn't allow compression, if the action applies.
2171 * 1 : csp = Current client state (buffers, headers, etc...)
2172 * 2 : header = On input, pointer to header to modify.
2173 * On output, pointer to the modified header, or NULL
2174 * to remove the header. This function frees the
2175 * original string if necessary.
2177 * Returns : JB_ERR_OK on success, or
2178 * JB_ERR_MEMORY on out-of-memory error.
2180 *********************************************************************/
2181 jb_err client_te(struct client_state *csp, char **header)
2183 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2186 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2192 /*********************************************************************
2194 * Function : client_referrer
2196 * Description : Handle the "referer" config setting properly.
2197 * Called from `sed'.
2200 * 1 : csp = Current client state (buffers, headers, etc...)
2201 * 2 : header = On input, pointer to header to modify.
2202 * On output, pointer to the modified header, or NULL
2203 * to remove the header. This function frees the
2204 * original string if necessary.
2206 * Returns : JB_ERR_OK on success, or
2207 * JB_ERR_MEMORY on out-of-memory error.
2209 *********************************************************************/
2210 jb_err client_referrer(struct client_state *csp, char **header)
2217 #ifdef FEATURE_FORCE_LOAD
2218 /* Since the referrer can include the prefix even
2219 * if the request itself is non-forced, we must
2220 * clean it unconditionally
2222 strclean(*header, FORCE_PREFIX);
2223 #endif /* def FEATURE_FORCE_LOAD */
2226 * Are we sending referer?
2228 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2233 newval = csp->action->string[ACTION_STRING_REFERER];
2235 if ((0 != strcmpic(newval, "conditional-block")))
2239 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2244 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2247 else if (0 == strcmpic(newval, "conditional-block"))
2250 * Block referer if host has changed.
2253 if (NULL == (host = strdup(csp->http->hostport)))
2256 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2257 return JB_ERR_MEMORY;
2259 if (NULL == (referer = strdup(*header)))
2263 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2264 return JB_ERR_MEMORY;
2266 hostlenght = strlen(host);
2267 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2269 /*Shorten referer to make sure the referer is blocked
2270 *if www.example.org/www.example.com-shall-see-the-referer/
2271 *links to www.example.com/
2273 referer[hostlenght+17] = '\0';
2275 if ( 0 == strstr(referer, host)) /*Host has changed*/
2277 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2282 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2288 else if (0 != strcmpic(newval, "forge"))
2291 * We have a specific (fixed) referer we want to send.
2293 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2295 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2297 *header = strdup("Referer: ");
2298 string_append(header, newval);
2299 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2301 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2306 * Forge a referer as http://[hostname:port of REQUEST]/
2307 * to fool stupid checks for in-site links
2310 *header = strdup("Referer: http://");
2311 string_append(header, csp->http->hostport);
2312 string_append(header, "/");
2313 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2315 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2319 /*********************************************************************
2321 * Function : client_accept_language
2323 * Description : Handle the "Accept-Language" config setting properly.
2324 * Called from `sed'.
2327 * 1 : csp = Current client state (buffers, headers, etc...)
2328 * 2 : header = On input, pointer to header to modify.
2329 * On output, pointer to the modified header, or NULL
2330 * to remove the header. This function frees the
2331 * original string if necessary.
2333 * Returns : JB_ERR_OK on success, or
2334 * JB_ERR_MEMORY on out-of-memory error.
2336 *********************************************************************/
2337 jb_err client_accept_language(struct client_state *csp, char **header)
2342 * Are we messing with the Accept-Language?
2344 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2346 /*I don't think so*/
2350 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2352 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2355 * Blocking Accept-Language header
2357 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2364 * Replacing Accept-Language header
2367 *header = strdup("Accept-Language: ");
2368 string_append(header, newval);
2370 if (*header == NULL)
2372 log_error(LOG_LEVEL_ERROR,
2373 "Insufficent memory. Accept-Language header crunched without replacement.");
2377 log_error(LOG_LEVEL_HEADER,
2378 "Accept-Language header crunched and replaced with: %s", *header);
2381 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2384 /*********************************************************************
2386 * Function : crunch_client_header
2388 * Description : Crunch client header if it matches a string supplied by the
2389 * user. Called from `sed'.
2392 * 1 : csp = Current client state (buffers, headers, etc...)
2393 * 2 : header = On input, pointer to header to modify.
2394 * On output, pointer to the modified header, or NULL
2395 * to remove the header. This function frees the
2396 * original string if necessary.
2398 * Returns : JB_ERR_OK on success and always succeeds
2400 *********************************************************************/
2401 jb_err crunch_client_header(struct client_state *csp, char **header)
2403 const char *crunch_pattern;
2404 /*Is there a header to crunch*/
2406 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2408 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2410 /*Is the current header the lucky one?*/
2411 if (strstr(*header, crunch_pattern))
2413 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2421 /*********************************************************************
2423 * Function : client_uagent
2425 * Description : Handle the "user-agent" config setting properly
2426 * and remember its original value to enable browser
2427 * bug workarounds. Called from `sed'.
2430 * 1 : csp = Current client state (buffers, headers, etc...)
2431 * 2 : header = On input, pointer to header to modify.
2432 * On output, pointer to the modified header, or NULL
2433 * to remove the header. This function frees the
2434 * original string if necessary.
2436 * Returns : JB_ERR_OK on success, or
2437 * JB_ERR_MEMORY on out-of-memory error.
2439 *********************************************************************/
2440 jb_err client_uagent(struct client_state *csp, char **header)
2444 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2449 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2456 *header = strdup("User-Agent: ");
2457 string_append(header, newval);
2459 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2461 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2464 /*********************************************************************
2466 * Function : client_ua
2468 * Description : Handle "ua-" headers properly. Called from `sed'.
2471 * 1 : csp = Current client state (buffers, headers, etc...)
2472 * 2 : header = On input, pointer to header to modify.
2473 * On output, pointer to the modified header, or NULL
2474 * to remove the header. This function frees the
2475 * original string if necessary.
2477 * Returns : JB_ERR_OK on success, or
2478 * JB_ERR_MEMORY on out-of-memory error.
2480 *********************************************************************/
2481 jb_err client_ua(struct client_state *csp, char **header)
2483 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2485 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2493 /*********************************************************************
2495 * Function : client_from
2497 * Description : Handle the "from" config setting properly.
2498 * Called from `sed'.
2501 * 1 : csp = Current client state (buffers, headers, etc...)
2502 * 2 : header = On input, pointer to header to modify.
2503 * On output, pointer to the modified header, or NULL
2504 * to remove the header. This function frees the
2505 * original string if necessary.
2507 * Returns : JB_ERR_OK on success, or
2508 * JB_ERR_MEMORY on out-of-memory error.
2510 *********************************************************************/
2511 jb_err client_from(struct client_state *csp, char **header)
2515 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2522 newval = csp->action->string[ACTION_STRING_FROM];
2525 * Are we blocking the e-mail address?
2527 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2529 log_error(LOG_LEVEL_HEADER, "crunched From!");
2533 log_error(LOG_LEVEL_HEADER, " modified");
2535 *header = strdup("From: ");
2536 string_append(header, newval);
2538 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2542 /*********************************************************************
2544 * Function : client_send_cookie
2546 * Description : Handle the "cookie" header properly. Called from `sed'.
2547 * If cookie is accepted, add it to the cookie_list,
2548 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2551 * 1 : csp = Current client state (buffers, headers, etc...)
2552 * 2 : header = On input, pointer to header to modify.
2553 * On output, pointer to the modified header, or NULL
2554 * to remove the header. This function frees the
2555 * original string if necessary.
2557 * Returns : JB_ERR_OK on success, or
2558 * JB_ERR_MEMORY on out-of-memory error.
2560 *********************************************************************/
2561 jb_err client_send_cookie(struct client_state *csp, char **header)
2563 jb_err result = JB_ERR_OK;
2565 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2567 /* strlen("cookie: ") == 8 */
2568 result = enlist(csp->cookie_list, *header + 8);
2572 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2576 * Always remove the cookie here. The cookie header
2577 * will be sent at the end of the header.
2585 /*********************************************************************
2587 * Function : client_x_forwarded
2589 * Description : Handle the "x-forwarded-for" config setting properly,
2590 * also used in the add_client_headers list. Called from `sed'.
2593 * 1 : csp = Current client state (buffers, headers, etc...)
2594 * 2 : header = On input, pointer to header to modify.
2595 * On output, pointer to the modified header, or NULL
2596 * to remove the header. This function frees the
2597 * original string if necessary.
2599 * Returns : JB_ERR_OK on success, or
2600 * JB_ERR_MEMORY on out-of-memory error.
2602 *********************************************************************/
2603 jb_err client_x_forwarded(struct client_state *csp, char **header)
2605 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2607 /* Save it so we can re-add it later */
2608 freez(csp->x_forwarded);
2609 csp->x_forwarded = *header;
2612 * Always set *header = NULL, since this information
2613 * will be sent at the end of the header.
2620 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2627 /*********************************************************************
2629 * Function : client_max_forwards
2631 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2632 * from the value of the Max-Forwards header field.
2635 * 1 : csp = Current client state (buffers, headers, etc...)
2636 * 2 : header = On input, pointer to header to modify.
2637 * On output, pointer to the modified header, or NULL
2638 * to remove the header. This function frees the
2639 * original string if necessary.
2641 * Returns : JB_ERR_OK on success, or
2642 * JB_ERR_MEMORY on out-of-memory error.
2644 *********************************************************************/
2645 jb_err client_max_forwards(struct client_state *csp, char **header)
2647 unsigned int max_forwards;
2649 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2650 (0 == strcmpic(csp->http->gpc, "options")))
2652 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2654 if (max_forwards > 0)
2656 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
2657 log_error(LOG_LEVEL_HEADER, "Max-Forwards header for %s request replaced with: %s",
2658 csp->http->gpc, *header);
2663 * direct_response() which was called earlier
2664 * in chat() should prevent that we ever get
2667 log_error(LOG_LEVEL_ERROR,
2668 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2669 assert(max_forwards != 0);
2674 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2683 /*********************************************************************
2685 * Function : client_host
2687 * Description : If the request URI did not contain host and
2688 * port information, parse and evaluate the Host
2691 * Also, kill ill-formed HOST: headers as sent by
2692 * Apple's iTunes software when used with a proxy.
2695 * 1 : csp = Current client state (buffers, headers, etc...)
2696 * 2 : header = On input, pointer to header to modify.
2697 * On output, pointer to the modified header, or NULL
2698 * to remove the header. This function frees the
2699 * original string if necessary.
2701 * Returns : JB_ERR_OK on success, or
2702 * JB_ERR_MEMORY on out-of-memory error.
2704 *********************************************************************/
2705 jb_err client_host(struct client_state *csp, char **header)
2710 * If the header field name is all upper-case, chances are that it's
2711 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2712 * not a problem -- they are regenerated later.
2714 if ((*header)[1] == 'O')
2716 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2721 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2722 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2725 if (NULL == (p = strdup((*header)+6)))
2727 return JB_ERR_MEMORY;
2730 if (NULL == (q = strdup(p)))
2733 return JB_ERR_MEMORY;
2736 freez(csp->http->hostport);
2737 csp->http->hostport = p;
2738 freez(csp->http->host);
2739 csp->http->host = q;
2740 q = strchr(csp->http->host, ':');
2743 /* Terminate hostname and evaluate port string */
2745 csp->http->port = atoi(q);
2749 csp->http->port = csp->http->ssl ? 443 : 80;
2752 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2753 csp->http->hostport, csp->http->host, csp->http->port);
2759 /*********************************************************************
2761 * Function : client_if_modified_since
2763 * Description : Remove or modify the If-Modified-Since header.
2766 * 1 : csp = Current client state (buffers, headers, etc...)
2767 * 2 : header = On input, pointer to header to modify.
2768 * On output, pointer to the modified header, or NULL
2769 * to remove the header. This function frees the
2770 * original string if necessary.
2772 * Returns : JB_ERR_OK on success, or
2773 * JB_ERR_MEMORY on out-of-memory error.
2775 *********************************************************************/
2776 jb_err client_if_modified_since(struct client_state *csp, char **header)
2779 #ifdef HAVE_GMTIME_R
2782 struct tm *timeptr = NULL;
2786 long int hours, minutes, seconds;
2790 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2793 * The client got an error message because of a temporary problem,
2794 * the problem is gone and the client now tries to revalidate our
2795 * error message on the real server. The revalidation would always
2796 * end with the transmission of the whole document and there is
2797 * no need to expose the bogus If-Modified-Since header.
2799 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2802 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2804 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2806 if ((0 == strcmpic(newval, "block")))
2808 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2811 else /* add random value */
2813 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2815 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2820 rtime = strtol(newval, &endptr, 0);
2823 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2824 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2831 rtime = pick_from_range(rtime);
2835 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2838 tm += rtime * (negative ? -1 : 1);
2839 #ifdef HAVE_GMTIME_R
2840 timeptr = gmtime_r(&tm, &gmt);
2841 #elif FEATURE_PTHREAD
2842 pthread_mutex_lock(&gmtime_mutex);
2843 timeptr = gmtime(&tm);
2844 pthread_mutex_unlock(&gmtime_mutex);
2846 timeptr = gmtime(&tm);
2848 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2851 *header = strdup("If-Modified-Since: ");
2852 string_append(header, newheader);
2854 if (*header == NULL)
2856 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2857 return JB_ERR_MEMORY;
2860 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2862 hours = rtime / 3600;
2863 minutes = rtime / 60 % 60;
2864 seconds = rtime % 60;
2866 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2867 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2868 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2877 /*********************************************************************
2879 * Function : client_if_none_match
2881 * Description : Remove the If-None-Match header.
2884 * 1 : csp = Current client state (buffers, headers, etc...)
2885 * 2 : header = On input, pointer to header to modify.
2886 * On output, pointer to the modified header, or NULL
2887 * to remove the header. This function frees the
2888 * original string if necessary.
2890 * Returns : JB_ERR_OK on success, or
2891 * JB_ERR_MEMORY on out-of-memory error.
2893 *********************************************************************/
2894 jb_err client_if_none_match(struct client_state *csp, char **header)
2896 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2898 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2905 /*********************************************************************
2907 * Function : client_x_filter
2909 * Description : Disables filtering if the client set "X-Filter: No".
2910 * Called from `sed'.
2913 * 1 : csp = Current client state (buffers, headers, etc...)
2914 * 2 : header = On input, pointer to header to modify.
2915 * On output, pointer to the modified header, or NULL
2916 * to remove the header. This function frees the
2917 * original string if necessary.
2919 * Returns : JB_ERR_OK on success
2921 *********************************************************************/
2922 jb_err client_x_filter(struct client_state *csp, char **header)
2924 if ( 0 == strcmpic(*header, "X-Filter: No"))
2926 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2928 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2932 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2934 log_error(LOG_LEVEL_HEADER,
2935 "force-text-mode overruled the client's request to fetch without filtering!");
2939 csp->content_type = CT_TABOO;
2940 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
2941 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
2942 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
2944 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2951 /* the following functions add headers directly to the header list */
2953 /*********************************************************************
2955 * Function : client_host_adder
2957 * Description : Adds the Host: header field if it is missing.
2958 * Called from `sed'.
2961 * 1 : csp = Current client state (buffers, headers, etc...)
2963 * Returns : JB_ERR_OK on success, or
2964 * JB_ERR_MEMORY on out-of-memory error.
2966 *********************************************************************/
2967 jb_err client_host_adder(struct client_state *csp)
2972 if ( !csp->http->hostport || !*(csp->http->hostport))
2978 * remove 'user:pass@' from 'proto://user:pass@host'
2980 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2986 p = csp->http->hostport;
2989 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2990 err = enlist_unique_header(csp->headers, "Host", p);
2996 /*********************************************************************
2998 * Function : client_cookie_adder
3000 * Description : Used in the add_client_headers list. Called from `sed'.
3003 * 1 : csp = Current client state (buffers, headers, etc...)
3005 * Returns : JB_ERR_OK on success, or
3006 * JB_ERR_MEMORY on out-of-memory error.
3008 *********************************************************************/
3009 jb_err client_cookie_adder(struct client_state *csp)
3011 struct list_entry *lst;
3013 struct list_entry *list1 = csp->cookie_list->first;
3014 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
3015 int first_cookie = 1;
3018 if ((list1 == NULL) && (list2 == NULL))
3024 tmp = strdup("Cookie: ");
3026 for (lst = list1; lst ; lst = lst->next)
3034 string_append(&tmp, "; ");
3036 string_append(&tmp, lst->str);
3039 for (lst = list2; lst ; lst = lst->next)
3047 string_append(&tmp, "; ");
3049 string_join(&tmp, cookie_encode(lst->str));
3054 return JB_ERR_MEMORY;
3057 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3058 err = enlist(csp->headers, tmp);
3064 /*********************************************************************
3066 * Function : client_accept_encoding_adder
3068 * Description : Add an Accept-Encoding header to the client's request
3069 * that disables compression if the action applies, and
3070 * the header is not already there. Called from `sed'.
3071 * Note: For HTTP/1.0, the absence of the header is enough.
3074 * 1 : csp = Current client state (buffers, headers, etc...)
3076 * Returns : JB_ERR_OK on success, or
3077 * JB_ERR_MEMORY on out-of-memory error.
3079 *********************************************************************/
3080 jb_err client_accept_encoding_adder(struct client_state *csp)
3082 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3083 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3085 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3092 /*********************************************************************
3094 * Function : client_xtra_adder
3096 * Description : Used in the add_client_headers list. Called from `sed'.
3099 * 1 : csp = Current client state (buffers, headers, etc...)
3101 * Returns : JB_ERR_OK on success, or
3102 * JB_ERR_MEMORY on out-of-memory error.
3104 *********************************************************************/
3105 jb_err client_xtra_adder(struct client_state *csp)
3107 struct list_entry *lst;
3110 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3111 lst ; lst = lst->next)
3113 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3114 err = enlist(csp->headers, lst->str);
3126 /*********************************************************************
3128 * Function : client_x_forwarded_adder
3130 * Description : Used in the add_client_headers list. Called from `sed'.
3133 * 1 : csp = Current client state (buffers, headers, etc...)
3135 * Returns : JB_ERR_OK on success, or
3136 * JB_ERR_MEMORY on out-of-memory error.
3138 *********************************************************************/
3139 jb_err client_x_forwarded_adder(struct client_state *csp)
3144 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3149 if (csp->x_forwarded)
3151 p = strdup(csp->x_forwarded);
3152 string_append(&p, ", ");
3156 p = strdup("X-Forwarded-For: ");
3158 string_append(&p, csp->ip_addr_str);
3162 return JB_ERR_MEMORY;
3165 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3166 err = enlist(csp->headers, p);
3173 /*********************************************************************
3175 * Function : connection_close_adder
3177 * Description : Adds a "Connection: close" header to csp->headers
3178 * as a temporary fix for the needed but missing HTTP/1.1
3179 * support. Called from `sed'.
3180 * FIXME: This whole function shouldn't be neccessary!
3183 * 1 : csp = Current client state (buffers, headers, etc...)
3185 * Returns : JB_ERR_OK on success, or
3186 * JB_ERR_MEMORY on out-of-memory error.
3188 *********************************************************************/
3189 jb_err connection_close_adder(struct client_state *csp)
3191 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3192 return enlist(csp->headers, "Connection: close");
3196 /*********************************************************************
3198 * Function : server_http
3200 * Description : - Save the HTTP Status into csp->http->status
3201 * - Set CT_TABOO to prevent filtering if the answer
3202 * is a partial range (HTTP status 206)
3203 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3207 * 1 : csp = Current client state (buffers, headers, etc...)
3208 * 2 : header = On input, pointer to header to modify.
3209 * On output, pointer to the modified header, or NULL
3210 * to remove the header. This function frees the
3211 * original string if necessary.
3213 * Returns : JB_ERR_OK on success, or
3214 * JB_ERR_MEMORY on out-of-memory error.
3216 *********************************************************************/
3217 jb_err server_http(struct client_state *csp, char **header)
3219 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3220 if (csp->http->status == 206)
3222 csp->content_type = CT_TABOO;
3225 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3228 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3235 /*********************************************************************
3237 * Function : server_set_cookie
3239 * Description : Handle the server "cookie" header properly.
3240 * Log cookie to the jar file. Then "crunch",
3241 * accept or rewrite it to a session cookie.
3242 * Called from `sed'.
3244 * TODO: Allow the user to specify a new expiration
3245 * time to cause the cookie to expire even before the
3246 * browser is closed.
3249 * 1 : csp = Current client state (buffers, headers, etc...)
3250 * 2 : header = On input, pointer to header to modify.
3251 * On output, pointer to the modified header, or NULL
3252 * to remove the header. This function frees the
3253 * original string if necessary.
3255 * Returns : JB_ERR_OK on success, or
3256 * JB_ERR_MEMORY on out-of-memory error.
3258 *********************************************************************/
3259 jb_err server_set_cookie(struct client_state *csp, char **header)
3264 struct tm tm_cookie;
3267 #ifdef FEATURE_COOKIE_JAR
3268 if (csp->config->jar)
3271 * Write timestamp into outbuf.
3273 * Complex because not all OSs have tm_gmtoff or
3274 * the %z field in strftime()
3276 char tempbuf[ BUFFER_SIZE ];
3278 #ifdef HAVE_LOCALTIME_R
3279 tm_now = *localtime_r(&now, &tm_now);
3280 #elif FEATURE_PTHREAD
3281 pthread_mutex_lock(&localtime_mutex);
3282 tm_now = *localtime (&now);
3283 pthread_mutex_unlock(&localtime_mutex);
3285 tm_now = *localtime (&now);
3287 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3289 /* strlen("set-cookie: ") = 12 */
3290 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3292 #endif /* def FEATURE_COOKIE_JAR */
3294 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3296 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
3297 return crumble(csp, header);
3299 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3301 /* Flag whether or not to log a message */
3304 /* A variable to store the tag we're working on */
3307 /* Skip "Set-Cookie:" (11 characters) in header */
3308 cur_tag = *header + 11;
3310 /* skip whitespace between "Set-Cookie:" and value */
3311 while (*cur_tag && ijb_isspace(*cur_tag))
3316 /* Loop through each tag in the cookie */
3320 char *next_tag = strchr(cur_tag, ';');
3321 if (next_tag != NULL)
3323 /* Skip the ';' character itself */
3326 /* skip whitespace ";" and start of tag */
3327 while (*next_tag && ijb_isspace(*next_tag))
3334 /* "Next tag" is the end of the string */
3335 next_tag = cur_tag + strlen(cur_tag);
3339 * Check the expiration date to see
3340 * if the cookie is still valid, if yes,
3341 * rewrite it to a session cookie.
3343 if (strncmpic(cur_tag, "expires=", 8) == 0)
3347 * Try the valid time formats we know about.
3349 * XXX: Maybe the log messages should be removed
3350 * for the next stable release. They just exist to
3351 * see which time format gets the most hits and
3352 * should be checked for first.
3354 if (NULL != (match = strptime(cur_tag, "expires=%a, %e-%b-%y %H:%M:%S ", &tm_cookie)))
3356 log_error(LOG_LEVEL_HEADER,
3357 "cookie \'%s\' send by %s appears to be using time format 1.",
3358 csp->http->url, *header);
3360 else if (NULL != (match = strptime(cur_tag, "expires=%A, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3362 log_error(LOG_LEVEL_HEADER,
3363 "cookie \'%s\' send by %s appears to be using time format 2.",
3364 csp->http->url, *header);
3367 else if (NULL != (match = strptime(cur_tag, "expires=%a, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3369 log_error(LOG_LEVEL_HEADER,
3370 "cookie \'%s\' send by %s appears to be using time format 3.",
3371 csp->http->url, *header);
3374 /* Did any of them match? */
3378 * Nope, treat it as if it was still valid.
3380 * XXX: Should we remove the whole cookie instead?
3382 log_error(LOG_LEVEL_ERROR,
3383 "Can't parse %s. Unsupported time format?", cur_tag);
3384 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3390 * Yes. Check if the cookie is still valid.
3392 * If the cookie is already expired it's probably
3393 * a delete cookie and even if it isn't, the browser
3394 * will discard it anyway.
3398 * XXX: timegm() isn't available on some AmigaOS
3399 * versions and our replacement doesn't work.
3401 * Our options are to either:
3403 * - disable session-cookies-only completely if timegm
3406 * - to simply remove all expired tags, like it has
3407 * been done until Privoxy 3.0.6 and to live with
3408 * the consequence that it can cause login/logout
3409 * problems on servers that don't validate their
3410 * input properly, or
3412 * - to replace it with mktime in which
3413 * case there is a slight chance of valid cookies
3414 * passing as already expired.
3416 * This is the way it's currently done and it's not
3417 * as bad as it sounds. If the missing GMT offset is
3418 * enough to change the result of the expiration check
3419 * the cookie will be only valid for a few hours
3420 * anyway, which in many cases will be shorter
3421 * than a browser session.
3423 cookie_time = timegm(&tm_cookie);
3424 if (cookie_time - now < 0)
3426 log_error(LOG_LEVEL_HEADER,
3427 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3428 /* Just in case some clown sets more then one expiration date */
3433 log_error(LOG_LEVEL_HEADER,
3434 "Cookie \'%s\' is still valid and has to be rewritten.", *header);
3437 * Delete the tag by copying the rest of the string over it.
3438 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3439 * since the behaviour of strcpy is undefined for overlapping
3442 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3444 /* That changed the header, need to issue a log message */
3448 * Note that the next tag has now been moved to *cur_tag,
3449 * so we do not need to update the cur_tag pointer.
3457 /* Move on to next cookie tag */
3464 assert(NULL != *header);
3465 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3474 #ifdef FEATURE_FORCE_LOAD
3475 /*********************************************************************
3477 * Function : strclean
3479 * Description : In-Situ-Eliminate all occurances of substring in
3483 * 1 : string = string to clean
3484 * 2 : substring = substring to eliminate
3486 * Returns : Number of eliminations
3488 *********************************************************************/
3489 int strclean(const char *string, const char *substring)
3495 len = strlen(substring);
3497 while((pos = strstr(string, substring)) != NULL)
3504 while (*p++ != '\0');
3511 #endif /* def FEATURE_FORCE_LOAD */
3513 /*********************************************************************
3515 * Function : parse_header_time
3517 * Description : Transforms time inside a HTTP header into
3518 * the usual time format.
3521 * 1 : header = header to parse
3522 * 2 : tm = storage for the resulting time in seconds
3524 * Returns : Time struct containing the header time, or
3525 * NULL in case of a parsing problems.
3527 *********************************************************************/
3528 struct tm *parse_header_time(char *header, time_t *tm) {
3532 struct tm * timeptr;
3535 * Initializing gmt to prevent time zone offsets.
3537 * While this is only necessary on some platforms
3538 * (mingw32 for example), I don't know how to
3539 * detect these automatically and doing it everywhere
3543 #ifdef HAVE_LOCALTIME_R
3544 gmt = *localtime_r(tm, &gmt);
3545 #elif FEATURE_PTHREAD
3546 pthread_mutex_lock(&localtime_mutex);
3547 gmt = *localtime(tm);
3548 pthread_mutex_unlock(&localtime_mutex);
3550 gmt = *localtime(tm);
3553 /* Skipping header name */
3554 timestring = strstr(header, ": ");
3555 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)
3568 /*********************************************************************
3570 * Function : get_destination_from_headers
3572 * Description : Parse the "Host:" header to get the request's destination.
3573 * Only needed if the client's request was forcefully
3574 * redirected into Privoxy.
3576 * Code mainly copied from client_host() which is currently
3577 * run too late for this purpose.
3580 * 1 : headers = List of headers (one of them hopefully being
3581 * the "Host:" header)
3582 * 2 : http = storage for the result (host, port and hostport).
3584 * Returns : JB_ERR_MEMORY in case of memory problems,
3585 * JB_ERR_PARSE if the host header couldn't be found,
3586 * JB_ERR_OK otherwise.
3588 *********************************************************************/
3589 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3595 host = get_header_value(headers, "Host:");
3599 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3600 return JB_ERR_PARSE;
3603 if (NULL == (p = strdup((host))))
3605 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3606 return JB_ERR_MEMORY;
3609 if (NULL == (q = strdup(p)))
3612 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3613 return JB_ERR_MEMORY;
3616 freez(http->hostport);
3620 q = strchr(http->host, ':');
3623 /* Terminate hostname and evaluate port string */
3625 http->port = atoi(q);
3629 http->port = http->ssl ? 443 : 80;
3632 /* Rebuild request URL */
3634 http->url = strdup(http->ssl ? "https://" : "http://");
3635 string_append(&http->url, http->hostport);
3636 string_append(&http->url, http->path);
3637 if (http->url == NULL)
3639 return JB_ERR_MEMORY;
3642 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",