1 const char parsers_rcs[] = "$Id: parsers.c,v 1.102 2007/05/27 12:39:32 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.102 2007/05/27 12:39:32 fabiankeil
48 * Adjust "X-Filter: No" to disable dedicated header filters.
50 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
51 * Streamline client_cookie_adder().
53 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
54 * Make sure filters with dynamic jobs actually use them.
56 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
57 * - Introduce dynamic pcrs jobs that can resolve variables.
58 * - Remove unnecessary update_action_bits_for_all_tags() call.
60 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
61 * - Make tagging based on tags set by earlier taggers
62 * of the same kind possible.
63 * - Log whether or not new tags cause action bits updates
64 * (in which case a matching tag-pattern section exists).
65 * - Log if the user tries to set a tag that is already set.
67 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
68 * Introduce tags as alternative way to specify which
69 * actions apply to a request. At the moment tags can be
70 * created based on client and server headers.
72 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
73 * Log a warning if the content is compressed, filtering is
74 * enabled and Privoxy was compiled without zlib support.
77 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
78 * - Fix warnings when compiled with glibc.
79 * - Don't use crumble() for cookie crunching.
80 * - Move cookie time parsing into parse_header_time().
81 * - Let parse_header_time() return a jb_err code
82 * instead of a pointer that can only be used to
83 * check for NULL anyway.
85 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
86 * - Add better protection against malicious gzip headers.
87 * - Stop logging the first hundred bytes of decompressed content.
88 * It looks like it's working and there is always debug 16.
89 * - Log the content size after decompression in decompress_iob()
90 * instead of pcrs_filter_response().
92 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
93 * - Use dedicated header filter actions instead of abusing "filter".
94 * Replace "filter-client-headers" and "filter-client-headers"
95 * with "server-header-filter" and "client-header-filter".
96 * - Remove filter_client_header() and filter_client_header(),
97 * filter_header() now checks the shiny new
98 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
100 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
101 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
102 * - Handle "Cookie:" and "Connection:" headers a bit smarter
103 * (don't crunch them just to recreate them later on).
104 * - Add another non-standard time format for the cookie
105 * expiration date detection.
106 * - Fix a valgrind warning.
108 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
109 * Improve cookie expiration date detection.
111 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
112 * Don't run server_content_length() the first time
113 * sed() parses server headers; only adjust the
114 * Content-Length header if the page was modified.
116 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
117 * Fix log messages regarding the cookie time format
118 * (cookie and request URL were mixed up).
120 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
121 * - Let decompress_iob()
122 * - not corrupt the content if decompression fails
123 * early. (the first byte(s) were lost).
124 * - use pointer arithmetics with defined outcome for
126 * - Use a different kludge to remember a failed decompression.
128 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
129 * Search for Max-Forwards headers case-insensitive,
130 * don't generate the "501 unsupported" message for invalid
131 * Max-Forwards values and don't increase negative ones.
133 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
134 * - Let server_set_cookie() check the expiration date
135 * of cookies and don't touch the ones that are already
136 * expired. Fixes problems with low quality web applications
137 * as described in BR 932612.
139 * - Adjust comment in client_max_forwards to reality;
140 * remove invalid Max-Forwards headers.
142 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
143 * Stop filter_header() from unintentionally removing
144 * empty header lines that were enlisted by the continue
147 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
148 * - Repeat the request URL before logging any headers.
149 * Makes reading the log easier in case of simultaneous requests.
150 * - If there are more than one Content-Type headers in one request,
151 * use the first one and remove the others.
152 * - Remove "newval" variable in server_content_type().
153 * It's only used once.
155 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
156 * Correct a cast, check inflateEnd() exit code
157 * to see if we have to, replace sprintf calls
160 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
161 * Integrate a modified version of Wil Mahan's
162 * zlib patch (PR #895531).
164 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
165 * Skip empty filter files in filter_header()
166 * but don't ignore the ones that come afterwards.
167 * Fixes BR 1619208, this time for real.
169 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
170 * Reverted parts of my last commit
171 * to keep error handling working.
173 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
174 * Fixed gcc43 conversion warnings.
176 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
177 * Bringing back the "useless" localtime() call
178 * I removed in revision 1.67. On some platforms
179 * it's necessary to prevent time zone offsets.
181 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
182 * Rebuild request URL in get_destination_from_headers()
183 * to make sure redirect{pcrs command} works as expected
184 * for intercepted requests.
186 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
187 * Added get_destination_from_headers().
189 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
190 * Make pthread mutex locking more generic. Instead of
191 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
192 * and use mutex locking unless there is an _r function
193 * available. Better safe than sorry.
195 * Fixes "./configure --disable-pthread" and should result
196 * in less threading-related problems on pthread-using platforms,
197 * but it still doesn't fix BR#1122404.
199 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
200 * The special header "X-Filter: No" now disables
201 * header filtering as well.
203 * Revision 1.73 2006/09/23 13:26:38 roro
204 * Replace TABs by spaces in source code.
206 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
207 * Don't print a log message every time filter_headers is
208 * entered or left. It only creates noise without any real
211 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
212 * Fix +hide-if-modified-since{-n}.
214 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
215 * Have hide-if-modified-since interpret the random
216 * range value as minutes instead of hours. Allows
217 * more fine-grained configuration.
219 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
220 * Always have parse_header_time return a pointer
221 * that actual makes sense, even though we currently
222 * only need it to detect problems.
224 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
225 * Added config option enable-remote-http-toggle
226 * to specify if Privoxy should recognize special
227 * headers (currently only X-Filter) to change its
228 * behaviour. Disabled by default.
230 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
231 * After filtering de-chunked instances, remove
232 * "Transfer-Encoding" header entirely instead of changing
233 * it to "Transfer-Encoding: identity", which is invalid.
234 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
236 * Don't use localtime in parse_header_time. An empty time struct
237 * is good enough, it gets overwritten by strptime anyway.
239 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
240 * Use gmtime_r if available, fallback to gmtime with mutex
241 * protection for MacOSX and use vanilla gmtime for the rest.
243 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
244 * Changed client_referrer to use the right type (size_t) for
245 * hostlenght and to shorten the temporary referrer string with
246 * '\0' instead of adding a useless line break.
248 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
249 * - Back to timegm() using GnuPG's replacement if necessary.
250 * Using mktime() and localtime() could add a on hour offset if
251 * the randomize factor was big enough to lead to a summer/wintertime
254 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
256 * - Moved randomization code into pick_from_range().
258 * - Changed parse_header_time definition.
259 * time_t isn't guaranteed to be signed and
260 * if it isn't, -1 isn't available as error code.
261 * Changed some variable types in client_if_modified_since()
262 * because of the same reason.
264 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
265 * OS/2 compilation compatibility fixups
267 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
268 * Changed include from strptime.c to strptime.h
270 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
271 * Split filter-headers{} into filter-client-headers{}
272 * and filter-server-headers{}.
273 * Added parse_header_time() to share some code.
274 * Replaced timegm() with mktime().
276 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
277 * Windows service integration
279 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
280 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
282 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
283 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
284 * with what was really the latest development (the v_3_0_branch branch)
286 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
287 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
289 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
290 * Add the ability to check jpeg images for invalid
291 * lengths of comment blocks. Defensive strategy
292 * against the exploit:
293 * Microsoft Security Bulletin MS04-028
294 * Buffer Overrun in JPEG Processing (GDI+) Could
295 * Allow Code Execution (833987)
296 * Enabled with +inspect-jpegs in actions files.
298 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
299 * Excluded text/plain objects from filtering. This fixes a
300 * couple of client-crashing, download corruption and
301 * Privoxy performance issues, whose root cause lies in
302 * web servers labelling content of unknown type as text/plain.
304 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
305 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
307 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
308 * Completing the previous change
310 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
311 * Added temporary workaround for bug in PHP < 4.2.3
313 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
314 * 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.
316 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
317 * Fix typo: supressed -> suppressed
319 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
320 * Improved cookie logging
322 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
323 * Added basic support for OPTIONS and TRACE HTTP methods:
324 * - New parser function client_max_forwards which decrements
325 * the Max-Forwards HTTP header field of OPTIONS and TRACE
326 * requests by one before forwarding
327 * - New parser function client_host which extracts the host
328 * and port information from the HTTP header field if the
329 * request URI was not absolute
330 * - Don't crumble and re-add the Host: header, but only generate
331 * and append if missing
333 * Revision 1.56 2002/05/12 15:34:22 jongfoster
334 * Fixing typo in a comment
336 * Revision 1.55 2002/05/08 16:01:07 oes
337 * Optimized add_to_iob:
338 * - Use realloc instead of malloc(), memcpy(), free()
339 * - Expand to powers of two if possible, to get
340 * O(log n) reallocs instead of O(n).
341 * - Moved check for buffer limit here from chat
342 * - Report failure via returncode
344 * Revision 1.54 2002/04/02 15:03:16 oes
345 * Tiny code cosmetics
347 * Revision 1.53 2002/03/26 22:29:55 swa
348 * we have a new homepage!
350 * Revision 1.52 2002/03/24 13:25:43 swa
351 * name change related issues
353 * Revision 1.51 2002/03/13 00:27:05 jongfoster
356 * Revision 1.50 2002/03/12 01:45:35 oes
357 * More verbose logging
359 * Revision 1.49 2002/03/09 20:03:52 jongfoster
360 * - Making various functions return int rather than size_t.
361 * (Undoing a recent change). Since size_t is unsigned on
362 * Windows, functions like read_socket that return -1 on
363 * error cannot return a size_t.
365 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
366 * crashes, and also frequently caused JB to jump to 100%
367 * CPU and stay there. (Because it thought it had just
368 * read ((unsigned)-1) == 4Gb of data...)
370 * - The signature of write_socket has changed, it now simply
371 * returns success=0/failure=nonzero.
373 * - Trying to get rid of a few warnings --with-debug on
374 * Windows, I've introduced a new type "jb_socket". This is
375 * used for the socket file descriptors. On Windows, this
376 * is SOCKET (a typedef for unsigned). Everywhere else, it's
377 * an int. The error value can't be -1 any more, so it's
378 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
379 * Windows it maps to the #define INVALID_SOCKET.)
381 * - The signature of bind_port has changed.
383 * Revision 1.48 2002/03/07 03:46:53 oes
384 * Fixed compiler warnings etc
386 * Revision 1.47 2002/02/20 23:15:13 jongfoster
387 * Parsing functions now handle out-of-memory gracefully by returning
390 * Revision 1.46 2002/01/17 21:03:47 jongfoster
391 * Moving all our URL and URL pattern parsing code to urlmatch.c.
393 * Revision 1.45 2002/01/09 14:33:03 oes
394 * Added support for localtime_r.
396 * Revision 1.44 2001/12/14 01:22:54 steudten
397 * Remove 'user:pass@' from 'proto://user:pass@host' for the
398 * new added header 'Host: ..'. (See Req ID 491818)
400 * Revision 1.43 2001/11/23 00:26:38 jongfoster
401 * Fixing two really stupid errors in my previous commit
403 * Revision 1.42 2001/11/22 21:59:30 jongfoster
404 * Adding code to handle +no-cookies-keep
406 * Revision 1.41 2001/11/05 23:43:05 steudten
407 * Add time+date to log files.
409 * Revision 1.40 2001/10/26 20:13:09 jongfoster
410 * ctype.h is needed in Windows, too.
412 * Revision 1.39 2001/10/26 17:40:04 oes
413 * Introduced get_header_value()
414 * Removed http->user_agent, csp->referrer and csp->accept_types
415 * Removed client_accept()
417 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
418 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
419 * threads to call select() simultaneously. So, it's time to do a real, live,
420 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
421 * (native). Both versions will work, but using __OS2__ offers multi-threading.
423 * Revision 1.37 2001/10/23 21:36:02 jongfoster
424 * Documenting sed()'s error behaviou (doc change only)
426 * Revision 1.36 2001/10/13 12:51:51 joergs
427 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
428 * force-load), instead crumble Host: and add it (again) in client_host_adder
429 * (in case we get a HTTP/1.0 request without Host: header and forward it to
430 * a HTTP/1.1 server/proxy).
432 * Revision 1.35 2001/10/09 22:39:21 jongfoster
433 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
436 * Revision 1.34 2001/10/07 18:50:55 oes
437 * Added server_content_encoding, renamed server_transfer_encoding
439 * Revision 1.33 2001/10/07 18:04:49 oes
440 * Changed server_http11 to server_http and its pattern to "HTTP".
441 * Additional functionality: it now saves the HTTP status into
442 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
444 * Revision 1.32 2001/10/07 15:43:28 oes
445 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
446 * client_te and client_accept_encoding_adder, triggered by the new
447 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
448 * changed to allow only identity and chunked, and the TE header is
449 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
451 * parse_http_request no longer does anything than parsing. The rewriting
452 * of http->cmd and version mangling are gone. It now also recognizes
453 * the put and delete methods and saves the url in http->url. Removed
456 * renamed content_type and content_length to have the server_ prefix
458 * server_content_type now only works if csp->content_type != CT_TABOO
460 * added server_transfer_encoding, which
461 * - Sets CT_TABOO to prohibit filtering if encoding compresses
462 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
463 * - Change from "chunked" to "identity" if body was chunked
464 * but has been de-chunked for filtering.
466 * added server_content_md5 which crunches any Content-MD5 headers
467 * if the body was modified.
469 * made server_http11 conditional on +downgrade action
471 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
473 * Revision 1.31 2001/10/05 14:25:02 oes
474 * Crumble Keep-Alive from Server
476 * Revision 1.30 2001/09/29 12:56:03 joergs
477 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
479 * Revision 1.29 2001/09/24 21:09:24 jongfoster
480 * Fixing 2 memory leaks that Guy spotted, where the paramater to
481 * enlist() was not being free()d.
483 * Revision 1.28 2001/09/22 16:32:28 jongfoster
484 * Removing unused #includes.
486 * Revision 1.27 2001/09/20 15:45:25 steudten
488 * add casting from size_t to int for printf()
489 * remove local variable shadow s2
491 * Revision 1.26 2001/09/16 17:05:14 jongfoster
492 * Removing unused #include showarg.h
494 * Revision 1.25 2001/09/16 13:21:27 jongfoster
495 * Changes to use new list functions.
497 * Revision 1.24 2001/09/13 23:05:50 jongfoster
498 * Changing the string paramater to the header parsers a "const".
500 * Revision 1.23 2001/09/12 18:08:19 steudten
502 * In parse_http_request() header rewriting miss the host value, so
503 * from http://www.mydomain.com the result was just " / " not
504 * http://www.mydomain.com/ in case we forward.
506 * Revision 1.22 2001/09/10 10:58:53 oes
507 * Silenced compiler warnings
509 * Revision 1.21 2001/07/31 14:46:00 oes
510 * - Persistant connections now suppressed
511 * - sed() no longer appends empty header to csp->headers
513 * Revision 1.20 2001/07/30 22:08:36 jongfoster
514 * Tidying up #defines:
515 * - All feature #defines are now of the form FEATURE_xxx
516 * - Permanently turned off WIN_GUI_EDIT
517 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
519 * Revision 1.19 2001/07/25 17:21:54 oes
520 * client_uagent now saves copy of User-Agent: header value
522 * Revision 1.18 2001/07/13 14:02:46 oes
523 * - Included fix to repair broken HTTP requests that
524 * don't contain a path, not even '/'.
525 * - Removed all #ifdef PCRS
526 * - content_type now always inspected and classified as
527 * text, gif or other.
528 * - formatting / comments
530 * Revision 1.17 2001/06/29 21:45:41 oes
531 * Indentation, CRLF->LF, Tab-> Space
533 * Revision 1.16 2001/06/29 13:32:42 oes
535 * - Adapted free_http_request
536 * - Removed logentry from cancelled commit
538 * Revision 1.15 2001/06/03 19:12:38 oes
539 * deleted const struct interceptors
541 * Revision 1.14 2001/06/01 18:49:17 jongfoster
542 * Replaced "list_share" with "list" - the tiny memory gain was not
543 * worth the extra complexity.
545 * Revision 1.13 2001/05/31 21:30:33 jongfoster
546 * Removed list code - it's now in list.[ch]
547 * Renamed "permission" to "action", and changed many features
548 * to use the actions file rather than the global config.
550 * Revision 1.12 2001/05/31 17:33:13 oes
554 * Revision 1.11 2001/05/29 20:11:19 joergs
555 * '/ * inside comment' warning removed.
557 * Revision 1.10 2001/05/29 09:50:24 jongfoster
558 * Unified blocklist/imagelist/permissionslist.
559 * File format is still under discussion, but the internal changes
562 * Also modified interceptor behaviour:
563 * - We now intercept all URLs beginning with one of the following
564 * prefixes (and *only* these prefixes):
566 * * http://ijbswa.sf.net/config/
567 * * http://ijbswa.sourceforge.net/config/
568 * - New interceptors "home page" - go to http://i.j.b/ to see it.
569 * - Internal changes so that intercepted and fast redirect pages
570 * are not replaced with an image.
571 * - Interceptors now have the option to send a binary page direct
572 * to the client. (i.e. ijb-send-banner uses this)
573 * - Implemented show-url-info interceptor. (Which is why I needed
574 * the above interceptors changes - a typical URL is
575 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
576 * The previous mechanism would not have intercepted that, and
577 * if it had been intercepted then it then it would have replaced
580 * Revision 1.9 2001/05/28 17:26:33 jongfoster
581 * Fixing segfault if last header was crunched.
582 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
583 * can use the cross-platform sprintf() instead.)
585 * Revision 1.8 2001/05/27 22:17:04 oes
587 * - re_process_buffer no longer writes the modified buffer
588 * to the client, which was very ugly. It now returns the
589 * buffer, which it is then written by chat.
591 * - content_length now adjusts the Content-Length: header
592 * for modified documents rather than crunch()ing it.
593 * (Length info in csp->content_length, which is 0 for
594 * unmodified documents)
596 * - For this to work, sed() is called twice when filtering.
598 * Revision 1.7 2001/05/27 13:19:06 oes
599 * Patched Joergs solution for the content-length in.
601 * Revision 1.6 2001/05/26 13:39:32 jongfoster
602 * Only crunches Content-Length header if applying RE filtering.
603 * Without this fix, Microsoft Windows Update wouldn't work.
605 * Revision 1.5 2001/05/26 00:28:36 jongfoster
606 * Automatic reloading of config file.
607 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
608 * Most of the global variables have been moved to a new
609 * struct configuration_spec, accessed through csp->config->globalname
610 * Most of the globals remaining are used by the Win32 GUI.
612 * Revision 1.4 2001/05/22 18:46:04 oes
614 * - Enabled filtering banners by size rather than URL
615 * by adding patterns that replace all standard banner
616 * sizes with the "Junkbuster" gif to the re_filterfile
618 * - Enabled filtering WebBugs by providing a pattern
619 * which kills all 1x1 images
621 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
622 * which is selected by the (nonstandard and therefore
623 * capital) letter 'U' in the option string.
624 * It causes the quantifiers to be ungreedy by default.
625 * Appending a ? turns back to greedy (!).
627 * - Added a new interceptor ijb-send-banner, which
628 * sends back the "Junkbuster" gif. Without imagelist or
629 * MSIE detection support, or if tinygif = 1, or the
630 * URL isn't recognized as an imageurl, a lame HTML
631 * explanation is sent instead.
633 * - Added new feature, which permits blocking remote
634 * script redirects and firing back a local redirect
636 * The feature is conditionally compiled, i.e. it
637 * can be disabled with --disable-fast-redirects,
638 * plus it must be activated by a "fast-redirects"
639 * line in the config file, has its own log level
640 * and of course wants to be displayed by show-proxy-args
641 * Note: Boy, all the #ifdefs in 1001 locations and
642 * all the fumbling with configure.in and acconfig.h
643 * were *way* more work than the feature itself :-(
645 * - Because a generic redirect template was needed for
646 * this, tinygif = 3 now uses the same.
648 * - Moved GIFs, and other static HTTP response templates
653 * - Removed some >400 CRs again (Jon, you really worked
656 * Revision 1.3 2001/05/20 01:21:20 jongfoster
657 * Version 2.9.4 checkin.
658 * - Merged popupfile and cookiefile, and added control over PCRS
659 * filtering, in new "permissionsfile".
660 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
661 * file error you now get a message box (in the Win32 GUI) rather
662 * than the program exiting with no explanation.
663 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
665 * - Removed tabs from "config"
666 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
667 * - Bumped up version number.
669 * Revision 1.2 2001/05/17 23:02:36 oes
670 * - Made referrer option accept 'L' as a substitute for '§'
672 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
673 * Initial import of version 2.9.3 source tree
676 *********************************************************************/
683 #include <sys/types.h>
693 * Convince GNU's libc to provide a strptime prototype.
696 #endif /*__GLIBC__ */
703 #if !defined(_WIN32) && !defined(__OS2__)
709 #ifdef FEATURE_PTHREAD
711 /* jcc.h is for mutex semapores only */
712 #endif /* def FEATURE_PTHREAD */
718 #include "jbsockets.h"
719 #include "miscutil.h"
724 #ifndef HAVE_STRPTIME
725 #include "strptime.h"
728 const char parsers_h_rcs[] = PARSERS_H_VERSION;
730 /* Fix a problem with Solaris. There should be no effect on other
732 * Solaris's isspace() is a macro which uses its argument directly
733 * as an array index. Therefore we need to make sure that high-bit
734 * characters generate +ve values, and ideally we also want to make
735 * the argument match the declared parameter type of "int".
737 * Why did they write a character function that can't take a simple
738 * "char" argument? Doh!
740 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
741 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
743 jb_err header_tagger(struct client_state *csp, char *header);
744 jb_err scan_headers(struct client_state *csp);
746 const struct parsers client_patterns[] = {
747 { "referer:", 8, client_referrer },
748 { "user-agent:", 11, client_uagent },
749 { "ua-", 3, client_ua },
750 { "from:", 5, client_from },
751 { "cookie:", 7, client_send_cookie },
752 { "x-forwarded-for:", 16, client_x_forwarded },
753 { "Accept-Encoding:", 16, client_accept_encoding },
754 { "TE:", 3, client_te },
755 { "Host:", 5, client_host },
756 { "if-modified-since:", 18, client_if_modified_since },
757 { "Keep-Alive:", 11, crumble },
758 { "connection:", 11, connection },
759 { "proxy-connection:", 17, crumble },
760 { "max-forwards:", 13, client_max_forwards },
761 { "Accept-Language:", 16, client_accept_language },
762 { "if-none-match:", 14, client_if_none_match },
763 { "X-Filter:", 9, client_x_filter },
764 { "*", 0, crunch_client_header },
765 { "*", 0, filter_header },
769 const struct parsers server_patterns[] = {
770 { "HTTP", 4, server_http },
771 { "set-cookie:", 11, server_set_cookie },
772 { "connection:", 11, connection },
773 { "Content-Type:", 13, server_content_type },
774 { "Content-MD5:", 12, server_content_md5 },
775 { "Content-Encoding:", 17, server_content_encoding },
776 { "Transfer-Encoding:", 18, server_transfer_coding },
777 { "Keep-Alive:", 11, crumble },
778 { "content-disposition:", 20, server_content_disposition },
779 { "Last-Modified:", 14, server_last_modified },
780 { "*", 0, crunch_server_header },
781 { "*", 0, filter_header },
785 const struct parsers server_patterns_light[] = {
786 { "Content-Length:", 15, server_content_length },
787 { "Transfer-Encoding:", 18, server_transfer_coding },
789 { "Content-Encoding:", 17, server_content_encoding },
790 #endif /* def FEATURE_ZLIB */
794 const add_header_func_ptr add_client_headers[] = {
797 client_x_forwarded_adder,
799 /* Temporarily disabled: client_accept_encoding_adder, */
800 connection_close_adder,
805 const add_header_func_ptr add_server_headers[] = {
806 connection_close_adder,
810 /*********************************************************************
812 * Function : flush_socket
814 * Description : Write any pending "buffered" content.
817 * 1 : fd = file descriptor of the socket to read
818 * 2 : csp = Current client state (buffers, headers, etc...)
820 * Returns : On success, the number of bytes written are returned (zero
821 * indicates nothing was written). On error, -1 is returned,
822 * and errno is set appropriately. If count is zero and the
823 * file descriptor refers to a regular file, 0 will be
824 * returned without causing any other effect. For a special
825 * file, the results are not portable.
827 *********************************************************************/
828 int flush_socket(jb_socket fd, struct client_state *csp)
830 struct iob *iob = csp->iob;
831 int len = iob->eod - iob->cur;
838 if (write_socket(fd, iob->cur, (size_t)len))
842 iob->eod = iob->cur = iob->buf;
848 /*********************************************************************
850 * Function : add_to_iob
852 * Description : Add content to the buffered page, expanding the
853 * buffer if necessary.
856 * 1 : csp = Current client state (buffers, headers, etc...)
857 * 2 : buf = holds the content to be added to the page
858 * 3 : n = number of bytes to be added
860 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
861 * or buffer limit reached.
863 *********************************************************************/
864 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
866 struct iob *iob = csp->iob;
867 size_t used, offset, need, want;
870 if (n <= 0) return JB_ERR_OK;
872 used = (size_t)(iob->eod - iob->buf);
873 offset = (size_t)(iob->cur - iob->buf);
874 need = used + (size_t)n + 1;
877 * If the buffer can't hold the new data, extend it first.
878 * Use the next power of two if possible, else use the actual need.
880 if (need > csp->config->buffer_limit)
882 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
883 return JB_ERR_MEMORY;
886 if (need > iob->size)
888 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
890 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
894 else if (NULL != (p = (char *)realloc(iob->buf, need)))
900 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
901 return JB_ERR_MEMORY;
904 /* Update the iob pointers */
905 iob->cur = p + offset;
910 /* copy the new data into the iob buffer */
911 memcpy(iob->eod, buf, (size_t)n);
913 /* point to the end of the data */
916 /* null terminate == cheap insurance */
925 /*********************************************************************
927 * Function : decompress_iob
929 * Description : Decompress buffered page, expanding the
930 * buffer as necessary. csp->iob->cur
931 * should point to the the beginning of the
932 * compressed data block.
935 * 1 : csp = Current client state (buffers, headers, etc...)
937 * Returns : JB_ERR_OK on success,
938 * JB_ERR_MEMORY if out-of-memory limit reached, and
939 * JB_ERR_COMPRESS if error decompressing buffer.
941 *********************************************************************/
942 jb_err decompress_iob(struct client_state *csp)
944 char *buf; /* new, uncompressed buffer */
945 char *cur; /* Current iob position (to keep the original
946 * iob->cur unmodified if we return early) */
947 size_t bufsize; /* allocated size of the new buffer */
948 size_t old_size; /* Content size before decompression */
949 size_t skip_size; /* Number of bytes at the beginning of the iob
950 that we should NOT decompress. */
951 int status; /* return status of the inflate() call */
952 z_stream zstr; /* used by calls to zlib */
954 assert(csp->iob->cur - csp->iob->buf > 0);
955 assert(csp->iob->eod - csp->iob->cur > 0);
957 bufsize = csp->iob->size;
958 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
959 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
966 * This is to protect the parsing of gzipped data,
967 * but it should(?) be valid for deflated data also.
969 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
970 return JB_ERR_COMPRESS;
973 if (csp->content_type & CT_GZIP)
976 * Our task is slightly complicated by the facts that data
977 * compressed by gzip does not include a zlib header, and
978 * that there is no easily accessible interface in zlib to
979 * handle a gzip header. We strip off the gzip header by
980 * hand, and later inform zlib not to expect a header.
984 * Strip off the gzip header. Please see RFC 1952 for more
985 * explanation of the appropriate fields.
987 if ((*cur++ != (char)0x1f)
988 || (*cur++ != (char)0x8b)
989 || (*cur++ != Z_DEFLATED))
991 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
992 return JB_ERR_COMPRESS;
998 * XXX: These magic numbers should be replaced
999 * with macros to give a better idea what they do.
1003 /* The gzip header has reserved bits set; bail out. */
1004 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1005 return JB_ERR_COMPRESS;
1009 /* Skip extra fields if necessary. */
1013 * Skip a given number of bytes, specified
1014 * as a 16-bit little-endian value.
1017 * XXX: This code used to be:
1019 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1021 * which I had to change into:
1023 * cur += *cur++ + (*cur++ << 8);
1025 * at which point gcc43 finally noticed that the value
1026 * of cur is undefined (it depends on which of the
1027 * summands is evaluated first).
1029 * I haven't come across a site where this
1030 * code is actually executed yet, but I hope
1034 skip_bytes = *cur++;
1035 skip_bytes = *cur++ << 8;
1037 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1040 * The number of bytes to skip should be positive
1041 * and we'd like to stay in the buffer.
1043 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1045 log_error (LOG_LEVEL_ERROR,
1046 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1048 return JB_ERR_COMPRESS;
1050 log_error (LOG_LEVEL_INFO,
1051 "Skipping %d bytes for gzip compression. Does this sound right?",
1056 /* Skip the filename if necessary. */
1059 /* A null-terminated string is supposed to follow. */
1060 while (*cur++ && (cur < csp->iob->eod));
1064 /* Skip the comment if necessary. */
1067 /* A null-terminated string is supposed to follow. */
1068 while (*cur++ && (cur < csp->iob->eod));
1071 /* Skip the CRC if necessary. */
1077 if (cur >= csp->iob->eod)
1080 * If the current position pointer reached or passed
1081 * the buffer end, we were obviously tricked to skip
1084 log_error (LOG_LEVEL_ERROR,
1085 "Malformed gzip header detected. Aborting decompression.");
1086 return JB_ERR_COMPRESS;
1090 else if (csp->content_type & CT_DEFLATE)
1093 * XXX: The debug level should be lowered
1094 * before the next stable release.
1096 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1098 * In theory (that is, according to RFC 1950), deflate-compressed
1099 * data should begin with a two-byte zlib header and have an
1100 * adler32 checksum at the end. It seems that in practice only
1101 * the raw compressed data is sent. Note that this means that
1102 * we are not RFC 1950-compliant here, but the advantage is that
1103 * this actually works. :)
1105 * We add a dummy null byte to tell zlib where the data ends,
1106 * and later inform it not to expect a header.
1108 * Fortunately, add_to_iob() has thoughtfully null-terminated
1109 * the buffer; we can just increment the end pointer to include
1116 log_error (LOG_LEVEL_ERROR,
1117 "Unable to determine compression format for decompression");
1118 return JB_ERR_COMPRESS;
1121 /* Set up the fields required by zlib. */
1122 zstr.next_in = (Bytef *)cur;
1123 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1124 zstr.zalloc = Z_NULL;
1125 zstr.zfree = Z_NULL;
1126 zstr.opaque = Z_NULL;
1129 * Passing -MAX_WBITS to inflateInit2 tells the library
1130 * that there is no zlib header.
1132 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1134 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1135 return JB_ERR_COMPRESS;
1139 * Next, we allocate new storage for the inflated data.
1140 * We don't modify the existing iob yet, so in case there
1141 * is error in decompression we can recover gracefully.
1143 buf = zalloc (bufsize);
1146 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1147 return JB_ERR_MEMORY;
1150 assert(bufsize >= skip_size);
1151 memcpy(buf, csp->iob->buf, skip_size);
1152 zstr.avail_out = bufsize - skip_size;
1153 zstr.next_out = (Bytef *)buf + skip_size;
1155 /* Try to decompress the whole stream in one shot. */
1156 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1158 /* We need to allocate more memory for the output buffer. */
1160 char *tmpbuf; /* used for realloc'ing the buffer */
1161 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1164 * If zlib wants more data then there's a problem, because
1165 * the complete compressed file should have been buffered.
1167 if (0 == zstr.avail_in)
1169 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1170 return JB_ERR_COMPRESS;
1174 * If we tried the limit and still didn't have enough
1175 * memory, just give up.
1177 if (bufsize == csp->config->buffer_limit)
1179 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1180 return JB_ERR_MEMORY;
1183 /* Try doubling the buffer size each time. */
1186 /* Don't exceed the buffer limit. */
1187 if (bufsize > csp->config->buffer_limit)
1189 bufsize = csp->config->buffer_limit;
1192 /* Try to allocate the new buffer. */
1193 tmpbuf = realloc(buf, bufsize);
1196 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1198 return JB_ERR_MEMORY;
1202 char *oldnext_out = (char *)zstr.next_out;
1205 * Update the fields for inflate() to use the new
1206 * buffer, which may be in a location different from
1209 zstr.avail_out += bufsize - oldbufsize;
1210 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1213 * Compare with an uglier method of calculating these values
1214 * that doesn't require the extra oldbufsize variable.
1216 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1217 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1218 assert(zstr.avail_out > 0);
1224 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1226 log_error(LOG_LEVEL_ERROR,
1227 "Inconsistent stream state after decompression: %s", zstr.msg);
1229 * XXX: Intentionally no return.
1231 * According to zlib.h, Z_STREAM_ERROR is returned
1232 * "if the stream state was inconsistent".
1234 * I assume in this case inflate()'s status
1235 * would also be something different than Z_STREAM_END
1236 * so this check should be redundant, but lets see.
1240 if (status != Z_STREAM_END)
1242 /* We failed to decompress the stream. */
1243 log_error(LOG_LEVEL_ERROR,
1244 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1245 return JB_ERR_COMPRESS;
1249 * Finally, we can actually update the iob, since the
1250 * decompression was successful. First, free the old
1253 freez(csp->iob->buf);
1255 /* Now, update the iob to use the new buffer. */
1256 csp->iob->buf = buf;
1257 csp->iob->cur = csp->iob->buf + skip_size;
1258 csp->iob->eod = (char *)zstr.next_out;
1259 csp->iob->size = bufsize;
1262 * Make sure the new uncompressed iob obeys some minimal
1263 * consistency conditions.
1265 if ((csp->iob->buf < csp->iob->cur)
1266 && (csp->iob->cur <= csp->iob->eod)
1267 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1269 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1272 log_error(LOG_LEVEL_RE_FILTER,
1273 "Decompression successful. Old size: %d, new size: %d.",
1274 old_size, new_size);
1278 /* zlib thinks this is OK, so lets do the same. */
1279 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1284 /* It seems that zlib did something weird. */
1285 log_error(LOG_LEVEL_ERROR,
1286 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1287 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1288 csp->iob->eod, csp->iob->buf + csp->iob->size);
1289 return JB_ERR_COMPRESS;
1295 #endif /* defined(FEATURE_ZLIB) */
1298 /*********************************************************************
1300 * Function : get_header
1302 * Description : This (odd) routine will parse the csp->iob
1305 * 1 : csp = Current client state (buffers, headers, etc...)
1307 * Returns : Any one of the following:
1309 * 1) a pointer to a dynamically allocated string that contains a header line
1310 * 2) NULL indicating that the end of the header was reached
1311 * 3) "" indicating that the end of the iob was reached before finding
1312 * a complete header line.
1314 *********************************************************************/
1315 char *get_header(struct client_state *csp)
1321 if ((iob->cur == NULL)
1322 || ((p = strchr(iob->cur, '\n')) == NULL))
1324 return(""); /* couldn't find a complete header */
1329 ret = strdup(iob->cur);
1332 /* FIXME No way to handle error properly */
1333 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1338 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1340 /* is this a blank line (i.e. the end of the header) ? */
1352 /*********************************************************************
1354 * Function : get_header_value
1356 * Description : Get the value of a given header from a chained list
1357 * of header lines or return NULL if no such header is
1358 * present in the list.
1361 * 1 : header_list = pointer to list
1362 * 2 : header_name = string with name of header to look for.
1363 * Trailing colon required, capitalization
1366 * Returns : NULL if not found, else value of header
1368 *********************************************************************/
1369 char *get_header_value(const struct list *header_list, const char *header_name)
1371 struct list_entry *cur_entry;
1375 assert(header_list);
1376 assert(header_name);
1377 length = strlen(header_name);
1379 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1383 if (!strncmpic(cur_entry->str, header_name, length))
1386 * Found: return pointer to start of value
1388 ret = (char *) (cur_entry->str + length);
1389 while (*ret && ijb_isspace(*ret)) ret++;
1403 /*********************************************************************
1405 * Function : scan_headers
1407 * Description : Scans headers, applies tags and updates action bits.
1410 * 1 : csp = Current client state (buffers, headers, etc...)
1412 * Returns : JB_ERR_OK
1414 *********************************************************************/
1415 jb_err scan_headers(struct client_state *csp)
1417 struct list_entry *h; /* Header */
1418 jb_err err = JB_ERR_OK;
1420 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1422 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1424 /* Header crunch()ed in previous run? -> ignore */
1425 if (h->str == NULL) continue;
1426 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1427 err = header_tagger(csp, h->str);
1434 /*********************************************************************
1438 * Description : add, delete or modify lines in the HTTP header streams.
1439 * On entry, it receives a linked list of headers space
1440 * that was allocated dynamically (both the list nodes
1441 * and the header contents).
1443 * As a side effect it frees the space used by the original
1447 * 1 : pats = list of patterns to match against headers
1448 * 2 : more_headers = list of functions to add more
1449 * headers (client or server)
1450 * 3 : csp = Current client state (buffers, headers, etc...)
1452 * Returns : JB_ERR_OK in case off success, or
1453 * JB_ERR_MEMORY on out-of-memory error.
1455 *********************************************************************/
1456 jb_err sed(const struct parsers pats[],
1457 const add_header_func_ptr more_headers[],
1458 struct client_state *csp)
1460 struct list_entry *p;
1461 const struct parsers *v;
1462 const add_header_func_ptr *f;
1463 jb_err err = JB_ERR_OK;
1467 * If filtering is enabled, sed is run twice,
1468 * but most of the work needs to be done only once.
1470 first_run = (more_headers != NULL ) ? 1 : 0;
1472 if (first_run) /* Parse and print */
1476 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1478 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1480 /* Header crunch()ed in previous run? -> ignore */
1481 if (p->str == NULL) continue;
1483 /* Does the current parser handle this header? */
1484 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1486 err = v->parser(csp, (char **)&(p->str));
1490 /* place any additional headers on the csp->headers list */
1491 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1496 else /* Parse only */
1499 * The second run is only needed if the body was modified
1500 * and the content-lenght has changed.
1502 if (strncmpic(csp->http->cmd, "HEAD", 4))
1504 /*XXX: Code duplication */
1505 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1507 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1509 /* Header crunch()ed in previous run? -> ignore */
1510 if (p->str == NULL) continue;
1512 /* Does the current parser handle this header? */
1513 if (strncmpic(p->str, v->str, v->len) == 0)
1515 err = v->parser(csp, (char **)&(p->str));
1527 /*********************************************************************
1529 * Function : header_tagger
1531 * Description : Executes all text substitutions from applying
1532 * tag actions and saves the result as tag.
1534 * XXX: Shares enough code with filter_header() and
1535 * pcrs_filter_response() to warrant some helper functions.
1538 * 1 : csp = Current client state (buffers, headers, etc...)
1539 * 2 : header = Header that is used as tagger input
1541 * Returns : JB_ERR_OK on success and always succeeds
1543 *********************************************************************/
1544 jb_err header_tagger(struct client_state *csp, char *header)
1546 int wanted_filter_type;
1547 int multi_action_index;
1551 struct file_list *fl;
1552 struct re_filterfile_spec *b;
1553 struct list_entry *tag_name;
1555 int found_filters = 0;
1556 const size_t header_length = strlen(header);
1558 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1560 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1561 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1565 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1566 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1569 /* Check if there are any filters */
1570 for (i = 0; i < MAX_AF_FILES; i++)
1583 if (0 == found_filters)
1585 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1589 for (i = 0; i < MAX_AF_FILES; i++)
1592 if ((NULL == fl) || (NULL == fl->f))
1595 * Either there are no filter files
1596 * left, or this filter file just
1597 * contains no valid filters.
1599 * Continue to be sure we don't miss
1600 * valid filter files that are chained
1601 * after empty or invalid ones.
1606 /* For all filters, */
1607 for (b = fl->f; b; b = b->next)
1609 if (b->type != wanted_filter_type)
1611 /* skip the ones we don't care about, */
1614 /* leaving only taggers that could apply, of which we use the ones, */
1615 for (tag_name = csp->action->multi[multi_action_index]->first;
1616 NULL != tag_name; tag_name = tag_name->next)
1618 /* that do apply, and */
1619 if (strcmp(b->name, tag_name->str) == 0)
1621 char *modified_tag = NULL;
1623 size_t size = header_length;
1624 pcrs_job *joblist = b->joblist;
1626 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1628 if (NULL == joblist)
1630 log_error(LOG_LEVEL_RE_FILTER,
1631 "Tagger %s has empty joblist. Nothing to do.", b->name);
1635 /* execute their pcrs_joblist on the header. */
1636 for (job = joblist; NULL != job; job = job->next)
1638 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1642 /* Success, continue with the modified version. */
1651 /* Tagger doesn't match */
1654 /* Regex failure, log it but continue anyway. */
1655 log_error(LOG_LEVEL_ERROR,
1656 "Problems with tagger \'%s\' and header \'%s\': %s",
1657 b->name, *header, pcrs_strerror(hits));
1659 freez(modified_tag);
1663 if (b->dynamic) pcrs_free_joblist(joblist);
1665 /* If this tagger matched */
1671 * There is to technical limitation which makes
1672 * it impossible to use empty tags, but I assume
1673 * no one would do it intentionally.
1676 log_error(LOG_LEVEL_INFO,
1677 "Tagger \'%s\' created an empty tag. Ignored.",
1682 if (!list_contains_item(csp->tags, tag))
1684 if (JB_ERR_OK != enlist(csp->tags, tag))
1686 log_error(LOG_LEVEL_ERROR,
1687 "Insufficient memory to add tag \'%s\', "
1688 "based on tagger \'%s\' and header \'%s\'",
1689 tag, b->name, *header);
1693 char *action_message;
1695 * update the action bits right away, to make
1696 * tagging based on tags set by earlier taggers
1697 * of the same kind possible.
1699 if (update_action_bits_for_tag(csp, tag))
1701 action_message = "Action bits updated accordingly.";
1705 action_message = "No action bits update necessary.";
1708 log_error(LOG_LEVEL_HEADER,
1709 "Tagger \'%s\' added tag \'%s\'. %s",
1710 b->name, tag, action_message);
1715 /* XXX: Is this log-worthy? */
1716 log_error(LOG_LEVEL_HEADER,
1717 "Tagger \'%s\' didn't add tag \'%s\'. "
1718 "Tag already present", b->name, tag);
1721 } /* if the tagger matched */
1722 } /* if the tagger applies */
1723 } /* for every tagger that could apply */
1724 } /* for all filters */
1725 } /* for all filter files */
1730 /* here begins the family of parser functions that reformat header lines */
1732 /*********************************************************************
1734 * Function : filter_header
1736 * Description : Executes all text substitutions from all applying
1737 * +(server|client)-header-filter actions on the header.
1738 * Most of the code was copied from pcrs_filter_response,
1739 * including the rather short variable names
1742 * 1 : csp = Current client state (buffers, headers, etc...)
1743 * 2 : header = On input, pointer to header to modify.
1744 * On output, pointer to the modified header, or NULL
1745 * to remove the header. This function frees the
1746 * original string if necessary.
1748 * Returns : JB_ERR_OK on success and always succeeds
1750 *********************************************************************/
1751 jb_err filter_header(struct client_state *csp, char **header)
1755 size_t size = strlen(*header);
1757 char *newheader = NULL;
1760 struct file_list *fl;
1761 struct re_filterfile_spec *b;
1762 struct list_entry *filtername;
1764 int i, found_filters = 0;
1765 int wanted_filter_type;
1766 int multi_action_index;
1768 if (csp->flags & CSP_FLAG_NO_FILTERING)
1773 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1775 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1776 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1780 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1781 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1785 * Need to check the set of re_filterfiles...
1787 for (i = 0; i < MAX_AF_FILES; i++)
1800 if (0 == found_filters)
1802 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1806 for (i = 0; i < MAX_AF_FILES; i++)
1809 if ((NULL == fl) || (NULL == fl->f))
1812 * Either there are no filter files
1813 * left, or this filter file just
1814 * contains no valid filters.
1816 * Continue to be sure we don't miss
1817 * valid filter files that are chained
1818 * after empty or invalid ones.
1823 * For all applying +filter actions, look if a filter by that
1824 * name exists and if yes, execute its pcrs_joblist on the
1827 for (b = fl->f; b; b = b->next)
1829 if (b->type != wanted_filter_type)
1831 /* Skip other filter types */
1835 for (filtername = csp->action->multi[multi_action_index]->first;
1836 filtername ; filtername = filtername->next)
1838 if (strcmp(b->name, filtername->str) == 0)
1840 int current_hits = 0;
1841 pcrs_job *joblist = b->joblist;
1843 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1845 if (NULL == joblist)
1847 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1851 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1852 *header, size, b->name);
1854 /* Apply all jobs from the joblist */
1855 for (job = joblist; NULL != job; job = job->next)
1857 matches = pcrs_execute(job, *header, size, &newheader, &size);
1860 current_hits += matches;
1861 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1863 *header = newheader;
1865 else if ( 0 == matches )
1867 /* Filter doesn't change header */
1873 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1874 *header, b->name, pcrs_strerror(matches));
1875 if( newheader != NULL)
1877 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1883 if (b->dynamic) pcrs_free_joblist(joblist);
1885 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1886 hits += current_hits;
1893 * Additionally checking for hits is important because if
1894 * the continue hack is triggered, server headers can
1895 * arrive empty to separate multiple heads from each other.
1897 if ((0 == size) && hits)
1899 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1907 /*********************************************************************
1909 * Function : connection
1911 * Description : Makes sure that the value of the Connection: header
1912 * is "close" and signals connection_close_adder
1916 * 1 : csp = Current client state (buffers, headers, etc...)
1917 * 2 : header = On input, pointer to header to modify.
1918 * On output, pointer to the modified header, or NULL
1919 * to remove the header. This function frees the
1920 * original string if necessary.
1922 * Returns : JB_ERR_OK on success, or
1923 * JB_ERR_MEMORY on out-of-memory error.
1925 *********************************************************************/
1926 jb_err connection(struct client_state *csp, char **header)
1928 char *old_header = *header;
1930 /* Do we have a 'Connection: close' header? */
1931 if (strcmpic(*header, "Connection: close"))
1933 /* No, create one */
1934 *header = strdup("Connection: close");
1937 return JB_ERR_MEMORY;
1939 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1943 /* Signal connection_close_adder() to return early. */
1944 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1946 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
1950 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
1957 /*********************************************************************
1959 * Function : crumble
1961 * Description : This is called if a header matches a pattern to "crunch"
1964 * 1 : csp = Current client state (buffers, headers, etc...)
1965 * 2 : header = On input, pointer to header to modify.
1966 * On output, pointer to the modified header, or NULL
1967 * to remove the header. This function frees the
1968 * original string if necessary.
1970 * Returns : JB_ERR_OK on success, or
1971 * JB_ERR_MEMORY on out-of-memory error.
1973 *********************************************************************/
1974 jb_err crumble(struct client_state *csp, char **header)
1976 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1981 /*********************************************************************
1983 * Function : crunch_server_header
1985 * Description : Crunch server header if it matches a string supplied by the
1986 * user. Called from `sed'.
1989 * 1 : csp = Current client state (buffers, headers, etc...)
1990 * 2 : header = On input, pointer to header to modify.
1991 * On output, pointer to the modified header, or NULL
1992 * to remove the header. This function frees the
1993 * original string if necessary.
1995 * Returns : JB_ERR_OK on success and always succeeds
1997 *********************************************************************/
1998 jb_err crunch_server_header(struct client_state *csp, char **header)
2000 const char *crunch_pattern;
2002 /* Do we feel like crunching? */
2003 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2005 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2007 /* Is the current header the lucky one? */
2008 if (strstr(*header, crunch_pattern))
2010 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2019 /*********************************************************************
2021 * Function : server_content_type
2023 * Description : Set the content-type for filterable types (text/.*,
2024 * .*xml.*, javascript and image/gif) unless filtering has been
2025 * forbidden (CT_TABOO) while parsing earlier headers.
2026 * NOTE: Since text/plain is commonly used by web servers
2027 * for files whose correct type is unknown, we don't
2028 * set CT_TEXT for it.
2031 * 1 : csp = Current client state (buffers, headers, etc...)
2032 * 2 : header = On input, pointer to header to modify.
2033 * On output, pointer to the modified header, or NULL
2034 * to remove the header. This function frees the
2035 * original string if necessary.
2037 * Returns : JB_ERR_OK on success, or
2038 * JB_ERR_MEMORY on out-of-memory error.
2040 *********************************************************************/
2041 jb_err server_content_type(struct client_state *csp, char **header)
2043 /* Remove header if it isn't the first Content-Type header */
2044 if(csp->content_type && (csp->content_type != CT_TABOO))
2047 * Another, slightly slower, way to see if
2048 * we already parsed another Content-Type header.
2050 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2052 log_error(LOG_LEVEL_ERROR,
2053 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2060 if (!(csp->content_type & CT_TABOO))
2062 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2063 || strstr(*header, "xml")
2064 || strstr(*header, "application/x-javascript"))
2066 csp->content_type |= CT_TEXT;
2068 else if (strstr(*header, " image/gif"))
2070 csp->content_type |= CT_GIF;
2072 else if (strstr(*header, " image/jpeg"))
2074 csp->content_type |= CT_JPEG;
2078 csp->content_type = 0;
2082 * Are we enabling text mode by force?
2084 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2087 * Do we really have to?
2089 if (csp->content_type & CT_TEXT)
2091 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2095 csp->content_type |= CT_TEXT;
2096 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2100 * Are we messing with the content type?
2102 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2105 * Make sure the user doesn't accidently
2106 * change the content type of binary documents.
2108 if (csp->content_type & CT_TEXT)
2111 *header = strdup("Content-Type: ");
2112 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2116 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2117 return JB_ERR_MEMORY;
2119 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2123 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2124 "Enable force-text-mode if you know what you're doing.", *header);
2131 /*********************************************************************
2133 * Function : server_transfer_coding
2135 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2136 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2137 * - Remove header if body was chunked but has been
2138 * de-chunked for filtering.
2141 * 1 : csp = Current client state (buffers, headers, etc...)
2142 * 2 : header = On input, pointer to header to modify.
2143 * On output, pointer to the modified header, or NULL
2144 * to remove the header. This function frees the
2145 * original string if necessary.
2147 * Returns : JB_ERR_OK on success, or
2148 * JB_ERR_MEMORY on out-of-memory error.
2150 *********************************************************************/
2151 jb_err server_transfer_coding(struct client_state *csp, char **header)
2154 * Turn off pcrs and gif filtering if body compressed
2156 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2160 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2162 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2163 csp->http->cmd, *header);
2164 #endif /* def FEATURE_ZLIB */
2165 csp->content_type = CT_TABOO;
2169 * Raise flag if body chunked
2171 if (strstr(*header, "chunked"))
2173 csp->flags |= CSP_FLAG_CHUNKED;
2176 * If the body was modified, it has been de-chunked first
2177 * and the header must be removed.
2179 * FIXME: If there is more than one transfer encoding,
2180 * only the "chunked" part should be removed here.
2182 if (csp->flags & CSP_FLAG_MODIFIED)
2184 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2193 /*********************************************************************
2195 * Function : server_content_encoding
2197 * Description : This function is run twice for each request,
2198 * unless FEATURE_ZLIB and filtering are disabled.
2200 * The first run is used to check if the content
2201 * is compressed, if FEATURE_ZLIB is disabled
2202 * filtering is then disabled as well, if FEATURE_ZLIB
2203 * is enabled the content is marked for decompression.
2205 * The second run is used to remove the Content-Encoding
2206 * header if the decompression was successful.
2209 * 1 : csp = Current client state (buffers, headers, etc...)
2210 * 2 : header = On input, pointer to header to modify.
2211 * On output, pointer to the modified header, or NULL
2212 * to remove the header. This function frees the
2213 * original string if necessary.
2215 * Returns : JB_ERR_OK on success, or
2216 * JB_ERR_MEMORY on out-of-memory error.
2218 *********************************************************************/
2219 jb_err server_content_encoding(struct client_state *csp, char **header)
2222 if ((csp->flags & CSP_FLAG_MODIFIED)
2223 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2226 * We successfully decompressed the content,
2227 * and have to clean the header now, so the
2228 * client no longer expects compressed data..
2230 * XXX: There is a difference between cleaning
2231 * and removing it completely.
2233 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2236 else if (strstr(*header, "gzip"))
2238 /* Mark for gzip decompression */
2239 csp->content_type |= CT_GZIP;
2241 else if (strstr(*header, "deflate"))
2243 /* Mark for zlib decompression */
2244 csp->content_type |= CT_DEFLATE;
2246 else if (strstr(*header, "compress"))
2249 * We can't decompress this; therefore we can't filter
2252 csp->content_type |= CT_TABOO;
2254 #else /* !defined(FEATURE_ZLIB) */
2255 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2258 * Body is compressed, turn off pcrs and gif filtering.
2260 csp->content_type |= CT_TABOO;
2263 * Log a warning if the user expects the content to be filtered.
2265 if ((csp->rlist != NULL) &&
2266 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2268 log_error(LOG_LEVEL_INFO,
2269 "Compressed content detected, content filtering disabled. "
2270 "Consider recompiling Privoxy with zlib support or "
2271 "enable the prevent-compression action.");
2274 #endif /* defined(FEATURE_ZLIB) */
2281 /*********************************************************************
2283 * Function : server_content_length
2285 * Description : Adjust Content-Length header if we modified
2289 * 1 : csp = Current client state (buffers, headers, etc...)
2290 * 2 : header = On input, pointer to header to modify.
2291 * On output, pointer to the modified header, or NULL
2292 * to remove the header. This function frees the
2293 * original string if necessary.
2295 * Returns : JB_ERR_OK on success, or
2296 * JB_ERR_MEMORY on out-of-memory error.
2298 *********************************************************************/
2299 jb_err server_content_length(struct client_state *csp, char **header)
2301 const size_t max_header_length = 80;
2303 /* Regenerate header if the content was modified. */
2304 if (csp->flags & CSP_FLAG_MODIFIED)
2307 *header = (char *) zalloc(max_header_length);
2308 if (*header == NULL)
2310 return JB_ERR_MEMORY;
2313 snprintf(*header, max_header_length, "Content-Length: %d",
2314 (int)csp->content_length);
2315 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2316 (int)csp->content_length);
2323 /*********************************************************************
2325 * Function : server_content_md5
2327 * Description : Crumble any Content-MD5 headers if the document was
2328 * modified. FIXME: Should we re-compute instead?
2331 * 1 : csp = Current client state (buffers, headers, etc...)
2332 * 2 : header = On input, pointer to header to modify.
2333 * On output, pointer to the modified header, or NULL
2334 * to remove the header. This function frees the
2335 * original string if necessary.
2337 * Returns : JB_ERR_OK on success, or
2338 * JB_ERR_MEMORY on out-of-memory error.
2340 *********************************************************************/
2341 jb_err server_content_md5(struct client_state *csp, char **header)
2343 if (csp->flags & CSP_FLAG_MODIFIED)
2345 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2352 /*********************************************************************
2354 * Function : server_content_disposition
2356 * Description : If enabled, blocks or modifies the "content-disposition" header.
2357 * Called from `sed'.
2360 * 1 : csp = Current client state (buffers, headers, etc...)
2361 * 2 : header = On input, pointer to header to modify.
2362 * On output, pointer to the modified header, or NULL
2363 * to remove the header. This function frees the
2364 * original string if necessary.
2366 * Returns : JB_ERR_OK on success, or
2367 * JB_ERR_MEMORY on out-of-memory error.
2369 *********************************************************************/
2370 jb_err server_content_disposition(struct client_state *csp, char **header)
2375 * Are we messing with the content-disposition header?
2377 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2383 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2385 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2388 * Blocking content-disposition header
2390 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2397 * Replacing content-disposition header
2400 *header = strdup("content-disposition: ");
2401 string_append(header, newval);
2403 if (*header == NULL)
2405 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2409 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2412 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2415 /*********************************************************************
2417 * Function : server_last_modified
2419 * Description : Changes Last-Modified header to the actual date
2420 * to help hide-if-modified-since.
2421 * Called from `sed'.
2424 * 1 : csp = Current client state (buffers, headers, etc...)
2425 * 2 : header = On input, pointer to header to modify.
2426 * On output, pointer to the modified header, or NULL
2427 * to remove the header. This function frees the
2428 * original string if necessary.
2430 * Returns : JB_ERR_OK on success, or
2431 * JB_ERR_MEMORY on out-of-memory error.
2433 *********************************************************************/
2434 jb_err server_last_modified(struct client_state *csp, char **header)
2437 char buf[BUFFER_SIZE];
2440 #ifdef HAVE_GMTIME_R
2443 struct tm *timeptr = NULL;
2444 time_t now, last_modified;
2446 long int days, hours, minutes, seconds;
2449 * Are we messing with the Last-Modified header?
2451 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2457 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2459 if (0 == strcmpic(newval, "block") )
2462 * Blocking Last-Modified header. Useless but why not.
2464 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2468 else if (0 == strcmpic(newval, "reset-to-request-time"))
2471 * Setting Last-Modified Header to now.
2473 get_http_time(0, buf);
2475 *header = strdup("Last-Modified: ");
2476 string_append(header, buf);
2478 if (*header == NULL)
2480 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2484 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2487 else if (0 == strcmpic(newval, "randomize"))
2489 const char *header_time = *header + sizeof("Last-Modified:");
2491 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2493 #ifdef HAVE_GMTIME_R
2494 timeptr = gmtime_r(&now, &gmt);
2495 #elif FEATURE_PTHREAD
2496 pthread_mutex_lock(&gmtime_mutex);
2497 timeptr = gmtime(&now);
2498 pthread_mutex_unlock(&gmtime_mutex);
2500 timeptr = gmtime(&now);
2502 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2504 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2509 rtime = (long int)difftime(now, last_modified);
2512 rtime = pick_from_range(rtime);
2513 last_modified += rtime;
2514 #ifdef HAVE_GMTIME_R
2515 timeptr = gmtime_r(&last_modified, &gmt);
2516 #elif FEATURE_PTHREAD
2517 pthread_mutex_lock(&gmtime_mutex);
2518 timeptr = gmtime(&last_modified);
2519 pthread_mutex_unlock(&gmtime_mutex);
2521 timeptr = gmtime(&last_modified);
2523 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2525 *header = strdup("Last-Modified: ");
2526 string_append(header, newheader);
2528 if (*header == NULL)
2530 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2531 return JB_ERR_MEMORY;
2534 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2536 days = rtime / (3600 * 24);
2537 hours = rtime / 3600 % 24;
2538 minutes = rtime / 60 % 60;
2539 seconds = rtime % 60;
2541 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2542 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2543 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2548 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2557 /*********************************************************************
2559 * Function : client_accept_encoding
2561 * Description : Rewrite the client's Accept-Encoding header so that
2562 * if doesn't allow compression, if the action applies.
2563 * Note: For HTTP/1.0 the absence of the header is enough.
2566 * 1 : csp = Current client state (buffers, headers, etc...)
2567 * 2 : header = On input, pointer to header to modify.
2568 * On output, pointer to the modified header, or NULL
2569 * to remove the header. This function frees the
2570 * original string if necessary.
2572 * Returns : JB_ERR_OK on success, or
2573 * JB_ERR_MEMORY on out-of-memory error.
2575 *********************************************************************/
2576 jb_err client_accept_encoding(struct client_state *csp, char **header)
2578 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2580 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2584 /* Temporarily disable the correct behaviour to
2585 * work around a PHP bug.
2587 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2589 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2590 * if (*header == NULL)
2592 * return JB_ERR_MEMORY;
2603 /*********************************************************************
2605 * Function : client_te
2607 * Description : Rewrite the client's TE header so that
2608 * if doesn't allow compression, if the action applies.
2611 * 1 : csp = Current client state (buffers, headers, etc...)
2612 * 2 : header = On input, pointer to header to modify.
2613 * On output, pointer to the modified header, or NULL
2614 * to remove the header. This function frees the
2615 * original string if necessary.
2617 * Returns : JB_ERR_OK on success, or
2618 * JB_ERR_MEMORY on out-of-memory error.
2620 *********************************************************************/
2621 jb_err client_te(struct client_state *csp, char **header)
2623 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2626 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2632 /*********************************************************************
2634 * Function : client_referrer
2636 * Description : Handle the "referer" config setting properly.
2637 * Called from `sed'.
2640 * 1 : csp = Current client state (buffers, headers, etc...)
2641 * 2 : header = On input, pointer to header to modify.
2642 * On output, pointer to the modified header, or NULL
2643 * to remove the header. This function frees the
2644 * original string if necessary.
2646 * Returns : JB_ERR_OK on success, or
2647 * JB_ERR_MEMORY on out-of-memory error.
2649 *********************************************************************/
2650 jb_err client_referrer(struct client_state *csp, char **header)
2657 #ifdef FEATURE_FORCE_LOAD
2658 /* Since the referrer can include the prefix even
2659 * if the request itself is non-forced, we must
2660 * clean it unconditionally
2662 strclean(*header, FORCE_PREFIX);
2663 #endif /* def FEATURE_FORCE_LOAD */
2666 * Are we sending referer?
2668 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2673 newval = csp->action->string[ACTION_STRING_REFERER];
2675 if ((0 != strcmpic(newval, "conditional-block")))
2679 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2684 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2687 else if (0 == strcmpic(newval, "conditional-block"))
2690 * Block referer if host has changed.
2693 if (NULL == (host = strdup(csp->http->hostport)))
2696 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2697 return JB_ERR_MEMORY;
2699 if (NULL == (referer = strdup(*header)))
2703 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2704 return JB_ERR_MEMORY;
2706 hostlenght = strlen(host);
2707 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2709 /*Shorten referer to make sure the referer is blocked
2710 *if www.example.org/www.example.com-shall-see-the-referer/
2711 *links to www.example.com/
2713 referer[hostlenght+17] = '\0';
2715 if ( 0 == strstr(referer, host)) /*Host has changed*/
2717 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2722 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2728 else if (0 != strcmpic(newval, "forge"))
2731 * We have a specific (fixed) referer we want to send.
2733 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2735 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2737 *header = strdup("Referer: ");
2738 string_append(header, newval);
2739 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2741 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2746 * Forge a referer as http://[hostname:port of REQUEST]/
2747 * to fool stupid checks for in-site links
2750 *header = strdup("Referer: http://");
2751 string_append(header, csp->http->hostport);
2752 string_append(header, "/");
2753 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2755 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2759 /*********************************************************************
2761 * Function : client_accept_language
2763 * Description : Handle the "Accept-Language" config setting properly.
2764 * Called from `sed'.
2767 * 1 : csp = Current client state (buffers, headers, etc...)
2768 * 2 : header = On input, pointer to header to modify.
2769 * On output, pointer to the modified header, or NULL
2770 * to remove the header. This function frees the
2771 * original string if necessary.
2773 * Returns : JB_ERR_OK on success, or
2774 * JB_ERR_MEMORY on out-of-memory error.
2776 *********************************************************************/
2777 jb_err client_accept_language(struct client_state *csp, char **header)
2782 * Are we messing with the Accept-Language?
2784 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2786 /*I don't think so*/
2790 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2792 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2795 * Blocking Accept-Language header
2797 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2804 * Replacing Accept-Language header
2807 *header = strdup("Accept-Language: ");
2808 string_append(header, newval);
2810 if (*header == NULL)
2812 log_error(LOG_LEVEL_ERROR,
2813 "Insufficent memory. Accept-Language header crunched without replacement.");
2817 log_error(LOG_LEVEL_HEADER,
2818 "Accept-Language header crunched and replaced with: %s", *header);
2821 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2824 /*********************************************************************
2826 * Function : crunch_client_header
2828 * Description : Crunch client header if it matches a string supplied by the
2829 * user. Called from `sed'.
2832 * 1 : csp = Current client state (buffers, headers, etc...)
2833 * 2 : header = On input, pointer to header to modify.
2834 * On output, pointer to the modified header, or NULL
2835 * to remove the header. This function frees the
2836 * original string if necessary.
2838 * Returns : JB_ERR_OK on success and always succeeds
2840 *********************************************************************/
2841 jb_err crunch_client_header(struct client_state *csp, char **header)
2843 const char *crunch_pattern;
2845 /* Do we feel like crunching? */
2846 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2848 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2850 /* Is the current header the lucky one? */
2851 if (strstr(*header, crunch_pattern))
2853 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2861 /*********************************************************************
2863 * Function : client_uagent
2865 * Description : Handle the "user-agent" config setting properly
2866 * and remember its original value to enable browser
2867 * bug workarounds. Called from `sed'.
2870 * 1 : csp = Current client state (buffers, headers, etc...)
2871 * 2 : header = On input, pointer to header to modify.
2872 * On output, pointer to the modified header, or NULL
2873 * to remove the header. This function frees the
2874 * original string if necessary.
2876 * Returns : JB_ERR_OK on success, or
2877 * JB_ERR_MEMORY on out-of-memory error.
2879 *********************************************************************/
2880 jb_err client_uagent(struct client_state *csp, char **header)
2884 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2889 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2896 *header = strdup("User-Agent: ");
2897 string_append(header, newval);
2899 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2901 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2904 /*********************************************************************
2906 * Function : client_ua
2908 * Description : Handle "ua-" headers properly. Called from `sed'.
2911 * 1 : csp = Current client state (buffers, headers, etc...)
2912 * 2 : header = On input, pointer to header to modify.
2913 * On output, pointer to the modified header, or NULL
2914 * to remove the header. This function frees the
2915 * original string if necessary.
2917 * Returns : JB_ERR_OK on success, or
2918 * JB_ERR_MEMORY on out-of-memory error.
2920 *********************************************************************/
2921 jb_err client_ua(struct client_state *csp, char **header)
2923 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2925 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2933 /*********************************************************************
2935 * Function : client_from
2937 * Description : Handle the "from" config setting properly.
2938 * Called from `sed'.
2941 * 1 : csp = Current client state (buffers, headers, etc...)
2942 * 2 : header = On input, pointer to header to modify.
2943 * On output, pointer to the modified header, or NULL
2944 * to remove the header. This function frees the
2945 * original string if necessary.
2947 * Returns : JB_ERR_OK on success, or
2948 * JB_ERR_MEMORY on out-of-memory error.
2950 *********************************************************************/
2951 jb_err client_from(struct client_state *csp, char **header)
2955 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2962 newval = csp->action->string[ACTION_STRING_FROM];
2965 * Are we blocking the e-mail address?
2967 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2969 log_error(LOG_LEVEL_HEADER, "crunched From!");
2973 log_error(LOG_LEVEL_HEADER, " modified");
2975 *header = strdup("From: ");
2976 string_append(header, newval);
2978 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2982 /*********************************************************************
2984 * Function : client_send_cookie
2986 * Description : Crunches the "cookie" header if necessary.
2987 * Called from `sed'.
2989 * XXX: Stupid name, doesn't send squat.
2992 * 1 : csp = Current client state (buffers, headers, etc...)
2993 * 2 : header = On input, pointer to header to modify.
2994 * On output, pointer to the modified header, or NULL
2995 * to remove the header. This function frees the
2996 * original string if necessary.
2998 * Returns : JB_ERR_OK on success, or
2999 * JB_ERR_MEMORY on out-of-memory error.
3001 *********************************************************************/
3002 jb_err client_send_cookie(struct client_state *csp, char **header)
3004 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3006 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3014 /*********************************************************************
3016 * Function : client_x_forwarded
3018 * Description : Handle the "x-forwarded-for" config setting properly,
3019 * also used in the add_client_headers list. Called from `sed'.
3022 * 1 : csp = Current client state (buffers, headers, etc...)
3023 * 2 : header = On input, pointer to header to modify.
3024 * On output, pointer to the modified header, or NULL
3025 * to remove the header. This function frees the
3026 * original string if necessary.
3028 * Returns : JB_ERR_OK on success, or
3029 * JB_ERR_MEMORY on out-of-memory error.
3031 *********************************************************************/
3032 jb_err client_x_forwarded(struct client_state *csp, char **header)
3034 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3036 /* Save it so we can re-add it later */
3037 freez(csp->x_forwarded);
3038 csp->x_forwarded = *header;
3041 * Always set *header = NULL, since this information
3042 * will be sent at the end of the header.
3049 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3056 /*********************************************************************
3058 * Function : client_max_forwards
3060 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3061 * from the value of the Max-Forwards header field.
3064 * 1 : csp = Current client state (buffers, headers, etc...)
3065 * 2 : header = On input, pointer to header to modify.
3066 * On output, pointer to the modified header, or NULL
3067 * to remove the header. This function frees the
3068 * original string if necessary.
3070 * Returns : JB_ERR_OK on success, or
3071 * JB_ERR_MEMORY on out-of-memory error.
3073 *********************************************************************/
3074 jb_err client_max_forwards(struct client_state *csp, char **header)
3078 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3079 (0 == strcmpic(csp->http->gpc, "options")))
3081 assert(*(*header+12) == ':');
3082 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3084 if (max_forwards > 0)
3086 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3087 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3088 csp->http->gpc, max_forwards);
3090 else if (max_forwards < 0)
3092 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3098 * Not supposed to be reached. direct_response() which
3099 * was already called earlier in chat() should have
3100 * intercepted the request.
3102 log_error(LOG_LEVEL_ERROR,
3103 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3104 assert(max_forwards != 0);
3109 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3118 /*********************************************************************
3120 * Function : client_host
3122 * Description : If the request URI did not contain host and
3123 * port information, parse and evaluate the Host
3126 * Also, kill ill-formed HOST: headers as sent by
3127 * Apple's iTunes software when used with a proxy.
3130 * 1 : csp = Current client state (buffers, headers, etc...)
3131 * 2 : header = On input, pointer to header to modify.
3132 * On output, pointer to the modified header, or NULL
3133 * to remove the header. This function frees the
3134 * original string if necessary.
3136 * Returns : JB_ERR_OK on success, or
3137 * JB_ERR_MEMORY on out-of-memory error.
3139 *********************************************************************/
3140 jb_err client_host(struct client_state *csp, char **header)
3145 * If the header field name is all upper-case, chances are that it's
3146 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3147 * not a problem -- they are regenerated later.
3149 if ((*header)[1] == 'O')
3151 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3156 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3157 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3160 if (NULL == (p = strdup((*header)+6)))
3162 return JB_ERR_MEMORY;
3165 if (NULL == (q = strdup(p)))
3168 return JB_ERR_MEMORY;
3171 freez(csp->http->hostport);
3172 csp->http->hostport = p;
3173 freez(csp->http->host);
3174 csp->http->host = q;
3175 q = strchr(csp->http->host, ':');
3178 /* Terminate hostname and evaluate port string */
3180 csp->http->port = atoi(q);
3184 csp->http->port = csp->http->ssl ? 443 : 80;
3187 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3188 csp->http->hostport, csp->http->host, csp->http->port);
3191 /* Signal client_host_adder() to return right away */
3192 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3197 /*********************************************************************
3199 * Function : client_if_modified_since
3201 * Description : Remove or modify the If-Modified-Since header.
3204 * 1 : csp = Current client state (buffers, headers, etc...)
3205 * 2 : header = On input, pointer to header to modify.
3206 * On output, pointer to the modified header, or NULL
3207 * to remove the header. This function frees the
3208 * original string if necessary.
3210 * Returns : JB_ERR_OK on success, or
3211 * JB_ERR_MEMORY on out-of-memory error.
3213 *********************************************************************/
3214 jb_err client_if_modified_since(struct client_state *csp, char **header)
3217 #ifdef HAVE_GMTIME_R
3220 struct tm *timeptr = NULL;
3224 long int hours, minutes, seconds;
3228 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3231 * The client got an error message because of a temporary problem,
3232 * the problem is gone and the client now tries to revalidate our
3233 * error message on the real server. The revalidation would always
3234 * end with the transmission of the whole document and there is
3235 * no need to expose the bogus If-Modified-Since header.
3237 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3240 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3242 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3244 if ((0 == strcmpic(newval, "block")))
3246 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3249 else /* add random value */
3251 const char *header_time = *header + sizeof("If-Modified-Since:");
3253 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3255 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3260 rtime = strtol(newval, &endptr, 0);
3263 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3264 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3271 rtime = pick_from_range(rtime);
3275 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3278 tm += rtime * (negative ? -1 : 1);
3279 #ifdef HAVE_GMTIME_R
3280 timeptr = gmtime_r(&tm, &gmt);
3281 #elif FEATURE_PTHREAD
3282 pthread_mutex_lock(&gmtime_mutex);
3283 timeptr = gmtime(&tm);
3284 pthread_mutex_unlock(&gmtime_mutex);
3286 timeptr = gmtime(&tm);
3288 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3291 *header = strdup("If-Modified-Since: ");
3292 string_append(header, newheader);
3294 if (*header == NULL)
3296 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3297 return JB_ERR_MEMORY;
3300 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3302 hours = rtime / 3600;
3303 minutes = rtime / 60 % 60;
3304 seconds = rtime % 60;
3306 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3307 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3308 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3317 /*********************************************************************
3319 * Function : client_if_none_match
3321 * Description : Remove the If-None-Match header.
3324 * 1 : csp = Current client state (buffers, headers, etc...)
3325 * 2 : header = On input, pointer to header to modify.
3326 * On output, pointer to the modified header, or NULL
3327 * to remove the header. This function frees the
3328 * original string if necessary.
3330 * Returns : JB_ERR_OK on success, or
3331 * JB_ERR_MEMORY on out-of-memory error.
3333 *********************************************************************/
3334 jb_err client_if_none_match(struct client_state *csp, char **header)
3336 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3338 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3345 /*********************************************************************
3347 * Function : client_x_filter
3349 * Description : Disables filtering if the client set "X-Filter: No".
3350 * Called from `sed'.
3353 * 1 : csp = Current client state (buffers, headers, etc...)
3354 * 2 : header = On input, pointer to header to modify.
3355 * On output, pointer to the modified header, or NULL
3356 * to remove the header. This function frees the
3357 * original string if necessary.
3359 * Returns : JB_ERR_OK on success
3361 *********************************************************************/
3362 jb_err client_x_filter(struct client_state *csp, char **header)
3364 if ( 0 == strcmpic(*header, "X-Filter: No"))
3366 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3368 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3372 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3374 log_error(LOG_LEVEL_HEADER,
3375 "force-text-mode overruled the client's request to fetch without filtering!");
3379 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3380 csp->flags |= CSP_FLAG_NO_FILTERING;
3381 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3383 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3390 /* the following functions add headers directly to the header list */
3392 /*********************************************************************
3394 * Function : client_host_adder
3396 * Description : Adds the Host: header field if it is missing.
3397 * Called from `sed'.
3400 * 1 : csp = Current client state (buffers, headers, etc...)
3402 * Returns : JB_ERR_OK on success, or
3403 * JB_ERR_MEMORY on out-of-memory error.
3405 *********************************************************************/
3406 jb_err client_host_adder(struct client_state *csp)
3411 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3413 /* Header already set by the client, nothing to do. */
3417 if ( !csp->http->hostport || !*(csp->http->hostport))
3419 /* XXX: When does this happen and why is it OK? */
3420 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3425 * remove 'user:pass@' from 'proto://user:pass@host'
3427 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3433 p = csp->http->hostport;
3436 /* XXX: Just add it, we already made sure that it will be unique */
3437 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3438 err = enlist_unique_header(csp->headers, "Host", p);
3444 /*********************************************************************
3446 * Function : client_cookie_adder
3448 * Description : Used in the add_client_headers list to add "wafers".
3449 * Called from `sed'.
3452 * 1 : csp = Current client state (buffers, headers, etc...)
3454 * Returns : JB_ERR_OK on success, or
3455 * JB_ERR_MEMORY on out-of-memory error.
3457 *********************************************************************/
3458 jb_err client_cookie_adder(struct client_state *csp)
3461 struct list_entry *wafer;
3462 struct list_entry *wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3465 if (NULL == wafer_list)
3471 tmp = strdup("Cookie: ");
3473 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3475 if (wafer != wafer_list)
3477 /* As this isn't the first wafer, we need a delimiter. */
3478 string_append(&tmp, "; ");
3480 string_join(&tmp, cookie_encode(wafer->str));
3485 return JB_ERR_MEMORY;
3488 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3489 err = enlist(csp->headers, tmp);
3495 /*********************************************************************
3497 * Function : client_accept_encoding_adder
3499 * Description : Add an Accept-Encoding header to the client's request
3500 * that disables compression if the action applies, and
3501 * the header is not already there. Called from `sed'.
3502 * Note: For HTTP/1.0, the absence of the header is enough.
3505 * 1 : csp = Current client state (buffers, headers, etc...)
3507 * Returns : JB_ERR_OK on success, or
3508 * JB_ERR_MEMORY on out-of-memory error.
3510 *********************************************************************/
3511 jb_err client_accept_encoding_adder(struct client_state *csp)
3513 assert(0); /* Not in use */
3515 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3516 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3518 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3525 /*********************************************************************
3527 * Function : client_xtra_adder
3529 * Description : Used in the add_client_headers list. Called from `sed'.
3532 * 1 : csp = Current client state (buffers, headers, etc...)
3534 * Returns : JB_ERR_OK on success, or
3535 * JB_ERR_MEMORY on out-of-memory error.
3537 *********************************************************************/
3538 jb_err client_xtra_adder(struct client_state *csp)
3540 struct list_entry *lst;
3543 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3544 lst ; lst = lst->next)
3546 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3547 err = enlist(csp->headers, lst->str);
3559 /*********************************************************************
3561 * Function : client_x_forwarded_adder
3563 * Description : Used in the add_client_headers list. Called from `sed'.
3566 * 1 : csp = Current client state (buffers, headers, etc...)
3568 * Returns : JB_ERR_OK on success, or
3569 * JB_ERR_MEMORY on out-of-memory error.
3571 *********************************************************************/
3572 jb_err client_x_forwarded_adder(struct client_state *csp)
3577 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3582 if (csp->x_forwarded)
3584 p = strdup(csp->x_forwarded);
3585 string_append(&p, ", ");
3589 p = strdup("X-Forwarded-For: ");
3591 string_append(&p, csp->ip_addr_str);
3595 return JB_ERR_MEMORY;
3598 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3599 err = enlist(csp->headers, p);
3606 /*********************************************************************
3608 * Function : connection_close_adder
3610 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3611 * support. Adds a "Connection: close" header to csp->headers
3612 * unless the header was already present. Called from `sed'.
3614 * FIXME: This whole function shouldn't be neccessary!
3617 * 1 : csp = Current client state (buffers, headers, etc...)
3619 * Returns : JB_ERR_OK on success, or
3620 * JB_ERR_MEMORY on out-of-memory error.
3622 *********************************************************************/
3623 jb_err connection_close_adder(struct client_state *csp)
3625 const unsigned int flags = csp->flags;
3628 * Return right away if
3630 * - we're parsing server headers and the server header
3631 * "Connection: close" is already set, or if
3633 * - we're parsing client headers and the client header
3634 * "Connection: close" is already set.
3636 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3637 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3638 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3639 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3644 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3646 return enlist(csp->headers, "Connection: close");
3650 /*********************************************************************
3652 * Function : server_http
3654 * Description : - Save the HTTP Status into csp->http->status
3655 * - Set CT_TABOO to prevent filtering if the answer
3656 * is a partial range (HTTP status 206)
3657 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3661 * 1 : csp = Current client state (buffers, headers, etc...)
3662 * 2 : header = On input, pointer to header to modify.
3663 * On output, pointer to the modified header, or NULL
3664 * to remove the header. This function frees the
3665 * original string if necessary.
3667 * Returns : JB_ERR_OK on success, or
3668 * JB_ERR_MEMORY on out-of-memory error.
3670 *********************************************************************/
3671 jb_err server_http(struct client_state *csp, char **header)
3673 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3674 if (csp->http->status == 206)
3676 csp->content_type = CT_TABOO;
3679 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3682 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3689 /*********************************************************************
3691 * Function : server_set_cookie
3693 * Description : Handle the server "cookie" header properly.
3694 * Log cookie to the jar file. Then "crunch",
3695 * accept or rewrite it to a session cookie.
3696 * Called from `sed'.
3698 * TODO: Allow the user to specify a new expiration
3699 * time to cause the cookie to expire even before the
3700 * browser is closed.
3703 * 1 : csp = Current client state (buffers, headers, etc...)
3704 * 2 : header = On input, pointer to header to modify.
3705 * On output, pointer to the modified header, or NULL
3706 * to remove the header. This function frees the
3707 * original string if necessary.
3709 * Returns : JB_ERR_OK on success, or
3710 * JB_ERR_MEMORY on out-of-memory error.
3712 *********************************************************************/
3713 jb_err server_set_cookie(struct client_state *csp, char **header)
3720 #ifdef FEATURE_COOKIE_JAR
3721 if (csp->config->jar)
3724 * Write timestamp into outbuf.
3726 * Complex because not all OSs have tm_gmtoff or
3727 * the %z field in strftime()
3729 char tempbuf[ BUFFER_SIZE ];
3731 #ifdef HAVE_LOCALTIME_R
3732 tm_now = *localtime_r(&now, &tm_now);
3733 #elif FEATURE_PTHREAD
3734 pthread_mutex_lock(&localtime_mutex);
3735 tm_now = *localtime (&now);
3736 pthread_mutex_unlock(&localtime_mutex);
3738 tm_now = *localtime (&now);
3740 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3742 /* strlen("set-cookie: ") = 12 */
3743 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3745 #endif /* def FEATURE_COOKIE_JAR */
3747 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3749 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3752 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3754 /* Flag whether or not to log a message */
3757 /* A variable to store the tag we're working on */
3760 /* Skip "Set-Cookie:" (11 characters) in header */
3761 cur_tag = *header + 11;
3763 /* skip whitespace between "Set-Cookie:" and value */
3764 while (*cur_tag && ijb_isspace(*cur_tag))
3769 /* Loop through each tag in the cookie */
3773 char *next_tag = strchr(cur_tag, ';');
3774 if (next_tag != NULL)
3776 /* Skip the ';' character itself */
3779 /* skip whitespace ";" and start of tag */
3780 while (*next_tag && ijb_isspace(*next_tag))
3787 /* "Next tag" is the end of the string */
3788 next_tag = cur_tag + strlen(cur_tag);
3792 * Check the expiration date to see
3793 * if the cookie is still valid, if yes,
3794 * rewrite it to a session cookie.
3796 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3798 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3800 /* Did we detect the date properly? */
3801 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3804 * Nope, treat it as if it was still valid.
3806 * XXX: Should we remove the whole cookie instead?
3808 log_error(LOG_LEVEL_ERROR,
3809 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3810 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3816 * Yes. Check if the cookie is still valid.
3818 * If the cookie is already expired it's probably
3819 * a delete cookie and even if it isn't, the browser
3820 * will discard it anyway.
3824 * XXX: timegm() isn't available on some AmigaOS
3825 * versions and our replacement doesn't work.
3827 * Our options are to either:
3829 * - disable session-cookies-only completely if timegm
3832 * - to simply remove all expired tags, like it has
3833 * been done until Privoxy 3.0.6 and to live with
3834 * the consequence that it can cause login/logout
3835 * problems on servers that don't validate their
3836 * input properly, or
3838 * - to replace it with mktime in which
3839 * case there is a slight chance of valid cookies
3840 * passing as already expired.
3842 * This is the way it's currently done and it's not
3843 * as bad as it sounds. If the missing GMT offset is
3844 * enough to change the result of the expiration check
3845 * the cookie will be only valid for a few hours
3846 * anyway, which in many cases will be shorter
3847 * than a browser session.
3849 if (cookie_time - now < 0)
3851 log_error(LOG_LEVEL_HEADER,
3852 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3853 /* Just in case some clown sets more then one expiration date */
3859 * Still valid, delete expiration date by copying
3860 * the rest of the string over it.
3862 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3863 * since the behaviour of strcpy is undefined for overlapping
3866 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3868 /* That changed the header, need to issue a log message */
3872 * Note that the next tag has now been moved to *cur_tag,
3873 * so we do not need to update the cur_tag pointer.
3881 /* Move on to next cookie tag */
3888 assert(NULL != *header);
3889 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3898 #ifdef FEATURE_FORCE_LOAD
3899 /*********************************************************************
3901 * Function : strclean
3903 * Description : In-Situ-Eliminate all occurances of substring in
3907 * 1 : string = string to clean
3908 * 2 : substring = substring to eliminate
3910 * Returns : Number of eliminations
3912 *********************************************************************/
3913 int strclean(const char *string, const char *substring)
3919 len = strlen(substring);
3921 while((pos = strstr(string, substring)) != NULL)
3928 while (*p++ != '\0');
3935 #endif /* def FEATURE_FORCE_LOAD */
3937 /*********************************************************************
3939 * Function : parse_header_time
3941 * Description : Parses time formats used in HTTP header strings
3942 * to get the numerical respresentation.
3945 * 1 : header_time = HTTP header time as string.
3946 * 2 : result = storage for header_time in seconds
3948 * Returns : JB_ERR_OK if the time format was recognized, or
3949 * JB_ERR_PARSE otherwise.
3951 *********************************************************************/
3952 jb_err parse_header_time(const char *header_time, time_t *result)
3957 * Zero out gmt to prevent time zone offsets.
3959 * While this is only necessary on some platforms
3960 * (mingw32 for example), I don't know how to
3961 * detect these automatically and doing it everywhere
3964 memset(&gmt, 0, sizeof(gmt));
3966 /* Tue, 02 Jun 2037 20:00:00 */
3967 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3968 /* Tue, 02-Jun-2037 20:00:00 */
3969 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3970 /* Tue, 02-Jun-37 20:00:00 */
3971 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3972 /* Tuesday, 02-Jun-2037 20:00:00 */
3973 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3974 /* Tuesday Jun 02 20:00:00 2037 */
3975 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3977 return JB_ERR_PARSE;
3980 *result = timegm(&gmt);
3986 /*********************************************************************
3988 * Function : get_destination_from_headers
3990 * Description : Parse the "Host:" header to get the request's destination.
3991 * Only needed if the client's request was forcefully
3992 * redirected into Privoxy.
3994 * Code mainly copied from client_host() which is currently
3995 * run too late for this purpose.
3998 * 1 : headers = List of headers (one of them hopefully being
3999 * the "Host:" header)
4000 * 2 : http = storage for the result (host, port and hostport).
4002 * Returns : JB_ERR_MEMORY in case of memory problems,
4003 * JB_ERR_PARSE if the host header couldn't be found,
4004 * JB_ERR_OK otherwise.
4006 *********************************************************************/
4007 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4013 host = get_header_value(headers, "Host:");
4017 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4018 return JB_ERR_PARSE;
4021 if (NULL == (p = strdup((host))))
4023 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4024 return JB_ERR_MEMORY;
4027 if (NULL == (q = strdup(p)))
4030 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4031 return JB_ERR_MEMORY;
4034 freez(http->hostport);
4038 q = strchr(http->host, ':');
4041 /* Terminate hostname and evaluate port string */
4043 http->port = atoi(q);
4047 http->port = http->ssl ? 443 : 80;
4050 /* Rebuild request URL */
4052 http->url = strdup(http->ssl ? "https://" : "http://");
4053 string_append(&http->url, http->hostport);
4054 string_append(&http->url, http->path);
4055 if (http->url == NULL)
4057 return JB_ERR_MEMORY;
4060 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",