1 const char parsers_rcs[] = "$Id: parsers.c,v 1.103 2007/06/01 16:31:54 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.103 2007/06/01 16:31:54 fabiankeil
48 * Change sed() to return a jb_err in preparation for forward-override{}.
50 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
51 * Adjust "X-Filter: No" to disable dedicated header filters.
53 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
54 * Streamline client_cookie_adder().
56 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
57 * Make sure filters with dynamic jobs actually use them.
59 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
60 * - Introduce dynamic pcrs jobs that can resolve variables.
61 * - Remove unnecessary update_action_bits_for_all_tags() call.
63 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
64 * - Make tagging based on tags set by earlier taggers
65 * of the same kind possible.
66 * - Log whether or not new tags cause action bits updates
67 * (in which case a matching tag-pattern section exists).
68 * - Log if the user tries to set a tag that is already set.
70 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
71 * Introduce tags as alternative way to specify which
72 * actions apply to a request. At the moment tags can be
73 * created based on client and server headers.
75 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
76 * Log a warning if the content is compressed, filtering is
77 * enabled and Privoxy was compiled without zlib support.
80 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
81 * - Fix warnings when compiled with glibc.
82 * - Don't use crumble() for cookie crunching.
83 * - Move cookie time parsing into parse_header_time().
84 * - Let parse_header_time() return a jb_err code
85 * instead of a pointer that can only be used to
86 * check for NULL anyway.
88 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
89 * - Add better protection against malicious gzip headers.
90 * - Stop logging the first hundred bytes of decompressed content.
91 * It looks like it's working and there is always debug 16.
92 * - Log the content size after decompression in decompress_iob()
93 * instead of pcrs_filter_response().
95 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
96 * - Use dedicated header filter actions instead of abusing "filter".
97 * Replace "filter-client-headers" and "filter-client-headers"
98 * with "server-header-filter" and "client-header-filter".
99 * - Remove filter_client_header() and filter_client_header(),
100 * filter_header() now checks the shiny new
101 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
103 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
104 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
105 * - Handle "Cookie:" and "Connection:" headers a bit smarter
106 * (don't crunch them just to recreate them later on).
107 * - Add another non-standard time format for the cookie
108 * expiration date detection.
109 * - Fix a valgrind warning.
111 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
112 * Improve cookie expiration date detection.
114 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
115 * Don't run server_content_length() the first time
116 * sed() parses server headers; only adjust the
117 * Content-Length header if the page was modified.
119 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
120 * Fix log messages regarding the cookie time format
121 * (cookie and request URL were mixed up).
123 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
124 * - Let decompress_iob()
125 * - not corrupt the content if decompression fails
126 * early. (the first byte(s) were lost).
127 * - use pointer arithmetics with defined outcome for
129 * - Use a different kludge to remember a failed decompression.
131 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
132 * Search for Max-Forwards headers case-insensitive,
133 * don't generate the "501 unsupported" message for invalid
134 * Max-Forwards values and don't increase negative ones.
136 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
137 * - Let server_set_cookie() check the expiration date
138 * of cookies and don't touch the ones that are already
139 * expired. Fixes problems with low quality web applications
140 * as described in BR 932612.
142 * - Adjust comment in client_max_forwards to reality;
143 * remove invalid Max-Forwards headers.
145 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
146 * Stop filter_header() from unintentionally removing
147 * empty header lines that were enlisted by the continue
150 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
151 * - Repeat the request URL before logging any headers.
152 * Makes reading the log easier in case of simultaneous requests.
153 * - If there are more than one Content-Type headers in one request,
154 * use the first one and remove the others.
155 * - Remove "newval" variable in server_content_type().
156 * It's only used once.
158 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
159 * Correct a cast, check inflateEnd() exit code
160 * to see if we have to, replace sprintf calls
163 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
164 * Integrate a modified version of Wil Mahan's
165 * zlib patch (PR #895531).
167 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
168 * Skip empty filter files in filter_header()
169 * but don't ignore the ones that come afterwards.
170 * Fixes BR 1619208, this time for real.
172 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
173 * Reverted parts of my last commit
174 * to keep error handling working.
176 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
177 * Fixed gcc43 conversion warnings.
179 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
180 * Bringing back the "useless" localtime() call
181 * I removed in revision 1.67. On some platforms
182 * it's necessary to prevent time zone offsets.
184 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
185 * Rebuild request URL in get_destination_from_headers()
186 * to make sure redirect{pcrs command} works as expected
187 * for intercepted requests.
189 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
190 * Added get_destination_from_headers().
192 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
193 * Make pthread mutex locking more generic. Instead of
194 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
195 * and use mutex locking unless there is an _r function
196 * available. Better safe than sorry.
198 * Fixes "./configure --disable-pthread" and should result
199 * in less threading-related problems on pthread-using platforms,
200 * but it still doesn't fix BR#1122404.
202 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
203 * The special header "X-Filter: No" now disables
204 * header filtering as well.
206 * Revision 1.73 2006/09/23 13:26:38 roro
207 * Replace TABs by spaces in source code.
209 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
210 * Don't print a log message every time filter_headers is
211 * entered or left. It only creates noise without any real
214 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
215 * Fix +hide-if-modified-since{-n}.
217 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
218 * Have hide-if-modified-since interpret the random
219 * range value as minutes instead of hours. Allows
220 * more fine-grained configuration.
222 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
223 * Always have parse_header_time return a pointer
224 * that actual makes sense, even though we currently
225 * only need it to detect problems.
227 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
228 * Added config option enable-remote-http-toggle
229 * to specify if Privoxy should recognize special
230 * headers (currently only X-Filter) to change its
231 * behaviour. Disabled by default.
233 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
234 * After filtering de-chunked instances, remove
235 * "Transfer-Encoding" header entirely instead of changing
236 * it to "Transfer-Encoding: identity", which is invalid.
237 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
239 * Don't use localtime in parse_header_time. An empty time struct
240 * is good enough, it gets overwritten by strptime anyway.
242 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
243 * Use gmtime_r if available, fallback to gmtime with mutex
244 * protection for MacOSX and use vanilla gmtime for the rest.
246 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
247 * Changed client_referrer to use the right type (size_t) for
248 * hostlenght and to shorten the temporary referrer string with
249 * '\0' instead of adding a useless line break.
251 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
252 * - Back to timegm() using GnuPG's replacement if necessary.
253 * Using mktime() and localtime() could add a on hour offset if
254 * the randomize factor was big enough to lead to a summer/wintertime
257 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
259 * - Moved randomization code into pick_from_range().
261 * - Changed parse_header_time definition.
262 * time_t isn't guaranteed to be signed and
263 * if it isn't, -1 isn't available as error code.
264 * Changed some variable types in client_if_modified_since()
265 * because of the same reason.
267 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
268 * OS/2 compilation compatibility fixups
270 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
271 * Changed include from strptime.c to strptime.h
273 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
274 * Split filter-headers{} into filter-client-headers{}
275 * and filter-server-headers{}.
276 * Added parse_header_time() to share some code.
277 * Replaced timegm() with mktime().
279 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
280 * Windows service integration
282 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
283 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
285 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
286 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
287 * with what was really the latest development (the v_3_0_branch branch)
289 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
290 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
292 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
293 * Add the ability to check jpeg images for invalid
294 * lengths of comment blocks. Defensive strategy
295 * against the exploit:
296 * Microsoft Security Bulletin MS04-028
297 * Buffer Overrun in JPEG Processing (GDI+) Could
298 * Allow Code Execution (833987)
299 * Enabled with +inspect-jpegs in actions files.
301 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
302 * Excluded text/plain objects from filtering. This fixes a
303 * couple of client-crashing, download corruption and
304 * Privoxy performance issues, whose root cause lies in
305 * web servers labelling content of unknown type as text/plain.
307 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
308 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
310 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
311 * Completing the previous change
313 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
314 * Added temporary workaround for bug in PHP < 4.2.3
316 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
317 * 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.
319 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
320 * Fix typo: supressed -> suppressed
322 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
323 * Improved cookie logging
325 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
326 * Added basic support for OPTIONS and TRACE HTTP methods:
327 * - New parser function client_max_forwards which decrements
328 * the Max-Forwards HTTP header field of OPTIONS and TRACE
329 * requests by one before forwarding
330 * - New parser function client_host which extracts the host
331 * and port information from the HTTP header field if the
332 * request URI was not absolute
333 * - Don't crumble and re-add the Host: header, but only generate
334 * and append if missing
336 * Revision 1.56 2002/05/12 15:34:22 jongfoster
337 * Fixing typo in a comment
339 * Revision 1.55 2002/05/08 16:01:07 oes
340 * Optimized add_to_iob:
341 * - Use realloc instead of malloc(), memcpy(), free()
342 * - Expand to powers of two if possible, to get
343 * O(log n) reallocs instead of O(n).
344 * - Moved check for buffer limit here from chat
345 * - Report failure via returncode
347 * Revision 1.54 2002/04/02 15:03:16 oes
348 * Tiny code cosmetics
350 * Revision 1.53 2002/03/26 22:29:55 swa
351 * we have a new homepage!
353 * Revision 1.52 2002/03/24 13:25:43 swa
354 * name change related issues
356 * Revision 1.51 2002/03/13 00:27:05 jongfoster
359 * Revision 1.50 2002/03/12 01:45:35 oes
360 * More verbose logging
362 * Revision 1.49 2002/03/09 20:03:52 jongfoster
363 * - Making various functions return int rather than size_t.
364 * (Undoing a recent change). Since size_t is unsigned on
365 * Windows, functions like read_socket that return -1 on
366 * error cannot return a size_t.
368 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
369 * crashes, and also frequently caused JB to jump to 100%
370 * CPU and stay there. (Because it thought it had just
371 * read ((unsigned)-1) == 4Gb of data...)
373 * - The signature of write_socket has changed, it now simply
374 * returns success=0/failure=nonzero.
376 * - Trying to get rid of a few warnings --with-debug on
377 * Windows, I've introduced a new type "jb_socket". This is
378 * used for the socket file descriptors. On Windows, this
379 * is SOCKET (a typedef for unsigned). Everywhere else, it's
380 * an int. The error value can't be -1 any more, so it's
381 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
382 * Windows it maps to the #define INVALID_SOCKET.)
384 * - The signature of bind_port has changed.
386 * Revision 1.48 2002/03/07 03:46:53 oes
387 * Fixed compiler warnings etc
389 * Revision 1.47 2002/02/20 23:15:13 jongfoster
390 * Parsing functions now handle out-of-memory gracefully by returning
393 * Revision 1.46 2002/01/17 21:03:47 jongfoster
394 * Moving all our URL and URL pattern parsing code to urlmatch.c.
396 * Revision 1.45 2002/01/09 14:33:03 oes
397 * Added support for localtime_r.
399 * Revision 1.44 2001/12/14 01:22:54 steudten
400 * Remove 'user:pass@' from 'proto://user:pass@host' for the
401 * new added header 'Host: ..'. (See Req ID 491818)
403 * Revision 1.43 2001/11/23 00:26:38 jongfoster
404 * Fixing two really stupid errors in my previous commit
406 * Revision 1.42 2001/11/22 21:59:30 jongfoster
407 * Adding code to handle +no-cookies-keep
409 * Revision 1.41 2001/11/05 23:43:05 steudten
410 * Add time+date to log files.
412 * Revision 1.40 2001/10/26 20:13:09 jongfoster
413 * ctype.h is needed in Windows, too.
415 * Revision 1.39 2001/10/26 17:40:04 oes
416 * Introduced get_header_value()
417 * Removed http->user_agent, csp->referrer and csp->accept_types
418 * Removed client_accept()
420 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
421 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
422 * threads to call select() simultaneously. So, it's time to do a real, live,
423 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
424 * (native). Both versions will work, but using __OS2__ offers multi-threading.
426 * Revision 1.37 2001/10/23 21:36:02 jongfoster
427 * Documenting sed()'s error behaviou (doc change only)
429 * Revision 1.36 2001/10/13 12:51:51 joergs
430 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
431 * force-load), instead crumble Host: and add it (again) in client_host_adder
432 * (in case we get a HTTP/1.0 request without Host: header and forward it to
433 * a HTTP/1.1 server/proxy).
435 * Revision 1.35 2001/10/09 22:39:21 jongfoster
436 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
439 * Revision 1.34 2001/10/07 18:50:55 oes
440 * Added server_content_encoding, renamed server_transfer_encoding
442 * Revision 1.33 2001/10/07 18:04:49 oes
443 * Changed server_http11 to server_http and its pattern to "HTTP".
444 * Additional functionality: it now saves the HTTP status into
445 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
447 * Revision 1.32 2001/10/07 15:43:28 oes
448 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
449 * client_te and client_accept_encoding_adder, triggered by the new
450 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
451 * changed to allow only identity and chunked, and the TE header is
452 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
454 * parse_http_request no longer does anything than parsing. The rewriting
455 * of http->cmd and version mangling are gone. It now also recognizes
456 * the put and delete methods and saves the url in http->url. Removed
459 * renamed content_type and content_length to have the server_ prefix
461 * server_content_type now only works if csp->content_type != CT_TABOO
463 * added server_transfer_encoding, which
464 * - Sets CT_TABOO to prohibit filtering if encoding compresses
465 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
466 * - Change from "chunked" to "identity" if body was chunked
467 * but has been de-chunked for filtering.
469 * added server_content_md5 which crunches any Content-MD5 headers
470 * if the body was modified.
472 * made server_http11 conditional on +downgrade action
474 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
476 * Revision 1.31 2001/10/05 14:25:02 oes
477 * Crumble Keep-Alive from Server
479 * Revision 1.30 2001/09/29 12:56:03 joergs
480 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
482 * Revision 1.29 2001/09/24 21:09:24 jongfoster
483 * Fixing 2 memory leaks that Guy spotted, where the paramater to
484 * enlist() was not being free()d.
486 * Revision 1.28 2001/09/22 16:32:28 jongfoster
487 * Removing unused #includes.
489 * Revision 1.27 2001/09/20 15:45:25 steudten
491 * add casting from size_t to int for printf()
492 * remove local variable shadow s2
494 * Revision 1.26 2001/09/16 17:05:14 jongfoster
495 * Removing unused #include showarg.h
497 * Revision 1.25 2001/09/16 13:21:27 jongfoster
498 * Changes to use new list functions.
500 * Revision 1.24 2001/09/13 23:05:50 jongfoster
501 * Changing the string paramater to the header parsers a "const".
503 * Revision 1.23 2001/09/12 18:08:19 steudten
505 * In parse_http_request() header rewriting miss the host value, so
506 * from http://www.mydomain.com the result was just " / " not
507 * http://www.mydomain.com/ in case we forward.
509 * Revision 1.22 2001/09/10 10:58:53 oes
510 * Silenced compiler warnings
512 * Revision 1.21 2001/07/31 14:46:00 oes
513 * - Persistant connections now suppressed
514 * - sed() no longer appends empty header to csp->headers
516 * Revision 1.20 2001/07/30 22:08:36 jongfoster
517 * Tidying up #defines:
518 * - All feature #defines are now of the form FEATURE_xxx
519 * - Permanently turned off WIN_GUI_EDIT
520 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
522 * Revision 1.19 2001/07/25 17:21:54 oes
523 * client_uagent now saves copy of User-Agent: header value
525 * Revision 1.18 2001/07/13 14:02:46 oes
526 * - Included fix to repair broken HTTP requests that
527 * don't contain a path, not even '/'.
528 * - Removed all #ifdef PCRS
529 * - content_type now always inspected and classified as
530 * text, gif or other.
531 * - formatting / comments
533 * Revision 1.17 2001/06/29 21:45:41 oes
534 * Indentation, CRLF->LF, Tab-> Space
536 * Revision 1.16 2001/06/29 13:32:42 oes
538 * - Adapted free_http_request
539 * - Removed logentry from cancelled commit
541 * Revision 1.15 2001/06/03 19:12:38 oes
542 * deleted const struct interceptors
544 * Revision 1.14 2001/06/01 18:49:17 jongfoster
545 * Replaced "list_share" with "list" - the tiny memory gain was not
546 * worth the extra complexity.
548 * Revision 1.13 2001/05/31 21:30:33 jongfoster
549 * Removed list code - it's now in list.[ch]
550 * Renamed "permission" to "action", and changed many features
551 * to use the actions file rather than the global config.
553 * Revision 1.12 2001/05/31 17:33:13 oes
557 * Revision 1.11 2001/05/29 20:11:19 joergs
558 * '/ * inside comment' warning removed.
560 * Revision 1.10 2001/05/29 09:50:24 jongfoster
561 * Unified blocklist/imagelist/permissionslist.
562 * File format is still under discussion, but the internal changes
565 * Also modified interceptor behaviour:
566 * - We now intercept all URLs beginning with one of the following
567 * prefixes (and *only* these prefixes):
569 * * http://ijbswa.sf.net/config/
570 * * http://ijbswa.sourceforge.net/config/
571 * - New interceptors "home page" - go to http://i.j.b/ to see it.
572 * - Internal changes so that intercepted and fast redirect pages
573 * are not replaced with an image.
574 * - Interceptors now have the option to send a binary page direct
575 * to the client. (i.e. ijb-send-banner uses this)
576 * - Implemented show-url-info interceptor. (Which is why I needed
577 * the above interceptors changes - a typical URL is
578 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
579 * The previous mechanism would not have intercepted that, and
580 * if it had been intercepted then it then it would have replaced
583 * Revision 1.9 2001/05/28 17:26:33 jongfoster
584 * Fixing segfault if last header was crunched.
585 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
586 * can use the cross-platform sprintf() instead.)
588 * Revision 1.8 2001/05/27 22:17:04 oes
590 * - re_process_buffer no longer writes the modified buffer
591 * to the client, which was very ugly. It now returns the
592 * buffer, which it is then written by chat.
594 * - content_length now adjusts the Content-Length: header
595 * for modified documents rather than crunch()ing it.
596 * (Length info in csp->content_length, which is 0 for
597 * unmodified documents)
599 * - For this to work, sed() is called twice when filtering.
601 * Revision 1.7 2001/05/27 13:19:06 oes
602 * Patched Joergs solution for the content-length in.
604 * Revision 1.6 2001/05/26 13:39:32 jongfoster
605 * Only crunches Content-Length header if applying RE filtering.
606 * Without this fix, Microsoft Windows Update wouldn't work.
608 * Revision 1.5 2001/05/26 00:28:36 jongfoster
609 * Automatic reloading of config file.
610 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
611 * Most of the global variables have been moved to a new
612 * struct configuration_spec, accessed through csp->config->globalname
613 * Most of the globals remaining are used by the Win32 GUI.
615 * Revision 1.4 2001/05/22 18:46:04 oes
617 * - Enabled filtering banners by size rather than URL
618 * by adding patterns that replace all standard banner
619 * sizes with the "Junkbuster" gif to the re_filterfile
621 * - Enabled filtering WebBugs by providing a pattern
622 * which kills all 1x1 images
624 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
625 * which is selected by the (nonstandard and therefore
626 * capital) letter 'U' in the option string.
627 * It causes the quantifiers to be ungreedy by default.
628 * Appending a ? turns back to greedy (!).
630 * - Added a new interceptor ijb-send-banner, which
631 * sends back the "Junkbuster" gif. Without imagelist or
632 * MSIE detection support, or if tinygif = 1, or the
633 * URL isn't recognized as an imageurl, a lame HTML
634 * explanation is sent instead.
636 * - Added new feature, which permits blocking remote
637 * script redirects and firing back a local redirect
639 * The feature is conditionally compiled, i.e. it
640 * can be disabled with --disable-fast-redirects,
641 * plus it must be activated by a "fast-redirects"
642 * line in the config file, has its own log level
643 * and of course wants to be displayed by show-proxy-args
644 * Note: Boy, all the #ifdefs in 1001 locations and
645 * all the fumbling with configure.in and acconfig.h
646 * were *way* more work than the feature itself :-(
648 * - Because a generic redirect template was needed for
649 * this, tinygif = 3 now uses the same.
651 * - Moved GIFs, and other static HTTP response templates
656 * - Removed some >400 CRs again (Jon, you really worked
659 * Revision 1.3 2001/05/20 01:21:20 jongfoster
660 * Version 2.9.4 checkin.
661 * - Merged popupfile and cookiefile, and added control over PCRS
662 * filtering, in new "permissionsfile".
663 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
664 * file error you now get a message box (in the Win32 GUI) rather
665 * than the program exiting with no explanation.
666 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
668 * - Removed tabs from "config"
669 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
670 * - Bumped up version number.
672 * Revision 1.2 2001/05/17 23:02:36 oes
673 * - Made referrer option accept 'L' as a substitute for '§'
675 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
676 * Initial import of version 2.9.3 source tree
679 *********************************************************************/
686 #include <sys/types.h>
696 * Convince GNU's libc to provide a strptime prototype.
699 #endif /*__GLIBC__ */
706 #if !defined(_WIN32) && !defined(__OS2__)
712 #ifdef FEATURE_PTHREAD
714 /* jcc.h is for mutex semapores only */
715 #endif /* def FEATURE_PTHREAD */
721 #include "jbsockets.h"
722 #include "miscutil.h"
727 #ifndef HAVE_STRPTIME
728 #include "strptime.h"
731 const char parsers_h_rcs[] = PARSERS_H_VERSION;
733 /* Fix a problem with Solaris. There should be no effect on other
735 * Solaris's isspace() is a macro which uses its argument directly
736 * as an array index. Therefore we need to make sure that high-bit
737 * characters generate +ve values, and ideally we also want to make
738 * the argument match the declared parameter type of "int".
740 * Why did they write a character function that can't take a simple
741 * "char" argument? Doh!
743 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
744 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
746 jb_err header_tagger(struct client_state *csp, char *header);
747 jb_err scan_headers(struct client_state *csp);
749 const struct parsers client_patterns[] = {
750 { "referer:", 8, client_referrer },
751 { "user-agent:", 11, client_uagent },
752 { "ua-", 3, client_ua },
753 { "from:", 5, client_from },
754 { "cookie:", 7, client_send_cookie },
755 { "x-forwarded-for:", 16, client_x_forwarded },
756 { "Accept-Encoding:", 16, client_accept_encoding },
757 { "TE:", 3, client_te },
758 { "Host:", 5, client_host },
759 { "if-modified-since:", 18, client_if_modified_since },
760 { "Keep-Alive:", 11, crumble },
761 { "connection:", 11, connection },
762 { "proxy-connection:", 17, crumble },
763 { "max-forwards:", 13, client_max_forwards },
764 { "Accept-Language:", 16, client_accept_language },
765 { "if-none-match:", 14, client_if_none_match },
766 { "X-Filter:", 9, client_x_filter },
767 { "*", 0, crunch_client_header },
768 { "*", 0, filter_header },
772 const struct parsers server_patterns[] = {
773 { "HTTP", 4, server_http },
774 { "set-cookie:", 11, server_set_cookie },
775 { "connection:", 11, connection },
776 { "Content-Type:", 13, server_content_type },
777 { "Content-MD5:", 12, server_content_md5 },
778 { "Content-Encoding:", 17, server_content_encoding },
779 { "Transfer-Encoding:", 18, server_transfer_coding },
780 { "Keep-Alive:", 11, crumble },
781 { "content-disposition:", 20, server_content_disposition },
782 { "Last-Modified:", 14, server_last_modified },
783 { "*", 0, crunch_server_header },
784 { "*", 0, filter_header },
788 const struct parsers server_patterns_light[] = {
789 { "Content-Length:", 15, server_content_length },
790 { "Transfer-Encoding:", 18, server_transfer_coding },
792 { "Content-Encoding:", 17, server_content_encoding },
793 #endif /* def FEATURE_ZLIB */
797 const add_header_func_ptr add_client_headers[] = {
800 client_x_forwarded_adder,
802 /* Temporarily disabled: client_accept_encoding_adder, */
803 connection_close_adder,
808 const add_header_func_ptr add_server_headers[] = {
809 connection_close_adder,
813 /*********************************************************************
815 * Function : flush_socket
817 * Description : Write any pending "buffered" content.
820 * 1 : fd = file descriptor of the socket to read
821 * 2 : csp = Current client state (buffers, headers, etc...)
823 * Returns : On success, the number of bytes written are returned (zero
824 * indicates nothing was written). On error, -1 is returned,
825 * and errno is set appropriately. If count is zero and the
826 * file descriptor refers to a regular file, 0 will be
827 * returned without causing any other effect. For a special
828 * file, the results are not portable.
830 *********************************************************************/
831 int flush_socket(jb_socket fd, struct client_state *csp)
833 struct iob *iob = csp->iob;
834 int len = iob->eod - iob->cur;
841 if (write_socket(fd, iob->cur, (size_t)len))
845 iob->eod = iob->cur = iob->buf;
851 /*********************************************************************
853 * Function : add_to_iob
855 * Description : Add content to the buffered page, expanding the
856 * buffer if necessary.
859 * 1 : csp = Current client state (buffers, headers, etc...)
860 * 2 : buf = holds the content to be added to the page
861 * 3 : n = number of bytes to be added
863 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
864 * or buffer limit reached.
866 *********************************************************************/
867 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
869 struct iob *iob = csp->iob;
870 size_t used, offset, need, want;
873 if (n <= 0) return JB_ERR_OK;
875 used = (size_t)(iob->eod - iob->buf);
876 offset = (size_t)(iob->cur - iob->buf);
877 need = used + (size_t)n + 1;
880 * If the buffer can't hold the new data, extend it first.
881 * Use the next power of two if possible, else use the actual need.
883 if (need > csp->config->buffer_limit)
885 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
886 return JB_ERR_MEMORY;
889 if (need > iob->size)
891 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
893 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
897 else if (NULL != (p = (char *)realloc(iob->buf, need)))
903 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
904 return JB_ERR_MEMORY;
907 /* Update the iob pointers */
908 iob->cur = p + offset;
913 /* copy the new data into the iob buffer */
914 memcpy(iob->eod, buf, (size_t)n);
916 /* point to the end of the data */
919 /* null terminate == cheap insurance */
928 /*********************************************************************
930 * Function : decompress_iob
932 * Description : Decompress buffered page, expanding the
933 * buffer as necessary. csp->iob->cur
934 * should point to the the beginning of the
935 * compressed data block.
938 * 1 : csp = Current client state (buffers, headers, etc...)
940 * Returns : JB_ERR_OK on success,
941 * JB_ERR_MEMORY if out-of-memory limit reached, and
942 * JB_ERR_COMPRESS if error decompressing buffer.
944 *********************************************************************/
945 jb_err decompress_iob(struct client_state *csp)
947 char *buf; /* new, uncompressed buffer */
948 char *cur; /* Current iob position (to keep the original
949 * iob->cur unmodified if we return early) */
950 size_t bufsize; /* allocated size of the new buffer */
951 size_t old_size; /* Content size before decompression */
952 size_t skip_size; /* Number of bytes at the beginning of the iob
953 that we should NOT decompress. */
954 int status; /* return status of the inflate() call */
955 z_stream zstr; /* used by calls to zlib */
957 assert(csp->iob->cur - csp->iob->buf > 0);
958 assert(csp->iob->eod - csp->iob->cur > 0);
960 bufsize = csp->iob->size;
961 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
962 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
969 * This is to protect the parsing of gzipped data,
970 * but it should(?) be valid for deflated data also.
972 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
973 return JB_ERR_COMPRESS;
976 if (csp->content_type & CT_GZIP)
979 * Our task is slightly complicated by the facts that data
980 * compressed by gzip does not include a zlib header, and
981 * that there is no easily accessible interface in zlib to
982 * handle a gzip header. We strip off the gzip header by
983 * hand, and later inform zlib not to expect a header.
987 * Strip off the gzip header. Please see RFC 1952 for more
988 * explanation of the appropriate fields.
990 if ((*cur++ != (char)0x1f)
991 || (*cur++ != (char)0x8b)
992 || (*cur++ != Z_DEFLATED))
994 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
995 return JB_ERR_COMPRESS;
1001 * XXX: These magic numbers should be replaced
1002 * with macros to give a better idea what they do.
1006 /* The gzip header has reserved bits set; bail out. */
1007 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1008 return JB_ERR_COMPRESS;
1012 /* Skip extra fields if necessary. */
1016 * Skip a given number of bytes, specified
1017 * as a 16-bit little-endian value.
1020 * XXX: This code used to be:
1022 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1024 * which I had to change into:
1026 * cur += *cur++ + (*cur++ << 8);
1028 * at which point gcc43 finally noticed that the value
1029 * of cur is undefined (it depends on which of the
1030 * summands is evaluated first).
1032 * I haven't come across a site where this
1033 * code is actually executed yet, but I hope
1037 skip_bytes = *cur++;
1038 skip_bytes = *cur++ << 8;
1040 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1043 * The number of bytes to skip should be positive
1044 * and we'd like to stay in the buffer.
1046 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1048 log_error (LOG_LEVEL_ERROR,
1049 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1051 return JB_ERR_COMPRESS;
1053 log_error (LOG_LEVEL_INFO,
1054 "Skipping %d bytes for gzip compression. Does this sound right?",
1059 /* Skip the filename if necessary. */
1062 /* A null-terminated string is supposed to follow. */
1063 while (*cur++ && (cur < csp->iob->eod));
1067 /* Skip the comment if necessary. */
1070 /* A null-terminated string is supposed to follow. */
1071 while (*cur++ && (cur < csp->iob->eod));
1074 /* Skip the CRC if necessary. */
1080 if (cur >= csp->iob->eod)
1083 * If the current position pointer reached or passed
1084 * the buffer end, we were obviously tricked to skip
1087 log_error (LOG_LEVEL_ERROR,
1088 "Malformed gzip header detected. Aborting decompression.");
1089 return JB_ERR_COMPRESS;
1093 else if (csp->content_type & CT_DEFLATE)
1096 * XXX: The debug level should be lowered
1097 * before the next stable release.
1099 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1101 * In theory (that is, according to RFC 1950), deflate-compressed
1102 * data should begin with a two-byte zlib header and have an
1103 * adler32 checksum at the end. It seems that in practice only
1104 * the raw compressed data is sent. Note that this means that
1105 * we are not RFC 1950-compliant here, but the advantage is that
1106 * this actually works. :)
1108 * We add a dummy null byte to tell zlib where the data ends,
1109 * and later inform it not to expect a header.
1111 * Fortunately, add_to_iob() has thoughtfully null-terminated
1112 * the buffer; we can just increment the end pointer to include
1119 log_error (LOG_LEVEL_ERROR,
1120 "Unable to determine compression format for decompression");
1121 return JB_ERR_COMPRESS;
1124 /* Set up the fields required by zlib. */
1125 zstr.next_in = (Bytef *)cur;
1126 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1127 zstr.zalloc = Z_NULL;
1128 zstr.zfree = Z_NULL;
1129 zstr.opaque = Z_NULL;
1132 * Passing -MAX_WBITS to inflateInit2 tells the library
1133 * that there is no zlib header.
1135 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1137 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1138 return JB_ERR_COMPRESS;
1142 * Next, we allocate new storage for the inflated data.
1143 * We don't modify the existing iob yet, so in case there
1144 * is error in decompression we can recover gracefully.
1146 buf = zalloc (bufsize);
1149 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1150 return JB_ERR_MEMORY;
1153 assert(bufsize >= skip_size);
1154 memcpy(buf, csp->iob->buf, skip_size);
1155 zstr.avail_out = bufsize - skip_size;
1156 zstr.next_out = (Bytef *)buf + skip_size;
1158 /* Try to decompress the whole stream in one shot. */
1159 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1161 /* We need to allocate more memory for the output buffer. */
1163 char *tmpbuf; /* used for realloc'ing the buffer */
1164 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1167 * If zlib wants more data then there's a problem, because
1168 * the complete compressed file should have been buffered.
1170 if (0 == zstr.avail_in)
1172 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1173 return JB_ERR_COMPRESS;
1177 * If we tried the limit and still didn't have enough
1178 * memory, just give up.
1180 if (bufsize == csp->config->buffer_limit)
1182 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1183 return JB_ERR_MEMORY;
1186 /* Try doubling the buffer size each time. */
1189 /* Don't exceed the buffer limit. */
1190 if (bufsize > csp->config->buffer_limit)
1192 bufsize = csp->config->buffer_limit;
1195 /* Try to allocate the new buffer. */
1196 tmpbuf = realloc(buf, bufsize);
1199 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1201 return JB_ERR_MEMORY;
1205 char *oldnext_out = (char *)zstr.next_out;
1208 * Update the fields for inflate() to use the new
1209 * buffer, which may be in a location different from
1212 zstr.avail_out += bufsize - oldbufsize;
1213 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1216 * Compare with an uglier method of calculating these values
1217 * that doesn't require the extra oldbufsize variable.
1219 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1220 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1221 assert(zstr.avail_out > 0);
1227 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1229 log_error(LOG_LEVEL_ERROR,
1230 "Inconsistent stream state after decompression: %s", zstr.msg);
1232 * XXX: Intentionally no return.
1234 * According to zlib.h, Z_STREAM_ERROR is returned
1235 * "if the stream state was inconsistent".
1237 * I assume in this case inflate()'s status
1238 * would also be something different than Z_STREAM_END
1239 * so this check should be redundant, but lets see.
1243 if (status != Z_STREAM_END)
1245 /* We failed to decompress the stream. */
1246 log_error(LOG_LEVEL_ERROR,
1247 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1248 return JB_ERR_COMPRESS;
1252 * Finally, we can actually update the iob, since the
1253 * decompression was successful. First, free the old
1256 freez(csp->iob->buf);
1258 /* Now, update the iob to use the new buffer. */
1259 csp->iob->buf = buf;
1260 csp->iob->cur = csp->iob->buf + skip_size;
1261 csp->iob->eod = (char *)zstr.next_out;
1262 csp->iob->size = bufsize;
1265 * Make sure the new uncompressed iob obeys some minimal
1266 * consistency conditions.
1268 if ((csp->iob->buf < csp->iob->cur)
1269 && (csp->iob->cur <= csp->iob->eod)
1270 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1272 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1275 log_error(LOG_LEVEL_RE_FILTER,
1276 "Decompression successful. Old size: %d, new size: %d.",
1277 old_size, new_size);
1281 /* zlib thinks this is OK, so lets do the same. */
1282 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1287 /* It seems that zlib did something weird. */
1288 log_error(LOG_LEVEL_ERROR,
1289 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1290 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1291 csp->iob->eod, csp->iob->buf + csp->iob->size);
1292 return JB_ERR_COMPRESS;
1298 #endif /* defined(FEATURE_ZLIB) */
1301 /*********************************************************************
1303 * Function : get_header
1305 * Description : This (odd) routine will parse the csp->iob
1308 * 1 : csp = Current client state (buffers, headers, etc...)
1310 * Returns : Any one of the following:
1312 * 1) a pointer to a dynamically allocated string that contains a header line
1313 * 2) NULL indicating that the end of the header was reached
1314 * 3) "" indicating that the end of the iob was reached before finding
1315 * a complete header line.
1317 *********************************************************************/
1318 char *get_header(struct client_state *csp)
1324 if ((iob->cur == NULL)
1325 || ((p = strchr(iob->cur, '\n')) == NULL))
1327 return(""); /* couldn't find a complete header */
1332 ret = strdup(iob->cur);
1335 /* FIXME No way to handle error properly */
1336 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1341 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1343 /* is this a blank line (i.e. the end of the header) ? */
1355 /*********************************************************************
1357 * Function : get_header_value
1359 * Description : Get the value of a given header from a chained list
1360 * of header lines or return NULL if no such header is
1361 * present in the list.
1364 * 1 : header_list = pointer to list
1365 * 2 : header_name = string with name of header to look for.
1366 * Trailing colon required, capitalization
1369 * Returns : NULL if not found, else value of header
1371 *********************************************************************/
1372 char *get_header_value(const struct list *header_list, const char *header_name)
1374 struct list_entry *cur_entry;
1378 assert(header_list);
1379 assert(header_name);
1380 length = strlen(header_name);
1382 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1386 if (!strncmpic(cur_entry->str, header_name, length))
1389 * Found: return pointer to start of value
1391 ret = (char *) (cur_entry->str + length);
1392 while (*ret && ijb_isspace(*ret)) ret++;
1406 /*********************************************************************
1408 * Function : scan_headers
1410 * Description : Scans headers, applies tags and updates action bits.
1413 * 1 : csp = Current client state (buffers, headers, etc...)
1415 * Returns : JB_ERR_OK
1417 *********************************************************************/
1418 jb_err scan_headers(struct client_state *csp)
1420 struct list_entry *h; /* Header */
1421 jb_err err = JB_ERR_OK;
1423 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1425 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1427 /* Header crunch()ed in previous run? -> ignore */
1428 if (h->str == NULL) continue;
1429 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1430 err = header_tagger(csp, h->str);
1437 /*********************************************************************
1441 * Description : add, delete or modify lines in the HTTP header streams.
1442 * On entry, it receives a linked list of headers space
1443 * that was allocated dynamically (both the list nodes
1444 * and the header contents).
1446 * As a side effect it frees the space used by the original
1450 * 1 : pats = list of patterns to match against headers
1451 * 2 : more_headers = list of functions to add more
1452 * headers (client or server)
1453 * 3 : csp = Current client state (buffers, headers, etc...)
1455 * Returns : JB_ERR_OK in case off success, or
1456 * JB_ERR_MEMORY on out-of-memory error.
1458 *********************************************************************/
1459 jb_err sed(const struct parsers pats[],
1460 const add_header_func_ptr more_headers[],
1461 struct client_state *csp)
1463 struct list_entry *p;
1464 const struct parsers *v;
1465 const add_header_func_ptr *f;
1466 jb_err err = JB_ERR_OK;
1470 * If filtering is enabled, sed is run twice,
1471 * but most of the work needs to be done only once.
1473 first_run = (more_headers != NULL ) ? 1 : 0;
1475 if (first_run) /* Parse and print */
1479 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1481 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1483 /* Header crunch()ed in previous run? -> ignore */
1484 if (p->str == NULL) continue;
1486 /* Does the current parser handle this header? */
1487 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1489 err = v->parser(csp, (char **)&(p->str));
1493 /* place any additional headers on the csp->headers list */
1494 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1499 else /* Parse only */
1502 * The second run is only needed if the body was modified
1503 * and the content-lenght has changed.
1505 if (strncmpic(csp->http->cmd, "HEAD", 4))
1507 /*XXX: Code duplication */
1508 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1510 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1512 /* Header crunch()ed in previous run? -> ignore */
1513 if (p->str == NULL) continue;
1515 /* Does the current parser handle this header? */
1516 if (strncmpic(p->str, v->str, v->len) == 0)
1518 err = v->parser(csp, (char **)&(p->str));
1530 /*********************************************************************
1532 * Function : header_tagger
1534 * Description : Executes all text substitutions from applying
1535 * tag actions and saves the result as tag.
1537 * XXX: Shares enough code with filter_header() and
1538 * pcrs_filter_response() to warrant some helper functions.
1541 * 1 : csp = Current client state (buffers, headers, etc...)
1542 * 2 : header = Header that is used as tagger input
1544 * Returns : JB_ERR_OK on success and always succeeds
1546 *********************************************************************/
1547 jb_err header_tagger(struct client_state *csp, char *header)
1549 int wanted_filter_type;
1550 int multi_action_index;
1554 struct file_list *fl;
1555 struct re_filterfile_spec *b;
1556 struct list_entry *tag_name;
1558 int found_filters = 0;
1559 const size_t header_length = strlen(header);
1561 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1563 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1564 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1568 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1569 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1572 /* Check if there are any filters */
1573 for (i = 0; i < MAX_AF_FILES; i++)
1586 if (0 == found_filters)
1588 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1592 for (i = 0; i < MAX_AF_FILES; i++)
1595 if ((NULL == fl) || (NULL == fl->f))
1598 * Either there are no filter files
1599 * left, or this filter file just
1600 * contains no valid filters.
1602 * Continue to be sure we don't miss
1603 * valid filter files that are chained
1604 * after empty or invalid ones.
1609 /* For all filters, */
1610 for (b = fl->f; b; b = b->next)
1612 if (b->type != wanted_filter_type)
1614 /* skip the ones we don't care about, */
1617 /* leaving only taggers that could apply, of which we use the ones, */
1618 for (tag_name = csp->action->multi[multi_action_index]->first;
1619 NULL != tag_name; tag_name = tag_name->next)
1621 /* that do apply, and */
1622 if (strcmp(b->name, tag_name->str) == 0)
1624 char *modified_tag = NULL;
1626 size_t size = header_length;
1627 pcrs_job *joblist = b->joblist;
1629 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1631 if (NULL == joblist)
1633 log_error(LOG_LEVEL_RE_FILTER,
1634 "Tagger %s has empty joblist. Nothing to do.", b->name);
1638 /* execute their pcrs_joblist on the header. */
1639 for (job = joblist; NULL != job; job = job->next)
1641 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1645 /* Success, continue with the modified version. */
1654 /* Tagger doesn't match */
1657 /* Regex failure, log it but continue anyway. */
1658 log_error(LOG_LEVEL_ERROR,
1659 "Problems with tagger \'%s\' and header \'%s\': %s",
1660 b->name, *header, pcrs_strerror(hits));
1662 freez(modified_tag);
1666 if (b->dynamic) pcrs_free_joblist(joblist);
1668 /* If this tagger matched */
1674 * There is to technical limitation which makes
1675 * it impossible to use empty tags, but I assume
1676 * no one would do it intentionally.
1679 log_error(LOG_LEVEL_INFO,
1680 "Tagger \'%s\' created an empty tag. Ignored.",
1685 if (!list_contains_item(csp->tags, tag))
1687 if (JB_ERR_OK != enlist(csp->tags, tag))
1689 log_error(LOG_LEVEL_ERROR,
1690 "Insufficient memory to add tag \'%s\', "
1691 "based on tagger \'%s\' and header \'%s\'",
1692 tag, b->name, *header);
1696 char *action_message;
1698 * update the action bits right away, to make
1699 * tagging based on tags set by earlier taggers
1700 * of the same kind possible.
1702 if (update_action_bits_for_tag(csp, tag))
1704 action_message = "Action bits updated accordingly.";
1708 action_message = "No action bits update necessary.";
1711 log_error(LOG_LEVEL_HEADER,
1712 "Tagger \'%s\' added tag \'%s\'. %s",
1713 b->name, tag, action_message);
1718 /* XXX: Is this log-worthy? */
1719 log_error(LOG_LEVEL_HEADER,
1720 "Tagger \'%s\' didn't add tag \'%s\'. "
1721 "Tag already present", b->name, tag);
1724 } /* if the tagger matched */
1725 } /* if the tagger applies */
1726 } /* for every tagger that could apply */
1727 } /* for all filters */
1728 } /* for all filter files */
1733 /* here begins the family of parser functions that reformat header lines */
1735 /*********************************************************************
1737 * Function : filter_header
1739 * Description : Executes all text substitutions from all applying
1740 * +(server|client)-header-filter actions on the header.
1741 * Most of the code was copied from pcrs_filter_response,
1742 * including the rather short variable names
1745 * 1 : csp = Current client state (buffers, headers, etc...)
1746 * 2 : header = On input, pointer to header to modify.
1747 * On output, pointer to the modified header, or NULL
1748 * to remove the header. This function frees the
1749 * original string if necessary.
1751 * Returns : JB_ERR_OK on success and always succeeds
1753 *********************************************************************/
1754 jb_err filter_header(struct client_state *csp, char **header)
1758 size_t size = strlen(*header);
1760 char *newheader = NULL;
1763 struct file_list *fl;
1764 struct re_filterfile_spec *b;
1765 struct list_entry *filtername;
1767 int i, found_filters = 0;
1768 int wanted_filter_type;
1769 int multi_action_index;
1771 if (csp->flags & CSP_FLAG_NO_FILTERING)
1776 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1778 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1779 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1783 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1784 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1788 * Need to check the set of re_filterfiles...
1790 for (i = 0; i < MAX_AF_FILES; i++)
1803 if (0 == found_filters)
1805 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1809 for (i = 0; i < MAX_AF_FILES; i++)
1812 if ((NULL == fl) || (NULL == fl->f))
1815 * Either there are no filter files
1816 * left, or this filter file just
1817 * contains no valid filters.
1819 * Continue to be sure we don't miss
1820 * valid filter files that are chained
1821 * after empty or invalid ones.
1826 * For all applying +filter actions, look if a filter by that
1827 * name exists and if yes, execute its pcrs_joblist on the
1830 for (b = fl->f; b; b = b->next)
1832 if (b->type != wanted_filter_type)
1834 /* Skip other filter types */
1838 for (filtername = csp->action->multi[multi_action_index]->first;
1839 filtername ; filtername = filtername->next)
1841 if (strcmp(b->name, filtername->str) == 0)
1843 int current_hits = 0;
1844 pcrs_job *joblist = b->joblist;
1846 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1848 if (NULL == joblist)
1850 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1854 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1855 *header, size, b->name);
1857 /* Apply all jobs from the joblist */
1858 for (job = joblist; NULL != job; job = job->next)
1860 matches = pcrs_execute(job, *header, size, &newheader, &size);
1863 current_hits += matches;
1864 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1866 *header = newheader;
1868 else if ( 0 == matches )
1870 /* Filter doesn't change header */
1876 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1877 *header, b->name, pcrs_strerror(matches));
1878 if( newheader != NULL)
1880 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1886 if (b->dynamic) pcrs_free_joblist(joblist);
1888 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1889 hits += current_hits;
1896 * Additionally checking for hits is important because if
1897 * the continue hack is triggered, server headers can
1898 * arrive empty to separate multiple heads from each other.
1900 if ((0 == size) && hits)
1902 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1910 /*********************************************************************
1912 * Function : connection
1914 * Description : Makes sure that the value of the Connection: header
1915 * is "close" and signals connection_close_adder
1919 * 1 : csp = Current client state (buffers, headers, etc...)
1920 * 2 : header = On input, pointer to header to modify.
1921 * On output, pointer to the modified header, or NULL
1922 * to remove the header. This function frees the
1923 * original string if necessary.
1925 * Returns : JB_ERR_OK on success, or
1926 * JB_ERR_MEMORY on out-of-memory error.
1928 *********************************************************************/
1929 jb_err connection(struct client_state *csp, char **header)
1931 char *old_header = *header;
1933 /* Do we have a 'Connection: close' header? */
1934 if (strcmpic(*header, "Connection: close"))
1936 /* No, create one */
1937 *header = strdup("Connection: close");
1940 return JB_ERR_MEMORY;
1942 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1946 /* Signal connection_close_adder() to return early. */
1947 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1949 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
1953 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
1960 /*********************************************************************
1962 * Function : crumble
1964 * Description : This is called if a header matches a pattern to "crunch"
1967 * 1 : csp = Current client state (buffers, headers, etc...)
1968 * 2 : header = On input, pointer to header to modify.
1969 * On output, pointer to the modified header, or NULL
1970 * to remove the header. This function frees the
1971 * original string if necessary.
1973 * Returns : JB_ERR_OK on success, or
1974 * JB_ERR_MEMORY on out-of-memory error.
1976 *********************************************************************/
1977 jb_err crumble(struct client_state *csp, char **header)
1979 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1984 /*********************************************************************
1986 * Function : crunch_server_header
1988 * Description : Crunch server header if it matches a string supplied by the
1989 * user. Called from `sed'.
1992 * 1 : csp = Current client state (buffers, headers, etc...)
1993 * 2 : header = On input, pointer to header to modify.
1994 * On output, pointer to the modified header, or NULL
1995 * to remove the header. This function frees the
1996 * original string if necessary.
1998 * Returns : JB_ERR_OK on success and always succeeds
2000 *********************************************************************/
2001 jb_err crunch_server_header(struct client_state *csp, char **header)
2003 const char *crunch_pattern;
2005 /* Do we feel like crunching? */
2006 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2008 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2010 /* Is the current header the lucky one? */
2011 if (strstr(*header, crunch_pattern))
2013 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2022 /*********************************************************************
2024 * Function : server_content_type
2026 * Description : Set the content-type for filterable types (text/.*,
2027 * .*xml.*, javascript and image/gif) unless filtering has been
2028 * forbidden (CT_TABOO) while parsing earlier headers.
2029 * NOTE: Since text/plain is commonly used by web servers
2030 * for files whose correct type is unknown, we don't
2031 * set CT_TEXT for it.
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, or
2041 * JB_ERR_MEMORY on out-of-memory error.
2043 *********************************************************************/
2044 jb_err server_content_type(struct client_state *csp, char **header)
2046 /* Remove header if it isn't the first Content-Type header */
2047 if ((csp->content_type & CT_DECLARED))
2050 * Another, slightly slower, way to see if
2051 * we already parsed another Content-Type header.
2053 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2055 log_error(LOG_LEVEL_ERROR,
2056 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2064 * Signal that the Content-Type has been set.
2066 csp->content_type |= CT_DECLARED;
2068 if (!(csp->content_type & CT_TABOO))
2070 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2071 || strstr(*header, "xml")
2072 || strstr(*header, "application/x-javascript"))
2074 csp->content_type |= CT_TEXT;
2076 else if (strstr(*header, " image/gif"))
2078 csp->content_type |= CT_GIF;
2080 else if (strstr(*header, " image/jpeg"))
2082 csp->content_type |= CT_JPEG;
2087 * Are we messing with the content type?
2089 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2092 * Make sure the user doesn't accidently
2093 * change the content type of binary documents.
2095 if (csp->content_type & CT_TEXT)
2098 *header = strdup("Content-Type: ");
2099 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2103 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2104 return JB_ERR_MEMORY;
2106 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2110 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2111 "Enable force-text-mode if you know what you're doing.", *header);
2119 /*********************************************************************
2121 * Function : server_transfer_coding
2123 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2124 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2125 * - Remove header if body was chunked but has been
2126 * de-chunked for filtering.
2129 * 1 : csp = Current client state (buffers, headers, etc...)
2130 * 2 : header = On input, pointer to header to modify.
2131 * On output, pointer to the modified header, or NULL
2132 * to remove the header. This function frees the
2133 * original string if necessary.
2135 * Returns : JB_ERR_OK on success, or
2136 * JB_ERR_MEMORY on out-of-memory error.
2138 *********************************************************************/
2139 jb_err server_transfer_coding(struct client_state *csp, char **header)
2142 * Turn off pcrs and gif filtering if body compressed
2144 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2148 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2150 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2151 csp->http->cmd, *header);
2152 #endif /* def FEATURE_ZLIB */
2153 csp->content_type = CT_TABOO;
2157 * Raise flag if body chunked
2159 if (strstr(*header, "chunked"))
2161 csp->flags |= CSP_FLAG_CHUNKED;
2164 * If the body was modified, it has been de-chunked first
2165 * and the header must be removed.
2167 * FIXME: If there is more than one transfer encoding,
2168 * only the "chunked" part should be removed here.
2170 if (csp->flags & CSP_FLAG_MODIFIED)
2172 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2181 /*********************************************************************
2183 * Function : server_content_encoding
2185 * Description : This function is run twice for each request,
2186 * unless FEATURE_ZLIB and filtering are disabled.
2188 * The first run is used to check if the content
2189 * is compressed, if FEATURE_ZLIB is disabled
2190 * filtering is then disabled as well, if FEATURE_ZLIB
2191 * is enabled the content is marked for decompression.
2193 * The second run is used to remove the Content-Encoding
2194 * header if the decompression was successful.
2197 * 1 : csp = Current client state (buffers, headers, etc...)
2198 * 2 : header = On input, pointer to header to modify.
2199 * On output, pointer to the modified header, or NULL
2200 * to remove the header. This function frees the
2201 * original string if necessary.
2203 * Returns : JB_ERR_OK on success, or
2204 * JB_ERR_MEMORY on out-of-memory error.
2206 *********************************************************************/
2207 jb_err server_content_encoding(struct client_state *csp, char **header)
2210 if ((csp->flags & CSP_FLAG_MODIFIED)
2211 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2214 * We successfully decompressed the content,
2215 * and have to clean the header now, so the
2216 * client no longer expects compressed data..
2218 * XXX: There is a difference between cleaning
2219 * and removing it completely.
2221 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2224 else if (strstr(*header, "gzip"))
2226 /* Mark for gzip decompression */
2227 csp->content_type |= CT_GZIP;
2229 else if (strstr(*header, "deflate"))
2231 /* Mark for zlib decompression */
2232 csp->content_type |= CT_DEFLATE;
2234 else if (strstr(*header, "compress"))
2237 * We can't decompress this; therefore we can't filter
2240 csp->content_type |= CT_TABOO;
2242 #else /* !defined(FEATURE_ZLIB) */
2243 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2246 * Body is compressed, turn off pcrs and gif filtering.
2248 csp->content_type |= CT_TABOO;
2251 * Log a warning if the user expects the content to be filtered.
2253 if ((csp->rlist != NULL) &&
2254 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2256 log_error(LOG_LEVEL_INFO,
2257 "Compressed content detected, content filtering disabled. "
2258 "Consider recompiling Privoxy with zlib support or "
2259 "enable the prevent-compression action.");
2262 #endif /* defined(FEATURE_ZLIB) */
2269 /*********************************************************************
2271 * Function : server_content_length
2273 * Description : Adjust Content-Length header if we modified
2277 * 1 : csp = Current client state (buffers, headers, etc...)
2278 * 2 : header = On input, pointer to header to modify.
2279 * On output, pointer to the modified header, or NULL
2280 * to remove the header. This function frees the
2281 * original string if necessary.
2283 * Returns : JB_ERR_OK on success, or
2284 * JB_ERR_MEMORY on out-of-memory error.
2286 *********************************************************************/
2287 jb_err server_content_length(struct client_state *csp, char **header)
2289 const size_t max_header_length = 80;
2291 /* Regenerate header if the content was modified. */
2292 if (csp->flags & CSP_FLAG_MODIFIED)
2295 *header = (char *) zalloc(max_header_length);
2296 if (*header == NULL)
2298 return JB_ERR_MEMORY;
2301 snprintf(*header, max_header_length, "Content-Length: %d",
2302 (int)csp->content_length);
2303 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2304 (int)csp->content_length);
2311 /*********************************************************************
2313 * Function : server_content_md5
2315 * Description : Crumble any Content-MD5 headers if the document was
2316 * modified. FIXME: Should we re-compute instead?
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 jb_err server_content_md5(struct client_state *csp, char **header)
2331 if (csp->flags & CSP_FLAG_MODIFIED)
2333 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2340 /*********************************************************************
2342 * Function : server_content_disposition
2344 * Description : If enabled, blocks or modifies the "content-disposition" header.
2345 * Called from `sed'.
2348 * 1 : csp = Current client state (buffers, headers, etc...)
2349 * 2 : header = On input, pointer to header to modify.
2350 * On output, pointer to the modified header, or NULL
2351 * to remove the header. This function frees the
2352 * original string if necessary.
2354 * Returns : JB_ERR_OK on success, or
2355 * JB_ERR_MEMORY on out-of-memory error.
2357 *********************************************************************/
2358 jb_err server_content_disposition(struct client_state *csp, char **header)
2363 * Are we messing with the content-disposition header?
2365 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2371 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2373 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2376 * Blocking content-disposition header
2378 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2385 * Replacing content-disposition header
2388 *header = strdup("content-disposition: ");
2389 string_append(header, newval);
2391 if (*header == NULL)
2393 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2397 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2400 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2403 /*********************************************************************
2405 * Function : server_last_modified
2407 * Description : Changes Last-Modified header to the actual date
2408 * to help hide-if-modified-since.
2409 * Called from `sed'.
2412 * 1 : csp = Current client state (buffers, headers, etc...)
2413 * 2 : header = On input, pointer to header to modify.
2414 * On output, pointer to the modified header, or NULL
2415 * to remove the header. This function frees the
2416 * original string if necessary.
2418 * Returns : JB_ERR_OK on success, or
2419 * JB_ERR_MEMORY on out-of-memory error.
2421 *********************************************************************/
2422 jb_err server_last_modified(struct client_state *csp, char **header)
2425 char buf[BUFFER_SIZE];
2428 #ifdef HAVE_GMTIME_R
2431 struct tm *timeptr = NULL;
2432 time_t now, last_modified;
2434 long int days, hours, minutes, seconds;
2437 * Are we messing with the Last-Modified header?
2439 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2445 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2447 if (0 == strcmpic(newval, "block") )
2450 * Blocking Last-Modified header. Useless but why not.
2452 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2456 else if (0 == strcmpic(newval, "reset-to-request-time"))
2459 * Setting Last-Modified Header to now.
2461 get_http_time(0, buf);
2463 *header = strdup("Last-Modified: ");
2464 string_append(header, buf);
2466 if (*header == NULL)
2468 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2472 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2475 else if (0 == strcmpic(newval, "randomize"))
2477 const char *header_time = *header + sizeof("Last-Modified:");
2479 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2481 #ifdef HAVE_GMTIME_R
2482 timeptr = gmtime_r(&now, &gmt);
2483 #elif FEATURE_PTHREAD
2484 pthread_mutex_lock(&gmtime_mutex);
2485 timeptr = gmtime(&now);
2486 pthread_mutex_unlock(&gmtime_mutex);
2488 timeptr = gmtime(&now);
2490 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2492 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2497 rtime = (long int)difftime(now, last_modified);
2500 rtime = pick_from_range(rtime);
2501 last_modified += rtime;
2502 #ifdef HAVE_GMTIME_R
2503 timeptr = gmtime_r(&last_modified, &gmt);
2504 #elif FEATURE_PTHREAD
2505 pthread_mutex_lock(&gmtime_mutex);
2506 timeptr = gmtime(&last_modified);
2507 pthread_mutex_unlock(&gmtime_mutex);
2509 timeptr = gmtime(&last_modified);
2511 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2513 *header = strdup("Last-Modified: ");
2514 string_append(header, newheader);
2516 if (*header == NULL)
2518 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2519 return JB_ERR_MEMORY;
2522 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2524 days = rtime / (3600 * 24);
2525 hours = rtime / 3600 % 24;
2526 minutes = rtime / 60 % 60;
2527 seconds = rtime % 60;
2529 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2530 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2531 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2536 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2545 /*********************************************************************
2547 * Function : client_accept_encoding
2549 * Description : Rewrite the client's Accept-Encoding header so that
2550 * if doesn't allow compression, if the action applies.
2551 * Note: For HTTP/1.0 the absence of the header is enough.
2554 * 1 : csp = Current client state (buffers, headers, etc...)
2555 * 2 : header = On input, pointer to header to modify.
2556 * On output, pointer to the modified header, or NULL
2557 * to remove the header. This function frees the
2558 * original string if necessary.
2560 * Returns : JB_ERR_OK on success, or
2561 * JB_ERR_MEMORY on out-of-memory error.
2563 *********************************************************************/
2564 jb_err client_accept_encoding(struct client_state *csp, char **header)
2566 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2568 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2572 /* Temporarily disable the correct behaviour to
2573 * work around a PHP bug.
2575 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2577 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2578 * if (*header == NULL)
2580 * return JB_ERR_MEMORY;
2591 /*********************************************************************
2593 * Function : client_te
2595 * Description : Rewrite the client's TE header so that
2596 * if doesn't allow compression, if the action applies.
2599 * 1 : csp = Current client state (buffers, headers, etc...)
2600 * 2 : header = On input, pointer to header to modify.
2601 * On output, pointer to the modified header, or NULL
2602 * to remove the header. This function frees the
2603 * original string if necessary.
2605 * Returns : JB_ERR_OK on success, or
2606 * JB_ERR_MEMORY on out-of-memory error.
2608 *********************************************************************/
2609 jb_err client_te(struct client_state *csp, char **header)
2611 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2614 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2620 /*********************************************************************
2622 * Function : client_referrer
2624 * Description : Handle the "referer" config setting properly.
2625 * Called from `sed'.
2628 * 1 : csp = Current client state (buffers, headers, etc...)
2629 * 2 : header = On input, pointer to header to modify.
2630 * On output, pointer to the modified header, or NULL
2631 * to remove the header. This function frees the
2632 * original string if necessary.
2634 * Returns : JB_ERR_OK on success, or
2635 * JB_ERR_MEMORY on out-of-memory error.
2637 *********************************************************************/
2638 jb_err client_referrer(struct client_state *csp, char **header)
2645 #ifdef FEATURE_FORCE_LOAD
2646 /* Since the referrer can include the prefix even
2647 * if the request itself is non-forced, we must
2648 * clean it unconditionally
2650 strclean(*header, FORCE_PREFIX);
2651 #endif /* def FEATURE_FORCE_LOAD */
2654 * Are we sending referer?
2656 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2661 newval = csp->action->string[ACTION_STRING_REFERER];
2663 if ((0 != strcmpic(newval, "conditional-block")))
2667 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2672 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2675 else if (0 == strcmpic(newval, "conditional-block"))
2678 * Block referer if host has changed.
2681 if (NULL == (host = strdup(csp->http->hostport)))
2684 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2685 return JB_ERR_MEMORY;
2687 if (NULL == (referer = strdup(*header)))
2691 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2692 return JB_ERR_MEMORY;
2694 hostlenght = strlen(host);
2695 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2697 /*Shorten referer to make sure the referer is blocked
2698 *if www.example.org/www.example.com-shall-see-the-referer/
2699 *links to www.example.com/
2701 referer[hostlenght+17] = '\0';
2703 if ( 0 == strstr(referer, host)) /*Host has changed*/
2705 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2710 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2716 else if (0 != strcmpic(newval, "forge"))
2719 * We have a specific (fixed) referer we want to send.
2721 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2723 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2725 *header = strdup("Referer: ");
2726 string_append(header, newval);
2727 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2729 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2734 * Forge a referer as http://[hostname:port of REQUEST]/
2735 * to fool stupid checks for in-site links
2738 *header = strdup("Referer: http://");
2739 string_append(header, csp->http->hostport);
2740 string_append(header, "/");
2741 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2743 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2747 /*********************************************************************
2749 * Function : client_accept_language
2751 * Description : Handle the "Accept-Language" config setting properly.
2752 * Called from `sed'.
2755 * 1 : csp = Current client state (buffers, headers, etc...)
2756 * 2 : header = On input, pointer to header to modify.
2757 * On output, pointer to the modified header, or NULL
2758 * to remove the header. This function frees the
2759 * original string if necessary.
2761 * Returns : JB_ERR_OK on success, or
2762 * JB_ERR_MEMORY on out-of-memory error.
2764 *********************************************************************/
2765 jb_err client_accept_language(struct client_state *csp, char **header)
2770 * Are we messing with the Accept-Language?
2772 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2774 /*I don't think so*/
2778 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2780 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2783 * Blocking Accept-Language header
2785 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2792 * Replacing Accept-Language header
2795 *header = strdup("Accept-Language: ");
2796 string_append(header, newval);
2798 if (*header == NULL)
2800 log_error(LOG_LEVEL_ERROR,
2801 "Insufficent memory. Accept-Language header crunched without replacement.");
2805 log_error(LOG_LEVEL_HEADER,
2806 "Accept-Language header crunched and replaced with: %s", *header);
2809 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2812 /*********************************************************************
2814 * Function : crunch_client_header
2816 * Description : Crunch client header if it matches a string supplied by the
2817 * user. Called from `sed'.
2820 * 1 : csp = Current client state (buffers, headers, etc...)
2821 * 2 : header = On input, pointer to header to modify.
2822 * On output, pointer to the modified header, or NULL
2823 * to remove the header. This function frees the
2824 * original string if necessary.
2826 * Returns : JB_ERR_OK on success and always succeeds
2828 *********************************************************************/
2829 jb_err crunch_client_header(struct client_state *csp, char **header)
2831 const char *crunch_pattern;
2833 /* Do we feel like crunching? */
2834 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2836 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2838 /* Is the current header the lucky one? */
2839 if (strstr(*header, crunch_pattern))
2841 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2849 /*********************************************************************
2851 * Function : client_uagent
2853 * Description : Handle the "user-agent" config setting properly
2854 * and remember its original value to enable browser
2855 * bug workarounds. Called from `sed'.
2858 * 1 : csp = Current client state (buffers, headers, etc...)
2859 * 2 : header = On input, pointer to header to modify.
2860 * On output, pointer to the modified header, or NULL
2861 * to remove the header. This function frees the
2862 * original string if necessary.
2864 * Returns : JB_ERR_OK on success, or
2865 * JB_ERR_MEMORY on out-of-memory error.
2867 *********************************************************************/
2868 jb_err client_uagent(struct client_state *csp, char **header)
2872 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2877 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2884 *header = strdup("User-Agent: ");
2885 string_append(header, newval);
2887 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2889 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2892 /*********************************************************************
2894 * Function : client_ua
2896 * Description : Handle "ua-" headers properly. Called from `sed'.
2899 * 1 : csp = Current client state (buffers, headers, etc...)
2900 * 2 : header = On input, pointer to header to modify.
2901 * On output, pointer to the modified header, or NULL
2902 * to remove the header. This function frees the
2903 * original string if necessary.
2905 * Returns : JB_ERR_OK on success, or
2906 * JB_ERR_MEMORY on out-of-memory error.
2908 *********************************************************************/
2909 jb_err client_ua(struct client_state *csp, char **header)
2911 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2913 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2921 /*********************************************************************
2923 * Function : client_from
2925 * Description : Handle the "from" config setting properly.
2926 * Called from `sed'.
2929 * 1 : csp = Current client state (buffers, headers, etc...)
2930 * 2 : header = On input, pointer to header to modify.
2931 * On output, pointer to the modified header, or NULL
2932 * to remove the header. This function frees the
2933 * original string if necessary.
2935 * Returns : JB_ERR_OK on success, or
2936 * JB_ERR_MEMORY on out-of-memory error.
2938 *********************************************************************/
2939 jb_err client_from(struct client_state *csp, char **header)
2943 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2950 newval = csp->action->string[ACTION_STRING_FROM];
2953 * Are we blocking the e-mail address?
2955 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2957 log_error(LOG_LEVEL_HEADER, "crunched From!");
2961 log_error(LOG_LEVEL_HEADER, " modified");
2963 *header = strdup("From: ");
2964 string_append(header, newval);
2966 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2970 /*********************************************************************
2972 * Function : client_send_cookie
2974 * Description : Crunches the "cookie" header if necessary.
2975 * Called from `sed'.
2977 * XXX: Stupid name, doesn't send squat.
2980 * 1 : csp = Current client state (buffers, headers, etc...)
2981 * 2 : header = On input, pointer to header to modify.
2982 * On output, pointer to the modified header, or NULL
2983 * to remove the header. This function frees the
2984 * original string if necessary.
2986 * Returns : JB_ERR_OK on success, or
2987 * JB_ERR_MEMORY on out-of-memory error.
2989 *********************************************************************/
2990 jb_err client_send_cookie(struct client_state *csp, char **header)
2992 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2994 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3002 /*********************************************************************
3004 * Function : client_x_forwarded
3006 * Description : Handle the "x-forwarded-for" config setting properly,
3007 * also used in the add_client_headers list. Called from `sed'.
3010 * 1 : csp = Current client state (buffers, headers, etc...)
3011 * 2 : header = On input, pointer to header to modify.
3012 * On output, pointer to the modified header, or NULL
3013 * to remove the header. This function frees the
3014 * original string if necessary.
3016 * Returns : JB_ERR_OK on success, or
3017 * JB_ERR_MEMORY on out-of-memory error.
3019 *********************************************************************/
3020 jb_err client_x_forwarded(struct client_state *csp, char **header)
3022 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3024 /* Save it so we can re-add it later */
3025 freez(csp->x_forwarded);
3026 csp->x_forwarded = *header;
3029 * Always set *header = NULL, since this information
3030 * will be sent at the end of the header.
3037 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3044 /*********************************************************************
3046 * Function : client_max_forwards
3048 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3049 * from the value of the Max-Forwards header field.
3052 * 1 : csp = Current client state (buffers, headers, etc...)
3053 * 2 : header = On input, pointer to header to modify.
3054 * On output, pointer to the modified header, or NULL
3055 * to remove the header. This function frees the
3056 * original string if necessary.
3058 * Returns : JB_ERR_OK on success, or
3059 * JB_ERR_MEMORY on out-of-memory error.
3061 *********************************************************************/
3062 jb_err client_max_forwards(struct client_state *csp, char **header)
3066 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3067 (0 == strcmpic(csp->http->gpc, "options")))
3069 assert(*(*header+12) == ':');
3070 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3072 if (max_forwards > 0)
3074 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3075 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3076 csp->http->gpc, max_forwards);
3078 else if (max_forwards < 0)
3080 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3086 * Not supposed to be reached. direct_response() which
3087 * was already called earlier in chat() should have
3088 * intercepted the request.
3090 log_error(LOG_LEVEL_ERROR,
3091 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3092 assert(max_forwards != 0);
3097 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3106 /*********************************************************************
3108 * Function : client_host
3110 * Description : If the request URI did not contain host and
3111 * port information, parse and evaluate the Host
3114 * Also, kill ill-formed HOST: headers as sent by
3115 * Apple's iTunes software when used with a proxy.
3118 * 1 : csp = Current client state (buffers, headers, etc...)
3119 * 2 : header = On input, pointer to header to modify.
3120 * On output, pointer to the modified header, or NULL
3121 * to remove the header. This function frees the
3122 * original string if necessary.
3124 * Returns : JB_ERR_OK on success, or
3125 * JB_ERR_MEMORY on out-of-memory error.
3127 *********************************************************************/
3128 jb_err client_host(struct client_state *csp, char **header)
3133 * If the header field name is all upper-case, chances are that it's
3134 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3135 * not a problem -- they are regenerated later.
3137 if ((*header)[1] == 'O')
3139 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3144 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3145 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3148 if (NULL == (p = strdup((*header)+6)))
3150 return JB_ERR_MEMORY;
3153 if (NULL == (q = strdup(p)))
3156 return JB_ERR_MEMORY;
3159 freez(csp->http->hostport);
3160 csp->http->hostport = p;
3161 freez(csp->http->host);
3162 csp->http->host = q;
3163 q = strchr(csp->http->host, ':');
3166 /* Terminate hostname and evaluate port string */
3168 csp->http->port = atoi(q);
3172 csp->http->port = csp->http->ssl ? 443 : 80;
3175 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3176 csp->http->hostport, csp->http->host, csp->http->port);
3179 /* Signal client_host_adder() to return right away */
3180 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3185 /*********************************************************************
3187 * Function : client_if_modified_since
3189 * Description : Remove or modify the If-Modified-Since header.
3192 * 1 : csp = Current client state (buffers, headers, etc...)
3193 * 2 : header = On input, pointer to header to modify.
3194 * On output, pointer to the modified header, or NULL
3195 * to remove the header. This function frees the
3196 * original string if necessary.
3198 * Returns : JB_ERR_OK on success, or
3199 * JB_ERR_MEMORY on out-of-memory error.
3201 *********************************************************************/
3202 jb_err client_if_modified_since(struct client_state *csp, char **header)
3205 #ifdef HAVE_GMTIME_R
3208 struct tm *timeptr = NULL;
3212 long int hours, minutes, seconds;
3216 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3219 * The client got an error message because of a temporary problem,
3220 * the problem is gone and the client now tries to revalidate our
3221 * error message on the real server. The revalidation would always
3222 * end with the transmission of the whole document and there is
3223 * no need to expose the bogus If-Modified-Since header.
3225 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3228 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3230 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3232 if ((0 == strcmpic(newval, "block")))
3234 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3237 else /* add random value */
3239 const char *header_time = *header + sizeof("If-Modified-Since:");
3241 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3243 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3248 rtime = strtol(newval, &endptr, 0);
3251 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3252 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3259 rtime = pick_from_range(rtime);
3263 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3266 tm += rtime * (negative ? -1 : 1);
3267 #ifdef HAVE_GMTIME_R
3268 timeptr = gmtime_r(&tm, &gmt);
3269 #elif FEATURE_PTHREAD
3270 pthread_mutex_lock(&gmtime_mutex);
3271 timeptr = gmtime(&tm);
3272 pthread_mutex_unlock(&gmtime_mutex);
3274 timeptr = gmtime(&tm);
3276 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3279 *header = strdup("If-Modified-Since: ");
3280 string_append(header, newheader);
3282 if (*header == NULL)
3284 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3285 return JB_ERR_MEMORY;
3288 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3290 hours = rtime / 3600;
3291 minutes = rtime / 60 % 60;
3292 seconds = rtime % 60;
3294 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3295 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3296 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3305 /*********************************************************************
3307 * Function : client_if_none_match
3309 * Description : Remove the If-None-Match header.
3312 * 1 : csp = Current client state (buffers, headers, etc...)
3313 * 2 : header = On input, pointer to header to modify.
3314 * On output, pointer to the modified header, or NULL
3315 * to remove the header. This function frees the
3316 * original string if necessary.
3318 * Returns : JB_ERR_OK on success, or
3319 * JB_ERR_MEMORY on out-of-memory error.
3321 *********************************************************************/
3322 jb_err client_if_none_match(struct client_state *csp, char **header)
3324 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3326 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3333 /*********************************************************************
3335 * Function : client_x_filter
3337 * Description : Disables filtering if the client set "X-Filter: No".
3338 * Called from `sed'.
3341 * 1 : csp = Current client state (buffers, headers, etc...)
3342 * 2 : header = On input, pointer to header to modify.
3343 * On output, pointer to the modified header, or NULL
3344 * to remove the header. This function frees the
3345 * original string if necessary.
3347 * Returns : JB_ERR_OK on success
3349 *********************************************************************/
3350 jb_err client_x_filter(struct client_state *csp, char **header)
3352 if ( 0 == strcmpic(*header, "X-Filter: No"))
3354 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3356 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3360 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3362 log_error(LOG_LEVEL_HEADER,
3363 "force-text-mode overruled the client's request to fetch without filtering!");
3367 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3368 csp->flags |= CSP_FLAG_NO_FILTERING;
3369 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3371 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3378 /* the following functions add headers directly to the header list */
3380 /*********************************************************************
3382 * Function : client_host_adder
3384 * Description : Adds the Host: header field if it is missing.
3385 * Called from `sed'.
3388 * 1 : csp = Current client state (buffers, headers, etc...)
3390 * Returns : JB_ERR_OK on success, or
3391 * JB_ERR_MEMORY on out-of-memory error.
3393 *********************************************************************/
3394 jb_err client_host_adder(struct client_state *csp)
3399 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3401 /* Header already set by the client, nothing to do. */
3405 if ( !csp->http->hostport || !*(csp->http->hostport))
3407 /* XXX: When does this happen and why is it OK? */
3408 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3413 * remove 'user:pass@' from 'proto://user:pass@host'
3415 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3421 p = csp->http->hostport;
3424 /* XXX: Just add it, we already made sure that it will be unique */
3425 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3426 err = enlist_unique_header(csp->headers, "Host", p);
3432 /*********************************************************************
3434 * Function : client_cookie_adder
3436 * Description : Used in the add_client_headers list to add "wafers".
3437 * Called from `sed'.
3440 * 1 : csp = Current client state (buffers, headers, etc...)
3442 * Returns : JB_ERR_OK on success, or
3443 * JB_ERR_MEMORY on out-of-memory error.
3445 *********************************************************************/
3446 jb_err client_cookie_adder(struct client_state *csp)
3449 struct list_entry *wafer;
3450 struct list_entry *wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3453 if (NULL == wafer_list)
3459 tmp = strdup("Cookie: ");
3461 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3463 if (wafer != wafer_list)
3465 /* As this isn't the first wafer, we need a delimiter. */
3466 string_append(&tmp, "; ");
3468 string_join(&tmp, cookie_encode(wafer->str));
3473 return JB_ERR_MEMORY;
3476 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3477 err = enlist(csp->headers, tmp);
3483 /*********************************************************************
3485 * Function : client_accept_encoding_adder
3487 * Description : Add an Accept-Encoding header to the client's request
3488 * that disables compression if the action applies, and
3489 * the header is not already there. Called from `sed'.
3490 * Note: For HTTP/1.0, the absence of the header is enough.
3493 * 1 : csp = Current client state (buffers, headers, etc...)
3495 * Returns : JB_ERR_OK on success, or
3496 * JB_ERR_MEMORY on out-of-memory error.
3498 *********************************************************************/
3499 jb_err client_accept_encoding_adder(struct client_state *csp)
3501 assert(0); /* Not in use */
3503 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3504 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3506 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3513 /*********************************************************************
3515 * Function : client_xtra_adder
3517 * Description : Used in the add_client_headers list. Called from `sed'.
3520 * 1 : csp = Current client state (buffers, headers, etc...)
3522 * Returns : JB_ERR_OK on success, or
3523 * JB_ERR_MEMORY on out-of-memory error.
3525 *********************************************************************/
3526 jb_err client_xtra_adder(struct client_state *csp)
3528 struct list_entry *lst;
3531 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3532 lst ; lst = lst->next)
3534 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3535 err = enlist(csp->headers, lst->str);
3547 /*********************************************************************
3549 * Function : client_x_forwarded_adder
3551 * Description : Used in the add_client_headers list. Called from `sed'.
3554 * 1 : csp = Current client state (buffers, headers, etc...)
3556 * Returns : JB_ERR_OK on success, or
3557 * JB_ERR_MEMORY on out-of-memory error.
3559 *********************************************************************/
3560 jb_err client_x_forwarded_adder(struct client_state *csp)
3565 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3570 if (csp->x_forwarded)
3572 p = strdup(csp->x_forwarded);
3573 string_append(&p, ", ");
3577 p = strdup("X-Forwarded-For: ");
3579 string_append(&p, csp->ip_addr_str);
3583 return JB_ERR_MEMORY;
3586 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3587 err = enlist(csp->headers, p);
3594 /*********************************************************************
3596 * Function : connection_close_adder
3598 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3599 * support. Adds a "Connection: close" header to csp->headers
3600 * unless the header was already present. Called from `sed'.
3602 * FIXME: This whole function shouldn't be neccessary!
3605 * 1 : csp = Current client state (buffers, headers, etc...)
3607 * Returns : JB_ERR_OK on success, or
3608 * JB_ERR_MEMORY on out-of-memory error.
3610 *********************************************************************/
3611 jb_err connection_close_adder(struct client_state *csp)
3613 const unsigned int flags = csp->flags;
3616 * Return right away if
3618 * - we're parsing server headers and the server header
3619 * "Connection: close" is already set, or if
3621 * - we're parsing client headers and the client header
3622 * "Connection: close" is already set.
3624 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3625 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3626 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3627 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3632 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3634 return enlist(csp->headers, "Connection: close");
3638 /*********************************************************************
3640 * Function : server_http
3642 * Description : - Save the HTTP Status into csp->http->status
3643 * - Set CT_TABOO to prevent filtering if the answer
3644 * is a partial range (HTTP status 206)
3645 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3649 * 1 : csp = Current client state (buffers, headers, etc...)
3650 * 2 : header = On input, pointer to header to modify.
3651 * On output, pointer to the modified header, or NULL
3652 * to remove the header. This function frees the
3653 * original string if necessary.
3655 * Returns : JB_ERR_OK on success, or
3656 * JB_ERR_MEMORY on out-of-memory error.
3658 *********************************************************************/
3659 jb_err server_http(struct client_state *csp, char **header)
3661 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3662 if (csp->http->status == 206)
3664 csp->content_type = CT_TABOO;
3667 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3670 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3677 /*********************************************************************
3679 * Function : server_set_cookie
3681 * Description : Handle the server "cookie" header properly.
3682 * Log cookie to the jar file. Then "crunch",
3683 * accept or rewrite it to a session cookie.
3684 * Called from `sed'.
3686 * TODO: Allow the user to specify a new expiration
3687 * time to cause the cookie to expire even before the
3688 * browser is closed.
3691 * 1 : csp = Current client state (buffers, headers, etc...)
3692 * 2 : header = On input, pointer to header to modify.
3693 * On output, pointer to the modified header, or NULL
3694 * to remove the header. This function frees the
3695 * original string if necessary.
3697 * Returns : JB_ERR_OK on success, or
3698 * JB_ERR_MEMORY on out-of-memory error.
3700 *********************************************************************/
3701 jb_err server_set_cookie(struct client_state *csp, char **header)
3708 #ifdef FEATURE_COOKIE_JAR
3709 if (csp->config->jar)
3712 * Write timestamp into outbuf.
3714 * Complex because not all OSs have tm_gmtoff or
3715 * the %z field in strftime()
3717 char tempbuf[ BUFFER_SIZE ];
3719 #ifdef HAVE_LOCALTIME_R
3720 tm_now = *localtime_r(&now, &tm_now);
3721 #elif FEATURE_PTHREAD
3722 pthread_mutex_lock(&localtime_mutex);
3723 tm_now = *localtime (&now);
3724 pthread_mutex_unlock(&localtime_mutex);
3726 tm_now = *localtime (&now);
3728 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3730 /* strlen("set-cookie: ") = 12 */
3731 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3733 #endif /* def FEATURE_COOKIE_JAR */
3735 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3737 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3740 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3742 /* Flag whether or not to log a message */
3745 /* A variable to store the tag we're working on */
3748 /* Skip "Set-Cookie:" (11 characters) in header */
3749 cur_tag = *header + 11;
3751 /* skip whitespace between "Set-Cookie:" and value */
3752 while (*cur_tag && ijb_isspace(*cur_tag))
3757 /* Loop through each tag in the cookie */
3761 char *next_tag = strchr(cur_tag, ';');
3762 if (next_tag != NULL)
3764 /* Skip the ';' character itself */
3767 /* skip whitespace ";" and start of tag */
3768 while (*next_tag && ijb_isspace(*next_tag))
3775 /* "Next tag" is the end of the string */
3776 next_tag = cur_tag + strlen(cur_tag);
3780 * Check the expiration date to see
3781 * if the cookie is still valid, if yes,
3782 * rewrite it to a session cookie.
3784 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3786 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3788 /* Did we detect the date properly? */
3789 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3792 * Nope, treat it as if it was still valid.
3794 * XXX: Should we remove the whole cookie instead?
3796 log_error(LOG_LEVEL_ERROR,
3797 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3798 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3804 * Yes. Check if the cookie is still valid.
3806 * If the cookie is already expired it's probably
3807 * a delete cookie and even if it isn't, the browser
3808 * will discard it anyway.
3812 * XXX: timegm() isn't available on some AmigaOS
3813 * versions and our replacement doesn't work.
3815 * Our options are to either:
3817 * - disable session-cookies-only completely if timegm
3820 * - to simply remove all expired tags, like it has
3821 * been done until Privoxy 3.0.6 and to live with
3822 * the consequence that it can cause login/logout
3823 * problems on servers that don't validate their
3824 * input properly, or
3826 * - to replace it with mktime in which
3827 * case there is a slight chance of valid cookies
3828 * passing as already expired.
3830 * This is the way it's currently done and it's not
3831 * as bad as it sounds. If the missing GMT offset is
3832 * enough to change the result of the expiration check
3833 * the cookie will be only valid for a few hours
3834 * anyway, which in many cases will be shorter
3835 * than a browser session.
3837 if (cookie_time - now < 0)
3839 log_error(LOG_LEVEL_HEADER,
3840 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3841 /* Just in case some clown sets more then one expiration date */
3847 * Still valid, delete expiration date by copying
3848 * the rest of the string over it.
3850 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3851 * since the behaviour of strcpy is undefined for overlapping
3854 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3856 /* That changed the header, need to issue a log message */
3860 * Note that the next tag has now been moved to *cur_tag,
3861 * so we do not need to update the cur_tag pointer.
3869 /* Move on to next cookie tag */
3876 assert(NULL != *header);
3877 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3886 #ifdef FEATURE_FORCE_LOAD
3887 /*********************************************************************
3889 * Function : strclean
3891 * Description : In-Situ-Eliminate all occurances of substring in
3895 * 1 : string = string to clean
3896 * 2 : substring = substring to eliminate
3898 * Returns : Number of eliminations
3900 *********************************************************************/
3901 int strclean(const char *string, const char *substring)
3907 len = strlen(substring);
3909 while((pos = strstr(string, substring)) != NULL)
3916 while (*p++ != '\0');
3923 #endif /* def FEATURE_FORCE_LOAD */
3925 /*********************************************************************
3927 * Function : parse_header_time
3929 * Description : Parses time formats used in HTTP header strings
3930 * to get the numerical respresentation.
3933 * 1 : header_time = HTTP header time as string.
3934 * 2 : result = storage for header_time in seconds
3936 * Returns : JB_ERR_OK if the time format was recognized, or
3937 * JB_ERR_PARSE otherwise.
3939 *********************************************************************/
3940 jb_err parse_header_time(const char *header_time, time_t *result)
3945 * Zero out gmt to prevent time zone offsets.
3947 * While this is only necessary on some platforms
3948 * (mingw32 for example), I don't know how to
3949 * detect these automatically and doing it everywhere
3952 memset(&gmt, 0, sizeof(gmt));
3954 /* Tue, 02 Jun 2037 20:00:00 */
3955 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3956 /* Tue, 02-Jun-2037 20:00:00 */
3957 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3958 /* Tue, 02-Jun-37 20:00:00 */
3959 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3960 /* Tuesday, 02-Jun-2037 20:00:00 */
3961 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3962 /* Tuesday Jun 02 20:00:00 2037 */
3963 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3965 return JB_ERR_PARSE;
3968 *result = timegm(&gmt);
3974 /*********************************************************************
3976 * Function : get_destination_from_headers
3978 * Description : Parse the "Host:" header to get the request's destination.
3979 * Only needed if the client's request was forcefully
3980 * redirected into Privoxy.
3982 * Code mainly copied from client_host() which is currently
3983 * run too late for this purpose.
3986 * 1 : headers = List of headers (one of them hopefully being
3987 * the "Host:" header)
3988 * 2 : http = storage for the result (host, port and hostport).
3990 * Returns : JB_ERR_MEMORY in case of memory problems,
3991 * JB_ERR_PARSE if the host header couldn't be found,
3992 * JB_ERR_OK otherwise.
3994 *********************************************************************/
3995 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4001 host = get_header_value(headers, "Host:");
4005 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4006 return JB_ERR_PARSE;
4009 if (NULL == (p = strdup((host))))
4011 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4012 return JB_ERR_MEMORY;
4015 if (NULL == (q = strdup(p)))
4018 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4019 return JB_ERR_MEMORY;
4022 freez(http->hostport);
4026 q = strchr(http->host, ':');
4029 /* Terminate hostname and evaluate port string */
4031 http->port = atoi(q);
4035 http->port = http->ssl ? 443 : 80;
4038 /* Rebuild request URL */
4040 http->url = strdup(http->ssl ? "https://" : "http://");
4041 string_append(&http->url, http->hostport);
4042 string_append(&http->url, http->path);
4043 if (http->url == NULL)
4045 return JB_ERR_MEMORY;
4048 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",