1 const char parsers_rcs[] = "$Id: parsers.c,v 1.107 2007/08/28 18:16: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.107 2007/08/28 18:16:32 fabiankeil
48 * Fix possible memory corruption in server_http, make sure it's not
49 * executed for ordinary server headers and mark some problems for later.
51 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
52 * Let content-type-overwrite{} honour force-text-mode again.
54 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
55 * - Add prototpyes for the header parsers and make them static.
56 * - Comment out client_accept_encoding_adder() which isn't used right now.
58 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
59 * Move the ACTION_FORCE_TEXT_MODE check out of
60 * server_content_type(). Signal other functions
61 * whether or not a content type has been declared.
62 * Part of the fix for BR#1750917.
64 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
65 * Change sed() to return a jb_err in preparation for forward-override{}.
67 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
68 * Adjust "X-Filter: No" to disable dedicated header filters.
70 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
71 * Streamline client_cookie_adder().
73 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
74 * Make sure filters with dynamic jobs actually use them.
76 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
77 * - Introduce dynamic pcrs jobs that can resolve variables.
78 * - Remove unnecessary update_action_bits_for_all_tags() call.
80 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
81 * - Make tagging based on tags set by earlier taggers
82 * of the same kind possible.
83 * - Log whether or not new tags cause action bits updates
84 * (in which case a matching tag-pattern section exists).
85 * - Log if the user tries to set a tag that is already set.
87 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
88 * Introduce tags as alternative way to specify which
89 * actions apply to a request. At the moment tags can be
90 * created based on client and server headers.
92 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
93 * Log a warning if the content is compressed, filtering is
94 * enabled and Privoxy was compiled without zlib support.
97 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
98 * - Fix warnings when compiled with glibc.
99 * - Don't use crumble() for cookie crunching.
100 * - Move cookie time parsing into parse_header_time().
101 * - Let parse_header_time() return a jb_err code
102 * instead of a pointer that can only be used to
103 * check for NULL anyway.
105 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
106 * - Add better protection against malicious gzip headers.
107 * - Stop logging the first hundred bytes of decompressed content.
108 * It looks like it's working and there is always debug 16.
109 * - Log the content size after decompression in decompress_iob()
110 * instead of pcrs_filter_response().
112 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
113 * - Use dedicated header filter actions instead of abusing "filter".
114 * Replace "filter-client-headers" and "filter-client-headers"
115 * with "server-header-filter" and "client-header-filter".
116 * - Remove filter_client_header() and filter_client_header(),
117 * filter_header() now checks the shiny new
118 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
120 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
121 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
122 * - Handle "Cookie:" and "Connection:" headers a bit smarter
123 * (don't crunch them just to recreate them later on).
124 * - Add another non-standard time format for the cookie
125 * expiration date detection.
126 * - Fix a valgrind warning.
128 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
129 * Improve cookie expiration date detection.
131 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
132 * Don't run server_content_length() the first time
133 * sed() parses server headers; only adjust the
134 * Content-Length header if the page was modified.
136 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
137 * Fix log messages regarding the cookie time format
138 * (cookie and request URL were mixed up).
140 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
141 * - Let decompress_iob()
142 * - not corrupt the content if decompression fails
143 * early. (the first byte(s) were lost).
144 * - use pointer arithmetics with defined outcome for
146 * - Use a different kludge to remember a failed decompression.
148 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
149 * Search for Max-Forwards headers case-insensitive,
150 * don't generate the "501 unsupported" message for invalid
151 * Max-Forwards values and don't increase negative ones.
153 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
154 * - Let server_set_cookie() check the expiration date
155 * of cookies and don't touch the ones that are already
156 * expired. Fixes problems with low quality web applications
157 * as described in BR 932612.
159 * - Adjust comment in client_max_forwards to reality;
160 * remove invalid Max-Forwards headers.
162 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
163 * Stop filter_header() from unintentionally removing
164 * empty header lines that were enlisted by the continue
167 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
168 * - Repeat the request URL before logging any headers.
169 * Makes reading the log easier in case of simultaneous requests.
170 * - If there are more than one Content-Type headers in one request,
171 * use the first one and remove the others.
172 * - Remove "newval" variable in server_content_type().
173 * It's only used once.
175 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
176 * Correct a cast, check inflateEnd() exit code
177 * to see if we have to, replace sprintf calls
180 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
181 * Integrate a modified version of Wil Mahan's
182 * zlib patch (PR #895531).
184 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
185 * Skip empty filter files in filter_header()
186 * but don't ignore the ones that come afterwards.
187 * Fixes BR 1619208, this time for real.
189 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
190 * Reverted parts of my last commit
191 * to keep error handling working.
193 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
194 * Fixed gcc43 conversion warnings.
196 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
197 * Bringing back the "useless" localtime() call
198 * I removed in revision 1.67. On some platforms
199 * it's necessary to prevent time zone offsets.
201 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
202 * Rebuild request URL in get_destination_from_headers()
203 * to make sure redirect{pcrs command} works as expected
204 * for intercepted requests.
206 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
207 * Added get_destination_from_headers().
209 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
210 * Make pthread mutex locking more generic. Instead of
211 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
212 * and use mutex locking unless there is an _r function
213 * available. Better safe than sorry.
215 * Fixes "./configure --disable-pthread" and should result
216 * in less threading-related problems on pthread-using platforms,
217 * but it still doesn't fix BR#1122404.
219 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
220 * The special header "X-Filter: No" now disables
221 * header filtering as well.
223 * Revision 1.73 2006/09/23 13:26:38 roro
224 * Replace TABs by spaces in source code.
226 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
227 * Don't print a log message every time filter_headers is
228 * entered or left. It only creates noise without any real
231 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
232 * Fix +hide-if-modified-since{-n}.
234 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
235 * Have hide-if-modified-since interpret the random
236 * range value as minutes instead of hours. Allows
237 * more fine-grained configuration.
239 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
240 * Always have parse_header_time return a pointer
241 * that actual makes sense, even though we currently
242 * only need it to detect problems.
244 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
245 * Added config option enable-remote-http-toggle
246 * to specify if Privoxy should recognize special
247 * headers (currently only X-Filter) to change its
248 * behaviour. Disabled by default.
250 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
251 * After filtering de-chunked instances, remove
252 * "Transfer-Encoding" header entirely instead of changing
253 * it to "Transfer-Encoding: identity", which is invalid.
254 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
256 * Don't use localtime in parse_header_time. An empty time struct
257 * is good enough, it gets overwritten by strptime anyway.
259 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
260 * Use gmtime_r if available, fallback to gmtime with mutex
261 * protection for MacOSX and use vanilla gmtime for the rest.
263 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
264 * Changed client_referrer to use the right type (size_t) for
265 * hostlenght and to shorten the temporary referrer string with
266 * '\0' instead of adding a useless line break.
268 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
269 * - Back to timegm() using GnuPG's replacement if necessary.
270 * Using mktime() and localtime() could add a on hour offset if
271 * the randomize factor was big enough to lead to a summer/wintertime
274 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
276 * - Moved randomization code into pick_from_range().
278 * - Changed parse_header_time definition.
279 * time_t isn't guaranteed to be signed and
280 * if it isn't, -1 isn't available as error code.
281 * Changed some variable types in client_if_modified_since()
282 * because of the same reason.
284 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
285 * OS/2 compilation compatibility fixups
287 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
288 * Changed include from strptime.c to strptime.h
290 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
291 * Split filter-headers{} into filter-client-headers{}
292 * and filter-server-headers{}.
293 * Added parse_header_time() to share some code.
294 * Replaced timegm() with mktime().
296 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
297 * Windows service integration
299 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
300 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
302 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
303 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
304 * with what was really the latest development (the v_3_0_branch branch)
306 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
307 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
309 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
310 * Add the ability to check jpeg images for invalid
311 * lengths of comment blocks. Defensive strategy
312 * against the exploit:
313 * Microsoft Security Bulletin MS04-028
314 * Buffer Overrun in JPEG Processing (GDI+) Could
315 * Allow Code Execution (833987)
316 * Enabled with +inspect-jpegs in actions files.
318 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
319 * Excluded text/plain objects from filtering. This fixes a
320 * couple of client-crashing, download corruption and
321 * Privoxy performance issues, whose root cause lies in
322 * web servers labelling content of unknown type as text/plain.
324 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
325 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
327 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
328 * Completing the previous change
330 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
331 * Added temporary workaround for bug in PHP < 4.2.3
333 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
334 * 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.
336 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
337 * Fix typo: supressed -> suppressed
339 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
340 * Improved cookie logging
342 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
343 * Added basic support for OPTIONS and TRACE HTTP methods:
344 * - New parser function client_max_forwards which decrements
345 * the Max-Forwards HTTP header field of OPTIONS and TRACE
346 * requests by one before forwarding
347 * - New parser function client_host which extracts the host
348 * and port information from the HTTP header field if the
349 * request URI was not absolute
350 * - Don't crumble and re-add the Host: header, but only generate
351 * and append if missing
353 * Revision 1.56 2002/05/12 15:34:22 jongfoster
354 * Fixing typo in a comment
356 * Revision 1.55 2002/05/08 16:01:07 oes
357 * Optimized add_to_iob:
358 * - Use realloc instead of malloc(), memcpy(), free()
359 * - Expand to powers of two if possible, to get
360 * O(log n) reallocs instead of O(n).
361 * - Moved check for buffer limit here from chat
362 * - Report failure via returncode
364 * Revision 1.54 2002/04/02 15:03:16 oes
365 * Tiny code cosmetics
367 * Revision 1.53 2002/03/26 22:29:55 swa
368 * we have a new homepage!
370 * Revision 1.52 2002/03/24 13:25:43 swa
371 * name change related issues
373 * Revision 1.51 2002/03/13 00:27:05 jongfoster
376 * Revision 1.50 2002/03/12 01:45:35 oes
377 * More verbose logging
379 * Revision 1.49 2002/03/09 20:03:52 jongfoster
380 * - Making various functions return int rather than size_t.
381 * (Undoing a recent change). Since size_t is unsigned on
382 * Windows, functions like read_socket that return -1 on
383 * error cannot return a size_t.
385 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
386 * crashes, and also frequently caused JB to jump to 100%
387 * CPU and stay there. (Because it thought it had just
388 * read ((unsigned)-1) == 4Gb of data...)
390 * - The signature of write_socket has changed, it now simply
391 * returns success=0/failure=nonzero.
393 * - Trying to get rid of a few warnings --with-debug on
394 * Windows, I've introduced a new type "jb_socket". This is
395 * used for the socket file descriptors. On Windows, this
396 * is SOCKET (a typedef for unsigned). Everywhere else, it's
397 * an int. The error value can't be -1 any more, so it's
398 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
399 * Windows it maps to the #define INVALID_SOCKET.)
401 * - The signature of bind_port has changed.
403 * Revision 1.48 2002/03/07 03:46:53 oes
404 * Fixed compiler warnings etc
406 * Revision 1.47 2002/02/20 23:15:13 jongfoster
407 * Parsing functions now handle out-of-memory gracefully by returning
410 * Revision 1.46 2002/01/17 21:03:47 jongfoster
411 * Moving all our URL and URL pattern parsing code to urlmatch.c.
413 * Revision 1.45 2002/01/09 14:33:03 oes
414 * Added support for localtime_r.
416 * Revision 1.44 2001/12/14 01:22:54 steudten
417 * Remove 'user:pass@' from 'proto://user:pass@host' for the
418 * new added header 'Host: ..'. (See Req ID 491818)
420 * Revision 1.43 2001/11/23 00:26:38 jongfoster
421 * Fixing two really stupid errors in my previous commit
423 * Revision 1.42 2001/11/22 21:59:30 jongfoster
424 * Adding code to handle +no-cookies-keep
426 * Revision 1.41 2001/11/05 23:43:05 steudten
427 * Add time+date to log files.
429 * Revision 1.40 2001/10/26 20:13:09 jongfoster
430 * ctype.h is needed in Windows, too.
432 * Revision 1.39 2001/10/26 17:40:04 oes
433 * Introduced get_header_value()
434 * Removed http->user_agent, csp->referrer and csp->accept_types
435 * Removed client_accept()
437 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
438 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
439 * threads to call select() simultaneously. So, it's time to do a real, live,
440 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
441 * (native). Both versions will work, but using __OS2__ offers multi-threading.
443 * Revision 1.37 2001/10/23 21:36:02 jongfoster
444 * Documenting sed()'s error behaviou (doc change only)
446 * Revision 1.36 2001/10/13 12:51:51 joergs
447 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
448 * force-load), instead crumble Host: and add it (again) in client_host_adder
449 * (in case we get a HTTP/1.0 request without Host: header and forward it to
450 * a HTTP/1.1 server/proxy).
452 * Revision 1.35 2001/10/09 22:39:21 jongfoster
453 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
456 * Revision 1.34 2001/10/07 18:50:55 oes
457 * Added server_content_encoding, renamed server_transfer_encoding
459 * Revision 1.33 2001/10/07 18:04:49 oes
460 * Changed server_http11 to server_http and its pattern to "HTTP".
461 * Additional functionality: it now saves the HTTP status into
462 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
464 * Revision 1.32 2001/10/07 15:43:28 oes
465 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
466 * client_te and client_accept_encoding_adder, triggered by the new
467 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
468 * changed to allow only identity and chunked, and the TE header is
469 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
471 * parse_http_request no longer does anything than parsing. The rewriting
472 * of http->cmd and version mangling are gone. It now also recognizes
473 * the put and delete methods and saves the url in http->url. Removed
476 * renamed content_type and content_length to have the server_ prefix
478 * server_content_type now only works if csp->content_type != CT_TABOO
480 * added server_transfer_encoding, which
481 * - Sets CT_TABOO to prohibit filtering if encoding compresses
482 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
483 * - Change from "chunked" to "identity" if body was chunked
484 * but has been de-chunked for filtering.
486 * added server_content_md5 which crunches any Content-MD5 headers
487 * if the body was modified.
489 * made server_http11 conditional on +downgrade action
491 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
493 * Revision 1.31 2001/10/05 14:25:02 oes
494 * Crumble Keep-Alive from Server
496 * Revision 1.30 2001/09/29 12:56:03 joergs
497 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
499 * Revision 1.29 2001/09/24 21:09:24 jongfoster
500 * Fixing 2 memory leaks that Guy spotted, where the paramater to
501 * enlist() was not being free()d.
503 * Revision 1.28 2001/09/22 16:32:28 jongfoster
504 * Removing unused #includes.
506 * Revision 1.27 2001/09/20 15:45:25 steudten
508 * add casting from size_t to int for printf()
509 * remove local variable shadow s2
511 * Revision 1.26 2001/09/16 17:05:14 jongfoster
512 * Removing unused #include showarg.h
514 * Revision 1.25 2001/09/16 13:21:27 jongfoster
515 * Changes to use new list functions.
517 * Revision 1.24 2001/09/13 23:05:50 jongfoster
518 * Changing the string paramater to the header parsers a "const".
520 * Revision 1.23 2001/09/12 18:08:19 steudten
522 * In parse_http_request() header rewriting miss the host value, so
523 * from http://www.mydomain.com the result was just " / " not
524 * http://www.mydomain.com/ in case we forward.
526 * Revision 1.22 2001/09/10 10:58:53 oes
527 * Silenced compiler warnings
529 * Revision 1.21 2001/07/31 14:46:00 oes
530 * - Persistant connections now suppressed
531 * - sed() no longer appends empty header to csp->headers
533 * Revision 1.20 2001/07/30 22:08:36 jongfoster
534 * Tidying up #defines:
535 * - All feature #defines are now of the form FEATURE_xxx
536 * - Permanently turned off WIN_GUI_EDIT
537 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
539 * Revision 1.19 2001/07/25 17:21:54 oes
540 * client_uagent now saves copy of User-Agent: header value
542 * Revision 1.18 2001/07/13 14:02:46 oes
543 * - Included fix to repair broken HTTP requests that
544 * don't contain a path, not even '/'.
545 * - Removed all #ifdef PCRS
546 * - content_type now always inspected and classified as
547 * text, gif or other.
548 * - formatting / comments
550 * Revision 1.17 2001/06/29 21:45:41 oes
551 * Indentation, CRLF->LF, Tab-> Space
553 * Revision 1.16 2001/06/29 13:32:42 oes
555 * - Adapted free_http_request
556 * - Removed logentry from cancelled commit
558 * Revision 1.15 2001/06/03 19:12:38 oes
559 * deleted const struct interceptors
561 * Revision 1.14 2001/06/01 18:49:17 jongfoster
562 * Replaced "list_share" with "list" - the tiny memory gain was not
563 * worth the extra complexity.
565 * Revision 1.13 2001/05/31 21:30:33 jongfoster
566 * Removed list code - it's now in list.[ch]
567 * Renamed "permission" to "action", and changed many features
568 * to use the actions file rather than the global config.
570 * Revision 1.12 2001/05/31 17:33:13 oes
574 * Revision 1.11 2001/05/29 20:11:19 joergs
575 * '/ * inside comment' warning removed.
577 * Revision 1.10 2001/05/29 09:50:24 jongfoster
578 * Unified blocklist/imagelist/permissionslist.
579 * File format is still under discussion, but the internal changes
582 * Also modified interceptor behaviour:
583 * - We now intercept all URLs beginning with one of the following
584 * prefixes (and *only* these prefixes):
586 * * http://ijbswa.sf.net/config/
587 * * http://ijbswa.sourceforge.net/config/
588 * - New interceptors "home page" - go to http://i.j.b/ to see it.
589 * - Internal changes so that intercepted and fast redirect pages
590 * are not replaced with an image.
591 * - Interceptors now have the option to send a binary page direct
592 * to the client. (i.e. ijb-send-banner uses this)
593 * - Implemented show-url-info interceptor. (Which is why I needed
594 * the above interceptors changes - a typical URL is
595 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
596 * The previous mechanism would not have intercepted that, and
597 * if it had been intercepted then it then it would have replaced
600 * Revision 1.9 2001/05/28 17:26:33 jongfoster
601 * Fixing segfault if last header was crunched.
602 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
603 * can use the cross-platform sprintf() instead.)
605 * Revision 1.8 2001/05/27 22:17:04 oes
607 * - re_process_buffer no longer writes the modified buffer
608 * to the client, which was very ugly. It now returns the
609 * buffer, which it is then written by chat.
611 * - content_length now adjusts the Content-Length: header
612 * for modified documents rather than crunch()ing it.
613 * (Length info in csp->content_length, which is 0 for
614 * unmodified documents)
616 * - For this to work, sed() is called twice when filtering.
618 * Revision 1.7 2001/05/27 13:19:06 oes
619 * Patched Joergs solution for the content-length in.
621 * Revision 1.6 2001/05/26 13:39:32 jongfoster
622 * Only crunches Content-Length header if applying RE filtering.
623 * Without this fix, Microsoft Windows Update wouldn't work.
625 * Revision 1.5 2001/05/26 00:28:36 jongfoster
626 * Automatic reloading of config file.
627 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
628 * Most of the global variables have been moved to a new
629 * struct configuration_spec, accessed through csp->config->globalname
630 * Most of the globals remaining are used by the Win32 GUI.
632 * Revision 1.4 2001/05/22 18:46:04 oes
634 * - Enabled filtering banners by size rather than URL
635 * by adding patterns that replace all standard banner
636 * sizes with the "Junkbuster" gif to the re_filterfile
638 * - Enabled filtering WebBugs by providing a pattern
639 * which kills all 1x1 images
641 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
642 * which is selected by the (nonstandard and therefore
643 * capital) letter 'U' in the option string.
644 * It causes the quantifiers to be ungreedy by default.
645 * Appending a ? turns back to greedy (!).
647 * - Added a new interceptor ijb-send-banner, which
648 * sends back the "Junkbuster" gif. Without imagelist or
649 * MSIE detection support, or if tinygif = 1, or the
650 * URL isn't recognized as an imageurl, a lame HTML
651 * explanation is sent instead.
653 * - Added new feature, which permits blocking remote
654 * script redirects and firing back a local redirect
656 * The feature is conditionally compiled, i.e. it
657 * can be disabled with --disable-fast-redirects,
658 * plus it must be activated by a "fast-redirects"
659 * line in the config file, has its own log level
660 * and of course wants to be displayed by show-proxy-args
661 * Note: Boy, all the #ifdefs in 1001 locations and
662 * all the fumbling with configure.in and acconfig.h
663 * were *way* more work than the feature itself :-(
665 * - Because a generic redirect template was needed for
666 * this, tinygif = 3 now uses the same.
668 * - Moved GIFs, and other static HTTP response templates
673 * - Removed some >400 CRs again (Jon, you really worked
676 * Revision 1.3 2001/05/20 01:21:20 jongfoster
677 * Version 2.9.4 checkin.
678 * - Merged popupfile and cookiefile, and added control over PCRS
679 * filtering, in new "permissionsfile".
680 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
681 * file error you now get a message box (in the Win32 GUI) rather
682 * than the program exiting with no explanation.
683 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
685 * - Removed tabs from "config"
686 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
687 * - Bumped up version number.
689 * Revision 1.2 2001/05/17 23:02:36 oes
690 * - Made referrer option accept 'L' as a substitute for '§'
692 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
693 * Initial import of version 2.9.3 source tree
696 *********************************************************************/
703 #include <sys/types.h>
713 * Convince GNU's libc to provide a strptime prototype.
716 #endif /*__GLIBC__ */
723 #if !defined(_WIN32) && !defined(__OS2__)
729 #ifdef FEATURE_PTHREAD
731 /* jcc.h is for mutex semapores only */
732 #endif /* def FEATURE_PTHREAD */
738 #include "jbsockets.h"
739 #include "miscutil.h"
744 #ifndef HAVE_STRPTIME
745 #include "strptime.h"
748 const char parsers_h_rcs[] = PARSERS_H_VERSION;
750 /* Fix a problem with Solaris. There should be no effect on other
752 * Solaris's isspace() is a macro which uses its argument directly
753 * as an array index. Therefore we need to make sure that high-bit
754 * characters generate +ve values, and ideally we also want to make
755 * the argument match the declared parameter type of "int".
757 * Why did they write a character function that can't take a simple
758 * "char" argument? Doh!
760 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
761 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
763 static jb_err scan_headers(struct client_state *csp);
764 static jb_err header_tagger(struct client_state *csp, char *header);
765 static jb_err parse_header_time(const char *header_time, time_t *result);
767 static jb_err crumble (struct client_state *csp, char **header);
768 static jb_err connection (struct client_state *csp, char **header);
769 static jb_err filter_header (struct client_state *csp, char **header);
770 static jb_err client_referrer (struct client_state *csp, char **header);
771 static jb_err client_uagent (struct client_state *csp, char **header);
772 static jb_err client_ua (struct client_state *csp, char **header);
773 static jb_err client_from (struct client_state *csp, char **header);
774 static jb_err client_send_cookie (struct client_state *csp, char **header);
775 static jb_err client_x_forwarded (struct client_state *csp, char **header);
776 static jb_err client_accept_encoding (struct client_state *csp, char **header);
777 static jb_err client_te (struct client_state *csp, char **header);
778 static jb_err client_max_forwards (struct client_state *csp, char **header);
779 static jb_err client_host (struct client_state *csp, char **header);
780 static jb_err client_if_modified_since (struct client_state *csp, char **header);
781 static jb_err client_accept_language (struct client_state *csp, char **header);
782 static jb_err client_if_none_match (struct client_state *csp, char **header);
783 static jb_err crunch_client_header (struct client_state *csp, char **header);
784 static jb_err client_x_filter (struct client_state *csp, char **header);
785 static jb_err server_set_cookie (struct client_state *csp, char **header);
786 static jb_err server_content_type (struct client_state *csp, char **header);
787 static jb_err server_content_length (struct client_state *csp, char **header);
788 static jb_err server_content_md5 (struct client_state *csp, char **header);
789 static jb_err server_content_encoding (struct client_state *csp, char **header);
790 static jb_err server_transfer_coding (struct client_state *csp, char **header);
791 static jb_err server_http (struct client_state *csp, char **header);
792 static jb_err crunch_server_header (struct client_state *csp, char **header);
793 static jb_err server_last_modified (struct client_state *csp, char **header);
794 static jb_err server_content_disposition(struct client_state *csp, char **header);
796 static jb_err client_host_adder (struct client_state *csp);
797 static jb_err client_cookie_adder (struct client_state *csp);
798 static jb_err client_xtra_adder (struct client_state *csp);
799 static jb_err client_x_forwarded_adder(struct client_state *csp);
800 static jb_err connection_close_adder (struct client_state *csp);
802 const struct parsers client_patterns[] = {
803 { "referer:", 8, client_referrer },
804 { "user-agent:", 11, client_uagent },
805 { "ua-", 3, client_ua },
806 { "from:", 5, client_from },
807 { "cookie:", 7, client_send_cookie },
808 { "x-forwarded-for:", 16, client_x_forwarded },
809 { "Accept-Encoding:", 16, client_accept_encoding },
810 { "TE:", 3, client_te },
811 { "Host:", 5, client_host },
812 { "if-modified-since:", 18, client_if_modified_since },
813 { "Keep-Alive:", 11, crumble },
814 { "connection:", 11, connection },
815 { "proxy-connection:", 17, crumble },
816 { "max-forwards:", 13, client_max_forwards },
817 { "Accept-Language:", 16, client_accept_language },
818 { "if-none-match:", 14, client_if_none_match },
819 { "X-Filter:", 9, client_x_filter },
820 { "*", 0, crunch_client_header },
821 { "*", 0, filter_header },
825 const struct parsers server_patterns[] = {
826 { "HTTP/", 5, server_http },
827 { "set-cookie:", 11, server_set_cookie },
828 { "connection:", 11, connection },
829 { "Content-Type:", 13, server_content_type },
830 { "Content-MD5:", 12, server_content_md5 },
831 { "Content-Encoding:", 17, server_content_encoding },
832 { "Transfer-Encoding:", 18, server_transfer_coding },
833 { "Keep-Alive:", 11, crumble },
834 { "content-disposition:", 20, server_content_disposition },
835 { "Last-Modified:", 14, server_last_modified },
836 { "*", 0, crunch_server_header },
837 { "*", 0, filter_header },
841 const struct parsers server_patterns_light[] = {
842 { "Content-Length:", 15, server_content_length },
843 { "Transfer-Encoding:", 18, server_transfer_coding },
845 { "Content-Encoding:", 17, server_content_encoding },
846 #endif /* def FEATURE_ZLIB */
850 const add_header_func_ptr add_client_headers[] = {
853 client_x_forwarded_adder,
855 /* Temporarily disabled: client_accept_encoding_adder, */
856 connection_close_adder,
861 const add_header_func_ptr add_server_headers[] = {
862 connection_close_adder,
866 /*********************************************************************
868 * Function : flush_socket
870 * Description : Write any pending "buffered" content.
873 * 1 : fd = file descriptor of the socket to read
874 * 2 : csp = Current client state (buffers, headers, etc...)
876 * Returns : On success, the number of bytes written are returned (zero
877 * indicates nothing was written). On error, -1 is returned,
878 * and errno is set appropriately. If count is zero and the
879 * file descriptor refers to a regular file, 0 will be
880 * returned without causing any other effect. For a special
881 * file, the results are not portable.
883 *********************************************************************/
884 int flush_socket(jb_socket fd, struct client_state *csp)
886 struct iob *iob = csp->iob;
887 int len = iob->eod - iob->cur;
894 if (write_socket(fd, iob->cur, (size_t)len))
898 iob->eod = iob->cur = iob->buf;
904 /*********************************************************************
906 * Function : add_to_iob
908 * Description : Add content to the buffered page, expanding the
909 * buffer if necessary.
912 * 1 : csp = Current client state (buffers, headers, etc...)
913 * 2 : buf = holds the content to be added to the page
914 * 3 : n = number of bytes to be added
916 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
917 * or buffer limit reached.
919 *********************************************************************/
920 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
922 struct iob *iob = csp->iob;
923 size_t used, offset, need, want;
926 if (n <= 0) return JB_ERR_OK;
928 used = (size_t)(iob->eod - iob->buf);
929 offset = (size_t)(iob->cur - iob->buf);
930 need = used + (size_t)n + 1;
933 * If the buffer can't hold the new data, extend it first.
934 * Use the next power of two if possible, else use the actual need.
936 if (need > csp->config->buffer_limit)
938 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
939 return JB_ERR_MEMORY;
942 if (need > iob->size)
944 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
946 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
950 else if (NULL != (p = (char *)realloc(iob->buf, need)))
956 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
957 return JB_ERR_MEMORY;
960 /* Update the iob pointers */
961 iob->cur = p + offset;
966 /* copy the new data into the iob buffer */
967 memcpy(iob->eod, buf, (size_t)n);
969 /* point to the end of the data */
972 /* null terminate == cheap insurance */
981 /*********************************************************************
983 * Function : decompress_iob
985 * Description : Decompress buffered page, expanding the
986 * buffer as necessary. csp->iob->cur
987 * should point to the the beginning of the
988 * compressed data block.
991 * 1 : csp = Current client state (buffers, headers, etc...)
993 * Returns : JB_ERR_OK on success,
994 * JB_ERR_MEMORY if out-of-memory limit reached, and
995 * JB_ERR_COMPRESS if error decompressing buffer.
997 *********************************************************************/
998 jb_err decompress_iob(struct client_state *csp)
1000 char *buf; /* new, uncompressed buffer */
1001 char *cur; /* Current iob position (to keep the original
1002 * iob->cur unmodified if we return early) */
1003 size_t bufsize; /* allocated size of the new buffer */
1004 size_t old_size; /* Content size before decompression */
1005 size_t skip_size; /* Number of bytes at the beginning of the iob
1006 that we should NOT decompress. */
1007 int status; /* return status of the inflate() call */
1008 z_stream zstr; /* used by calls to zlib */
1010 assert(csp->iob->cur - csp->iob->buf > 0);
1011 assert(csp->iob->eod - csp->iob->cur > 0);
1013 bufsize = csp->iob->size;
1014 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1015 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1017 cur = csp->iob->cur;
1022 * This is to protect the parsing of gzipped data,
1023 * but it should(?) be valid for deflated data also.
1025 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1026 return JB_ERR_COMPRESS;
1029 if (csp->content_type & CT_GZIP)
1032 * Our task is slightly complicated by the facts that data
1033 * compressed by gzip does not include a zlib header, and
1034 * that there is no easily accessible interface in zlib to
1035 * handle a gzip header. We strip off the gzip header by
1036 * hand, and later inform zlib not to expect a header.
1040 * Strip off the gzip header. Please see RFC 1952 for more
1041 * explanation of the appropriate fields.
1043 if ((*cur++ != (char)0x1f)
1044 || (*cur++ != (char)0x8b)
1045 || (*cur++ != Z_DEFLATED))
1047 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1048 return JB_ERR_COMPRESS;
1054 * XXX: These magic numbers should be replaced
1055 * with macros to give a better idea what they do.
1059 /* The gzip header has reserved bits set; bail out. */
1060 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1061 return JB_ERR_COMPRESS;
1065 /* Skip extra fields if necessary. */
1069 * Skip a given number of bytes, specified
1070 * as a 16-bit little-endian value.
1073 * XXX: This code used to be:
1075 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1077 * which I had to change into:
1079 * cur += *cur++ + (*cur++ << 8);
1081 * at which point gcc43 finally noticed that the value
1082 * of cur is undefined (it depends on which of the
1083 * summands is evaluated first).
1085 * I haven't come across a site where this
1086 * code is actually executed yet, but I hope
1090 skip_bytes = *cur++;
1091 skip_bytes = *cur++ << 8;
1093 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1096 * The number of bytes to skip should be positive
1097 * and we'd like to stay in the buffer.
1099 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1101 log_error(LOG_LEVEL_ERROR,
1102 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1104 return JB_ERR_COMPRESS;
1106 log_error(LOG_LEVEL_INFO,
1107 "Skipping %d bytes for gzip compression. Does this sound right?",
1112 /* Skip the filename if necessary. */
1115 /* A null-terminated string is supposed to follow. */
1116 while (*cur++ && (cur < csp->iob->eod));
1120 /* Skip the comment if necessary. */
1123 /* A null-terminated string is supposed to follow. */
1124 while (*cur++ && (cur < csp->iob->eod));
1127 /* Skip the CRC if necessary. */
1133 if (cur >= csp->iob->eod)
1136 * If the current position pointer reached or passed
1137 * the buffer end, we were obviously tricked to skip
1140 log_error(LOG_LEVEL_ERROR,
1141 "Malformed gzip header detected. Aborting decompression.");
1142 return JB_ERR_COMPRESS;
1146 else if (csp->content_type & CT_DEFLATE)
1149 * XXX: The debug level should be lowered
1150 * before the next stable release.
1152 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1154 * In theory (that is, according to RFC 1950), deflate-compressed
1155 * data should begin with a two-byte zlib header and have an
1156 * adler32 checksum at the end. It seems that in practice only
1157 * the raw compressed data is sent. Note that this means that
1158 * we are not RFC 1950-compliant here, but the advantage is that
1159 * this actually works. :)
1161 * We add a dummy null byte to tell zlib where the data ends,
1162 * and later inform it not to expect a header.
1164 * Fortunately, add_to_iob() has thoughtfully null-terminated
1165 * the buffer; we can just increment the end pointer to include
1172 log_error(LOG_LEVEL_ERROR,
1173 "Unable to determine compression format for decompression");
1174 return JB_ERR_COMPRESS;
1177 /* Set up the fields required by zlib. */
1178 zstr.next_in = (Bytef *)cur;
1179 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1180 zstr.zalloc = Z_NULL;
1181 zstr.zfree = Z_NULL;
1182 zstr.opaque = Z_NULL;
1185 * Passing -MAX_WBITS to inflateInit2 tells the library
1186 * that there is no zlib header.
1188 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1190 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1191 return JB_ERR_COMPRESS;
1195 * Next, we allocate new storage for the inflated data.
1196 * We don't modify the existing iob yet, so in case there
1197 * is error in decompression we can recover gracefully.
1199 buf = zalloc(bufsize);
1202 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1203 return JB_ERR_MEMORY;
1206 assert(bufsize >= skip_size);
1207 memcpy(buf, csp->iob->buf, skip_size);
1208 zstr.avail_out = bufsize - skip_size;
1209 zstr.next_out = (Bytef *)buf + skip_size;
1211 /* Try to decompress the whole stream in one shot. */
1212 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1214 /* We need to allocate more memory for the output buffer. */
1216 char *tmpbuf; /* used for realloc'ing the buffer */
1217 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1220 * If zlib wants more data then there's a problem, because
1221 * the complete compressed file should have been buffered.
1223 if (0 == zstr.avail_in)
1225 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1226 return JB_ERR_COMPRESS;
1230 * If we tried the limit and still didn't have enough
1231 * memory, just give up.
1233 if (bufsize == csp->config->buffer_limit)
1235 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1236 return JB_ERR_MEMORY;
1239 /* Try doubling the buffer size each time. */
1242 /* Don't exceed the buffer limit. */
1243 if (bufsize > csp->config->buffer_limit)
1245 bufsize = csp->config->buffer_limit;
1248 /* Try to allocate the new buffer. */
1249 tmpbuf = realloc(buf, bufsize);
1252 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1254 return JB_ERR_MEMORY;
1258 char *oldnext_out = (char *)zstr.next_out;
1261 * Update the fields for inflate() to use the new
1262 * buffer, which may be in a location different from
1265 zstr.avail_out += bufsize - oldbufsize;
1266 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1269 * Compare with an uglier method of calculating these values
1270 * that doesn't require the extra oldbufsize variable.
1272 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1273 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1274 assert(zstr.avail_out > 0);
1280 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1282 log_error(LOG_LEVEL_ERROR,
1283 "Inconsistent stream state after decompression: %s", zstr.msg);
1285 * XXX: Intentionally no return.
1287 * According to zlib.h, Z_STREAM_ERROR is returned
1288 * "if the stream state was inconsistent".
1290 * I assume in this case inflate()'s status
1291 * would also be something different than Z_STREAM_END
1292 * so this check should be redundant, but lets see.
1296 if (status != Z_STREAM_END)
1298 /* We failed to decompress the stream. */
1299 log_error(LOG_LEVEL_ERROR,
1300 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1301 return JB_ERR_COMPRESS;
1305 * Finally, we can actually update the iob, since the
1306 * decompression was successful. First, free the old
1309 freez(csp->iob->buf);
1311 /* Now, update the iob to use the new buffer. */
1312 csp->iob->buf = buf;
1313 csp->iob->cur = csp->iob->buf + skip_size;
1314 csp->iob->eod = (char *)zstr.next_out;
1315 csp->iob->size = bufsize;
1318 * Make sure the new uncompressed iob obeys some minimal
1319 * consistency conditions.
1321 if ((csp->iob->buf < csp->iob->cur)
1322 && (csp->iob->cur <= csp->iob->eod)
1323 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1325 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1328 log_error(LOG_LEVEL_RE_FILTER,
1329 "Decompression successful. Old size: %d, new size: %d.",
1330 old_size, new_size);
1334 /* zlib thinks this is OK, so lets do the same. */
1335 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1340 /* It seems that zlib did something weird. */
1341 log_error(LOG_LEVEL_ERROR,
1342 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1343 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1344 csp->iob->eod, csp->iob->buf + csp->iob->size);
1345 return JB_ERR_COMPRESS;
1351 #endif /* defined(FEATURE_ZLIB) */
1354 /*********************************************************************
1356 * Function : get_header
1358 * Description : This (odd) routine will parse the csp->iob
1361 * 1 : csp = Current client state (buffers, headers, etc...)
1363 * Returns : Any one of the following:
1365 * 1) a pointer to a dynamically allocated string that contains a header line
1366 * 2) NULL indicating that the end of the header was reached
1367 * 3) "" indicating that the end of the iob was reached before finding
1368 * a complete header line.
1370 *********************************************************************/
1371 char *get_header(struct client_state *csp)
1377 if ((iob->cur == NULL)
1378 || ((p = strchr(iob->cur, '\n')) == NULL))
1380 return(""); /* couldn't find a complete header */
1385 ret = strdup(iob->cur);
1388 /* FIXME No way to handle error properly */
1389 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1394 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1396 /* is this a blank line (i.e. the end of the header) ? */
1408 /*********************************************************************
1410 * Function : get_header_value
1412 * Description : Get the value of a given header from a chained list
1413 * of header lines or return NULL if no such header is
1414 * present in the list.
1417 * 1 : header_list = pointer to list
1418 * 2 : header_name = string with name of header to look for.
1419 * Trailing colon required, capitalization
1422 * Returns : NULL if not found, else value of header
1424 *********************************************************************/
1425 char *get_header_value(const struct list *header_list, const char *header_name)
1427 struct list_entry *cur_entry;
1431 assert(header_list);
1432 assert(header_name);
1433 length = strlen(header_name);
1435 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1439 if (!strncmpic(cur_entry->str, header_name, length))
1442 * Found: return pointer to start of value
1444 ret = (char *) (cur_entry->str + length);
1445 while (*ret && ijb_isspace(*ret)) ret++;
1459 /*********************************************************************
1461 * Function : scan_headers
1463 * Description : Scans headers, applies tags and updates action bits.
1466 * 1 : csp = Current client state (buffers, headers, etc...)
1468 * Returns : JB_ERR_OK
1470 *********************************************************************/
1471 static jb_err scan_headers(struct client_state *csp)
1473 struct list_entry *h; /* Header */
1474 jb_err err = JB_ERR_OK;
1476 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1478 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1480 /* Header crunch()ed in previous run? -> ignore */
1481 if (h->str == NULL) continue;
1482 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1483 err = header_tagger(csp, h->str);
1490 /*********************************************************************
1494 * Description : add, delete or modify lines in the HTTP header streams.
1495 * On entry, it receives a linked list of headers space
1496 * that was allocated dynamically (both the list nodes
1497 * and the header contents).
1499 * As a side effect it frees the space used by the original
1503 * 1 : pats = list of patterns to match against headers
1504 * 2 : more_headers = list of functions to add more
1505 * headers (client or server)
1506 * 3 : csp = Current client state (buffers, headers, etc...)
1508 * Returns : JB_ERR_OK in case off success, or
1509 * JB_ERR_MEMORY on out-of-memory error.
1511 *********************************************************************/
1512 jb_err sed(const struct parsers pats[],
1513 const add_header_func_ptr more_headers[],
1514 struct client_state *csp)
1516 struct list_entry *p;
1517 const struct parsers *v;
1518 const add_header_func_ptr *f;
1519 jb_err err = JB_ERR_OK;
1523 * If filtering is enabled, sed is run twice,
1524 * but most of the work needs to be done only once.
1526 first_run = (more_headers != NULL ) ? 1 : 0;
1528 if (first_run) /* Parse and print */
1532 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1534 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1536 /* Header crunch()ed in previous run? -> ignore */
1537 if (p->str == NULL) continue;
1539 /* Does the current parser handle this header? */
1540 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1542 err = v->parser(csp, (char **)&(p->str));
1546 /* place any additional headers on the csp->headers list */
1547 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1552 else /* Parse only */
1555 * The second run is only needed if the body was modified
1556 * and the content-lenght has changed.
1558 if (strncmpic(csp->http->cmd, "HEAD", 4))
1560 /*XXX: Code duplication */
1561 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1563 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1565 /* Header crunch()ed in previous run? -> ignore */
1566 if (p->str == NULL) continue;
1568 /* Does the current parser handle this header? */
1569 if (strncmpic(p->str, v->str, v->len) == 0)
1571 err = v->parser(csp, (char **)&(p->str));
1583 /*********************************************************************
1585 * Function : header_tagger
1587 * Description : Executes all text substitutions from applying
1588 * tag actions and saves the result as tag.
1590 * XXX: Shares enough code with filter_header() and
1591 * pcrs_filter_response() to warrant some helper functions.
1594 * 1 : csp = Current client state (buffers, headers, etc...)
1595 * 2 : header = Header that is used as tagger input
1597 * Returns : JB_ERR_OK on success and always succeeds
1599 *********************************************************************/
1600 static jb_err header_tagger(struct client_state *csp, char *header)
1602 int wanted_filter_type;
1603 int multi_action_index;
1607 struct file_list *fl;
1608 struct re_filterfile_spec *b;
1609 struct list_entry *tag_name;
1611 int found_filters = 0;
1612 const size_t header_length = strlen(header);
1614 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1616 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1617 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1621 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1622 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1625 /* Check if there are any filters */
1626 for (i = 0; i < MAX_AF_FILES; i++)
1639 if (0 == found_filters)
1641 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1645 for (i = 0; i < MAX_AF_FILES; i++)
1648 if ((NULL == fl) || (NULL == fl->f))
1651 * Either there are no filter files
1652 * left, or this filter file just
1653 * contains no valid filters.
1655 * Continue to be sure we don't miss
1656 * valid filter files that are chained
1657 * after empty or invalid ones.
1662 /* For all filters, */
1663 for (b = fl->f; b; b = b->next)
1665 if (b->type != wanted_filter_type)
1667 /* skip the ones we don't care about, */
1670 /* leaving only taggers that could apply, of which we use the ones, */
1671 for (tag_name = csp->action->multi[multi_action_index]->first;
1672 NULL != tag_name; tag_name = tag_name->next)
1674 /* that do apply, and */
1675 if (strcmp(b->name, tag_name->str) == 0)
1677 char *modified_tag = NULL;
1679 size_t size = header_length;
1680 pcrs_job *joblist = b->joblist;
1682 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1684 if (NULL == joblist)
1686 log_error(LOG_LEVEL_RE_FILTER,
1687 "Tagger %s has empty joblist. Nothing to do.", b->name);
1691 /* execute their pcrs_joblist on the header. */
1692 for (job = joblist; NULL != job; job = job->next)
1694 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1698 /* Success, continue with the modified version. */
1707 /* Tagger doesn't match */
1710 /* Regex failure, log it but continue anyway. */
1711 log_error(LOG_LEVEL_ERROR,
1712 "Problems with tagger \'%s\' and header \'%s\': %s",
1713 b->name, *header, pcrs_strerror(hits));
1715 freez(modified_tag);
1719 if (b->dynamic) pcrs_free_joblist(joblist);
1721 /* If this tagger matched */
1727 * There is to technical limitation which makes
1728 * it impossible to use empty tags, but I assume
1729 * no one would do it intentionally.
1732 log_error(LOG_LEVEL_INFO,
1733 "Tagger \'%s\' created an empty tag. Ignored.",
1738 if (!list_contains_item(csp->tags, tag))
1740 if (JB_ERR_OK != enlist(csp->tags, tag))
1742 log_error(LOG_LEVEL_ERROR,
1743 "Insufficient memory to add tag \'%s\', "
1744 "based on tagger \'%s\' and header \'%s\'",
1745 tag, b->name, *header);
1749 char *action_message;
1751 * update the action bits right away, to make
1752 * tagging based on tags set by earlier taggers
1753 * of the same kind possible.
1755 if (update_action_bits_for_tag(csp, tag))
1757 action_message = "Action bits updated accordingly.";
1761 action_message = "No action bits update necessary.";
1764 log_error(LOG_LEVEL_HEADER,
1765 "Tagger \'%s\' added tag \'%s\'. %s",
1766 b->name, tag, action_message);
1771 /* XXX: Is this log-worthy? */
1772 log_error(LOG_LEVEL_HEADER,
1773 "Tagger \'%s\' didn't add tag \'%s\'. "
1774 "Tag already present", b->name, tag);
1777 } /* if the tagger matched */
1778 } /* if the tagger applies */
1779 } /* for every tagger that could apply */
1780 } /* for all filters */
1781 } /* for all filter files */
1786 /* here begins the family of parser functions that reformat header lines */
1788 /*********************************************************************
1790 * Function : filter_header
1792 * Description : Executes all text substitutions from all applying
1793 * +(server|client)-header-filter actions on the header.
1794 * Most of the code was copied from pcrs_filter_response,
1795 * including the rather short variable names
1798 * 1 : csp = Current client state (buffers, headers, etc...)
1799 * 2 : header = On input, pointer to header to modify.
1800 * On output, pointer to the modified header, or NULL
1801 * to remove the header. This function frees the
1802 * original string if necessary.
1804 * Returns : JB_ERR_OK on success and always succeeds
1806 *********************************************************************/
1807 static jb_err filter_header(struct client_state *csp, char **header)
1811 size_t size = strlen(*header);
1813 char *newheader = NULL;
1816 struct file_list *fl;
1817 struct re_filterfile_spec *b;
1818 struct list_entry *filtername;
1820 int i, found_filters = 0;
1821 int wanted_filter_type;
1822 int multi_action_index;
1824 if (csp->flags & CSP_FLAG_NO_FILTERING)
1829 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1831 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1832 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1836 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1837 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1841 * Need to check the set of re_filterfiles...
1843 for (i = 0; i < MAX_AF_FILES; i++)
1856 if (0 == found_filters)
1858 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1862 for (i = 0; i < MAX_AF_FILES; i++)
1865 if ((NULL == fl) || (NULL == fl->f))
1868 * Either there are no filter files
1869 * left, or this filter file just
1870 * contains no valid filters.
1872 * Continue to be sure we don't miss
1873 * valid filter files that are chained
1874 * after empty or invalid ones.
1879 * For all applying +filter actions, look if a filter by that
1880 * name exists and if yes, execute its pcrs_joblist on the
1883 for (b = fl->f; b; b = b->next)
1885 if (b->type != wanted_filter_type)
1887 /* Skip other filter types */
1891 for (filtername = csp->action->multi[multi_action_index]->first;
1892 filtername ; filtername = filtername->next)
1894 if (strcmp(b->name, filtername->str) == 0)
1896 int current_hits = 0;
1897 pcrs_job *joblist = b->joblist;
1899 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1901 if (NULL == joblist)
1903 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1907 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1908 *header, size, b->name);
1910 /* Apply all jobs from the joblist */
1911 for (job = joblist; NULL != job; job = job->next)
1913 matches = pcrs_execute(job, *header, size, &newheader, &size);
1916 current_hits += matches;
1917 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1919 *header = newheader;
1921 else if ( 0 == matches )
1923 /* Filter doesn't change header */
1929 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1930 *header, b->name, pcrs_strerror(matches));
1931 if( newheader != NULL)
1933 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1939 if (b->dynamic) pcrs_free_joblist(joblist);
1941 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1942 hits += current_hits;
1949 * Additionally checking for hits is important because if
1950 * the continue hack is triggered, server headers can
1951 * arrive empty to separate multiple heads from each other.
1953 if ((0 == size) && hits)
1955 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1963 /*********************************************************************
1965 * Function : connection
1967 * Description : Makes sure that the value of the Connection: header
1968 * is "close" and signals connection_close_adder
1972 * 1 : csp = Current client state (buffers, headers, etc...)
1973 * 2 : header = On input, pointer to header to modify.
1974 * On output, pointer to the modified header, or NULL
1975 * to remove the header. This function frees the
1976 * original string if necessary.
1978 * Returns : JB_ERR_OK on success, or
1979 * JB_ERR_MEMORY on out-of-memory error.
1981 *********************************************************************/
1982 static jb_err connection(struct client_state *csp, char **header)
1984 char *old_header = *header;
1986 /* Do we have a 'Connection: close' header? */
1987 if (strcmpic(*header, "Connection: close"))
1989 /* No, create one */
1990 *header = strdup("Connection: close");
1993 return JB_ERR_MEMORY;
1995 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1999 /* Signal connection_close_adder() to return early. */
2000 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2002 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2006 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2013 /*********************************************************************
2015 * Function : crumble
2017 * Description : This is called if a header matches a pattern to "crunch"
2020 * 1 : csp = Current client state (buffers, headers, etc...)
2021 * 2 : header = On input, pointer to header to modify.
2022 * On output, pointer to the modified header, or NULL
2023 * to remove the header. This function frees the
2024 * original string if necessary.
2026 * Returns : JB_ERR_OK on success, or
2027 * JB_ERR_MEMORY on out-of-memory error.
2029 *********************************************************************/
2030 static jb_err crumble(struct client_state *csp, char **header)
2032 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2037 /*********************************************************************
2039 * Function : crunch_server_header
2041 * Description : Crunch server header if it matches a string supplied by the
2042 * user. Called from `sed'.
2045 * 1 : csp = Current client state (buffers, headers, etc...)
2046 * 2 : header = On input, pointer to header to modify.
2047 * On output, pointer to the modified header, or NULL
2048 * to remove the header. This function frees the
2049 * original string if necessary.
2051 * Returns : JB_ERR_OK on success and always succeeds
2053 *********************************************************************/
2054 static jb_err crunch_server_header(struct client_state *csp, char **header)
2056 const char *crunch_pattern;
2058 /* Do we feel like crunching? */
2059 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2061 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2063 /* Is the current header the lucky one? */
2064 if (strstr(*header, crunch_pattern))
2066 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2075 /*********************************************************************
2077 * Function : server_content_type
2079 * Description : Set the content-type for filterable types (text/.*,
2080 * .*xml.*, javascript and image/gif) unless filtering has been
2081 * forbidden (CT_TABOO) while parsing earlier headers.
2082 * NOTE: Since text/plain is commonly used by web servers
2083 * for files whose correct type is unknown, we don't
2084 * set CT_TEXT for it.
2087 * 1 : csp = Current client state (buffers, headers, etc...)
2088 * 2 : header = On input, pointer to header to modify.
2089 * On output, pointer to the modified header, or NULL
2090 * to remove the header. This function frees the
2091 * original string if necessary.
2093 * Returns : JB_ERR_OK on success, or
2094 * JB_ERR_MEMORY on out-of-memory error.
2096 *********************************************************************/
2097 static jb_err server_content_type(struct client_state *csp, char **header)
2099 /* Remove header if it isn't the first Content-Type header */
2100 if ((csp->content_type & CT_DECLARED))
2103 * Another, slightly slower, way to see if
2104 * we already parsed another Content-Type header.
2106 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2108 log_error(LOG_LEVEL_ERROR,
2109 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2117 * Signal that the Content-Type has been set.
2119 csp->content_type |= CT_DECLARED;
2121 if (!(csp->content_type & CT_TABOO))
2123 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2124 || strstr(*header, "xml")
2125 || strstr(*header, "application/x-javascript"))
2127 csp->content_type |= CT_TEXT;
2129 else if (strstr(*header, " image/gif"))
2131 csp->content_type |= CT_GIF;
2133 else if (strstr(*header, " image/jpeg"))
2135 csp->content_type |= CT_JPEG;
2140 * Are we messing with the content type?
2142 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2145 * Make sure the user doesn't accidently
2146 * change the content type of binary documents.
2148 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2151 *header = strdup("Content-Type: ");
2152 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2156 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2157 return JB_ERR_MEMORY;
2159 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2163 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2164 "Enable force-text-mode if you know what you're doing.", *header);
2172 /*********************************************************************
2174 * Function : server_transfer_coding
2176 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2177 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2178 * - Remove header if body was chunked but has been
2179 * de-chunked for filtering.
2182 * 1 : csp = Current client state (buffers, headers, etc...)
2183 * 2 : header = On input, pointer to header to modify.
2184 * On output, pointer to the modified header, or NULL
2185 * to remove the header. This function frees the
2186 * original string if necessary.
2188 * Returns : JB_ERR_OK on success, or
2189 * JB_ERR_MEMORY on out-of-memory error.
2191 *********************************************************************/
2192 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2195 * Turn off pcrs and gif filtering if body compressed
2197 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2201 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2203 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2204 csp->http->cmd, *header);
2205 #endif /* def FEATURE_ZLIB */
2206 csp->content_type = CT_TABOO;
2210 * Raise flag if body chunked
2212 if (strstr(*header, "chunked"))
2214 csp->flags |= CSP_FLAG_CHUNKED;
2217 * If the body was modified, it has been de-chunked first
2218 * and the header must be removed.
2220 * FIXME: If there is more than one transfer encoding,
2221 * only the "chunked" part should be removed here.
2223 if (csp->flags & CSP_FLAG_MODIFIED)
2225 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2234 /*********************************************************************
2236 * Function : server_content_encoding
2238 * Description : This function is run twice for each request,
2239 * unless FEATURE_ZLIB and filtering are disabled.
2241 * The first run is used to check if the content
2242 * is compressed, if FEATURE_ZLIB is disabled
2243 * filtering is then disabled as well, if FEATURE_ZLIB
2244 * is enabled the content is marked for decompression.
2246 * The second run is used to remove the Content-Encoding
2247 * header if the decompression was successful.
2250 * 1 : csp = Current client state (buffers, headers, etc...)
2251 * 2 : header = On input, pointer to header to modify.
2252 * On output, pointer to the modified header, or NULL
2253 * to remove the header. This function frees the
2254 * original string if necessary.
2256 * Returns : JB_ERR_OK on success, or
2257 * JB_ERR_MEMORY on out-of-memory error.
2259 *********************************************************************/
2260 static jb_err server_content_encoding(struct client_state *csp, char **header)
2263 if ((csp->flags & CSP_FLAG_MODIFIED)
2264 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2267 * We successfully decompressed the content,
2268 * and have to clean the header now, so the
2269 * client no longer expects compressed data..
2271 * XXX: There is a difference between cleaning
2272 * and removing it completely.
2274 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2277 else if (strstr(*header, "gzip"))
2279 /* Mark for gzip decompression */
2280 csp->content_type |= CT_GZIP;
2282 else if (strstr(*header, "deflate"))
2284 /* Mark for zlib decompression */
2285 csp->content_type |= CT_DEFLATE;
2287 else if (strstr(*header, "compress"))
2290 * We can't decompress this; therefore we can't filter
2293 csp->content_type |= CT_TABOO;
2295 #else /* !defined(FEATURE_ZLIB) */
2296 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2299 * Body is compressed, turn off pcrs and gif filtering.
2301 csp->content_type |= CT_TABOO;
2304 * Log a warning if the user expects the content to be filtered.
2306 if ((csp->rlist != NULL) &&
2307 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2309 log_error(LOG_LEVEL_INFO,
2310 "Compressed content detected, content filtering disabled. "
2311 "Consider recompiling Privoxy with zlib support or "
2312 "enable the prevent-compression action.");
2315 #endif /* defined(FEATURE_ZLIB) */
2322 /*********************************************************************
2324 * Function : server_content_length
2326 * Description : Adjust Content-Length header if we modified
2330 * 1 : csp = Current client state (buffers, headers, etc...)
2331 * 2 : header = On input, pointer to header to modify.
2332 * On output, pointer to the modified header, or NULL
2333 * to remove the header. This function frees the
2334 * original string if necessary.
2336 * Returns : JB_ERR_OK on success, or
2337 * JB_ERR_MEMORY on out-of-memory error.
2339 *********************************************************************/
2340 static jb_err server_content_length(struct client_state *csp, char **header)
2342 const size_t max_header_length = 80;
2344 /* Regenerate header if the content was modified. */
2345 if (csp->flags & CSP_FLAG_MODIFIED)
2348 *header = (char *) zalloc(max_header_length);
2349 if (*header == NULL)
2351 return JB_ERR_MEMORY;
2354 snprintf(*header, max_header_length, "Content-Length: %d",
2355 (int)csp->content_length);
2356 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2357 (int)csp->content_length);
2364 /*********************************************************************
2366 * Function : server_content_md5
2368 * Description : Crumble any Content-MD5 headers if the document was
2369 * modified. FIXME: Should we re-compute instead?
2372 * 1 : csp = Current client state (buffers, headers, etc...)
2373 * 2 : header = On input, pointer to header to modify.
2374 * On output, pointer to the modified header, or NULL
2375 * to remove the header. This function frees the
2376 * original string if necessary.
2378 * Returns : JB_ERR_OK on success, or
2379 * JB_ERR_MEMORY on out-of-memory error.
2381 *********************************************************************/
2382 static jb_err server_content_md5(struct client_state *csp, char **header)
2384 if (csp->flags & CSP_FLAG_MODIFIED)
2386 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2393 /*********************************************************************
2395 * Function : server_content_disposition
2397 * Description : If enabled, blocks or modifies the "content-disposition" header.
2398 * Called from `sed'.
2401 * 1 : csp = Current client state (buffers, headers, etc...)
2402 * 2 : header = On input, pointer to header to modify.
2403 * On output, pointer to the modified header, or NULL
2404 * to remove the header. This function frees the
2405 * original string if necessary.
2407 * Returns : JB_ERR_OK on success, or
2408 * JB_ERR_MEMORY on out-of-memory error.
2410 *********************************************************************/
2411 static jb_err server_content_disposition(struct client_state *csp, char **header)
2416 * Are we messing with the content-disposition header?
2418 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2424 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2426 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2429 * Blocking content-disposition header
2431 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2438 * Replacing content-disposition header
2441 *header = strdup("content-disposition: ");
2442 string_append(header, newval);
2444 if (*header == NULL)
2446 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2450 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2453 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2456 /*********************************************************************
2458 * Function : server_last_modified
2460 * Description : Changes Last-Modified header to the actual date
2461 * to help hide-if-modified-since.
2462 * Called from `sed'.
2465 * 1 : csp = Current client state (buffers, headers, etc...)
2466 * 2 : header = On input, pointer to header to modify.
2467 * On output, pointer to the modified header, or NULL
2468 * to remove the header. This function frees the
2469 * original string if necessary.
2471 * Returns : JB_ERR_OK on success, or
2472 * JB_ERR_MEMORY on out-of-memory error.
2474 *********************************************************************/
2475 static jb_err server_last_modified(struct client_state *csp, char **header)
2478 char buf[BUFFER_SIZE];
2481 #ifdef HAVE_GMTIME_R
2484 struct tm *timeptr = NULL;
2485 time_t now, last_modified;
2487 long int days, hours, minutes, seconds;
2490 * Are we messing with the Last-Modified header?
2492 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2498 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2500 if (0 == strcmpic(newval, "block") )
2503 * Blocking Last-Modified header. Useless but why not.
2505 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2509 else if (0 == strcmpic(newval, "reset-to-request-time"))
2512 * Setting Last-Modified Header to now.
2514 get_http_time(0, buf);
2516 *header = strdup("Last-Modified: ");
2517 string_append(header, buf);
2519 if (*header == NULL)
2521 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2525 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2528 else if (0 == strcmpic(newval, "randomize"))
2530 const char *header_time = *header + sizeof("Last-Modified:");
2532 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2534 #ifdef HAVE_GMTIME_R
2535 timeptr = gmtime_r(&now, &gmt);
2536 #elif FEATURE_PTHREAD
2537 pthread_mutex_lock(&gmtime_mutex);
2538 timeptr = gmtime(&now);
2539 pthread_mutex_unlock(&gmtime_mutex);
2541 timeptr = gmtime(&now);
2543 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2545 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2550 rtime = (long int)difftime(now, last_modified);
2553 rtime = pick_from_range(rtime);
2554 last_modified += rtime;
2555 #ifdef HAVE_GMTIME_R
2556 timeptr = gmtime_r(&last_modified, &gmt);
2557 #elif FEATURE_PTHREAD
2558 pthread_mutex_lock(&gmtime_mutex);
2559 timeptr = gmtime(&last_modified);
2560 pthread_mutex_unlock(&gmtime_mutex);
2562 timeptr = gmtime(&last_modified);
2564 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2566 *header = strdup("Last-Modified: ");
2567 string_append(header, newheader);
2569 if (*header == NULL)
2571 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2572 return JB_ERR_MEMORY;
2575 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2577 days = rtime / (3600 * 24);
2578 hours = rtime / 3600 % 24;
2579 minutes = rtime / 60 % 60;
2580 seconds = rtime % 60;
2582 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2583 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2584 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2589 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2598 /*********************************************************************
2600 * Function : client_accept_encoding
2602 * Description : Rewrite the client's Accept-Encoding header so that
2603 * if doesn't allow compression, if the action applies.
2604 * Note: For HTTP/1.0 the absence of the header is enough.
2607 * 1 : csp = Current client state (buffers, headers, etc...)
2608 * 2 : header = On input, pointer to header to modify.
2609 * On output, pointer to the modified header, or NULL
2610 * to remove the header. This function frees the
2611 * original string if necessary.
2613 * Returns : JB_ERR_OK on success, or
2614 * JB_ERR_MEMORY on out-of-memory error.
2616 *********************************************************************/
2617 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2619 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2621 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2625 /* Temporarily disable the correct behaviour to
2626 * work around a PHP bug.
2628 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2630 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2631 * if (*header == NULL)
2633 * return JB_ERR_MEMORY;
2644 /*********************************************************************
2646 * Function : client_te
2648 * Description : Rewrite the client's TE header so that
2649 * if doesn't allow compression, if the action applies.
2652 * 1 : csp = Current client state (buffers, headers, etc...)
2653 * 2 : header = On input, pointer to header to modify.
2654 * On output, pointer to the modified header, or NULL
2655 * to remove the header. This function frees the
2656 * original string if necessary.
2658 * Returns : JB_ERR_OK on success, or
2659 * JB_ERR_MEMORY on out-of-memory error.
2661 *********************************************************************/
2662 static jb_err client_te(struct client_state *csp, char **header)
2664 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2667 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2673 /*********************************************************************
2675 * Function : client_referrer
2677 * Description : Handle the "referer" config setting properly.
2678 * Called from `sed'.
2681 * 1 : csp = Current client state (buffers, headers, etc...)
2682 * 2 : header = On input, pointer to header to modify.
2683 * On output, pointer to the modified header, or NULL
2684 * to remove the header. This function frees the
2685 * original string if necessary.
2687 * Returns : JB_ERR_OK on success, or
2688 * JB_ERR_MEMORY on out-of-memory error.
2690 *********************************************************************/
2691 static jb_err client_referrer(struct client_state *csp, char **header)
2698 #ifdef FEATURE_FORCE_LOAD
2699 /* Since the referrer can include the prefix even
2700 * if the request itself is non-forced, we must
2701 * clean it unconditionally
2703 strclean(*header, FORCE_PREFIX);
2704 #endif /* def FEATURE_FORCE_LOAD */
2707 * Are we sending referer?
2709 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2714 newval = csp->action->string[ACTION_STRING_REFERER];
2716 if ((0 != strcmpic(newval, "conditional-block")))
2720 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2725 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2728 else if (0 == strcmpic(newval, "conditional-block"))
2731 * Block referer if host has changed.
2734 if (NULL == (host = strdup(csp->http->hostport)))
2737 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2738 return JB_ERR_MEMORY;
2740 if (NULL == (referer = strdup(*header)))
2744 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2745 return JB_ERR_MEMORY;
2747 hostlenght = strlen(host);
2748 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2750 /*Shorten referer to make sure the referer is blocked
2751 *if www.example.org/www.example.com-shall-see-the-referer/
2752 *links to www.example.com/
2754 referer[hostlenght+17] = '\0';
2756 if ( 0 == strstr(referer, host)) /*Host has changed*/
2758 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2763 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2769 else if (0 != strcmpic(newval, "forge"))
2772 * We have a specific (fixed) referer we want to send.
2774 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2776 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2778 *header = strdup("Referer: ");
2779 string_append(header, newval);
2780 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2782 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2787 * Forge a referer as http://[hostname:port of REQUEST]/
2788 * to fool stupid checks for in-site links
2791 *header = strdup("Referer: http://");
2792 string_append(header, csp->http->hostport);
2793 string_append(header, "/");
2794 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2796 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2800 /*********************************************************************
2802 * Function : client_accept_language
2804 * Description : Handle the "Accept-Language" config setting properly.
2805 * Called from `sed'.
2808 * 1 : csp = Current client state (buffers, headers, etc...)
2809 * 2 : header = On input, pointer to header to modify.
2810 * On output, pointer to the modified header, or NULL
2811 * to remove the header. This function frees the
2812 * original string if necessary.
2814 * Returns : JB_ERR_OK on success, or
2815 * JB_ERR_MEMORY on out-of-memory error.
2817 *********************************************************************/
2818 static jb_err client_accept_language(struct client_state *csp, char **header)
2823 * Are we messing with the Accept-Language?
2825 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2827 /*I don't think so*/
2831 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2833 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2836 * Blocking Accept-Language header
2838 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2845 * Replacing Accept-Language header
2848 *header = strdup("Accept-Language: ");
2849 string_append(header, newval);
2851 if (*header == NULL)
2853 log_error(LOG_LEVEL_ERROR,
2854 "Insufficent memory. Accept-Language header crunched without replacement.");
2858 log_error(LOG_LEVEL_HEADER,
2859 "Accept-Language header crunched and replaced with: %s", *header);
2862 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2866 /*********************************************************************
2868 * Function : crunch_client_header
2870 * Description : Crunch client header if it matches a string supplied by the
2871 * user. Called from `sed'.
2874 * 1 : csp = Current client state (buffers, headers, etc...)
2875 * 2 : header = On input, pointer to header to modify.
2876 * On output, pointer to the modified header, or NULL
2877 * to remove the header. This function frees the
2878 * original string if necessary.
2880 * Returns : JB_ERR_OK on success and always succeeds
2882 *********************************************************************/
2883 static jb_err crunch_client_header(struct client_state *csp, char **header)
2885 const char *crunch_pattern;
2887 /* Do we feel like crunching? */
2888 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2890 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2892 /* Is the current header the lucky one? */
2893 if (strstr(*header, crunch_pattern))
2895 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2903 /*********************************************************************
2905 * Function : client_uagent
2907 * Description : Handle the "user-agent" config setting properly
2908 * and remember its original value to enable browser
2909 * bug workarounds. Called from `sed'.
2912 * 1 : csp = Current client state (buffers, headers, etc...)
2913 * 2 : header = On input, pointer to header to modify.
2914 * On output, pointer to the modified header, or NULL
2915 * to remove the header. This function frees the
2916 * original string if necessary.
2918 * Returns : JB_ERR_OK on success, or
2919 * JB_ERR_MEMORY on out-of-memory error.
2921 *********************************************************************/
2922 static jb_err client_uagent(struct client_state *csp, char **header)
2926 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2931 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2938 *header = strdup("User-Agent: ");
2939 string_append(header, newval);
2941 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2943 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2946 /*********************************************************************
2948 * Function : client_ua
2950 * Description : Handle "ua-" headers properly. Called from `sed'.
2953 * 1 : csp = Current client state (buffers, headers, etc...)
2954 * 2 : header = On input, pointer to header to modify.
2955 * On output, pointer to the modified header, or NULL
2956 * to remove the header. This function frees the
2957 * original string if necessary.
2959 * Returns : JB_ERR_OK on success, or
2960 * JB_ERR_MEMORY on out-of-memory error.
2962 *********************************************************************/
2963 static jb_err client_ua(struct client_state *csp, char **header)
2965 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2967 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2975 /*********************************************************************
2977 * Function : client_from
2979 * Description : Handle the "from" config setting properly.
2980 * Called from `sed'.
2983 * 1 : csp = Current client state (buffers, headers, etc...)
2984 * 2 : header = On input, pointer to header to modify.
2985 * On output, pointer to the modified header, or NULL
2986 * to remove the header. This function frees the
2987 * original string if necessary.
2989 * Returns : JB_ERR_OK on success, or
2990 * JB_ERR_MEMORY on out-of-memory error.
2992 *********************************************************************/
2993 static jb_err client_from(struct client_state *csp, char **header)
2997 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3004 newval = csp->action->string[ACTION_STRING_FROM];
3007 * Are we blocking the e-mail address?
3009 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3011 log_error(LOG_LEVEL_HEADER, "crunched From!");
3015 log_error(LOG_LEVEL_HEADER, " modified");
3017 *header = strdup("From: ");
3018 string_append(header, newval);
3020 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3024 /*********************************************************************
3026 * Function : client_send_cookie
3028 * Description : Crunches the "cookie" header if necessary.
3029 * Called from `sed'.
3031 * XXX: Stupid name, doesn't send squat.
3034 * 1 : csp = Current client state (buffers, headers, etc...)
3035 * 2 : header = On input, pointer to header to modify.
3036 * On output, pointer to the modified header, or NULL
3037 * to remove the header. This function frees the
3038 * original string if necessary.
3040 * Returns : JB_ERR_OK on success, or
3041 * JB_ERR_MEMORY on out-of-memory error.
3043 *********************************************************************/
3044 static jb_err client_send_cookie(struct client_state *csp, char **header)
3046 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3048 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3056 /*********************************************************************
3058 * Function : client_x_forwarded
3060 * Description : Handle the "x-forwarded-for" config setting properly,
3061 * also used in the add_client_headers list. Called from `sed'.
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_x_forwarded(struct client_state *csp, char **header)
3076 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3078 /* Save it so we can re-add it later */
3079 freez(csp->x_forwarded);
3080 csp->x_forwarded = *header;
3083 * Always set *header = NULL, since this information
3084 * will be sent at the end of the header.
3091 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3098 /*********************************************************************
3100 * Function : client_max_forwards
3102 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3103 * from the value of the Max-Forwards header field.
3106 * 1 : csp = Current client state (buffers, headers, etc...)
3107 * 2 : header = On input, pointer to header to modify.
3108 * On output, pointer to the modified header, or NULL
3109 * to remove the header. This function frees the
3110 * original string if necessary.
3112 * Returns : JB_ERR_OK on success, or
3113 * JB_ERR_MEMORY on out-of-memory error.
3115 *********************************************************************/
3116 static jb_err client_max_forwards(struct client_state *csp, char **header)
3120 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3121 (0 == strcmpic(csp->http->gpc, "options")))
3123 assert(*(*header+12) == ':');
3124 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3126 if (max_forwards > 0)
3128 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3129 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3130 csp->http->gpc, max_forwards);
3132 else if (max_forwards < 0)
3134 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3140 * Not supposed to be reached. direct_response() which
3141 * was already called earlier in chat() should have
3142 * intercepted the request.
3144 log_error(LOG_LEVEL_ERROR,
3145 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3146 assert(max_forwards != 0);
3151 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3160 /*********************************************************************
3162 * Function : client_host
3164 * Description : If the request URI did not contain host and
3165 * port information, parse and evaluate the Host
3168 * Also, kill ill-formed HOST: headers as sent by
3169 * Apple's iTunes software when used with a proxy.
3172 * 1 : csp = Current client state (buffers, headers, etc...)
3173 * 2 : header = On input, pointer to header to modify.
3174 * On output, pointer to the modified header, or NULL
3175 * to remove the header. This function frees the
3176 * original string if necessary.
3178 * Returns : JB_ERR_OK on success, or
3179 * JB_ERR_MEMORY on out-of-memory error.
3181 *********************************************************************/
3182 static jb_err client_host(struct client_state *csp, char **header)
3187 * If the header field name is all upper-case, chances are that it's
3188 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3189 * not a problem -- they are regenerated later.
3191 if ((*header)[1] == 'O')
3193 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3198 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3199 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3202 if (NULL == (p = strdup((*header)+6)))
3204 return JB_ERR_MEMORY;
3207 if (NULL == (q = strdup(p)))
3210 return JB_ERR_MEMORY;
3213 freez(csp->http->hostport);
3214 csp->http->hostport = p;
3215 freez(csp->http->host);
3216 csp->http->host = q;
3217 q = strchr(csp->http->host, ':');
3220 /* Terminate hostname and evaluate port string */
3222 csp->http->port = atoi(q);
3226 csp->http->port = csp->http->ssl ? 443 : 80;
3229 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3230 csp->http->hostport, csp->http->host, csp->http->port);
3233 /* Signal client_host_adder() to return right away */
3234 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3239 /*********************************************************************
3241 * Function : client_if_modified_since
3243 * Description : Remove or modify the If-Modified-Since header.
3246 * 1 : csp = Current client state (buffers, headers, etc...)
3247 * 2 : header = On input, pointer to header to modify.
3248 * On output, pointer to the modified header, or NULL
3249 * to remove the header. This function frees the
3250 * original string if necessary.
3252 * Returns : JB_ERR_OK on success, or
3253 * JB_ERR_MEMORY on out-of-memory error.
3255 *********************************************************************/
3256 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3259 #ifdef HAVE_GMTIME_R
3262 struct tm *timeptr = NULL;
3266 long int hours, minutes, seconds;
3270 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3273 * The client got an error message because of a temporary problem,
3274 * the problem is gone and the client now tries to revalidate our
3275 * error message on the real server. The revalidation would always
3276 * end with the transmission of the whole document and there is
3277 * no need to expose the bogus If-Modified-Since header.
3279 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3282 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3284 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3286 if ((0 == strcmpic(newval, "block")))
3288 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3291 else /* add random value */
3293 const char *header_time = *header + sizeof("If-Modified-Since:");
3295 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3297 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3302 rtime = strtol(newval, &endptr, 0);
3305 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3306 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3313 rtime = pick_from_range(rtime);
3317 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3320 tm += rtime * (negative ? -1 : 1);
3321 #ifdef HAVE_GMTIME_R
3322 timeptr = gmtime_r(&tm, &gmt);
3323 #elif FEATURE_PTHREAD
3324 pthread_mutex_lock(&gmtime_mutex);
3325 timeptr = gmtime(&tm);
3326 pthread_mutex_unlock(&gmtime_mutex);
3328 timeptr = gmtime(&tm);
3330 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3333 *header = strdup("If-Modified-Since: ");
3334 string_append(header, newheader);
3336 if (*header == NULL)
3338 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3339 return JB_ERR_MEMORY;
3342 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3344 hours = rtime / 3600;
3345 minutes = rtime / 60 % 60;
3346 seconds = rtime % 60;
3348 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3349 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3350 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3359 /*********************************************************************
3361 * Function : client_if_none_match
3363 * Description : Remove the If-None-Match header.
3366 * 1 : csp = Current client state (buffers, headers, etc...)
3367 * 2 : header = On input, pointer to header to modify.
3368 * On output, pointer to the modified header, or NULL
3369 * to remove the header. This function frees the
3370 * original string if necessary.
3372 * Returns : JB_ERR_OK on success, or
3373 * JB_ERR_MEMORY on out-of-memory error.
3375 *********************************************************************/
3376 static jb_err client_if_none_match(struct client_state *csp, char **header)
3378 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3380 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3387 /*********************************************************************
3389 * Function : client_x_filter
3391 * Description : Disables filtering if the client set "X-Filter: No".
3392 * Called from `sed'.
3395 * 1 : csp = Current client state (buffers, headers, etc...)
3396 * 2 : header = On input, pointer to header to modify.
3397 * On output, pointer to the modified header, or NULL
3398 * to remove the header. This function frees the
3399 * original string if necessary.
3401 * Returns : JB_ERR_OK on success
3403 *********************************************************************/
3404 jb_err client_x_filter(struct client_state *csp, char **header)
3406 if ( 0 == strcmpic(*header, "X-Filter: No"))
3408 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3410 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3414 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3416 log_error(LOG_LEVEL_HEADER,
3417 "force-text-mode overruled the client's request to fetch without filtering!");
3421 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3422 csp->flags |= CSP_FLAG_NO_FILTERING;
3423 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3425 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3432 /* the following functions add headers directly to the header list */
3434 /*********************************************************************
3436 * Function : client_host_adder
3438 * Description : Adds the Host: header field if it is missing.
3439 * Called from `sed'.
3442 * 1 : csp = Current client state (buffers, headers, etc...)
3444 * Returns : JB_ERR_OK on success, or
3445 * JB_ERR_MEMORY on out-of-memory error.
3447 *********************************************************************/
3448 static jb_err client_host_adder(struct client_state *csp)
3453 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3455 /* Header already set by the client, nothing to do. */
3459 if ( !csp->http->hostport || !*(csp->http->hostport))
3461 /* XXX: When does this happen and why is it OK? */
3462 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3467 * remove 'user:pass@' from 'proto://user:pass@host'
3469 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3475 p = csp->http->hostport;
3478 /* XXX: Just add it, we already made sure that it will be unique */
3479 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3480 err = enlist_unique_header(csp->headers, "Host", p);
3486 /*********************************************************************
3488 * Function : client_cookie_adder
3490 * Description : Used in the add_client_headers list to add "wafers".
3491 * Called from `sed'.
3494 * 1 : csp = Current client state (buffers, headers, etc...)
3496 * Returns : JB_ERR_OK on success, or
3497 * JB_ERR_MEMORY on out-of-memory error.
3499 *********************************************************************/
3500 jb_err client_cookie_adder(struct client_state *csp)
3503 struct list_entry *wafer;
3504 struct list_entry *wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3507 if (NULL == wafer_list)
3513 tmp = strdup("Cookie: ");
3515 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3517 if (wafer != wafer_list)
3519 /* As this isn't the first wafer, we need a delimiter. */
3520 string_append(&tmp, "; ");
3522 string_join(&tmp, cookie_encode(wafer->str));
3527 return JB_ERR_MEMORY;
3530 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3531 err = enlist(csp->headers, tmp);
3537 /*********************************************************************
3539 * Function : client_accept_encoding_adder
3541 * Description : Add an Accept-Encoding header to the client's request
3542 * that disables compression if the action applies, and
3543 * the header is not already there. Called from `sed'.
3544 * Note: For HTTP/1.0, the absence of the header is enough.
3547 * 1 : csp = Current client state (buffers, headers, etc...)
3549 * Returns : JB_ERR_OK on success, or
3550 * JB_ERR_MEMORY on out-of-memory error.
3552 *********************************************************************/
3553 static jb_err client_accept_encoding_adder(struct client_state *csp)
3555 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3556 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3558 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3565 /*********************************************************************
3567 * Function : client_xtra_adder
3569 * Description : Used in the add_client_headers list. Called from `sed'.
3572 * 1 : csp = Current client state (buffers, headers, etc...)
3574 * Returns : JB_ERR_OK on success, or
3575 * JB_ERR_MEMORY on out-of-memory error.
3577 *********************************************************************/
3578 static jb_err client_xtra_adder(struct client_state *csp)
3580 struct list_entry *lst;
3583 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3584 lst ; lst = lst->next)
3586 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3587 err = enlist(csp->headers, lst->str);
3599 /*********************************************************************
3601 * Function : client_x_forwarded_adder
3603 * Description : Used in the add_client_headers list. Called from `sed'.
3606 * 1 : csp = Current client state (buffers, headers, etc...)
3608 * Returns : JB_ERR_OK on success, or
3609 * JB_ERR_MEMORY on out-of-memory error.
3611 *********************************************************************/
3612 static jb_err client_x_forwarded_adder(struct client_state *csp)
3617 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3622 if (csp->x_forwarded)
3624 p = strdup(csp->x_forwarded);
3625 string_append(&p, ", ");
3629 p = strdup("X-Forwarded-For: ");
3631 string_append(&p, csp->ip_addr_str);
3635 return JB_ERR_MEMORY;
3638 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3639 err = enlist(csp->headers, p);
3646 /*********************************************************************
3648 * Function : connection_close_adder
3650 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3651 * support. Adds a "Connection: close" header to csp->headers
3652 * unless the header was already present. Called from `sed'.
3654 * FIXME: This whole function shouldn't be neccessary!
3657 * 1 : csp = Current client state (buffers, headers, etc...)
3659 * Returns : JB_ERR_OK on success, or
3660 * JB_ERR_MEMORY on out-of-memory error.
3662 *********************************************************************/
3663 static jb_err connection_close_adder(struct client_state *csp)
3665 const unsigned int flags = csp->flags;
3668 * Return right away if
3670 * - we're parsing server headers and the server header
3671 * "Connection: close" is already set, or if
3673 * - we're parsing client headers and the client header
3674 * "Connection: close" is already set.
3676 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3677 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3678 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3679 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3684 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3686 return enlist(csp->headers, "Connection: close");
3690 /*********************************************************************
3692 * Function : server_http
3694 * Description : - Save the HTTP Status into csp->http->status
3695 * - Set CT_TABOO to prevent filtering if the answer
3696 * is a partial range (HTTP status 206)
3697 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3701 * 1 : csp = Current client state (buffers, headers, etc...)
3702 * 2 : header = On input, pointer to header to modify.
3703 * On output, pointer to the modified header, or NULL
3704 * to remove the header. This function frees the
3705 * original string if necessary.
3707 * Returns : JB_ERR_OK on success, or
3708 * JB_ERR_MEMORY on out-of-memory error.
3710 *********************************************************************/
3711 static jb_err server_http(struct client_state *csp, char **header)
3713 /* XXX: Doesn't belong here. */
3714 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3715 if (csp->http->status == 206)
3717 csp->content_type = CT_TABOO;
3720 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3722 /* XXX: Should we do a real validity check here? */
3723 if (strlen(*header) > 8)
3726 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3731 * XXX: Should we block the request or
3732 * enlist a valid status code line here?
3734 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3735 "Downgrading to HTTP/1.0 impossible.");
3743 /*********************************************************************
3745 * Function : server_set_cookie
3747 * Description : Handle the server "cookie" header properly.
3748 * Log cookie to the jar file. Then "crunch",
3749 * accept or rewrite it to a session cookie.
3750 * Called from `sed'.
3752 * TODO: Allow the user to specify a new expiration
3753 * time to cause the cookie to expire even before the
3754 * browser is closed.
3757 * 1 : csp = Current client state (buffers, headers, etc...)
3758 * 2 : header = On input, pointer to header to modify.
3759 * On output, pointer to the modified header, or NULL
3760 * to remove the header. This function frees the
3761 * original string if necessary.
3763 * Returns : JB_ERR_OK on success, or
3764 * JB_ERR_MEMORY on out-of-memory error.
3766 *********************************************************************/
3767 static jb_err server_set_cookie(struct client_state *csp, char **header)
3774 #ifdef FEATURE_COOKIE_JAR
3775 if (csp->config->jar)
3778 * Write timestamp into outbuf.
3780 * Complex because not all OSs have tm_gmtoff or
3781 * the %z field in strftime()
3783 char tempbuf[ BUFFER_SIZE ];
3785 #ifdef HAVE_LOCALTIME_R
3786 tm_now = *localtime_r(&now, &tm_now);
3787 #elif FEATURE_PTHREAD
3788 pthread_mutex_lock(&localtime_mutex);
3789 tm_now = *localtime (&now);
3790 pthread_mutex_unlock(&localtime_mutex);
3792 tm_now = *localtime (&now);
3794 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3796 /* strlen("set-cookie: ") = 12 */
3797 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3799 #endif /* def FEATURE_COOKIE_JAR */
3801 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3803 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3806 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3808 /* Flag whether or not to log a message */
3811 /* A variable to store the tag we're working on */
3814 /* Skip "Set-Cookie:" (11 characters) in header */
3815 cur_tag = *header + 11;
3817 /* skip whitespace between "Set-Cookie:" and value */
3818 while (*cur_tag && ijb_isspace(*cur_tag))
3823 /* Loop through each tag in the cookie */
3827 char *next_tag = strchr(cur_tag, ';');
3828 if (next_tag != NULL)
3830 /* Skip the ';' character itself */
3833 /* skip whitespace ";" and start of tag */
3834 while (*next_tag && ijb_isspace(*next_tag))
3841 /* "Next tag" is the end of the string */
3842 next_tag = cur_tag + strlen(cur_tag);
3846 * Check the expiration date to see
3847 * if the cookie is still valid, if yes,
3848 * rewrite it to a session cookie.
3850 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3852 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3854 /* Did we detect the date properly? */
3855 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3858 * Nope, treat it as if it was still valid.
3860 * XXX: Should we remove the whole cookie instead?
3862 log_error(LOG_LEVEL_ERROR,
3863 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3864 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3870 * Yes. Check if the cookie is still valid.
3872 * If the cookie is already expired it's probably
3873 * a delete cookie and even if it isn't, the browser
3874 * will discard it anyway.
3878 * XXX: timegm() isn't available on some AmigaOS
3879 * versions and our replacement doesn't work.
3881 * Our options are to either:
3883 * - disable session-cookies-only completely if timegm
3886 * - to simply remove all expired tags, like it has
3887 * been done until Privoxy 3.0.6 and to live with
3888 * the consequence that it can cause login/logout
3889 * problems on servers that don't validate their
3890 * input properly, or
3892 * - to replace it with mktime in which
3893 * case there is a slight chance of valid cookies
3894 * passing as already expired.
3896 * This is the way it's currently done and it's not
3897 * as bad as it sounds. If the missing GMT offset is
3898 * enough to change the result of the expiration check
3899 * the cookie will be only valid for a few hours
3900 * anyway, which in many cases will be shorter
3901 * than a browser session.
3903 if (cookie_time - now < 0)
3905 log_error(LOG_LEVEL_HEADER,
3906 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3907 /* Just in case some clown sets more then one expiration date */
3913 * Still valid, delete expiration date by copying
3914 * the rest of the string over it.
3916 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3917 * since the behaviour of strcpy is undefined for overlapping
3920 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3922 /* That changed the header, need to issue a log message */
3926 * Note that the next tag has now been moved to *cur_tag,
3927 * so we do not need to update the cur_tag pointer.
3935 /* Move on to next cookie tag */
3942 assert(NULL != *header);
3943 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3952 #ifdef FEATURE_FORCE_LOAD
3953 /*********************************************************************
3955 * Function : strclean
3957 * Description : In-Situ-Eliminate all occurances of substring in
3961 * 1 : string = string to clean
3962 * 2 : substring = substring to eliminate
3964 * Returns : Number of eliminations
3966 *********************************************************************/
3967 int strclean(const char *string, const char *substring)
3973 len = strlen(substring);
3975 while((pos = strstr(string, substring)) != NULL)
3982 while (*p++ != '\0');
3989 #endif /* def FEATURE_FORCE_LOAD */
3991 /*********************************************************************
3993 * Function : parse_header_time
3995 * Description : Parses time formats used in HTTP header strings
3996 * to get the numerical respresentation.
3999 * 1 : header_time = HTTP header time as string.
4000 * 2 : result = storage for header_time in seconds
4002 * Returns : JB_ERR_OK if the time format was recognized, or
4003 * JB_ERR_PARSE otherwise.
4005 *********************************************************************/
4006 static jb_err parse_header_time(const char *header_time, time_t *result)
4011 * Zero out gmt to prevent time zone offsets.
4013 * While this is only necessary on some platforms
4014 * (mingw32 for example), I don't know how to
4015 * detect these automatically and doing it everywhere
4018 memset(&gmt, 0, sizeof(gmt));
4020 /* Tue, 02 Jun 2037 20:00:00 */
4021 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4022 /* Tue, 02-Jun-2037 20:00:00 */
4023 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4024 /* Tue, 02-Jun-37 20:00:00 */
4025 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4026 /* Tuesday, 02-Jun-2037 20:00:00 */
4027 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4028 /* Tuesday Jun 02 20:00:00 2037 */
4029 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4031 return JB_ERR_PARSE;
4034 *result = timegm(&gmt);
4040 /*********************************************************************
4042 * Function : get_destination_from_headers
4044 * Description : Parse the "Host:" header to get the request's destination.
4045 * Only needed if the client's request was forcefully
4046 * redirected into Privoxy.
4048 * Code mainly copied from client_host() which is currently
4049 * run too late for this purpose.
4052 * 1 : headers = List of headers (one of them hopefully being
4053 * the "Host:" header)
4054 * 2 : http = storage for the result (host, port and hostport).
4056 * Returns : JB_ERR_MEMORY in case of memory problems,
4057 * JB_ERR_PARSE if the host header couldn't be found,
4058 * JB_ERR_OK otherwise.
4060 *********************************************************************/
4061 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4067 host = get_header_value(headers, "Host:");
4071 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4072 return JB_ERR_PARSE;
4075 if (NULL == (p = strdup((host))))
4077 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4078 return JB_ERR_MEMORY;
4081 if (NULL == (q = strdup(p)))
4084 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4085 return JB_ERR_MEMORY;
4088 freez(http->hostport);
4092 q = strchr(http->host, ':');
4095 /* Terminate hostname and evaluate port string */
4097 http->port = atoi(q);
4101 http->port = http->ssl ? 443 : 80;
4104 /* Rebuild request URL */
4106 http->url = strdup(http->ssl ? "https://" : "http://");
4107 string_append(&http->url, http->hostport);
4108 string_append(&http->url, http->path);
4109 if (http->url == NULL)
4111 return JB_ERR_MEMORY;
4114 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",