1 const char parsers_rcs[] = "$Id: parsers.c,v 1.104 2007/07/14 07:38:19 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2007 the SourceForge
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
48 * Move the ACTION_FORCE_TEXT_MODE check out of
49 * server_content_type(). Signal other functions
50 * whether or not a content type has been declared.
51 * Part of the fix for BR#1750917.
53 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
54 * Change sed() to return a jb_err in preparation for forward-override{}.
56 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
57 * Adjust "X-Filter: No" to disable dedicated header filters.
59 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
60 * Streamline client_cookie_adder().
62 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
63 * Make sure filters with dynamic jobs actually use them.
65 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
66 * - Introduce dynamic pcrs jobs that can resolve variables.
67 * - Remove unnecessary update_action_bits_for_all_tags() call.
69 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
70 * - Make tagging based on tags set by earlier taggers
71 * of the same kind possible.
72 * - Log whether or not new tags cause action bits updates
73 * (in which case a matching tag-pattern section exists).
74 * - Log if the user tries to set a tag that is already set.
76 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
77 * Introduce tags as alternative way to specify which
78 * actions apply to a request. At the moment tags can be
79 * created based on client and server headers.
81 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
82 * Log a warning if the content is compressed, filtering is
83 * enabled and Privoxy was compiled without zlib support.
86 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
87 * - Fix warnings when compiled with glibc.
88 * - Don't use crumble() for cookie crunching.
89 * - Move cookie time parsing into parse_header_time().
90 * - Let parse_header_time() return a jb_err code
91 * instead of a pointer that can only be used to
92 * check for NULL anyway.
94 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
95 * - Add better protection against malicious gzip headers.
96 * - Stop logging the first hundred bytes of decompressed content.
97 * It looks like it's working and there is always debug 16.
98 * - Log the content size after decompression in decompress_iob()
99 * instead of pcrs_filter_response().
101 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
102 * - Use dedicated header filter actions instead of abusing "filter".
103 * Replace "filter-client-headers" and "filter-client-headers"
104 * with "server-header-filter" and "client-header-filter".
105 * - Remove filter_client_header() and filter_client_header(),
106 * filter_header() now checks the shiny new
107 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
109 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
110 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
111 * - Handle "Cookie:" and "Connection:" headers a bit smarter
112 * (don't crunch them just to recreate them later on).
113 * - Add another non-standard time format for the cookie
114 * expiration date detection.
115 * - Fix a valgrind warning.
117 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
118 * Improve cookie expiration date detection.
120 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
121 * Don't run server_content_length() the first time
122 * sed() parses server headers; only adjust the
123 * Content-Length header if the page was modified.
125 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
126 * Fix log messages regarding the cookie time format
127 * (cookie and request URL were mixed up).
129 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
130 * - Let decompress_iob()
131 * - not corrupt the content if decompression fails
132 * early. (the first byte(s) were lost).
133 * - use pointer arithmetics with defined outcome for
135 * - Use a different kludge to remember a failed decompression.
137 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
138 * Search for Max-Forwards headers case-insensitive,
139 * don't generate the "501 unsupported" message for invalid
140 * Max-Forwards values and don't increase negative ones.
142 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
143 * - Let server_set_cookie() check the expiration date
144 * of cookies and don't touch the ones that are already
145 * expired. Fixes problems with low quality web applications
146 * as described in BR 932612.
148 * - Adjust comment in client_max_forwards to reality;
149 * remove invalid Max-Forwards headers.
151 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
152 * Stop filter_header() from unintentionally removing
153 * empty header lines that were enlisted by the continue
156 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
157 * - Repeat the request URL before logging any headers.
158 * Makes reading the log easier in case of simultaneous requests.
159 * - If there are more than one Content-Type headers in one request,
160 * use the first one and remove the others.
161 * - Remove "newval" variable in server_content_type().
162 * It's only used once.
164 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
165 * Correct a cast, check inflateEnd() exit code
166 * to see if we have to, replace sprintf calls
169 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
170 * Integrate a modified version of Wil Mahan's
171 * zlib patch (PR #895531).
173 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
174 * Skip empty filter files in filter_header()
175 * but don't ignore the ones that come afterwards.
176 * Fixes BR 1619208, this time for real.
178 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
179 * Reverted parts of my last commit
180 * to keep error handling working.
182 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
183 * Fixed gcc43 conversion warnings.
185 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
186 * Bringing back the "useless" localtime() call
187 * I removed in revision 1.67. On some platforms
188 * it's necessary to prevent time zone offsets.
190 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
191 * Rebuild request URL in get_destination_from_headers()
192 * to make sure redirect{pcrs command} works as expected
193 * for intercepted requests.
195 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
196 * Added get_destination_from_headers().
198 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
199 * Make pthread mutex locking more generic. Instead of
200 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
201 * and use mutex locking unless there is an _r function
202 * available. Better safe than sorry.
204 * Fixes "./configure --disable-pthread" and should result
205 * in less threading-related problems on pthread-using platforms,
206 * but it still doesn't fix BR#1122404.
208 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
209 * The special header "X-Filter: No" now disables
210 * header filtering as well.
212 * Revision 1.73 2006/09/23 13:26:38 roro
213 * Replace TABs by spaces in source code.
215 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
216 * Don't print a log message every time filter_headers is
217 * entered or left. It only creates noise without any real
220 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
221 * Fix +hide-if-modified-since{-n}.
223 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
224 * Have hide-if-modified-since interpret the random
225 * range value as minutes instead of hours. Allows
226 * more fine-grained configuration.
228 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
229 * Always have parse_header_time return a pointer
230 * that actual makes sense, even though we currently
231 * only need it to detect problems.
233 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
234 * Added config option enable-remote-http-toggle
235 * to specify if Privoxy should recognize special
236 * headers (currently only X-Filter) to change its
237 * behaviour. Disabled by default.
239 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
240 * After filtering de-chunked instances, remove
241 * "Transfer-Encoding" header entirely instead of changing
242 * it to "Transfer-Encoding: identity", which is invalid.
243 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
245 * Don't use localtime in parse_header_time. An empty time struct
246 * is good enough, it gets overwritten by strptime anyway.
248 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
249 * Use gmtime_r if available, fallback to gmtime with mutex
250 * protection for MacOSX and use vanilla gmtime for the rest.
252 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
253 * Changed client_referrer to use the right type (size_t) for
254 * hostlenght and to shorten the temporary referrer string with
255 * '\0' instead of adding a useless line break.
257 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
258 * - Back to timegm() using GnuPG's replacement if necessary.
259 * Using mktime() and localtime() could add a on hour offset if
260 * the randomize factor was big enough to lead to a summer/wintertime
263 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
265 * - Moved randomization code into pick_from_range().
267 * - Changed parse_header_time definition.
268 * time_t isn't guaranteed to be signed and
269 * if it isn't, -1 isn't available as error code.
270 * Changed some variable types in client_if_modified_since()
271 * because of the same reason.
273 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
274 * OS/2 compilation compatibility fixups
276 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
277 * Changed include from strptime.c to strptime.h
279 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
280 * Split filter-headers{} into filter-client-headers{}
281 * and filter-server-headers{}.
282 * Added parse_header_time() to share some code.
283 * Replaced timegm() with mktime().
285 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
286 * Windows service integration
288 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
289 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
291 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
292 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
293 * with what was really the latest development (the v_3_0_branch branch)
295 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
296 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
298 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
299 * Add the ability to check jpeg images for invalid
300 * lengths of comment blocks. Defensive strategy
301 * against the exploit:
302 * Microsoft Security Bulletin MS04-028
303 * Buffer Overrun in JPEG Processing (GDI+) Could
304 * Allow Code Execution (833987)
305 * Enabled with +inspect-jpegs in actions files.
307 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
308 * Excluded text/plain objects from filtering. This fixes a
309 * couple of client-crashing, download corruption and
310 * Privoxy performance issues, whose root cause lies in
311 * web servers labelling content of unknown type as text/plain.
313 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
314 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
316 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
317 * Completing the previous change
319 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
320 * Added temporary workaround for bug in PHP < 4.2.3
322 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
323 * 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.
325 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
326 * Fix typo: supressed -> suppressed
328 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
329 * Improved cookie logging
331 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
332 * Added basic support for OPTIONS and TRACE HTTP methods:
333 * - New parser function client_max_forwards which decrements
334 * the Max-Forwards HTTP header field of OPTIONS and TRACE
335 * requests by one before forwarding
336 * - New parser function client_host which extracts the host
337 * and port information from the HTTP header field if the
338 * request URI was not absolute
339 * - Don't crumble and re-add the Host: header, but only generate
340 * and append if missing
342 * Revision 1.56 2002/05/12 15:34:22 jongfoster
343 * Fixing typo in a comment
345 * Revision 1.55 2002/05/08 16:01:07 oes
346 * Optimized add_to_iob:
347 * - Use realloc instead of malloc(), memcpy(), free()
348 * - Expand to powers of two if possible, to get
349 * O(log n) reallocs instead of O(n).
350 * - Moved check for buffer limit here from chat
351 * - Report failure via returncode
353 * Revision 1.54 2002/04/02 15:03:16 oes
354 * Tiny code cosmetics
356 * Revision 1.53 2002/03/26 22:29:55 swa
357 * we have a new homepage!
359 * Revision 1.52 2002/03/24 13:25:43 swa
360 * name change related issues
362 * Revision 1.51 2002/03/13 00:27:05 jongfoster
365 * Revision 1.50 2002/03/12 01:45:35 oes
366 * More verbose logging
368 * Revision 1.49 2002/03/09 20:03:52 jongfoster
369 * - Making various functions return int rather than size_t.
370 * (Undoing a recent change). Since size_t is unsigned on
371 * Windows, functions like read_socket that return -1 on
372 * error cannot return a size_t.
374 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
375 * crashes, and also frequently caused JB to jump to 100%
376 * CPU and stay there. (Because it thought it had just
377 * read ((unsigned)-1) == 4Gb of data...)
379 * - The signature of write_socket has changed, it now simply
380 * returns success=0/failure=nonzero.
382 * - Trying to get rid of a few warnings --with-debug on
383 * Windows, I've introduced a new type "jb_socket". This is
384 * used for the socket file descriptors. On Windows, this
385 * is SOCKET (a typedef for unsigned). Everywhere else, it's
386 * an int. The error value can't be -1 any more, so it's
387 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
388 * Windows it maps to the #define INVALID_SOCKET.)
390 * - The signature of bind_port has changed.
392 * Revision 1.48 2002/03/07 03:46:53 oes
393 * Fixed compiler warnings etc
395 * Revision 1.47 2002/02/20 23:15:13 jongfoster
396 * Parsing functions now handle out-of-memory gracefully by returning
399 * Revision 1.46 2002/01/17 21:03:47 jongfoster
400 * Moving all our URL and URL pattern parsing code to urlmatch.c.
402 * Revision 1.45 2002/01/09 14:33:03 oes
403 * Added support for localtime_r.
405 * Revision 1.44 2001/12/14 01:22:54 steudten
406 * Remove 'user:pass@' from 'proto://user:pass@host' for the
407 * new added header 'Host: ..'. (See Req ID 491818)
409 * Revision 1.43 2001/11/23 00:26:38 jongfoster
410 * Fixing two really stupid errors in my previous commit
412 * Revision 1.42 2001/11/22 21:59:30 jongfoster
413 * Adding code to handle +no-cookies-keep
415 * Revision 1.41 2001/11/05 23:43:05 steudten
416 * Add time+date to log files.
418 * Revision 1.40 2001/10/26 20:13:09 jongfoster
419 * ctype.h is needed in Windows, too.
421 * Revision 1.39 2001/10/26 17:40:04 oes
422 * Introduced get_header_value()
423 * Removed http->user_agent, csp->referrer and csp->accept_types
424 * Removed client_accept()
426 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
427 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
428 * threads to call select() simultaneously. So, it's time to do a real, live,
429 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
430 * (native). Both versions will work, but using __OS2__ offers multi-threading.
432 * Revision 1.37 2001/10/23 21:36:02 jongfoster
433 * Documenting sed()'s error behaviou (doc change only)
435 * Revision 1.36 2001/10/13 12:51:51 joergs
436 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
437 * force-load), instead crumble Host: and add it (again) in client_host_adder
438 * (in case we get a HTTP/1.0 request without Host: header and forward it to
439 * a HTTP/1.1 server/proxy).
441 * Revision 1.35 2001/10/09 22:39:21 jongfoster
442 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
445 * Revision 1.34 2001/10/07 18:50:55 oes
446 * Added server_content_encoding, renamed server_transfer_encoding
448 * Revision 1.33 2001/10/07 18:04:49 oes
449 * Changed server_http11 to server_http and its pattern to "HTTP".
450 * Additional functionality: it now saves the HTTP status into
451 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
453 * Revision 1.32 2001/10/07 15:43:28 oes
454 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
455 * client_te and client_accept_encoding_adder, triggered by the new
456 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
457 * changed to allow only identity and chunked, and the TE header is
458 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
460 * parse_http_request no longer does anything than parsing. The rewriting
461 * of http->cmd and version mangling are gone. It now also recognizes
462 * the put and delete methods and saves the url in http->url. Removed
465 * renamed content_type and content_length to have the server_ prefix
467 * server_content_type now only works if csp->content_type != CT_TABOO
469 * added server_transfer_encoding, which
470 * - Sets CT_TABOO to prohibit filtering if encoding compresses
471 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
472 * - Change from "chunked" to "identity" if body was chunked
473 * but has been de-chunked for filtering.
475 * added server_content_md5 which crunches any Content-MD5 headers
476 * if the body was modified.
478 * made server_http11 conditional on +downgrade action
480 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
482 * Revision 1.31 2001/10/05 14:25:02 oes
483 * Crumble Keep-Alive from Server
485 * Revision 1.30 2001/09/29 12:56:03 joergs
486 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
488 * Revision 1.29 2001/09/24 21:09:24 jongfoster
489 * Fixing 2 memory leaks that Guy spotted, where the paramater to
490 * enlist() was not being free()d.
492 * Revision 1.28 2001/09/22 16:32:28 jongfoster
493 * Removing unused #includes.
495 * Revision 1.27 2001/09/20 15:45:25 steudten
497 * add casting from size_t to int for printf()
498 * remove local variable shadow s2
500 * Revision 1.26 2001/09/16 17:05:14 jongfoster
501 * Removing unused #include showarg.h
503 * Revision 1.25 2001/09/16 13:21:27 jongfoster
504 * Changes to use new list functions.
506 * Revision 1.24 2001/09/13 23:05:50 jongfoster
507 * Changing the string paramater to the header parsers a "const".
509 * Revision 1.23 2001/09/12 18:08:19 steudten
511 * In parse_http_request() header rewriting miss the host value, so
512 * from http://www.mydomain.com the result was just " / " not
513 * http://www.mydomain.com/ in case we forward.
515 * Revision 1.22 2001/09/10 10:58:53 oes
516 * Silenced compiler warnings
518 * Revision 1.21 2001/07/31 14:46:00 oes
519 * - Persistant connections now suppressed
520 * - sed() no longer appends empty header to csp->headers
522 * Revision 1.20 2001/07/30 22:08:36 jongfoster
523 * Tidying up #defines:
524 * - All feature #defines are now of the form FEATURE_xxx
525 * - Permanently turned off WIN_GUI_EDIT
526 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
528 * Revision 1.19 2001/07/25 17:21:54 oes
529 * client_uagent now saves copy of User-Agent: header value
531 * Revision 1.18 2001/07/13 14:02:46 oes
532 * - Included fix to repair broken HTTP requests that
533 * don't contain a path, not even '/'.
534 * - Removed all #ifdef PCRS
535 * - content_type now always inspected and classified as
536 * text, gif or other.
537 * - formatting / comments
539 * Revision 1.17 2001/06/29 21:45:41 oes
540 * Indentation, CRLF->LF, Tab-> Space
542 * Revision 1.16 2001/06/29 13:32:42 oes
544 * - Adapted free_http_request
545 * - Removed logentry from cancelled commit
547 * Revision 1.15 2001/06/03 19:12:38 oes
548 * deleted const struct interceptors
550 * Revision 1.14 2001/06/01 18:49:17 jongfoster
551 * Replaced "list_share" with "list" - the tiny memory gain was not
552 * worth the extra complexity.
554 * Revision 1.13 2001/05/31 21:30:33 jongfoster
555 * Removed list code - it's now in list.[ch]
556 * Renamed "permission" to "action", and changed many features
557 * to use the actions file rather than the global config.
559 * Revision 1.12 2001/05/31 17:33:13 oes
563 * Revision 1.11 2001/05/29 20:11:19 joergs
564 * '/ * inside comment' warning removed.
566 * Revision 1.10 2001/05/29 09:50:24 jongfoster
567 * Unified blocklist/imagelist/permissionslist.
568 * File format is still under discussion, but the internal changes
571 * Also modified interceptor behaviour:
572 * - We now intercept all URLs beginning with one of the following
573 * prefixes (and *only* these prefixes):
575 * * http://ijbswa.sf.net/config/
576 * * http://ijbswa.sourceforge.net/config/
577 * - New interceptors "home page" - go to http://i.j.b/ to see it.
578 * - Internal changes so that intercepted and fast redirect pages
579 * are not replaced with an image.
580 * - Interceptors now have the option to send a binary page direct
581 * to the client. (i.e. ijb-send-banner uses this)
582 * - Implemented show-url-info interceptor. (Which is why I needed
583 * the above interceptors changes - a typical URL is
584 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
585 * The previous mechanism would not have intercepted that, and
586 * if it had been intercepted then it then it would have replaced
589 * Revision 1.9 2001/05/28 17:26:33 jongfoster
590 * Fixing segfault if last header was crunched.
591 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
592 * can use the cross-platform sprintf() instead.)
594 * Revision 1.8 2001/05/27 22:17:04 oes
596 * - re_process_buffer no longer writes the modified buffer
597 * to the client, which was very ugly. It now returns the
598 * buffer, which it is then written by chat.
600 * - content_length now adjusts the Content-Length: header
601 * for modified documents rather than crunch()ing it.
602 * (Length info in csp->content_length, which is 0 for
603 * unmodified documents)
605 * - For this to work, sed() is called twice when filtering.
607 * Revision 1.7 2001/05/27 13:19:06 oes
608 * Patched Joergs solution for the content-length in.
610 * Revision 1.6 2001/05/26 13:39:32 jongfoster
611 * Only crunches Content-Length header if applying RE filtering.
612 * Without this fix, Microsoft Windows Update wouldn't work.
614 * Revision 1.5 2001/05/26 00:28:36 jongfoster
615 * Automatic reloading of config file.
616 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
617 * Most of the global variables have been moved to a new
618 * struct configuration_spec, accessed through csp->config->globalname
619 * Most of the globals remaining are used by the Win32 GUI.
621 * Revision 1.4 2001/05/22 18:46:04 oes
623 * - Enabled filtering banners by size rather than URL
624 * by adding patterns that replace all standard banner
625 * sizes with the "Junkbuster" gif to the re_filterfile
627 * - Enabled filtering WebBugs by providing a pattern
628 * which kills all 1x1 images
630 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
631 * which is selected by the (nonstandard and therefore
632 * capital) letter 'U' in the option string.
633 * It causes the quantifiers to be ungreedy by default.
634 * Appending a ? turns back to greedy (!).
636 * - Added a new interceptor ijb-send-banner, which
637 * sends back the "Junkbuster" gif. Without imagelist or
638 * MSIE detection support, or if tinygif = 1, or the
639 * URL isn't recognized as an imageurl, a lame HTML
640 * explanation is sent instead.
642 * - Added new feature, which permits blocking remote
643 * script redirects and firing back a local redirect
645 * The feature is conditionally compiled, i.e. it
646 * can be disabled with --disable-fast-redirects,
647 * plus it must be activated by a "fast-redirects"
648 * line in the config file, has its own log level
649 * and of course wants to be displayed by show-proxy-args
650 * Note: Boy, all the #ifdefs in 1001 locations and
651 * all the fumbling with configure.in and acconfig.h
652 * were *way* more work than the feature itself :-(
654 * - Because a generic redirect template was needed for
655 * this, tinygif = 3 now uses the same.
657 * - Moved GIFs, and other static HTTP response templates
662 * - Removed some >400 CRs again (Jon, you really worked
665 * Revision 1.3 2001/05/20 01:21:20 jongfoster
666 * Version 2.9.4 checkin.
667 * - Merged popupfile and cookiefile, and added control over PCRS
668 * filtering, in new "permissionsfile".
669 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
670 * file error you now get a message box (in the Win32 GUI) rather
671 * than the program exiting with no explanation.
672 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
674 * - Removed tabs from "config"
675 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
676 * - Bumped up version number.
678 * Revision 1.2 2001/05/17 23:02:36 oes
679 * - Made referrer option accept 'L' as a substitute for '§'
681 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
682 * Initial import of version 2.9.3 source tree
685 *********************************************************************/
692 #include <sys/types.h>
702 * Convince GNU's libc to provide a strptime prototype.
705 #endif /*__GLIBC__ */
712 #if !defined(_WIN32) && !defined(__OS2__)
718 #ifdef FEATURE_PTHREAD
720 /* jcc.h is for mutex semapores only */
721 #endif /* def FEATURE_PTHREAD */
727 #include "jbsockets.h"
728 #include "miscutil.h"
733 #ifndef HAVE_STRPTIME
734 #include "strptime.h"
737 const char parsers_h_rcs[] = PARSERS_H_VERSION;
739 /* Fix a problem with Solaris. There should be no effect on other
741 * Solaris's isspace() is a macro which uses its argument directly
742 * as an array index. Therefore we need to make sure that high-bit
743 * characters generate +ve values, and ideally we also want to make
744 * the argument match the declared parameter type of "int".
746 * Why did they write a character function that can't take a simple
747 * "char" argument? Doh!
749 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
750 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
752 static jb_err scan_headers(struct client_state *csp);
753 static jb_err header_tagger(struct client_state *csp, char *header);
754 static jb_err parse_header_time(const char *header_time, time_t *result);
756 static jb_err crumble (struct client_state *csp, char **header);
757 static jb_err connection (struct client_state *csp, char **header);
758 static jb_err filter_header (struct client_state *csp, char **header);
759 static jb_err client_referrer (struct client_state *csp, char **header);
760 static jb_err client_uagent (struct client_state *csp, char **header);
761 static jb_err client_ua (struct client_state *csp, char **header);
762 static jb_err client_from (struct client_state *csp, char **header);
763 static jb_err client_send_cookie (struct client_state *csp, char **header);
764 static jb_err client_x_forwarded (struct client_state *csp, char **header);
765 static jb_err client_accept_encoding (struct client_state *csp, char **header);
766 static jb_err client_te (struct client_state *csp, char **header);
767 static jb_err client_max_forwards (struct client_state *csp, char **header);
768 static jb_err client_host (struct client_state *csp, char **header);
769 static jb_err client_if_modified_since (struct client_state *csp, char **header);
770 static jb_err client_accept_language (struct client_state *csp, char **header);
771 static jb_err client_if_none_match (struct client_state *csp, char **header);
772 static jb_err crunch_client_header (struct client_state *csp, char **header);
773 static jb_err client_x_filter (struct client_state *csp, char **header);
774 static jb_err server_set_cookie (struct client_state *csp, char **header);
775 static jb_err server_content_type (struct client_state *csp, char **header);
776 static jb_err server_content_length (struct client_state *csp, char **header);
777 static jb_err server_content_md5 (struct client_state *csp, char **header);
778 static jb_err server_content_encoding (struct client_state *csp, char **header);
779 static jb_err server_transfer_coding (struct client_state *csp, char **header);
780 static jb_err server_http (struct client_state *csp, char **header);
781 static jb_err crunch_server_header (struct client_state *csp, char **header);
782 static jb_err server_last_modified (struct client_state *csp, char **header);
783 static jb_err server_content_disposition(struct client_state *csp, char **header);
785 static jb_err client_host_adder (struct client_state *csp);
786 static jb_err client_cookie_adder (struct client_state *csp);
787 static jb_err client_xtra_adder (struct client_state *csp);
788 static jb_err client_x_forwarded_adder(struct client_state *csp);
789 static jb_err connection_close_adder (struct client_state *csp);
791 const struct parsers client_patterns[] = {
792 { "referer:", 8, client_referrer },
793 { "user-agent:", 11, client_uagent },
794 { "ua-", 3, client_ua },
795 { "from:", 5, client_from },
796 { "cookie:", 7, client_send_cookie },
797 { "x-forwarded-for:", 16, client_x_forwarded },
798 { "Accept-Encoding:", 16, client_accept_encoding },
799 { "TE:", 3, client_te },
800 { "Host:", 5, client_host },
801 { "if-modified-since:", 18, client_if_modified_since },
802 { "Keep-Alive:", 11, crumble },
803 { "connection:", 11, connection },
804 { "proxy-connection:", 17, crumble },
805 { "max-forwards:", 13, client_max_forwards },
806 { "Accept-Language:", 16, client_accept_language },
807 { "if-none-match:", 14, client_if_none_match },
808 { "X-Filter:", 9, client_x_filter },
809 { "*", 0, crunch_client_header },
810 { "*", 0, filter_header },
814 const struct parsers server_patterns[] = {
815 { "HTTP", 4, server_http },
816 { "set-cookie:", 11, server_set_cookie },
817 { "connection:", 11, connection },
818 { "Content-Type:", 13, server_content_type },
819 { "Content-MD5:", 12, server_content_md5 },
820 { "Content-Encoding:", 17, server_content_encoding },
821 { "Transfer-Encoding:", 18, server_transfer_coding },
822 { "Keep-Alive:", 11, crumble },
823 { "content-disposition:", 20, server_content_disposition },
824 { "Last-Modified:", 14, server_last_modified },
825 { "*", 0, crunch_server_header },
826 { "*", 0, filter_header },
830 const struct parsers server_patterns_light[] = {
831 { "Content-Length:", 15, server_content_length },
832 { "Transfer-Encoding:", 18, server_transfer_coding },
834 { "Content-Encoding:", 17, server_content_encoding },
835 #endif /* def FEATURE_ZLIB */
839 const add_header_func_ptr add_client_headers[] = {
842 client_x_forwarded_adder,
844 /* Temporarily disabled: client_accept_encoding_adder, */
845 connection_close_adder,
850 const add_header_func_ptr add_server_headers[] = {
851 connection_close_adder,
855 /*********************************************************************
857 * Function : flush_socket
859 * Description : Write any pending "buffered" content.
862 * 1 : fd = file descriptor of the socket to read
863 * 2 : csp = Current client state (buffers, headers, etc...)
865 * Returns : On success, the number of bytes written are returned (zero
866 * indicates nothing was written). On error, -1 is returned,
867 * and errno is set appropriately. If count is zero and the
868 * file descriptor refers to a regular file, 0 will be
869 * returned without causing any other effect. For a special
870 * file, the results are not portable.
872 *********************************************************************/
873 int flush_socket(jb_socket fd, struct client_state *csp)
875 struct iob *iob = csp->iob;
876 int len = iob->eod - iob->cur;
883 if (write_socket(fd, iob->cur, (size_t)len))
887 iob->eod = iob->cur = iob->buf;
893 /*********************************************************************
895 * Function : add_to_iob
897 * Description : Add content to the buffered page, expanding the
898 * buffer if necessary.
901 * 1 : csp = Current client state (buffers, headers, etc...)
902 * 2 : buf = holds the content to be added to the page
903 * 3 : n = number of bytes to be added
905 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
906 * or buffer limit reached.
908 *********************************************************************/
909 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
911 struct iob *iob = csp->iob;
912 size_t used, offset, need, want;
915 if (n <= 0) return JB_ERR_OK;
917 used = (size_t)(iob->eod - iob->buf);
918 offset = (size_t)(iob->cur - iob->buf);
919 need = used + (size_t)n + 1;
922 * If the buffer can't hold the new data, extend it first.
923 * Use the next power of two if possible, else use the actual need.
925 if (need > csp->config->buffer_limit)
927 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
928 return JB_ERR_MEMORY;
931 if (need > iob->size)
933 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
935 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
939 else if (NULL != (p = (char *)realloc(iob->buf, need)))
945 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
946 return JB_ERR_MEMORY;
949 /* Update the iob pointers */
950 iob->cur = p + offset;
955 /* copy the new data into the iob buffer */
956 memcpy(iob->eod, buf, (size_t)n);
958 /* point to the end of the data */
961 /* null terminate == cheap insurance */
970 /*********************************************************************
972 * Function : decompress_iob
974 * Description : Decompress buffered page, expanding the
975 * buffer as necessary. csp->iob->cur
976 * should point to the the beginning of the
977 * compressed data block.
980 * 1 : csp = Current client state (buffers, headers, etc...)
982 * Returns : JB_ERR_OK on success,
983 * JB_ERR_MEMORY if out-of-memory limit reached, and
984 * JB_ERR_COMPRESS if error decompressing buffer.
986 *********************************************************************/
987 jb_err decompress_iob(struct client_state *csp)
989 char *buf; /* new, uncompressed buffer */
990 char *cur; /* Current iob position (to keep the original
991 * iob->cur unmodified if we return early) */
992 size_t bufsize; /* allocated size of the new buffer */
993 size_t old_size; /* Content size before decompression */
994 size_t skip_size; /* Number of bytes at the beginning of the iob
995 that we should NOT decompress. */
996 int status; /* return status of the inflate() call */
997 z_stream zstr; /* used by calls to zlib */
999 assert(csp->iob->cur - csp->iob->buf > 0);
1000 assert(csp->iob->eod - csp->iob->cur > 0);
1002 bufsize = csp->iob->size;
1003 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1004 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1006 cur = csp->iob->cur;
1011 * This is to protect the parsing of gzipped data,
1012 * but it should(?) be valid for deflated data also.
1014 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1015 return JB_ERR_COMPRESS;
1018 if (csp->content_type & CT_GZIP)
1021 * Our task is slightly complicated by the facts that data
1022 * compressed by gzip does not include a zlib header, and
1023 * that there is no easily accessible interface in zlib to
1024 * handle a gzip header. We strip off the gzip header by
1025 * hand, and later inform zlib not to expect a header.
1029 * Strip off the gzip header. Please see RFC 1952 for more
1030 * explanation of the appropriate fields.
1032 if ((*cur++ != (char)0x1f)
1033 || (*cur++ != (char)0x8b)
1034 || (*cur++ != Z_DEFLATED))
1036 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1037 return JB_ERR_COMPRESS;
1043 * XXX: These magic numbers should be replaced
1044 * with macros to give a better idea what they do.
1048 /* The gzip header has reserved bits set; bail out. */
1049 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1050 return JB_ERR_COMPRESS;
1054 /* Skip extra fields if necessary. */
1058 * Skip a given number of bytes, specified
1059 * as a 16-bit little-endian value.
1062 * XXX: This code used to be:
1064 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1066 * which I had to change into:
1068 * cur += *cur++ + (*cur++ << 8);
1070 * at which point gcc43 finally noticed that the value
1071 * of cur is undefined (it depends on which of the
1072 * summands is evaluated first).
1074 * I haven't come across a site where this
1075 * code is actually executed yet, but I hope
1079 skip_bytes = *cur++;
1080 skip_bytes = *cur++ << 8;
1082 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1085 * The number of bytes to skip should be positive
1086 * and we'd like to stay in the buffer.
1088 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1090 log_error (LOG_LEVEL_ERROR,
1091 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1093 return JB_ERR_COMPRESS;
1095 log_error (LOG_LEVEL_INFO,
1096 "Skipping %d bytes for gzip compression. Does this sound right?",
1101 /* Skip the filename if necessary. */
1104 /* A null-terminated string is supposed to follow. */
1105 while (*cur++ && (cur < csp->iob->eod));
1109 /* Skip the comment if necessary. */
1112 /* A null-terminated string is supposed to follow. */
1113 while (*cur++ && (cur < csp->iob->eod));
1116 /* Skip the CRC if necessary. */
1122 if (cur >= csp->iob->eod)
1125 * If the current position pointer reached or passed
1126 * the buffer end, we were obviously tricked to skip
1129 log_error (LOG_LEVEL_ERROR,
1130 "Malformed gzip header detected. Aborting decompression.");
1131 return JB_ERR_COMPRESS;
1135 else if (csp->content_type & CT_DEFLATE)
1138 * XXX: The debug level should be lowered
1139 * before the next stable release.
1141 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1143 * In theory (that is, according to RFC 1950), deflate-compressed
1144 * data should begin with a two-byte zlib header and have an
1145 * adler32 checksum at the end. It seems that in practice only
1146 * the raw compressed data is sent. Note that this means that
1147 * we are not RFC 1950-compliant here, but the advantage is that
1148 * this actually works. :)
1150 * We add a dummy null byte to tell zlib where the data ends,
1151 * and later inform it not to expect a header.
1153 * Fortunately, add_to_iob() has thoughtfully null-terminated
1154 * the buffer; we can just increment the end pointer to include
1161 log_error (LOG_LEVEL_ERROR,
1162 "Unable to determine compression format for decompression");
1163 return JB_ERR_COMPRESS;
1166 /* Set up the fields required by zlib. */
1167 zstr.next_in = (Bytef *)cur;
1168 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1169 zstr.zalloc = Z_NULL;
1170 zstr.zfree = Z_NULL;
1171 zstr.opaque = Z_NULL;
1174 * Passing -MAX_WBITS to inflateInit2 tells the library
1175 * that there is no zlib header.
1177 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1179 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1180 return JB_ERR_COMPRESS;
1184 * Next, we allocate new storage for the inflated data.
1185 * We don't modify the existing iob yet, so in case there
1186 * is error in decompression we can recover gracefully.
1188 buf = zalloc (bufsize);
1191 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1192 return JB_ERR_MEMORY;
1195 assert(bufsize >= skip_size);
1196 memcpy(buf, csp->iob->buf, skip_size);
1197 zstr.avail_out = bufsize - skip_size;
1198 zstr.next_out = (Bytef *)buf + skip_size;
1200 /* Try to decompress the whole stream in one shot. */
1201 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1203 /* We need to allocate more memory for the output buffer. */
1205 char *tmpbuf; /* used for realloc'ing the buffer */
1206 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1209 * If zlib wants more data then there's a problem, because
1210 * the complete compressed file should have been buffered.
1212 if (0 == zstr.avail_in)
1214 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1215 return JB_ERR_COMPRESS;
1219 * If we tried the limit and still didn't have enough
1220 * memory, just give up.
1222 if (bufsize == csp->config->buffer_limit)
1224 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1225 return JB_ERR_MEMORY;
1228 /* Try doubling the buffer size each time. */
1231 /* Don't exceed the buffer limit. */
1232 if (bufsize > csp->config->buffer_limit)
1234 bufsize = csp->config->buffer_limit;
1237 /* Try to allocate the new buffer. */
1238 tmpbuf = realloc(buf, bufsize);
1241 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1243 return JB_ERR_MEMORY;
1247 char *oldnext_out = (char *)zstr.next_out;
1250 * Update the fields for inflate() to use the new
1251 * buffer, which may be in a location different from
1254 zstr.avail_out += bufsize - oldbufsize;
1255 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1258 * Compare with an uglier method of calculating these values
1259 * that doesn't require the extra oldbufsize variable.
1261 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1262 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1263 assert(zstr.avail_out > 0);
1269 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1271 log_error(LOG_LEVEL_ERROR,
1272 "Inconsistent stream state after decompression: %s", zstr.msg);
1274 * XXX: Intentionally no return.
1276 * According to zlib.h, Z_STREAM_ERROR is returned
1277 * "if the stream state was inconsistent".
1279 * I assume in this case inflate()'s status
1280 * would also be something different than Z_STREAM_END
1281 * so this check should be redundant, but lets see.
1285 if (status != Z_STREAM_END)
1287 /* We failed to decompress the stream. */
1288 log_error(LOG_LEVEL_ERROR,
1289 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1290 return JB_ERR_COMPRESS;
1294 * Finally, we can actually update the iob, since the
1295 * decompression was successful. First, free the old
1298 freez(csp->iob->buf);
1300 /* Now, update the iob to use the new buffer. */
1301 csp->iob->buf = buf;
1302 csp->iob->cur = csp->iob->buf + skip_size;
1303 csp->iob->eod = (char *)zstr.next_out;
1304 csp->iob->size = bufsize;
1307 * Make sure the new uncompressed iob obeys some minimal
1308 * consistency conditions.
1310 if ((csp->iob->buf < csp->iob->cur)
1311 && (csp->iob->cur <= csp->iob->eod)
1312 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1314 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1317 log_error(LOG_LEVEL_RE_FILTER,
1318 "Decompression successful. Old size: %d, new size: %d.",
1319 old_size, new_size);
1323 /* zlib thinks this is OK, so lets do the same. */
1324 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1329 /* It seems that zlib did something weird. */
1330 log_error(LOG_LEVEL_ERROR,
1331 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1332 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1333 csp->iob->eod, csp->iob->buf + csp->iob->size);
1334 return JB_ERR_COMPRESS;
1340 #endif /* defined(FEATURE_ZLIB) */
1343 /*********************************************************************
1345 * Function : get_header
1347 * Description : This (odd) routine will parse the csp->iob
1350 * 1 : csp = Current client state (buffers, headers, etc...)
1352 * Returns : Any one of the following:
1354 * 1) a pointer to a dynamically allocated string that contains a header line
1355 * 2) NULL indicating that the end of the header was reached
1356 * 3) "" indicating that the end of the iob was reached before finding
1357 * a complete header line.
1359 *********************************************************************/
1360 char *get_header(struct client_state *csp)
1366 if ((iob->cur == NULL)
1367 || ((p = strchr(iob->cur, '\n')) == NULL))
1369 return(""); /* couldn't find a complete header */
1374 ret = strdup(iob->cur);
1377 /* FIXME No way to handle error properly */
1378 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1383 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1385 /* is this a blank line (i.e. the end of the header) ? */
1397 /*********************************************************************
1399 * Function : get_header_value
1401 * Description : Get the value of a given header from a chained list
1402 * of header lines or return NULL if no such header is
1403 * present in the list.
1406 * 1 : header_list = pointer to list
1407 * 2 : header_name = string with name of header to look for.
1408 * Trailing colon required, capitalization
1411 * Returns : NULL if not found, else value of header
1413 *********************************************************************/
1414 char *get_header_value(const struct list *header_list, const char *header_name)
1416 struct list_entry *cur_entry;
1420 assert(header_list);
1421 assert(header_name);
1422 length = strlen(header_name);
1424 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1428 if (!strncmpic(cur_entry->str, header_name, length))
1431 * Found: return pointer to start of value
1433 ret = (char *) (cur_entry->str + length);
1434 while (*ret && ijb_isspace(*ret)) ret++;
1448 /*********************************************************************
1450 * Function : scan_headers
1452 * Description : Scans headers, applies tags and updates action bits.
1455 * 1 : csp = Current client state (buffers, headers, etc...)
1457 * Returns : JB_ERR_OK
1459 *********************************************************************/
1460 static jb_err scan_headers(struct client_state *csp)
1462 struct list_entry *h; /* Header */
1463 jb_err err = JB_ERR_OK;
1465 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1467 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1469 /* Header crunch()ed in previous run? -> ignore */
1470 if (h->str == NULL) continue;
1471 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1472 err = header_tagger(csp, h->str);
1479 /*********************************************************************
1483 * Description : add, delete or modify lines in the HTTP header streams.
1484 * On entry, it receives a linked list of headers space
1485 * that was allocated dynamically (both the list nodes
1486 * and the header contents).
1488 * As a side effect it frees the space used by the original
1492 * 1 : pats = list of patterns to match against headers
1493 * 2 : more_headers = list of functions to add more
1494 * headers (client or server)
1495 * 3 : csp = Current client state (buffers, headers, etc...)
1497 * Returns : JB_ERR_OK in case off success, or
1498 * JB_ERR_MEMORY on out-of-memory error.
1500 *********************************************************************/
1501 jb_err sed(const struct parsers pats[],
1502 const add_header_func_ptr more_headers[],
1503 struct client_state *csp)
1505 struct list_entry *p;
1506 const struct parsers *v;
1507 const add_header_func_ptr *f;
1508 jb_err err = JB_ERR_OK;
1512 * If filtering is enabled, sed is run twice,
1513 * but most of the work needs to be done only once.
1515 first_run = (more_headers != NULL ) ? 1 : 0;
1517 if (first_run) /* Parse and print */
1521 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1523 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1525 /* Header crunch()ed in previous run? -> ignore */
1526 if (p->str == NULL) continue;
1528 /* Does the current parser handle this header? */
1529 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1531 err = v->parser(csp, (char **)&(p->str));
1535 /* place any additional headers on the csp->headers list */
1536 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1541 else /* Parse only */
1544 * The second run is only needed if the body was modified
1545 * and the content-lenght has changed.
1547 if (strncmpic(csp->http->cmd, "HEAD", 4))
1549 /*XXX: Code duplication */
1550 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1552 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1554 /* Header crunch()ed in previous run? -> ignore */
1555 if (p->str == NULL) continue;
1557 /* Does the current parser handle this header? */
1558 if (strncmpic(p->str, v->str, v->len) == 0)
1560 err = v->parser(csp, (char **)&(p->str));
1572 /*********************************************************************
1574 * Function : header_tagger
1576 * Description : Executes all text substitutions from applying
1577 * tag actions and saves the result as tag.
1579 * XXX: Shares enough code with filter_header() and
1580 * pcrs_filter_response() to warrant some helper functions.
1583 * 1 : csp = Current client state (buffers, headers, etc...)
1584 * 2 : header = Header that is used as tagger input
1586 * Returns : JB_ERR_OK on success and always succeeds
1588 *********************************************************************/
1589 static jb_err header_tagger(struct client_state *csp, char *header)
1591 int wanted_filter_type;
1592 int multi_action_index;
1596 struct file_list *fl;
1597 struct re_filterfile_spec *b;
1598 struct list_entry *tag_name;
1600 int found_filters = 0;
1601 const size_t header_length = strlen(header);
1603 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1605 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1606 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1610 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1611 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1614 /* Check if there are any filters */
1615 for (i = 0; i < MAX_AF_FILES; i++)
1628 if (0 == found_filters)
1630 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1634 for (i = 0; i < MAX_AF_FILES; i++)
1637 if ((NULL == fl) || (NULL == fl->f))
1640 * Either there are no filter files
1641 * left, or this filter file just
1642 * contains no valid filters.
1644 * Continue to be sure we don't miss
1645 * valid filter files that are chained
1646 * after empty or invalid ones.
1651 /* For all filters, */
1652 for (b = fl->f; b; b = b->next)
1654 if (b->type != wanted_filter_type)
1656 /* skip the ones we don't care about, */
1659 /* leaving only taggers that could apply, of which we use the ones, */
1660 for (tag_name = csp->action->multi[multi_action_index]->first;
1661 NULL != tag_name; tag_name = tag_name->next)
1663 /* that do apply, and */
1664 if (strcmp(b->name, tag_name->str) == 0)
1666 char *modified_tag = NULL;
1668 size_t size = header_length;
1669 pcrs_job *joblist = b->joblist;
1671 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1673 if (NULL == joblist)
1675 log_error(LOG_LEVEL_RE_FILTER,
1676 "Tagger %s has empty joblist. Nothing to do.", b->name);
1680 /* execute their pcrs_joblist on the header. */
1681 for (job = joblist; NULL != job; job = job->next)
1683 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1687 /* Success, continue with the modified version. */
1696 /* Tagger doesn't match */
1699 /* Regex failure, log it but continue anyway. */
1700 log_error(LOG_LEVEL_ERROR,
1701 "Problems with tagger \'%s\' and header \'%s\': %s",
1702 b->name, *header, pcrs_strerror(hits));
1704 freez(modified_tag);
1708 if (b->dynamic) pcrs_free_joblist(joblist);
1710 /* If this tagger matched */
1716 * There is to technical limitation which makes
1717 * it impossible to use empty tags, but I assume
1718 * no one would do it intentionally.
1721 log_error(LOG_LEVEL_INFO,
1722 "Tagger \'%s\' created an empty tag. Ignored.",
1727 if (!list_contains_item(csp->tags, tag))
1729 if (JB_ERR_OK != enlist(csp->tags, tag))
1731 log_error(LOG_LEVEL_ERROR,
1732 "Insufficient memory to add tag \'%s\', "
1733 "based on tagger \'%s\' and header \'%s\'",
1734 tag, b->name, *header);
1738 char *action_message;
1740 * update the action bits right away, to make
1741 * tagging based on tags set by earlier taggers
1742 * of the same kind possible.
1744 if (update_action_bits_for_tag(csp, tag))
1746 action_message = "Action bits updated accordingly.";
1750 action_message = "No action bits update necessary.";
1753 log_error(LOG_LEVEL_HEADER,
1754 "Tagger \'%s\' added tag \'%s\'. %s",
1755 b->name, tag, action_message);
1760 /* XXX: Is this log-worthy? */
1761 log_error(LOG_LEVEL_HEADER,
1762 "Tagger \'%s\' didn't add tag \'%s\'. "
1763 "Tag already present", b->name, tag);
1766 } /* if the tagger matched */
1767 } /* if the tagger applies */
1768 } /* for every tagger that could apply */
1769 } /* for all filters */
1770 } /* for all filter files */
1775 /* here begins the family of parser functions that reformat header lines */
1777 /*********************************************************************
1779 * Function : filter_header
1781 * Description : Executes all text substitutions from all applying
1782 * +(server|client)-header-filter actions on the header.
1783 * Most of the code was copied from pcrs_filter_response,
1784 * including the rather short variable names
1787 * 1 : csp = Current client state (buffers, headers, etc...)
1788 * 2 : header = On input, pointer to header to modify.
1789 * On output, pointer to the modified header, or NULL
1790 * to remove the header. This function frees the
1791 * original string if necessary.
1793 * Returns : JB_ERR_OK on success and always succeeds
1795 *********************************************************************/
1796 static jb_err filter_header(struct client_state *csp, char **header)
1800 size_t size = strlen(*header);
1802 char *newheader = NULL;
1805 struct file_list *fl;
1806 struct re_filterfile_spec *b;
1807 struct list_entry *filtername;
1809 int i, found_filters = 0;
1810 int wanted_filter_type;
1811 int multi_action_index;
1813 if (csp->flags & CSP_FLAG_NO_FILTERING)
1818 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1820 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1821 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1825 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1826 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1830 * Need to check the set of re_filterfiles...
1832 for (i = 0; i < MAX_AF_FILES; i++)
1845 if (0 == found_filters)
1847 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1851 for (i = 0; i < MAX_AF_FILES; i++)
1854 if ((NULL == fl) || (NULL == fl->f))
1857 * Either there are no filter files
1858 * left, or this filter file just
1859 * contains no valid filters.
1861 * Continue to be sure we don't miss
1862 * valid filter files that are chained
1863 * after empty or invalid ones.
1868 * For all applying +filter actions, look if a filter by that
1869 * name exists and if yes, execute its pcrs_joblist on the
1872 for (b = fl->f; b; b = b->next)
1874 if (b->type != wanted_filter_type)
1876 /* Skip other filter types */
1880 for (filtername = csp->action->multi[multi_action_index]->first;
1881 filtername ; filtername = filtername->next)
1883 if (strcmp(b->name, filtername->str) == 0)
1885 int current_hits = 0;
1886 pcrs_job *joblist = b->joblist;
1888 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1890 if (NULL == joblist)
1892 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1896 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1897 *header, size, b->name);
1899 /* Apply all jobs from the joblist */
1900 for (job = joblist; NULL != job; job = job->next)
1902 matches = pcrs_execute(job, *header, size, &newheader, &size);
1905 current_hits += matches;
1906 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1908 *header = newheader;
1910 else if ( 0 == matches )
1912 /* Filter doesn't change header */
1918 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1919 *header, b->name, pcrs_strerror(matches));
1920 if( newheader != NULL)
1922 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1928 if (b->dynamic) pcrs_free_joblist(joblist);
1930 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1931 hits += current_hits;
1938 * Additionally checking for hits is important because if
1939 * the continue hack is triggered, server headers can
1940 * arrive empty to separate multiple heads from each other.
1942 if ((0 == size) && hits)
1944 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1952 /*********************************************************************
1954 * Function : connection
1956 * Description : Makes sure that the value of the Connection: header
1957 * is "close" and signals connection_close_adder
1961 * 1 : csp = Current client state (buffers, headers, etc...)
1962 * 2 : header = On input, pointer to header to modify.
1963 * On output, pointer to the modified header, or NULL
1964 * to remove the header. This function frees the
1965 * original string if necessary.
1967 * Returns : JB_ERR_OK on success, or
1968 * JB_ERR_MEMORY on out-of-memory error.
1970 *********************************************************************/
1971 static jb_err connection(struct client_state *csp, char **header)
1973 char *old_header = *header;
1975 /* Do we have a 'Connection: close' header? */
1976 if (strcmpic(*header, "Connection: close"))
1978 /* No, create one */
1979 *header = strdup("Connection: close");
1982 return JB_ERR_MEMORY;
1984 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1988 /* Signal connection_close_adder() to return early. */
1989 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1991 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
1995 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2002 /*********************************************************************
2004 * Function : crumble
2006 * Description : This is called if a header matches a pattern to "crunch"
2009 * 1 : csp = Current client state (buffers, headers, etc...)
2010 * 2 : header = On input, pointer to header to modify.
2011 * On output, pointer to the modified header, or NULL
2012 * to remove the header. This function frees the
2013 * original string if necessary.
2015 * Returns : JB_ERR_OK on success, or
2016 * JB_ERR_MEMORY on out-of-memory error.
2018 *********************************************************************/
2019 static jb_err crumble(struct client_state *csp, char **header)
2021 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2026 /*********************************************************************
2028 * Function : crunch_server_header
2030 * Description : Crunch server header if it matches a string supplied by the
2031 * user. Called from `sed'.
2034 * 1 : csp = Current client state (buffers, headers, etc...)
2035 * 2 : header = On input, pointer to header to modify.
2036 * On output, pointer to the modified header, or NULL
2037 * to remove the header. This function frees the
2038 * original string if necessary.
2040 * Returns : JB_ERR_OK on success and always succeeds
2042 *********************************************************************/
2043 static jb_err crunch_server_header(struct client_state *csp, char **header)
2045 const char *crunch_pattern;
2047 /* Do we feel like crunching? */
2048 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2050 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2052 /* Is the current header the lucky one? */
2053 if (strstr(*header, crunch_pattern))
2055 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2064 /*********************************************************************
2066 * Function : server_content_type
2068 * Description : Set the content-type for filterable types (text/.*,
2069 * .*xml.*, javascript and image/gif) unless filtering has been
2070 * forbidden (CT_TABOO) while parsing earlier headers.
2071 * NOTE: Since text/plain is commonly used by web servers
2072 * for files whose correct type is unknown, we don't
2073 * set CT_TEXT for it.
2076 * 1 : csp = Current client state (buffers, headers, etc...)
2077 * 2 : header = On input, pointer to header to modify.
2078 * On output, pointer to the modified header, or NULL
2079 * to remove the header. This function frees the
2080 * original string if necessary.
2082 * Returns : JB_ERR_OK on success, or
2083 * JB_ERR_MEMORY on out-of-memory error.
2085 *********************************************************************/
2086 static jb_err server_content_type(struct client_state *csp, char **header)
2088 /* Remove header if it isn't the first Content-Type header */
2089 if ((csp->content_type & CT_DECLARED))
2092 * Another, slightly slower, way to see if
2093 * we already parsed another Content-Type header.
2095 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2097 log_error(LOG_LEVEL_ERROR,
2098 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2106 * Signal that the Content-Type has been set.
2108 csp->content_type |= CT_DECLARED;
2110 if (!(csp->content_type & CT_TABOO))
2112 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2113 || strstr(*header, "xml")
2114 || strstr(*header, "application/x-javascript"))
2116 csp->content_type |= CT_TEXT;
2118 else if (strstr(*header, " image/gif"))
2120 csp->content_type |= CT_GIF;
2122 else if (strstr(*header, " image/jpeg"))
2124 csp->content_type |= CT_JPEG;
2129 * Are we messing with the content type?
2131 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2134 * Make sure the user doesn't accidently
2135 * change the content type of binary documents.
2137 if (csp->content_type & CT_TEXT)
2140 *header = strdup("Content-Type: ");
2141 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2145 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2146 return JB_ERR_MEMORY;
2148 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2152 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2153 "Enable force-text-mode if you know what you're doing.", *header);
2161 /*********************************************************************
2163 * Function : server_transfer_coding
2165 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2166 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2167 * - Remove header if body was chunked but has been
2168 * de-chunked for filtering.
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 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2184 * Turn off pcrs and gif filtering if body compressed
2186 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2190 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2192 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2193 csp->http->cmd, *header);
2194 #endif /* def FEATURE_ZLIB */
2195 csp->content_type = CT_TABOO;
2199 * Raise flag if body chunked
2201 if (strstr(*header, "chunked"))
2203 csp->flags |= CSP_FLAG_CHUNKED;
2206 * If the body was modified, it has been de-chunked first
2207 * and the header must be removed.
2209 * FIXME: If there is more than one transfer encoding,
2210 * only the "chunked" part should be removed here.
2212 if (csp->flags & CSP_FLAG_MODIFIED)
2214 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2223 /*********************************************************************
2225 * Function : server_content_encoding
2227 * Description : This function is run twice for each request,
2228 * unless FEATURE_ZLIB and filtering are disabled.
2230 * The first run is used to check if the content
2231 * is compressed, if FEATURE_ZLIB is disabled
2232 * filtering is then disabled as well, if FEATURE_ZLIB
2233 * is enabled the content is marked for decompression.
2235 * The second run is used to remove the Content-Encoding
2236 * header if the decompression was successful.
2239 * 1 : csp = Current client state (buffers, headers, etc...)
2240 * 2 : header = On input, pointer to header to modify.
2241 * On output, pointer to the modified header, or NULL
2242 * to remove the header. This function frees the
2243 * original string if necessary.
2245 * Returns : JB_ERR_OK on success, or
2246 * JB_ERR_MEMORY on out-of-memory error.
2248 *********************************************************************/
2249 static jb_err server_content_encoding(struct client_state *csp, char **header)
2252 if ((csp->flags & CSP_FLAG_MODIFIED)
2253 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2256 * We successfully decompressed the content,
2257 * and have to clean the header now, so the
2258 * client no longer expects compressed data..
2260 * XXX: There is a difference between cleaning
2261 * and removing it completely.
2263 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2266 else if (strstr(*header, "gzip"))
2268 /* Mark for gzip decompression */
2269 csp->content_type |= CT_GZIP;
2271 else if (strstr(*header, "deflate"))
2273 /* Mark for zlib decompression */
2274 csp->content_type |= CT_DEFLATE;
2276 else if (strstr(*header, "compress"))
2279 * We can't decompress this; therefore we can't filter
2282 csp->content_type |= CT_TABOO;
2284 #else /* !defined(FEATURE_ZLIB) */
2285 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2288 * Body is compressed, turn off pcrs and gif filtering.
2290 csp->content_type |= CT_TABOO;
2293 * Log a warning if the user expects the content to be filtered.
2295 if ((csp->rlist != NULL) &&
2296 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2298 log_error(LOG_LEVEL_INFO,
2299 "Compressed content detected, content filtering disabled. "
2300 "Consider recompiling Privoxy with zlib support or "
2301 "enable the prevent-compression action.");
2304 #endif /* defined(FEATURE_ZLIB) */
2311 /*********************************************************************
2313 * Function : server_content_length
2315 * Description : Adjust Content-Length header if we modified
2319 * 1 : csp = Current client state (buffers, headers, etc...)
2320 * 2 : header = On input, pointer to header to modify.
2321 * On output, pointer to the modified header, or NULL
2322 * to remove the header. This function frees the
2323 * original string if necessary.
2325 * Returns : JB_ERR_OK on success, or
2326 * JB_ERR_MEMORY on out-of-memory error.
2328 *********************************************************************/
2329 static jb_err server_content_length(struct client_state *csp, char **header)
2331 const size_t max_header_length = 80;
2333 /* Regenerate header if the content was modified. */
2334 if (csp->flags & CSP_FLAG_MODIFIED)
2337 *header = (char *) zalloc(max_header_length);
2338 if (*header == NULL)
2340 return JB_ERR_MEMORY;
2343 snprintf(*header, max_header_length, "Content-Length: %d",
2344 (int)csp->content_length);
2345 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2346 (int)csp->content_length);
2353 /*********************************************************************
2355 * Function : server_content_md5
2357 * Description : Crumble any Content-MD5 headers if the document was
2358 * modified. FIXME: Should we re-compute instead?
2361 * 1 : csp = Current client state (buffers, headers, etc...)
2362 * 2 : header = On input, pointer to header to modify.
2363 * On output, pointer to the modified header, or NULL
2364 * to remove the header. This function frees the
2365 * original string if necessary.
2367 * Returns : JB_ERR_OK on success, or
2368 * JB_ERR_MEMORY on out-of-memory error.
2370 *********************************************************************/
2371 static jb_err server_content_md5(struct client_state *csp, char **header)
2373 if (csp->flags & CSP_FLAG_MODIFIED)
2375 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2382 /*********************************************************************
2384 * Function : server_content_disposition
2386 * Description : If enabled, blocks or modifies the "content-disposition" header.
2387 * Called from `sed'.
2390 * 1 : csp = Current client state (buffers, headers, etc...)
2391 * 2 : header = On input, pointer to header to modify.
2392 * On output, pointer to the modified header, or NULL
2393 * to remove the header. This function frees the
2394 * original string if necessary.
2396 * Returns : JB_ERR_OK on success, or
2397 * JB_ERR_MEMORY on out-of-memory error.
2399 *********************************************************************/
2400 static jb_err server_content_disposition(struct client_state *csp, char **header)
2405 * Are we messing with the content-disposition header?
2407 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2413 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2415 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2418 * Blocking content-disposition header
2420 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2427 * Replacing content-disposition header
2430 *header = strdup("content-disposition: ");
2431 string_append(header, newval);
2433 if (*header == NULL)
2435 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2439 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2442 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2445 /*********************************************************************
2447 * Function : server_last_modified
2449 * Description : Changes Last-Modified header to the actual date
2450 * to help hide-if-modified-since.
2451 * Called from `sed'.
2454 * 1 : csp = Current client state (buffers, headers, etc...)
2455 * 2 : header = On input, pointer to header to modify.
2456 * On output, pointer to the modified header, or NULL
2457 * to remove the header. This function frees the
2458 * original string if necessary.
2460 * Returns : JB_ERR_OK on success, or
2461 * JB_ERR_MEMORY on out-of-memory error.
2463 *********************************************************************/
2464 static jb_err server_last_modified(struct client_state *csp, char **header)
2467 char buf[BUFFER_SIZE];
2470 #ifdef HAVE_GMTIME_R
2473 struct tm *timeptr = NULL;
2474 time_t now, last_modified;
2476 long int days, hours, minutes, seconds;
2479 * Are we messing with the Last-Modified header?
2481 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2487 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2489 if (0 == strcmpic(newval, "block") )
2492 * Blocking Last-Modified header. Useless but why not.
2494 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2498 else if (0 == strcmpic(newval, "reset-to-request-time"))
2501 * Setting Last-Modified Header to now.
2503 get_http_time(0, buf);
2505 *header = strdup("Last-Modified: ");
2506 string_append(header, buf);
2508 if (*header == NULL)
2510 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2514 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2517 else if (0 == strcmpic(newval, "randomize"))
2519 const char *header_time = *header + sizeof("Last-Modified:");
2521 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2523 #ifdef HAVE_GMTIME_R
2524 timeptr = gmtime_r(&now, &gmt);
2525 #elif FEATURE_PTHREAD
2526 pthread_mutex_lock(&gmtime_mutex);
2527 timeptr = gmtime(&now);
2528 pthread_mutex_unlock(&gmtime_mutex);
2530 timeptr = gmtime(&now);
2532 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2534 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2539 rtime = (long int)difftime(now, last_modified);
2542 rtime = pick_from_range(rtime);
2543 last_modified += rtime;
2544 #ifdef HAVE_GMTIME_R
2545 timeptr = gmtime_r(&last_modified, &gmt);
2546 #elif FEATURE_PTHREAD
2547 pthread_mutex_lock(&gmtime_mutex);
2548 timeptr = gmtime(&last_modified);
2549 pthread_mutex_unlock(&gmtime_mutex);
2551 timeptr = gmtime(&last_modified);
2553 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2555 *header = strdup("Last-Modified: ");
2556 string_append(header, newheader);
2558 if (*header == NULL)
2560 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2561 return JB_ERR_MEMORY;
2564 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2566 days = rtime / (3600 * 24);
2567 hours = rtime / 3600 % 24;
2568 minutes = rtime / 60 % 60;
2569 seconds = rtime % 60;
2571 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2572 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2573 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2578 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2587 /*********************************************************************
2589 * Function : client_accept_encoding
2591 * Description : Rewrite the client's Accept-Encoding header so that
2592 * if doesn't allow compression, if the action applies.
2593 * Note: For HTTP/1.0 the absence of the header is enough.
2596 * 1 : csp = Current client state (buffers, headers, etc...)
2597 * 2 : header = On input, pointer to header to modify.
2598 * On output, pointer to the modified header, or NULL
2599 * to remove the header. This function frees the
2600 * original string if necessary.
2602 * Returns : JB_ERR_OK on success, or
2603 * JB_ERR_MEMORY on out-of-memory error.
2605 *********************************************************************/
2606 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2608 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2610 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2614 /* Temporarily disable the correct behaviour to
2615 * work around a PHP bug.
2617 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2619 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2620 * if (*header == NULL)
2622 * return JB_ERR_MEMORY;
2633 /*********************************************************************
2635 * Function : client_te
2637 * Description : Rewrite the client's TE header so that
2638 * if doesn't allow compression, if the action applies.
2641 * 1 : csp = Current client state (buffers, headers, etc...)
2642 * 2 : header = On input, pointer to header to modify.
2643 * On output, pointer to the modified header, or NULL
2644 * to remove the header. This function frees the
2645 * original string if necessary.
2647 * Returns : JB_ERR_OK on success, or
2648 * JB_ERR_MEMORY on out-of-memory error.
2650 *********************************************************************/
2651 static jb_err client_te(struct client_state *csp, char **header)
2653 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2656 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2662 /*********************************************************************
2664 * Function : client_referrer
2666 * Description : Handle the "referer" config setting properly.
2667 * Called from `sed'.
2670 * 1 : csp = Current client state (buffers, headers, etc...)
2671 * 2 : header = On input, pointer to header to modify.
2672 * On output, pointer to the modified header, or NULL
2673 * to remove the header. This function frees the
2674 * original string if necessary.
2676 * Returns : JB_ERR_OK on success, or
2677 * JB_ERR_MEMORY on out-of-memory error.
2679 *********************************************************************/
2680 static jb_err client_referrer(struct client_state *csp, char **header)
2687 #ifdef FEATURE_FORCE_LOAD
2688 /* Since the referrer can include the prefix even
2689 * if the request itself is non-forced, we must
2690 * clean it unconditionally
2692 strclean(*header, FORCE_PREFIX);
2693 #endif /* def FEATURE_FORCE_LOAD */
2696 * Are we sending referer?
2698 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2703 newval = csp->action->string[ACTION_STRING_REFERER];
2705 if ((0 != strcmpic(newval, "conditional-block")))
2709 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2714 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2717 else if (0 == strcmpic(newval, "conditional-block"))
2720 * Block referer if host has changed.
2723 if (NULL == (host = strdup(csp->http->hostport)))
2726 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2727 return JB_ERR_MEMORY;
2729 if (NULL == (referer = strdup(*header)))
2733 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2734 return JB_ERR_MEMORY;
2736 hostlenght = strlen(host);
2737 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2739 /*Shorten referer to make sure the referer is blocked
2740 *if www.example.org/www.example.com-shall-see-the-referer/
2741 *links to www.example.com/
2743 referer[hostlenght+17] = '\0';
2745 if ( 0 == strstr(referer, host)) /*Host has changed*/
2747 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2752 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2758 else if (0 != strcmpic(newval, "forge"))
2761 * We have a specific (fixed) referer we want to send.
2763 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2765 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2767 *header = strdup("Referer: ");
2768 string_append(header, newval);
2769 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2771 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2776 * Forge a referer as http://[hostname:port of REQUEST]/
2777 * to fool stupid checks for in-site links
2780 *header = strdup("Referer: http://");
2781 string_append(header, csp->http->hostport);
2782 string_append(header, "/");
2783 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2785 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2789 /*********************************************************************
2791 * Function : client_accept_language
2793 * Description : Handle the "Accept-Language" config setting properly.
2794 * Called from `sed'.
2797 * 1 : csp = Current client state (buffers, headers, etc...)
2798 * 2 : header = On input, pointer to header to modify.
2799 * On output, pointer to the modified header, or NULL
2800 * to remove the header. This function frees the
2801 * original string if necessary.
2803 * Returns : JB_ERR_OK on success, or
2804 * JB_ERR_MEMORY on out-of-memory error.
2806 *********************************************************************/
2807 static jb_err client_accept_language(struct client_state *csp, char **header)
2812 * Are we messing with the Accept-Language?
2814 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2816 /*I don't think so*/
2820 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2822 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2825 * Blocking Accept-Language header
2827 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2834 * Replacing Accept-Language header
2837 *header = strdup("Accept-Language: ");
2838 string_append(header, newval);
2840 if (*header == NULL)
2842 log_error(LOG_LEVEL_ERROR,
2843 "Insufficent memory. Accept-Language header crunched without replacement.");
2847 log_error(LOG_LEVEL_HEADER,
2848 "Accept-Language header crunched and replaced with: %s", *header);
2851 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2855 /*********************************************************************
2857 * Function : crunch_client_header
2859 * Description : Crunch client header if it matches a string supplied by the
2860 * user. Called from `sed'.
2863 * 1 : csp = Current client state (buffers, headers, etc...)
2864 * 2 : header = On input, pointer to header to modify.
2865 * On output, pointer to the modified header, or NULL
2866 * to remove the header. This function frees the
2867 * original string if necessary.
2869 * Returns : JB_ERR_OK on success and always succeeds
2871 *********************************************************************/
2872 static jb_err crunch_client_header(struct client_state *csp, char **header)
2874 const char *crunch_pattern;
2876 /* Do we feel like crunching? */
2877 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2879 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2881 /* Is the current header the lucky one? */
2882 if (strstr(*header, crunch_pattern))
2884 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2892 /*********************************************************************
2894 * Function : client_uagent
2896 * Description : Handle the "user-agent" config setting properly
2897 * and remember its original value to enable browser
2898 * bug workarounds. Called from `sed'.
2901 * 1 : csp = Current client state (buffers, headers, etc...)
2902 * 2 : header = On input, pointer to header to modify.
2903 * On output, pointer to the modified header, or NULL
2904 * to remove the header. This function frees the
2905 * original string if necessary.
2907 * Returns : JB_ERR_OK on success, or
2908 * JB_ERR_MEMORY on out-of-memory error.
2910 *********************************************************************/
2911 static jb_err client_uagent(struct client_state *csp, char **header)
2915 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2920 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2927 *header = strdup("User-Agent: ");
2928 string_append(header, newval);
2930 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2932 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2935 /*********************************************************************
2937 * Function : client_ua
2939 * Description : Handle "ua-" headers properly. Called from `sed'.
2942 * 1 : csp = Current client state (buffers, headers, etc...)
2943 * 2 : header = On input, pointer to header to modify.
2944 * On output, pointer to the modified header, or NULL
2945 * to remove the header. This function frees the
2946 * original string if necessary.
2948 * Returns : JB_ERR_OK on success, or
2949 * JB_ERR_MEMORY on out-of-memory error.
2951 *********************************************************************/
2952 static jb_err client_ua(struct client_state *csp, char **header)
2954 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2956 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2964 /*********************************************************************
2966 * Function : client_from
2968 * Description : Handle the "from" config setting properly.
2969 * Called from `sed'.
2972 * 1 : csp = Current client state (buffers, headers, etc...)
2973 * 2 : header = On input, pointer to header to modify.
2974 * On output, pointer to the modified header, or NULL
2975 * to remove the header. This function frees the
2976 * original string if necessary.
2978 * Returns : JB_ERR_OK on success, or
2979 * JB_ERR_MEMORY on out-of-memory error.
2981 *********************************************************************/
2982 static jb_err client_from(struct client_state *csp, char **header)
2986 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2993 newval = csp->action->string[ACTION_STRING_FROM];
2996 * Are we blocking the e-mail address?
2998 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3000 log_error(LOG_LEVEL_HEADER, "crunched From!");
3004 log_error(LOG_LEVEL_HEADER, " modified");
3006 *header = strdup("From: ");
3007 string_append(header, newval);
3009 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3013 /*********************************************************************
3015 * Function : client_send_cookie
3017 * Description : Crunches the "cookie" header if necessary.
3018 * Called from `sed'.
3020 * XXX: Stupid name, doesn't send squat.
3023 * 1 : csp = Current client state (buffers, headers, etc...)
3024 * 2 : header = On input, pointer to header to modify.
3025 * On output, pointer to the modified header, or NULL
3026 * to remove the header. This function frees the
3027 * original string if necessary.
3029 * Returns : JB_ERR_OK on success, or
3030 * JB_ERR_MEMORY on out-of-memory error.
3032 *********************************************************************/
3033 static jb_err client_send_cookie(struct client_state *csp, char **header)
3035 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3037 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3045 /*********************************************************************
3047 * Function : client_x_forwarded
3049 * Description : Handle the "x-forwarded-for" config setting properly,
3050 * also used in the add_client_headers list. Called from `sed'.
3053 * 1 : csp = Current client state (buffers, headers, etc...)
3054 * 2 : header = On input, pointer to header to modify.
3055 * On output, pointer to the modified header, or NULL
3056 * to remove the header. This function frees the
3057 * original string if necessary.
3059 * Returns : JB_ERR_OK on success, or
3060 * JB_ERR_MEMORY on out-of-memory error.
3062 *********************************************************************/
3063 jb_err client_x_forwarded(struct client_state *csp, char **header)
3065 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3067 /* Save it so we can re-add it later */
3068 freez(csp->x_forwarded);
3069 csp->x_forwarded = *header;
3072 * Always set *header = NULL, since this information
3073 * will be sent at the end of the header.
3080 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3087 /*********************************************************************
3089 * Function : client_max_forwards
3091 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3092 * from the value of the Max-Forwards header field.
3095 * 1 : csp = Current client state (buffers, headers, etc...)
3096 * 2 : header = On input, pointer to header to modify.
3097 * On output, pointer to the modified header, or NULL
3098 * to remove the header. This function frees the
3099 * original string if necessary.
3101 * Returns : JB_ERR_OK on success, or
3102 * JB_ERR_MEMORY on out-of-memory error.
3104 *********************************************************************/
3105 static jb_err client_max_forwards(struct client_state *csp, char **header)
3109 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3110 (0 == strcmpic(csp->http->gpc, "options")))
3112 assert(*(*header+12) == ':');
3113 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3115 if (max_forwards > 0)
3117 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3118 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3119 csp->http->gpc, max_forwards);
3121 else if (max_forwards < 0)
3123 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3129 * Not supposed to be reached. direct_response() which
3130 * was already called earlier in chat() should have
3131 * intercepted the request.
3133 log_error(LOG_LEVEL_ERROR,
3134 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3135 assert(max_forwards != 0);
3140 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3149 /*********************************************************************
3151 * Function : client_host
3153 * Description : If the request URI did not contain host and
3154 * port information, parse and evaluate the Host
3157 * Also, kill ill-formed HOST: headers as sent by
3158 * Apple's iTunes software when used with a proxy.
3161 * 1 : csp = Current client state (buffers, headers, etc...)
3162 * 2 : header = On input, pointer to header to modify.
3163 * On output, pointer to the modified header, or NULL
3164 * to remove the header. This function frees the
3165 * original string if necessary.
3167 * Returns : JB_ERR_OK on success, or
3168 * JB_ERR_MEMORY on out-of-memory error.
3170 *********************************************************************/
3171 static jb_err client_host(struct client_state *csp, char **header)
3176 * If the header field name is all upper-case, chances are that it's
3177 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3178 * not a problem -- they are regenerated later.
3180 if ((*header)[1] == 'O')
3182 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3187 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3188 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3191 if (NULL == (p = strdup((*header)+6)))
3193 return JB_ERR_MEMORY;
3196 if (NULL == (q = strdup(p)))
3199 return JB_ERR_MEMORY;
3202 freez(csp->http->hostport);
3203 csp->http->hostport = p;
3204 freez(csp->http->host);
3205 csp->http->host = q;
3206 q = strchr(csp->http->host, ':');
3209 /* Terminate hostname and evaluate port string */
3211 csp->http->port = atoi(q);
3215 csp->http->port = csp->http->ssl ? 443 : 80;
3218 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3219 csp->http->hostport, csp->http->host, csp->http->port);
3222 /* Signal client_host_adder() to return right away */
3223 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3228 /*********************************************************************
3230 * Function : client_if_modified_since
3232 * Description : Remove or modify the If-Modified-Since header.
3235 * 1 : csp = Current client state (buffers, headers, etc...)
3236 * 2 : header = On input, pointer to header to modify.
3237 * On output, pointer to the modified header, or NULL
3238 * to remove the header. This function frees the
3239 * original string if necessary.
3241 * Returns : JB_ERR_OK on success, or
3242 * JB_ERR_MEMORY on out-of-memory error.
3244 *********************************************************************/
3245 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3248 #ifdef HAVE_GMTIME_R
3251 struct tm *timeptr = NULL;
3255 long int hours, minutes, seconds;
3259 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3262 * The client got an error message because of a temporary problem,
3263 * the problem is gone and the client now tries to revalidate our
3264 * error message on the real server. The revalidation would always
3265 * end with the transmission of the whole document and there is
3266 * no need to expose the bogus If-Modified-Since header.
3268 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3271 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3273 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3275 if ((0 == strcmpic(newval, "block")))
3277 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3280 else /* add random value */
3282 const char *header_time = *header + sizeof("If-Modified-Since:");
3284 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3286 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3291 rtime = strtol(newval, &endptr, 0);
3294 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3295 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3302 rtime = pick_from_range(rtime);
3306 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3309 tm += rtime * (negative ? -1 : 1);
3310 #ifdef HAVE_GMTIME_R
3311 timeptr = gmtime_r(&tm, &gmt);
3312 #elif FEATURE_PTHREAD
3313 pthread_mutex_lock(&gmtime_mutex);
3314 timeptr = gmtime(&tm);
3315 pthread_mutex_unlock(&gmtime_mutex);
3317 timeptr = gmtime(&tm);
3319 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3322 *header = strdup("If-Modified-Since: ");
3323 string_append(header, newheader);
3325 if (*header == NULL)
3327 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3328 return JB_ERR_MEMORY;
3331 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3333 hours = rtime / 3600;
3334 minutes = rtime / 60 % 60;
3335 seconds = rtime % 60;
3337 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3338 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3339 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3348 /*********************************************************************
3350 * Function : client_if_none_match
3352 * Description : Remove the If-None-Match header.
3355 * 1 : csp = Current client state (buffers, headers, etc...)
3356 * 2 : header = On input, pointer to header to modify.
3357 * On output, pointer to the modified header, or NULL
3358 * to remove the header. This function frees the
3359 * original string if necessary.
3361 * Returns : JB_ERR_OK on success, or
3362 * JB_ERR_MEMORY on out-of-memory error.
3364 *********************************************************************/
3365 static jb_err client_if_none_match(struct client_state *csp, char **header)
3367 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3369 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3376 /*********************************************************************
3378 * Function : client_x_filter
3380 * Description : Disables filtering if the client set "X-Filter: No".
3381 * Called from `sed'.
3384 * 1 : csp = Current client state (buffers, headers, etc...)
3385 * 2 : header = On input, pointer to header to modify.
3386 * On output, pointer to the modified header, or NULL
3387 * to remove the header. This function frees the
3388 * original string if necessary.
3390 * Returns : JB_ERR_OK on success
3392 *********************************************************************/
3393 jb_err client_x_filter(struct client_state *csp, char **header)
3395 if ( 0 == strcmpic(*header, "X-Filter: No"))
3397 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3399 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3403 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3405 log_error(LOG_LEVEL_HEADER,
3406 "force-text-mode overruled the client's request to fetch without filtering!");
3410 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3411 csp->flags |= CSP_FLAG_NO_FILTERING;
3412 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3414 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3421 /* the following functions add headers directly to the header list */
3423 /*********************************************************************
3425 * Function : client_host_adder
3427 * Description : Adds the Host: header field if it is missing.
3428 * Called from `sed'.
3431 * 1 : csp = Current client state (buffers, headers, etc...)
3433 * Returns : JB_ERR_OK on success, or
3434 * JB_ERR_MEMORY on out-of-memory error.
3436 *********************************************************************/
3437 static jb_err client_host_adder(struct client_state *csp)
3442 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3444 /* Header already set by the client, nothing to do. */
3448 if ( !csp->http->hostport || !*(csp->http->hostport))
3450 /* XXX: When does this happen and why is it OK? */
3451 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3456 * remove 'user:pass@' from 'proto://user:pass@host'
3458 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3464 p = csp->http->hostport;
3467 /* XXX: Just add it, we already made sure that it will be unique */
3468 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3469 err = enlist_unique_header(csp->headers, "Host", p);
3475 /*********************************************************************
3477 * Function : client_cookie_adder
3479 * Description : Used in the add_client_headers list to add "wafers".
3480 * Called from `sed'.
3483 * 1 : csp = Current client state (buffers, headers, etc...)
3485 * Returns : JB_ERR_OK on success, or
3486 * JB_ERR_MEMORY on out-of-memory error.
3488 *********************************************************************/
3489 jb_err client_cookie_adder(struct client_state *csp)
3492 struct list_entry *wafer;
3493 struct list_entry *wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3496 if (NULL == wafer_list)
3502 tmp = strdup("Cookie: ");
3504 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3506 if (wafer != wafer_list)
3508 /* As this isn't the first wafer, we need a delimiter. */
3509 string_append(&tmp, "; ");
3511 string_join(&tmp, cookie_encode(wafer->str));
3516 return JB_ERR_MEMORY;
3519 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3520 err = enlist(csp->headers, tmp);
3526 /*********************************************************************
3528 * Function : client_accept_encoding_adder
3530 * Description : Add an Accept-Encoding header to the client's request
3531 * that disables compression if the action applies, and
3532 * the header is not already there. Called from `sed'.
3533 * Note: For HTTP/1.0, the absence of the header is enough.
3536 * 1 : csp = Current client state (buffers, headers, etc...)
3538 * Returns : JB_ERR_OK on success, or
3539 * JB_ERR_MEMORY on out-of-memory error.
3541 *********************************************************************/
3542 static jb_err client_accept_encoding_adder(struct client_state *csp)
3544 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3545 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3547 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3554 /*********************************************************************
3556 * Function : client_xtra_adder
3558 * Description : Used in the add_client_headers list. Called from `sed'.
3561 * 1 : csp = Current client state (buffers, headers, etc...)
3563 * Returns : JB_ERR_OK on success, or
3564 * JB_ERR_MEMORY on out-of-memory error.
3566 *********************************************************************/
3567 static jb_err client_xtra_adder(struct client_state *csp)
3569 struct list_entry *lst;
3572 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3573 lst ; lst = lst->next)
3575 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3576 err = enlist(csp->headers, lst->str);
3588 /*********************************************************************
3590 * Function : client_x_forwarded_adder
3592 * Description : Used in the add_client_headers list. Called from `sed'.
3595 * 1 : csp = Current client state (buffers, headers, etc...)
3597 * Returns : JB_ERR_OK on success, or
3598 * JB_ERR_MEMORY on out-of-memory error.
3600 *********************************************************************/
3601 static jb_err client_x_forwarded_adder(struct client_state *csp)
3606 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3611 if (csp->x_forwarded)
3613 p = strdup(csp->x_forwarded);
3614 string_append(&p, ", ");
3618 p = strdup("X-Forwarded-For: ");
3620 string_append(&p, csp->ip_addr_str);
3624 return JB_ERR_MEMORY;
3627 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3628 err = enlist(csp->headers, p);
3635 /*********************************************************************
3637 * Function : connection_close_adder
3639 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3640 * support. Adds a "Connection: close" header to csp->headers
3641 * unless the header was already present. Called from `sed'.
3643 * FIXME: This whole function shouldn't be neccessary!
3646 * 1 : csp = Current client state (buffers, headers, etc...)
3648 * Returns : JB_ERR_OK on success, or
3649 * JB_ERR_MEMORY on out-of-memory error.
3651 *********************************************************************/
3652 static jb_err connection_close_adder(struct client_state *csp)
3654 const unsigned int flags = csp->flags;
3657 * Return right away if
3659 * - we're parsing server headers and the server header
3660 * "Connection: close" is already set, or if
3662 * - we're parsing client headers and the client header
3663 * "Connection: close" is already set.
3665 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3666 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3667 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3668 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3673 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3675 return enlist(csp->headers, "Connection: close");
3679 /*********************************************************************
3681 * Function : server_http
3683 * Description : - Save the HTTP Status into csp->http->status
3684 * - Set CT_TABOO to prevent filtering if the answer
3685 * is a partial range (HTTP status 206)
3686 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3690 * 1 : csp = Current client state (buffers, headers, etc...)
3691 * 2 : header = On input, pointer to header to modify.
3692 * On output, pointer to the modified header, or NULL
3693 * to remove the header. This function frees the
3694 * original string if necessary.
3696 * Returns : JB_ERR_OK on success, or
3697 * JB_ERR_MEMORY on out-of-memory error.
3699 *********************************************************************/
3700 static jb_err server_http(struct client_state *csp, char **header)
3702 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3703 if (csp->http->status == 206)
3705 csp->content_type = CT_TABOO;
3708 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3711 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3718 /*********************************************************************
3720 * Function : server_set_cookie
3722 * Description : Handle the server "cookie" header properly.
3723 * Log cookie to the jar file. Then "crunch",
3724 * accept or rewrite it to a session cookie.
3725 * Called from `sed'.
3727 * TODO: Allow the user to specify a new expiration
3728 * time to cause the cookie to expire even before the
3729 * browser is closed.
3732 * 1 : csp = Current client state (buffers, headers, etc...)
3733 * 2 : header = On input, pointer to header to modify.
3734 * On output, pointer to the modified header, or NULL
3735 * to remove the header. This function frees the
3736 * original string if necessary.
3738 * Returns : JB_ERR_OK on success, or
3739 * JB_ERR_MEMORY on out-of-memory error.
3741 *********************************************************************/
3742 static jb_err server_set_cookie(struct client_state *csp, char **header)
3749 #ifdef FEATURE_COOKIE_JAR
3750 if (csp->config->jar)
3753 * Write timestamp into outbuf.
3755 * Complex because not all OSs have tm_gmtoff or
3756 * the %z field in strftime()
3758 char tempbuf[ BUFFER_SIZE ];
3760 #ifdef HAVE_LOCALTIME_R
3761 tm_now = *localtime_r(&now, &tm_now);
3762 #elif FEATURE_PTHREAD
3763 pthread_mutex_lock(&localtime_mutex);
3764 tm_now = *localtime (&now);
3765 pthread_mutex_unlock(&localtime_mutex);
3767 tm_now = *localtime (&now);
3769 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3771 /* strlen("set-cookie: ") = 12 */
3772 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3774 #endif /* def FEATURE_COOKIE_JAR */
3776 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3778 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3781 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3783 /* Flag whether or not to log a message */
3786 /* A variable to store the tag we're working on */
3789 /* Skip "Set-Cookie:" (11 characters) in header */
3790 cur_tag = *header + 11;
3792 /* skip whitespace between "Set-Cookie:" and value */
3793 while (*cur_tag && ijb_isspace(*cur_tag))
3798 /* Loop through each tag in the cookie */
3802 char *next_tag = strchr(cur_tag, ';');
3803 if (next_tag != NULL)
3805 /* Skip the ';' character itself */
3808 /* skip whitespace ";" and start of tag */
3809 while (*next_tag && ijb_isspace(*next_tag))
3816 /* "Next tag" is the end of the string */
3817 next_tag = cur_tag + strlen(cur_tag);
3821 * Check the expiration date to see
3822 * if the cookie is still valid, if yes,
3823 * rewrite it to a session cookie.
3825 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3827 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3829 /* Did we detect the date properly? */
3830 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3833 * Nope, treat it as if it was still valid.
3835 * XXX: Should we remove the whole cookie instead?
3837 log_error(LOG_LEVEL_ERROR,
3838 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3839 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3845 * Yes. Check if the cookie is still valid.
3847 * If the cookie is already expired it's probably
3848 * a delete cookie and even if it isn't, the browser
3849 * will discard it anyway.
3853 * XXX: timegm() isn't available on some AmigaOS
3854 * versions and our replacement doesn't work.
3856 * Our options are to either:
3858 * - disable session-cookies-only completely if timegm
3861 * - to simply remove all expired tags, like it has
3862 * been done until Privoxy 3.0.6 and to live with
3863 * the consequence that it can cause login/logout
3864 * problems on servers that don't validate their
3865 * input properly, or
3867 * - to replace it with mktime in which
3868 * case there is a slight chance of valid cookies
3869 * passing as already expired.
3871 * This is the way it's currently done and it's not
3872 * as bad as it sounds. If the missing GMT offset is
3873 * enough to change the result of the expiration check
3874 * the cookie will be only valid for a few hours
3875 * anyway, which in many cases will be shorter
3876 * than a browser session.
3878 if (cookie_time - now < 0)
3880 log_error(LOG_LEVEL_HEADER,
3881 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3882 /* Just in case some clown sets more then one expiration date */
3888 * Still valid, delete expiration date by copying
3889 * the rest of the string over it.
3891 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3892 * since the behaviour of strcpy is undefined for overlapping
3895 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3897 /* That changed the header, need to issue a log message */
3901 * Note that the next tag has now been moved to *cur_tag,
3902 * so we do not need to update the cur_tag pointer.
3910 /* Move on to next cookie tag */
3917 assert(NULL != *header);
3918 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3927 #ifdef FEATURE_FORCE_LOAD
3928 /*********************************************************************
3930 * Function : strclean
3932 * Description : In-Situ-Eliminate all occurances of substring in
3936 * 1 : string = string to clean
3937 * 2 : substring = substring to eliminate
3939 * Returns : Number of eliminations
3941 *********************************************************************/
3942 int strclean(const char *string, const char *substring)
3948 len = strlen(substring);
3950 while((pos = strstr(string, substring)) != NULL)
3957 while (*p++ != '\0');
3964 #endif /* def FEATURE_FORCE_LOAD */
3966 /*********************************************************************
3968 * Function : parse_header_time
3970 * Description : Parses time formats used in HTTP header strings
3971 * to get the numerical respresentation.
3974 * 1 : header_time = HTTP header time as string.
3975 * 2 : result = storage for header_time in seconds
3977 * Returns : JB_ERR_OK if the time format was recognized, or
3978 * JB_ERR_PARSE otherwise.
3980 *********************************************************************/
3981 static jb_err parse_header_time(const char *header_time, time_t *result)
3986 * Zero out gmt to prevent time zone offsets.
3988 * While this is only necessary on some platforms
3989 * (mingw32 for example), I don't know how to
3990 * detect these automatically and doing it everywhere
3993 memset(&gmt, 0, sizeof(gmt));
3995 /* Tue, 02 Jun 2037 20:00:00 */
3996 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3997 /* Tue, 02-Jun-2037 20:00:00 */
3998 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3999 /* Tue, 02-Jun-37 20:00:00 */
4000 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4001 /* Tuesday, 02-Jun-2037 20:00:00 */
4002 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4003 /* Tuesday Jun 02 20:00:00 2037 */
4004 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4006 return JB_ERR_PARSE;
4009 *result = timegm(&gmt);
4015 /*********************************************************************
4017 * Function : get_destination_from_headers
4019 * Description : Parse the "Host:" header to get the request's destination.
4020 * Only needed if the client's request was forcefully
4021 * redirected into Privoxy.
4023 * Code mainly copied from client_host() which is currently
4024 * run too late for this purpose.
4027 * 1 : headers = List of headers (one of them hopefully being
4028 * the "Host:" header)
4029 * 2 : http = storage for the result (host, port and hostport).
4031 * Returns : JB_ERR_MEMORY in case of memory problems,
4032 * JB_ERR_PARSE if the host header couldn't be found,
4033 * JB_ERR_OK otherwise.
4035 *********************************************************************/
4036 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4042 host = get_header_value(headers, "Host:");
4046 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4047 return JB_ERR_PARSE;
4050 if (NULL == (p = strdup((host))))
4052 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4053 return JB_ERR_MEMORY;
4056 if (NULL == (q = strdup(p)))
4059 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4060 return JB_ERR_MEMORY;
4063 freez(http->hostport);
4067 q = strchr(http->host, ':');
4070 /* Terminate hostname and evaluate port string */
4072 http->port = atoi(q);
4076 http->port = http->ssl ? 443 : 80;
4079 /* Rebuild request URL */
4081 http->url = strdup(http->ssl ? "https://" : "http://");
4082 string_append(&http->url, http->hostport);
4083 string_append(&http->url, http->path);
4084 if (http->url == NULL)
4086 return JB_ERR_MEMORY;
4089 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",