1 const char parsers_rcs[] = "$Id: parsers.c,v 1.100 2007/04/30 15:53:11 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.100 2007/04/30 15:53:11 fabiankeil
48 * Make sure filters with dynamic jobs actually use them.
50 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
51 * - Introduce dynamic pcrs jobs that can resolve variables.
52 * - Remove unnecessary update_action_bits_for_all_tags() call.
54 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
55 * - Make tagging based on tags set by earlier taggers
56 * of the same kind possible.
57 * - Log whether or not new tags cause action bits updates
58 * (in which case a matching tag-pattern section exists).
59 * - Log if the user tries to set a tag that is already set.
61 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
62 * Introduce tags as alternative way to specify which
63 * actions apply to a request. At the moment tags can be
64 * created based on client and server headers.
66 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
67 * Log a warning if the content is compressed, filtering is
68 * enabled and Privoxy was compiled without zlib support.
71 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
72 * - Fix warnings when compiled with glibc.
73 * - Don't use crumble() for cookie crunching.
74 * - Move cookie time parsing into parse_header_time().
75 * - Let parse_header_time() return a jb_err code
76 * instead of a pointer that can only be used to
77 * check for NULL anyway.
79 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
80 * - Add better protection against malicious gzip headers.
81 * - Stop logging the first hundred bytes of decompressed content.
82 * It looks like it's working and there is always debug 16.
83 * - Log the content size after decompression in decompress_iob()
84 * instead of pcrs_filter_response().
86 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
87 * - Use dedicated header filter actions instead of abusing "filter".
88 * Replace "filter-client-headers" and "filter-client-headers"
89 * with "server-header-filter" and "client-header-filter".
90 * - Remove filter_client_header() and filter_client_header(),
91 * filter_header() now checks the shiny new
92 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
94 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
95 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
96 * - Handle "Cookie:" and "Connection:" headers a bit smarter
97 * (don't crunch them just to recreate them later on).
98 * - Add another non-standard time format for the cookie
99 * expiration date detection.
100 * - Fix a valgrind warning.
102 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
103 * Improve cookie expiration date detection.
105 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
106 * Don't run server_content_length() the first time
107 * sed() parses server headers; only adjust the
108 * Content-Length header if the page was modified.
110 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
111 * Fix log messages regarding the cookie time format
112 * (cookie and request URL were mixed up).
114 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
115 * - Let decompress_iob()
116 * - not corrupt the content if decompression fails
117 * early. (the first byte(s) were lost).
118 * - use pointer arithmetics with defined outcome for
120 * - Use a different kludge to remember a failed decompression.
122 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
123 * Search for Max-Forwards headers case-insensitive,
124 * don't generate the "501 unsupported" message for invalid
125 * Max-Forwards values and don't increase negative ones.
127 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
128 * - Let server_set_cookie() check the expiration date
129 * of cookies and don't touch the ones that are already
130 * expired. Fixes problems with low quality web applications
131 * as described in BR 932612.
133 * - Adjust comment in client_max_forwards to reality;
134 * remove invalid Max-Forwards headers.
136 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
137 * Stop filter_header() from unintentionally removing
138 * empty header lines that were enlisted by the continue
141 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
142 * - Repeat the request URL before logging any headers.
143 * Makes reading the log easier in case of simultaneous requests.
144 * - If there are more than one Content-Type headers in one request,
145 * use the first one and remove the others.
146 * - Remove "newval" variable in server_content_type().
147 * It's only used once.
149 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
150 * Correct a cast, check inflateEnd() exit code
151 * to see if we have to, replace sprintf calls
154 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
155 * Integrate a modified version of Wil Mahan's
156 * zlib patch (PR #895531).
158 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
159 * Skip empty filter files in filter_header()
160 * but don't ignore the ones that come afterwards.
161 * Fixes BR 1619208, this time for real.
163 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
164 * Reverted parts of my last commit
165 * to keep error handling working.
167 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
168 * Fixed gcc43 conversion warnings.
170 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
171 * Bringing back the "useless" localtime() call
172 * I removed in revision 1.67. On some platforms
173 * it's necessary to prevent time zone offsets.
175 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
176 * Rebuild request URL in get_destination_from_headers()
177 * to make sure redirect{pcrs command} works as expected
178 * for intercepted requests.
180 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
181 * Added get_destination_from_headers().
183 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
184 * Make pthread mutex locking more generic. Instead of
185 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
186 * and use mutex locking unless there is an _r function
187 * available. Better safe than sorry.
189 * Fixes "./configure --disable-pthread" and should result
190 * in less threading-related problems on pthread-using platforms,
191 * but it still doesn't fix BR#1122404.
193 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
194 * The special header "X-Filter: No" now disables
195 * header filtering as well.
197 * Revision 1.73 2006/09/23 13:26:38 roro
198 * Replace TABs by spaces in source code.
200 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
201 * Don't print a log message every time filter_headers is
202 * entered or left. It only creates noise without any real
205 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
206 * Fix +hide-if-modified-since{-n}.
208 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
209 * Have hide-if-modified-since interpret the random
210 * range value as minutes instead of hours. Allows
211 * more fine-grained configuration.
213 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
214 * Always have parse_header_time return a pointer
215 * that actual makes sense, even though we currently
216 * only need it to detect problems.
218 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
219 * Added config option enable-remote-http-toggle
220 * to specify if Privoxy should recognize special
221 * headers (currently only X-Filter) to change its
222 * behaviour. Disabled by default.
224 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
225 * After filtering de-chunked instances, remove
226 * "Transfer-Encoding" header entirely instead of changing
227 * it to "Transfer-Encoding: identity", which is invalid.
228 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
230 * Don't use localtime in parse_header_time. An empty time struct
231 * is good enough, it gets overwritten by strptime anyway.
233 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
234 * Use gmtime_r if available, fallback to gmtime with mutex
235 * protection for MacOSX and use vanilla gmtime for the rest.
237 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
238 * Changed client_referrer to use the right type (size_t) for
239 * hostlenght and to shorten the temporary referrer string with
240 * '\0' instead of adding a useless line break.
242 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
243 * - Back to timegm() using GnuPG's replacement if necessary.
244 * Using mktime() and localtime() could add a on hour offset if
245 * the randomize factor was big enough to lead to a summer/wintertime
248 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
250 * - Moved randomization code into pick_from_range().
252 * - Changed parse_header_time definition.
253 * time_t isn't guaranteed to be signed and
254 * if it isn't, -1 isn't available as error code.
255 * Changed some variable types in client_if_modified_since()
256 * because of the same reason.
258 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
259 * OS/2 compilation compatibility fixups
261 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
262 * Changed include from strptime.c to strptime.h
264 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
265 * Split filter-headers{} into filter-client-headers{}
266 * and filter-server-headers{}.
267 * Added parse_header_time() to share some code.
268 * Replaced timegm() with mktime().
270 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
271 * Windows service integration
273 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
274 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
276 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
277 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
278 * with what was really the latest development (the v_3_0_branch branch)
280 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
281 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
283 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
284 * Add the ability to check jpeg images for invalid
285 * lengths of comment blocks. Defensive strategy
286 * against the exploit:
287 * Microsoft Security Bulletin MS04-028
288 * Buffer Overrun in JPEG Processing (GDI+) Could
289 * Allow Code Execution (833987)
290 * Enabled with +inspect-jpegs in actions files.
292 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
293 * Excluded text/plain objects from filtering. This fixes a
294 * couple of client-crashing, download corruption and
295 * Privoxy performance issues, whose root cause lies in
296 * web servers labelling content of unknown type as text/plain.
298 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
299 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
301 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
302 * Completing the previous change
304 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
305 * Added temporary workaround for bug in PHP < 4.2.3
307 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
308 * 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.
310 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
311 * Fix typo: supressed -> suppressed
313 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
314 * Improved cookie logging
316 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
317 * Added basic support for OPTIONS and TRACE HTTP methods:
318 * - New parser function client_max_forwards which decrements
319 * the Max-Forwards HTTP header field of OPTIONS and TRACE
320 * requests by one before forwarding
321 * - New parser function client_host which extracts the host
322 * and port information from the HTTP header field if the
323 * request URI was not absolute
324 * - Don't crumble and re-add the Host: header, but only generate
325 * and append if missing
327 * Revision 1.56 2002/05/12 15:34:22 jongfoster
328 * Fixing typo in a comment
330 * Revision 1.55 2002/05/08 16:01:07 oes
331 * Optimized add_to_iob:
332 * - Use realloc instead of malloc(), memcpy(), free()
333 * - Expand to powers of two if possible, to get
334 * O(log n) reallocs instead of O(n).
335 * - Moved check for buffer limit here from chat
336 * - Report failure via returncode
338 * Revision 1.54 2002/04/02 15:03:16 oes
339 * Tiny code cosmetics
341 * Revision 1.53 2002/03/26 22:29:55 swa
342 * we have a new homepage!
344 * Revision 1.52 2002/03/24 13:25:43 swa
345 * name change related issues
347 * Revision 1.51 2002/03/13 00:27:05 jongfoster
350 * Revision 1.50 2002/03/12 01:45:35 oes
351 * More verbose logging
353 * Revision 1.49 2002/03/09 20:03:52 jongfoster
354 * - Making various functions return int rather than size_t.
355 * (Undoing a recent change). Since size_t is unsigned on
356 * Windows, functions like read_socket that return -1 on
357 * error cannot return a size_t.
359 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
360 * crashes, and also frequently caused JB to jump to 100%
361 * CPU and stay there. (Because it thought it had just
362 * read ((unsigned)-1) == 4Gb of data...)
364 * - The signature of write_socket has changed, it now simply
365 * returns success=0/failure=nonzero.
367 * - Trying to get rid of a few warnings --with-debug on
368 * Windows, I've introduced a new type "jb_socket". This is
369 * used for the socket file descriptors. On Windows, this
370 * is SOCKET (a typedef for unsigned). Everywhere else, it's
371 * an int. The error value can't be -1 any more, so it's
372 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
373 * Windows it maps to the #define INVALID_SOCKET.)
375 * - The signature of bind_port has changed.
377 * Revision 1.48 2002/03/07 03:46:53 oes
378 * Fixed compiler warnings etc
380 * Revision 1.47 2002/02/20 23:15:13 jongfoster
381 * Parsing functions now handle out-of-memory gracefully by returning
384 * Revision 1.46 2002/01/17 21:03:47 jongfoster
385 * Moving all our URL and URL pattern parsing code to urlmatch.c.
387 * Revision 1.45 2002/01/09 14:33:03 oes
388 * Added support for localtime_r.
390 * Revision 1.44 2001/12/14 01:22:54 steudten
391 * Remove 'user:pass@' from 'proto://user:pass@host' for the
392 * new added header 'Host: ..'. (See Req ID 491818)
394 * Revision 1.43 2001/11/23 00:26:38 jongfoster
395 * Fixing two really stupid errors in my previous commit
397 * Revision 1.42 2001/11/22 21:59:30 jongfoster
398 * Adding code to handle +no-cookies-keep
400 * Revision 1.41 2001/11/05 23:43:05 steudten
401 * Add time+date to log files.
403 * Revision 1.40 2001/10/26 20:13:09 jongfoster
404 * ctype.h is needed in Windows, too.
406 * Revision 1.39 2001/10/26 17:40:04 oes
407 * Introduced get_header_value()
408 * Removed http->user_agent, csp->referrer and csp->accept_types
409 * Removed client_accept()
411 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
412 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
413 * threads to call select() simultaneously. So, it's time to do a real, live,
414 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
415 * (native). Both versions will work, but using __OS2__ offers multi-threading.
417 * Revision 1.37 2001/10/23 21:36:02 jongfoster
418 * Documenting sed()'s error behaviou (doc change only)
420 * Revision 1.36 2001/10/13 12:51:51 joergs
421 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
422 * force-load), instead crumble Host: and add it (again) in client_host_adder
423 * (in case we get a HTTP/1.0 request without Host: header and forward it to
424 * a HTTP/1.1 server/proxy).
426 * Revision 1.35 2001/10/09 22:39:21 jongfoster
427 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
430 * Revision 1.34 2001/10/07 18:50:55 oes
431 * Added server_content_encoding, renamed server_transfer_encoding
433 * Revision 1.33 2001/10/07 18:04:49 oes
434 * Changed server_http11 to server_http and its pattern to "HTTP".
435 * Additional functionality: it now saves the HTTP status into
436 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
438 * Revision 1.32 2001/10/07 15:43:28 oes
439 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
440 * client_te and client_accept_encoding_adder, triggered by the new
441 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
442 * changed to allow only identity and chunked, and the TE header is
443 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
445 * parse_http_request no longer does anything than parsing. The rewriting
446 * of http->cmd and version mangling are gone. It now also recognizes
447 * the put and delete methods and saves the url in http->url. Removed
450 * renamed content_type and content_length to have the server_ prefix
452 * server_content_type now only works if csp->content_type != CT_TABOO
454 * added server_transfer_encoding, which
455 * - Sets CT_TABOO to prohibit filtering if encoding compresses
456 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
457 * - Change from "chunked" to "identity" if body was chunked
458 * but has been de-chunked for filtering.
460 * added server_content_md5 which crunches any Content-MD5 headers
461 * if the body was modified.
463 * made server_http11 conditional on +downgrade action
465 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
467 * Revision 1.31 2001/10/05 14:25:02 oes
468 * Crumble Keep-Alive from Server
470 * Revision 1.30 2001/09/29 12:56:03 joergs
471 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
473 * Revision 1.29 2001/09/24 21:09:24 jongfoster
474 * Fixing 2 memory leaks that Guy spotted, where the paramater to
475 * enlist() was not being free()d.
477 * Revision 1.28 2001/09/22 16:32:28 jongfoster
478 * Removing unused #includes.
480 * Revision 1.27 2001/09/20 15:45:25 steudten
482 * add casting from size_t to int for printf()
483 * remove local variable shadow s2
485 * Revision 1.26 2001/09/16 17:05:14 jongfoster
486 * Removing unused #include showarg.h
488 * Revision 1.25 2001/09/16 13:21:27 jongfoster
489 * Changes to use new list functions.
491 * Revision 1.24 2001/09/13 23:05:50 jongfoster
492 * Changing the string paramater to the header parsers a "const".
494 * Revision 1.23 2001/09/12 18:08:19 steudten
496 * In parse_http_request() header rewriting miss the host value, so
497 * from http://www.mydomain.com the result was just " / " not
498 * http://www.mydomain.com/ in case we forward.
500 * Revision 1.22 2001/09/10 10:58:53 oes
501 * Silenced compiler warnings
503 * Revision 1.21 2001/07/31 14:46:00 oes
504 * - Persistant connections now suppressed
505 * - sed() no longer appends empty header to csp->headers
507 * Revision 1.20 2001/07/30 22:08:36 jongfoster
508 * Tidying up #defines:
509 * - All feature #defines are now of the form FEATURE_xxx
510 * - Permanently turned off WIN_GUI_EDIT
511 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
513 * Revision 1.19 2001/07/25 17:21:54 oes
514 * client_uagent now saves copy of User-Agent: header value
516 * Revision 1.18 2001/07/13 14:02:46 oes
517 * - Included fix to repair broken HTTP requests that
518 * don't contain a path, not even '/'.
519 * - Removed all #ifdef PCRS
520 * - content_type now always inspected and classified as
521 * text, gif or other.
522 * - formatting / comments
524 * Revision 1.17 2001/06/29 21:45:41 oes
525 * Indentation, CRLF->LF, Tab-> Space
527 * Revision 1.16 2001/06/29 13:32:42 oes
529 * - Adapted free_http_request
530 * - Removed logentry from cancelled commit
532 * Revision 1.15 2001/06/03 19:12:38 oes
533 * deleted const struct interceptors
535 * Revision 1.14 2001/06/01 18:49:17 jongfoster
536 * Replaced "list_share" with "list" - the tiny memory gain was not
537 * worth the extra complexity.
539 * Revision 1.13 2001/05/31 21:30:33 jongfoster
540 * Removed list code - it's now in list.[ch]
541 * Renamed "permission" to "action", and changed many features
542 * to use the actions file rather than the global config.
544 * Revision 1.12 2001/05/31 17:33:13 oes
548 * Revision 1.11 2001/05/29 20:11:19 joergs
549 * '/ * inside comment' warning removed.
551 * Revision 1.10 2001/05/29 09:50:24 jongfoster
552 * Unified blocklist/imagelist/permissionslist.
553 * File format is still under discussion, but the internal changes
556 * Also modified interceptor behaviour:
557 * - We now intercept all URLs beginning with one of the following
558 * prefixes (and *only* these prefixes):
560 * * http://ijbswa.sf.net/config/
561 * * http://ijbswa.sourceforge.net/config/
562 * - New interceptors "home page" - go to http://i.j.b/ to see it.
563 * - Internal changes so that intercepted and fast redirect pages
564 * are not replaced with an image.
565 * - Interceptors now have the option to send a binary page direct
566 * to the client. (i.e. ijb-send-banner uses this)
567 * - Implemented show-url-info interceptor. (Which is why I needed
568 * the above interceptors changes - a typical URL is
569 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
570 * The previous mechanism would not have intercepted that, and
571 * if it had been intercepted then it then it would have replaced
574 * Revision 1.9 2001/05/28 17:26:33 jongfoster
575 * Fixing segfault if last header was crunched.
576 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
577 * can use the cross-platform sprintf() instead.)
579 * Revision 1.8 2001/05/27 22:17:04 oes
581 * - re_process_buffer no longer writes the modified buffer
582 * to the client, which was very ugly. It now returns the
583 * buffer, which it is then written by chat.
585 * - content_length now adjusts the Content-Length: header
586 * for modified documents rather than crunch()ing it.
587 * (Length info in csp->content_length, which is 0 for
588 * unmodified documents)
590 * - For this to work, sed() is called twice when filtering.
592 * Revision 1.7 2001/05/27 13:19:06 oes
593 * Patched Joergs solution for the content-length in.
595 * Revision 1.6 2001/05/26 13:39:32 jongfoster
596 * Only crunches Content-Length header if applying RE filtering.
597 * Without this fix, Microsoft Windows Update wouldn't work.
599 * Revision 1.5 2001/05/26 00:28:36 jongfoster
600 * Automatic reloading of config file.
601 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
602 * Most of the global variables have been moved to a new
603 * struct configuration_spec, accessed through csp->config->globalname
604 * Most of the globals remaining are used by the Win32 GUI.
606 * Revision 1.4 2001/05/22 18:46:04 oes
608 * - Enabled filtering banners by size rather than URL
609 * by adding patterns that replace all standard banner
610 * sizes with the "Junkbuster" gif to the re_filterfile
612 * - Enabled filtering WebBugs by providing a pattern
613 * which kills all 1x1 images
615 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
616 * which is selected by the (nonstandard and therefore
617 * capital) letter 'U' in the option string.
618 * It causes the quantifiers to be ungreedy by default.
619 * Appending a ? turns back to greedy (!).
621 * - Added a new interceptor ijb-send-banner, which
622 * sends back the "Junkbuster" gif. Without imagelist or
623 * MSIE detection support, or if tinygif = 1, or the
624 * URL isn't recognized as an imageurl, a lame HTML
625 * explanation is sent instead.
627 * - Added new feature, which permits blocking remote
628 * script redirects and firing back a local redirect
630 * The feature is conditionally compiled, i.e. it
631 * can be disabled with --disable-fast-redirects,
632 * plus it must be activated by a "fast-redirects"
633 * line in the config file, has its own log level
634 * and of course wants to be displayed by show-proxy-args
635 * Note: Boy, all the #ifdefs in 1001 locations and
636 * all the fumbling with configure.in and acconfig.h
637 * were *way* more work than the feature itself :-(
639 * - Because a generic redirect template was needed for
640 * this, tinygif = 3 now uses the same.
642 * - Moved GIFs, and other static HTTP response templates
647 * - Removed some >400 CRs again (Jon, you really worked
650 * Revision 1.3 2001/05/20 01:21:20 jongfoster
651 * Version 2.9.4 checkin.
652 * - Merged popupfile and cookiefile, and added control over PCRS
653 * filtering, in new "permissionsfile".
654 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
655 * file error you now get a message box (in the Win32 GUI) rather
656 * than the program exiting with no explanation.
657 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
659 * - Removed tabs from "config"
660 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
661 * - Bumped up version number.
663 * Revision 1.2 2001/05/17 23:02:36 oes
664 * - Made referrer option accept 'L' as a substitute for '§'
666 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
667 * Initial import of version 2.9.3 source tree
670 *********************************************************************/
677 #include <sys/types.h>
687 * Convince GNU's libc to provide a strptime prototype.
690 #endif /*__GLIBC__ */
697 #if !defined(_WIN32) && !defined(__OS2__)
703 #ifdef FEATURE_PTHREAD
705 /* jcc.h is for mutex semapores only */
706 #endif /* def FEATURE_PTHREAD */
712 #include "jbsockets.h"
713 #include "miscutil.h"
718 #ifndef HAVE_STRPTIME
719 #include "strptime.h"
722 const char parsers_h_rcs[] = PARSERS_H_VERSION;
724 /* Fix a problem with Solaris. There should be no effect on other
726 * Solaris's isspace() is a macro which uses its argument directly
727 * as an array index. Therefore we need to make sure that high-bit
728 * characters generate +ve values, and ideally we also want to make
729 * the argument match the declared parameter type of "int".
731 * Why did they write a character function that can't take a simple
732 * "char" argument? Doh!
734 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
735 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
737 jb_err header_tagger(struct client_state *csp, char *header);
738 jb_err scan_headers(struct client_state *csp);
740 const struct parsers client_patterns[] = {
741 { "referer:", 8, client_referrer },
742 { "user-agent:", 11, client_uagent },
743 { "ua-", 3, client_ua },
744 { "from:", 5, client_from },
745 { "cookie:", 7, client_send_cookie },
746 { "x-forwarded-for:", 16, client_x_forwarded },
747 { "Accept-Encoding:", 16, client_accept_encoding },
748 { "TE:", 3, client_te },
749 { "Host:", 5, client_host },
750 { "if-modified-since:", 18, client_if_modified_since },
751 { "Keep-Alive:", 11, crumble },
752 { "connection:", 11, connection },
753 { "proxy-connection:", 17, crumble },
754 { "max-forwards:", 13, client_max_forwards },
755 { "Accept-Language:", 16, client_accept_language },
756 { "if-none-match:", 14, client_if_none_match },
757 { "X-Filter:", 9, client_x_filter },
758 { "*", 0, crunch_client_header },
759 { "*", 0, filter_header },
763 const struct parsers server_patterns[] = {
764 { "HTTP", 4, server_http },
765 { "set-cookie:", 11, server_set_cookie },
766 { "connection:", 11, connection },
767 { "Content-Type:", 13, server_content_type },
768 { "Content-MD5:", 12, server_content_md5 },
769 { "Content-Encoding:", 17, server_content_encoding },
770 { "Transfer-Encoding:", 18, server_transfer_coding },
771 { "Keep-Alive:", 11, crumble },
772 { "content-disposition:", 20, server_content_disposition },
773 { "Last-Modified:", 14, server_last_modified },
774 { "*", 0, crunch_server_header },
775 { "*", 0, filter_header },
779 const struct parsers server_patterns_light[] = {
780 { "Content-Length:", 15, server_content_length },
781 { "Transfer-Encoding:", 18, server_transfer_coding },
783 { "Content-Encoding:", 17, server_content_encoding },
784 #endif /* def FEATURE_ZLIB */
788 const add_header_func_ptr add_client_headers[] = {
791 client_x_forwarded_adder,
793 /* Temporarily disabled: client_accept_encoding_adder, */
794 connection_close_adder,
799 const add_header_func_ptr add_server_headers[] = {
800 connection_close_adder,
804 /*********************************************************************
806 * Function : flush_socket
808 * Description : Write any pending "buffered" content.
811 * 1 : fd = file descriptor of the socket to read
812 * 2 : csp = Current client state (buffers, headers, etc...)
814 * Returns : On success, the number of bytes written are returned (zero
815 * indicates nothing was written). On error, -1 is returned,
816 * and errno is set appropriately. If count is zero and the
817 * file descriptor refers to a regular file, 0 will be
818 * returned without causing any other effect. For a special
819 * file, the results are not portable.
821 *********************************************************************/
822 int flush_socket(jb_socket fd, struct client_state *csp)
824 struct iob *iob = csp->iob;
825 int len = iob->eod - iob->cur;
832 if (write_socket(fd, iob->cur, (size_t)len))
836 iob->eod = iob->cur = iob->buf;
842 /*********************************************************************
844 * Function : add_to_iob
846 * Description : Add content to the buffered page, expanding the
847 * buffer if necessary.
850 * 1 : csp = Current client state (buffers, headers, etc...)
851 * 2 : buf = holds the content to be added to the page
852 * 3 : n = number of bytes to be added
854 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
855 * or buffer limit reached.
857 *********************************************************************/
858 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
860 struct iob *iob = csp->iob;
861 size_t used, offset, need, want;
864 if (n <= 0) return JB_ERR_OK;
866 used = (size_t)(iob->eod - iob->buf);
867 offset = (size_t)(iob->cur - iob->buf);
868 need = used + (size_t)n + 1;
871 * If the buffer can't hold the new data, extend it first.
872 * Use the next power of two if possible, else use the actual need.
874 if (need > csp->config->buffer_limit)
876 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
877 return JB_ERR_MEMORY;
880 if (need > iob->size)
882 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
884 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
888 else if (NULL != (p = (char *)realloc(iob->buf, need)))
894 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
895 return JB_ERR_MEMORY;
898 /* Update the iob pointers */
899 iob->cur = p + offset;
904 /* copy the new data into the iob buffer */
905 memcpy(iob->eod, buf, (size_t)n);
907 /* point to the end of the data */
910 /* null terminate == cheap insurance */
919 /*********************************************************************
921 * Function : decompress_iob
923 * Description : Decompress buffered page, expanding the
924 * buffer as necessary. csp->iob->cur
925 * should point to the the beginning of the
926 * compressed data block.
929 * 1 : csp = Current client state (buffers, headers, etc...)
931 * Returns : JB_ERR_OK on success,
932 * JB_ERR_MEMORY if out-of-memory limit reached, and
933 * JB_ERR_COMPRESS if error decompressing buffer.
935 *********************************************************************/
936 jb_err decompress_iob(struct client_state *csp)
938 char *buf; /* new, uncompressed buffer */
939 char *cur; /* Current iob position (to keep the original
940 * iob->cur unmodified if we return early) */
941 size_t bufsize; /* allocated size of the new buffer */
942 size_t old_size; /* Content size before decompression */
943 size_t skip_size; /* Number of bytes at the beginning of the iob
944 that we should NOT decompress. */
945 int status; /* return status of the inflate() call */
946 z_stream zstr; /* used by calls to zlib */
948 assert(csp->iob->cur - csp->iob->buf > 0);
949 assert(csp->iob->eod - csp->iob->cur > 0);
951 bufsize = csp->iob->size;
952 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
953 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
960 * This is to protect the parsing of gzipped data,
961 * but it should(?) be valid for deflated data also.
963 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
964 return JB_ERR_COMPRESS;
967 if (csp->content_type & CT_GZIP)
970 * Our task is slightly complicated by the facts that data
971 * compressed by gzip does not include a zlib header, and
972 * that there is no easily accessible interface in zlib to
973 * handle a gzip header. We strip off the gzip header by
974 * hand, and later inform zlib not to expect a header.
978 * Strip off the gzip header. Please see RFC 1952 for more
979 * explanation of the appropriate fields.
981 if ((*cur++ != (char)0x1f)
982 || (*cur++ != (char)0x8b)
983 || (*cur++ != Z_DEFLATED))
985 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
986 return JB_ERR_COMPRESS;
992 * XXX: These magic numbers should be replaced
993 * with macros to give a better idea what they do.
997 /* The gzip header has reserved bits set; bail out. */
998 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
999 return JB_ERR_COMPRESS;
1003 /* Skip extra fields if necessary. */
1007 * Skip a given number of bytes, specified
1008 * as a 16-bit little-endian value.
1011 * XXX: This code used to be:
1013 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1015 * which I had to change into:
1017 * cur += *cur++ + (*cur++ << 8);
1019 * at which point gcc43 finally noticed that the value
1020 * of cur is undefined (it depends on which of the
1021 * summands is evaluated first).
1023 * I haven't come across a site where this
1024 * code is actually executed yet, but I hope
1028 skip_bytes = *cur++;
1029 skip_bytes = *cur++ << 8;
1031 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1034 * The number of bytes to skip should be positive
1035 * and we'd like to stay in the buffer.
1037 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1039 log_error (LOG_LEVEL_ERROR,
1040 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1042 return JB_ERR_COMPRESS;
1044 log_error (LOG_LEVEL_INFO,
1045 "Skipping %d bytes for gzip compression. Does this sound right?",
1050 /* Skip the filename if necessary. */
1053 /* A null-terminated string is supposed to follow. */
1054 while (*cur++ && (cur < csp->iob->eod));
1058 /* Skip the comment if necessary. */
1061 /* A null-terminated string is supposed to follow. */
1062 while (*cur++ && (cur < csp->iob->eod));
1065 /* Skip the CRC if necessary. */
1071 if (cur >= csp->iob->eod)
1074 * If the current position pointer reached or passed
1075 * the buffer end, we were obviously tricked to skip
1078 log_error (LOG_LEVEL_ERROR,
1079 "Malformed gzip header detected. Aborting decompression.");
1080 return JB_ERR_COMPRESS;
1084 else if (csp->content_type & CT_DEFLATE)
1087 * XXX: The debug level should be lowered
1088 * before the next stable release.
1090 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1092 * In theory (that is, according to RFC 1950), deflate-compressed
1093 * data should begin with a two-byte zlib header and have an
1094 * adler32 checksum at the end. It seems that in practice only
1095 * the raw compressed data is sent. Note that this means that
1096 * we are not RFC 1950-compliant here, but the advantage is that
1097 * this actually works. :)
1099 * We add a dummy null byte to tell zlib where the data ends,
1100 * and later inform it not to expect a header.
1102 * Fortunately, add_to_iob() has thoughtfully null-terminated
1103 * the buffer; we can just increment the end pointer to include
1110 log_error (LOG_LEVEL_ERROR,
1111 "Unable to determine compression format for decompression");
1112 return JB_ERR_COMPRESS;
1115 /* Set up the fields required by zlib. */
1116 zstr.next_in = (Bytef *)cur;
1117 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1118 zstr.zalloc = Z_NULL;
1119 zstr.zfree = Z_NULL;
1120 zstr.opaque = Z_NULL;
1123 * Passing -MAX_WBITS to inflateInit2 tells the library
1124 * that there is no zlib header.
1126 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1128 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1129 return JB_ERR_COMPRESS;
1133 * Next, we allocate new storage for the inflated data.
1134 * We don't modify the existing iob yet, so in case there
1135 * is error in decompression we can recover gracefully.
1137 buf = zalloc (bufsize);
1140 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1141 return JB_ERR_MEMORY;
1144 assert(bufsize >= skip_size);
1145 memcpy(buf, csp->iob->buf, skip_size);
1146 zstr.avail_out = bufsize - skip_size;
1147 zstr.next_out = (Bytef *)buf + skip_size;
1149 /* Try to decompress the whole stream in one shot. */
1150 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1152 /* We need to allocate more memory for the output buffer. */
1154 char *tmpbuf; /* used for realloc'ing the buffer */
1155 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1158 * If zlib wants more data then there's a problem, because
1159 * the complete compressed file should have been buffered.
1161 if (0 == zstr.avail_in)
1163 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1164 return JB_ERR_COMPRESS;
1168 * If we tried the limit and still didn't have enough
1169 * memory, just give up.
1171 if (bufsize == csp->config->buffer_limit)
1173 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1174 return JB_ERR_MEMORY;
1177 /* Try doubling the buffer size each time. */
1180 /* Don't exceed the buffer limit. */
1181 if (bufsize > csp->config->buffer_limit)
1183 bufsize = csp->config->buffer_limit;
1186 /* Try to allocate the new buffer. */
1187 tmpbuf = realloc(buf, bufsize);
1190 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1192 return JB_ERR_MEMORY;
1196 char *oldnext_out = (char *)zstr.next_out;
1199 * Update the fields for inflate() to use the new
1200 * buffer, which may be in a location different from
1203 zstr.avail_out += bufsize - oldbufsize;
1204 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1207 * Compare with an uglier method of calculating these values
1208 * that doesn't require the extra oldbufsize variable.
1210 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1211 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1212 assert(zstr.avail_out > 0);
1218 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1220 log_error(LOG_LEVEL_ERROR,
1221 "Inconsistent stream state after decompression: %s", zstr.msg);
1223 * XXX: Intentionally no return.
1225 * According to zlib.h, Z_STREAM_ERROR is returned
1226 * "if the stream state was inconsistent".
1228 * I assume in this case inflate()'s status
1229 * would also be something different than Z_STREAM_END
1230 * so this check should be redundant, but lets see.
1234 if (status != Z_STREAM_END)
1236 /* We failed to decompress the stream. */
1237 log_error(LOG_LEVEL_ERROR,
1238 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1239 return JB_ERR_COMPRESS;
1243 * Finally, we can actually update the iob, since the
1244 * decompression was successful. First, free the old
1247 freez(csp->iob->buf);
1249 /* Now, update the iob to use the new buffer. */
1250 csp->iob->buf = buf;
1251 csp->iob->cur = csp->iob->buf + skip_size;
1252 csp->iob->eod = (char *)zstr.next_out;
1253 csp->iob->size = bufsize;
1256 * Make sure the new uncompressed iob obeys some minimal
1257 * consistency conditions.
1259 if ((csp->iob->buf < csp->iob->cur)
1260 && (csp->iob->cur <= csp->iob->eod)
1261 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1263 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1266 log_error(LOG_LEVEL_RE_FILTER,
1267 "Decompression successful. Old size: %d, new size: %d.",
1268 old_size, new_size);
1272 /* zlib thinks this is OK, so lets do the same. */
1273 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1278 /* It seems that zlib did something weird. */
1279 log_error(LOG_LEVEL_ERROR,
1280 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1281 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1282 csp->iob->eod, csp->iob->buf + csp->iob->size);
1283 return JB_ERR_COMPRESS;
1289 #endif /* defined(FEATURE_ZLIB) */
1292 /*********************************************************************
1294 * Function : get_header
1296 * Description : This (odd) routine will parse the csp->iob
1299 * 1 : csp = Current client state (buffers, headers, etc...)
1301 * Returns : Any one of the following:
1303 * 1) a pointer to a dynamically allocated string that contains a header line
1304 * 2) NULL indicating that the end of the header was reached
1305 * 3) "" indicating that the end of the iob was reached before finding
1306 * a complete header line.
1308 *********************************************************************/
1309 char *get_header(struct client_state *csp)
1315 if ((iob->cur == NULL)
1316 || ((p = strchr(iob->cur, '\n')) == NULL))
1318 return(""); /* couldn't find a complete header */
1323 ret = strdup(iob->cur);
1326 /* FIXME No way to handle error properly */
1327 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1332 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1334 /* is this a blank line (i.e. the end of the header) ? */
1346 /*********************************************************************
1348 * Function : get_header_value
1350 * Description : Get the value of a given header from a chained list
1351 * of header lines or return NULL if no such header is
1352 * present in the list.
1355 * 1 : header_list = pointer to list
1356 * 2 : header_name = string with name of header to look for.
1357 * Trailing colon required, capitalization
1360 * Returns : NULL if not found, else value of header
1362 *********************************************************************/
1363 char *get_header_value(const struct list *header_list, const char *header_name)
1365 struct list_entry *cur_entry;
1369 assert(header_list);
1370 assert(header_name);
1371 length = strlen(header_name);
1373 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1377 if (!strncmpic(cur_entry->str, header_name, length))
1380 * Found: return pointer to start of value
1382 ret = (char *) (cur_entry->str + length);
1383 while (*ret && ijb_isspace(*ret)) ret++;
1397 /*********************************************************************
1399 * Function : scan_headers
1401 * Description : Scans headers, applies tags and updates action bits.
1404 * 1 : csp = Current client state (buffers, headers, etc...)
1406 * Returns : JB_ERR_OK
1408 *********************************************************************/
1409 jb_err scan_headers(struct client_state *csp)
1411 struct list_entry *h; /* Header */
1412 jb_err err = JB_ERR_OK;
1414 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1416 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1418 /* Header crunch()ed in previous run? -> ignore */
1419 if (h->str == NULL) continue;
1420 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1421 err = header_tagger(csp, h->str);
1428 /*********************************************************************
1432 * Description : add, delete or modify lines in the HTTP header streams.
1433 * On entry, it receives a linked list of headers space
1434 * that was allocated dynamically (both the list nodes
1435 * and the header contents).
1437 * As a side effect it frees the space used by the original
1441 * 1 : pats = list of patterns to match against headers
1442 * 2 : more_headers = list of functions to add more
1443 * headers (client or server)
1444 * 3 : csp = Current client state (buffers, headers, etc...)
1446 * Returns : Single pointer to a fully formed header, or NULL
1447 * on out-of-memory error.
1449 *********************************************************************/
1450 char *sed(const struct parsers pats[],
1451 const add_header_func_ptr more_headers[],
1452 struct client_state *csp)
1454 struct list_entry *p;
1455 const struct parsers *v;
1456 const add_header_func_ptr *f;
1457 jb_err err = JB_ERR_OK;
1461 * If filtering is enabled, sed is run twice,
1462 * but most of the work needs to be done only once.
1464 first_run = (more_headers != NULL ) ? 1 : 0;
1466 if (first_run) /* Parse and print */
1470 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1472 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1474 /* Header crunch()ed in previous run? -> ignore */
1475 if (p->str == NULL) continue;
1477 /* Does the current parser handle this header? */
1478 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1480 err = v->parser(csp, (char **)&(p->str));
1484 /* place any additional headers on the csp->headers list */
1485 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1490 else /* Parse only */
1493 * The second run is only needed if the body was modified
1494 * and the content-lenght has changed.
1496 if (strncmpic(csp->http->cmd, "HEAD", 4))
1498 /*XXX: Code duplication */
1499 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1501 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1503 /* Header crunch()ed in previous run? -> ignore */
1504 if (p->str == NULL) continue;
1506 /* Does the current parser handle this header? */
1507 if (strncmpic(p->str, v->str, v->len) == 0)
1509 err = v->parser(csp, (char **)&(p->str));
1516 if (err != JB_ERR_OK)
1521 return list_to_text(csp->headers);
1526 /*********************************************************************
1528 * Function : header_tagger
1530 * Description : Executes all text substitutions from applying
1531 * tag actions and saves the result as tag.
1533 * XXX: Shares enough code with filter_header() and
1534 * pcrs_filter_response() to warrant some helper functions.
1537 * 1 : csp = Current client state (buffers, headers, etc...)
1538 * 2 : header = Header that is used as tagger input
1540 * Returns : JB_ERR_OK on success and always succeeds
1542 *********************************************************************/
1543 jb_err header_tagger(struct client_state *csp, char *header)
1545 int wanted_filter_type;
1546 int multi_action_index;
1550 struct file_list *fl;
1551 struct re_filterfile_spec *b;
1552 struct list_entry *tag_name;
1554 int found_filters = 0;
1555 const size_t header_length = strlen(header);
1557 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1559 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1560 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1564 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1565 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1568 /* Check if there are any filters */
1569 for (i = 0; i < MAX_AF_FILES; i++)
1582 if (0 == found_filters)
1584 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1588 for (i = 0; i < MAX_AF_FILES; i++)
1591 if ((NULL == fl) || (NULL == fl->f))
1594 * Either there are no filter files
1595 * left, or this filter file just
1596 * contains no valid filters.
1598 * Continue to be sure we don't miss
1599 * valid filter files that are chained
1600 * after empty or invalid ones.
1605 /* For all filters, */
1606 for (b = fl->f; b; b = b->next)
1608 if (b->type != wanted_filter_type)
1610 /* skip the ones we don't care about, */
1613 /* leaving only taggers that could apply, of which we use the ones, */
1614 for (tag_name = csp->action->multi[multi_action_index]->first;
1615 NULL != tag_name; tag_name = tag_name->next)
1617 /* that do apply, and */
1618 if (strcmp(b->name, tag_name->str) == 0)
1620 char *modified_tag = NULL;
1622 size_t size = header_length;
1623 pcrs_job *joblist = b->joblist;
1625 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1627 if (NULL == joblist)
1629 log_error(LOG_LEVEL_RE_FILTER,
1630 "Tagger %s has empty joblist. Nothing to do.", b->name);
1634 /* execute their pcrs_joblist on the header. */
1635 for (job = joblist; NULL != job; job = job->next)
1637 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1641 /* Success, continue with the modified version. */
1650 /* Tagger doesn't match */
1653 /* Regex failure, log it but continue anyway. */
1654 log_error(LOG_LEVEL_ERROR,
1655 "Problems with tagger \'%s\' and header \'%s\': %s",
1656 b->name, *header, pcrs_strerror(hits));
1658 freez(modified_tag);
1662 if (b->dynamic) pcrs_free_joblist(joblist);
1664 /* If this tagger matched */
1670 * There is to technical limitation which makes
1671 * it impossible to use empty tags, but I assume
1672 * no one would do it intentionally.
1675 log_error(LOG_LEVEL_INFO,
1676 "Tagger \'%s\' created an empty tag. Ignored.",
1681 if (!list_contains_item(csp->tags, tag))
1683 if (JB_ERR_OK != enlist(csp->tags, tag))
1685 log_error(LOG_LEVEL_ERROR,
1686 "Insufficient memory to add tag \'%s\', "
1687 "based on tagger \'%s\' and header \'%s\'",
1688 tag, b->name, *header);
1692 char *action_message;
1694 * update the action bits right away, to make
1695 * tagging based on tags set by earlier taggers
1696 * of the same kind possible.
1698 if (update_action_bits_for_tag(csp, tag))
1700 action_message = "Action bits updated accordingly.";
1704 action_message = "No action bits update necessary.";
1707 log_error(LOG_LEVEL_HEADER,
1708 "Tagger \'%s\' added tag \'%s\'. %s",
1709 b->name, tag, action_message);
1714 /* XXX: Is this log-worthy? */
1715 log_error(LOG_LEVEL_HEADER,
1716 "Tagger \'%s\' didn't add tag \'%s\'. "
1717 "Tag already present", b->name, tag);
1720 } /* if the tagger matched */
1721 } /* if the tagger applies */
1722 } /* for every tagger that could apply */
1723 } /* for all filters */
1724 } /* for all filter files */
1729 /* here begins the family of parser functions that reformat header lines */
1731 /*********************************************************************
1733 * Function : filter_header
1735 * Description : Executes all text substitutions from all applying
1736 * +(server|client)-header-filter actions on the header.
1737 * Most of the code was copied from pcrs_filter_response,
1738 * including the rather short variable names
1741 * 1 : csp = Current client state (buffers, headers, etc...)
1742 * 2 : header = On input, pointer to header to modify.
1743 * On output, pointer to the modified header, or NULL
1744 * to remove the header. This function frees the
1745 * original string if necessary.
1747 * Returns : JB_ERR_OK on success and always succeeds
1749 *********************************************************************/
1750 jb_err filter_header(struct client_state *csp, char **header)
1754 size_t size = strlen(*header);
1756 char *newheader = NULL;
1759 struct file_list *fl;
1760 struct re_filterfile_spec *b;
1761 struct list_entry *filtername;
1763 int i, found_filters = 0;
1764 int wanted_filter_type;
1765 int multi_action_index;
1767 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1769 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1770 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1774 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1775 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1779 * Need to check the set of re_filterfiles...
1781 for (i = 0; i < MAX_AF_FILES; i++)
1794 if (0 == found_filters)
1796 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1800 for (i = 0; i < MAX_AF_FILES; i++)
1803 if ((NULL == fl) || (NULL == fl->f))
1806 * Either there are no filter files
1807 * left, or this filter file just
1808 * contains no valid filters.
1810 * Continue to be sure we don't miss
1811 * valid filter files that are chained
1812 * after empty or invalid ones.
1817 * For all applying +filter actions, look if a filter by that
1818 * name exists and if yes, execute its pcrs_joblist on the
1821 for (b = fl->f; b; b = b->next)
1823 if (b->type != wanted_filter_type)
1825 /* Skip other filter types */
1829 for (filtername = csp->action->multi[multi_action_index]->first;
1830 filtername ; filtername = filtername->next)
1832 if (strcmp(b->name, filtername->str) == 0)
1834 int current_hits = 0;
1835 pcrs_job *joblist = b->joblist;
1837 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1839 if (NULL == joblist)
1841 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1845 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1846 *header, size, b->name);
1848 /* Apply all jobs from the joblist */
1849 for (job = joblist; NULL != job; job = job->next)
1851 matches = pcrs_execute(job, *header, size, &newheader, &size);
1854 current_hits += matches;
1855 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1857 *header = newheader;
1859 else if ( 0 == matches )
1861 /* Filter doesn't change header */
1867 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1868 *header, b->name, pcrs_strerror(matches));
1869 if( newheader != NULL)
1871 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1877 if (b->dynamic) pcrs_free_joblist(joblist);
1879 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1880 hits += current_hits;
1887 * Additionally checking for hits is important because if
1888 * the continue hack is triggered, server headers can
1889 * arrive empty to separate multiple heads from each other.
1891 if ((0 == size) && hits)
1893 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1901 /*********************************************************************
1903 * Function : connection
1905 * Description : Makes sure that the value of the Connection: header
1906 * is "close" and signals connection_close_adder
1910 * 1 : csp = Current client state (buffers, headers, etc...)
1911 * 2 : header = On input, pointer to header to modify.
1912 * On output, pointer to the modified header, or NULL
1913 * to remove the header. This function frees the
1914 * original string if necessary.
1916 * Returns : JB_ERR_OK on success, or
1917 * JB_ERR_MEMORY on out-of-memory error.
1919 *********************************************************************/
1920 jb_err connection(struct client_state *csp, char **header)
1922 char *old_header = *header;
1924 /* Do we have a 'Connection: close' header? */
1925 if (strcmpic(*header, "Connection: close"))
1927 /* No, create one */
1928 *header = strdup("Connection: close");
1931 return JB_ERR_MEMORY;
1933 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1937 /* Signal connection_close_adder() to return early. */
1938 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1940 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
1944 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
1951 /*********************************************************************
1953 * Function : crumble
1955 * Description : This is called if a header matches a pattern to "crunch"
1958 * 1 : csp = Current client state (buffers, headers, etc...)
1959 * 2 : header = On input, pointer to header to modify.
1960 * On output, pointer to the modified header, or NULL
1961 * to remove the header. This function frees the
1962 * original string if necessary.
1964 * Returns : JB_ERR_OK on success, or
1965 * JB_ERR_MEMORY on out-of-memory error.
1967 *********************************************************************/
1968 jb_err crumble(struct client_state *csp, char **header)
1970 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1975 /*********************************************************************
1977 * Function : crunch_server_header
1979 * Description : Crunch server header if it matches a string supplied by the
1980 * user. Called from `sed'.
1983 * 1 : csp = Current client state (buffers, headers, etc...)
1984 * 2 : header = On input, pointer to header to modify.
1985 * On output, pointer to the modified header, or NULL
1986 * to remove the header. This function frees the
1987 * original string if necessary.
1989 * Returns : JB_ERR_OK on success and always succeeds
1991 *********************************************************************/
1992 jb_err crunch_server_header(struct client_state *csp, char **header)
1994 const char *crunch_pattern;
1996 /* Do we feel like crunching? */
1997 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1999 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2001 /* Is the current header the lucky one? */
2002 if (strstr(*header, crunch_pattern))
2004 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2013 /*********************************************************************
2015 * Function : server_content_type
2017 * Description : Set the content-type for filterable types (text/.*,
2018 * .*xml.*, javascript and image/gif) unless filtering has been
2019 * forbidden (CT_TABOO) while parsing earlier headers.
2020 * NOTE: Since text/plain is commonly used by web servers
2021 * for files whose correct type is unknown, we don't
2022 * set CT_TEXT for it.
2025 * 1 : csp = Current client state (buffers, headers, etc...)
2026 * 2 : header = On input, pointer to header to modify.
2027 * On output, pointer to the modified header, or NULL
2028 * to remove the header. This function frees the
2029 * original string if necessary.
2031 * Returns : JB_ERR_OK on success, or
2032 * JB_ERR_MEMORY on out-of-memory error.
2034 *********************************************************************/
2035 jb_err server_content_type(struct client_state *csp, char **header)
2037 /* Remove header if it isn't the first Content-Type header */
2038 if(csp->content_type && (csp->content_type != CT_TABOO))
2041 * Another, slightly slower, way to see if
2042 * we already parsed another Content-Type header.
2044 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2046 log_error(LOG_LEVEL_ERROR,
2047 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2054 if (!(csp->content_type & CT_TABOO))
2056 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2057 || strstr(*header, "xml")
2058 || strstr(*header, "application/x-javascript"))
2060 csp->content_type |= CT_TEXT;
2062 else if (strstr(*header, " image/gif"))
2064 csp->content_type |= CT_GIF;
2066 else if (strstr(*header, " image/jpeg"))
2068 csp->content_type |= CT_JPEG;
2072 csp->content_type = 0;
2076 * Are we enabling text mode by force?
2078 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2081 * Do we really have to?
2083 if (csp->content_type & CT_TEXT)
2085 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2089 csp->content_type |= CT_TEXT;
2090 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2094 * Are we messing with the content type?
2096 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2099 * Make sure the user doesn't accidently
2100 * change the content type of binary documents.
2102 if (csp->content_type & CT_TEXT)
2105 *header = strdup("Content-Type: ");
2106 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2110 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2111 return JB_ERR_MEMORY;
2113 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2117 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2118 "Enable force-text-mode if you know what you're doing.", *header);
2125 /*********************************************************************
2127 * Function : server_transfer_coding
2129 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2130 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2131 * - Remove header if body was chunked but has been
2132 * de-chunked for filtering.
2135 * 1 : csp = Current client state (buffers, headers, etc...)
2136 * 2 : header = On input, pointer to header to modify.
2137 * On output, pointer to the modified header, or NULL
2138 * to remove the header. This function frees the
2139 * original string if necessary.
2141 * Returns : JB_ERR_OK on success, or
2142 * JB_ERR_MEMORY on out-of-memory error.
2144 *********************************************************************/
2145 jb_err server_transfer_coding(struct client_state *csp, char **header)
2148 * Turn off pcrs and gif filtering if body compressed
2150 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2154 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2156 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2157 csp->http->cmd, *header);
2158 #endif /* def FEATURE_ZLIB */
2159 csp->content_type = CT_TABOO;
2163 * Raise flag if body chunked
2165 if (strstr(*header, "chunked"))
2167 csp->flags |= CSP_FLAG_CHUNKED;
2170 * If the body was modified, it has been de-chunked first
2171 * and the header must be removed.
2173 * FIXME: If there is more than one transfer encoding,
2174 * only the "chunked" part should be removed here.
2176 if (csp->flags & CSP_FLAG_MODIFIED)
2178 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2187 /*********************************************************************
2189 * Function : server_content_encoding
2191 * Description : This function is run twice for each request,
2192 * unless FEATURE_ZLIB and filtering are disabled.
2194 * The first run is used to check if the content
2195 * is compressed, if FEATURE_ZLIB is disabled
2196 * filtering is then disabled as well, if FEATURE_ZLIB
2197 * is enabled the content is marked for decompression.
2199 * The second run is used to remove the Content-Encoding
2200 * header if the decompression was successful.
2203 * 1 : csp = Current client state (buffers, headers, etc...)
2204 * 2 : header = On input, pointer to header to modify.
2205 * On output, pointer to the modified header, or NULL
2206 * to remove the header. This function frees the
2207 * original string if necessary.
2209 * Returns : JB_ERR_OK on success, or
2210 * JB_ERR_MEMORY on out-of-memory error.
2212 *********************************************************************/
2213 jb_err server_content_encoding(struct client_state *csp, char **header)
2216 if ((csp->flags & CSP_FLAG_MODIFIED)
2217 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2220 * We successfully decompressed the content,
2221 * and have to clean the header now, so the
2222 * client no longer expects compressed data..
2224 * XXX: There is a difference between cleaning
2225 * and removing it completely.
2227 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2230 else if (strstr(*header, "gzip"))
2232 /* Mark for gzip decompression */
2233 csp->content_type |= CT_GZIP;
2235 else if (strstr(*header, "deflate"))
2237 /* Mark for zlib decompression */
2238 csp->content_type |= CT_DEFLATE;
2240 else if (strstr(*header, "compress"))
2243 * We can't decompress this; therefore we can't filter
2246 csp->content_type |= CT_TABOO;
2248 #else /* !defined(FEATURE_ZLIB) */
2249 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2252 * Body is compressed, turn off pcrs and gif filtering.
2254 csp->content_type |= CT_TABOO;
2257 * Log a warning if the user expects the content to be filtered.
2259 if ((csp->rlist != NULL) &&
2260 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2262 log_error(LOG_LEVEL_INFO,
2263 "Compressed content detected, content filtering disabled. "
2264 "Consider recompiling Privoxy with zlib support or "
2265 "enable the prevent-compression action.");
2268 #endif /* defined(FEATURE_ZLIB) */
2275 /*********************************************************************
2277 * Function : server_content_length
2279 * Description : Adjust Content-Length header if we modified
2283 * 1 : csp = Current client state (buffers, headers, etc...)
2284 * 2 : header = On input, pointer to header to modify.
2285 * On output, pointer to the modified header, or NULL
2286 * to remove the header. This function frees the
2287 * original string if necessary.
2289 * Returns : JB_ERR_OK on success, or
2290 * JB_ERR_MEMORY on out-of-memory error.
2292 *********************************************************************/
2293 jb_err server_content_length(struct client_state *csp, char **header)
2295 const size_t max_header_length = 80;
2297 /* Regenerate header if the content was modified. */
2298 if (csp->flags & CSP_FLAG_MODIFIED)
2301 *header = (char *) zalloc(max_header_length);
2302 if (*header == NULL)
2304 return JB_ERR_MEMORY;
2307 snprintf(*header, max_header_length, "Content-Length: %d",
2308 (int)csp->content_length);
2309 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2310 (int)csp->content_length);
2317 /*********************************************************************
2319 * Function : server_content_md5
2321 * Description : Crumble any Content-MD5 headers if the document was
2322 * modified. FIXME: Should we re-compute instead?
2325 * 1 : csp = Current client state (buffers, headers, etc...)
2326 * 2 : header = On input, pointer to header to modify.
2327 * On output, pointer to the modified header, or NULL
2328 * to remove the header. This function frees the
2329 * original string if necessary.
2331 * Returns : JB_ERR_OK on success, or
2332 * JB_ERR_MEMORY on out-of-memory error.
2334 *********************************************************************/
2335 jb_err server_content_md5(struct client_state *csp, char **header)
2337 if (csp->flags & CSP_FLAG_MODIFIED)
2339 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2346 /*********************************************************************
2348 * Function : server_content_disposition
2350 * Description : If enabled, blocks or modifies the "content-disposition" header.
2351 * Called from `sed'.
2354 * 1 : csp = Current client state (buffers, headers, etc...)
2355 * 2 : header = On input, pointer to header to modify.
2356 * On output, pointer to the modified header, or NULL
2357 * to remove the header. This function frees the
2358 * original string if necessary.
2360 * Returns : JB_ERR_OK on success, or
2361 * JB_ERR_MEMORY on out-of-memory error.
2363 *********************************************************************/
2364 jb_err server_content_disposition(struct client_state *csp, char **header)
2369 * Are we messing with the content-disposition header?
2371 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2377 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2379 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2382 * Blocking content-disposition header
2384 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2391 * Replacing content-disposition header
2394 *header = strdup("content-disposition: ");
2395 string_append(header, newval);
2397 if (*header == NULL)
2399 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2403 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2406 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2409 /*********************************************************************
2411 * Function : server_last_modified
2413 * Description : Changes Last-Modified header to the actual date
2414 * to help hide-if-modified-since.
2415 * Called from `sed'.
2418 * 1 : csp = Current client state (buffers, headers, etc...)
2419 * 2 : header = On input, pointer to header to modify.
2420 * On output, pointer to the modified header, or NULL
2421 * to remove the header. This function frees the
2422 * original string if necessary.
2424 * Returns : JB_ERR_OK on success, or
2425 * JB_ERR_MEMORY on out-of-memory error.
2427 *********************************************************************/
2428 jb_err server_last_modified(struct client_state *csp, char **header)
2431 char buf[BUFFER_SIZE];
2434 #ifdef HAVE_GMTIME_R
2437 struct tm *timeptr = NULL;
2438 time_t now, last_modified;
2440 long int days, hours, minutes, seconds;
2443 * Are we messing with the Last-Modified header?
2445 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2451 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2453 if (0 == strcmpic(newval, "block") )
2456 * Blocking Last-Modified header. Useless but why not.
2458 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2462 else if (0 == strcmpic(newval, "reset-to-request-time"))
2465 * Setting Last-Modified Header to now.
2467 get_http_time(0, buf);
2469 *header = strdup("Last-Modified: ");
2470 string_append(header, buf);
2472 if (*header == NULL)
2474 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2478 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2481 else if (0 == strcmpic(newval, "randomize"))
2483 const char *header_time = *header + sizeof("Last-Modified:");
2485 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2487 #ifdef HAVE_GMTIME_R
2488 timeptr = gmtime_r(&now, &gmt);
2489 #elif FEATURE_PTHREAD
2490 pthread_mutex_lock(&gmtime_mutex);
2491 timeptr = gmtime(&now);
2492 pthread_mutex_unlock(&gmtime_mutex);
2494 timeptr = gmtime(&now);
2496 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2498 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2503 rtime = (long int)difftime(now, last_modified);
2506 rtime = pick_from_range(rtime);
2507 last_modified += rtime;
2508 #ifdef HAVE_GMTIME_R
2509 timeptr = gmtime_r(&last_modified, &gmt);
2510 #elif FEATURE_PTHREAD
2511 pthread_mutex_lock(&gmtime_mutex);
2512 timeptr = gmtime(&last_modified);
2513 pthread_mutex_unlock(&gmtime_mutex);
2515 timeptr = gmtime(&last_modified);
2517 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2519 *header = strdup("Last-Modified: ");
2520 string_append(header, newheader);
2522 if (*header == NULL)
2524 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2525 return JB_ERR_MEMORY;
2528 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2530 days = rtime / (3600 * 24);
2531 hours = rtime / 3600 % 24;
2532 minutes = rtime / 60 % 60;
2533 seconds = rtime % 60;
2535 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2536 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2537 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2542 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2551 /*********************************************************************
2553 * Function : client_accept_encoding
2555 * Description : Rewrite the client's Accept-Encoding header so that
2556 * if doesn't allow compression, if the action applies.
2557 * Note: For HTTP/1.0 the absence of the header is enough.
2560 * 1 : csp = Current client state (buffers, headers, etc...)
2561 * 2 : header = On input, pointer to header to modify.
2562 * On output, pointer to the modified header, or NULL
2563 * to remove the header. This function frees the
2564 * original string if necessary.
2566 * Returns : JB_ERR_OK on success, or
2567 * JB_ERR_MEMORY on out-of-memory error.
2569 *********************************************************************/
2570 jb_err client_accept_encoding(struct client_state *csp, char **header)
2572 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2574 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2578 /* Temporarily disable the correct behaviour to
2579 * work around a PHP bug.
2581 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2583 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2584 * if (*header == NULL)
2586 * return JB_ERR_MEMORY;
2597 /*********************************************************************
2599 * Function : client_te
2601 * Description : Rewrite the client's TE header so that
2602 * if doesn't allow compression, if the action applies.
2605 * 1 : csp = Current client state (buffers, headers, etc...)
2606 * 2 : header = On input, pointer to header to modify.
2607 * On output, pointer to the modified header, or NULL
2608 * to remove the header. This function frees the
2609 * original string if necessary.
2611 * Returns : JB_ERR_OK on success, or
2612 * JB_ERR_MEMORY on out-of-memory error.
2614 *********************************************************************/
2615 jb_err client_te(struct client_state *csp, char **header)
2617 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2620 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2626 /*********************************************************************
2628 * Function : client_referrer
2630 * Description : Handle the "referer" config setting properly.
2631 * Called from `sed'.
2634 * 1 : csp = Current client state (buffers, headers, etc...)
2635 * 2 : header = On input, pointer to header to modify.
2636 * On output, pointer to the modified header, or NULL
2637 * to remove the header. This function frees the
2638 * original string if necessary.
2640 * Returns : JB_ERR_OK on success, or
2641 * JB_ERR_MEMORY on out-of-memory error.
2643 *********************************************************************/
2644 jb_err client_referrer(struct client_state *csp, char **header)
2651 #ifdef FEATURE_FORCE_LOAD
2652 /* Since the referrer can include the prefix even
2653 * if the request itself is non-forced, we must
2654 * clean it unconditionally
2656 strclean(*header, FORCE_PREFIX);
2657 #endif /* def FEATURE_FORCE_LOAD */
2660 * Are we sending referer?
2662 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2667 newval = csp->action->string[ACTION_STRING_REFERER];
2669 if ((0 != strcmpic(newval, "conditional-block")))
2673 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2678 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2681 else if (0 == strcmpic(newval, "conditional-block"))
2684 * Block referer if host has changed.
2687 if (NULL == (host = strdup(csp->http->hostport)))
2690 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2691 return JB_ERR_MEMORY;
2693 if (NULL == (referer = strdup(*header)))
2697 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2698 return JB_ERR_MEMORY;
2700 hostlenght = strlen(host);
2701 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2703 /*Shorten referer to make sure the referer is blocked
2704 *if www.example.org/www.example.com-shall-see-the-referer/
2705 *links to www.example.com/
2707 referer[hostlenght+17] = '\0';
2709 if ( 0 == strstr(referer, host)) /*Host has changed*/
2711 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2716 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2722 else if (0 != strcmpic(newval, "forge"))
2725 * We have a specific (fixed) referer we want to send.
2727 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2729 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2731 *header = strdup("Referer: ");
2732 string_append(header, newval);
2733 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2735 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2740 * Forge a referer as http://[hostname:port of REQUEST]/
2741 * to fool stupid checks for in-site links
2744 *header = strdup("Referer: http://");
2745 string_append(header, csp->http->hostport);
2746 string_append(header, "/");
2747 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2749 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2753 /*********************************************************************
2755 * Function : client_accept_language
2757 * Description : Handle the "Accept-Language" config setting properly.
2758 * Called from `sed'.
2761 * 1 : csp = Current client state (buffers, headers, etc...)
2762 * 2 : header = On input, pointer to header to modify.
2763 * On output, pointer to the modified header, or NULL
2764 * to remove the header. This function frees the
2765 * original string if necessary.
2767 * Returns : JB_ERR_OK on success, or
2768 * JB_ERR_MEMORY on out-of-memory error.
2770 *********************************************************************/
2771 jb_err client_accept_language(struct client_state *csp, char **header)
2776 * Are we messing with the Accept-Language?
2778 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2780 /*I don't think so*/
2784 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2786 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2789 * Blocking Accept-Language header
2791 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2798 * Replacing Accept-Language header
2801 *header = strdup("Accept-Language: ");
2802 string_append(header, newval);
2804 if (*header == NULL)
2806 log_error(LOG_LEVEL_ERROR,
2807 "Insufficent memory. Accept-Language header crunched without replacement.");
2811 log_error(LOG_LEVEL_HEADER,
2812 "Accept-Language header crunched and replaced with: %s", *header);
2815 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2818 /*********************************************************************
2820 * Function : crunch_client_header
2822 * Description : Crunch client header if it matches a string supplied by the
2823 * user. Called from `sed'.
2826 * 1 : csp = Current client state (buffers, headers, etc...)
2827 * 2 : header = On input, pointer to header to modify.
2828 * On output, pointer to the modified header, or NULL
2829 * to remove the header. This function frees the
2830 * original string if necessary.
2832 * Returns : JB_ERR_OK on success and always succeeds
2834 *********************************************************************/
2835 jb_err crunch_client_header(struct client_state *csp, char **header)
2837 const char *crunch_pattern;
2839 /* Do we feel like crunching? */
2840 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2842 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2844 /* Is the current header the lucky one? */
2845 if (strstr(*header, crunch_pattern))
2847 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2855 /*********************************************************************
2857 * Function : client_uagent
2859 * Description : Handle the "user-agent" config setting properly
2860 * and remember its original value to enable browser
2861 * bug workarounds. Called from `sed'.
2864 * 1 : csp = Current client state (buffers, headers, etc...)
2865 * 2 : header = On input, pointer to header to modify.
2866 * On output, pointer to the modified header, or NULL
2867 * to remove the header. This function frees the
2868 * original string if necessary.
2870 * Returns : JB_ERR_OK on success, or
2871 * JB_ERR_MEMORY on out-of-memory error.
2873 *********************************************************************/
2874 jb_err client_uagent(struct client_state *csp, char **header)
2878 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2883 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2890 *header = strdup("User-Agent: ");
2891 string_append(header, newval);
2893 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2895 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2898 /*********************************************************************
2900 * Function : client_ua
2902 * Description : Handle "ua-" headers properly. Called from `sed'.
2905 * 1 : csp = Current client state (buffers, headers, etc...)
2906 * 2 : header = On input, pointer to header to modify.
2907 * On output, pointer to the modified header, or NULL
2908 * to remove the header. This function frees the
2909 * original string if necessary.
2911 * Returns : JB_ERR_OK on success, or
2912 * JB_ERR_MEMORY on out-of-memory error.
2914 *********************************************************************/
2915 jb_err client_ua(struct client_state *csp, char **header)
2917 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2919 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2927 /*********************************************************************
2929 * Function : client_from
2931 * Description : Handle the "from" config setting properly.
2932 * Called from `sed'.
2935 * 1 : csp = Current client state (buffers, headers, etc...)
2936 * 2 : header = On input, pointer to header to modify.
2937 * On output, pointer to the modified header, or NULL
2938 * to remove the header. This function frees the
2939 * original string if necessary.
2941 * Returns : JB_ERR_OK on success, or
2942 * JB_ERR_MEMORY on out-of-memory error.
2944 *********************************************************************/
2945 jb_err client_from(struct client_state *csp, char **header)
2949 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2956 newval = csp->action->string[ACTION_STRING_FROM];
2959 * Are we blocking the e-mail address?
2961 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2963 log_error(LOG_LEVEL_HEADER, "crunched From!");
2967 log_error(LOG_LEVEL_HEADER, " modified");
2969 *header = strdup("From: ");
2970 string_append(header, newval);
2972 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2976 /*********************************************************************
2978 * Function : client_send_cookie
2980 * Description : Crunches the "cookie" header if necessary.
2981 * Called from `sed'.
2983 * XXX: Stupid name, doesn't send squat.
2986 * 1 : csp = Current client state (buffers, headers, etc...)
2987 * 2 : header = On input, pointer to header to modify.
2988 * On output, pointer to the modified header, or NULL
2989 * to remove the header. This function frees the
2990 * original string if necessary.
2992 * Returns : JB_ERR_OK on success, or
2993 * JB_ERR_MEMORY on out-of-memory error.
2995 *********************************************************************/
2996 jb_err client_send_cookie(struct client_state *csp, char **header)
2998 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3000 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3008 /*********************************************************************
3010 * Function : client_x_forwarded
3012 * Description : Handle the "x-forwarded-for" config setting properly,
3013 * also used in the add_client_headers list. Called from `sed'.
3016 * 1 : csp = Current client state (buffers, headers, etc...)
3017 * 2 : header = On input, pointer to header to modify.
3018 * On output, pointer to the modified header, or NULL
3019 * to remove the header. This function frees the
3020 * original string if necessary.
3022 * Returns : JB_ERR_OK on success, or
3023 * JB_ERR_MEMORY on out-of-memory error.
3025 *********************************************************************/
3026 jb_err client_x_forwarded(struct client_state *csp, char **header)
3028 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3030 /* Save it so we can re-add it later */
3031 freez(csp->x_forwarded);
3032 csp->x_forwarded = *header;
3035 * Always set *header = NULL, since this information
3036 * will be sent at the end of the header.
3043 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3050 /*********************************************************************
3052 * Function : client_max_forwards
3054 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3055 * from the value of the Max-Forwards header field.
3058 * 1 : csp = Current client state (buffers, headers, etc...)
3059 * 2 : header = On input, pointer to header to modify.
3060 * On output, pointer to the modified header, or NULL
3061 * to remove the header. This function frees the
3062 * original string if necessary.
3064 * Returns : JB_ERR_OK on success, or
3065 * JB_ERR_MEMORY on out-of-memory error.
3067 *********************************************************************/
3068 jb_err client_max_forwards(struct client_state *csp, char **header)
3072 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3073 (0 == strcmpic(csp->http->gpc, "options")))
3075 assert(*(*header+12) == ':');
3076 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3078 if (max_forwards > 0)
3080 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3081 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3082 csp->http->gpc, max_forwards);
3084 else if (max_forwards < 0)
3086 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3092 * Not supposed to be reached. direct_response() which
3093 * was already called earlier in chat() should have
3094 * intercepted the request.
3096 log_error(LOG_LEVEL_ERROR,
3097 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3098 assert(max_forwards != 0);
3103 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3112 /*********************************************************************
3114 * Function : client_host
3116 * Description : If the request URI did not contain host and
3117 * port information, parse and evaluate the Host
3120 * Also, kill ill-formed HOST: headers as sent by
3121 * Apple's iTunes software when used with a proxy.
3124 * 1 : csp = Current client state (buffers, headers, etc...)
3125 * 2 : header = On input, pointer to header to modify.
3126 * On output, pointer to the modified header, or NULL
3127 * to remove the header. This function frees the
3128 * original string if necessary.
3130 * Returns : JB_ERR_OK on success, or
3131 * JB_ERR_MEMORY on out-of-memory error.
3133 *********************************************************************/
3134 jb_err client_host(struct client_state *csp, char **header)
3139 * If the header field name is all upper-case, chances are that it's
3140 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3141 * not a problem -- they are regenerated later.
3143 if ((*header)[1] == 'O')
3145 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3150 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3151 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3154 if (NULL == (p = strdup((*header)+6)))
3156 return JB_ERR_MEMORY;
3159 if (NULL == (q = strdup(p)))
3162 return JB_ERR_MEMORY;
3165 freez(csp->http->hostport);
3166 csp->http->hostport = p;
3167 freez(csp->http->host);
3168 csp->http->host = q;
3169 q = strchr(csp->http->host, ':');
3172 /* Terminate hostname and evaluate port string */
3174 csp->http->port = atoi(q);
3178 csp->http->port = csp->http->ssl ? 443 : 80;
3181 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3182 csp->http->hostport, csp->http->host, csp->http->port);
3185 /* Signal client_host_adder() to return right away */
3186 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3191 /*********************************************************************
3193 * Function : client_if_modified_since
3195 * Description : Remove or modify the If-Modified-Since header.
3198 * 1 : csp = Current client state (buffers, headers, etc...)
3199 * 2 : header = On input, pointer to header to modify.
3200 * On output, pointer to the modified header, or NULL
3201 * to remove the header. This function frees the
3202 * original string if necessary.
3204 * Returns : JB_ERR_OK on success, or
3205 * JB_ERR_MEMORY on out-of-memory error.
3207 *********************************************************************/
3208 jb_err client_if_modified_since(struct client_state *csp, char **header)
3211 #ifdef HAVE_GMTIME_R
3214 struct tm *timeptr = NULL;
3218 long int hours, minutes, seconds;
3222 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3225 * The client got an error message because of a temporary problem,
3226 * the problem is gone and the client now tries to revalidate our
3227 * error message on the real server. The revalidation would always
3228 * end with the transmission of the whole document and there is
3229 * no need to expose the bogus If-Modified-Since header.
3231 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3234 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3236 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3238 if ((0 == strcmpic(newval, "block")))
3240 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3243 else /* add random value */
3245 const char *header_time = *header + sizeof("If-Modified-Since:");
3247 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3249 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3254 rtime = strtol(newval, &endptr, 0);
3257 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3258 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3265 rtime = pick_from_range(rtime);
3269 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3272 tm += rtime * (negative ? -1 : 1);
3273 #ifdef HAVE_GMTIME_R
3274 timeptr = gmtime_r(&tm, &gmt);
3275 #elif FEATURE_PTHREAD
3276 pthread_mutex_lock(&gmtime_mutex);
3277 timeptr = gmtime(&tm);
3278 pthread_mutex_unlock(&gmtime_mutex);
3280 timeptr = gmtime(&tm);
3282 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3285 *header = strdup("If-Modified-Since: ");
3286 string_append(header, newheader);
3288 if (*header == NULL)
3290 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3291 return JB_ERR_MEMORY;
3294 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3296 hours = rtime / 3600;
3297 minutes = rtime / 60 % 60;
3298 seconds = rtime % 60;
3300 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3301 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3302 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3311 /*********************************************************************
3313 * Function : client_if_none_match
3315 * Description : Remove the If-None-Match header.
3318 * 1 : csp = Current client state (buffers, headers, etc...)
3319 * 2 : header = On input, pointer to header to modify.
3320 * On output, pointer to the modified header, or NULL
3321 * to remove the header. This function frees the
3322 * original string if necessary.
3324 * Returns : JB_ERR_OK on success, or
3325 * JB_ERR_MEMORY on out-of-memory error.
3327 *********************************************************************/
3328 jb_err client_if_none_match(struct client_state *csp, char **header)
3330 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3332 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3339 /*********************************************************************
3341 * Function : client_x_filter
3343 * Description : Disables filtering if the client set "X-Filter: No".
3344 * Called from `sed'.
3347 * 1 : csp = Current client state (buffers, headers, etc...)
3348 * 2 : header = On input, pointer to header to modify.
3349 * On output, pointer to the modified header, or NULL
3350 * to remove the header. This function frees the
3351 * original string if necessary.
3353 * Returns : JB_ERR_OK on success
3355 *********************************************************************/
3356 jb_err client_x_filter(struct client_state *csp, char **header)
3358 if ( 0 == strcmpic(*header, "X-Filter: No"))
3360 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3362 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3366 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3368 log_error(LOG_LEVEL_HEADER,
3369 "force-text-mode overruled the client's request to fetch without filtering!");
3373 csp->content_type = CT_TABOO;
3374 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
3375 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
3376 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3378 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3385 /* the following functions add headers directly to the header list */
3387 /*********************************************************************
3389 * Function : client_host_adder
3391 * Description : Adds the Host: header field if it is missing.
3392 * Called from `sed'.
3395 * 1 : csp = Current client state (buffers, headers, etc...)
3397 * Returns : JB_ERR_OK on success, or
3398 * JB_ERR_MEMORY on out-of-memory error.
3400 *********************************************************************/
3401 jb_err client_host_adder(struct client_state *csp)
3406 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3408 /* Header already set by the client, nothing to do. */
3412 if ( !csp->http->hostport || !*(csp->http->hostport))
3414 /* XXX: When does this happen and why is it OK? */
3415 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3420 * remove 'user:pass@' from 'proto://user:pass@host'
3422 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3428 p = csp->http->hostport;
3431 /* XXX: Just add it, we already made sure that it will be unique */
3432 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3433 err = enlist_unique_header(csp->headers, "Host", p);
3439 /*********************************************************************
3441 * Function : client_cookie_adder
3443 * Description : Used in the add_client_headers list to add "wafers".
3444 * Called from `sed'.
3447 * 1 : csp = Current client state (buffers, headers, etc...)
3449 * Returns : JB_ERR_OK on success, or
3450 * JB_ERR_MEMORY on out-of-memory error.
3452 *********************************************************************/
3453 jb_err client_cookie_adder(struct client_state *csp)
3456 struct list_entry *wafer;
3457 struct list_entry *wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3460 if (NULL == wafer_list)
3466 tmp = strdup("Cookie: ");
3468 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3470 if (wafer != wafer_list)
3472 /* As this isn't the first wafer, we need a delimiter. */
3473 string_append(&tmp, "; ");
3475 string_join(&tmp, cookie_encode(wafer->str));
3480 return JB_ERR_MEMORY;
3483 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3484 err = enlist(csp->headers, tmp);
3490 /*********************************************************************
3492 * Function : client_accept_encoding_adder
3494 * Description : Add an Accept-Encoding header to the client's request
3495 * that disables compression if the action applies, and
3496 * the header is not already there. Called from `sed'.
3497 * Note: For HTTP/1.0, the absence of the header is enough.
3500 * 1 : csp = Current client state (buffers, headers, etc...)
3502 * Returns : JB_ERR_OK on success, or
3503 * JB_ERR_MEMORY on out-of-memory error.
3505 *********************************************************************/
3506 jb_err client_accept_encoding_adder(struct client_state *csp)
3508 assert(0); /* Not in use */
3510 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3511 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3513 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3520 /*********************************************************************
3522 * Function : client_xtra_adder
3524 * Description : Used in the add_client_headers list. Called from `sed'.
3527 * 1 : csp = Current client state (buffers, headers, etc...)
3529 * Returns : JB_ERR_OK on success, or
3530 * JB_ERR_MEMORY on out-of-memory error.
3532 *********************************************************************/
3533 jb_err client_xtra_adder(struct client_state *csp)
3535 struct list_entry *lst;
3538 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3539 lst ; lst = lst->next)
3541 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3542 err = enlist(csp->headers, lst->str);
3554 /*********************************************************************
3556 * Function : client_x_forwarded_adder
3558 * Description : Used in the add_client_headers list. Called from `sed'.
3561 * 1 : csp = Current client state (buffers, headers, etc...)
3563 * Returns : JB_ERR_OK on success, or
3564 * JB_ERR_MEMORY on out-of-memory error.
3566 *********************************************************************/
3567 jb_err client_x_forwarded_adder(struct client_state *csp)
3572 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3577 if (csp->x_forwarded)
3579 p = strdup(csp->x_forwarded);
3580 string_append(&p, ", ");
3584 p = strdup("X-Forwarded-For: ");
3586 string_append(&p, csp->ip_addr_str);
3590 return JB_ERR_MEMORY;
3593 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3594 err = enlist(csp->headers, p);
3601 /*********************************************************************
3603 * Function : connection_close_adder
3605 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3606 * support. Adds a "Connection: close" header to csp->headers
3607 * unless the header was already present. Called from `sed'.
3609 * FIXME: This whole function shouldn't be neccessary!
3612 * 1 : csp = Current client state (buffers, headers, etc...)
3614 * Returns : JB_ERR_OK on success, or
3615 * JB_ERR_MEMORY on out-of-memory error.
3617 *********************************************************************/
3618 jb_err connection_close_adder(struct client_state *csp)
3620 const unsigned int flags = csp->flags;
3623 * Return right away if
3625 * - we're parsing server headers and the server header
3626 * "Connection: close" is already set, or if
3628 * - we're parsing client headers and the client header
3629 * "Connection: close" is already set.
3631 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3632 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3633 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3634 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3639 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3641 return enlist(csp->headers, "Connection: close");
3645 /*********************************************************************
3647 * Function : server_http
3649 * Description : - Save the HTTP Status into csp->http->status
3650 * - Set CT_TABOO to prevent filtering if the answer
3651 * is a partial range (HTTP status 206)
3652 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3656 * 1 : csp = Current client state (buffers, headers, etc...)
3657 * 2 : header = On input, pointer to header to modify.
3658 * On output, pointer to the modified header, or NULL
3659 * to remove the header. This function frees the
3660 * original string if necessary.
3662 * Returns : JB_ERR_OK on success, or
3663 * JB_ERR_MEMORY on out-of-memory error.
3665 *********************************************************************/
3666 jb_err server_http(struct client_state *csp, char **header)
3668 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3669 if (csp->http->status == 206)
3671 csp->content_type = CT_TABOO;
3674 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3677 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3684 /*********************************************************************
3686 * Function : server_set_cookie
3688 * Description : Handle the server "cookie" header properly.
3689 * Log cookie to the jar file. Then "crunch",
3690 * accept or rewrite it to a session cookie.
3691 * Called from `sed'.
3693 * TODO: Allow the user to specify a new expiration
3694 * time to cause the cookie to expire even before the
3695 * browser is closed.
3698 * 1 : csp = Current client state (buffers, headers, etc...)
3699 * 2 : header = On input, pointer to header to modify.
3700 * On output, pointer to the modified header, or NULL
3701 * to remove the header. This function frees the
3702 * original string if necessary.
3704 * Returns : JB_ERR_OK on success, or
3705 * JB_ERR_MEMORY on out-of-memory error.
3707 *********************************************************************/
3708 jb_err server_set_cookie(struct client_state *csp, char **header)
3715 #ifdef FEATURE_COOKIE_JAR
3716 if (csp->config->jar)
3719 * Write timestamp into outbuf.
3721 * Complex because not all OSs have tm_gmtoff or
3722 * the %z field in strftime()
3724 char tempbuf[ BUFFER_SIZE ];
3726 #ifdef HAVE_LOCALTIME_R
3727 tm_now = *localtime_r(&now, &tm_now);
3728 #elif FEATURE_PTHREAD
3729 pthread_mutex_lock(&localtime_mutex);
3730 tm_now = *localtime (&now);
3731 pthread_mutex_unlock(&localtime_mutex);
3733 tm_now = *localtime (&now);
3735 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3737 /* strlen("set-cookie: ") = 12 */
3738 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3740 #endif /* def FEATURE_COOKIE_JAR */
3742 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3744 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3747 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3749 /* Flag whether or not to log a message */
3752 /* A variable to store the tag we're working on */
3755 /* Skip "Set-Cookie:" (11 characters) in header */
3756 cur_tag = *header + 11;
3758 /* skip whitespace between "Set-Cookie:" and value */
3759 while (*cur_tag && ijb_isspace(*cur_tag))
3764 /* Loop through each tag in the cookie */
3768 char *next_tag = strchr(cur_tag, ';');
3769 if (next_tag != NULL)
3771 /* Skip the ';' character itself */
3774 /* skip whitespace ";" and start of tag */
3775 while (*next_tag && ijb_isspace(*next_tag))
3782 /* "Next tag" is the end of the string */
3783 next_tag = cur_tag + strlen(cur_tag);
3787 * Check the expiration date to see
3788 * if the cookie is still valid, if yes,
3789 * rewrite it to a session cookie.
3791 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3793 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3795 /* Did we detect the date properly? */
3796 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3799 * Nope, treat it as if it was still valid.
3801 * XXX: Should we remove the whole cookie instead?
3803 log_error(LOG_LEVEL_ERROR,
3804 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3805 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3811 * Yes. Check if the cookie is still valid.
3813 * If the cookie is already expired it's probably
3814 * a delete cookie and even if it isn't, the browser
3815 * will discard it anyway.
3819 * XXX: timegm() isn't available on some AmigaOS
3820 * versions and our replacement doesn't work.
3822 * Our options are to either:
3824 * - disable session-cookies-only completely if timegm
3827 * - to simply remove all expired tags, like it has
3828 * been done until Privoxy 3.0.6 and to live with
3829 * the consequence that it can cause login/logout
3830 * problems on servers that don't validate their
3831 * input properly, or
3833 * - to replace it with mktime in which
3834 * case there is a slight chance of valid cookies
3835 * passing as already expired.
3837 * This is the way it's currently done and it's not
3838 * as bad as it sounds. If the missing GMT offset is
3839 * enough to change the result of the expiration check
3840 * the cookie will be only valid for a few hours
3841 * anyway, which in many cases will be shorter
3842 * than a browser session.
3844 if (cookie_time - now < 0)
3846 log_error(LOG_LEVEL_HEADER,
3847 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3848 /* Just in case some clown sets more then one expiration date */
3854 * Still valid, delete expiration date by copying
3855 * the rest of the string over it.
3857 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3858 * since the behaviour of strcpy is undefined for overlapping
3861 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3863 /* That changed the header, need to issue a log message */
3867 * Note that the next tag has now been moved to *cur_tag,
3868 * so we do not need to update the cur_tag pointer.
3876 /* Move on to next cookie tag */
3883 assert(NULL != *header);
3884 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3893 #ifdef FEATURE_FORCE_LOAD
3894 /*********************************************************************
3896 * Function : strclean
3898 * Description : In-Situ-Eliminate all occurances of substring in
3902 * 1 : string = string to clean
3903 * 2 : substring = substring to eliminate
3905 * Returns : Number of eliminations
3907 *********************************************************************/
3908 int strclean(const char *string, const char *substring)
3914 len = strlen(substring);
3916 while((pos = strstr(string, substring)) != NULL)
3923 while (*p++ != '\0');
3930 #endif /* def FEATURE_FORCE_LOAD */
3932 /*********************************************************************
3934 * Function : parse_header_time
3936 * Description : Parses time formats used in HTTP header strings
3937 * to get the numerical respresentation.
3940 * 1 : header_time = HTTP header time as string.
3941 * 2 : result = storage for header_time in seconds
3943 * Returns : JB_ERR_OK if the time format was recognized, or
3944 * JB_ERR_PARSE otherwise.
3946 *********************************************************************/
3947 jb_err parse_header_time(const char *header_time, time_t *result)
3952 * Zero out gmt to prevent time zone offsets.
3954 * While this is only necessary on some platforms
3955 * (mingw32 for example), I don't know how to
3956 * detect these automatically and doing it everywhere
3959 memset(&gmt, 0, sizeof(gmt));
3961 /* Tue, 02 Jun 2037 20:00:00 */
3962 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3963 /* Tue, 02-Jun-2037 20:00:00 */
3964 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3965 /* Tue, 02-Jun-37 20:00:00 */
3966 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3967 /* Tuesday, 02-Jun-2037 20:00:00 */
3968 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3969 /* Tuesday Jun 02 20:00:00 2037 */
3970 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3972 return JB_ERR_PARSE;
3975 *result = timegm(&gmt);
3981 /*********************************************************************
3983 * Function : get_destination_from_headers
3985 * Description : Parse the "Host:" header to get the request's destination.
3986 * Only needed if the client's request was forcefully
3987 * redirected into Privoxy.
3989 * Code mainly copied from client_host() which is currently
3990 * run too late for this purpose.
3993 * 1 : headers = List of headers (one of them hopefully being
3994 * the "Host:" header)
3995 * 2 : http = storage for the result (host, port and hostport).
3997 * Returns : JB_ERR_MEMORY in case of memory problems,
3998 * JB_ERR_PARSE if the host header couldn't be found,
3999 * JB_ERR_OK otherwise.
4001 *********************************************************************/
4002 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4008 host = get_header_value(headers, "Host:");
4012 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4013 return JB_ERR_PARSE;
4016 if (NULL == (p = strdup((host))))
4018 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4019 return JB_ERR_MEMORY;
4022 if (NULL == (q = strdup(p)))
4025 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4026 return JB_ERR_MEMORY;
4029 freez(http->hostport);
4033 q = strchr(http->host, ':');
4036 /* Terminate hostname and evaluate port string */
4038 http->port = atoi(q);
4042 http->port = http->ssl ? 443 : 80;
4045 /* Rebuild request URL */
4047 http->url = strdup(http->ssl ? "https://" : "http://");
4048 string_append(&http->url, http->hostport);
4049 string_append(&http->url, http->path);
4050 if (http->url == NULL)
4052 return JB_ERR_MEMORY;
4055 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",