1 const char parsers_rcs[] = "$Id: parsers.c,v 1.97 2007/04/15 16:39:21 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.97 2007/04/15 16:39:21 fabiankeil
48 * Introduce tags as alternative way to specify which
49 * actions apply to a request. At the moment tags can be
50 * created based on client and server headers.
52 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
53 * Log a warning if the content is compressed, filtering is
54 * enabled and Privoxy was compiled without zlib support.
57 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
58 * - Fix warnings when compiled with glibc.
59 * - Don't use crumble() for cookie crunching.
60 * - Move cookie time parsing into parse_header_time().
61 * - Let parse_header_time() return a jb_err code
62 * instead of a pointer that can only be used to
63 * check for NULL anyway.
65 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
66 * - Add better protection against malicious gzip headers.
67 * - Stop logging the first hundred bytes of decompressed content.
68 * It looks like it's working and there is always debug 16.
69 * - Log the content size after decompression in decompress_iob()
70 * instead of pcrs_filter_response().
72 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
73 * - Use dedicated header filter actions instead of abusing "filter".
74 * Replace "filter-client-headers" and "filter-client-headers"
75 * with "server-header-filter" and "client-header-filter".
76 * - Remove filter_client_header() and filter_client_header(),
77 * filter_header() now checks the shiny new
78 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
80 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
81 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
82 * - Handle "Cookie:" and "Connection:" headers a bit smarter
83 * (don't crunch them just to recreate them later on).
84 * - Add another non-standard time format for the cookie
85 * expiration date detection.
86 * - Fix a valgrind warning.
88 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
89 * Improve cookie expiration date detection.
91 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
92 * Don't run server_content_length() the first time
93 * sed() parses server headers; only adjust the
94 * Content-Length header if the page was modified.
96 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
97 * Fix log messages regarding the cookie time format
98 * (cookie and request URL were mixed up).
100 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
101 * - Let decompress_iob()
102 * - not corrupt the content if decompression fails
103 * early. (the first byte(s) were lost).
104 * - use pointer arithmetics with defined outcome for
106 * - Use a different kludge to remember a failed decompression.
108 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
109 * Search for Max-Forwards headers case-insensitive,
110 * don't generate the "501 unsupported" message for invalid
111 * Max-Forwards values and don't increase negative ones.
113 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
114 * - Let server_set_cookie() check the expiration date
115 * of cookies and don't touch the ones that are already
116 * expired. Fixes problems with low quality web applications
117 * as described in BR 932612.
119 * - Adjust comment in client_max_forwards to reality;
120 * remove invalid Max-Forwards headers.
122 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
123 * Stop filter_header() from unintentionally removing
124 * empty header lines that were enlisted by the continue
127 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
128 * - Repeat the request URL before logging any headers.
129 * Makes reading the log easier in case of simultaneous requests.
130 * - If there are more than one Content-Type headers in one request,
131 * use the first one and remove the others.
132 * - Remove "newval" variable in server_content_type().
133 * It's only used once.
135 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
136 * Correct a cast, check inflateEnd() exit code
137 * to see if we have to, replace sprintf calls
140 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
141 * Integrate a modified version of Wil Mahan's
142 * zlib patch (PR #895531).
144 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
145 * Skip empty filter files in filter_header()
146 * but don't ignore the ones that come afterwards.
147 * Fixes BR 1619208, this time for real.
149 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
150 * Reverted parts of my last commit
151 * to keep error handling working.
153 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
154 * Fixed gcc43 conversion warnings.
156 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
157 * Bringing back the "useless" localtime() call
158 * I removed in revision 1.67. On some platforms
159 * it's necessary to prevent time zone offsets.
161 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
162 * Rebuild request URL in get_destination_from_headers()
163 * to make sure redirect{pcrs command} works as expected
164 * for intercepted requests.
166 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
167 * Added get_destination_from_headers().
169 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
170 * Make pthread mutex locking more generic. Instead of
171 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
172 * and use mutex locking unless there is an _r function
173 * available. Better safe than sorry.
175 * Fixes "./configure --disable-pthread" and should result
176 * in less threading-related problems on pthread-using platforms,
177 * but it still doesn't fix BR#1122404.
179 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
180 * The special header "X-Filter: No" now disables
181 * header filtering as well.
183 * Revision 1.73 2006/09/23 13:26:38 roro
184 * Replace TABs by spaces in source code.
186 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
187 * Don't print a log message every time filter_headers is
188 * entered or left. It only creates noise without any real
191 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
192 * Fix +hide-if-modified-since{-n}.
194 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
195 * Have hide-if-modified-since interpret the random
196 * range value as minutes instead of hours. Allows
197 * more fine-grained configuration.
199 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
200 * Always have parse_header_time return a pointer
201 * that actual makes sense, even though we currently
202 * only need it to detect problems.
204 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
205 * Added config option enable-remote-http-toggle
206 * to specify if Privoxy should recognize special
207 * headers (currently only X-Filter) to change its
208 * behaviour. Disabled by default.
210 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
211 * After filtering de-chunked instances, remove
212 * "Transfer-Encoding" header entirely instead of changing
213 * it to "Transfer-Encoding: identity", which is invalid.
214 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
216 * Don't use localtime in parse_header_time. An empty time struct
217 * is good enough, it gets overwritten by strptime anyway.
219 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
220 * Use gmtime_r if available, fallback to gmtime with mutex
221 * protection for MacOSX and use vanilla gmtime for the rest.
223 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
224 * Changed client_referrer to use the right type (size_t) for
225 * hostlenght and to shorten the temporary referrer string with
226 * '\0' instead of adding a useless line break.
228 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
229 * - Back to timegm() using GnuPG's replacement if necessary.
230 * Using mktime() and localtime() could add a on hour offset if
231 * the randomize factor was big enough to lead to a summer/wintertime
234 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
236 * - Moved randomization code into pick_from_range().
238 * - Changed parse_header_time definition.
239 * time_t isn't guaranteed to be signed and
240 * if it isn't, -1 isn't available as error code.
241 * Changed some variable types in client_if_modified_since()
242 * because of the same reason.
244 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
245 * OS/2 compilation compatibility fixups
247 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
248 * Changed include from strptime.c to strptime.h
250 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
251 * Split filter-headers{} into filter-client-headers{}
252 * and filter-server-headers{}.
253 * Added parse_header_time() to share some code.
254 * Replaced timegm() with mktime().
256 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
257 * Windows service integration
259 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
260 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
262 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
263 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
264 * with what was really the latest development (the v_3_0_branch branch)
266 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
267 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
269 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
270 * Add the ability to check jpeg images for invalid
271 * lengths of comment blocks. Defensive strategy
272 * against the exploit:
273 * Microsoft Security Bulletin MS04-028
274 * Buffer Overrun in JPEG Processing (GDI+) Could
275 * Allow Code Execution (833987)
276 * Enabled with +inspect-jpegs in actions files.
278 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
279 * Excluded text/plain objects from filtering. This fixes a
280 * couple of client-crashing, download corruption and
281 * Privoxy performance issues, whose root cause lies in
282 * web servers labelling content of unknown type as text/plain.
284 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
285 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
287 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
288 * Completing the previous change
290 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
291 * Added temporary workaround for bug in PHP < 4.2.3
293 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
294 * 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.
296 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
297 * Fix typo: supressed -> suppressed
299 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
300 * Improved cookie logging
302 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
303 * Added basic support for OPTIONS and TRACE HTTP methods:
304 * - New parser function client_max_forwards which decrements
305 * the Max-Forwards HTTP header field of OPTIONS and TRACE
306 * requests by one before forwarding
307 * - New parser function client_host which extracts the host
308 * and port information from the HTTP header field if the
309 * request URI was not absolute
310 * - Don't crumble and re-add the Host: header, but only generate
311 * and append if missing
313 * Revision 1.56 2002/05/12 15:34:22 jongfoster
314 * Fixing typo in a comment
316 * Revision 1.55 2002/05/08 16:01:07 oes
317 * Optimized add_to_iob:
318 * - Use realloc instead of malloc(), memcpy(), free()
319 * - Expand to powers of two if possible, to get
320 * O(log n) reallocs instead of O(n).
321 * - Moved check for buffer limit here from chat
322 * - Report failure via returncode
324 * Revision 1.54 2002/04/02 15:03:16 oes
325 * Tiny code cosmetics
327 * Revision 1.53 2002/03/26 22:29:55 swa
328 * we have a new homepage!
330 * Revision 1.52 2002/03/24 13:25:43 swa
331 * name change related issues
333 * Revision 1.51 2002/03/13 00:27:05 jongfoster
336 * Revision 1.50 2002/03/12 01:45:35 oes
337 * More verbose logging
339 * Revision 1.49 2002/03/09 20:03:52 jongfoster
340 * - Making various functions return int rather than size_t.
341 * (Undoing a recent change). Since size_t is unsigned on
342 * Windows, functions like read_socket that return -1 on
343 * error cannot return a size_t.
345 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
346 * crashes, and also frequently caused JB to jump to 100%
347 * CPU and stay there. (Because it thought it had just
348 * read ((unsigned)-1) == 4Gb of data...)
350 * - The signature of write_socket has changed, it now simply
351 * returns success=0/failure=nonzero.
353 * - Trying to get rid of a few warnings --with-debug on
354 * Windows, I've introduced a new type "jb_socket". This is
355 * used for the socket file descriptors. On Windows, this
356 * is SOCKET (a typedef for unsigned). Everywhere else, it's
357 * an int. The error value can't be -1 any more, so it's
358 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
359 * Windows it maps to the #define INVALID_SOCKET.)
361 * - The signature of bind_port has changed.
363 * Revision 1.48 2002/03/07 03:46:53 oes
364 * Fixed compiler warnings etc
366 * Revision 1.47 2002/02/20 23:15:13 jongfoster
367 * Parsing functions now handle out-of-memory gracefully by returning
370 * Revision 1.46 2002/01/17 21:03:47 jongfoster
371 * Moving all our URL and URL pattern parsing code to urlmatch.c.
373 * Revision 1.45 2002/01/09 14:33:03 oes
374 * Added support for localtime_r.
376 * Revision 1.44 2001/12/14 01:22:54 steudten
377 * Remove 'user:pass@' from 'proto://user:pass@host' for the
378 * new added header 'Host: ..'. (See Req ID 491818)
380 * Revision 1.43 2001/11/23 00:26:38 jongfoster
381 * Fixing two really stupid errors in my previous commit
383 * Revision 1.42 2001/11/22 21:59:30 jongfoster
384 * Adding code to handle +no-cookies-keep
386 * Revision 1.41 2001/11/05 23:43:05 steudten
387 * Add time+date to log files.
389 * Revision 1.40 2001/10/26 20:13:09 jongfoster
390 * ctype.h is needed in Windows, too.
392 * Revision 1.39 2001/10/26 17:40:04 oes
393 * Introduced get_header_value()
394 * Removed http->user_agent, csp->referrer and csp->accept_types
395 * Removed client_accept()
397 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
398 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
399 * threads to call select() simultaneously. So, it's time to do a real, live,
400 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
401 * (native). Both versions will work, but using __OS2__ offers multi-threading.
403 * Revision 1.37 2001/10/23 21:36:02 jongfoster
404 * Documenting sed()'s error behaviou (doc change only)
406 * Revision 1.36 2001/10/13 12:51:51 joergs
407 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
408 * force-load), instead crumble Host: and add it (again) in client_host_adder
409 * (in case we get a HTTP/1.0 request without Host: header and forward it to
410 * a HTTP/1.1 server/proxy).
412 * Revision 1.35 2001/10/09 22:39:21 jongfoster
413 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
416 * Revision 1.34 2001/10/07 18:50:55 oes
417 * Added server_content_encoding, renamed server_transfer_encoding
419 * Revision 1.33 2001/10/07 18:04:49 oes
420 * Changed server_http11 to server_http and its pattern to "HTTP".
421 * Additional functionality: it now saves the HTTP status into
422 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
424 * Revision 1.32 2001/10/07 15:43:28 oes
425 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
426 * client_te and client_accept_encoding_adder, triggered by the new
427 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
428 * changed to allow only identity and chunked, and the TE header is
429 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
431 * parse_http_request no longer does anything than parsing. The rewriting
432 * of http->cmd and version mangling are gone. It now also recognizes
433 * the put and delete methods and saves the url in http->url. Removed
436 * renamed content_type and content_length to have the server_ prefix
438 * server_content_type now only works if csp->content_type != CT_TABOO
440 * added server_transfer_encoding, which
441 * - Sets CT_TABOO to prohibit filtering if encoding compresses
442 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
443 * - Change from "chunked" to "identity" if body was chunked
444 * but has been de-chunked for filtering.
446 * added server_content_md5 which crunches any Content-MD5 headers
447 * if the body was modified.
449 * made server_http11 conditional on +downgrade action
451 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
453 * Revision 1.31 2001/10/05 14:25:02 oes
454 * Crumble Keep-Alive from Server
456 * Revision 1.30 2001/09/29 12:56:03 joergs
457 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
459 * Revision 1.29 2001/09/24 21:09:24 jongfoster
460 * Fixing 2 memory leaks that Guy spotted, where the paramater to
461 * enlist() was not being free()d.
463 * Revision 1.28 2001/09/22 16:32:28 jongfoster
464 * Removing unused #includes.
466 * Revision 1.27 2001/09/20 15:45:25 steudten
468 * add casting from size_t to int for printf()
469 * remove local variable shadow s2
471 * Revision 1.26 2001/09/16 17:05:14 jongfoster
472 * Removing unused #include showarg.h
474 * Revision 1.25 2001/09/16 13:21:27 jongfoster
475 * Changes to use new list functions.
477 * Revision 1.24 2001/09/13 23:05:50 jongfoster
478 * Changing the string paramater to the header parsers a "const".
480 * Revision 1.23 2001/09/12 18:08:19 steudten
482 * In parse_http_request() header rewriting miss the host value, so
483 * from http://www.mydomain.com the result was just " / " not
484 * http://www.mydomain.com/ in case we forward.
486 * Revision 1.22 2001/09/10 10:58:53 oes
487 * Silenced compiler warnings
489 * Revision 1.21 2001/07/31 14:46:00 oes
490 * - Persistant connections now suppressed
491 * - sed() no longer appends empty header to csp->headers
493 * Revision 1.20 2001/07/30 22:08:36 jongfoster
494 * Tidying up #defines:
495 * - All feature #defines are now of the form FEATURE_xxx
496 * - Permanently turned off WIN_GUI_EDIT
497 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
499 * Revision 1.19 2001/07/25 17:21:54 oes
500 * client_uagent now saves copy of User-Agent: header value
502 * Revision 1.18 2001/07/13 14:02:46 oes
503 * - Included fix to repair broken HTTP requests that
504 * don't contain a path, not even '/'.
505 * - Removed all #ifdef PCRS
506 * - content_type now always inspected and classified as
507 * text, gif or other.
508 * - formatting / comments
510 * Revision 1.17 2001/06/29 21:45:41 oes
511 * Indentation, CRLF->LF, Tab-> Space
513 * Revision 1.16 2001/06/29 13:32:42 oes
515 * - Adapted free_http_request
516 * - Removed logentry from cancelled commit
518 * Revision 1.15 2001/06/03 19:12:38 oes
519 * deleted const struct interceptors
521 * Revision 1.14 2001/06/01 18:49:17 jongfoster
522 * Replaced "list_share" with "list" - the tiny memory gain was not
523 * worth the extra complexity.
525 * Revision 1.13 2001/05/31 21:30:33 jongfoster
526 * Removed list code - it's now in list.[ch]
527 * Renamed "permission" to "action", and changed many features
528 * to use the actions file rather than the global config.
530 * Revision 1.12 2001/05/31 17:33:13 oes
534 * Revision 1.11 2001/05/29 20:11:19 joergs
535 * '/ * inside comment' warning removed.
537 * Revision 1.10 2001/05/29 09:50:24 jongfoster
538 * Unified blocklist/imagelist/permissionslist.
539 * File format is still under discussion, but the internal changes
542 * Also modified interceptor behaviour:
543 * - We now intercept all URLs beginning with one of the following
544 * prefixes (and *only* these prefixes):
546 * * http://ijbswa.sf.net/config/
547 * * http://ijbswa.sourceforge.net/config/
548 * - New interceptors "home page" - go to http://i.j.b/ to see it.
549 * - Internal changes so that intercepted and fast redirect pages
550 * are not replaced with an image.
551 * - Interceptors now have the option to send a binary page direct
552 * to the client. (i.e. ijb-send-banner uses this)
553 * - Implemented show-url-info interceptor. (Which is why I needed
554 * the above interceptors changes - a typical URL is
555 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
556 * The previous mechanism would not have intercepted that, and
557 * if it had been intercepted then it then it would have replaced
560 * Revision 1.9 2001/05/28 17:26:33 jongfoster
561 * Fixing segfault if last header was crunched.
562 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
563 * can use the cross-platform sprintf() instead.)
565 * Revision 1.8 2001/05/27 22:17:04 oes
567 * - re_process_buffer no longer writes the modified buffer
568 * to the client, which was very ugly. It now returns the
569 * buffer, which it is then written by chat.
571 * - content_length now adjusts the Content-Length: header
572 * for modified documents rather than crunch()ing it.
573 * (Length info in csp->content_length, which is 0 for
574 * unmodified documents)
576 * - For this to work, sed() is called twice when filtering.
578 * Revision 1.7 2001/05/27 13:19:06 oes
579 * Patched Joergs solution for the content-length in.
581 * Revision 1.6 2001/05/26 13:39:32 jongfoster
582 * Only crunches Content-Length header if applying RE filtering.
583 * Without this fix, Microsoft Windows Update wouldn't work.
585 * Revision 1.5 2001/05/26 00:28:36 jongfoster
586 * Automatic reloading of config file.
587 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
588 * Most of the global variables have been moved to a new
589 * struct configuration_spec, accessed through csp->config->globalname
590 * Most of the globals remaining are used by the Win32 GUI.
592 * Revision 1.4 2001/05/22 18:46:04 oes
594 * - Enabled filtering banners by size rather than URL
595 * by adding patterns that replace all standard banner
596 * sizes with the "Junkbuster" gif to the re_filterfile
598 * - Enabled filtering WebBugs by providing a pattern
599 * which kills all 1x1 images
601 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
602 * which is selected by the (nonstandard and therefore
603 * capital) letter 'U' in the option string.
604 * It causes the quantifiers to be ungreedy by default.
605 * Appending a ? turns back to greedy (!).
607 * - Added a new interceptor ijb-send-banner, which
608 * sends back the "Junkbuster" gif. Without imagelist or
609 * MSIE detection support, or if tinygif = 1, or the
610 * URL isn't recognized as an imageurl, a lame HTML
611 * explanation is sent instead.
613 * - Added new feature, which permits blocking remote
614 * script redirects and firing back a local redirect
616 * The feature is conditionally compiled, i.e. it
617 * can be disabled with --disable-fast-redirects,
618 * plus it must be activated by a "fast-redirects"
619 * line in the config file, has its own log level
620 * and of course wants to be displayed by show-proxy-args
621 * Note: Boy, all the #ifdefs in 1001 locations and
622 * all the fumbling with configure.in and acconfig.h
623 * were *way* more work than the feature itself :-(
625 * - Because a generic redirect template was needed for
626 * this, tinygif = 3 now uses the same.
628 * - Moved GIFs, and other static HTTP response templates
633 * - Removed some >400 CRs again (Jon, you really worked
636 * Revision 1.3 2001/05/20 01:21:20 jongfoster
637 * Version 2.9.4 checkin.
638 * - Merged popupfile and cookiefile, and added control over PCRS
639 * filtering, in new "permissionsfile".
640 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
641 * file error you now get a message box (in the Win32 GUI) rather
642 * than the program exiting with no explanation.
643 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
645 * - Removed tabs from "config"
646 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
647 * - Bumped up version number.
649 * Revision 1.2 2001/05/17 23:02:36 oes
650 * - Made referrer option accept 'L' as a substitute for '§'
652 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
653 * Initial import of version 2.9.3 source tree
656 *********************************************************************/
663 #include <sys/types.h>
673 * Convince GNU's libc to provide a strptime prototype.
676 #endif /*__GLIBC__ */
683 #if !defined(_WIN32) && !defined(__OS2__)
689 #ifdef FEATURE_PTHREAD
691 /* jcc.h is for mutex semapores only */
692 #endif /* def FEATURE_PTHREAD */
698 #include "jbsockets.h"
699 #include "miscutil.h"
703 #ifndef HAVE_STRPTIME
704 #include "strptime.h"
707 const char parsers_h_rcs[] = PARSERS_H_VERSION;
709 /* Fix a problem with Solaris. There should be no effect on other
711 * Solaris's isspace() is a macro which uses its argument directly
712 * as an array index. Therefore we need to make sure that high-bit
713 * characters generate +ve values, and ideally we also want to make
714 * the argument match the declared parameter type of "int".
716 * Why did they write a character function that can't take a simple
717 * "char" argument? Doh!
719 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
720 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
722 jb_err header_tagger(struct client_state *csp, char *header);
723 jb_err scan_headers(struct client_state *csp);
725 const struct parsers client_patterns[] = {
726 { "referer:", 8, client_referrer },
727 { "user-agent:", 11, client_uagent },
728 { "ua-", 3, client_ua },
729 { "from:", 5, client_from },
730 { "cookie:", 7, client_send_cookie },
731 { "x-forwarded-for:", 16, client_x_forwarded },
732 { "Accept-Encoding:", 16, client_accept_encoding },
733 { "TE:", 3, client_te },
734 { "Host:", 5, client_host },
735 { "if-modified-since:", 18, client_if_modified_since },
736 { "Keep-Alive:", 11, crumble },
737 { "connection:", 11, connection },
738 { "proxy-connection:", 17, crumble },
739 { "max-forwards:", 13, client_max_forwards },
740 { "Accept-Language:", 16, client_accept_language },
741 { "if-none-match:", 14, client_if_none_match },
742 { "X-Filter:", 9, client_x_filter },
743 { "*", 0, crunch_client_header },
744 { "*", 0, filter_header },
748 const struct parsers server_patterns[] = {
749 { "HTTP", 4, server_http },
750 { "set-cookie:", 11, server_set_cookie },
751 { "connection:", 11, connection },
752 { "Content-Type:", 13, server_content_type },
753 { "Content-MD5:", 12, server_content_md5 },
754 { "Content-Encoding:", 17, server_content_encoding },
755 { "Transfer-Encoding:", 18, server_transfer_coding },
756 { "Keep-Alive:", 11, crumble },
757 { "content-disposition:", 20, server_content_disposition },
758 { "Last-Modified:", 14, server_last_modified },
759 { "*", 0, crunch_server_header },
760 { "*", 0, filter_header },
764 const struct parsers server_patterns_light[] = {
765 { "Content-Length:", 15, server_content_length },
766 { "Transfer-Encoding:", 18, server_transfer_coding },
768 { "Content-Encoding:", 17, server_content_encoding },
769 #endif /* def FEATURE_ZLIB */
773 const add_header_func_ptr add_client_headers[] = {
776 client_x_forwarded_adder,
778 /* Temporarily disabled: client_accept_encoding_adder, */
779 connection_close_adder,
784 const add_header_func_ptr add_server_headers[] = {
785 connection_close_adder,
789 /*********************************************************************
791 * Function : flush_socket
793 * Description : Write any pending "buffered" content.
796 * 1 : fd = file descriptor of the socket to read
797 * 2 : csp = Current client state (buffers, headers, etc...)
799 * Returns : On success, the number of bytes written are returned (zero
800 * indicates nothing was written). On error, -1 is returned,
801 * and errno is set appropriately. If count is zero and the
802 * file descriptor refers to a regular file, 0 will be
803 * returned without causing any other effect. For a special
804 * file, the results are not portable.
806 *********************************************************************/
807 int flush_socket(jb_socket fd, struct client_state *csp)
809 struct iob *iob = csp->iob;
810 int len = iob->eod - iob->cur;
817 if (write_socket(fd, iob->cur, (size_t)len))
821 iob->eod = iob->cur = iob->buf;
827 /*********************************************************************
829 * Function : add_to_iob
831 * Description : Add content to the buffered page, expanding the
832 * buffer if necessary.
835 * 1 : csp = Current client state (buffers, headers, etc...)
836 * 2 : buf = holds the content to be added to the page
837 * 3 : n = number of bytes to be added
839 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
840 * or buffer limit reached.
842 *********************************************************************/
843 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
845 struct iob *iob = csp->iob;
846 size_t used, offset, need, want;
849 if (n <= 0) return JB_ERR_OK;
851 used = (size_t)(iob->eod - iob->buf);
852 offset = (size_t)(iob->cur - iob->buf);
853 need = used + (size_t)n + 1;
856 * If the buffer can't hold the new data, extend it first.
857 * Use the next power of two if possible, else use the actual need.
859 if (need > csp->config->buffer_limit)
861 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
862 return JB_ERR_MEMORY;
865 if (need > iob->size)
867 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
869 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
873 else if (NULL != (p = (char *)realloc(iob->buf, need)))
879 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
880 return JB_ERR_MEMORY;
883 /* Update the iob pointers */
884 iob->cur = p + offset;
889 /* copy the new data into the iob buffer */
890 memcpy(iob->eod, buf, (size_t)n);
892 /* point to the end of the data */
895 /* null terminate == cheap insurance */
904 /*********************************************************************
906 * Function : decompress_iob
908 * Description : Decompress buffered page, expanding the
909 * buffer as necessary. csp->iob->cur
910 * should point to the the beginning of the
911 * compressed data block.
914 * 1 : csp = Current client state (buffers, headers, etc...)
916 * Returns : JB_ERR_OK on success,
917 * JB_ERR_MEMORY if out-of-memory limit reached, and
918 * JB_ERR_COMPRESS if error decompressing buffer.
920 *********************************************************************/
921 jb_err decompress_iob(struct client_state *csp)
923 char *buf; /* new, uncompressed buffer */
924 char *cur; /* Current iob position (to keep the original
925 * iob->cur unmodified if we return early) */
926 size_t bufsize; /* allocated size of the new buffer */
927 size_t old_size; /* Content size before decompression */
928 size_t skip_size; /* Number of bytes at the beginning of the iob
929 that we should NOT decompress. */
930 int status; /* return status of the inflate() call */
931 z_stream zstr; /* used by calls to zlib */
933 assert(csp->iob->cur - csp->iob->buf > 0);
934 assert(csp->iob->eod - csp->iob->cur > 0);
936 bufsize = csp->iob->size;
937 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
938 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
945 * This is to protect the parsing of gzipped data,
946 * but it should(?) be valid for deflated data also.
948 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
949 return JB_ERR_COMPRESS;
952 if (csp->content_type & CT_GZIP)
955 * Our task is slightly complicated by the facts that data
956 * compressed by gzip does not include a zlib header, and
957 * that there is no easily accessible interface in zlib to
958 * handle a gzip header. We strip off the gzip header by
959 * hand, and later inform zlib not to expect a header.
963 * Strip off the gzip header. Please see RFC 1952 for more
964 * explanation of the appropriate fields.
966 if ((*cur++ != (char)0x1f)
967 || (*cur++ != (char)0x8b)
968 || (*cur++ != Z_DEFLATED))
970 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
971 return JB_ERR_COMPRESS;
977 * XXX: These magic numbers should be replaced
978 * with macros to give a better idea what they do.
982 /* The gzip header has reserved bits set; bail out. */
983 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
984 return JB_ERR_COMPRESS;
988 /* Skip extra fields if necessary. */
992 * Skip a given number of bytes, specified
993 * as a 16-bit little-endian value.
996 * XXX: This code used to be:
998 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1000 * which I had to change into:
1002 * cur += *cur++ + (*cur++ << 8);
1004 * at which point gcc43 finally noticed that the value
1005 * of cur is undefined (it depends on which of the
1006 * summands is evaluated first).
1008 * I haven't come across a site where this
1009 * code is actually executed yet, but I hope
1013 skip_bytes = *cur++;
1014 skip_bytes = *cur++ << 8;
1016 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1019 * The number of bytes to skip should be positive
1020 * and we'd like to stay in the buffer.
1022 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1024 log_error (LOG_LEVEL_ERROR,
1025 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1027 return JB_ERR_COMPRESS;
1029 log_error (LOG_LEVEL_INFO,
1030 "Skipping %d bytes for gzip compression. Does this sound right?",
1035 /* Skip the filename if necessary. */
1038 /* A null-terminated string is supposed to follow. */
1039 while (*cur++ && (cur < csp->iob->eod));
1043 /* Skip the comment if necessary. */
1046 /* A null-terminated string is supposed to follow. */
1047 while (*cur++ && (cur < csp->iob->eod));
1050 /* Skip the CRC if necessary. */
1056 if (cur >= csp->iob->eod)
1059 * If the current position pointer reached or passed
1060 * the buffer end, we were obviously tricked to skip
1063 log_error (LOG_LEVEL_ERROR,
1064 "Malformed gzip header detected. Aborting decompression.");
1065 return JB_ERR_COMPRESS;
1069 else if (csp->content_type & CT_DEFLATE)
1072 * XXX: The debug level should be lowered
1073 * before the next stable release.
1075 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1077 * In theory (that is, according to RFC 1950), deflate-compressed
1078 * data should begin with a two-byte zlib header and have an
1079 * adler32 checksum at the end. It seems that in practice only
1080 * the raw compressed data is sent. Note that this means that
1081 * we are not RFC 1950-compliant here, but the advantage is that
1082 * this actually works. :)
1084 * We add a dummy null byte to tell zlib where the data ends,
1085 * and later inform it not to expect a header.
1087 * Fortunately, add_to_iob() has thoughtfully null-terminated
1088 * the buffer; we can just increment the end pointer to include
1095 log_error (LOG_LEVEL_ERROR,
1096 "Unable to determine compression format for decompression");
1097 return JB_ERR_COMPRESS;
1100 /* Set up the fields required by zlib. */
1101 zstr.next_in = (Bytef *)cur;
1102 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1103 zstr.zalloc = Z_NULL;
1104 zstr.zfree = Z_NULL;
1105 zstr.opaque = Z_NULL;
1108 * Passing -MAX_WBITS to inflateInit2 tells the library
1109 * that there is no zlib header.
1111 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1113 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1114 return JB_ERR_COMPRESS;
1118 * Next, we allocate new storage for the inflated data.
1119 * We don't modify the existing iob yet, so in case there
1120 * is error in decompression we can recover gracefully.
1122 buf = zalloc (bufsize);
1125 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1126 return JB_ERR_MEMORY;
1129 assert(bufsize >= skip_size);
1130 memcpy(buf, csp->iob->buf, skip_size);
1131 zstr.avail_out = bufsize - skip_size;
1132 zstr.next_out = (Bytef *)buf + skip_size;
1134 /* Try to decompress the whole stream in one shot. */
1135 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1137 /* We need to allocate more memory for the output buffer. */
1139 char *tmpbuf; /* used for realloc'ing the buffer */
1140 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1143 * If zlib wants more data then there's a problem, because
1144 * the complete compressed file should have been buffered.
1146 if (0 == zstr.avail_in)
1148 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1149 return JB_ERR_COMPRESS;
1153 * If we tried the limit and still didn't have enough
1154 * memory, just give up.
1156 if (bufsize == csp->config->buffer_limit)
1158 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1159 return JB_ERR_MEMORY;
1162 /* Try doubling the buffer size each time. */
1165 /* Don't exceed the buffer limit. */
1166 if (bufsize > csp->config->buffer_limit)
1168 bufsize = csp->config->buffer_limit;
1171 /* Try to allocate the new buffer. */
1172 tmpbuf = realloc(buf, bufsize);
1175 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1177 return JB_ERR_MEMORY;
1181 char *oldnext_out = (char *)zstr.next_out;
1184 * Update the fields for inflate() to use the new
1185 * buffer, which may be in a location different from
1188 zstr.avail_out += bufsize - oldbufsize;
1189 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1192 * Compare with an uglier method of calculating these values
1193 * that doesn't require the extra oldbufsize variable.
1195 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1196 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1197 assert(zstr.avail_out > 0);
1203 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1205 log_error(LOG_LEVEL_ERROR,
1206 "Inconsistent stream state after decompression: %s", zstr.msg);
1208 * XXX: Intentionally no return.
1210 * According to zlib.h, Z_STREAM_ERROR is returned
1211 * "if the stream state was inconsistent".
1213 * I assume in this case inflate()'s status
1214 * would also be something different than Z_STREAM_END
1215 * so this check should be redundant, but lets see.
1219 if (status != Z_STREAM_END)
1221 /* We failed to decompress the stream. */
1222 log_error(LOG_LEVEL_ERROR,
1223 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1224 return JB_ERR_COMPRESS;
1228 * Finally, we can actually update the iob, since the
1229 * decompression was successful. First, free the old
1232 freez(csp->iob->buf);
1234 /* Now, update the iob to use the new buffer. */
1235 csp->iob->buf = buf;
1236 csp->iob->cur = csp->iob->buf + skip_size;
1237 csp->iob->eod = (char *)zstr.next_out;
1238 csp->iob->size = bufsize;
1241 * Make sure the new uncompressed iob obeys some minimal
1242 * consistency conditions.
1244 if ((csp->iob->buf < csp->iob->cur)
1245 && (csp->iob->cur <= csp->iob->eod)
1246 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1248 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1251 log_error(LOG_LEVEL_RE_FILTER,
1252 "Decompression successful. Old size: %d, new size: %d.",
1253 old_size, new_size);
1257 /* zlib thinks this is OK, so lets do the same. */
1258 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1263 /* It seems that zlib did something weird. */
1264 log_error(LOG_LEVEL_ERROR,
1265 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1266 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1267 csp->iob->eod, csp->iob->buf + csp->iob->size);
1268 return JB_ERR_COMPRESS;
1274 #endif /* defined(FEATURE_ZLIB) */
1277 /*********************************************************************
1279 * Function : get_header
1281 * Description : This (odd) routine will parse the csp->iob
1284 * 1 : csp = Current client state (buffers, headers, etc...)
1286 * Returns : Any one of the following:
1288 * 1) a pointer to a dynamically allocated string that contains a header line
1289 * 2) NULL indicating that the end of the header was reached
1290 * 3) "" indicating that the end of the iob was reached before finding
1291 * a complete header line.
1293 *********************************************************************/
1294 char *get_header(struct client_state *csp)
1300 if ((iob->cur == NULL)
1301 || ((p = strchr(iob->cur, '\n')) == NULL))
1303 return(""); /* couldn't find a complete header */
1308 ret = strdup(iob->cur);
1311 /* FIXME No way to handle error properly */
1312 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1317 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1319 /* is this a blank line (i.e. the end of the header) ? */
1331 /*********************************************************************
1333 * Function : get_header_value
1335 * Description : Get the value of a given header from a chained list
1336 * of header lines or return NULL if no such header is
1337 * present in the list.
1340 * 1 : header_list = pointer to list
1341 * 2 : header_name = string with name of header to look for.
1342 * Trailing colon required, capitalization
1345 * Returns : NULL if not found, else value of header
1347 *********************************************************************/
1348 char *get_header_value(const struct list *header_list, const char *header_name)
1350 struct list_entry *cur_entry;
1354 assert(header_list);
1355 assert(header_name);
1356 length = strlen(header_name);
1358 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1362 if (!strncmpic(cur_entry->str, header_name, length))
1365 * Found: return pointer to start of value
1367 ret = (char *) (cur_entry->str + length);
1368 while (*ret && ijb_isspace(*ret)) ret++;
1382 /*********************************************************************
1384 * Function : scan_headers
1386 * Description : Scans headers, applies tags and updates action bits.
1389 * 1 : csp = Current client state (buffers, headers, etc...)
1391 * Returns : JB_ERR_OK
1393 *********************************************************************/
1394 jb_err scan_headers(struct client_state *csp)
1396 struct list_entry *h; /* Header */
1397 jb_err err = JB_ERR_OK;
1399 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1401 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1403 /* Header crunch()ed in previous run? -> ignore */
1404 if (h->str == NULL) continue;
1405 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1406 err = header_tagger(csp, h->str);
1410 * header_tagger already updated the action bits
1411 * for every new tag, but unless I'm confused,
1412 * updating them again after all tags are collected,
1413 * should give us another level of indirection when
1414 * it comes to tagging based on tags which were set
1415 * by tag sections which were active because of other
1416 * tag sections themselves (or something like this).
1418 update_action_bits_for_all_tags(csp);
1424 /*********************************************************************
1428 * Description : add, delete or modify lines in the HTTP header streams.
1429 * On entry, it receives a linked list of headers space
1430 * that was allocated dynamically (both the list nodes
1431 * and the header contents).
1433 * As a side effect it frees the space used by the original
1437 * 1 : pats = list of patterns to match against headers
1438 * 2 : more_headers = list of functions to add more
1439 * headers (client or server)
1440 * 3 : csp = Current client state (buffers, headers, etc...)
1442 * Returns : Single pointer to a fully formed header, or NULL
1443 * on out-of-memory error.
1445 *********************************************************************/
1446 char *sed(const struct parsers pats[],
1447 const add_header_func_ptr more_headers[],
1448 struct client_state *csp)
1450 struct list_entry *p;
1451 const struct parsers *v;
1452 const add_header_func_ptr *f;
1453 jb_err err = JB_ERR_OK;
1457 * If filtering is enabled, sed is run twice,
1458 * but most of the work needs to be done only once.
1460 first_run = (more_headers != NULL ) ? 1 : 0;
1462 if (first_run) /* Parse and print */
1466 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1468 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1470 /* Header crunch()ed in previous run? -> ignore */
1471 if (p->str == NULL) continue;
1473 /* Does the current parser handle this header? */
1474 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1476 err = v->parser(csp, (char **)&(p->str));
1480 /* place any additional headers on the csp->headers list */
1481 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1486 else /* Parse only */
1489 * The second run is only needed if the body was modified
1490 * and the content-lenght has changed.
1492 if (strncmpic(csp->http->cmd, "HEAD", 4))
1494 /*XXX: Code duplication */
1495 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1497 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1499 /* Header crunch()ed in previous run? -> ignore */
1500 if (p->str == NULL) continue;
1502 /* Does the current parser handle this header? */
1503 if (strncmpic(p->str, v->str, v->len) == 0)
1505 err = v->parser(csp, (char **)&(p->str));
1512 if (err != JB_ERR_OK)
1517 return list_to_text(csp->headers);
1522 /*********************************************************************
1524 * Function : header_tagger
1526 * Description : Executes all text substitutions from applying
1527 * tag actions and saves the result as tag.
1529 * XXX: Shares enough code with filter_header() and
1530 * pcrs_filter_response() to warrant some helper functions.
1533 * 1 : csp = Current client state (buffers, headers, etc...)
1534 * 2 : header = Header that is used as tagger input
1536 * Returns : JB_ERR_OK on success and always succeeds
1538 *********************************************************************/
1539 jb_err header_tagger(struct client_state *csp, char *header)
1541 int wanted_filter_type;
1542 int multi_action_index;
1546 struct file_list *fl;
1547 struct re_filterfile_spec *b;
1548 struct list_entry *tag_name;
1550 int found_filters = 0;
1551 const size_t header_length = strlen(header);
1553 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1555 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1556 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1560 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1561 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1564 /* Check if there are any filters */
1565 for (i = 0; i < MAX_AF_FILES; i++)
1578 if (0 == found_filters)
1580 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1584 for (i = 0; i < MAX_AF_FILES; i++)
1587 if ((NULL == fl) || (NULL == fl->f))
1590 * Either there are no filter files
1591 * left, or this filter file just
1592 * contains no valid filters.
1594 * Continue to be sure we don't miss
1595 * valid filter files that are chained
1596 * after empty or invalid ones.
1601 /* For all filters, */
1602 for (b = fl->f; b; b = b->next)
1604 if (b->type != wanted_filter_type)
1606 /* skip the ones we don't care about, */
1609 /* leaving only taggers that could apply, of which we use the ones, */
1610 for (tag_name = csp->action->multi[multi_action_index]->first;
1611 NULL != tag_name; tag_name = tag_name->next)
1613 /* that do apply, and */
1614 if (strcmp(b->name, tag_name->str) == 0)
1616 char *modified_tag = NULL;
1618 size_t size = header_length;
1620 if (NULL == b->joblist)
1622 log_error(LOG_LEVEL_RE_FILTER,
1623 "Tagger %s has empty joblist. Nothing to do.", b->name);
1627 /* execute their pcrs_joblist on the header. */
1628 for (job = b->joblist; NULL != job; job = job->next)
1630 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1634 /* Success, continue with the modified version. */
1643 /* Tagger doesn't match */
1646 /* Regex failure, log it but continue anyway. */
1647 log_error(LOG_LEVEL_ERROR,
1648 "Problems with tagger \'%s\' and header \'%s\': %s",
1649 b->name, *header, pcrs_strerror(hits));
1651 freez(modified_tag);
1655 /* If this tagger matched */
1661 * There is to technical limitation which makes
1662 * it impossible to use empty tags, but I assume
1663 * no one would do it intentionally.
1666 log_error(LOG_LEVEL_INFO,
1667 "Tagger \'%s\' created an empty tag. Ignored.",
1672 if (!list_contains_item(csp->tags, tag))
1674 if (JB_ERR_OK != enlist(csp->tags, tag))
1676 log_error(LOG_LEVEL_ERROR,
1677 "Insufficient memory to add tag \'%s\', "
1678 "based on tagger \'%s\' and header \'%s\'",
1679 tag, b->name, *header);
1683 char *action_message;
1685 * update the action bits right away, to make
1686 * tagging based on tags set by earlier taggers
1687 * of the same kind possible.
1689 if (update_action_bits_for_tag(csp, tag))
1691 action_message = "Action bits updated accordingly.";
1695 action_message = "No action bits update necessary.";
1698 log_error(LOG_LEVEL_HEADER,
1699 "Tagger \'%s\' added tag \'%s\'. %s",
1700 b->name, tag, action_message);
1705 /* XXX: Is this log-worthy? */
1706 log_error(LOG_LEVEL_HEADER,
1707 "Tagger \'%s\' didn't add tag \'%s\'. "
1708 "Tag already present", b->name, tag);
1711 } /* if the tagger matched */
1712 } /* if the tagger applies */
1713 } /* for every tagger that could apply */
1714 } /* for all filters */
1715 } /* for all filter files */
1720 /* here begins the family of parser functions that reformat header lines */
1722 /*********************************************************************
1724 * Function : filter_header
1726 * Description : Executes all text substitutions from all applying
1727 * +(server|client)-header-filter actions on the header.
1728 * Most of the code was copied from pcrs_filter_response,
1729 * including the rather short variable names
1732 * 1 : csp = Current client state (buffers, headers, etc...)
1733 * 2 : header = On input, pointer to header to modify.
1734 * On output, pointer to the modified header, or NULL
1735 * to remove the header. This function frees the
1736 * original string if necessary.
1738 * Returns : JB_ERR_OK on success and always succeeds
1740 *********************************************************************/
1741 jb_err filter_header(struct client_state *csp, char **header)
1745 size_t size = strlen(*header);
1747 char *newheader = NULL;
1750 struct file_list *fl;
1751 struct re_filterfile_spec *b;
1752 struct list_entry *filtername;
1754 int i, found_filters = 0;
1755 int wanted_filter_type;
1756 int multi_action_index;
1758 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1760 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1761 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1765 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1766 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1770 * Need to check the set of re_filterfiles...
1772 for (i = 0; i < MAX_AF_FILES; i++)
1785 if (0 == found_filters)
1787 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1791 for (i = 0; i < MAX_AF_FILES; i++)
1794 if ((NULL == fl) || (NULL == fl->f))
1797 * Either there are no filter files
1798 * left, or this filter file just
1799 * contains no valid filters.
1801 * Continue to be sure we don't miss
1802 * valid filter files that are chained
1803 * after empty or invalid ones.
1808 * For all applying +filter actions, look if a filter by that
1809 * name exists and if yes, execute its pcrs_joblist on the
1812 for (b = fl->f; b; b = b->next)
1814 if (b->type != wanted_filter_type)
1816 /* Skip other filter types */
1820 for (filtername = csp->action->multi[multi_action_index]->first;
1821 filtername ; filtername = filtername->next)
1823 if (strcmp(b->name, filtername->str) == 0)
1825 int current_hits = 0;
1827 if ( NULL == b->joblist )
1829 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1833 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1834 *header, size, b->name);
1836 /* Apply all jobs from the joblist */
1837 for (job = b->joblist; NULL != job; job = job->next)
1839 matches = pcrs_execute(job, *header, size, &newheader, &size);
1842 current_hits += matches;
1843 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1845 *header = newheader;
1847 else if ( 0 == matches )
1849 /* Filter doesn't change header */
1855 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1856 *header, b->name, pcrs_strerror(matches));
1857 if( newheader != NULL)
1859 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1864 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1865 hits += current_hits;
1872 * Additionally checking for hits is important because if
1873 * the continue hack is triggered, server headers can
1874 * arrive empty to separate multiple heads from each other.
1876 if ((0 == size) && hits)
1878 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1886 /*********************************************************************
1888 * Function : connection
1890 * Description : Makes sure that the value of the Connection: header
1891 * is "close" and signals connection_close_adder
1895 * 1 : csp = Current client state (buffers, headers, etc...)
1896 * 2 : header = On input, pointer to header to modify.
1897 * On output, pointer to the modified header, or NULL
1898 * to remove the header. This function frees the
1899 * original string if necessary.
1901 * Returns : JB_ERR_OK on success, or
1902 * JB_ERR_MEMORY on out-of-memory error.
1904 *********************************************************************/
1905 jb_err connection(struct client_state *csp, char **header)
1907 char *old_header = *header;
1909 /* Do we have a 'Connection: close' header? */
1910 if (strcmpic(*header, "Connection: close"))
1912 /* No, create one */
1913 *header = strdup("Connection: close");
1916 return JB_ERR_MEMORY;
1918 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1922 /* Signal connection_close_adder() to return early. */
1923 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1925 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
1929 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
1936 /*********************************************************************
1938 * Function : crumble
1940 * Description : This is called if a header matches a pattern to "crunch"
1943 * 1 : csp = Current client state (buffers, headers, etc...)
1944 * 2 : header = On input, pointer to header to modify.
1945 * On output, pointer to the modified header, or NULL
1946 * to remove the header. This function frees the
1947 * original string if necessary.
1949 * Returns : JB_ERR_OK on success, or
1950 * JB_ERR_MEMORY on out-of-memory error.
1952 *********************************************************************/
1953 jb_err crumble(struct client_state *csp, char **header)
1955 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1960 /*********************************************************************
1962 * Function : crunch_server_header
1964 * Description : Crunch server header if it matches a string supplied by the
1965 * user. Called from `sed'.
1968 * 1 : csp = Current client state (buffers, headers, etc...)
1969 * 2 : header = On input, pointer to header to modify.
1970 * On output, pointer to the modified header, or NULL
1971 * to remove the header. This function frees the
1972 * original string if necessary.
1974 * Returns : JB_ERR_OK on success and always succeeds
1976 *********************************************************************/
1977 jb_err crunch_server_header(struct client_state *csp, char **header)
1979 const char *crunch_pattern;
1981 /* Do we feel like crunching? */
1982 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1984 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1986 /* Is the current header the lucky one? */
1987 if (strstr(*header, crunch_pattern))
1989 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1998 /*********************************************************************
2000 * Function : server_content_type
2002 * Description : Set the content-type for filterable types (text/.*,
2003 * .*xml.*, javascript and image/gif) unless filtering has been
2004 * forbidden (CT_TABOO) while parsing earlier headers.
2005 * NOTE: Since text/plain is commonly used by web servers
2006 * for files whose correct type is unknown, we don't
2007 * set CT_TEXT for it.
2010 * 1 : csp = Current client state (buffers, headers, etc...)
2011 * 2 : header = On input, pointer to header to modify.
2012 * On output, pointer to the modified header, or NULL
2013 * to remove the header. This function frees the
2014 * original string if necessary.
2016 * Returns : JB_ERR_OK on success, or
2017 * JB_ERR_MEMORY on out-of-memory error.
2019 *********************************************************************/
2020 jb_err server_content_type(struct client_state *csp, char **header)
2022 /* Remove header if it isn't the first Content-Type header */
2023 if(csp->content_type && (csp->content_type != CT_TABOO))
2026 * Another, slightly slower, way to see if
2027 * we already parsed another Content-Type header.
2029 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2031 log_error(LOG_LEVEL_ERROR,
2032 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2039 if (!(csp->content_type & CT_TABOO))
2041 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2042 || strstr(*header, "xml")
2043 || strstr(*header, "application/x-javascript"))
2045 csp->content_type |= CT_TEXT;
2047 else if (strstr(*header, " image/gif"))
2049 csp->content_type |= CT_GIF;
2051 else if (strstr(*header, " image/jpeg"))
2053 csp->content_type |= CT_JPEG;
2057 csp->content_type = 0;
2061 * Are we enabling text mode by force?
2063 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2066 * Do we really have to?
2068 if (csp->content_type & CT_TEXT)
2070 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
2074 csp->content_type |= CT_TEXT;
2075 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
2079 * Are we messing with the content type?
2081 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2084 * Make sure the user doesn't accidently
2085 * change the content type of binary documents.
2087 if (csp->content_type & CT_TEXT)
2090 *header = strdup("Content-Type: ");
2091 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2095 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2096 return JB_ERR_MEMORY;
2098 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2102 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2103 "Enable force-text-mode if you know what you're doing.", *header);
2110 /*********************************************************************
2112 * Function : server_transfer_coding
2114 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2115 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2116 * - Remove header if body was chunked but has been
2117 * de-chunked for filtering.
2120 * 1 : csp = Current client state (buffers, headers, etc...)
2121 * 2 : header = On input, pointer to header to modify.
2122 * On output, pointer to the modified header, or NULL
2123 * to remove the header. This function frees the
2124 * original string if necessary.
2126 * Returns : JB_ERR_OK on success, or
2127 * JB_ERR_MEMORY on out-of-memory error.
2129 *********************************************************************/
2130 jb_err server_transfer_coding(struct client_state *csp, char **header)
2133 * Turn off pcrs and gif filtering if body compressed
2135 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2139 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2141 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2142 csp->http->cmd, *header);
2143 #endif /* def FEATURE_ZLIB */
2144 csp->content_type = CT_TABOO;
2148 * Raise flag if body chunked
2150 if (strstr(*header, "chunked"))
2152 csp->flags |= CSP_FLAG_CHUNKED;
2155 * If the body was modified, it has been de-chunked first
2156 * and the header must be removed.
2158 * FIXME: If there is more than one transfer encoding,
2159 * only the "chunked" part should be removed here.
2161 if (csp->flags & CSP_FLAG_MODIFIED)
2163 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2172 /*********************************************************************
2174 * Function : server_content_encoding
2176 * Description : This function is run twice for each request,
2177 * unless FEATURE_ZLIB and filtering are disabled.
2179 * The first run is used to check if the content
2180 * is compressed, if FEATURE_ZLIB is disabled
2181 * filtering is then disabled as well, if FEATURE_ZLIB
2182 * is enabled the content is marked for decompression.
2184 * The second run is used to remove the Content-Encoding
2185 * header if the decompression was successful.
2188 * 1 : csp = Current client state (buffers, headers, etc...)
2189 * 2 : header = On input, pointer to header to modify.
2190 * On output, pointer to the modified header, or NULL
2191 * to remove the header. This function frees the
2192 * original string if necessary.
2194 * Returns : JB_ERR_OK on success, or
2195 * JB_ERR_MEMORY on out-of-memory error.
2197 *********************************************************************/
2198 jb_err server_content_encoding(struct client_state *csp, char **header)
2201 if ((csp->flags & CSP_FLAG_MODIFIED)
2202 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2205 * We successfully decompressed the content,
2206 * and have to clean the header now, so the
2207 * client no longer expects compressed data..
2209 * XXX: There is a difference between cleaning
2210 * and removing it completely.
2212 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2215 else if (strstr(*header, "gzip"))
2217 /* Mark for gzip decompression */
2218 csp->content_type |= CT_GZIP;
2220 else if (strstr(*header, "deflate"))
2222 /* Mark for zlib decompression */
2223 csp->content_type |= CT_DEFLATE;
2225 else if (strstr(*header, "compress"))
2228 * We can't decompress this; therefore we can't filter
2231 csp->content_type |= CT_TABOO;
2233 #else /* !defined(FEATURE_ZLIB) */
2234 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2237 * Body is compressed, turn off pcrs and gif filtering.
2239 csp->content_type |= CT_TABOO;
2242 * Log a warning if the user expects the content to be filtered.
2244 if ((csp->rlist != NULL) &&
2245 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2247 log_error(LOG_LEVEL_INFO,
2248 "Compressed content detected, content filtering disabled. "
2249 "Consider recompiling Privoxy with zlib support or "
2250 "enable the prevent-compression action.");
2253 #endif /* defined(FEATURE_ZLIB) */
2260 /*********************************************************************
2262 * Function : server_content_length
2264 * Description : Adjust Content-Length header if we modified
2268 * 1 : csp = Current client state (buffers, headers, etc...)
2269 * 2 : header = On input, pointer to header to modify.
2270 * On output, pointer to the modified header, or NULL
2271 * to remove the header. This function frees the
2272 * original string if necessary.
2274 * Returns : JB_ERR_OK on success, or
2275 * JB_ERR_MEMORY on out-of-memory error.
2277 *********************************************************************/
2278 jb_err server_content_length(struct client_state *csp, char **header)
2280 const size_t max_header_length = 80;
2282 /* Regenerate header if the content was modified. */
2283 if (csp->flags & CSP_FLAG_MODIFIED)
2286 *header = (char *) zalloc(max_header_length);
2287 if (*header == NULL)
2289 return JB_ERR_MEMORY;
2292 snprintf(*header, max_header_length, "Content-Length: %d",
2293 (int)csp->content_length);
2294 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2295 (int)csp->content_length);
2302 /*********************************************************************
2304 * Function : server_content_md5
2306 * Description : Crumble any Content-MD5 headers if the document was
2307 * modified. FIXME: Should we re-compute instead?
2310 * 1 : csp = Current client state (buffers, headers, etc...)
2311 * 2 : header = On input, pointer to header to modify.
2312 * On output, pointer to the modified header, or NULL
2313 * to remove the header. This function frees the
2314 * original string if necessary.
2316 * Returns : JB_ERR_OK on success, or
2317 * JB_ERR_MEMORY on out-of-memory error.
2319 *********************************************************************/
2320 jb_err server_content_md5(struct client_state *csp, char **header)
2322 if (csp->flags & CSP_FLAG_MODIFIED)
2324 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2331 /*********************************************************************
2333 * Function : server_content_disposition
2335 * Description : If enabled, blocks or modifies the "content-disposition" header.
2336 * Called from `sed'.
2339 * 1 : csp = Current client state (buffers, headers, etc...)
2340 * 2 : header = On input, pointer to header to modify.
2341 * On output, pointer to the modified header, or NULL
2342 * to remove the header. This function frees the
2343 * original string if necessary.
2345 * Returns : JB_ERR_OK on success, or
2346 * JB_ERR_MEMORY on out-of-memory error.
2348 *********************************************************************/
2349 jb_err server_content_disposition(struct client_state *csp, char **header)
2354 * Are we messing with the content-disposition header?
2356 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2362 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2364 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2367 * Blocking content-disposition header
2369 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2376 * Replacing content-disposition header
2379 *header = strdup("content-disposition: ");
2380 string_append(header, newval);
2382 if (*header == NULL)
2384 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2388 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2391 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2394 /*********************************************************************
2396 * Function : server_last_modified
2398 * Description : Changes Last-Modified header to the actual date
2399 * to help hide-if-modified-since.
2400 * Called from `sed'.
2403 * 1 : csp = Current client state (buffers, headers, etc...)
2404 * 2 : header = On input, pointer to header to modify.
2405 * On output, pointer to the modified header, or NULL
2406 * to remove the header. This function frees the
2407 * original string if necessary.
2409 * Returns : JB_ERR_OK on success, or
2410 * JB_ERR_MEMORY on out-of-memory error.
2412 *********************************************************************/
2413 jb_err server_last_modified(struct client_state *csp, char **header)
2416 char buf[BUFFER_SIZE];
2419 #ifdef HAVE_GMTIME_R
2422 struct tm *timeptr = NULL;
2423 time_t now, last_modified;
2425 long int days, hours, minutes, seconds;
2428 * Are we messing with the Last-Modified header?
2430 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2436 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2438 if (0 == strcmpic(newval, "block") )
2441 * Blocking Last-Modified header. Useless but why not.
2443 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2447 else if (0 == strcmpic(newval, "reset-to-request-time"))
2450 * Setting Last-Modified Header to now.
2452 get_http_time(0, buf);
2454 *header = strdup("Last-Modified: ");
2455 string_append(header, buf);
2457 if (*header == NULL)
2459 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2463 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2466 else if (0 == strcmpic(newval, "randomize"))
2468 const char *header_time = *header + sizeof("Last-Modified:");
2470 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2472 #ifdef HAVE_GMTIME_R
2473 timeptr = gmtime_r(&now, &gmt);
2474 #elif FEATURE_PTHREAD
2475 pthread_mutex_lock(&gmtime_mutex);
2476 timeptr = gmtime(&now);
2477 pthread_mutex_unlock(&gmtime_mutex);
2479 timeptr = gmtime(&now);
2481 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2483 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2488 rtime = (long int)difftime(now, last_modified);
2491 rtime = pick_from_range(rtime);
2492 last_modified += rtime;
2493 #ifdef HAVE_GMTIME_R
2494 timeptr = gmtime_r(&last_modified, &gmt);
2495 #elif FEATURE_PTHREAD
2496 pthread_mutex_lock(&gmtime_mutex);
2497 timeptr = gmtime(&last_modified);
2498 pthread_mutex_unlock(&gmtime_mutex);
2500 timeptr = gmtime(&last_modified);
2502 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2504 *header = strdup("Last-Modified: ");
2505 string_append(header, newheader);
2507 if (*header == NULL)
2509 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2510 return JB_ERR_MEMORY;
2513 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2515 days = rtime / (3600 * 24);
2516 hours = rtime / 3600 % 24;
2517 minutes = rtime / 60 % 60;
2518 seconds = rtime % 60;
2520 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2521 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2522 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2527 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2536 /*********************************************************************
2538 * Function : client_accept_encoding
2540 * Description : Rewrite the client's Accept-Encoding header so that
2541 * if doesn't allow compression, if the action applies.
2542 * Note: For HTTP/1.0 the absence of the header is enough.
2545 * 1 : csp = Current client state (buffers, headers, etc...)
2546 * 2 : header = On input, pointer to header to modify.
2547 * On output, pointer to the modified header, or NULL
2548 * to remove the header. This function frees the
2549 * original string if necessary.
2551 * Returns : JB_ERR_OK on success, or
2552 * JB_ERR_MEMORY on out-of-memory error.
2554 *********************************************************************/
2555 jb_err client_accept_encoding(struct client_state *csp, char **header)
2557 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2559 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2563 /* Temporarily disable the correct behaviour to
2564 * work around a PHP bug.
2566 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2568 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2569 * if (*header == NULL)
2571 * return JB_ERR_MEMORY;
2582 /*********************************************************************
2584 * Function : client_te
2586 * Description : Rewrite the client's TE header so that
2587 * if doesn't allow compression, if the action applies.
2590 * 1 : csp = Current client state (buffers, headers, etc...)
2591 * 2 : header = On input, pointer to header to modify.
2592 * On output, pointer to the modified header, or NULL
2593 * to remove the header. This function frees the
2594 * original string if necessary.
2596 * Returns : JB_ERR_OK on success, or
2597 * JB_ERR_MEMORY on out-of-memory error.
2599 *********************************************************************/
2600 jb_err client_te(struct client_state *csp, char **header)
2602 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2605 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2611 /*********************************************************************
2613 * Function : client_referrer
2615 * Description : Handle the "referer" config setting properly.
2616 * Called from `sed'.
2619 * 1 : csp = Current client state (buffers, headers, etc...)
2620 * 2 : header = On input, pointer to header to modify.
2621 * On output, pointer to the modified header, or NULL
2622 * to remove the header. This function frees the
2623 * original string if necessary.
2625 * Returns : JB_ERR_OK on success, or
2626 * JB_ERR_MEMORY on out-of-memory error.
2628 *********************************************************************/
2629 jb_err client_referrer(struct client_state *csp, char **header)
2636 #ifdef FEATURE_FORCE_LOAD
2637 /* Since the referrer can include the prefix even
2638 * if the request itself is non-forced, we must
2639 * clean it unconditionally
2641 strclean(*header, FORCE_PREFIX);
2642 #endif /* def FEATURE_FORCE_LOAD */
2645 * Are we sending referer?
2647 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2652 newval = csp->action->string[ACTION_STRING_REFERER];
2654 if ((0 != strcmpic(newval, "conditional-block")))
2658 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2663 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2666 else if (0 == strcmpic(newval, "conditional-block"))
2669 * Block referer if host has changed.
2672 if (NULL == (host = strdup(csp->http->hostport)))
2675 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2676 return JB_ERR_MEMORY;
2678 if (NULL == (referer = strdup(*header)))
2682 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2683 return JB_ERR_MEMORY;
2685 hostlenght = strlen(host);
2686 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2688 /*Shorten referer to make sure the referer is blocked
2689 *if www.example.org/www.example.com-shall-see-the-referer/
2690 *links to www.example.com/
2692 referer[hostlenght+17] = '\0';
2694 if ( 0 == strstr(referer, host)) /*Host has changed*/
2696 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2701 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2707 else if (0 != strcmpic(newval, "forge"))
2710 * We have a specific (fixed) referer we want to send.
2712 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2714 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2716 *header = strdup("Referer: ");
2717 string_append(header, newval);
2718 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2720 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2725 * Forge a referer as http://[hostname:port of REQUEST]/
2726 * to fool stupid checks for in-site links
2729 *header = strdup("Referer: http://");
2730 string_append(header, csp->http->hostport);
2731 string_append(header, "/");
2732 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2734 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2738 /*********************************************************************
2740 * Function : client_accept_language
2742 * Description : Handle the "Accept-Language" config setting properly.
2743 * Called from `sed'.
2746 * 1 : csp = Current client state (buffers, headers, etc...)
2747 * 2 : header = On input, pointer to header to modify.
2748 * On output, pointer to the modified header, or NULL
2749 * to remove the header. This function frees the
2750 * original string if necessary.
2752 * Returns : JB_ERR_OK on success, or
2753 * JB_ERR_MEMORY on out-of-memory error.
2755 *********************************************************************/
2756 jb_err client_accept_language(struct client_state *csp, char **header)
2761 * Are we messing with the Accept-Language?
2763 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2765 /*I don't think so*/
2769 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2771 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2774 * Blocking Accept-Language header
2776 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2783 * Replacing Accept-Language header
2786 *header = strdup("Accept-Language: ");
2787 string_append(header, newval);
2789 if (*header == NULL)
2791 log_error(LOG_LEVEL_ERROR,
2792 "Insufficent memory. Accept-Language header crunched without replacement.");
2796 log_error(LOG_LEVEL_HEADER,
2797 "Accept-Language header crunched and replaced with: %s", *header);
2800 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2803 /*********************************************************************
2805 * Function : crunch_client_header
2807 * Description : Crunch client header if it matches a string supplied by the
2808 * user. Called from `sed'.
2811 * 1 : csp = Current client state (buffers, headers, etc...)
2812 * 2 : header = On input, pointer to header to modify.
2813 * On output, pointer to the modified header, or NULL
2814 * to remove the header. This function frees the
2815 * original string if necessary.
2817 * Returns : JB_ERR_OK on success and always succeeds
2819 *********************************************************************/
2820 jb_err crunch_client_header(struct client_state *csp, char **header)
2822 const char *crunch_pattern;
2824 /* Do we feel like crunching? */
2825 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2827 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2829 /* Is the current header the lucky one? */
2830 if (strstr(*header, crunch_pattern))
2832 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2840 /*********************************************************************
2842 * Function : client_uagent
2844 * Description : Handle the "user-agent" config setting properly
2845 * and remember its original value to enable browser
2846 * bug workarounds. Called from `sed'.
2849 * 1 : csp = Current client state (buffers, headers, etc...)
2850 * 2 : header = On input, pointer to header to modify.
2851 * On output, pointer to the modified header, or NULL
2852 * to remove the header. This function frees the
2853 * original string if necessary.
2855 * Returns : JB_ERR_OK on success, or
2856 * JB_ERR_MEMORY on out-of-memory error.
2858 *********************************************************************/
2859 jb_err client_uagent(struct client_state *csp, char **header)
2863 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2868 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2875 *header = strdup("User-Agent: ");
2876 string_append(header, newval);
2878 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2880 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2883 /*********************************************************************
2885 * Function : client_ua
2887 * Description : Handle "ua-" headers properly. Called from `sed'.
2890 * 1 : csp = Current client state (buffers, headers, etc...)
2891 * 2 : header = On input, pointer to header to modify.
2892 * On output, pointer to the modified header, or NULL
2893 * to remove the header. This function frees the
2894 * original string if necessary.
2896 * Returns : JB_ERR_OK on success, or
2897 * JB_ERR_MEMORY on out-of-memory error.
2899 *********************************************************************/
2900 jb_err client_ua(struct client_state *csp, char **header)
2902 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2904 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2912 /*********************************************************************
2914 * Function : client_from
2916 * Description : Handle the "from" config setting properly.
2917 * Called from `sed'.
2920 * 1 : csp = Current client state (buffers, headers, etc...)
2921 * 2 : header = On input, pointer to header to modify.
2922 * On output, pointer to the modified header, or NULL
2923 * to remove the header. This function frees the
2924 * original string if necessary.
2926 * Returns : JB_ERR_OK on success, or
2927 * JB_ERR_MEMORY on out-of-memory error.
2929 *********************************************************************/
2930 jb_err client_from(struct client_state *csp, char **header)
2934 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2941 newval = csp->action->string[ACTION_STRING_FROM];
2944 * Are we blocking the e-mail address?
2946 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2948 log_error(LOG_LEVEL_HEADER, "crunched From!");
2952 log_error(LOG_LEVEL_HEADER, " modified");
2954 *header = strdup("From: ");
2955 string_append(header, newval);
2957 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2961 /*********************************************************************
2963 * Function : client_send_cookie
2965 * Description : Crunches the "cookie" header if necessary.
2966 * Called from `sed'.
2968 * XXX: Stupid name, doesn't send squat.
2971 * 1 : csp = Current client state (buffers, headers, etc...)
2972 * 2 : header = On input, pointer to header to modify.
2973 * On output, pointer to the modified header, or NULL
2974 * to remove the header. This function frees the
2975 * original string if necessary.
2977 * Returns : JB_ERR_OK on success, or
2978 * JB_ERR_MEMORY on out-of-memory error.
2980 *********************************************************************/
2981 jb_err client_send_cookie(struct client_state *csp, char **header)
2983 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2985 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2993 /*********************************************************************
2995 * Function : client_x_forwarded
2997 * Description : Handle the "x-forwarded-for" config setting properly,
2998 * also used in the add_client_headers list. Called from `sed'.
3001 * 1 : csp = Current client state (buffers, headers, etc...)
3002 * 2 : header = On input, pointer to header to modify.
3003 * On output, pointer to the modified header, or NULL
3004 * to remove the header. This function frees the
3005 * original string if necessary.
3007 * Returns : JB_ERR_OK on success, or
3008 * JB_ERR_MEMORY on out-of-memory error.
3010 *********************************************************************/
3011 jb_err client_x_forwarded(struct client_state *csp, char **header)
3013 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3015 /* Save it so we can re-add it later */
3016 freez(csp->x_forwarded);
3017 csp->x_forwarded = *header;
3020 * Always set *header = NULL, since this information
3021 * will be sent at the end of the header.
3028 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3035 /*********************************************************************
3037 * Function : client_max_forwards
3039 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3040 * from the value of the Max-Forwards header field.
3043 * 1 : csp = Current client state (buffers, headers, etc...)
3044 * 2 : header = On input, pointer to header to modify.
3045 * On output, pointer to the modified header, or NULL
3046 * to remove the header. This function frees the
3047 * original string if necessary.
3049 * Returns : JB_ERR_OK on success, or
3050 * JB_ERR_MEMORY on out-of-memory error.
3052 *********************************************************************/
3053 jb_err client_max_forwards(struct client_state *csp, char **header)
3057 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3058 (0 == strcmpic(csp->http->gpc, "options")))
3060 assert(*(*header+12) == ':');
3061 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3063 if (max_forwards > 0)
3065 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3066 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3067 csp->http->gpc, max_forwards);
3069 else if (max_forwards < 0)
3071 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3077 * Not supposed to be reached. direct_response() which
3078 * was already called earlier in chat() should have
3079 * intercepted the request.
3081 log_error(LOG_LEVEL_ERROR,
3082 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3083 assert(max_forwards != 0);
3088 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3097 /*********************************************************************
3099 * Function : client_host
3101 * Description : If the request URI did not contain host and
3102 * port information, parse and evaluate the Host
3105 * Also, kill ill-formed HOST: headers as sent by
3106 * Apple's iTunes software when used with a proxy.
3109 * 1 : csp = Current client state (buffers, headers, etc...)
3110 * 2 : header = On input, pointer to header to modify.
3111 * On output, pointer to the modified header, or NULL
3112 * to remove the header. This function frees the
3113 * original string if necessary.
3115 * Returns : JB_ERR_OK on success, or
3116 * JB_ERR_MEMORY on out-of-memory error.
3118 *********************************************************************/
3119 jb_err client_host(struct client_state *csp, char **header)
3124 * If the header field name is all upper-case, chances are that it's
3125 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3126 * not a problem -- they are regenerated later.
3128 if ((*header)[1] == 'O')
3130 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3135 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3136 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3139 if (NULL == (p = strdup((*header)+6)))
3141 return JB_ERR_MEMORY;
3144 if (NULL == (q = strdup(p)))
3147 return JB_ERR_MEMORY;
3150 freez(csp->http->hostport);
3151 csp->http->hostport = p;
3152 freez(csp->http->host);
3153 csp->http->host = q;
3154 q = strchr(csp->http->host, ':');
3157 /* Terminate hostname and evaluate port string */
3159 csp->http->port = atoi(q);
3163 csp->http->port = csp->http->ssl ? 443 : 80;
3166 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3167 csp->http->hostport, csp->http->host, csp->http->port);
3170 /* Signal client_host_adder() to return right away */
3171 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3176 /*********************************************************************
3178 * Function : client_if_modified_since
3180 * Description : Remove or modify the If-Modified-Since header.
3183 * 1 : csp = Current client state (buffers, headers, etc...)
3184 * 2 : header = On input, pointer to header to modify.
3185 * On output, pointer to the modified header, or NULL
3186 * to remove the header. This function frees the
3187 * original string if necessary.
3189 * Returns : JB_ERR_OK on success, or
3190 * JB_ERR_MEMORY on out-of-memory error.
3192 *********************************************************************/
3193 jb_err client_if_modified_since(struct client_state *csp, char **header)
3196 #ifdef HAVE_GMTIME_R
3199 struct tm *timeptr = NULL;
3203 long int hours, minutes, seconds;
3207 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3210 * The client got an error message because of a temporary problem,
3211 * the problem is gone and the client now tries to revalidate our
3212 * error message on the real server. The revalidation would always
3213 * end with the transmission of the whole document and there is
3214 * no need to expose the bogus If-Modified-Since header.
3216 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3219 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3221 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3223 if ((0 == strcmpic(newval, "block")))
3225 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3228 else /* add random value */
3230 const char *header_time = *header + sizeof("If-Modified-Since:");
3232 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3234 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3239 rtime = strtol(newval, &endptr, 0);
3242 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3243 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3250 rtime = pick_from_range(rtime);
3254 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3257 tm += rtime * (negative ? -1 : 1);
3258 #ifdef HAVE_GMTIME_R
3259 timeptr = gmtime_r(&tm, &gmt);
3260 #elif FEATURE_PTHREAD
3261 pthread_mutex_lock(&gmtime_mutex);
3262 timeptr = gmtime(&tm);
3263 pthread_mutex_unlock(&gmtime_mutex);
3265 timeptr = gmtime(&tm);
3267 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3270 *header = strdup("If-Modified-Since: ");
3271 string_append(header, newheader);
3273 if (*header == NULL)
3275 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3276 return JB_ERR_MEMORY;
3279 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3281 hours = rtime / 3600;
3282 minutes = rtime / 60 % 60;
3283 seconds = rtime % 60;
3285 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3286 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3287 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3296 /*********************************************************************
3298 * Function : client_if_none_match
3300 * Description : Remove the If-None-Match header.
3303 * 1 : csp = Current client state (buffers, headers, etc...)
3304 * 2 : header = On input, pointer to header to modify.
3305 * On output, pointer to the modified header, or NULL
3306 * to remove the header. This function frees the
3307 * original string if necessary.
3309 * Returns : JB_ERR_OK on success, or
3310 * JB_ERR_MEMORY on out-of-memory error.
3312 *********************************************************************/
3313 jb_err client_if_none_match(struct client_state *csp, char **header)
3315 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3317 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3324 /*********************************************************************
3326 * Function : client_x_filter
3328 * Description : Disables filtering if the client set "X-Filter: No".
3329 * Called from `sed'.
3332 * 1 : csp = Current client state (buffers, headers, etc...)
3333 * 2 : header = On input, pointer to header to modify.
3334 * On output, pointer to the modified header, or NULL
3335 * to remove the header. This function frees the
3336 * original string if necessary.
3338 * Returns : JB_ERR_OK on success
3340 *********************************************************************/
3341 jb_err client_x_filter(struct client_state *csp, char **header)
3343 if ( 0 == strcmpic(*header, "X-Filter: No"))
3345 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3347 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3351 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3353 log_error(LOG_LEVEL_HEADER,
3354 "force-text-mode overruled the client's request to fetch without filtering!");
3358 csp->content_type = CT_TABOO;
3359 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
3360 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
3361 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3363 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3370 /* the following functions add headers directly to the header list */
3372 /*********************************************************************
3374 * Function : client_host_adder
3376 * Description : Adds the Host: header field if it is missing.
3377 * Called from `sed'.
3380 * 1 : csp = Current client state (buffers, headers, etc...)
3382 * Returns : JB_ERR_OK on success, or
3383 * JB_ERR_MEMORY on out-of-memory error.
3385 *********************************************************************/
3386 jb_err client_host_adder(struct client_state *csp)
3391 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3393 /* Header already set by the client, nothing to do. */
3397 if ( !csp->http->hostport || !*(csp->http->hostport))
3399 /* XXX: When does this happen and why is it OK? */
3400 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3405 * remove 'user:pass@' from 'proto://user:pass@host'
3407 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3413 p = csp->http->hostport;
3416 /* XXX: Just add it, we already made sure that it will be unique */
3417 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3418 err = enlist_unique_header(csp->headers, "Host", p);
3424 /*********************************************************************
3426 * Function : client_cookie_adder
3428 * Description : Used in the add_client_headers list. Called from `sed'.
3430 * XXX: Remove csp->cookie_list which is no longer used.
3433 * 1 : csp = Current client state (buffers, headers, etc...)
3435 * Returns : JB_ERR_OK on success, or
3436 * JB_ERR_MEMORY on out-of-memory error.
3438 *********************************************************************/
3439 jb_err client_cookie_adder(struct client_state *csp)
3441 struct list_entry *lst;
3443 struct list_entry *list1 = csp->cookie_list->first;
3444 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
3445 int first_cookie = 1;
3448 if ((list1 == NULL) && (list2 == NULL))
3454 tmp = strdup("Cookie: ");
3456 for (lst = list1; lst ; lst = lst->next)
3464 string_append(&tmp, "; ");
3466 string_append(&tmp, lst->str);
3469 for (lst = list2; lst ; lst = lst->next)
3477 string_append(&tmp, "; ");
3479 string_join(&tmp, cookie_encode(lst->str));
3484 return JB_ERR_MEMORY;
3487 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3488 err = enlist(csp->headers, tmp);
3494 /*********************************************************************
3496 * Function : client_accept_encoding_adder
3498 * Description : Add an Accept-Encoding header to the client's request
3499 * that disables compression if the action applies, and
3500 * the header is not already there. Called from `sed'.
3501 * Note: For HTTP/1.0, the absence of the header is enough.
3504 * 1 : csp = Current client state (buffers, headers, etc...)
3506 * Returns : JB_ERR_OK on success, or
3507 * JB_ERR_MEMORY on out-of-memory error.
3509 *********************************************************************/
3510 jb_err client_accept_encoding_adder(struct client_state *csp)
3512 assert(0); /* Not in use */
3514 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3515 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3517 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3524 /*********************************************************************
3526 * Function : client_xtra_adder
3528 * Description : Used in the add_client_headers list. Called from `sed'.
3531 * 1 : csp = Current client state (buffers, headers, etc...)
3533 * Returns : JB_ERR_OK on success, or
3534 * JB_ERR_MEMORY on out-of-memory error.
3536 *********************************************************************/
3537 jb_err client_xtra_adder(struct client_state *csp)
3539 struct list_entry *lst;
3542 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3543 lst ; lst = lst->next)
3545 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3546 err = enlist(csp->headers, lst->str);
3558 /*********************************************************************
3560 * Function : client_x_forwarded_adder
3562 * Description : Used in the add_client_headers list. Called from `sed'.
3565 * 1 : csp = Current client state (buffers, headers, etc...)
3567 * Returns : JB_ERR_OK on success, or
3568 * JB_ERR_MEMORY on out-of-memory error.
3570 *********************************************************************/
3571 jb_err client_x_forwarded_adder(struct client_state *csp)
3576 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3581 if (csp->x_forwarded)
3583 p = strdup(csp->x_forwarded);
3584 string_append(&p, ", ");
3588 p = strdup("X-Forwarded-For: ");
3590 string_append(&p, csp->ip_addr_str);
3594 return JB_ERR_MEMORY;
3597 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3598 err = enlist(csp->headers, p);
3605 /*********************************************************************
3607 * Function : connection_close_adder
3609 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3610 * support. Adds a "Connection: close" header to csp->headers
3611 * unless the header was already present. Called from `sed'.
3613 * FIXME: This whole function shouldn't be neccessary!
3616 * 1 : csp = Current client state (buffers, headers, etc...)
3618 * Returns : JB_ERR_OK on success, or
3619 * JB_ERR_MEMORY on out-of-memory error.
3621 *********************************************************************/
3622 jb_err connection_close_adder(struct client_state *csp)
3624 const unsigned int flags = csp->flags;
3627 * Return right away if
3629 * - we're parsing server headers and the server header
3630 * "Connection: close" is already set, or if
3632 * - we're parsing client headers and the client header
3633 * "Connection: close" is already set.
3635 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3636 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3637 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3638 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3643 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3645 return enlist(csp->headers, "Connection: close");
3649 /*********************************************************************
3651 * Function : server_http
3653 * Description : - Save the HTTP Status into csp->http->status
3654 * - Set CT_TABOO to prevent filtering if the answer
3655 * is a partial range (HTTP status 206)
3656 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3660 * 1 : csp = Current client state (buffers, headers, etc...)
3661 * 2 : header = On input, pointer to header to modify.
3662 * On output, pointer to the modified header, or NULL
3663 * to remove the header. This function frees the
3664 * original string if necessary.
3666 * Returns : JB_ERR_OK on success, or
3667 * JB_ERR_MEMORY on out-of-memory error.
3669 *********************************************************************/
3670 jb_err server_http(struct client_state *csp, char **header)
3672 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3673 if (csp->http->status == 206)
3675 csp->content_type = CT_TABOO;
3678 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3681 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3688 /*********************************************************************
3690 * Function : server_set_cookie
3692 * Description : Handle the server "cookie" header properly.
3693 * Log cookie to the jar file. Then "crunch",
3694 * accept or rewrite it to a session cookie.
3695 * Called from `sed'.
3697 * TODO: Allow the user to specify a new expiration
3698 * time to cause the cookie to expire even before the
3699 * browser is closed.
3702 * 1 : csp = Current client state (buffers, headers, etc...)
3703 * 2 : header = On input, pointer to header to modify.
3704 * On output, pointer to the modified header, or NULL
3705 * to remove the header. This function frees the
3706 * original string if necessary.
3708 * Returns : JB_ERR_OK on success, or
3709 * JB_ERR_MEMORY on out-of-memory error.
3711 *********************************************************************/
3712 jb_err server_set_cookie(struct client_state *csp, char **header)
3719 #ifdef FEATURE_COOKIE_JAR
3720 if (csp->config->jar)
3723 * Write timestamp into outbuf.
3725 * Complex because not all OSs have tm_gmtoff or
3726 * the %z field in strftime()
3728 char tempbuf[ BUFFER_SIZE ];
3730 #ifdef HAVE_LOCALTIME_R
3731 tm_now = *localtime_r(&now, &tm_now);
3732 #elif FEATURE_PTHREAD
3733 pthread_mutex_lock(&localtime_mutex);
3734 tm_now = *localtime (&now);
3735 pthread_mutex_unlock(&localtime_mutex);
3737 tm_now = *localtime (&now);
3739 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3741 /* strlen("set-cookie: ") = 12 */
3742 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3744 #endif /* def FEATURE_COOKIE_JAR */
3746 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3748 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3751 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3753 /* Flag whether or not to log a message */
3756 /* A variable to store the tag we're working on */
3759 /* Skip "Set-Cookie:" (11 characters) in header */
3760 cur_tag = *header + 11;
3762 /* skip whitespace between "Set-Cookie:" and value */
3763 while (*cur_tag && ijb_isspace(*cur_tag))
3768 /* Loop through each tag in the cookie */
3772 char *next_tag = strchr(cur_tag, ';');
3773 if (next_tag != NULL)
3775 /* Skip the ';' character itself */
3778 /* skip whitespace ";" and start of tag */
3779 while (*next_tag && ijb_isspace(*next_tag))
3786 /* "Next tag" is the end of the string */
3787 next_tag = cur_tag + strlen(cur_tag);
3791 * Check the expiration date to see
3792 * if the cookie is still valid, if yes,
3793 * rewrite it to a session cookie.
3795 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3797 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3799 /* Did we detect the date properly? */
3800 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3803 * Nope, treat it as if it was still valid.
3805 * XXX: Should we remove the whole cookie instead?
3807 log_error(LOG_LEVEL_ERROR,
3808 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3809 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3815 * Yes. Check if the cookie is still valid.
3817 * If the cookie is already expired it's probably
3818 * a delete cookie and even if it isn't, the browser
3819 * will discard it anyway.
3823 * XXX: timegm() isn't available on some AmigaOS
3824 * versions and our replacement doesn't work.
3826 * Our options are to either:
3828 * - disable session-cookies-only completely if timegm
3831 * - to simply remove all expired tags, like it has
3832 * been done until Privoxy 3.0.6 and to live with
3833 * the consequence that it can cause login/logout
3834 * problems on servers that don't validate their
3835 * input properly, or
3837 * - to replace it with mktime in which
3838 * case there is a slight chance of valid cookies
3839 * passing as already expired.
3841 * This is the way it's currently done and it's not
3842 * as bad as it sounds. If the missing GMT offset is
3843 * enough to change the result of the expiration check
3844 * the cookie will be only valid for a few hours
3845 * anyway, which in many cases will be shorter
3846 * than a browser session.
3848 if (cookie_time - now < 0)
3850 log_error(LOG_LEVEL_HEADER,
3851 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3852 /* Just in case some clown sets more then one expiration date */
3858 * Still valid, delete expiration date by copying
3859 * the rest of the string over it.
3861 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3862 * since the behaviour of strcpy is undefined for overlapping
3865 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3867 /* That changed the header, need to issue a log message */
3871 * Note that the next tag has now been moved to *cur_tag,
3872 * so we do not need to update the cur_tag pointer.
3880 /* Move on to next cookie tag */
3887 assert(NULL != *header);
3888 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3897 #ifdef FEATURE_FORCE_LOAD
3898 /*********************************************************************
3900 * Function : strclean
3902 * Description : In-Situ-Eliminate all occurances of substring in
3906 * 1 : string = string to clean
3907 * 2 : substring = substring to eliminate
3909 * Returns : Number of eliminations
3911 *********************************************************************/
3912 int strclean(const char *string, const char *substring)
3918 len = strlen(substring);
3920 while((pos = strstr(string, substring)) != NULL)
3927 while (*p++ != '\0');
3934 #endif /* def FEATURE_FORCE_LOAD */
3936 /*********************************************************************
3938 * Function : parse_header_time
3940 * Description : Parses time formats used in HTTP header strings
3941 * to get the numerical respresentation.
3944 * 1 : header_time = HTTP header time as string.
3945 * 2 : result = storage for header_time in seconds
3947 * Returns : JB_ERR_OK if the time format was recognized, or
3948 * JB_ERR_PARSE otherwise.
3950 *********************************************************************/
3951 jb_err parse_header_time(const char *header_time, time_t *result)
3956 * Zero out gmt to prevent time zone offsets.
3958 * While this is only necessary on some platforms
3959 * (mingw32 for example), I don't know how to
3960 * detect these automatically and doing it everywhere
3963 memset(&gmt, 0, sizeof(gmt));
3965 /* Tue, 02 Jun 2037 20:00:00 */
3966 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3967 /* Tue, 02-Jun-2037 20:00:00 */
3968 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3969 /* Tue, 02-Jun-37 20:00:00 */
3970 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3971 /* Tuesday, 02-Jun-2037 20:00:00 */
3972 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3973 /* Tuesday Jun 02 20:00:00 2037 */
3974 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3976 return JB_ERR_PARSE;
3979 *result = timegm(&gmt);
3985 /*********************************************************************
3987 * Function : get_destination_from_headers
3989 * Description : Parse the "Host:" header to get the request's destination.
3990 * Only needed if the client's request was forcefully
3991 * redirected into Privoxy.
3993 * Code mainly copied from client_host() which is currently
3994 * run too late for this purpose.
3997 * 1 : headers = List of headers (one of them hopefully being
3998 * the "Host:" header)
3999 * 2 : http = storage for the result (host, port and hostport).
4001 * Returns : JB_ERR_MEMORY in case of memory problems,
4002 * JB_ERR_PARSE if the host header couldn't be found,
4003 * JB_ERR_OK otherwise.
4005 *********************************************************************/
4006 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4012 host = get_header_value(headers, "Host:");
4016 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4017 return JB_ERR_PARSE;
4020 if (NULL == (p = strdup((host))))
4022 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4023 return JB_ERR_MEMORY;
4026 if (NULL == (q = strdup(p)))
4029 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4030 return JB_ERR_MEMORY;
4033 freez(http->hostport);
4037 q = strchr(http->host, ':');
4040 /* Terminate hostname and evaluate port string */
4042 http->port = atoi(q);
4046 http->port = http->ssl ? 443 : 80;
4049 /* Rebuild request URL */
4051 http->url = strdup(http->ssl ? "https://" : "http://");
4052 string_append(&http->url, http->hostport);
4053 string_append(&http->url, http->path);
4054 if (http->url == NULL)
4056 return JB_ERR_MEMORY;
4059 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",