1 const char parsers_rcs[] = "$Id: parsers.c,v 1.101 2007/05/14 10:16:41 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.101 2007/05/14 10:16:41 fabiankeil
48 * Streamline client_cookie_adder().
50 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
51 * Make sure filters with dynamic jobs actually use them.
53 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
54 * - Introduce dynamic pcrs jobs that can resolve variables.
55 * - Remove unnecessary update_action_bits_for_all_tags() call.
57 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
58 * - Make tagging based on tags set by earlier taggers
59 * of the same kind possible.
60 * - Log whether or not new tags cause action bits updates
61 * (in which case a matching tag-pattern section exists).
62 * - Log if the user tries to set a tag that is already set.
64 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
65 * Introduce tags as alternative way to specify which
66 * actions apply to a request. At the moment tags can be
67 * created based on client and server headers.
69 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
70 * Log a warning if the content is compressed, filtering is
71 * enabled and Privoxy was compiled without zlib support.
74 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
75 * - Fix warnings when compiled with glibc.
76 * - Don't use crumble() for cookie crunching.
77 * - Move cookie time parsing into parse_header_time().
78 * - Let parse_header_time() return a jb_err code
79 * instead of a pointer that can only be used to
80 * check for NULL anyway.
82 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
83 * - Add better protection against malicious gzip headers.
84 * - Stop logging the first hundred bytes of decompressed content.
85 * It looks like it's working and there is always debug 16.
86 * - Log the content size after decompression in decompress_iob()
87 * instead of pcrs_filter_response().
89 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
90 * - Use dedicated header filter actions instead of abusing "filter".
91 * Replace "filter-client-headers" and "filter-client-headers"
92 * with "server-header-filter" and "client-header-filter".
93 * - Remove filter_client_header() and filter_client_header(),
94 * filter_header() now checks the shiny new
95 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
97 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
98 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
99 * - Handle "Cookie:" and "Connection:" headers a bit smarter
100 * (don't crunch them just to recreate them later on).
101 * - Add another non-standard time format for the cookie
102 * expiration date detection.
103 * - Fix a valgrind warning.
105 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
106 * Improve cookie expiration date detection.
108 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
109 * Don't run server_content_length() the first time
110 * sed() parses server headers; only adjust the
111 * Content-Length header if the page was modified.
113 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
114 * Fix log messages regarding the cookie time format
115 * (cookie and request URL were mixed up).
117 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
118 * - Let decompress_iob()
119 * - not corrupt the content if decompression fails
120 * early. (the first byte(s) were lost).
121 * - use pointer arithmetics with defined outcome for
123 * - Use a different kludge to remember a failed decompression.
125 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
126 * Search for Max-Forwards headers case-insensitive,
127 * don't generate the "501 unsupported" message for invalid
128 * Max-Forwards values and don't increase negative ones.
130 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
131 * - Let server_set_cookie() check the expiration date
132 * of cookies and don't touch the ones that are already
133 * expired. Fixes problems with low quality web applications
134 * as described in BR 932612.
136 * - Adjust comment in client_max_forwards to reality;
137 * remove invalid Max-Forwards headers.
139 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
140 * Stop filter_header() from unintentionally removing
141 * empty header lines that were enlisted by the continue
144 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
145 * - Repeat the request URL before logging any headers.
146 * Makes reading the log easier in case of simultaneous requests.
147 * - If there are more than one Content-Type headers in one request,
148 * use the first one and remove the others.
149 * - Remove "newval" variable in server_content_type().
150 * It's only used once.
152 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
153 * Correct a cast, check inflateEnd() exit code
154 * to see if we have to, replace sprintf calls
157 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
158 * Integrate a modified version of Wil Mahan's
159 * zlib patch (PR #895531).
161 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
162 * Skip empty filter files in filter_header()
163 * but don't ignore the ones that come afterwards.
164 * Fixes BR 1619208, this time for real.
166 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
167 * Reverted parts of my last commit
168 * to keep error handling working.
170 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
171 * Fixed gcc43 conversion warnings.
173 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
174 * Bringing back the "useless" localtime() call
175 * I removed in revision 1.67. On some platforms
176 * it's necessary to prevent time zone offsets.
178 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
179 * Rebuild request URL in get_destination_from_headers()
180 * to make sure redirect{pcrs command} works as expected
181 * for intercepted requests.
183 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
184 * Added get_destination_from_headers().
186 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
187 * Make pthread mutex locking more generic. Instead of
188 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
189 * and use mutex locking unless there is an _r function
190 * available. Better safe than sorry.
192 * Fixes "./configure --disable-pthread" and should result
193 * in less threading-related problems on pthread-using platforms,
194 * but it still doesn't fix BR#1122404.
196 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
197 * The special header "X-Filter: No" now disables
198 * header filtering as well.
200 * Revision 1.73 2006/09/23 13:26:38 roro
201 * Replace TABs by spaces in source code.
203 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
204 * Don't print a log message every time filter_headers is
205 * entered or left. It only creates noise without any real
208 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
209 * Fix +hide-if-modified-since{-n}.
211 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
212 * Have hide-if-modified-since interpret the random
213 * range value as minutes instead of hours. Allows
214 * more fine-grained configuration.
216 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
217 * Always have parse_header_time return a pointer
218 * that actual makes sense, even though we currently
219 * only need it to detect problems.
221 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
222 * Added config option enable-remote-http-toggle
223 * to specify if Privoxy should recognize special
224 * headers (currently only X-Filter) to change its
225 * behaviour. Disabled by default.
227 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
228 * After filtering de-chunked instances, remove
229 * "Transfer-Encoding" header entirely instead of changing
230 * it to "Transfer-Encoding: identity", which is invalid.
231 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
233 * Don't use localtime in parse_header_time. An empty time struct
234 * is good enough, it gets overwritten by strptime anyway.
236 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
237 * Use gmtime_r if available, fallback to gmtime with mutex
238 * protection for MacOSX and use vanilla gmtime for the rest.
240 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
241 * Changed client_referrer to use the right type (size_t) for
242 * hostlenght and to shorten the temporary referrer string with
243 * '\0' instead of adding a useless line break.
245 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
246 * - Back to timegm() using GnuPG's replacement if necessary.
247 * Using mktime() and localtime() could add a on hour offset if
248 * the randomize factor was big enough to lead to a summer/wintertime
251 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
253 * - Moved randomization code into pick_from_range().
255 * - Changed parse_header_time definition.
256 * time_t isn't guaranteed to be signed and
257 * if it isn't, -1 isn't available as error code.
258 * Changed some variable types in client_if_modified_since()
259 * because of the same reason.
261 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
262 * OS/2 compilation compatibility fixups
264 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
265 * Changed include from strptime.c to strptime.h
267 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
268 * Split filter-headers{} into filter-client-headers{}
269 * and filter-server-headers{}.
270 * Added parse_header_time() to share some code.
271 * Replaced timegm() with mktime().
273 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
274 * Windows service integration
276 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
277 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
279 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
280 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
281 * with what was really the latest development (the v_3_0_branch branch)
283 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
284 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
286 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
287 * Add the ability to check jpeg images for invalid
288 * lengths of comment blocks. Defensive strategy
289 * against the exploit:
290 * Microsoft Security Bulletin MS04-028
291 * Buffer Overrun in JPEG Processing (GDI+) Could
292 * Allow Code Execution (833987)
293 * Enabled with +inspect-jpegs in actions files.
295 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
296 * Excluded text/plain objects from filtering. This fixes a
297 * couple of client-crashing, download corruption and
298 * Privoxy performance issues, whose root cause lies in
299 * web servers labelling content of unknown type as text/plain.
301 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
302 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
304 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
305 * Completing the previous change
307 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
308 * Added temporary workaround for bug in PHP < 4.2.3
310 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
311 * 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.
313 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
314 * Fix typo: supressed -> suppressed
316 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
317 * Improved cookie logging
319 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
320 * Added basic support for OPTIONS and TRACE HTTP methods:
321 * - New parser function client_max_forwards which decrements
322 * the Max-Forwards HTTP header field of OPTIONS and TRACE
323 * requests by one before forwarding
324 * - New parser function client_host which extracts the host
325 * and port information from the HTTP header field if the
326 * request URI was not absolute
327 * - Don't crumble and re-add the Host: header, but only generate
328 * and append if missing
330 * Revision 1.56 2002/05/12 15:34:22 jongfoster
331 * Fixing typo in a comment
333 * Revision 1.55 2002/05/08 16:01:07 oes
334 * Optimized add_to_iob:
335 * - Use realloc instead of malloc(), memcpy(), free()
336 * - Expand to powers of two if possible, to get
337 * O(log n) reallocs instead of O(n).
338 * - Moved check for buffer limit here from chat
339 * - Report failure via returncode
341 * Revision 1.54 2002/04/02 15:03:16 oes
342 * Tiny code cosmetics
344 * Revision 1.53 2002/03/26 22:29:55 swa
345 * we have a new homepage!
347 * Revision 1.52 2002/03/24 13:25:43 swa
348 * name change related issues
350 * Revision 1.51 2002/03/13 00:27:05 jongfoster
353 * Revision 1.50 2002/03/12 01:45:35 oes
354 * More verbose logging
356 * Revision 1.49 2002/03/09 20:03:52 jongfoster
357 * - Making various functions return int rather than size_t.
358 * (Undoing a recent change). Since size_t is unsigned on
359 * Windows, functions like read_socket that return -1 on
360 * error cannot return a size_t.
362 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
363 * crashes, and also frequently caused JB to jump to 100%
364 * CPU and stay there. (Because it thought it had just
365 * read ((unsigned)-1) == 4Gb of data...)
367 * - The signature of write_socket has changed, it now simply
368 * returns success=0/failure=nonzero.
370 * - Trying to get rid of a few warnings --with-debug on
371 * Windows, I've introduced a new type "jb_socket". This is
372 * used for the socket file descriptors. On Windows, this
373 * is SOCKET (a typedef for unsigned). Everywhere else, it's
374 * an int. The error value can't be -1 any more, so it's
375 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
376 * Windows it maps to the #define INVALID_SOCKET.)
378 * - The signature of bind_port has changed.
380 * Revision 1.48 2002/03/07 03:46:53 oes
381 * Fixed compiler warnings etc
383 * Revision 1.47 2002/02/20 23:15:13 jongfoster
384 * Parsing functions now handle out-of-memory gracefully by returning
387 * Revision 1.46 2002/01/17 21:03:47 jongfoster
388 * Moving all our URL and URL pattern parsing code to urlmatch.c.
390 * Revision 1.45 2002/01/09 14:33:03 oes
391 * Added support for localtime_r.
393 * Revision 1.44 2001/12/14 01:22:54 steudten
394 * Remove 'user:pass@' from 'proto://user:pass@host' for the
395 * new added header 'Host: ..'. (See Req ID 491818)
397 * Revision 1.43 2001/11/23 00:26:38 jongfoster
398 * Fixing two really stupid errors in my previous commit
400 * Revision 1.42 2001/11/22 21:59:30 jongfoster
401 * Adding code to handle +no-cookies-keep
403 * Revision 1.41 2001/11/05 23:43:05 steudten
404 * Add time+date to log files.
406 * Revision 1.40 2001/10/26 20:13:09 jongfoster
407 * ctype.h is needed in Windows, too.
409 * Revision 1.39 2001/10/26 17:40:04 oes
410 * Introduced get_header_value()
411 * Removed http->user_agent, csp->referrer and csp->accept_types
412 * Removed client_accept()
414 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
415 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
416 * threads to call select() simultaneously. So, it's time to do a real, live,
417 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
418 * (native). Both versions will work, but using __OS2__ offers multi-threading.
420 * Revision 1.37 2001/10/23 21:36:02 jongfoster
421 * Documenting sed()'s error behaviou (doc change only)
423 * Revision 1.36 2001/10/13 12:51:51 joergs
424 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
425 * force-load), instead crumble Host: and add it (again) in client_host_adder
426 * (in case we get a HTTP/1.0 request without Host: header and forward it to
427 * a HTTP/1.1 server/proxy).
429 * Revision 1.35 2001/10/09 22:39:21 jongfoster
430 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
433 * Revision 1.34 2001/10/07 18:50:55 oes
434 * Added server_content_encoding, renamed server_transfer_encoding
436 * Revision 1.33 2001/10/07 18:04:49 oes
437 * Changed server_http11 to server_http and its pattern to "HTTP".
438 * Additional functionality: it now saves the HTTP status into
439 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
441 * Revision 1.32 2001/10/07 15:43:28 oes
442 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
443 * client_te and client_accept_encoding_adder, triggered by the new
444 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
445 * changed to allow only identity and chunked, and the TE header is
446 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
448 * parse_http_request no longer does anything than parsing. The rewriting
449 * of http->cmd and version mangling are gone. It now also recognizes
450 * the put and delete methods and saves the url in http->url. Removed
453 * renamed content_type and content_length to have the server_ prefix
455 * server_content_type now only works if csp->content_type != CT_TABOO
457 * added server_transfer_encoding, which
458 * - Sets CT_TABOO to prohibit filtering if encoding compresses
459 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
460 * - Change from "chunked" to "identity" if body was chunked
461 * but has been de-chunked for filtering.
463 * added server_content_md5 which crunches any Content-MD5 headers
464 * if the body was modified.
466 * made server_http11 conditional on +downgrade action
468 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
470 * Revision 1.31 2001/10/05 14:25:02 oes
471 * Crumble Keep-Alive from Server
473 * Revision 1.30 2001/09/29 12:56:03 joergs
474 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
476 * Revision 1.29 2001/09/24 21:09:24 jongfoster
477 * Fixing 2 memory leaks that Guy spotted, where the paramater to
478 * enlist() was not being free()d.
480 * Revision 1.28 2001/09/22 16:32:28 jongfoster
481 * Removing unused #includes.
483 * Revision 1.27 2001/09/20 15:45:25 steudten
485 * add casting from size_t to int for printf()
486 * remove local variable shadow s2
488 * Revision 1.26 2001/09/16 17:05:14 jongfoster
489 * Removing unused #include showarg.h
491 * Revision 1.25 2001/09/16 13:21:27 jongfoster
492 * Changes to use new list functions.
494 * Revision 1.24 2001/09/13 23:05:50 jongfoster
495 * Changing the string paramater to the header parsers a "const".
497 * Revision 1.23 2001/09/12 18:08:19 steudten
499 * In parse_http_request() header rewriting miss the host value, so
500 * from http://www.mydomain.com the result was just " / " not
501 * http://www.mydomain.com/ in case we forward.
503 * Revision 1.22 2001/09/10 10:58:53 oes
504 * Silenced compiler warnings
506 * Revision 1.21 2001/07/31 14:46:00 oes
507 * - Persistant connections now suppressed
508 * - sed() no longer appends empty header to csp->headers
510 * Revision 1.20 2001/07/30 22:08:36 jongfoster
511 * Tidying up #defines:
512 * - All feature #defines are now of the form FEATURE_xxx
513 * - Permanently turned off WIN_GUI_EDIT
514 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
516 * Revision 1.19 2001/07/25 17:21:54 oes
517 * client_uagent now saves copy of User-Agent: header value
519 * Revision 1.18 2001/07/13 14:02:46 oes
520 * - Included fix to repair broken HTTP requests that
521 * don't contain a path, not even '/'.
522 * - Removed all #ifdef PCRS
523 * - content_type now always inspected and classified as
524 * text, gif or other.
525 * - formatting / comments
527 * Revision 1.17 2001/06/29 21:45:41 oes
528 * Indentation, CRLF->LF, Tab-> Space
530 * Revision 1.16 2001/06/29 13:32:42 oes
532 * - Adapted free_http_request
533 * - Removed logentry from cancelled commit
535 * Revision 1.15 2001/06/03 19:12:38 oes
536 * deleted const struct interceptors
538 * Revision 1.14 2001/06/01 18:49:17 jongfoster
539 * Replaced "list_share" with "list" - the tiny memory gain was not
540 * worth the extra complexity.
542 * Revision 1.13 2001/05/31 21:30:33 jongfoster
543 * Removed list code - it's now in list.[ch]
544 * Renamed "permission" to "action", and changed many features
545 * to use the actions file rather than the global config.
547 * Revision 1.12 2001/05/31 17:33:13 oes
551 * Revision 1.11 2001/05/29 20:11:19 joergs
552 * '/ * inside comment' warning removed.
554 * Revision 1.10 2001/05/29 09:50:24 jongfoster
555 * Unified blocklist/imagelist/permissionslist.
556 * File format is still under discussion, but the internal changes
559 * Also modified interceptor behaviour:
560 * - We now intercept all URLs beginning with one of the following
561 * prefixes (and *only* these prefixes):
563 * * http://ijbswa.sf.net/config/
564 * * http://ijbswa.sourceforge.net/config/
565 * - New interceptors "home page" - go to http://i.j.b/ to see it.
566 * - Internal changes so that intercepted and fast redirect pages
567 * are not replaced with an image.
568 * - Interceptors now have the option to send a binary page direct
569 * to the client. (i.e. ijb-send-banner uses this)
570 * - Implemented show-url-info interceptor. (Which is why I needed
571 * the above interceptors changes - a typical URL is
572 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
573 * The previous mechanism would not have intercepted that, and
574 * if it had been intercepted then it then it would have replaced
577 * Revision 1.9 2001/05/28 17:26:33 jongfoster
578 * Fixing segfault if last header was crunched.
579 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
580 * can use the cross-platform sprintf() instead.)
582 * Revision 1.8 2001/05/27 22:17:04 oes
584 * - re_process_buffer no longer writes the modified buffer
585 * to the client, which was very ugly. It now returns the
586 * buffer, which it is then written by chat.
588 * - content_length now adjusts the Content-Length: header
589 * for modified documents rather than crunch()ing it.
590 * (Length info in csp->content_length, which is 0 for
591 * unmodified documents)
593 * - For this to work, sed() is called twice when filtering.
595 * Revision 1.7 2001/05/27 13:19:06 oes
596 * Patched Joergs solution for the content-length in.
598 * Revision 1.6 2001/05/26 13:39:32 jongfoster
599 * Only crunches Content-Length header if applying RE filtering.
600 * Without this fix, Microsoft Windows Update wouldn't work.
602 * Revision 1.5 2001/05/26 00:28:36 jongfoster
603 * Automatic reloading of config file.
604 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
605 * Most of the global variables have been moved to a new
606 * struct configuration_spec, accessed through csp->config->globalname
607 * Most of the globals remaining are used by the Win32 GUI.
609 * Revision 1.4 2001/05/22 18:46:04 oes
611 * - Enabled filtering banners by size rather than URL
612 * by adding patterns that replace all standard banner
613 * sizes with the "Junkbuster" gif to the re_filterfile
615 * - Enabled filtering WebBugs by providing a pattern
616 * which kills all 1x1 images
618 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
619 * which is selected by the (nonstandard and therefore
620 * capital) letter 'U' in the option string.
621 * It causes the quantifiers to be ungreedy by default.
622 * Appending a ? turns back to greedy (!).
624 * - Added a new interceptor ijb-send-banner, which
625 * sends back the "Junkbuster" gif. Without imagelist or
626 * MSIE detection support, or if tinygif = 1, or the
627 * URL isn't recognized as an imageurl, a lame HTML
628 * explanation is sent instead.
630 * - Added new feature, which permits blocking remote
631 * script redirects and firing back a local redirect
633 * The feature is conditionally compiled, i.e. it
634 * can be disabled with --disable-fast-redirects,
635 * plus it must be activated by a "fast-redirects"
636 * line in the config file, has its own log level
637 * and of course wants to be displayed by show-proxy-args
638 * Note: Boy, all the #ifdefs in 1001 locations and
639 * all the fumbling with configure.in and acconfig.h
640 * were *way* more work than the feature itself :-(
642 * - Because a generic redirect template was needed for
643 * this, tinygif = 3 now uses the same.
645 * - Moved GIFs, and other static HTTP response templates
650 * - Removed some >400 CRs again (Jon, you really worked
653 * Revision 1.3 2001/05/20 01:21:20 jongfoster
654 * Version 2.9.4 checkin.
655 * - Merged popupfile and cookiefile, and added control over PCRS
656 * filtering, in new "permissionsfile".
657 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
658 * file error you now get a message box (in the Win32 GUI) rather
659 * than the program exiting with no explanation.
660 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
662 * - Removed tabs from "config"
663 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
664 * - Bumped up version number.
666 * Revision 1.2 2001/05/17 23:02:36 oes
667 * - Made referrer option accept 'L' as a substitute for '§'
669 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
670 * Initial import of version 2.9.3 source tree
673 *********************************************************************/
680 #include <sys/types.h>
690 * Convince GNU's libc to provide a strptime prototype.
693 #endif /*__GLIBC__ */
700 #if !defined(_WIN32) && !defined(__OS2__)
706 #ifdef FEATURE_PTHREAD
708 /* jcc.h is for mutex semapores only */
709 #endif /* def FEATURE_PTHREAD */
715 #include "jbsockets.h"
716 #include "miscutil.h"
721 #ifndef HAVE_STRPTIME
722 #include "strptime.h"
725 const char parsers_h_rcs[] = PARSERS_H_VERSION;
727 /* Fix a problem with Solaris. There should be no effect on other
729 * Solaris's isspace() is a macro which uses its argument directly
730 * as an array index. Therefore we need to make sure that high-bit
731 * characters generate +ve values, and ideally we also want to make
732 * the argument match the declared parameter type of "int".
734 * Why did they write a character function that can't take a simple
735 * "char" argument? Doh!
737 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
738 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
740 jb_err header_tagger(struct client_state *csp, char *header);
741 jb_err scan_headers(struct client_state *csp);
743 const struct parsers client_patterns[] = {
744 { "referer:", 8, client_referrer },
745 { "user-agent:", 11, client_uagent },
746 { "ua-", 3, client_ua },
747 { "from:", 5, client_from },
748 { "cookie:", 7, client_send_cookie },
749 { "x-forwarded-for:", 16, client_x_forwarded },
750 { "Accept-Encoding:", 16, client_accept_encoding },
751 { "TE:", 3, client_te },
752 { "Host:", 5, client_host },
753 { "if-modified-since:", 18, client_if_modified_since },
754 { "Keep-Alive:", 11, crumble },
755 { "connection:", 11, connection },
756 { "proxy-connection:", 17, crumble },
757 { "max-forwards:", 13, client_max_forwards },
758 { "Accept-Language:", 16, client_accept_language },
759 { "if-none-match:", 14, client_if_none_match },
760 { "X-Filter:", 9, client_x_filter },
761 { "*", 0, crunch_client_header },
762 { "*", 0, filter_header },
766 const struct parsers server_patterns[] = {
767 { "HTTP", 4, server_http },
768 { "set-cookie:", 11, server_set_cookie },
769 { "connection:", 11, connection },
770 { "Content-Type:", 13, server_content_type },
771 { "Content-MD5:", 12, server_content_md5 },
772 { "Content-Encoding:", 17, server_content_encoding },
773 { "Transfer-Encoding:", 18, server_transfer_coding },
774 { "Keep-Alive:", 11, crumble },
775 { "content-disposition:", 20, server_content_disposition },
776 { "Last-Modified:", 14, server_last_modified },
777 { "*", 0, crunch_server_header },
778 { "*", 0, filter_header },
782 const struct parsers server_patterns_light[] = {
783 { "Content-Length:", 15, server_content_length },
784 { "Transfer-Encoding:", 18, server_transfer_coding },
786 { "Content-Encoding:", 17, server_content_encoding },
787 #endif /* def FEATURE_ZLIB */
791 const add_header_func_ptr add_client_headers[] = {
794 client_x_forwarded_adder,
796 /* Temporarily disabled: client_accept_encoding_adder, */
797 connection_close_adder,
802 const add_header_func_ptr add_server_headers[] = {
803 connection_close_adder,
807 /*********************************************************************
809 * Function : flush_socket
811 * Description : Write any pending "buffered" content.
814 * 1 : fd = file descriptor of the socket to read
815 * 2 : csp = Current client state (buffers, headers, etc...)
817 * Returns : On success, the number of bytes written are returned (zero
818 * indicates nothing was written). On error, -1 is returned,
819 * and errno is set appropriately. If count is zero and the
820 * file descriptor refers to a regular file, 0 will be
821 * returned without causing any other effect. For a special
822 * file, the results are not portable.
824 *********************************************************************/
825 int flush_socket(jb_socket fd, struct client_state *csp)
827 struct iob *iob = csp->iob;
828 int len = iob->eod - iob->cur;
835 if (write_socket(fd, iob->cur, (size_t)len))
839 iob->eod = iob->cur = iob->buf;
845 /*********************************************************************
847 * Function : add_to_iob
849 * Description : Add content to the buffered page, expanding the
850 * buffer if necessary.
853 * 1 : csp = Current client state (buffers, headers, etc...)
854 * 2 : buf = holds the content to be added to the page
855 * 3 : n = number of bytes to be added
857 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
858 * or buffer limit reached.
860 *********************************************************************/
861 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
863 struct iob *iob = csp->iob;
864 size_t used, offset, need, want;
867 if (n <= 0) return JB_ERR_OK;
869 used = (size_t)(iob->eod - iob->buf);
870 offset = (size_t)(iob->cur - iob->buf);
871 need = used + (size_t)n + 1;
874 * If the buffer can't hold the new data, extend it first.
875 * Use the next power of two if possible, else use the actual need.
877 if (need > csp->config->buffer_limit)
879 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
880 return JB_ERR_MEMORY;
883 if (need > iob->size)
885 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
887 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
891 else if (NULL != (p = (char *)realloc(iob->buf, need)))
897 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
898 return JB_ERR_MEMORY;
901 /* Update the iob pointers */
902 iob->cur = p + offset;
907 /* copy the new data into the iob buffer */
908 memcpy(iob->eod, buf, (size_t)n);
910 /* point to the end of the data */
913 /* null terminate == cheap insurance */
922 /*********************************************************************
924 * Function : decompress_iob
926 * Description : Decompress buffered page, expanding the
927 * buffer as necessary. csp->iob->cur
928 * should point to the the beginning of the
929 * compressed data block.
932 * 1 : csp = Current client state (buffers, headers, etc...)
934 * Returns : JB_ERR_OK on success,
935 * JB_ERR_MEMORY if out-of-memory limit reached, and
936 * JB_ERR_COMPRESS if error decompressing buffer.
938 *********************************************************************/
939 jb_err decompress_iob(struct client_state *csp)
941 char *buf; /* new, uncompressed buffer */
942 char *cur; /* Current iob position (to keep the original
943 * iob->cur unmodified if we return early) */
944 size_t bufsize; /* allocated size of the new buffer */
945 size_t old_size; /* Content size before decompression */
946 size_t skip_size; /* Number of bytes at the beginning of the iob
947 that we should NOT decompress. */
948 int status; /* return status of the inflate() call */
949 z_stream zstr; /* used by calls to zlib */
951 assert(csp->iob->cur - csp->iob->buf > 0);
952 assert(csp->iob->eod - csp->iob->cur > 0);
954 bufsize = csp->iob->size;
955 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
956 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
963 * This is to protect the parsing of gzipped data,
964 * but it should(?) be valid for deflated data also.
966 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
967 return JB_ERR_COMPRESS;
970 if (csp->content_type & CT_GZIP)
973 * Our task is slightly complicated by the facts that data
974 * compressed by gzip does not include a zlib header, and
975 * that there is no easily accessible interface in zlib to
976 * handle a gzip header. We strip off the gzip header by
977 * hand, and later inform zlib not to expect a header.
981 * Strip off the gzip header. Please see RFC 1952 for more
982 * explanation of the appropriate fields.
984 if ((*cur++ != (char)0x1f)
985 || (*cur++ != (char)0x8b)
986 || (*cur++ != Z_DEFLATED))
988 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
989 return JB_ERR_COMPRESS;
995 * XXX: These magic numbers should be replaced
996 * with macros to give a better idea what they do.
1000 /* The gzip header has reserved bits set; bail out. */
1001 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1002 return JB_ERR_COMPRESS;
1006 /* Skip extra fields if necessary. */
1010 * Skip a given number of bytes, specified
1011 * as a 16-bit little-endian value.
1014 * XXX: This code used to be:
1016 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1018 * which I had to change into:
1020 * cur += *cur++ + (*cur++ << 8);
1022 * at which point gcc43 finally noticed that the value
1023 * of cur is undefined (it depends on which of the
1024 * summands is evaluated first).
1026 * I haven't come across a site where this
1027 * code is actually executed yet, but I hope
1031 skip_bytes = *cur++;
1032 skip_bytes = *cur++ << 8;
1034 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1037 * The number of bytes to skip should be positive
1038 * and we'd like to stay in the buffer.
1040 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1042 log_error (LOG_LEVEL_ERROR,
1043 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1045 return JB_ERR_COMPRESS;
1047 log_error (LOG_LEVEL_INFO,
1048 "Skipping %d bytes for gzip compression. Does this sound right?",
1053 /* Skip the filename if necessary. */
1056 /* A null-terminated string is supposed to follow. */
1057 while (*cur++ && (cur < csp->iob->eod));
1061 /* Skip the comment if necessary. */
1064 /* A null-terminated string is supposed to follow. */
1065 while (*cur++ && (cur < csp->iob->eod));
1068 /* Skip the CRC if necessary. */
1074 if (cur >= csp->iob->eod)
1077 * If the current position pointer reached or passed
1078 * the buffer end, we were obviously tricked to skip
1081 log_error (LOG_LEVEL_ERROR,
1082 "Malformed gzip header detected. Aborting decompression.");
1083 return JB_ERR_COMPRESS;
1087 else if (csp->content_type & CT_DEFLATE)
1090 * XXX: The debug level should be lowered
1091 * before the next stable release.
1093 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1095 * In theory (that is, according to RFC 1950), deflate-compressed
1096 * data should begin with a two-byte zlib header and have an
1097 * adler32 checksum at the end. It seems that in practice only
1098 * the raw compressed data is sent. Note that this means that
1099 * we are not RFC 1950-compliant here, but the advantage is that
1100 * this actually works. :)
1102 * We add a dummy null byte to tell zlib where the data ends,
1103 * and later inform it not to expect a header.
1105 * Fortunately, add_to_iob() has thoughtfully null-terminated
1106 * the buffer; we can just increment the end pointer to include
1113 log_error (LOG_LEVEL_ERROR,
1114 "Unable to determine compression format for decompression");
1115 return JB_ERR_COMPRESS;
1118 /* Set up the fields required by zlib. */
1119 zstr.next_in = (Bytef *)cur;
1120 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1121 zstr.zalloc = Z_NULL;
1122 zstr.zfree = Z_NULL;
1123 zstr.opaque = Z_NULL;
1126 * Passing -MAX_WBITS to inflateInit2 tells the library
1127 * that there is no zlib header.
1129 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1131 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1132 return JB_ERR_COMPRESS;
1136 * Next, we allocate new storage for the inflated data.
1137 * We don't modify the existing iob yet, so in case there
1138 * is error in decompression we can recover gracefully.
1140 buf = zalloc (bufsize);
1143 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1144 return JB_ERR_MEMORY;
1147 assert(bufsize >= skip_size);
1148 memcpy(buf, csp->iob->buf, skip_size);
1149 zstr.avail_out = bufsize - skip_size;
1150 zstr.next_out = (Bytef *)buf + skip_size;
1152 /* Try to decompress the whole stream in one shot. */
1153 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1155 /* We need to allocate more memory for the output buffer. */
1157 char *tmpbuf; /* used for realloc'ing the buffer */
1158 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1161 * If zlib wants more data then there's a problem, because
1162 * the complete compressed file should have been buffered.
1164 if (0 == zstr.avail_in)
1166 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1167 return JB_ERR_COMPRESS;
1171 * If we tried the limit and still didn't have enough
1172 * memory, just give up.
1174 if (bufsize == csp->config->buffer_limit)
1176 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1177 return JB_ERR_MEMORY;
1180 /* Try doubling the buffer size each time. */
1183 /* Don't exceed the buffer limit. */
1184 if (bufsize > csp->config->buffer_limit)
1186 bufsize = csp->config->buffer_limit;
1189 /* Try to allocate the new buffer. */
1190 tmpbuf = realloc(buf, bufsize);
1193 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1195 return JB_ERR_MEMORY;
1199 char *oldnext_out = (char *)zstr.next_out;
1202 * Update the fields for inflate() to use the new
1203 * buffer, which may be in a location different from
1206 zstr.avail_out += bufsize - oldbufsize;
1207 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1210 * Compare with an uglier method of calculating these values
1211 * that doesn't require the extra oldbufsize variable.
1213 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1214 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1215 assert(zstr.avail_out > 0);
1221 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1223 log_error(LOG_LEVEL_ERROR,
1224 "Inconsistent stream state after decompression: %s", zstr.msg);
1226 * XXX: Intentionally no return.
1228 * According to zlib.h, Z_STREAM_ERROR is returned
1229 * "if the stream state was inconsistent".
1231 * I assume in this case inflate()'s status
1232 * would also be something different than Z_STREAM_END
1233 * so this check should be redundant, but lets see.
1237 if (status != Z_STREAM_END)
1239 /* We failed to decompress the stream. */
1240 log_error(LOG_LEVEL_ERROR,
1241 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1242 return JB_ERR_COMPRESS;
1246 * Finally, we can actually update the iob, since the
1247 * decompression was successful. First, free the old
1250 freez(csp->iob->buf);
1252 /* Now, update the iob to use the new buffer. */
1253 csp->iob->buf = buf;
1254 csp->iob->cur = csp->iob->buf + skip_size;
1255 csp->iob->eod = (char *)zstr.next_out;
1256 csp->iob->size = bufsize;
1259 * Make sure the new uncompressed iob obeys some minimal
1260 * consistency conditions.
1262 if ((csp->iob->buf < csp->iob->cur)
1263 && (csp->iob->cur <= csp->iob->eod)
1264 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1266 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1269 log_error(LOG_LEVEL_RE_FILTER,
1270 "Decompression successful. Old size: %d, new size: %d.",
1271 old_size, new_size);
1275 /* zlib thinks this is OK, so lets do the same. */
1276 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1281 /* It seems that zlib did something weird. */
1282 log_error(LOG_LEVEL_ERROR,
1283 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1284 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1285 csp->iob->eod, csp->iob->buf + csp->iob->size);
1286 return JB_ERR_COMPRESS;
1292 #endif /* defined(FEATURE_ZLIB) */
1295 /*********************************************************************
1297 * Function : get_header
1299 * Description : This (odd) routine will parse the csp->iob
1302 * 1 : csp = Current client state (buffers, headers, etc...)
1304 * Returns : Any one of the following:
1306 * 1) a pointer to a dynamically allocated string that contains a header line
1307 * 2) NULL indicating that the end of the header was reached
1308 * 3) "" indicating that the end of the iob was reached before finding
1309 * a complete header line.
1311 *********************************************************************/
1312 char *get_header(struct client_state *csp)
1318 if ((iob->cur == NULL)
1319 || ((p = strchr(iob->cur, '\n')) == NULL))
1321 return(""); /* couldn't find a complete header */
1326 ret = strdup(iob->cur);
1329 /* FIXME No way to handle error properly */
1330 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1335 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1337 /* is this a blank line (i.e. the end of the header) ? */
1349 /*********************************************************************
1351 * Function : get_header_value
1353 * Description : Get the value of a given header from a chained list
1354 * of header lines or return NULL if no such header is
1355 * present in the list.
1358 * 1 : header_list = pointer to list
1359 * 2 : header_name = string with name of header to look for.
1360 * Trailing colon required, capitalization
1363 * Returns : NULL if not found, else value of header
1365 *********************************************************************/
1366 char *get_header_value(const struct list *header_list, const char *header_name)
1368 struct list_entry *cur_entry;
1372 assert(header_list);
1373 assert(header_name);
1374 length = strlen(header_name);
1376 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1380 if (!strncmpic(cur_entry->str, header_name, length))
1383 * Found: return pointer to start of value
1385 ret = (char *) (cur_entry->str + length);
1386 while (*ret && ijb_isspace(*ret)) ret++;
1400 /*********************************************************************
1402 * Function : scan_headers
1404 * Description : Scans headers, applies tags and updates action bits.
1407 * 1 : csp = Current client state (buffers, headers, etc...)
1409 * Returns : JB_ERR_OK
1411 *********************************************************************/
1412 jb_err scan_headers(struct client_state *csp)
1414 struct list_entry *h; /* Header */
1415 jb_err err = JB_ERR_OK;
1417 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1419 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1421 /* Header crunch()ed in previous run? -> ignore */
1422 if (h->str == NULL) continue;
1423 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1424 err = header_tagger(csp, h->str);
1431 /*********************************************************************
1435 * Description : add, delete or modify lines in the HTTP header streams.
1436 * On entry, it receives a linked list of headers space
1437 * that was allocated dynamically (both the list nodes
1438 * and the header contents).
1440 * As a side effect it frees the space used by the original
1444 * 1 : pats = list of patterns to match against headers
1445 * 2 : more_headers = list of functions to add more
1446 * headers (client or server)
1447 * 3 : csp = Current client state (buffers, headers, etc...)
1449 * Returns : Single pointer to a fully formed header, or NULL
1450 * on out-of-memory error.
1452 *********************************************************************/
1453 char *sed(const struct parsers pats[],
1454 const add_header_func_ptr more_headers[],
1455 struct client_state *csp)
1457 struct list_entry *p;
1458 const struct parsers *v;
1459 const add_header_func_ptr *f;
1460 jb_err err = JB_ERR_OK;
1464 * If filtering is enabled, sed is run twice,
1465 * but most of the work needs to be done only once.
1467 first_run = (more_headers != NULL ) ? 1 : 0;
1469 if (first_run) /* Parse and print */
1473 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1475 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1477 /* Header crunch()ed in previous run? -> ignore */
1478 if (p->str == NULL) continue;
1480 /* Does the current parser handle this header? */
1481 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1483 err = v->parser(csp, (char **)&(p->str));
1487 /* place any additional headers on the csp->headers list */
1488 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1493 else /* Parse only */
1496 * The second run is only needed if the body was modified
1497 * and the content-lenght has changed.
1499 if (strncmpic(csp->http->cmd, "HEAD", 4))
1501 /*XXX: Code duplication */
1502 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1504 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1506 /* Header crunch()ed in previous run? -> ignore */
1507 if (p->str == NULL) continue;
1509 /* Does the current parser handle this header? */
1510 if (strncmpic(p->str, v->str, v->len) == 0)
1512 err = v->parser(csp, (char **)&(p->str));
1519 if (err != JB_ERR_OK)
1524 return list_to_text(csp->headers);
1529 /*********************************************************************
1531 * Function : header_tagger
1533 * Description : Executes all text substitutions from applying
1534 * tag actions and saves the result as tag.
1536 * XXX: Shares enough code with filter_header() and
1537 * pcrs_filter_response() to warrant some helper functions.
1540 * 1 : csp = Current client state (buffers, headers, etc...)
1541 * 2 : header = Header that is used as tagger input
1543 * Returns : JB_ERR_OK on success and always succeeds
1545 *********************************************************************/
1546 jb_err header_tagger(struct client_state *csp, char *header)
1548 int wanted_filter_type;
1549 int multi_action_index;
1553 struct file_list *fl;
1554 struct re_filterfile_spec *b;
1555 struct list_entry *tag_name;
1557 int found_filters = 0;
1558 const size_t header_length = strlen(header);
1560 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1562 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1563 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1567 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1568 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1571 /* Check if there are any filters */
1572 for (i = 0; i < MAX_AF_FILES; i++)
1585 if (0 == found_filters)
1587 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1591 for (i = 0; i < MAX_AF_FILES; i++)
1594 if ((NULL == fl) || (NULL == fl->f))
1597 * Either there are no filter files
1598 * left, or this filter file just
1599 * contains no valid filters.
1601 * Continue to be sure we don't miss
1602 * valid filter files that are chained
1603 * after empty or invalid ones.
1608 /* For all filters, */
1609 for (b = fl->f; b; b = b->next)
1611 if (b->type != wanted_filter_type)
1613 /* skip the ones we don't care about, */
1616 /* leaving only taggers that could apply, of which we use the ones, */
1617 for (tag_name = csp->action->multi[multi_action_index]->first;
1618 NULL != tag_name; tag_name = tag_name->next)
1620 /* that do apply, and */
1621 if (strcmp(b->name, tag_name->str) == 0)
1623 char *modified_tag = NULL;
1625 size_t size = header_length;
1626 pcrs_job *joblist = b->joblist;
1628 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1630 if (NULL == joblist)
1632 log_error(LOG_LEVEL_RE_FILTER,
1633 "Tagger %s has empty joblist. Nothing to do.", b->name);
1637 /* execute their pcrs_joblist on the header. */
1638 for (job = joblist; NULL != job; job = job->next)
1640 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1644 /* Success, continue with the modified version. */
1653 /* Tagger doesn't match */
1656 /* Regex failure, log it but continue anyway. */
1657 log_error(LOG_LEVEL_ERROR,
1658 "Problems with tagger \'%s\' and header \'%s\': %s",
1659 b->name, *header, pcrs_strerror(hits));
1661 freez(modified_tag);
1665 if (b->dynamic) pcrs_free_joblist(joblist);
1667 /* If this tagger matched */
1673 * There is to technical limitation which makes
1674 * it impossible to use empty tags, but I assume
1675 * no one would do it intentionally.
1678 log_error(LOG_LEVEL_INFO,
1679 "Tagger \'%s\' created an empty tag. Ignored.",
1684 if (!list_contains_item(csp->tags, tag))
1686 if (JB_ERR_OK != enlist(csp->tags, tag))
1688 log_error(LOG_LEVEL_ERROR,
1689 "Insufficient memory to add tag \'%s\', "
1690 "based on tagger \'%s\' and header \'%s\'",
1691 tag, b->name, *header);
1695 char *action_message;
1697 * update the action bits right away, to make
1698 * tagging based on tags set by earlier taggers
1699 * of the same kind possible.
1701 if (update_action_bits_for_tag(csp, tag))
1703 action_message = "Action bits updated accordingly.";
1707 action_message = "No action bits update necessary.";
1710 log_error(LOG_LEVEL_HEADER,
1711 "Tagger \'%s\' added tag \'%s\'. %s",
1712 b->name, tag, action_message);
1717 /* XXX: Is this log-worthy? */
1718 log_error(LOG_LEVEL_HEADER,
1719 "Tagger \'%s\' didn't add tag \'%s\'. "
1720 "Tag already present", b->name, tag);
1723 } /* if the tagger matched */
1724 } /* if the tagger applies */
1725 } /* for every tagger that could apply */
1726 } /* for all filters */
1727 } /* for all filter files */
1732 /* here begins the family of parser functions that reformat header lines */
1734 /*********************************************************************
1736 * Function : filter_header
1738 * Description : Executes all text substitutions from all applying
1739 * +(server|client)-header-filter actions on the header.
1740 * Most of the code was copied from pcrs_filter_response,
1741 * including the rather short variable names
1744 * 1 : csp = Current client state (buffers, headers, etc...)
1745 * 2 : header = On input, pointer to header to modify.
1746 * On output, pointer to the modified header, or NULL
1747 * to remove the header. This function frees the
1748 * original string if necessary.
1750 * Returns : JB_ERR_OK on success and always succeeds
1752 *********************************************************************/
1753 jb_err filter_header(struct client_state *csp, char **header)
1757 size_t size = strlen(*header);
1759 char *newheader = NULL;
1762 struct file_list *fl;
1763 struct re_filterfile_spec *b;
1764 struct list_entry *filtername;
1766 int i, found_filters = 0;
1767 int wanted_filter_type;
1768 int multi_action_index;
1770 if (csp->flags & CSP_FLAG_NO_FILTERING)
1775 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1777 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1778 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1782 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1783 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1787 * Need to check the set of re_filterfiles...
1789 for (i = 0; i < MAX_AF_FILES; i++)
1802 if (0 == found_filters)
1804 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1808 for (i = 0; i < MAX_AF_FILES; i++)
1811 if ((NULL == fl) || (NULL == fl->f))
1814 * Either there are no filter files
1815 * left, or this filter file just
1816 * contains no valid filters.
1818 * Continue to be sure we don't miss
1819 * valid filter files that are chained
1820 * after empty or invalid ones.
1825 * For all applying +filter actions, look if a filter by that
1826 * name exists and if yes, execute its pcrs_joblist on the
1829 for (b = fl->f; b; b = b->next)
1831 if (b->type != wanted_filter_type)
1833 /* Skip other filter types */
1837 for (filtername = csp->action->multi[multi_action_index]->first;
1838 filtername ; filtername = filtername->next)
1840 if (strcmp(b->name, filtername->str) == 0)
1842 int current_hits = 0;
1843 pcrs_job *joblist = b->joblist;
1845 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1847 if (NULL == joblist)
1849 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1853 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1854 *header, size, b->name);
1856 /* Apply all jobs from the joblist */
1857 for (job = joblist; NULL != job; job = job->next)
1859 matches = pcrs_execute(job, *header, size, &newheader, &size);
1862 current_hits += matches;
1863 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1865 *header = newheader;
1867 else if ( 0 == matches )
1869 /* Filter doesn't change header */
1875 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1876 *header, b->name, pcrs_strerror(matches));
1877 if( newheader != NULL)
1879 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1885 if (b->dynamic) pcrs_free_joblist(joblist);
1887 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1888 hits += current_hits;
1895 * Additionally checking for hits is important because if
1896 * the continue hack is triggered, server headers can
1897 * arrive empty to separate multiple heads from each other.
1899 if ((0 == size) && hits)
1901 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1909 /*********************************************************************
1911 * Function : connection
1913 * Description : Makes sure that the value of the Connection: header
1914 * is "close" and signals connection_close_adder
1918 * 1 : csp = Current client state (buffers, headers, etc...)
1919 * 2 : header = On input, pointer to header to modify.
1920 * On output, pointer to the modified header, or NULL
1921 * to remove the header. This function frees the
1922 * original string if necessary.
1924 * Returns : JB_ERR_OK on success, or
1925 * JB_ERR_MEMORY on out-of-memory error.
1927 *********************************************************************/
1928 jb_err connection(struct client_state *csp, char **header)
1930 char *old_header = *header;
1932 /* Do we have a 'Connection: close' header? */
1933 if (strcmpic(*header, "Connection: close"))
1935 /* No, create one */
1936 *header = strdup("Connection: close");
1939 return JB_ERR_MEMORY;
1941 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1945 /* Signal connection_close_adder() to return early. */
1946 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1948 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
1952 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
1959 /*********************************************************************
1961 * Function : crumble
1963 * Description : This is called if a header matches a pattern to "crunch"
1966 * 1 : csp = Current client state (buffers, headers, etc...)
1967 * 2 : header = On input, pointer to header to modify.
1968 * On output, pointer to the modified header, or NULL
1969 * to remove the header. This function frees the
1970 * original string if necessary.
1972 * Returns : JB_ERR_OK on success, or
1973 * JB_ERR_MEMORY on out-of-memory error.
1975 *********************************************************************/
1976 jb_err crumble(struct client_state *csp, char **header)
1978 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1983 /*********************************************************************
1985 * Function : crunch_server_header
1987 * Description : Crunch server header if it matches a string supplied by the
1988 * user. Called from `sed'.
1991 * 1 : csp = Current client state (buffers, headers, etc...)
1992 * 2 : header = On input, pointer to header to modify.
1993 * On output, pointer to the modified header, or NULL
1994 * to remove the header. This function frees the
1995 * original string if necessary.
1997 * Returns : JB_ERR_OK on success and always succeeds
1999 *********************************************************************/
2000 jb_err crunch_server_header(struct client_state *csp, char **header)
2002 const char *crunch_pattern;
2004 /* Do we feel like crunching? */
2005 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2007 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2009 /* Is the current header the lucky one? */
2010 if (strstr(*header, crunch_pattern))
2012 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2021 /*********************************************************************
2023 * Function : server_content_type
2025 * Description : Set the content-type for filterable types (text/.*,
2026 * .*xml.*, javascript and image/gif) unless filtering has been
2027 * forbidden (CT_TABOO) while parsing earlier headers.
2028 * NOTE: Since text/plain is commonly used by web servers
2029 * for files whose correct type is unknown, we don't
2030 * set CT_TEXT for it.
2033 * 1 : csp = Current client state (buffers, headers, etc...)
2034 * 2 : header = On input, pointer to header to modify.
2035 * On output, pointer to the modified header, or NULL
2036 * to remove the header. This function frees the
2037 * original string if necessary.
2039 * Returns : JB_ERR_OK on success, or
2040 * JB_ERR_MEMORY on out-of-memory error.
2042 *********************************************************************/
2043 jb_err server_content_type(struct client_state *csp, char **header)
2045 /* Remove header if it isn't the first Content-Type header */
2046 if(csp->content_type && (csp->content_type != CT_TABOO))
2049 * Another, slightly slower, way to see if
2050 * we already parsed another Content-Type header.
2052 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2054 log_error(LOG_LEVEL_ERROR,
2055 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2062 if (!(csp->content_type & CT_TABOO))
2064 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2065 || strstr(*header, "xml")
2066 || strstr(*header, "application/x-javascript"))
2068 csp->content_type |= CT_TEXT;
2070 else if (strstr(*header, " image/gif"))
2072 csp->content_type |= CT_GIF;
2074 else if (strstr(*header, " image/jpeg"))
2076 csp->content_type |= CT_JPEG;
2080 csp->content_type = 0;
2084 * Are we enabling text mode by force?
2086 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2089 * Do we really have to?
2091 if (csp->content_type & CT_TEXT)
2093 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2097 csp->content_type |= CT_TEXT;
2098 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2102 * Are we messing with the content type?
2104 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2107 * Make sure the user doesn't accidently
2108 * change the content type of binary documents.
2110 if (csp->content_type & CT_TEXT)
2113 *header = strdup("Content-Type: ");
2114 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2118 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2119 return JB_ERR_MEMORY;
2121 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2125 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2126 "Enable force-text-mode if you know what you're doing.", *header);
2133 /*********************************************************************
2135 * Function : server_transfer_coding
2137 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2138 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2139 * - Remove header if body was chunked but has been
2140 * de-chunked for filtering.
2143 * 1 : csp = Current client state (buffers, headers, etc...)
2144 * 2 : header = On input, pointer to header to modify.
2145 * On output, pointer to the modified header, or NULL
2146 * to remove the header. This function frees the
2147 * original string if necessary.
2149 * Returns : JB_ERR_OK on success, or
2150 * JB_ERR_MEMORY on out-of-memory error.
2152 *********************************************************************/
2153 jb_err server_transfer_coding(struct client_state *csp, char **header)
2156 * Turn off pcrs and gif filtering if body compressed
2158 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2162 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2164 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2165 csp->http->cmd, *header);
2166 #endif /* def FEATURE_ZLIB */
2167 csp->content_type = CT_TABOO;
2171 * Raise flag if body chunked
2173 if (strstr(*header, "chunked"))
2175 csp->flags |= CSP_FLAG_CHUNKED;
2178 * If the body was modified, it has been de-chunked first
2179 * and the header must be removed.
2181 * FIXME: If there is more than one transfer encoding,
2182 * only the "chunked" part should be removed here.
2184 if (csp->flags & CSP_FLAG_MODIFIED)
2186 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2195 /*********************************************************************
2197 * Function : server_content_encoding
2199 * Description : This function is run twice for each request,
2200 * unless FEATURE_ZLIB and filtering are disabled.
2202 * The first run is used to check if the content
2203 * is compressed, if FEATURE_ZLIB is disabled
2204 * filtering is then disabled as well, if FEATURE_ZLIB
2205 * is enabled the content is marked for decompression.
2207 * The second run is used to remove the Content-Encoding
2208 * header if the decompression was successful.
2211 * 1 : csp = Current client state (buffers, headers, etc...)
2212 * 2 : header = On input, pointer to header to modify.
2213 * On output, pointer to the modified header, or NULL
2214 * to remove the header. This function frees the
2215 * original string if necessary.
2217 * Returns : JB_ERR_OK on success, or
2218 * JB_ERR_MEMORY on out-of-memory error.
2220 *********************************************************************/
2221 jb_err server_content_encoding(struct client_state *csp, char **header)
2224 if ((csp->flags & CSP_FLAG_MODIFIED)
2225 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2228 * We successfully decompressed the content,
2229 * and have to clean the header now, so the
2230 * client no longer expects compressed data..
2232 * XXX: There is a difference between cleaning
2233 * and removing it completely.
2235 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2238 else if (strstr(*header, "gzip"))
2240 /* Mark for gzip decompression */
2241 csp->content_type |= CT_GZIP;
2243 else if (strstr(*header, "deflate"))
2245 /* Mark for zlib decompression */
2246 csp->content_type |= CT_DEFLATE;
2248 else if (strstr(*header, "compress"))
2251 * We can't decompress this; therefore we can't filter
2254 csp->content_type |= CT_TABOO;
2256 #else /* !defined(FEATURE_ZLIB) */
2257 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2260 * Body is compressed, turn off pcrs and gif filtering.
2262 csp->content_type |= CT_TABOO;
2265 * Log a warning if the user expects the content to be filtered.
2267 if ((csp->rlist != NULL) &&
2268 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2270 log_error(LOG_LEVEL_INFO,
2271 "Compressed content detected, content filtering disabled. "
2272 "Consider recompiling Privoxy with zlib support or "
2273 "enable the prevent-compression action.");
2276 #endif /* defined(FEATURE_ZLIB) */
2283 /*********************************************************************
2285 * Function : server_content_length
2287 * Description : Adjust Content-Length header if we modified
2291 * 1 : csp = Current client state (buffers, headers, etc...)
2292 * 2 : header = On input, pointer to header to modify.
2293 * On output, pointer to the modified header, or NULL
2294 * to remove the header. This function frees the
2295 * original string if necessary.
2297 * Returns : JB_ERR_OK on success, or
2298 * JB_ERR_MEMORY on out-of-memory error.
2300 *********************************************************************/
2301 jb_err server_content_length(struct client_state *csp, char **header)
2303 const size_t max_header_length = 80;
2305 /* Regenerate header if the content was modified. */
2306 if (csp->flags & CSP_FLAG_MODIFIED)
2309 *header = (char *) zalloc(max_header_length);
2310 if (*header == NULL)
2312 return JB_ERR_MEMORY;
2315 snprintf(*header, max_header_length, "Content-Length: %d",
2316 (int)csp->content_length);
2317 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2318 (int)csp->content_length);
2325 /*********************************************************************
2327 * Function : server_content_md5
2329 * Description : Crumble any Content-MD5 headers if the document was
2330 * modified. FIXME: Should we re-compute instead?
2333 * 1 : csp = Current client state (buffers, headers, etc...)
2334 * 2 : header = On input, pointer to header to modify.
2335 * On output, pointer to the modified header, or NULL
2336 * to remove the header. This function frees the
2337 * original string if necessary.
2339 * Returns : JB_ERR_OK on success, or
2340 * JB_ERR_MEMORY on out-of-memory error.
2342 *********************************************************************/
2343 jb_err server_content_md5(struct client_state *csp, char **header)
2345 if (csp->flags & CSP_FLAG_MODIFIED)
2347 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2354 /*********************************************************************
2356 * Function : server_content_disposition
2358 * Description : If enabled, blocks or modifies the "content-disposition" header.
2359 * Called from `sed'.
2362 * 1 : csp = Current client state (buffers, headers, etc...)
2363 * 2 : header = On input, pointer to header to modify.
2364 * On output, pointer to the modified header, or NULL
2365 * to remove the header. This function frees the
2366 * original string if necessary.
2368 * Returns : JB_ERR_OK on success, or
2369 * JB_ERR_MEMORY on out-of-memory error.
2371 *********************************************************************/
2372 jb_err server_content_disposition(struct client_state *csp, char **header)
2377 * Are we messing with the content-disposition header?
2379 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2385 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2387 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2390 * Blocking content-disposition header
2392 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2399 * Replacing content-disposition header
2402 *header = strdup("content-disposition: ");
2403 string_append(header, newval);
2405 if (*header == NULL)
2407 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2411 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2414 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2417 /*********************************************************************
2419 * Function : server_last_modified
2421 * Description : Changes Last-Modified header to the actual date
2422 * to help hide-if-modified-since.
2423 * Called from `sed'.
2426 * 1 : csp = Current client state (buffers, headers, etc...)
2427 * 2 : header = On input, pointer to header to modify.
2428 * On output, pointer to the modified header, or NULL
2429 * to remove the header. This function frees the
2430 * original string if necessary.
2432 * Returns : JB_ERR_OK on success, or
2433 * JB_ERR_MEMORY on out-of-memory error.
2435 *********************************************************************/
2436 jb_err server_last_modified(struct client_state *csp, char **header)
2439 char buf[BUFFER_SIZE];
2442 #ifdef HAVE_GMTIME_R
2445 struct tm *timeptr = NULL;
2446 time_t now, last_modified;
2448 long int days, hours, minutes, seconds;
2451 * Are we messing with the Last-Modified header?
2453 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2459 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2461 if (0 == strcmpic(newval, "block") )
2464 * Blocking Last-Modified header. Useless but why not.
2466 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2470 else if (0 == strcmpic(newval, "reset-to-request-time"))
2473 * Setting Last-Modified Header to now.
2475 get_http_time(0, buf);
2477 *header = strdup("Last-Modified: ");
2478 string_append(header, buf);
2480 if (*header == NULL)
2482 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2486 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2489 else if (0 == strcmpic(newval, "randomize"))
2491 const char *header_time = *header + sizeof("Last-Modified:");
2493 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2495 #ifdef HAVE_GMTIME_R
2496 timeptr = gmtime_r(&now, &gmt);
2497 #elif FEATURE_PTHREAD
2498 pthread_mutex_lock(&gmtime_mutex);
2499 timeptr = gmtime(&now);
2500 pthread_mutex_unlock(&gmtime_mutex);
2502 timeptr = gmtime(&now);
2504 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2506 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2511 rtime = (long int)difftime(now, last_modified);
2514 rtime = pick_from_range(rtime);
2515 last_modified += rtime;
2516 #ifdef HAVE_GMTIME_R
2517 timeptr = gmtime_r(&last_modified, &gmt);
2518 #elif FEATURE_PTHREAD
2519 pthread_mutex_lock(&gmtime_mutex);
2520 timeptr = gmtime(&last_modified);
2521 pthread_mutex_unlock(&gmtime_mutex);
2523 timeptr = gmtime(&last_modified);
2525 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2527 *header = strdup("Last-Modified: ");
2528 string_append(header, newheader);
2530 if (*header == NULL)
2532 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2533 return JB_ERR_MEMORY;
2536 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2538 days = rtime / (3600 * 24);
2539 hours = rtime / 3600 % 24;
2540 minutes = rtime / 60 % 60;
2541 seconds = rtime % 60;
2543 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2544 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2545 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2550 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2559 /*********************************************************************
2561 * Function : client_accept_encoding
2563 * Description : Rewrite the client's Accept-Encoding header so that
2564 * if doesn't allow compression, if the action applies.
2565 * Note: For HTTP/1.0 the absence of the header is enough.
2568 * 1 : csp = Current client state (buffers, headers, etc...)
2569 * 2 : header = On input, pointer to header to modify.
2570 * On output, pointer to the modified header, or NULL
2571 * to remove the header. This function frees the
2572 * original string if necessary.
2574 * Returns : JB_ERR_OK on success, or
2575 * JB_ERR_MEMORY on out-of-memory error.
2577 *********************************************************************/
2578 jb_err client_accept_encoding(struct client_state *csp, char **header)
2580 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2582 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2586 /* Temporarily disable the correct behaviour to
2587 * work around a PHP bug.
2589 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2591 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2592 * if (*header == NULL)
2594 * return JB_ERR_MEMORY;
2605 /*********************************************************************
2607 * Function : client_te
2609 * Description : Rewrite the client's TE header so that
2610 * if doesn't allow compression, if the action applies.
2613 * 1 : csp = Current client state (buffers, headers, etc...)
2614 * 2 : header = On input, pointer to header to modify.
2615 * On output, pointer to the modified header, or NULL
2616 * to remove the header. This function frees the
2617 * original string if necessary.
2619 * Returns : JB_ERR_OK on success, or
2620 * JB_ERR_MEMORY on out-of-memory error.
2622 *********************************************************************/
2623 jb_err client_te(struct client_state *csp, char **header)
2625 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2628 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2634 /*********************************************************************
2636 * Function : client_referrer
2638 * Description : Handle the "referer" config setting properly.
2639 * Called from `sed'.
2642 * 1 : csp = Current client state (buffers, headers, etc...)
2643 * 2 : header = On input, pointer to header to modify.
2644 * On output, pointer to the modified header, or NULL
2645 * to remove the header. This function frees the
2646 * original string if necessary.
2648 * Returns : JB_ERR_OK on success, or
2649 * JB_ERR_MEMORY on out-of-memory error.
2651 *********************************************************************/
2652 jb_err client_referrer(struct client_state *csp, char **header)
2659 #ifdef FEATURE_FORCE_LOAD
2660 /* Since the referrer can include the prefix even
2661 * if the request itself is non-forced, we must
2662 * clean it unconditionally
2664 strclean(*header, FORCE_PREFIX);
2665 #endif /* def FEATURE_FORCE_LOAD */
2668 * Are we sending referer?
2670 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2675 newval = csp->action->string[ACTION_STRING_REFERER];
2677 if ((0 != strcmpic(newval, "conditional-block")))
2681 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2686 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2689 else if (0 == strcmpic(newval, "conditional-block"))
2692 * Block referer if host has changed.
2695 if (NULL == (host = strdup(csp->http->hostport)))
2698 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2699 return JB_ERR_MEMORY;
2701 if (NULL == (referer = strdup(*header)))
2705 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2706 return JB_ERR_MEMORY;
2708 hostlenght = strlen(host);
2709 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2711 /*Shorten referer to make sure the referer is blocked
2712 *if www.example.org/www.example.com-shall-see-the-referer/
2713 *links to www.example.com/
2715 referer[hostlenght+17] = '\0';
2717 if ( 0 == strstr(referer, host)) /*Host has changed*/
2719 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2724 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2730 else if (0 != strcmpic(newval, "forge"))
2733 * We have a specific (fixed) referer we want to send.
2735 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2737 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2739 *header = strdup("Referer: ");
2740 string_append(header, newval);
2741 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2743 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2748 * Forge a referer as http://[hostname:port of REQUEST]/
2749 * to fool stupid checks for in-site links
2752 *header = strdup("Referer: http://");
2753 string_append(header, csp->http->hostport);
2754 string_append(header, "/");
2755 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2757 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2761 /*********************************************************************
2763 * Function : client_accept_language
2765 * Description : Handle the "Accept-Language" config setting properly.
2766 * Called from `sed'.
2769 * 1 : csp = Current client state (buffers, headers, etc...)
2770 * 2 : header = On input, pointer to header to modify.
2771 * On output, pointer to the modified header, or NULL
2772 * to remove the header. This function frees the
2773 * original string if necessary.
2775 * Returns : JB_ERR_OK on success, or
2776 * JB_ERR_MEMORY on out-of-memory error.
2778 *********************************************************************/
2779 jb_err client_accept_language(struct client_state *csp, char **header)
2784 * Are we messing with the Accept-Language?
2786 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2788 /*I don't think so*/
2792 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2794 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2797 * Blocking Accept-Language header
2799 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2806 * Replacing Accept-Language header
2809 *header = strdup("Accept-Language: ");
2810 string_append(header, newval);
2812 if (*header == NULL)
2814 log_error(LOG_LEVEL_ERROR,
2815 "Insufficent memory. Accept-Language header crunched without replacement.");
2819 log_error(LOG_LEVEL_HEADER,
2820 "Accept-Language header crunched and replaced with: %s", *header);
2823 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2826 /*********************************************************************
2828 * Function : crunch_client_header
2830 * Description : Crunch client header if it matches a string supplied by the
2831 * user. Called from `sed'.
2834 * 1 : csp = Current client state (buffers, headers, etc...)
2835 * 2 : header = On input, pointer to header to modify.
2836 * On output, pointer to the modified header, or NULL
2837 * to remove the header. This function frees the
2838 * original string if necessary.
2840 * Returns : JB_ERR_OK on success and always succeeds
2842 *********************************************************************/
2843 jb_err crunch_client_header(struct client_state *csp, char **header)
2845 const char *crunch_pattern;
2847 /* Do we feel like crunching? */
2848 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2850 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2852 /* Is the current header the lucky one? */
2853 if (strstr(*header, crunch_pattern))
2855 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2863 /*********************************************************************
2865 * Function : client_uagent
2867 * Description : Handle the "user-agent" config setting properly
2868 * and remember its original value to enable browser
2869 * bug workarounds. Called from `sed'.
2872 * 1 : csp = Current client state (buffers, headers, etc...)
2873 * 2 : header = On input, pointer to header to modify.
2874 * On output, pointer to the modified header, or NULL
2875 * to remove the header. This function frees the
2876 * original string if necessary.
2878 * Returns : JB_ERR_OK on success, or
2879 * JB_ERR_MEMORY on out-of-memory error.
2881 *********************************************************************/
2882 jb_err client_uagent(struct client_state *csp, char **header)
2886 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2891 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2898 *header = strdup("User-Agent: ");
2899 string_append(header, newval);
2901 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2903 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2906 /*********************************************************************
2908 * Function : client_ua
2910 * Description : Handle "ua-" headers properly. Called from `sed'.
2913 * 1 : csp = Current client state (buffers, headers, etc...)
2914 * 2 : header = On input, pointer to header to modify.
2915 * On output, pointer to the modified header, or NULL
2916 * to remove the header. This function frees the
2917 * original string if necessary.
2919 * Returns : JB_ERR_OK on success, or
2920 * JB_ERR_MEMORY on out-of-memory error.
2922 *********************************************************************/
2923 jb_err client_ua(struct client_state *csp, char **header)
2925 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2927 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2935 /*********************************************************************
2937 * Function : client_from
2939 * Description : Handle the "from" config setting properly.
2940 * Called from `sed'.
2943 * 1 : csp = Current client state (buffers, headers, etc...)
2944 * 2 : header = On input, pointer to header to modify.
2945 * On output, pointer to the modified header, or NULL
2946 * to remove the header. This function frees the
2947 * original string if necessary.
2949 * Returns : JB_ERR_OK on success, or
2950 * JB_ERR_MEMORY on out-of-memory error.
2952 *********************************************************************/
2953 jb_err client_from(struct client_state *csp, char **header)
2957 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2964 newval = csp->action->string[ACTION_STRING_FROM];
2967 * Are we blocking the e-mail address?
2969 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2971 log_error(LOG_LEVEL_HEADER, "crunched From!");
2975 log_error(LOG_LEVEL_HEADER, " modified");
2977 *header = strdup("From: ");
2978 string_append(header, newval);
2980 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2984 /*********************************************************************
2986 * Function : client_send_cookie
2988 * Description : Crunches the "cookie" header if necessary.
2989 * Called from `sed'.
2991 * XXX: Stupid name, doesn't send squat.
2994 * 1 : csp = Current client state (buffers, headers, etc...)
2995 * 2 : header = On input, pointer to header to modify.
2996 * On output, pointer to the modified header, or NULL
2997 * to remove the header. This function frees the
2998 * original string if necessary.
3000 * Returns : JB_ERR_OK on success, or
3001 * JB_ERR_MEMORY on out-of-memory error.
3003 *********************************************************************/
3004 jb_err client_send_cookie(struct client_state *csp, char **header)
3006 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3008 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3016 /*********************************************************************
3018 * Function : client_x_forwarded
3020 * Description : Handle the "x-forwarded-for" config setting properly,
3021 * also used in the add_client_headers list. Called from `sed'.
3024 * 1 : csp = Current client state (buffers, headers, etc...)
3025 * 2 : header = On input, pointer to header to modify.
3026 * On output, pointer to the modified header, or NULL
3027 * to remove the header. This function frees the
3028 * original string if necessary.
3030 * Returns : JB_ERR_OK on success, or
3031 * JB_ERR_MEMORY on out-of-memory error.
3033 *********************************************************************/
3034 jb_err client_x_forwarded(struct client_state *csp, char **header)
3036 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3038 /* Save it so we can re-add it later */
3039 freez(csp->x_forwarded);
3040 csp->x_forwarded = *header;
3043 * Always set *header = NULL, since this information
3044 * will be sent at the end of the header.
3051 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3058 /*********************************************************************
3060 * Function : client_max_forwards
3062 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3063 * from the value of the Max-Forwards header field.
3066 * 1 : csp = Current client state (buffers, headers, etc...)
3067 * 2 : header = On input, pointer to header to modify.
3068 * On output, pointer to the modified header, or NULL
3069 * to remove the header. This function frees the
3070 * original string if necessary.
3072 * Returns : JB_ERR_OK on success, or
3073 * JB_ERR_MEMORY on out-of-memory error.
3075 *********************************************************************/
3076 jb_err client_max_forwards(struct client_state *csp, char **header)
3080 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3081 (0 == strcmpic(csp->http->gpc, "options")))
3083 assert(*(*header+12) == ':');
3084 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3086 if (max_forwards > 0)
3088 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3089 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3090 csp->http->gpc, max_forwards);
3092 else if (max_forwards < 0)
3094 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3100 * Not supposed to be reached. direct_response() which
3101 * was already called earlier in chat() should have
3102 * intercepted the request.
3104 log_error(LOG_LEVEL_ERROR,
3105 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3106 assert(max_forwards != 0);
3111 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3120 /*********************************************************************
3122 * Function : client_host
3124 * Description : If the request URI did not contain host and
3125 * port information, parse and evaluate the Host
3128 * Also, kill ill-formed HOST: headers as sent by
3129 * Apple's iTunes software when used with a proxy.
3132 * 1 : csp = Current client state (buffers, headers, etc...)
3133 * 2 : header = On input, pointer to header to modify.
3134 * On output, pointer to the modified header, or NULL
3135 * to remove the header. This function frees the
3136 * original string if necessary.
3138 * Returns : JB_ERR_OK on success, or
3139 * JB_ERR_MEMORY on out-of-memory error.
3141 *********************************************************************/
3142 jb_err client_host(struct client_state *csp, char **header)
3147 * If the header field name is all upper-case, chances are that it's
3148 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3149 * not a problem -- they are regenerated later.
3151 if ((*header)[1] == 'O')
3153 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3158 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3159 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3162 if (NULL == (p = strdup((*header)+6)))
3164 return JB_ERR_MEMORY;
3167 if (NULL == (q = strdup(p)))
3170 return JB_ERR_MEMORY;
3173 freez(csp->http->hostport);
3174 csp->http->hostport = p;
3175 freez(csp->http->host);
3176 csp->http->host = q;
3177 q = strchr(csp->http->host, ':');
3180 /* Terminate hostname and evaluate port string */
3182 csp->http->port = atoi(q);
3186 csp->http->port = csp->http->ssl ? 443 : 80;
3189 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3190 csp->http->hostport, csp->http->host, csp->http->port);
3193 /* Signal client_host_adder() to return right away */
3194 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3199 /*********************************************************************
3201 * Function : client_if_modified_since
3203 * Description : Remove or modify the If-Modified-Since header.
3206 * 1 : csp = Current client state (buffers, headers, etc...)
3207 * 2 : header = On input, pointer to header to modify.
3208 * On output, pointer to the modified header, or NULL
3209 * to remove the header. This function frees the
3210 * original string if necessary.
3212 * Returns : JB_ERR_OK on success, or
3213 * JB_ERR_MEMORY on out-of-memory error.
3215 *********************************************************************/
3216 jb_err client_if_modified_since(struct client_state *csp, char **header)
3219 #ifdef HAVE_GMTIME_R
3222 struct tm *timeptr = NULL;
3226 long int hours, minutes, seconds;
3230 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3233 * The client got an error message because of a temporary problem,
3234 * the problem is gone and the client now tries to revalidate our
3235 * error message on the real server. The revalidation would always
3236 * end with the transmission of the whole document and there is
3237 * no need to expose the bogus If-Modified-Since header.
3239 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3242 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3244 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3246 if ((0 == strcmpic(newval, "block")))
3248 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3251 else /* add random value */
3253 const char *header_time = *header + sizeof("If-Modified-Since:");
3255 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3257 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3262 rtime = strtol(newval, &endptr, 0);
3265 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3266 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3273 rtime = pick_from_range(rtime);
3277 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3280 tm += rtime * (negative ? -1 : 1);
3281 #ifdef HAVE_GMTIME_R
3282 timeptr = gmtime_r(&tm, &gmt);
3283 #elif FEATURE_PTHREAD
3284 pthread_mutex_lock(&gmtime_mutex);
3285 timeptr = gmtime(&tm);
3286 pthread_mutex_unlock(&gmtime_mutex);
3288 timeptr = gmtime(&tm);
3290 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3293 *header = strdup("If-Modified-Since: ");
3294 string_append(header, newheader);
3296 if (*header == NULL)
3298 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3299 return JB_ERR_MEMORY;
3302 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3304 hours = rtime / 3600;
3305 minutes = rtime / 60 % 60;
3306 seconds = rtime % 60;
3308 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3309 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3310 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3319 /*********************************************************************
3321 * Function : client_if_none_match
3323 * Description : Remove the If-None-Match header.
3326 * 1 : csp = Current client state (buffers, headers, etc...)
3327 * 2 : header = On input, pointer to header to modify.
3328 * On output, pointer to the modified header, or NULL
3329 * to remove the header. This function frees the
3330 * original string if necessary.
3332 * Returns : JB_ERR_OK on success, or
3333 * JB_ERR_MEMORY on out-of-memory error.
3335 *********************************************************************/
3336 jb_err client_if_none_match(struct client_state *csp, char **header)
3338 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3340 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3347 /*********************************************************************
3349 * Function : client_x_filter
3351 * Description : Disables filtering if the client set "X-Filter: No".
3352 * Called from `sed'.
3355 * 1 : csp = Current client state (buffers, headers, etc...)
3356 * 2 : header = On input, pointer to header to modify.
3357 * On output, pointer to the modified header, or NULL
3358 * to remove the header. This function frees the
3359 * original string if necessary.
3361 * Returns : JB_ERR_OK on success
3363 *********************************************************************/
3364 jb_err client_x_filter(struct client_state *csp, char **header)
3366 if ( 0 == strcmpic(*header, "X-Filter: No"))
3368 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3370 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3374 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3376 log_error(LOG_LEVEL_HEADER,
3377 "force-text-mode overruled the client's request to fetch without filtering!");
3381 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3382 csp->flags |= CSP_FLAG_NO_FILTERING;
3383 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3385 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3392 /* the following functions add headers directly to the header list */
3394 /*********************************************************************
3396 * Function : client_host_adder
3398 * Description : Adds the Host: header field if it is missing.
3399 * Called from `sed'.
3402 * 1 : csp = Current client state (buffers, headers, etc...)
3404 * Returns : JB_ERR_OK on success, or
3405 * JB_ERR_MEMORY on out-of-memory error.
3407 *********************************************************************/
3408 jb_err client_host_adder(struct client_state *csp)
3413 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3415 /* Header already set by the client, nothing to do. */
3419 if ( !csp->http->hostport || !*(csp->http->hostport))
3421 /* XXX: When does this happen and why is it OK? */
3422 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3427 * remove 'user:pass@' from 'proto://user:pass@host'
3429 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3435 p = csp->http->hostport;
3438 /* XXX: Just add it, we already made sure that it will be unique */
3439 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3440 err = enlist_unique_header(csp->headers, "Host", p);
3446 /*********************************************************************
3448 * Function : client_cookie_adder
3450 * Description : Used in the add_client_headers list to add "wafers".
3451 * Called from `sed'.
3454 * 1 : csp = Current client state (buffers, headers, etc...)
3456 * Returns : JB_ERR_OK on success, or
3457 * JB_ERR_MEMORY on out-of-memory error.
3459 *********************************************************************/
3460 jb_err client_cookie_adder(struct client_state *csp)
3463 struct list_entry *wafer;
3464 struct list_entry *wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3467 if (NULL == wafer_list)
3473 tmp = strdup("Cookie: ");
3475 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3477 if (wafer != wafer_list)
3479 /* As this isn't the first wafer, we need a delimiter. */
3480 string_append(&tmp, "; ");
3482 string_join(&tmp, cookie_encode(wafer->str));
3487 return JB_ERR_MEMORY;
3490 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3491 err = enlist(csp->headers, tmp);
3497 /*********************************************************************
3499 * Function : client_accept_encoding_adder
3501 * Description : Add an Accept-Encoding header to the client's request
3502 * that disables compression if the action applies, and
3503 * the header is not already there. Called from `sed'.
3504 * Note: For HTTP/1.0, the absence of the header is enough.
3507 * 1 : csp = Current client state (buffers, headers, etc...)
3509 * Returns : JB_ERR_OK on success, or
3510 * JB_ERR_MEMORY on out-of-memory error.
3512 *********************************************************************/
3513 jb_err client_accept_encoding_adder(struct client_state *csp)
3515 assert(0); /* Not in use */
3517 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3518 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3520 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3527 /*********************************************************************
3529 * Function : client_xtra_adder
3531 * Description : Used in the add_client_headers list. Called from `sed'.
3534 * 1 : csp = Current client state (buffers, headers, etc...)
3536 * Returns : JB_ERR_OK on success, or
3537 * JB_ERR_MEMORY on out-of-memory error.
3539 *********************************************************************/
3540 jb_err client_xtra_adder(struct client_state *csp)
3542 struct list_entry *lst;
3545 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3546 lst ; lst = lst->next)
3548 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3549 err = enlist(csp->headers, lst->str);
3561 /*********************************************************************
3563 * Function : client_x_forwarded_adder
3565 * Description : Used in the add_client_headers list. Called from `sed'.
3568 * 1 : csp = Current client state (buffers, headers, etc...)
3570 * Returns : JB_ERR_OK on success, or
3571 * JB_ERR_MEMORY on out-of-memory error.
3573 *********************************************************************/
3574 jb_err client_x_forwarded_adder(struct client_state *csp)
3579 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3584 if (csp->x_forwarded)
3586 p = strdup(csp->x_forwarded);
3587 string_append(&p, ", ");
3591 p = strdup("X-Forwarded-For: ");
3593 string_append(&p, csp->ip_addr_str);
3597 return JB_ERR_MEMORY;
3600 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3601 err = enlist(csp->headers, p);
3608 /*********************************************************************
3610 * Function : connection_close_adder
3612 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3613 * support. Adds a "Connection: close" header to csp->headers
3614 * unless the header was already present. Called from `sed'.
3616 * FIXME: This whole function shouldn't be neccessary!
3619 * 1 : csp = Current client state (buffers, headers, etc...)
3621 * Returns : JB_ERR_OK on success, or
3622 * JB_ERR_MEMORY on out-of-memory error.
3624 *********************************************************************/
3625 jb_err connection_close_adder(struct client_state *csp)
3627 const unsigned int flags = csp->flags;
3630 * Return right away if
3632 * - we're parsing server headers and the server header
3633 * "Connection: close" is already set, or if
3635 * - we're parsing client headers and the client header
3636 * "Connection: close" is already set.
3638 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3639 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3640 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3641 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3646 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3648 return enlist(csp->headers, "Connection: close");
3652 /*********************************************************************
3654 * Function : server_http
3656 * Description : - Save the HTTP Status into csp->http->status
3657 * - Set CT_TABOO to prevent filtering if the answer
3658 * is a partial range (HTTP status 206)
3659 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3663 * 1 : csp = Current client state (buffers, headers, etc...)
3664 * 2 : header = On input, pointer to header to modify.
3665 * On output, pointer to the modified header, or NULL
3666 * to remove the header. This function frees the
3667 * original string if necessary.
3669 * Returns : JB_ERR_OK on success, or
3670 * JB_ERR_MEMORY on out-of-memory error.
3672 *********************************************************************/
3673 jb_err server_http(struct client_state *csp, char **header)
3675 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3676 if (csp->http->status == 206)
3678 csp->content_type = CT_TABOO;
3681 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3684 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3691 /*********************************************************************
3693 * Function : server_set_cookie
3695 * Description : Handle the server "cookie" header properly.
3696 * Log cookie to the jar file. Then "crunch",
3697 * accept or rewrite it to a session cookie.
3698 * Called from `sed'.
3700 * TODO: Allow the user to specify a new expiration
3701 * time to cause the cookie to expire even before the
3702 * browser is closed.
3705 * 1 : csp = Current client state (buffers, headers, etc...)
3706 * 2 : header = On input, pointer to header to modify.
3707 * On output, pointer to the modified header, or NULL
3708 * to remove the header. This function frees the
3709 * original string if necessary.
3711 * Returns : JB_ERR_OK on success, or
3712 * JB_ERR_MEMORY on out-of-memory error.
3714 *********************************************************************/
3715 jb_err server_set_cookie(struct client_state *csp, char **header)
3722 #ifdef FEATURE_COOKIE_JAR
3723 if (csp->config->jar)
3726 * Write timestamp into outbuf.
3728 * Complex because not all OSs have tm_gmtoff or
3729 * the %z field in strftime()
3731 char tempbuf[ BUFFER_SIZE ];
3733 #ifdef HAVE_LOCALTIME_R
3734 tm_now = *localtime_r(&now, &tm_now);
3735 #elif FEATURE_PTHREAD
3736 pthread_mutex_lock(&localtime_mutex);
3737 tm_now = *localtime (&now);
3738 pthread_mutex_unlock(&localtime_mutex);
3740 tm_now = *localtime (&now);
3742 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3744 /* strlen("set-cookie: ") = 12 */
3745 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3747 #endif /* def FEATURE_COOKIE_JAR */
3749 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3751 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3754 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3756 /* Flag whether or not to log a message */
3759 /* A variable to store the tag we're working on */
3762 /* Skip "Set-Cookie:" (11 characters) in header */
3763 cur_tag = *header + 11;
3765 /* skip whitespace between "Set-Cookie:" and value */
3766 while (*cur_tag && ijb_isspace(*cur_tag))
3771 /* Loop through each tag in the cookie */
3775 char *next_tag = strchr(cur_tag, ';');
3776 if (next_tag != NULL)
3778 /* Skip the ';' character itself */
3781 /* skip whitespace ";" and start of tag */
3782 while (*next_tag && ijb_isspace(*next_tag))
3789 /* "Next tag" is the end of the string */
3790 next_tag = cur_tag + strlen(cur_tag);
3794 * Check the expiration date to see
3795 * if the cookie is still valid, if yes,
3796 * rewrite it to a session cookie.
3798 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3800 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3802 /* Did we detect the date properly? */
3803 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3806 * Nope, treat it as if it was still valid.
3808 * XXX: Should we remove the whole cookie instead?
3810 log_error(LOG_LEVEL_ERROR,
3811 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3812 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3818 * Yes. Check if the cookie is still valid.
3820 * If the cookie is already expired it's probably
3821 * a delete cookie and even if it isn't, the browser
3822 * will discard it anyway.
3826 * XXX: timegm() isn't available on some AmigaOS
3827 * versions and our replacement doesn't work.
3829 * Our options are to either:
3831 * - disable session-cookies-only completely if timegm
3834 * - to simply remove all expired tags, like it has
3835 * been done until Privoxy 3.0.6 and to live with
3836 * the consequence that it can cause login/logout
3837 * problems on servers that don't validate their
3838 * input properly, or
3840 * - to replace it with mktime in which
3841 * case there is a slight chance of valid cookies
3842 * passing as already expired.
3844 * This is the way it's currently done and it's not
3845 * as bad as it sounds. If the missing GMT offset is
3846 * enough to change the result of the expiration check
3847 * the cookie will be only valid for a few hours
3848 * anyway, which in many cases will be shorter
3849 * than a browser session.
3851 if (cookie_time - now < 0)
3853 log_error(LOG_LEVEL_HEADER,
3854 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3855 /* Just in case some clown sets more then one expiration date */
3861 * Still valid, delete expiration date by copying
3862 * the rest of the string over it.
3864 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3865 * since the behaviour of strcpy is undefined for overlapping
3868 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3870 /* That changed the header, need to issue a log message */
3874 * Note that the next tag has now been moved to *cur_tag,
3875 * so we do not need to update the cur_tag pointer.
3883 /* Move on to next cookie tag */
3890 assert(NULL != *header);
3891 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3900 #ifdef FEATURE_FORCE_LOAD
3901 /*********************************************************************
3903 * Function : strclean
3905 * Description : In-Situ-Eliminate all occurances of substring in
3909 * 1 : string = string to clean
3910 * 2 : substring = substring to eliminate
3912 * Returns : Number of eliminations
3914 *********************************************************************/
3915 int strclean(const char *string, const char *substring)
3921 len = strlen(substring);
3923 while((pos = strstr(string, substring)) != NULL)
3930 while (*p++ != '\0');
3937 #endif /* def FEATURE_FORCE_LOAD */
3939 /*********************************************************************
3941 * Function : parse_header_time
3943 * Description : Parses time formats used in HTTP header strings
3944 * to get the numerical respresentation.
3947 * 1 : header_time = HTTP header time as string.
3948 * 2 : result = storage for header_time in seconds
3950 * Returns : JB_ERR_OK if the time format was recognized, or
3951 * JB_ERR_PARSE otherwise.
3953 *********************************************************************/
3954 jb_err parse_header_time(const char *header_time, time_t *result)
3959 * Zero out gmt to prevent time zone offsets.
3961 * While this is only necessary on some platforms
3962 * (mingw32 for example), I don't know how to
3963 * detect these automatically and doing it everywhere
3966 memset(&gmt, 0, sizeof(gmt));
3968 /* Tue, 02 Jun 2037 20:00:00 */
3969 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3970 /* Tue, 02-Jun-2037 20:00:00 */
3971 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3972 /* Tue, 02-Jun-37 20:00:00 */
3973 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3974 /* Tuesday, 02-Jun-2037 20:00:00 */
3975 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3976 /* Tuesday Jun 02 20:00:00 2037 */
3977 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3979 return JB_ERR_PARSE;
3982 *result = timegm(&gmt);
3988 /*********************************************************************
3990 * Function : get_destination_from_headers
3992 * Description : Parse the "Host:" header to get the request's destination.
3993 * Only needed if the client's request was forcefully
3994 * redirected into Privoxy.
3996 * Code mainly copied from client_host() which is currently
3997 * run too late for this purpose.
4000 * 1 : headers = List of headers (one of them hopefully being
4001 * the "Host:" header)
4002 * 2 : http = storage for the result (host, port and hostport).
4004 * Returns : JB_ERR_MEMORY in case of memory problems,
4005 * JB_ERR_PARSE if the host header couldn't be found,
4006 * JB_ERR_OK otherwise.
4008 *********************************************************************/
4009 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4015 host = get_header_value(headers, "Host:");
4019 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4020 return JB_ERR_PARSE;
4023 if (NULL == (p = strdup((host))))
4025 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4026 return JB_ERR_MEMORY;
4029 if (NULL == (q = strdup(p)))
4032 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4033 return JB_ERR_MEMORY;
4036 freez(http->hostport);
4040 q = strchr(http->host, ':');
4043 /* Terminate hostname and evaluate port string */
4045 http->port = atoi(q);
4049 http->port = http->ssl ? 443 : 80;
4052 /* Rebuild request URL */
4054 http->url = strdup(http->ssl ? "https://" : "http://");
4055 string_append(&http->url, http->hostport);
4056 string_append(&http->url, http->path);
4057 if (http->url == NULL)
4059 return JB_ERR_MEMORY;
4062 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",