1 const char parsers_rcs[] = "$Id: parsers.c,v 1.99 2007/04/30 15:06:26 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.99 2007/04/30 15:06:26 fabiankeil
48 * - Introduce dynamic pcrs jobs that can resolve variables.
49 * - Remove unnecessary update_action_bits_for_all_tags() call.
51 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
52 * - Make tagging based on tags set by earlier taggers
53 * of the same kind possible.
54 * - Log whether or not new tags cause action bits updates
55 * (in which case a matching tag-pattern section exists).
56 * - Log if the user tries to set a tag that is already set.
58 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
59 * Introduce tags as alternative way to specify which
60 * actions apply to a request. At the moment tags can be
61 * created based on client and server headers.
63 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
64 * Log a warning if the content is compressed, filtering is
65 * enabled and Privoxy was compiled without zlib support.
68 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
69 * - Fix warnings when compiled with glibc.
70 * - Don't use crumble() for cookie crunching.
71 * - Move cookie time parsing into parse_header_time().
72 * - Let parse_header_time() return a jb_err code
73 * instead of a pointer that can only be used to
74 * check for NULL anyway.
76 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
77 * - Add better protection against malicious gzip headers.
78 * - Stop logging the first hundred bytes of decompressed content.
79 * It looks like it's working and there is always debug 16.
80 * - Log the content size after decompression in decompress_iob()
81 * instead of pcrs_filter_response().
83 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
84 * - Use dedicated header filter actions instead of abusing "filter".
85 * Replace "filter-client-headers" and "filter-client-headers"
86 * with "server-header-filter" and "client-header-filter".
87 * - Remove filter_client_header() and filter_client_header(),
88 * filter_header() now checks the shiny new
89 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
91 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
92 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
93 * - Handle "Cookie:" and "Connection:" headers a bit smarter
94 * (don't crunch them just to recreate them later on).
95 * - Add another non-standard time format for the cookie
96 * expiration date detection.
97 * - Fix a valgrind warning.
99 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
100 * Improve cookie expiration date detection.
102 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
103 * Don't run server_content_length() the first time
104 * sed() parses server headers; only adjust the
105 * Content-Length header if the page was modified.
107 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
108 * Fix log messages regarding the cookie time format
109 * (cookie and request URL were mixed up).
111 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
112 * - Let decompress_iob()
113 * - not corrupt the content if decompression fails
114 * early. (the first byte(s) were lost).
115 * - use pointer arithmetics with defined outcome for
117 * - Use a different kludge to remember a failed decompression.
119 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
120 * Search for Max-Forwards headers case-insensitive,
121 * don't generate the "501 unsupported" message for invalid
122 * Max-Forwards values and don't increase negative ones.
124 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
125 * - Let server_set_cookie() check the expiration date
126 * of cookies and don't touch the ones that are already
127 * expired. Fixes problems with low quality web applications
128 * as described in BR 932612.
130 * - Adjust comment in client_max_forwards to reality;
131 * remove invalid Max-Forwards headers.
133 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
134 * Stop filter_header() from unintentionally removing
135 * empty header lines that were enlisted by the continue
138 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
139 * - Repeat the request URL before logging any headers.
140 * Makes reading the log easier in case of simultaneous requests.
141 * - If there are more than one Content-Type headers in one request,
142 * use the first one and remove the others.
143 * - Remove "newval" variable in server_content_type().
144 * It's only used once.
146 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
147 * Correct a cast, check inflateEnd() exit code
148 * to see if we have to, replace sprintf calls
151 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
152 * Integrate a modified version of Wil Mahan's
153 * zlib patch (PR #895531).
155 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
156 * Skip empty filter files in filter_header()
157 * but don't ignore the ones that come afterwards.
158 * Fixes BR 1619208, this time for real.
160 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
161 * Reverted parts of my last commit
162 * to keep error handling working.
164 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
165 * Fixed gcc43 conversion warnings.
167 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
168 * Bringing back the "useless" localtime() call
169 * I removed in revision 1.67. On some platforms
170 * it's necessary to prevent time zone offsets.
172 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
173 * Rebuild request URL in get_destination_from_headers()
174 * to make sure redirect{pcrs command} works as expected
175 * for intercepted requests.
177 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
178 * Added get_destination_from_headers().
180 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
181 * Make pthread mutex locking more generic. Instead of
182 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
183 * and use mutex locking unless there is an _r function
184 * available. Better safe than sorry.
186 * Fixes "./configure --disable-pthread" and should result
187 * in less threading-related problems on pthread-using platforms,
188 * but it still doesn't fix BR#1122404.
190 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
191 * The special header "X-Filter: No" now disables
192 * header filtering as well.
194 * Revision 1.73 2006/09/23 13:26:38 roro
195 * Replace TABs by spaces in source code.
197 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
198 * Don't print a log message every time filter_headers is
199 * entered or left. It only creates noise without any real
202 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
203 * Fix +hide-if-modified-since{-n}.
205 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
206 * Have hide-if-modified-since interpret the random
207 * range value as minutes instead of hours. Allows
208 * more fine-grained configuration.
210 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
211 * Always have parse_header_time return a pointer
212 * that actual makes sense, even though we currently
213 * only need it to detect problems.
215 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
216 * Added config option enable-remote-http-toggle
217 * to specify if Privoxy should recognize special
218 * headers (currently only X-Filter) to change its
219 * behaviour. Disabled by default.
221 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
222 * After filtering de-chunked instances, remove
223 * "Transfer-Encoding" header entirely instead of changing
224 * it to "Transfer-Encoding: identity", which is invalid.
225 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
227 * Don't use localtime in parse_header_time. An empty time struct
228 * is good enough, it gets overwritten by strptime anyway.
230 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
231 * Use gmtime_r if available, fallback to gmtime with mutex
232 * protection for MacOSX and use vanilla gmtime for the rest.
234 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
235 * Changed client_referrer to use the right type (size_t) for
236 * hostlenght and to shorten the temporary referrer string with
237 * '\0' instead of adding a useless line break.
239 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
240 * - Back to timegm() using GnuPG's replacement if necessary.
241 * Using mktime() and localtime() could add a on hour offset if
242 * the randomize factor was big enough to lead to a summer/wintertime
245 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
247 * - Moved randomization code into pick_from_range().
249 * - Changed parse_header_time definition.
250 * time_t isn't guaranteed to be signed and
251 * if it isn't, -1 isn't available as error code.
252 * Changed some variable types in client_if_modified_since()
253 * because of the same reason.
255 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
256 * OS/2 compilation compatibility fixups
258 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
259 * Changed include from strptime.c to strptime.h
261 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
262 * Split filter-headers{} into filter-client-headers{}
263 * and filter-server-headers{}.
264 * Added parse_header_time() to share some code.
265 * Replaced timegm() with mktime().
267 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
268 * Windows service integration
270 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
271 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
273 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
274 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
275 * with what was really the latest development (the v_3_0_branch branch)
277 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
278 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
280 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
281 * Add the ability to check jpeg images for invalid
282 * lengths of comment blocks. Defensive strategy
283 * against the exploit:
284 * Microsoft Security Bulletin MS04-028
285 * Buffer Overrun in JPEG Processing (GDI+) Could
286 * Allow Code Execution (833987)
287 * Enabled with +inspect-jpegs in actions files.
289 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
290 * Excluded text/plain objects from filtering. This fixes a
291 * couple of client-crashing, download corruption and
292 * Privoxy performance issues, whose root cause lies in
293 * web servers labelling content of unknown type as text/plain.
295 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
296 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
298 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
299 * Completing the previous change
301 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
302 * Added temporary workaround for bug in PHP < 4.2.3
304 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
305 * 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.
307 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
308 * Fix typo: supressed -> suppressed
310 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
311 * Improved cookie logging
313 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
314 * Added basic support for OPTIONS and TRACE HTTP methods:
315 * - New parser function client_max_forwards which decrements
316 * the Max-Forwards HTTP header field of OPTIONS and TRACE
317 * requests by one before forwarding
318 * - New parser function client_host which extracts the host
319 * and port information from the HTTP header field if the
320 * request URI was not absolute
321 * - Don't crumble and re-add the Host: header, but only generate
322 * and append if missing
324 * Revision 1.56 2002/05/12 15:34:22 jongfoster
325 * Fixing typo in a comment
327 * Revision 1.55 2002/05/08 16:01:07 oes
328 * Optimized add_to_iob:
329 * - Use realloc instead of malloc(), memcpy(), free()
330 * - Expand to powers of two if possible, to get
331 * O(log n) reallocs instead of O(n).
332 * - Moved check for buffer limit here from chat
333 * - Report failure via returncode
335 * Revision 1.54 2002/04/02 15:03:16 oes
336 * Tiny code cosmetics
338 * Revision 1.53 2002/03/26 22:29:55 swa
339 * we have a new homepage!
341 * Revision 1.52 2002/03/24 13:25:43 swa
342 * name change related issues
344 * Revision 1.51 2002/03/13 00:27:05 jongfoster
347 * Revision 1.50 2002/03/12 01:45:35 oes
348 * More verbose logging
350 * Revision 1.49 2002/03/09 20:03:52 jongfoster
351 * - Making various functions return int rather than size_t.
352 * (Undoing a recent change). Since size_t is unsigned on
353 * Windows, functions like read_socket that return -1 on
354 * error cannot return a size_t.
356 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
357 * crashes, and also frequently caused JB to jump to 100%
358 * CPU and stay there. (Because it thought it had just
359 * read ((unsigned)-1) == 4Gb of data...)
361 * - The signature of write_socket has changed, it now simply
362 * returns success=0/failure=nonzero.
364 * - Trying to get rid of a few warnings --with-debug on
365 * Windows, I've introduced a new type "jb_socket". This is
366 * used for the socket file descriptors. On Windows, this
367 * is SOCKET (a typedef for unsigned). Everywhere else, it's
368 * an int. The error value can't be -1 any more, so it's
369 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
370 * Windows it maps to the #define INVALID_SOCKET.)
372 * - The signature of bind_port has changed.
374 * Revision 1.48 2002/03/07 03:46:53 oes
375 * Fixed compiler warnings etc
377 * Revision 1.47 2002/02/20 23:15:13 jongfoster
378 * Parsing functions now handle out-of-memory gracefully by returning
381 * Revision 1.46 2002/01/17 21:03:47 jongfoster
382 * Moving all our URL and URL pattern parsing code to urlmatch.c.
384 * Revision 1.45 2002/01/09 14:33:03 oes
385 * Added support for localtime_r.
387 * Revision 1.44 2001/12/14 01:22:54 steudten
388 * Remove 'user:pass@' from 'proto://user:pass@host' for the
389 * new added header 'Host: ..'. (See Req ID 491818)
391 * Revision 1.43 2001/11/23 00:26:38 jongfoster
392 * Fixing two really stupid errors in my previous commit
394 * Revision 1.42 2001/11/22 21:59:30 jongfoster
395 * Adding code to handle +no-cookies-keep
397 * Revision 1.41 2001/11/05 23:43:05 steudten
398 * Add time+date to log files.
400 * Revision 1.40 2001/10/26 20:13:09 jongfoster
401 * ctype.h is needed in Windows, too.
403 * Revision 1.39 2001/10/26 17:40:04 oes
404 * Introduced get_header_value()
405 * Removed http->user_agent, csp->referrer and csp->accept_types
406 * Removed client_accept()
408 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
409 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
410 * threads to call select() simultaneously. So, it's time to do a real, live,
411 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
412 * (native). Both versions will work, but using __OS2__ offers multi-threading.
414 * Revision 1.37 2001/10/23 21:36:02 jongfoster
415 * Documenting sed()'s error behaviou (doc change only)
417 * Revision 1.36 2001/10/13 12:51:51 joergs
418 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
419 * force-load), instead crumble Host: and add it (again) in client_host_adder
420 * (in case we get a HTTP/1.0 request without Host: header and forward it to
421 * a HTTP/1.1 server/proxy).
423 * Revision 1.35 2001/10/09 22:39:21 jongfoster
424 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
427 * Revision 1.34 2001/10/07 18:50:55 oes
428 * Added server_content_encoding, renamed server_transfer_encoding
430 * Revision 1.33 2001/10/07 18:04:49 oes
431 * Changed server_http11 to server_http and its pattern to "HTTP".
432 * Additional functionality: it now saves the HTTP status into
433 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
435 * Revision 1.32 2001/10/07 15:43:28 oes
436 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
437 * client_te and client_accept_encoding_adder, triggered by the new
438 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
439 * changed to allow only identity and chunked, and the TE header is
440 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
442 * parse_http_request no longer does anything than parsing. The rewriting
443 * of http->cmd and version mangling are gone. It now also recognizes
444 * the put and delete methods and saves the url in http->url. Removed
447 * renamed content_type and content_length to have the server_ prefix
449 * server_content_type now only works if csp->content_type != CT_TABOO
451 * added server_transfer_encoding, which
452 * - Sets CT_TABOO to prohibit filtering if encoding compresses
453 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
454 * - Change from "chunked" to "identity" if body was chunked
455 * but has been de-chunked for filtering.
457 * added server_content_md5 which crunches any Content-MD5 headers
458 * if the body was modified.
460 * made server_http11 conditional on +downgrade action
462 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
464 * Revision 1.31 2001/10/05 14:25:02 oes
465 * Crumble Keep-Alive from Server
467 * Revision 1.30 2001/09/29 12:56:03 joergs
468 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
470 * Revision 1.29 2001/09/24 21:09:24 jongfoster
471 * Fixing 2 memory leaks that Guy spotted, where the paramater to
472 * enlist() was not being free()d.
474 * Revision 1.28 2001/09/22 16:32:28 jongfoster
475 * Removing unused #includes.
477 * Revision 1.27 2001/09/20 15:45:25 steudten
479 * add casting from size_t to int for printf()
480 * remove local variable shadow s2
482 * Revision 1.26 2001/09/16 17:05:14 jongfoster
483 * Removing unused #include showarg.h
485 * Revision 1.25 2001/09/16 13:21:27 jongfoster
486 * Changes to use new list functions.
488 * Revision 1.24 2001/09/13 23:05:50 jongfoster
489 * Changing the string paramater to the header parsers a "const".
491 * Revision 1.23 2001/09/12 18:08:19 steudten
493 * In parse_http_request() header rewriting miss the host value, so
494 * from http://www.mydomain.com the result was just " / " not
495 * http://www.mydomain.com/ in case we forward.
497 * Revision 1.22 2001/09/10 10:58:53 oes
498 * Silenced compiler warnings
500 * Revision 1.21 2001/07/31 14:46:00 oes
501 * - Persistant connections now suppressed
502 * - sed() no longer appends empty header to csp->headers
504 * Revision 1.20 2001/07/30 22:08:36 jongfoster
505 * Tidying up #defines:
506 * - All feature #defines are now of the form FEATURE_xxx
507 * - Permanently turned off WIN_GUI_EDIT
508 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
510 * Revision 1.19 2001/07/25 17:21:54 oes
511 * client_uagent now saves copy of User-Agent: header value
513 * Revision 1.18 2001/07/13 14:02:46 oes
514 * - Included fix to repair broken HTTP requests that
515 * don't contain a path, not even '/'.
516 * - Removed all #ifdef PCRS
517 * - content_type now always inspected and classified as
518 * text, gif or other.
519 * - formatting / comments
521 * Revision 1.17 2001/06/29 21:45:41 oes
522 * Indentation, CRLF->LF, Tab-> Space
524 * Revision 1.16 2001/06/29 13:32:42 oes
526 * - Adapted free_http_request
527 * - Removed logentry from cancelled commit
529 * Revision 1.15 2001/06/03 19:12:38 oes
530 * deleted const struct interceptors
532 * Revision 1.14 2001/06/01 18:49:17 jongfoster
533 * Replaced "list_share" with "list" - the tiny memory gain was not
534 * worth the extra complexity.
536 * Revision 1.13 2001/05/31 21:30:33 jongfoster
537 * Removed list code - it's now in list.[ch]
538 * Renamed "permission" to "action", and changed many features
539 * to use the actions file rather than the global config.
541 * Revision 1.12 2001/05/31 17:33:13 oes
545 * Revision 1.11 2001/05/29 20:11:19 joergs
546 * '/ * inside comment' warning removed.
548 * Revision 1.10 2001/05/29 09:50:24 jongfoster
549 * Unified blocklist/imagelist/permissionslist.
550 * File format is still under discussion, but the internal changes
553 * Also modified interceptor behaviour:
554 * - We now intercept all URLs beginning with one of the following
555 * prefixes (and *only* these prefixes):
557 * * http://ijbswa.sf.net/config/
558 * * http://ijbswa.sourceforge.net/config/
559 * - New interceptors "home page" - go to http://i.j.b/ to see it.
560 * - Internal changes so that intercepted and fast redirect pages
561 * are not replaced with an image.
562 * - Interceptors now have the option to send a binary page direct
563 * to the client. (i.e. ijb-send-banner uses this)
564 * - Implemented show-url-info interceptor. (Which is why I needed
565 * the above interceptors changes - a typical URL is
566 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
567 * The previous mechanism would not have intercepted that, and
568 * if it had been intercepted then it then it would have replaced
571 * Revision 1.9 2001/05/28 17:26:33 jongfoster
572 * Fixing segfault if last header was crunched.
573 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
574 * can use the cross-platform sprintf() instead.)
576 * Revision 1.8 2001/05/27 22:17:04 oes
578 * - re_process_buffer no longer writes the modified buffer
579 * to the client, which was very ugly. It now returns the
580 * buffer, which it is then written by chat.
582 * - content_length now adjusts the Content-Length: header
583 * for modified documents rather than crunch()ing it.
584 * (Length info in csp->content_length, which is 0 for
585 * unmodified documents)
587 * - For this to work, sed() is called twice when filtering.
589 * Revision 1.7 2001/05/27 13:19:06 oes
590 * Patched Joergs solution for the content-length in.
592 * Revision 1.6 2001/05/26 13:39:32 jongfoster
593 * Only crunches Content-Length header if applying RE filtering.
594 * Without this fix, Microsoft Windows Update wouldn't work.
596 * Revision 1.5 2001/05/26 00:28:36 jongfoster
597 * Automatic reloading of config file.
598 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
599 * Most of the global variables have been moved to a new
600 * struct configuration_spec, accessed through csp->config->globalname
601 * Most of the globals remaining are used by the Win32 GUI.
603 * Revision 1.4 2001/05/22 18:46:04 oes
605 * - Enabled filtering banners by size rather than URL
606 * by adding patterns that replace all standard banner
607 * sizes with the "Junkbuster" gif to the re_filterfile
609 * - Enabled filtering WebBugs by providing a pattern
610 * which kills all 1x1 images
612 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
613 * which is selected by the (nonstandard and therefore
614 * capital) letter 'U' in the option string.
615 * It causes the quantifiers to be ungreedy by default.
616 * Appending a ? turns back to greedy (!).
618 * - Added a new interceptor ijb-send-banner, which
619 * sends back the "Junkbuster" gif. Without imagelist or
620 * MSIE detection support, or if tinygif = 1, or the
621 * URL isn't recognized as an imageurl, a lame HTML
622 * explanation is sent instead.
624 * - Added new feature, which permits blocking remote
625 * script redirects and firing back a local redirect
627 * The feature is conditionally compiled, i.e. it
628 * can be disabled with --disable-fast-redirects,
629 * plus it must be activated by a "fast-redirects"
630 * line in the config file, has its own log level
631 * and of course wants to be displayed by show-proxy-args
632 * Note: Boy, all the #ifdefs in 1001 locations and
633 * all the fumbling with configure.in and acconfig.h
634 * were *way* more work than the feature itself :-(
636 * - Because a generic redirect template was needed for
637 * this, tinygif = 3 now uses the same.
639 * - Moved GIFs, and other static HTTP response templates
644 * - Removed some >400 CRs again (Jon, you really worked
647 * Revision 1.3 2001/05/20 01:21:20 jongfoster
648 * Version 2.9.4 checkin.
649 * - Merged popupfile and cookiefile, and added control over PCRS
650 * filtering, in new "permissionsfile".
651 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
652 * file error you now get a message box (in the Win32 GUI) rather
653 * than the program exiting with no explanation.
654 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
656 * - Removed tabs from "config"
657 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
658 * - Bumped up version number.
660 * Revision 1.2 2001/05/17 23:02:36 oes
661 * - Made referrer option accept 'L' as a substitute for '§'
663 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
664 * Initial import of version 2.9.3 source tree
667 *********************************************************************/
674 #include <sys/types.h>
684 * Convince GNU's libc to provide a strptime prototype.
687 #endif /*__GLIBC__ */
694 #if !defined(_WIN32) && !defined(__OS2__)
700 #ifdef FEATURE_PTHREAD
702 /* jcc.h is for mutex semapores only */
703 #endif /* def FEATURE_PTHREAD */
709 #include "jbsockets.h"
710 #include "miscutil.h"
715 #ifndef HAVE_STRPTIME
716 #include "strptime.h"
719 const char parsers_h_rcs[] = PARSERS_H_VERSION;
721 /* Fix a problem with Solaris. There should be no effect on other
723 * Solaris's isspace() is a macro which uses its argument directly
724 * as an array index. Therefore we need to make sure that high-bit
725 * characters generate +ve values, and ideally we also want to make
726 * the argument match the declared parameter type of "int".
728 * Why did they write a character function that can't take a simple
729 * "char" argument? Doh!
731 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
732 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
734 jb_err header_tagger(struct client_state *csp, char *header);
735 jb_err scan_headers(struct client_state *csp);
737 const struct parsers client_patterns[] = {
738 { "referer:", 8, client_referrer },
739 { "user-agent:", 11, client_uagent },
740 { "ua-", 3, client_ua },
741 { "from:", 5, client_from },
742 { "cookie:", 7, client_send_cookie },
743 { "x-forwarded-for:", 16, client_x_forwarded },
744 { "Accept-Encoding:", 16, client_accept_encoding },
745 { "TE:", 3, client_te },
746 { "Host:", 5, client_host },
747 { "if-modified-since:", 18, client_if_modified_since },
748 { "Keep-Alive:", 11, crumble },
749 { "connection:", 11, connection },
750 { "proxy-connection:", 17, crumble },
751 { "max-forwards:", 13, client_max_forwards },
752 { "Accept-Language:", 16, client_accept_language },
753 { "if-none-match:", 14, client_if_none_match },
754 { "X-Filter:", 9, client_x_filter },
755 { "*", 0, crunch_client_header },
756 { "*", 0, filter_header },
760 const struct parsers server_patterns[] = {
761 { "HTTP", 4, server_http },
762 { "set-cookie:", 11, server_set_cookie },
763 { "connection:", 11, connection },
764 { "Content-Type:", 13, server_content_type },
765 { "Content-MD5:", 12, server_content_md5 },
766 { "Content-Encoding:", 17, server_content_encoding },
767 { "Transfer-Encoding:", 18, server_transfer_coding },
768 { "Keep-Alive:", 11, crumble },
769 { "content-disposition:", 20, server_content_disposition },
770 { "Last-Modified:", 14, server_last_modified },
771 { "*", 0, crunch_server_header },
772 { "*", 0, filter_header },
776 const struct parsers server_patterns_light[] = {
777 { "Content-Length:", 15, server_content_length },
778 { "Transfer-Encoding:", 18, server_transfer_coding },
780 { "Content-Encoding:", 17, server_content_encoding },
781 #endif /* def FEATURE_ZLIB */
785 const add_header_func_ptr add_client_headers[] = {
788 client_x_forwarded_adder,
790 /* Temporarily disabled: client_accept_encoding_adder, */
791 connection_close_adder,
796 const add_header_func_ptr add_server_headers[] = {
797 connection_close_adder,
801 /*********************************************************************
803 * Function : flush_socket
805 * Description : Write any pending "buffered" content.
808 * 1 : fd = file descriptor of the socket to read
809 * 2 : csp = Current client state (buffers, headers, etc...)
811 * Returns : On success, the number of bytes written are returned (zero
812 * indicates nothing was written). On error, -1 is returned,
813 * and errno is set appropriately. If count is zero and the
814 * file descriptor refers to a regular file, 0 will be
815 * returned without causing any other effect. For a special
816 * file, the results are not portable.
818 *********************************************************************/
819 int flush_socket(jb_socket fd, struct client_state *csp)
821 struct iob *iob = csp->iob;
822 int len = iob->eod - iob->cur;
829 if (write_socket(fd, iob->cur, (size_t)len))
833 iob->eod = iob->cur = iob->buf;
839 /*********************************************************************
841 * Function : add_to_iob
843 * Description : Add content to the buffered page, expanding the
844 * buffer if necessary.
847 * 1 : csp = Current client state (buffers, headers, etc...)
848 * 2 : buf = holds the content to be added to the page
849 * 3 : n = number of bytes to be added
851 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
852 * or buffer limit reached.
854 *********************************************************************/
855 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
857 struct iob *iob = csp->iob;
858 size_t used, offset, need, want;
861 if (n <= 0) return JB_ERR_OK;
863 used = (size_t)(iob->eod - iob->buf);
864 offset = (size_t)(iob->cur - iob->buf);
865 need = used + (size_t)n + 1;
868 * If the buffer can't hold the new data, extend it first.
869 * Use the next power of two if possible, else use the actual need.
871 if (need > csp->config->buffer_limit)
873 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
874 return JB_ERR_MEMORY;
877 if (need > iob->size)
879 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
881 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
885 else if (NULL != (p = (char *)realloc(iob->buf, need)))
891 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
892 return JB_ERR_MEMORY;
895 /* Update the iob pointers */
896 iob->cur = p + offset;
901 /* copy the new data into the iob buffer */
902 memcpy(iob->eod, buf, (size_t)n);
904 /* point to the end of the data */
907 /* null terminate == cheap insurance */
916 /*********************************************************************
918 * Function : decompress_iob
920 * Description : Decompress buffered page, expanding the
921 * buffer as necessary. csp->iob->cur
922 * should point to the the beginning of the
923 * compressed data block.
926 * 1 : csp = Current client state (buffers, headers, etc...)
928 * Returns : JB_ERR_OK on success,
929 * JB_ERR_MEMORY if out-of-memory limit reached, and
930 * JB_ERR_COMPRESS if error decompressing buffer.
932 *********************************************************************/
933 jb_err decompress_iob(struct client_state *csp)
935 char *buf; /* new, uncompressed buffer */
936 char *cur; /* Current iob position (to keep the original
937 * iob->cur unmodified if we return early) */
938 size_t bufsize; /* allocated size of the new buffer */
939 size_t old_size; /* Content size before decompression */
940 size_t skip_size; /* Number of bytes at the beginning of the iob
941 that we should NOT decompress. */
942 int status; /* return status of the inflate() call */
943 z_stream zstr; /* used by calls to zlib */
945 assert(csp->iob->cur - csp->iob->buf > 0);
946 assert(csp->iob->eod - csp->iob->cur > 0);
948 bufsize = csp->iob->size;
949 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
950 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
957 * This is to protect the parsing of gzipped data,
958 * but it should(?) be valid for deflated data also.
960 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
961 return JB_ERR_COMPRESS;
964 if (csp->content_type & CT_GZIP)
967 * Our task is slightly complicated by the facts that data
968 * compressed by gzip does not include a zlib header, and
969 * that there is no easily accessible interface in zlib to
970 * handle a gzip header. We strip off the gzip header by
971 * hand, and later inform zlib not to expect a header.
975 * Strip off the gzip header. Please see RFC 1952 for more
976 * explanation of the appropriate fields.
978 if ((*cur++ != (char)0x1f)
979 || (*cur++ != (char)0x8b)
980 || (*cur++ != Z_DEFLATED))
982 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
983 return JB_ERR_COMPRESS;
989 * XXX: These magic numbers should be replaced
990 * with macros to give a better idea what they do.
994 /* The gzip header has reserved bits set; bail out. */
995 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
996 return JB_ERR_COMPRESS;
1000 /* Skip extra fields if necessary. */
1004 * Skip a given number of bytes, specified
1005 * as a 16-bit little-endian value.
1008 * XXX: This code used to be:
1010 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1012 * which I had to change into:
1014 * cur += *cur++ + (*cur++ << 8);
1016 * at which point gcc43 finally noticed that the value
1017 * of cur is undefined (it depends on which of the
1018 * summands is evaluated first).
1020 * I haven't come across a site where this
1021 * code is actually executed yet, but I hope
1025 skip_bytes = *cur++;
1026 skip_bytes = *cur++ << 8;
1028 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1031 * The number of bytes to skip should be positive
1032 * and we'd like to stay in the buffer.
1034 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1036 log_error (LOG_LEVEL_ERROR,
1037 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1039 return JB_ERR_COMPRESS;
1041 log_error (LOG_LEVEL_INFO,
1042 "Skipping %d bytes for gzip compression. Does this sound right?",
1047 /* Skip the filename if necessary. */
1050 /* A null-terminated string is supposed to follow. */
1051 while (*cur++ && (cur < csp->iob->eod));
1055 /* Skip the comment if necessary. */
1058 /* A null-terminated string is supposed to follow. */
1059 while (*cur++ && (cur < csp->iob->eod));
1062 /* Skip the CRC if necessary. */
1068 if (cur >= csp->iob->eod)
1071 * If the current position pointer reached or passed
1072 * the buffer end, we were obviously tricked to skip
1075 log_error (LOG_LEVEL_ERROR,
1076 "Malformed gzip header detected. Aborting decompression.");
1077 return JB_ERR_COMPRESS;
1081 else if (csp->content_type & CT_DEFLATE)
1084 * XXX: The debug level should be lowered
1085 * before the next stable release.
1087 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1089 * In theory (that is, according to RFC 1950), deflate-compressed
1090 * data should begin with a two-byte zlib header and have an
1091 * adler32 checksum at the end. It seems that in practice only
1092 * the raw compressed data is sent. Note that this means that
1093 * we are not RFC 1950-compliant here, but the advantage is that
1094 * this actually works. :)
1096 * We add a dummy null byte to tell zlib where the data ends,
1097 * and later inform it not to expect a header.
1099 * Fortunately, add_to_iob() has thoughtfully null-terminated
1100 * the buffer; we can just increment the end pointer to include
1107 log_error (LOG_LEVEL_ERROR,
1108 "Unable to determine compression format for decompression");
1109 return JB_ERR_COMPRESS;
1112 /* Set up the fields required by zlib. */
1113 zstr.next_in = (Bytef *)cur;
1114 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1115 zstr.zalloc = Z_NULL;
1116 zstr.zfree = Z_NULL;
1117 zstr.opaque = Z_NULL;
1120 * Passing -MAX_WBITS to inflateInit2 tells the library
1121 * that there is no zlib header.
1123 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1125 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1126 return JB_ERR_COMPRESS;
1130 * Next, we allocate new storage for the inflated data.
1131 * We don't modify the existing iob yet, so in case there
1132 * is error in decompression we can recover gracefully.
1134 buf = zalloc (bufsize);
1137 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1138 return JB_ERR_MEMORY;
1141 assert(bufsize >= skip_size);
1142 memcpy(buf, csp->iob->buf, skip_size);
1143 zstr.avail_out = bufsize - skip_size;
1144 zstr.next_out = (Bytef *)buf + skip_size;
1146 /* Try to decompress the whole stream in one shot. */
1147 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1149 /* We need to allocate more memory for the output buffer. */
1151 char *tmpbuf; /* used for realloc'ing the buffer */
1152 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1155 * If zlib wants more data then there's a problem, because
1156 * the complete compressed file should have been buffered.
1158 if (0 == zstr.avail_in)
1160 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1161 return JB_ERR_COMPRESS;
1165 * If we tried the limit and still didn't have enough
1166 * memory, just give up.
1168 if (bufsize == csp->config->buffer_limit)
1170 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1171 return JB_ERR_MEMORY;
1174 /* Try doubling the buffer size each time. */
1177 /* Don't exceed the buffer limit. */
1178 if (bufsize > csp->config->buffer_limit)
1180 bufsize = csp->config->buffer_limit;
1183 /* Try to allocate the new buffer. */
1184 tmpbuf = realloc(buf, bufsize);
1187 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1189 return JB_ERR_MEMORY;
1193 char *oldnext_out = (char *)zstr.next_out;
1196 * Update the fields for inflate() to use the new
1197 * buffer, which may be in a location different from
1200 zstr.avail_out += bufsize - oldbufsize;
1201 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1204 * Compare with an uglier method of calculating these values
1205 * that doesn't require the extra oldbufsize variable.
1207 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1208 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1209 assert(zstr.avail_out > 0);
1215 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1217 log_error(LOG_LEVEL_ERROR,
1218 "Inconsistent stream state after decompression: %s", zstr.msg);
1220 * XXX: Intentionally no return.
1222 * According to zlib.h, Z_STREAM_ERROR is returned
1223 * "if the stream state was inconsistent".
1225 * I assume in this case inflate()'s status
1226 * would also be something different than Z_STREAM_END
1227 * so this check should be redundant, but lets see.
1231 if (status != Z_STREAM_END)
1233 /* We failed to decompress the stream. */
1234 log_error(LOG_LEVEL_ERROR,
1235 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1236 return JB_ERR_COMPRESS;
1240 * Finally, we can actually update the iob, since the
1241 * decompression was successful. First, free the old
1244 freez(csp->iob->buf);
1246 /* Now, update the iob to use the new buffer. */
1247 csp->iob->buf = buf;
1248 csp->iob->cur = csp->iob->buf + skip_size;
1249 csp->iob->eod = (char *)zstr.next_out;
1250 csp->iob->size = bufsize;
1253 * Make sure the new uncompressed iob obeys some minimal
1254 * consistency conditions.
1256 if ((csp->iob->buf < csp->iob->cur)
1257 && (csp->iob->cur <= csp->iob->eod)
1258 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1260 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1263 log_error(LOG_LEVEL_RE_FILTER,
1264 "Decompression successful. Old size: %d, new size: %d.",
1265 old_size, new_size);
1269 /* zlib thinks this is OK, so lets do the same. */
1270 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1275 /* It seems that zlib did something weird. */
1276 log_error(LOG_LEVEL_ERROR,
1277 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1278 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1279 csp->iob->eod, csp->iob->buf + csp->iob->size);
1280 return JB_ERR_COMPRESS;
1286 #endif /* defined(FEATURE_ZLIB) */
1289 /*********************************************************************
1291 * Function : get_header
1293 * Description : This (odd) routine will parse the csp->iob
1296 * 1 : csp = Current client state (buffers, headers, etc...)
1298 * Returns : Any one of the following:
1300 * 1) a pointer to a dynamically allocated string that contains a header line
1301 * 2) NULL indicating that the end of the header was reached
1302 * 3) "" indicating that the end of the iob was reached before finding
1303 * a complete header line.
1305 *********************************************************************/
1306 char *get_header(struct client_state *csp)
1312 if ((iob->cur == NULL)
1313 || ((p = strchr(iob->cur, '\n')) == NULL))
1315 return(""); /* couldn't find a complete header */
1320 ret = strdup(iob->cur);
1323 /* FIXME No way to handle error properly */
1324 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1329 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1331 /* is this a blank line (i.e. the end of the header) ? */
1343 /*********************************************************************
1345 * Function : get_header_value
1347 * Description : Get the value of a given header from a chained list
1348 * of header lines or return NULL if no such header is
1349 * present in the list.
1352 * 1 : header_list = pointer to list
1353 * 2 : header_name = string with name of header to look for.
1354 * Trailing colon required, capitalization
1357 * Returns : NULL if not found, else value of header
1359 *********************************************************************/
1360 char *get_header_value(const struct list *header_list, const char *header_name)
1362 struct list_entry *cur_entry;
1366 assert(header_list);
1367 assert(header_name);
1368 length = strlen(header_name);
1370 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1374 if (!strncmpic(cur_entry->str, header_name, length))
1377 * Found: return pointer to start of value
1379 ret = (char *) (cur_entry->str + length);
1380 while (*ret && ijb_isspace(*ret)) ret++;
1394 /*********************************************************************
1396 * Function : scan_headers
1398 * Description : Scans headers, applies tags and updates action bits.
1401 * 1 : csp = Current client state (buffers, headers, etc...)
1403 * Returns : JB_ERR_OK
1405 *********************************************************************/
1406 jb_err scan_headers(struct client_state *csp)
1408 struct list_entry *h; /* Header */
1409 jb_err err = JB_ERR_OK;
1411 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1413 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1415 /* Header crunch()ed in previous run? -> ignore */
1416 if (h->str == NULL) continue;
1417 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1418 err = header_tagger(csp, h->str);
1425 /*********************************************************************
1429 * Description : add, delete or modify lines in the HTTP header streams.
1430 * On entry, it receives a linked list of headers space
1431 * that was allocated dynamically (both the list nodes
1432 * and the header contents).
1434 * As a side effect it frees the space used by the original
1438 * 1 : pats = list of patterns to match against headers
1439 * 2 : more_headers = list of functions to add more
1440 * headers (client or server)
1441 * 3 : csp = Current client state (buffers, headers, etc...)
1443 * Returns : Single pointer to a fully formed header, or NULL
1444 * on out-of-memory error.
1446 *********************************************************************/
1447 char *sed(const struct parsers pats[],
1448 const add_header_func_ptr more_headers[],
1449 struct client_state *csp)
1451 struct list_entry *p;
1452 const struct parsers *v;
1453 const add_header_func_ptr *f;
1454 jb_err err = JB_ERR_OK;
1458 * If filtering is enabled, sed is run twice,
1459 * but most of the work needs to be done only once.
1461 first_run = (more_headers != NULL ) ? 1 : 0;
1463 if (first_run) /* Parse and print */
1467 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1469 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1471 /* Header crunch()ed in previous run? -> ignore */
1472 if (p->str == NULL) continue;
1474 /* Does the current parser handle this header? */
1475 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1477 err = v->parser(csp, (char **)&(p->str));
1481 /* place any additional headers on the csp->headers list */
1482 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1487 else /* Parse only */
1490 * The second run is only needed if the body was modified
1491 * and the content-lenght has changed.
1493 if (strncmpic(csp->http->cmd, "HEAD", 4))
1495 /*XXX: Code duplication */
1496 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1498 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1500 /* Header crunch()ed in previous run? -> ignore */
1501 if (p->str == NULL) continue;
1503 /* Does the current parser handle this header? */
1504 if (strncmpic(p->str, v->str, v->len) == 0)
1506 err = v->parser(csp, (char **)&(p->str));
1513 if (err != JB_ERR_OK)
1518 return list_to_text(csp->headers);
1523 /*********************************************************************
1525 * Function : header_tagger
1527 * Description : Executes all text substitutions from applying
1528 * tag actions and saves the result as tag.
1530 * XXX: Shares enough code with filter_header() and
1531 * pcrs_filter_response() to warrant some helper functions.
1534 * 1 : csp = Current client state (buffers, headers, etc...)
1535 * 2 : header = Header that is used as tagger input
1537 * Returns : JB_ERR_OK on success and always succeeds
1539 *********************************************************************/
1540 jb_err header_tagger(struct client_state *csp, char *header)
1542 int wanted_filter_type;
1543 int multi_action_index;
1547 struct file_list *fl;
1548 struct re_filterfile_spec *b;
1549 struct list_entry *tag_name;
1551 int found_filters = 0;
1552 const size_t header_length = strlen(header);
1554 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1556 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1557 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1561 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1562 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1565 /* Check if there are any filters */
1566 for (i = 0; i < MAX_AF_FILES; i++)
1579 if (0 == found_filters)
1581 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1585 for (i = 0; i < MAX_AF_FILES; i++)
1588 if ((NULL == fl) || (NULL == fl->f))
1591 * Either there are no filter files
1592 * left, or this filter file just
1593 * contains no valid filters.
1595 * Continue to be sure we don't miss
1596 * valid filter files that are chained
1597 * after empty or invalid ones.
1602 /* For all filters, */
1603 for (b = fl->f; b; b = b->next)
1605 if (b->type != wanted_filter_type)
1607 /* skip the ones we don't care about, */
1610 /* leaving only taggers that could apply, of which we use the ones, */
1611 for (tag_name = csp->action->multi[multi_action_index]->first;
1612 NULL != tag_name; tag_name = tag_name->next)
1614 /* that do apply, and */
1615 if (strcmp(b->name, tag_name->str) == 0)
1617 char *modified_tag = NULL;
1619 size_t size = header_length;
1620 pcrs_job *joblist = b->joblist;
1622 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1624 if (NULL == joblist)
1626 log_error(LOG_LEVEL_RE_FILTER,
1627 "Tagger %s has empty joblist. Nothing to do.", b->name);
1631 /* execute their pcrs_joblist on the header. */
1632 for (job = joblist; NULL != job; job = job->next)
1634 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1638 /* Success, continue with the modified version. */
1647 /* Tagger doesn't match */
1650 /* Regex failure, log it but continue anyway. */
1651 log_error(LOG_LEVEL_ERROR,
1652 "Problems with tagger \'%s\' and header \'%s\': %s",
1653 b->name, *header, pcrs_strerror(hits));
1655 freez(modified_tag);
1659 if (b->dynamic) pcrs_free_joblist(joblist);
1661 /* If this tagger matched */
1667 * There is to technical limitation which makes
1668 * it impossible to use empty tags, but I assume
1669 * no one would do it intentionally.
1672 log_error(LOG_LEVEL_INFO,
1673 "Tagger \'%s\' created an empty tag. Ignored.",
1678 if (!list_contains_item(csp->tags, tag))
1680 if (JB_ERR_OK != enlist(csp->tags, tag))
1682 log_error(LOG_LEVEL_ERROR,
1683 "Insufficient memory to add tag \'%s\', "
1684 "based on tagger \'%s\' and header \'%s\'",
1685 tag, b->name, *header);
1689 char *action_message;
1691 * update the action bits right away, to make
1692 * tagging based on tags set by earlier taggers
1693 * of the same kind possible.
1695 if (update_action_bits_for_tag(csp, tag))
1697 action_message = "Action bits updated accordingly.";
1701 action_message = "No action bits update necessary.";
1704 log_error(LOG_LEVEL_HEADER,
1705 "Tagger \'%s\' added tag \'%s\'. %s",
1706 b->name, tag, action_message);
1711 /* XXX: Is this log-worthy? */
1712 log_error(LOG_LEVEL_HEADER,
1713 "Tagger \'%s\' didn't add tag \'%s\'. "
1714 "Tag already present", b->name, tag);
1717 } /* if the tagger matched */
1718 } /* if the tagger applies */
1719 } /* for every tagger that could apply */
1720 } /* for all filters */
1721 } /* for all filter files */
1726 /* here begins the family of parser functions that reformat header lines */
1728 /*********************************************************************
1730 * Function : filter_header
1732 * Description : Executes all text substitutions from all applying
1733 * +(server|client)-header-filter actions on the header.
1734 * Most of the code was copied from pcrs_filter_response,
1735 * including the rather short variable names
1738 * 1 : csp = Current client state (buffers, headers, etc...)
1739 * 2 : header = On input, pointer to header to modify.
1740 * On output, pointer to the modified header, or NULL
1741 * to remove the header. This function frees the
1742 * original string if necessary.
1744 * Returns : JB_ERR_OK on success and always succeeds
1746 *********************************************************************/
1747 jb_err filter_header(struct client_state *csp, char **header)
1751 size_t size = strlen(*header);
1753 char *newheader = NULL;
1756 struct file_list *fl;
1757 struct re_filterfile_spec *b;
1758 struct list_entry *filtername;
1760 int i, found_filters = 0;
1761 int wanted_filter_type;
1762 int multi_action_index;
1764 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1766 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1767 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1771 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1772 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1776 * Need to check the set of re_filterfiles...
1778 for (i = 0; i < MAX_AF_FILES; i++)
1791 if (0 == found_filters)
1793 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1797 for (i = 0; i < MAX_AF_FILES; i++)
1800 if ((NULL == fl) || (NULL == fl->f))
1803 * Either there are no filter files
1804 * left, or this filter file just
1805 * contains no valid filters.
1807 * Continue to be sure we don't miss
1808 * valid filter files that are chained
1809 * after empty or invalid ones.
1814 * For all applying +filter actions, look if a filter by that
1815 * name exists and if yes, execute its pcrs_joblist on the
1818 for (b = fl->f; b; b = b->next)
1820 if (b->type != wanted_filter_type)
1822 /* Skip other filter types */
1826 for (filtername = csp->action->multi[multi_action_index]->first;
1827 filtername ; filtername = filtername->next)
1829 if (strcmp(b->name, filtername->str) == 0)
1831 int current_hits = 0;
1832 pcrs_job *joblist = b->joblist;
1834 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1836 if (NULL == joblist)
1838 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1842 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1843 *header, size, b->name);
1845 /* Apply all jobs from the joblist */
1846 for (job = joblist; NULL != job; job = job->next)
1848 matches = pcrs_execute(job, *header, size, &newheader, &size);
1851 current_hits += matches;
1852 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1854 *header = newheader;
1856 else if ( 0 == matches )
1858 /* Filter doesn't change header */
1864 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1865 *header, b->name, pcrs_strerror(matches));
1866 if( newheader != NULL)
1868 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1874 if (b->dynamic) pcrs_free_joblist(joblist);
1876 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1877 hits += current_hits;
1884 * Additionally checking for hits is important because if
1885 * the continue hack is triggered, server headers can
1886 * arrive empty to separate multiple heads from each other.
1888 if ((0 == size) && hits)
1890 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1898 /*********************************************************************
1900 * Function : connection
1902 * Description : Makes sure that the value of the Connection: header
1903 * is "close" and signals connection_close_adder
1907 * 1 : csp = Current client state (buffers, headers, etc...)
1908 * 2 : header = On input, pointer to header to modify.
1909 * On output, pointer to the modified header, or NULL
1910 * to remove the header. This function frees the
1911 * original string if necessary.
1913 * Returns : JB_ERR_OK on success, or
1914 * JB_ERR_MEMORY on out-of-memory error.
1916 *********************************************************************/
1917 jb_err connection(struct client_state *csp, char **header)
1919 char *old_header = *header;
1921 /* Do we have a 'Connection: close' header? */
1922 if (strcmpic(*header, "Connection: close"))
1924 /* No, create one */
1925 *header = strdup("Connection: close");
1928 return JB_ERR_MEMORY;
1930 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1934 /* Signal connection_close_adder() to return early. */
1935 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1937 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
1941 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
1948 /*********************************************************************
1950 * Function : crumble
1952 * Description : This is called if a header matches a pattern to "crunch"
1955 * 1 : csp = Current client state (buffers, headers, etc...)
1956 * 2 : header = On input, pointer to header to modify.
1957 * On output, pointer to the modified header, or NULL
1958 * to remove the header. This function frees the
1959 * original string if necessary.
1961 * Returns : JB_ERR_OK on success, or
1962 * JB_ERR_MEMORY on out-of-memory error.
1964 *********************************************************************/
1965 jb_err crumble(struct client_state *csp, char **header)
1967 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1972 /*********************************************************************
1974 * Function : crunch_server_header
1976 * Description : Crunch server header if it matches a string supplied by the
1977 * user. Called from `sed'.
1980 * 1 : csp = Current client state (buffers, headers, etc...)
1981 * 2 : header = On input, pointer to header to modify.
1982 * On output, pointer to the modified header, or NULL
1983 * to remove the header. This function frees the
1984 * original string if necessary.
1986 * Returns : JB_ERR_OK on success and always succeeds
1988 *********************************************************************/
1989 jb_err crunch_server_header(struct client_state *csp, char **header)
1991 const char *crunch_pattern;
1993 /* Do we feel like crunching? */
1994 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1996 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1998 /* Is the current header the lucky one? */
1999 if (strstr(*header, crunch_pattern))
2001 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2010 /*********************************************************************
2012 * Function : server_content_type
2014 * Description : Set the content-type for filterable types (text/.*,
2015 * .*xml.*, javascript and image/gif) unless filtering has been
2016 * forbidden (CT_TABOO) while parsing earlier headers.
2017 * NOTE: Since text/plain is commonly used by web servers
2018 * for files whose correct type is unknown, we don't
2019 * set CT_TEXT for it.
2022 * 1 : csp = Current client state (buffers, headers, etc...)
2023 * 2 : header = On input, pointer to header to modify.
2024 * On output, pointer to the modified header, or NULL
2025 * to remove the header. This function frees the
2026 * original string if necessary.
2028 * Returns : JB_ERR_OK on success, or
2029 * JB_ERR_MEMORY on out-of-memory error.
2031 *********************************************************************/
2032 jb_err server_content_type(struct client_state *csp, char **header)
2034 /* Remove header if it isn't the first Content-Type header */
2035 if(csp->content_type && (csp->content_type != CT_TABOO))
2038 * Another, slightly slower, way to see if
2039 * we already parsed another Content-Type header.
2041 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2043 log_error(LOG_LEVEL_ERROR,
2044 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2051 if (!(csp->content_type & CT_TABOO))
2053 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2054 || strstr(*header, "xml")
2055 || strstr(*header, "application/x-javascript"))
2057 csp->content_type |= CT_TEXT;
2059 else if (strstr(*header, " image/gif"))
2061 csp->content_type |= CT_GIF;
2063 else if (strstr(*header, " image/jpeg"))
2065 csp->content_type |= CT_JPEG;
2069 csp->content_type = 0;
2073 * Are we enabling text mode by force?
2075 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2078 * Do we really have to?
2080 if (csp->content_type & CT_TEXT)
2082 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2086 csp->content_type |= CT_TEXT;
2087 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2091 * Are we messing with the content type?
2093 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2096 * Make sure the user doesn't accidently
2097 * change the content type of binary documents.
2099 if (csp->content_type & CT_TEXT)
2102 *header = strdup("Content-Type: ");
2103 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2107 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2108 return JB_ERR_MEMORY;
2110 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2114 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2115 "Enable force-text-mode if you know what you're doing.", *header);
2122 /*********************************************************************
2124 * Function : server_transfer_coding
2126 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2127 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2128 * - Remove header if body was chunked but has been
2129 * de-chunked for filtering.
2132 * 1 : csp = Current client state (buffers, headers, etc...)
2133 * 2 : header = On input, pointer to header to modify.
2134 * On output, pointer to the modified header, or NULL
2135 * to remove the header. This function frees the
2136 * original string if necessary.
2138 * Returns : JB_ERR_OK on success, or
2139 * JB_ERR_MEMORY on out-of-memory error.
2141 *********************************************************************/
2142 jb_err server_transfer_coding(struct client_state *csp, char **header)
2145 * Turn off pcrs and gif filtering if body compressed
2147 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2151 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2153 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2154 csp->http->cmd, *header);
2155 #endif /* def FEATURE_ZLIB */
2156 csp->content_type = CT_TABOO;
2160 * Raise flag if body chunked
2162 if (strstr(*header, "chunked"))
2164 csp->flags |= CSP_FLAG_CHUNKED;
2167 * If the body was modified, it has been de-chunked first
2168 * and the header must be removed.
2170 * FIXME: If there is more than one transfer encoding,
2171 * only the "chunked" part should be removed here.
2173 if (csp->flags & CSP_FLAG_MODIFIED)
2175 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2184 /*********************************************************************
2186 * Function : server_content_encoding
2188 * Description : This function is run twice for each request,
2189 * unless FEATURE_ZLIB and filtering are disabled.
2191 * The first run is used to check if the content
2192 * is compressed, if FEATURE_ZLIB is disabled
2193 * filtering is then disabled as well, if FEATURE_ZLIB
2194 * is enabled the content is marked for decompression.
2196 * The second run is used to remove the Content-Encoding
2197 * header if the decompression was successful.
2200 * 1 : csp = Current client state (buffers, headers, etc...)
2201 * 2 : header = On input, pointer to header to modify.
2202 * On output, pointer to the modified header, or NULL
2203 * to remove the header. This function frees the
2204 * original string if necessary.
2206 * Returns : JB_ERR_OK on success, or
2207 * JB_ERR_MEMORY on out-of-memory error.
2209 *********************************************************************/
2210 jb_err server_content_encoding(struct client_state *csp, char **header)
2213 if ((csp->flags & CSP_FLAG_MODIFIED)
2214 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2217 * We successfully decompressed the content,
2218 * and have to clean the header now, so the
2219 * client no longer expects compressed data..
2221 * XXX: There is a difference between cleaning
2222 * and removing it completely.
2224 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2227 else if (strstr(*header, "gzip"))
2229 /* Mark for gzip decompression */
2230 csp->content_type |= CT_GZIP;
2232 else if (strstr(*header, "deflate"))
2234 /* Mark for zlib decompression */
2235 csp->content_type |= CT_DEFLATE;
2237 else if (strstr(*header, "compress"))
2240 * We can't decompress this; therefore we can't filter
2243 csp->content_type |= CT_TABOO;
2245 #else /* !defined(FEATURE_ZLIB) */
2246 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2249 * Body is compressed, turn off pcrs and gif filtering.
2251 csp->content_type |= CT_TABOO;
2254 * Log a warning if the user expects the content to be filtered.
2256 if ((csp->rlist != NULL) &&
2257 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2259 log_error(LOG_LEVEL_INFO,
2260 "Compressed content detected, content filtering disabled. "
2261 "Consider recompiling Privoxy with zlib support or "
2262 "enable the prevent-compression action.");
2265 #endif /* defined(FEATURE_ZLIB) */
2272 /*********************************************************************
2274 * Function : server_content_length
2276 * Description : Adjust Content-Length header if we modified
2280 * 1 : csp = Current client state (buffers, headers, etc...)
2281 * 2 : header = On input, pointer to header to modify.
2282 * On output, pointer to the modified header, or NULL
2283 * to remove the header. This function frees the
2284 * original string if necessary.
2286 * Returns : JB_ERR_OK on success, or
2287 * JB_ERR_MEMORY on out-of-memory error.
2289 *********************************************************************/
2290 jb_err server_content_length(struct client_state *csp, char **header)
2292 const size_t max_header_length = 80;
2294 /* Regenerate header if the content was modified. */
2295 if (csp->flags & CSP_FLAG_MODIFIED)
2298 *header = (char *) zalloc(max_header_length);
2299 if (*header == NULL)
2301 return JB_ERR_MEMORY;
2304 snprintf(*header, max_header_length, "Content-Length: %d",
2305 (int)csp->content_length);
2306 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2307 (int)csp->content_length);
2314 /*********************************************************************
2316 * Function : server_content_md5
2318 * Description : Crumble any Content-MD5 headers if the document was
2319 * modified. FIXME: Should we re-compute instead?
2322 * 1 : csp = Current client state (buffers, headers, etc...)
2323 * 2 : header = On input, pointer to header to modify.
2324 * On output, pointer to the modified header, or NULL
2325 * to remove the header. This function frees the
2326 * original string if necessary.
2328 * Returns : JB_ERR_OK on success, or
2329 * JB_ERR_MEMORY on out-of-memory error.
2331 *********************************************************************/
2332 jb_err server_content_md5(struct client_state *csp, char **header)
2334 if (csp->flags & CSP_FLAG_MODIFIED)
2336 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2343 /*********************************************************************
2345 * Function : server_content_disposition
2347 * Description : If enabled, blocks or modifies the "content-disposition" header.
2348 * Called from `sed'.
2351 * 1 : csp = Current client state (buffers, headers, etc...)
2352 * 2 : header = On input, pointer to header to modify.
2353 * On output, pointer to the modified header, or NULL
2354 * to remove the header. This function frees the
2355 * original string if necessary.
2357 * Returns : JB_ERR_OK on success, or
2358 * JB_ERR_MEMORY on out-of-memory error.
2360 *********************************************************************/
2361 jb_err server_content_disposition(struct client_state *csp, char **header)
2366 * Are we messing with the content-disposition header?
2368 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2374 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2376 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2379 * Blocking content-disposition header
2381 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2388 * Replacing content-disposition header
2391 *header = strdup("content-disposition: ");
2392 string_append(header, newval);
2394 if (*header == NULL)
2396 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2400 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2403 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2406 /*********************************************************************
2408 * Function : server_last_modified
2410 * Description : Changes Last-Modified header to the actual date
2411 * to help hide-if-modified-since.
2412 * Called from `sed'.
2415 * 1 : csp = Current client state (buffers, headers, etc...)
2416 * 2 : header = On input, pointer to header to modify.
2417 * On output, pointer to the modified header, or NULL
2418 * to remove the header. This function frees the
2419 * original string if necessary.
2421 * Returns : JB_ERR_OK on success, or
2422 * JB_ERR_MEMORY on out-of-memory error.
2424 *********************************************************************/
2425 jb_err server_last_modified(struct client_state *csp, char **header)
2428 char buf[BUFFER_SIZE];
2431 #ifdef HAVE_GMTIME_R
2434 struct tm *timeptr = NULL;
2435 time_t now, last_modified;
2437 long int days, hours, minutes, seconds;
2440 * Are we messing with the Last-Modified header?
2442 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2448 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2450 if (0 == strcmpic(newval, "block") )
2453 * Blocking Last-Modified header. Useless but why not.
2455 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2459 else if (0 == strcmpic(newval, "reset-to-request-time"))
2462 * Setting Last-Modified Header to now.
2464 get_http_time(0, buf);
2466 *header = strdup("Last-Modified: ");
2467 string_append(header, buf);
2469 if (*header == NULL)
2471 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2475 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2478 else if (0 == strcmpic(newval, "randomize"))
2480 const char *header_time = *header + sizeof("Last-Modified:");
2482 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2484 #ifdef HAVE_GMTIME_R
2485 timeptr = gmtime_r(&now, &gmt);
2486 #elif FEATURE_PTHREAD
2487 pthread_mutex_lock(&gmtime_mutex);
2488 timeptr = gmtime(&now);
2489 pthread_mutex_unlock(&gmtime_mutex);
2491 timeptr = gmtime(&now);
2493 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2495 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2500 rtime = (long int)difftime(now, last_modified);
2503 rtime = pick_from_range(rtime);
2504 last_modified += rtime;
2505 #ifdef HAVE_GMTIME_R
2506 timeptr = gmtime_r(&last_modified, &gmt);
2507 #elif FEATURE_PTHREAD
2508 pthread_mutex_lock(&gmtime_mutex);
2509 timeptr = gmtime(&last_modified);
2510 pthread_mutex_unlock(&gmtime_mutex);
2512 timeptr = gmtime(&last_modified);
2514 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2516 *header = strdup("Last-Modified: ");
2517 string_append(header, newheader);
2519 if (*header == NULL)
2521 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2522 return JB_ERR_MEMORY;
2525 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2527 days = rtime / (3600 * 24);
2528 hours = rtime / 3600 % 24;
2529 minutes = rtime / 60 % 60;
2530 seconds = rtime % 60;
2532 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2533 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2534 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2539 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2548 /*********************************************************************
2550 * Function : client_accept_encoding
2552 * Description : Rewrite the client's Accept-Encoding header so that
2553 * if doesn't allow compression, if the action applies.
2554 * Note: For HTTP/1.0 the absence of the header is enough.
2557 * 1 : csp = Current client state (buffers, headers, etc...)
2558 * 2 : header = On input, pointer to header to modify.
2559 * On output, pointer to the modified header, or NULL
2560 * to remove the header. This function frees the
2561 * original string if necessary.
2563 * Returns : JB_ERR_OK on success, or
2564 * JB_ERR_MEMORY on out-of-memory error.
2566 *********************************************************************/
2567 jb_err client_accept_encoding(struct client_state *csp, char **header)
2569 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2571 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2575 /* Temporarily disable the correct behaviour to
2576 * work around a PHP bug.
2578 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2580 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2581 * if (*header == NULL)
2583 * return JB_ERR_MEMORY;
2594 /*********************************************************************
2596 * Function : client_te
2598 * Description : Rewrite the client's TE header so that
2599 * if doesn't allow compression, if the action applies.
2602 * 1 : csp = Current client state (buffers, headers, etc...)
2603 * 2 : header = On input, pointer to header to modify.
2604 * On output, pointer to the modified header, or NULL
2605 * to remove the header. This function frees the
2606 * original string if necessary.
2608 * Returns : JB_ERR_OK on success, or
2609 * JB_ERR_MEMORY on out-of-memory error.
2611 *********************************************************************/
2612 jb_err client_te(struct client_state *csp, char **header)
2614 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2617 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2623 /*********************************************************************
2625 * Function : client_referrer
2627 * Description : Handle the "referer" config setting properly.
2628 * Called from `sed'.
2631 * 1 : csp = Current client state (buffers, headers, etc...)
2632 * 2 : header = On input, pointer to header to modify.
2633 * On output, pointer to the modified header, or NULL
2634 * to remove the header. This function frees the
2635 * original string if necessary.
2637 * Returns : JB_ERR_OK on success, or
2638 * JB_ERR_MEMORY on out-of-memory error.
2640 *********************************************************************/
2641 jb_err client_referrer(struct client_state *csp, char **header)
2648 #ifdef FEATURE_FORCE_LOAD
2649 /* Since the referrer can include the prefix even
2650 * if the request itself is non-forced, we must
2651 * clean it unconditionally
2653 strclean(*header, FORCE_PREFIX);
2654 #endif /* def FEATURE_FORCE_LOAD */
2657 * Are we sending referer?
2659 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2664 newval = csp->action->string[ACTION_STRING_REFERER];
2666 if ((0 != strcmpic(newval, "conditional-block")))
2670 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2675 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2678 else if (0 == strcmpic(newval, "conditional-block"))
2681 * Block referer if host has changed.
2684 if (NULL == (host = strdup(csp->http->hostport)))
2687 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2688 return JB_ERR_MEMORY;
2690 if (NULL == (referer = strdup(*header)))
2694 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2695 return JB_ERR_MEMORY;
2697 hostlenght = strlen(host);
2698 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2700 /*Shorten referer to make sure the referer is blocked
2701 *if www.example.org/www.example.com-shall-see-the-referer/
2702 *links to www.example.com/
2704 referer[hostlenght+17] = '\0';
2706 if ( 0 == strstr(referer, host)) /*Host has changed*/
2708 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2713 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2719 else if (0 != strcmpic(newval, "forge"))
2722 * We have a specific (fixed) referer we want to send.
2724 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2726 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2728 *header = strdup("Referer: ");
2729 string_append(header, newval);
2730 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2732 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2737 * Forge a referer as http://[hostname:port of REQUEST]/
2738 * to fool stupid checks for in-site links
2741 *header = strdup("Referer: http://");
2742 string_append(header, csp->http->hostport);
2743 string_append(header, "/");
2744 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2746 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2750 /*********************************************************************
2752 * Function : client_accept_language
2754 * Description : Handle the "Accept-Language" config setting properly.
2755 * Called from `sed'.
2758 * 1 : csp = Current client state (buffers, headers, etc...)
2759 * 2 : header = On input, pointer to header to modify.
2760 * On output, pointer to the modified header, or NULL
2761 * to remove the header. This function frees the
2762 * original string if necessary.
2764 * Returns : JB_ERR_OK on success, or
2765 * JB_ERR_MEMORY on out-of-memory error.
2767 *********************************************************************/
2768 jb_err client_accept_language(struct client_state *csp, char **header)
2773 * Are we messing with the Accept-Language?
2775 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2777 /*I don't think so*/
2781 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2783 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2786 * Blocking Accept-Language header
2788 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2795 * Replacing Accept-Language header
2798 *header = strdup("Accept-Language: ");
2799 string_append(header, newval);
2801 if (*header == NULL)
2803 log_error(LOG_LEVEL_ERROR,
2804 "Insufficent memory. Accept-Language header crunched without replacement.");
2808 log_error(LOG_LEVEL_HEADER,
2809 "Accept-Language header crunched and replaced with: %s", *header);
2812 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2815 /*********************************************************************
2817 * Function : crunch_client_header
2819 * Description : Crunch client header if it matches a string supplied by the
2820 * user. Called from `sed'.
2823 * 1 : csp = Current client state (buffers, headers, etc...)
2824 * 2 : header = On input, pointer to header to modify.
2825 * On output, pointer to the modified header, or NULL
2826 * to remove the header. This function frees the
2827 * original string if necessary.
2829 * Returns : JB_ERR_OK on success and always succeeds
2831 *********************************************************************/
2832 jb_err crunch_client_header(struct client_state *csp, char **header)
2834 const char *crunch_pattern;
2836 /* Do we feel like crunching? */
2837 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2839 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2841 /* Is the current header the lucky one? */
2842 if (strstr(*header, crunch_pattern))
2844 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2852 /*********************************************************************
2854 * Function : client_uagent
2856 * Description : Handle the "user-agent" config setting properly
2857 * and remember its original value to enable browser
2858 * bug workarounds. Called from `sed'.
2861 * 1 : csp = Current client state (buffers, headers, etc...)
2862 * 2 : header = On input, pointer to header to modify.
2863 * On output, pointer to the modified header, or NULL
2864 * to remove the header. This function frees the
2865 * original string if necessary.
2867 * Returns : JB_ERR_OK on success, or
2868 * JB_ERR_MEMORY on out-of-memory error.
2870 *********************************************************************/
2871 jb_err client_uagent(struct client_state *csp, char **header)
2875 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2880 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2887 *header = strdup("User-Agent: ");
2888 string_append(header, newval);
2890 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2892 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2895 /*********************************************************************
2897 * Function : client_ua
2899 * Description : Handle "ua-" headers properly. Called from `sed'.
2902 * 1 : csp = Current client state (buffers, headers, etc...)
2903 * 2 : header = On input, pointer to header to modify.
2904 * On output, pointer to the modified header, or NULL
2905 * to remove the header. This function frees the
2906 * original string if necessary.
2908 * Returns : JB_ERR_OK on success, or
2909 * JB_ERR_MEMORY on out-of-memory error.
2911 *********************************************************************/
2912 jb_err client_ua(struct client_state *csp, char **header)
2914 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2916 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2924 /*********************************************************************
2926 * Function : client_from
2928 * Description : Handle the "from" config setting properly.
2929 * Called from `sed'.
2932 * 1 : csp = Current client state (buffers, headers, etc...)
2933 * 2 : header = On input, pointer to header to modify.
2934 * On output, pointer to the modified header, or NULL
2935 * to remove the header. This function frees the
2936 * original string if necessary.
2938 * Returns : JB_ERR_OK on success, or
2939 * JB_ERR_MEMORY on out-of-memory error.
2941 *********************************************************************/
2942 jb_err client_from(struct client_state *csp, char **header)
2946 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2953 newval = csp->action->string[ACTION_STRING_FROM];
2956 * Are we blocking the e-mail address?
2958 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2960 log_error(LOG_LEVEL_HEADER, "crunched From!");
2964 log_error(LOG_LEVEL_HEADER, " modified");
2966 *header = strdup("From: ");
2967 string_append(header, newval);
2969 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2973 /*********************************************************************
2975 * Function : client_send_cookie
2977 * Description : Crunches the "cookie" header if necessary.
2978 * Called from `sed'.
2980 * XXX: Stupid name, doesn't send squat.
2983 * 1 : csp = Current client state (buffers, headers, etc...)
2984 * 2 : header = On input, pointer to header to modify.
2985 * On output, pointer to the modified header, or NULL
2986 * to remove the header. This function frees the
2987 * original string if necessary.
2989 * Returns : JB_ERR_OK on success, or
2990 * JB_ERR_MEMORY on out-of-memory error.
2992 *********************************************************************/
2993 jb_err client_send_cookie(struct client_state *csp, char **header)
2995 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2997 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3005 /*********************************************************************
3007 * Function : client_x_forwarded
3009 * Description : Handle the "x-forwarded-for" config setting properly,
3010 * also used in the add_client_headers list. Called from `sed'.
3013 * 1 : csp = Current client state (buffers, headers, etc...)
3014 * 2 : header = On input, pointer to header to modify.
3015 * On output, pointer to the modified header, or NULL
3016 * to remove the header. This function frees the
3017 * original string if necessary.
3019 * Returns : JB_ERR_OK on success, or
3020 * JB_ERR_MEMORY on out-of-memory error.
3022 *********************************************************************/
3023 jb_err client_x_forwarded(struct client_state *csp, char **header)
3025 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3027 /* Save it so we can re-add it later */
3028 freez(csp->x_forwarded);
3029 csp->x_forwarded = *header;
3032 * Always set *header = NULL, since this information
3033 * will be sent at the end of the header.
3040 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3047 /*********************************************************************
3049 * Function : client_max_forwards
3051 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3052 * from the value of the Max-Forwards header field.
3055 * 1 : csp = Current client state (buffers, headers, etc...)
3056 * 2 : header = On input, pointer to header to modify.
3057 * On output, pointer to the modified header, or NULL
3058 * to remove the header. This function frees the
3059 * original string if necessary.
3061 * Returns : JB_ERR_OK on success, or
3062 * JB_ERR_MEMORY on out-of-memory error.
3064 *********************************************************************/
3065 jb_err client_max_forwards(struct client_state *csp, char **header)
3069 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3070 (0 == strcmpic(csp->http->gpc, "options")))
3072 assert(*(*header+12) == ':');
3073 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3075 if (max_forwards > 0)
3077 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3078 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3079 csp->http->gpc, max_forwards);
3081 else if (max_forwards < 0)
3083 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3089 * Not supposed to be reached. direct_response() which
3090 * was already called earlier in chat() should have
3091 * intercepted the request.
3093 log_error(LOG_LEVEL_ERROR,
3094 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3095 assert(max_forwards != 0);
3100 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3109 /*********************************************************************
3111 * Function : client_host
3113 * Description : If the request URI did not contain host and
3114 * port information, parse and evaluate the Host
3117 * Also, kill ill-formed HOST: headers as sent by
3118 * Apple's iTunes software when used with a proxy.
3121 * 1 : csp = Current client state (buffers, headers, etc...)
3122 * 2 : header = On input, pointer to header to modify.
3123 * On output, pointer to the modified header, or NULL
3124 * to remove the header. This function frees the
3125 * original string if necessary.
3127 * Returns : JB_ERR_OK on success, or
3128 * JB_ERR_MEMORY on out-of-memory error.
3130 *********************************************************************/
3131 jb_err client_host(struct client_state *csp, char **header)
3136 * If the header field name is all upper-case, chances are that it's
3137 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3138 * not a problem -- they are regenerated later.
3140 if ((*header)[1] == 'O')
3142 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3147 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3148 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3151 if (NULL == (p = strdup((*header)+6)))
3153 return JB_ERR_MEMORY;
3156 if (NULL == (q = strdup(p)))
3159 return JB_ERR_MEMORY;
3162 freez(csp->http->hostport);
3163 csp->http->hostport = p;
3164 freez(csp->http->host);
3165 csp->http->host = q;
3166 q = strchr(csp->http->host, ':');
3169 /* Terminate hostname and evaluate port string */
3171 csp->http->port = atoi(q);
3175 csp->http->port = csp->http->ssl ? 443 : 80;
3178 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3179 csp->http->hostport, csp->http->host, csp->http->port);
3182 /* Signal client_host_adder() to return right away */
3183 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3188 /*********************************************************************
3190 * Function : client_if_modified_since
3192 * Description : Remove or modify the If-Modified-Since header.
3195 * 1 : csp = Current client state (buffers, headers, etc...)
3196 * 2 : header = On input, pointer to header to modify.
3197 * On output, pointer to the modified header, or NULL
3198 * to remove the header. This function frees the
3199 * original string if necessary.
3201 * Returns : JB_ERR_OK on success, or
3202 * JB_ERR_MEMORY on out-of-memory error.
3204 *********************************************************************/
3205 jb_err client_if_modified_since(struct client_state *csp, char **header)
3208 #ifdef HAVE_GMTIME_R
3211 struct tm *timeptr = NULL;
3215 long int hours, minutes, seconds;
3219 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3222 * The client got an error message because of a temporary problem,
3223 * the problem is gone and the client now tries to revalidate our
3224 * error message on the real server. The revalidation would always
3225 * end with the transmission of the whole document and there is
3226 * no need to expose the bogus If-Modified-Since header.
3228 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3231 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3233 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3235 if ((0 == strcmpic(newval, "block")))
3237 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3240 else /* add random value */
3242 const char *header_time = *header + sizeof("If-Modified-Since:");
3244 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3246 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3251 rtime = strtol(newval, &endptr, 0);
3254 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3255 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3262 rtime = pick_from_range(rtime);
3266 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3269 tm += rtime * (negative ? -1 : 1);
3270 #ifdef HAVE_GMTIME_R
3271 timeptr = gmtime_r(&tm, &gmt);
3272 #elif FEATURE_PTHREAD
3273 pthread_mutex_lock(&gmtime_mutex);
3274 timeptr = gmtime(&tm);
3275 pthread_mutex_unlock(&gmtime_mutex);
3277 timeptr = gmtime(&tm);
3279 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3282 *header = strdup("If-Modified-Since: ");
3283 string_append(header, newheader);
3285 if (*header == NULL)
3287 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3288 return JB_ERR_MEMORY;
3291 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3293 hours = rtime / 3600;
3294 minutes = rtime / 60 % 60;
3295 seconds = rtime % 60;
3297 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3298 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3299 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3308 /*********************************************************************
3310 * Function : client_if_none_match
3312 * Description : Remove the If-None-Match header.
3315 * 1 : csp = Current client state (buffers, headers, etc...)
3316 * 2 : header = On input, pointer to header to modify.
3317 * On output, pointer to the modified header, or NULL
3318 * to remove the header. This function frees the
3319 * original string if necessary.
3321 * Returns : JB_ERR_OK on success, or
3322 * JB_ERR_MEMORY on out-of-memory error.
3324 *********************************************************************/
3325 jb_err client_if_none_match(struct client_state *csp, char **header)
3327 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3329 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3336 /*********************************************************************
3338 * Function : client_x_filter
3340 * Description : Disables filtering if the client set "X-Filter: No".
3341 * Called from `sed'.
3344 * 1 : csp = Current client state (buffers, headers, etc...)
3345 * 2 : header = On input, pointer to header to modify.
3346 * On output, pointer to the modified header, or NULL
3347 * to remove the header. This function frees the
3348 * original string if necessary.
3350 * Returns : JB_ERR_OK on success
3352 *********************************************************************/
3353 jb_err client_x_filter(struct client_state *csp, char **header)
3355 if ( 0 == strcmpic(*header, "X-Filter: No"))
3357 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3359 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3363 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3365 log_error(LOG_LEVEL_HEADER,
3366 "force-text-mode overruled the client's request to fetch without filtering!");
3370 csp->content_type = CT_TABOO;
3371 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
3372 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
3373 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3375 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3382 /* the following functions add headers directly to the header list */
3384 /*********************************************************************
3386 * Function : client_host_adder
3388 * Description : Adds the Host: header field if it is missing.
3389 * Called from `sed'.
3392 * 1 : csp = Current client state (buffers, headers, etc...)
3394 * Returns : JB_ERR_OK on success, or
3395 * JB_ERR_MEMORY on out-of-memory error.
3397 *********************************************************************/
3398 jb_err client_host_adder(struct client_state *csp)
3403 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3405 /* Header already set by the client, nothing to do. */
3409 if ( !csp->http->hostport || !*(csp->http->hostport))
3411 /* XXX: When does this happen and why is it OK? */
3412 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3417 * remove 'user:pass@' from 'proto://user:pass@host'
3419 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3425 p = csp->http->hostport;
3428 /* XXX: Just add it, we already made sure that it will be unique */
3429 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3430 err = enlist_unique_header(csp->headers, "Host", p);
3436 /*********************************************************************
3438 * Function : client_cookie_adder
3440 * Description : Used in the add_client_headers list. Called from `sed'.
3442 * XXX: Remove csp->cookie_list which is no longer used.
3445 * 1 : csp = Current client state (buffers, headers, etc...)
3447 * Returns : JB_ERR_OK on success, or
3448 * JB_ERR_MEMORY on out-of-memory error.
3450 *********************************************************************/
3451 jb_err client_cookie_adder(struct client_state *csp)
3453 struct list_entry *lst;
3455 struct list_entry *list1 = csp->cookie_list->first;
3456 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
3457 int first_cookie = 1;
3460 if ((list1 == NULL) && (list2 == NULL))
3466 tmp = strdup("Cookie: ");
3468 for (lst = list1; lst ; lst = lst->next)
3476 string_append(&tmp, "; ");
3478 string_append(&tmp, lst->str);
3481 for (lst = list2; lst ; lst = lst->next)
3489 string_append(&tmp, "; ");
3491 string_join(&tmp, cookie_encode(lst->str));
3496 return JB_ERR_MEMORY;
3499 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3500 err = enlist(csp->headers, tmp);
3506 /*********************************************************************
3508 * Function : client_accept_encoding_adder
3510 * Description : Add an Accept-Encoding header to the client's request
3511 * that disables compression if the action applies, and
3512 * the header is not already there. Called from `sed'.
3513 * Note: For HTTP/1.0, the absence of the header is enough.
3516 * 1 : csp = Current client state (buffers, headers, etc...)
3518 * Returns : JB_ERR_OK on success, or
3519 * JB_ERR_MEMORY on out-of-memory error.
3521 *********************************************************************/
3522 jb_err client_accept_encoding_adder(struct client_state *csp)
3524 assert(0); /* Not in use */
3526 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3527 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3529 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3536 /*********************************************************************
3538 * Function : client_xtra_adder
3540 * Description : Used in the add_client_headers list. Called from `sed'.
3543 * 1 : csp = Current client state (buffers, headers, etc...)
3545 * Returns : JB_ERR_OK on success, or
3546 * JB_ERR_MEMORY on out-of-memory error.
3548 *********************************************************************/
3549 jb_err client_xtra_adder(struct client_state *csp)
3551 struct list_entry *lst;
3554 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3555 lst ; lst = lst->next)
3557 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3558 err = enlist(csp->headers, lst->str);
3570 /*********************************************************************
3572 * Function : client_x_forwarded_adder
3574 * Description : Used in the add_client_headers list. Called from `sed'.
3577 * 1 : csp = Current client state (buffers, headers, etc...)
3579 * Returns : JB_ERR_OK on success, or
3580 * JB_ERR_MEMORY on out-of-memory error.
3582 *********************************************************************/
3583 jb_err client_x_forwarded_adder(struct client_state *csp)
3588 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3593 if (csp->x_forwarded)
3595 p = strdup(csp->x_forwarded);
3596 string_append(&p, ", ");
3600 p = strdup("X-Forwarded-For: ");
3602 string_append(&p, csp->ip_addr_str);
3606 return JB_ERR_MEMORY;
3609 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3610 err = enlist(csp->headers, p);
3617 /*********************************************************************
3619 * Function : connection_close_adder
3621 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3622 * support. Adds a "Connection: close" header to csp->headers
3623 * unless the header was already present. Called from `sed'.
3625 * FIXME: This whole function shouldn't be neccessary!
3628 * 1 : csp = Current client state (buffers, headers, etc...)
3630 * Returns : JB_ERR_OK on success, or
3631 * JB_ERR_MEMORY on out-of-memory error.
3633 *********************************************************************/
3634 jb_err connection_close_adder(struct client_state *csp)
3636 const unsigned int flags = csp->flags;
3639 * Return right away if
3641 * - we're parsing server headers and the server header
3642 * "Connection: close" is already set, or if
3644 * - we're parsing client headers and the client header
3645 * "Connection: close" is already set.
3647 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3648 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3649 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3650 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3655 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3657 return enlist(csp->headers, "Connection: close");
3661 /*********************************************************************
3663 * Function : server_http
3665 * Description : - Save the HTTP Status into csp->http->status
3666 * - Set CT_TABOO to prevent filtering if the answer
3667 * is a partial range (HTTP status 206)
3668 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3672 * 1 : csp = Current client state (buffers, headers, etc...)
3673 * 2 : header = On input, pointer to header to modify.
3674 * On output, pointer to the modified header, or NULL
3675 * to remove the header. This function frees the
3676 * original string if necessary.
3678 * Returns : JB_ERR_OK on success, or
3679 * JB_ERR_MEMORY on out-of-memory error.
3681 *********************************************************************/
3682 jb_err server_http(struct client_state *csp, char **header)
3684 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3685 if (csp->http->status == 206)
3687 csp->content_type = CT_TABOO;
3690 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3693 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3700 /*********************************************************************
3702 * Function : server_set_cookie
3704 * Description : Handle the server "cookie" header properly.
3705 * Log cookie to the jar file. Then "crunch",
3706 * accept or rewrite it to a session cookie.
3707 * Called from `sed'.
3709 * TODO: Allow the user to specify a new expiration
3710 * time to cause the cookie to expire even before the
3711 * browser is closed.
3714 * 1 : csp = Current client state (buffers, headers, etc...)
3715 * 2 : header = On input, pointer to header to modify.
3716 * On output, pointer to the modified header, or NULL
3717 * to remove the header. This function frees the
3718 * original string if necessary.
3720 * Returns : JB_ERR_OK on success, or
3721 * JB_ERR_MEMORY on out-of-memory error.
3723 *********************************************************************/
3724 jb_err server_set_cookie(struct client_state *csp, char **header)
3731 #ifdef FEATURE_COOKIE_JAR
3732 if (csp->config->jar)
3735 * Write timestamp into outbuf.
3737 * Complex because not all OSs have tm_gmtoff or
3738 * the %z field in strftime()
3740 char tempbuf[ BUFFER_SIZE ];
3742 #ifdef HAVE_LOCALTIME_R
3743 tm_now = *localtime_r(&now, &tm_now);
3744 #elif FEATURE_PTHREAD
3745 pthread_mutex_lock(&localtime_mutex);
3746 tm_now = *localtime (&now);
3747 pthread_mutex_unlock(&localtime_mutex);
3749 tm_now = *localtime (&now);
3751 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3753 /* strlen("set-cookie: ") = 12 */
3754 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3756 #endif /* def FEATURE_COOKIE_JAR */
3758 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3760 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3763 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3765 /* Flag whether or not to log a message */
3768 /* A variable to store the tag we're working on */
3771 /* Skip "Set-Cookie:" (11 characters) in header */
3772 cur_tag = *header + 11;
3774 /* skip whitespace between "Set-Cookie:" and value */
3775 while (*cur_tag && ijb_isspace(*cur_tag))
3780 /* Loop through each tag in the cookie */
3784 char *next_tag = strchr(cur_tag, ';');
3785 if (next_tag != NULL)
3787 /* Skip the ';' character itself */
3790 /* skip whitespace ";" and start of tag */
3791 while (*next_tag && ijb_isspace(*next_tag))
3798 /* "Next tag" is the end of the string */
3799 next_tag = cur_tag + strlen(cur_tag);
3803 * Check the expiration date to see
3804 * if the cookie is still valid, if yes,
3805 * rewrite it to a session cookie.
3807 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3809 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3811 /* Did we detect the date properly? */
3812 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3815 * Nope, treat it as if it was still valid.
3817 * XXX: Should we remove the whole cookie instead?
3819 log_error(LOG_LEVEL_ERROR,
3820 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3821 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3827 * Yes. Check if the cookie is still valid.
3829 * If the cookie is already expired it's probably
3830 * a delete cookie and even if it isn't, the browser
3831 * will discard it anyway.
3835 * XXX: timegm() isn't available on some AmigaOS
3836 * versions and our replacement doesn't work.
3838 * Our options are to either:
3840 * - disable session-cookies-only completely if timegm
3843 * - to simply remove all expired tags, like it has
3844 * been done until Privoxy 3.0.6 and to live with
3845 * the consequence that it can cause login/logout
3846 * problems on servers that don't validate their
3847 * input properly, or
3849 * - to replace it with mktime in which
3850 * case there is a slight chance of valid cookies
3851 * passing as already expired.
3853 * This is the way it's currently done and it's not
3854 * as bad as it sounds. If the missing GMT offset is
3855 * enough to change the result of the expiration check
3856 * the cookie will be only valid for a few hours
3857 * anyway, which in many cases will be shorter
3858 * than a browser session.
3860 if (cookie_time - now < 0)
3862 log_error(LOG_LEVEL_HEADER,
3863 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3864 /* Just in case some clown sets more then one expiration date */
3870 * Still valid, delete expiration date by copying
3871 * the rest of the string over it.
3873 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3874 * since the behaviour of strcpy is undefined for overlapping
3877 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3879 /* That changed the header, need to issue a log message */
3883 * Note that the next tag has now been moved to *cur_tag,
3884 * so we do not need to update the cur_tag pointer.
3892 /* Move on to next cookie tag */
3899 assert(NULL != *header);
3900 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3909 #ifdef FEATURE_FORCE_LOAD
3910 /*********************************************************************
3912 * Function : strclean
3914 * Description : In-Situ-Eliminate all occurances of substring in
3918 * 1 : string = string to clean
3919 * 2 : substring = substring to eliminate
3921 * Returns : Number of eliminations
3923 *********************************************************************/
3924 int strclean(const char *string, const char *substring)
3930 len = strlen(substring);
3932 while((pos = strstr(string, substring)) != NULL)
3939 while (*p++ != '\0');
3946 #endif /* def FEATURE_FORCE_LOAD */
3948 /*********************************************************************
3950 * Function : parse_header_time
3952 * Description : Parses time formats used in HTTP header strings
3953 * to get the numerical respresentation.
3956 * 1 : header_time = HTTP header time as string.
3957 * 2 : result = storage for header_time in seconds
3959 * Returns : JB_ERR_OK if the time format was recognized, or
3960 * JB_ERR_PARSE otherwise.
3962 *********************************************************************/
3963 jb_err parse_header_time(const char *header_time, time_t *result)
3968 * Zero out gmt to prevent time zone offsets.
3970 * While this is only necessary on some platforms
3971 * (mingw32 for example), I don't know how to
3972 * detect these automatically and doing it everywhere
3975 memset(&gmt, 0, sizeof(gmt));
3977 /* Tue, 02 Jun 2037 20:00:00 */
3978 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3979 /* Tue, 02-Jun-2037 20:00:00 */
3980 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3981 /* Tue, 02-Jun-37 20:00:00 */
3982 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3983 /* Tuesday, 02-Jun-2037 20:00:00 */
3984 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3985 /* Tuesday Jun 02 20:00:00 2037 */
3986 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3988 return JB_ERR_PARSE;
3991 *result = timegm(&gmt);
3997 /*********************************************************************
3999 * Function : get_destination_from_headers
4001 * Description : Parse the "Host:" header to get the request's destination.
4002 * Only needed if the client's request was forcefully
4003 * redirected into Privoxy.
4005 * Code mainly copied from client_host() which is currently
4006 * run too late for this purpose.
4009 * 1 : headers = List of headers (one of them hopefully being
4010 * the "Host:" header)
4011 * 2 : http = storage for the result (host, port and hostport).
4013 * Returns : JB_ERR_MEMORY in case of memory problems,
4014 * JB_ERR_PARSE if the host header couldn't be found,
4015 * JB_ERR_OK otherwise.
4017 *********************************************************************/
4018 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4024 host = get_header_value(headers, "Host:");
4028 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4029 return JB_ERR_PARSE;
4032 if (NULL == (p = strdup((host))))
4034 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4035 return JB_ERR_MEMORY;
4038 if (NULL == (q = strdup(p)))
4041 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4042 return JB_ERR_MEMORY;
4045 freez(http->hostport);
4049 q = strchr(http->host, ':');
4052 /* Terminate hostname and evaluate port string */
4054 http->port = atoi(q);
4058 http->port = http->ssl ? 443 : 80;
4061 /* Rebuild request URL */
4063 http->url = strdup(http->ssl ? "https://" : "http://");
4064 string_append(&http->url, http->hostport);
4065 string_append(&http->url, http->path);
4066 if (http->url == NULL)
4068 return JB_ERR_MEMORY;
4071 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",