1 const char parsers_rcs[] = "$Id: parsers.c,v 1.105 2007/08/11 14:49:49 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.105 2007/08/11 14:49:49 fabiankeil
48 * - Add prototpyes for the header parsers and make them static.
49 * - Comment out client_accept_encoding_adder() which isn't used right now.
51 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
52 * Move the ACTION_FORCE_TEXT_MODE check out of
53 * server_content_type(). Signal other functions
54 * whether or not a content type has been declared.
55 * Part of the fix for BR#1750917.
57 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
58 * Change sed() to return a jb_err in preparation for forward-override{}.
60 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
61 * Adjust "X-Filter: No" to disable dedicated header filters.
63 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
64 * Streamline client_cookie_adder().
66 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
67 * Make sure filters with dynamic jobs actually use them.
69 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
70 * - Introduce dynamic pcrs jobs that can resolve variables.
71 * - Remove unnecessary update_action_bits_for_all_tags() call.
73 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
74 * - Make tagging based on tags set by earlier taggers
75 * of the same kind possible.
76 * - Log whether or not new tags cause action bits updates
77 * (in which case a matching tag-pattern section exists).
78 * - Log if the user tries to set a tag that is already set.
80 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
81 * Introduce tags as alternative way to specify which
82 * actions apply to a request. At the moment tags can be
83 * created based on client and server headers.
85 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
86 * Log a warning if the content is compressed, filtering is
87 * enabled and Privoxy was compiled without zlib support.
90 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
91 * - Fix warnings when compiled with glibc.
92 * - Don't use crumble() for cookie crunching.
93 * - Move cookie time parsing into parse_header_time().
94 * - Let parse_header_time() return a jb_err code
95 * instead of a pointer that can only be used to
96 * check for NULL anyway.
98 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
99 * - Add better protection against malicious gzip headers.
100 * - Stop logging the first hundred bytes of decompressed content.
101 * It looks like it's working and there is always debug 16.
102 * - Log the content size after decompression in decompress_iob()
103 * instead of pcrs_filter_response().
105 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
106 * - Use dedicated header filter actions instead of abusing "filter".
107 * Replace "filter-client-headers" and "filter-client-headers"
108 * with "server-header-filter" and "client-header-filter".
109 * - Remove filter_client_header() and filter_client_header(),
110 * filter_header() now checks the shiny new
111 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
113 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
114 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
115 * - Handle "Cookie:" and "Connection:" headers a bit smarter
116 * (don't crunch them just to recreate them later on).
117 * - Add another non-standard time format for the cookie
118 * expiration date detection.
119 * - Fix a valgrind warning.
121 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
122 * Improve cookie expiration date detection.
124 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
125 * Don't run server_content_length() the first time
126 * sed() parses server headers; only adjust the
127 * Content-Length header if the page was modified.
129 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
130 * Fix log messages regarding the cookie time format
131 * (cookie and request URL were mixed up).
133 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
134 * - Let decompress_iob()
135 * - not corrupt the content if decompression fails
136 * early. (the first byte(s) were lost).
137 * - use pointer arithmetics with defined outcome for
139 * - Use a different kludge to remember a failed decompression.
141 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
142 * Search for Max-Forwards headers case-insensitive,
143 * don't generate the "501 unsupported" message for invalid
144 * Max-Forwards values and don't increase negative ones.
146 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
147 * - Let server_set_cookie() check the expiration date
148 * of cookies and don't touch the ones that are already
149 * expired. Fixes problems with low quality web applications
150 * as described in BR 932612.
152 * - Adjust comment in client_max_forwards to reality;
153 * remove invalid Max-Forwards headers.
155 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
156 * Stop filter_header() from unintentionally removing
157 * empty header lines that were enlisted by the continue
160 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
161 * - Repeat the request URL before logging any headers.
162 * Makes reading the log easier in case of simultaneous requests.
163 * - If there are more than one Content-Type headers in one request,
164 * use the first one and remove the others.
165 * - Remove "newval" variable in server_content_type().
166 * It's only used once.
168 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
169 * Correct a cast, check inflateEnd() exit code
170 * to see if we have to, replace sprintf calls
173 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
174 * Integrate a modified version of Wil Mahan's
175 * zlib patch (PR #895531).
177 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
178 * Skip empty filter files in filter_header()
179 * but don't ignore the ones that come afterwards.
180 * Fixes BR 1619208, this time for real.
182 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
183 * Reverted parts of my last commit
184 * to keep error handling working.
186 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
187 * Fixed gcc43 conversion warnings.
189 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
190 * Bringing back the "useless" localtime() call
191 * I removed in revision 1.67. On some platforms
192 * it's necessary to prevent time zone offsets.
194 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
195 * Rebuild request URL in get_destination_from_headers()
196 * to make sure redirect{pcrs command} works as expected
197 * for intercepted requests.
199 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
200 * Added get_destination_from_headers().
202 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
203 * Make pthread mutex locking more generic. Instead of
204 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
205 * and use mutex locking unless there is an _r function
206 * available. Better safe than sorry.
208 * Fixes "./configure --disable-pthread" and should result
209 * in less threading-related problems on pthread-using platforms,
210 * but it still doesn't fix BR#1122404.
212 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
213 * The special header "X-Filter: No" now disables
214 * header filtering as well.
216 * Revision 1.73 2006/09/23 13:26:38 roro
217 * Replace TABs by spaces in source code.
219 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
220 * Don't print a log message every time filter_headers is
221 * entered or left. It only creates noise without any real
224 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
225 * Fix +hide-if-modified-since{-n}.
227 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
228 * Have hide-if-modified-since interpret the random
229 * range value as minutes instead of hours. Allows
230 * more fine-grained configuration.
232 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
233 * Always have parse_header_time return a pointer
234 * that actual makes sense, even though we currently
235 * only need it to detect problems.
237 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
238 * Added config option enable-remote-http-toggle
239 * to specify if Privoxy should recognize special
240 * headers (currently only X-Filter) to change its
241 * behaviour. Disabled by default.
243 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
244 * After filtering de-chunked instances, remove
245 * "Transfer-Encoding" header entirely instead of changing
246 * it to "Transfer-Encoding: identity", which is invalid.
247 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
249 * Don't use localtime in parse_header_time. An empty time struct
250 * is good enough, it gets overwritten by strptime anyway.
252 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
253 * Use gmtime_r if available, fallback to gmtime with mutex
254 * protection for MacOSX and use vanilla gmtime for the rest.
256 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
257 * Changed client_referrer to use the right type (size_t) for
258 * hostlenght and to shorten the temporary referrer string with
259 * '\0' instead of adding a useless line break.
261 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
262 * - Back to timegm() using GnuPG's replacement if necessary.
263 * Using mktime() and localtime() could add a on hour offset if
264 * the randomize factor was big enough to lead to a summer/wintertime
267 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
269 * - Moved randomization code into pick_from_range().
271 * - Changed parse_header_time definition.
272 * time_t isn't guaranteed to be signed and
273 * if it isn't, -1 isn't available as error code.
274 * Changed some variable types in client_if_modified_since()
275 * because of the same reason.
277 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
278 * OS/2 compilation compatibility fixups
280 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
281 * Changed include from strptime.c to strptime.h
283 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
284 * Split filter-headers{} into filter-client-headers{}
285 * and filter-server-headers{}.
286 * Added parse_header_time() to share some code.
287 * Replaced timegm() with mktime().
289 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
290 * Windows service integration
292 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
293 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
295 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
296 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
297 * with what was really the latest development (the v_3_0_branch branch)
299 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
300 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
302 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
303 * Add the ability to check jpeg images for invalid
304 * lengths of comment blocks. Defensive strategy
305 * against the exploit:
306 * Microsoft Security Bulletin MS04-028
307 * Buffer Overrun in JPEG Processing (GDI+) Could
308 * Allow Code Execution (833987)
309 * Enabled with +inspect-jpegs in actions files.
311 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
312 * Excluded text/plain objects from filtering. This fixes a
313 * couple of client-crashing, download corruption and
314 * Privoxy performance issues, whose root cause lies in
315 * web servers labelling content of unknown type as text/plain.
317 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
318 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
320 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
321 * Completing the previous change
323 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
324 * Added temporary workaround for bug in PHP < 4.2.3
326 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
327 * 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.
329 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
330 * Fix typo: supressed -> suppressed
332 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
333 * Improved cookie logging
335 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
336 * Added basic support for OPTIONS and TRACE HTTP methods:
337 * - New parser function client_max_forwards which decrements
338 * the Max-Forwards HTTP header field of OPTIONS and TRACE
339 * requests by one before forwarding
340 * - New parser function client_host which extracts the host
341 * and port information from the HTTP header field if the
342 * request URI was not absolute
343 * - Don't crumble and re-add the Host: header, but only generate
344 * and append if missing
346 * Revision 1.56 2002/05/12 15:34:22 jongfoster
347 * Fixing typo in a comment
349 * Revision 1.55 2002/05/08 16:01:07 oes
350 * Optimized add_to_iob:
351 * - Use realloc instead of malloc(), memcpy(), free()
352 * - Expand to powers of two if possible, to get
353 * O(log n) reallocs instead of O(n).
354 * - Moved check for buffer limit here from chat
355 * - Report failure via returncode
357 * Revision 1.54 2002/04/02 15:03:16 oes
358 * Tiny code cosmetics
360 * Revision 1.53 2002/03/26 22:29:55 swa
361 * we have a new homepage!
363 * Revision 1.52 2002/03/24 13:25:43 swa
364 * name change related issues
366 * Revision 1.51 2002/03/13 00:27:05 jongfoster
369 * Revision 1.50 2002/03/12 01:45:35 oes
370 * More verbose logging
372 * Revision 1.49 2002/03/09 20:03:52 jongfoster
373 * - Making various functions return int rather than size_t.
374 * (Undoing a recent change). Since size_t is unsigned on
375 * Windows, functions like read_socket that return -1 on
376 * error cannot return a size_t.
378 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
379 * crashes, and also frequently caused JB to jump to 100%
380 * CPU and stay there. (Because it thought it had just
381 * read ((unsigned)-1) == 4Gb of data...)
383 * - The signature of write_socket has changed, it now simply
384 * returns success=0/failure=nonzero.
386 * - Trying to get rid of a few warnings --with-debug on
387 * Windows, I've introduced a new type "jb_socket". This is
388 * used for the socket file descriptors. On Windows, this
389 * is SOCKET (a typedef for unsigned). Everywhere else, it's
390 * an int. The error value can't be -1 any more, so it's
391 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
392 * Windows it maps to the #define INVALID_SOCKET.)
394 * - The signature of bind_port has changed.
396 * Revision 1.48 2002/03/07 03:46:53 oes
397 * Fixed compiler warnings etc
399 * Revision 1.47 2002/02/20 23:15:13 jongfoster
400 * Parsing functions now handle out-of-memory gracefully by returning
403 * Revision 1.46 2002/01/17 21:03:47 jongfoster
404 * Moving all our URL and URL pattern parsing code to urlmatch.c.
406 * Revision 1.45 2002/01/09 14:33:03 oes
407 * Added support for localtime_r.
409 * Revision 1.44 2001/12/14 01:22:54 steudten
410 * Remove 'user:pass@' from 'proto://user:pass@host' for the
411 * new added header 'Host: ..'. (See Req ID 491818)
413 * Revision 1.43 2001/11/23 00:26:38 jongfoster
414 * Fixing two really stupid errors in my previous commit
416 * Revision 1.42 2001/11/22 21:59:30 jongfoster
417 * Adding code to handle +no-cookies-keep
419 * Revision 1.41 2001/11/05 23:43:05 steudten
420 * Add time+date to log files.
422 * Revision 1.40 2001/10/26 20:13:09 jongfoster
423 * ctype.h is needed in Windows, too.
425 * Revision 1.39 2001/10/26 17:40:04 oes
426 * Introduced get_header_value()
427 * Removed http->user_agent, csp->referrer and csp->accept_types
428 * Removed client_accept()
430 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
431 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
432 * threads to call select() simultaneously. So, it's time to do a real, live,
433 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
434 * (native). Both versions will work, but using __OS2__ offers multi-threading.
436 * Revision 1.37 2001/10/23 21:36:02 jongfoster
437 * Documenting sed()'s error behaviou (doc change only)
439 * Revision 1.36 2001/10/13 12:51:51 joergs
440 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
441 * force-load), instead crumble Host: and add it (again) in client_host_adder
442 * (in case we get a HTTP/1.0 request without Host: header and forward it to
443 * a HTTP/1.1 server/proxy).
445 * Revision 1.35 2001/10/09 22:39:21 jongfoster
446 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
449 * Revision 1.34 2001/10/07 18:50:55 oes
450 * Added server_content_encoding, renamed server_transfer_encoding
452 * Revision 1.33 2001/10/07 18:04:49 oes
453 * Changed server_http11 to server_http and its pattern to "HTTP".
454 * Additional functionality: it now saves the HTTP status into
455 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
457 * Revision 1.32 2001/10/07 15:43:28 oes
458 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
459 * client_te and client_accept_encoding_adder, triggered by the new
460 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
461 * changed to allow only identity and chunked, and the TE header is
462 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
464 * parse_http_request no longer does anything than parsing. The rewriting
465 * of http->cmd and version mangling are gone. It now also recognizes
466 * the put and delete methods and saves the url in http->url. Removed
469 * renamed content_type and content_length to have the server_ prefix
471 * server_content_type now only works if csp->content_type != CT_TABOO
473 * added server_transfer_encoding, which
474 * - Sets CT_TABOO to prohibit filtering if encoding compresses
475 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
476 * - Change from "chunked" to "identity" if body was chunked
477 * but has been de-chunked for filtering.
479 * added server_content_md5 which crunches any Content-MD5 headers
480 * if the body was modified.
482 * made server_http11 conditional on +downgrade action
484 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
486 * Revision 1.31 2001/10/05 14:25:02 oes
487 * Crumble Keep-Alive from Server
489 * Revision 1.30 2001/09/29 12:56:03 joergs
490 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
492 * Revision 1.29 2001/09/24 21:09:24 jongfoster
493 * Fixing 2 memory leaks that Guy spotted, where the paramater to
494 * enlist() was not being free()d.
496 * Revision 1.28 2001/09/22 16:32:28 jongfoster
497 * Removing unused #includes.
499 * Revision 1.27 2001/09/20 15:45:25 steudten
501 * add casting from size_t to int for printf()
502 * remove local variable shadow s2
504 * Revision 1.26 2001/09/16 17:05:14 jongfoster
505 * Removing unused #include showarg.h
507 * Revision 1.25 2001/09/16 13:21:27 jongfoster
508 * Changes to use new list functions.
510 * Revision 1.24 2001/09/13 23:05:50 jongfoster
511 * Changing the string paramater to the header parsers a "const".
513 * Revision 1.23 2001/09/12 18:08:19 steudten
515 * In parse_http_request() header rewriting miss the host value, so
516 * from http://www.mydomain.com the result was just " / " not
517 * http://www.mydomain.com/ in case we forward.
519 * Revision 1.22 2001/09/10 10:58:53 oes
520 * Silenced compiler warnings
522 * Revision 1.21 2001/07/31 14:46:00 oes
523 * - Persistant connections now suppressed
524 * - sed() no longer appends empty header to csp->headers
526 * Revision 1.20 2001/07/30 22:08:36 jongfoster
527 * Tidying up #defines:
528 * - All feature #defines are now of the form FEATURE_xxx
529 * - Permanently turned off WIN_GUI_EDIT
530 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
532 * Revision 1.19 2001/07/25 17:21:54 oes
533 * client_uagent now saves copy of User-Agent: header value
535 * Revision 1.18 2001/07/13 14:02:46 oes
536 * - Included fix to repair broken HTTP requests that
537 * don't contain a path, not even '/'.
538 * - Removed all #ifdef PCRS
539 * - content_type now always inspected and classified as
540 * text, gif or other.
541 * - formatting / comments
543 * Revision 1.17 2001/06/29 21:45:41 oes
544 * Indentation, CRLF->LF, Tab-> Space
546 * Revision 1.16 2001/06/29 13:32:42 oes
548 * - Adapted free_http_request
549 * - Removed logentry from cancelled commit
551 * Revision 1.15 2001/06/03 19:12:38 oes
552 * deleted const struct interceptors
554 * Revision 1.14 2001/06/01 18:49:17 jongfoster
555 * Replaced "list_share" with "list" - the tiny memory gain was not
556 * worth the extra complexity.
558 * Revision 1.13 2001/05/31 21:30:33 jongfoster
559 * Removed list code - it's now in list.[ch]
560 * Renamed "permission" to "action", and changed many features
561 * to use the actions file rather than the global config.
563 * Revision 1.12 2001/05/31 17:33:13 oes
567 * Revision 1.11 2001/05/29 20:11:19 joergs
568 * '/ * inside comment' warning removed.
570 * Revision 1.10 2001/05/29 09:50:24 jongfoster
571 * Unified blocklist/imagelist/permissionslist.
572 * File format is still under discussion, but the internal changes
575 * Also modified interceptor behaviour:
576 * - We now intercept all URLs beginning with one of the following
577 * prefixes (and *only* these prefixes):
579 * * http://ijbswa.sf.net/config/
580 * * http://ijbswa.sourceforge.net/config/
581 * - New interceptors "home page" - go to http://i.j.b/ to see it.
582 * - Internal changes so that intercepted and fast redirect pages
583 * are not replaced with an image.
584 * - Interceptors now have the option to send a binary page direct
585 * to the client. (i.e. ijb-send-banner uses this)
586 * - Implemented show-url-info interceptor. (Which is why I needed
587 * the above interceptors changes - a typical URL is
588 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
589 * The previous mechanism would not have intercepted that, and
590 * if it had been intercepted then it then it would have replaced
593 * Revision 1.9 2001/05/28 17:26:33 jongfoster
594 * Fixing segfault if last header was crunched.
595 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
596 * can use the cross-platform sprintf() instead.)
598 * Revision 1.8 2001/05/27 22:17:04 oes
600 * - re_process_buffer no longer writes the modified buffer
601 * to the client, which was very ugly. It now returns the
602 * buffer, which it is then written by chat.
604 * - content_length now adjusts the Content-Length: header
605 * for modified documents rather than crunch()ing it.
606 * (Length info in csp->content_length, which is 0 for
607 * unmodified documents)
609 * - For this to work, sed() is called twice when filtering.
611 * Revision 1.7 2001/05/27 13:19:06 oes
612 * Patched Joergs solution for the content-length in.
614 * Revision 1.6 2001/05/26 13:39:32 jongfoster
615 * Only crunches Content-Length header if applying RE filtering.
616 * Without this fix, Microsoft Windows Update wouldn't work.
618 * Revision 1.5 2001/05/26 00:28:36 jongfoster
619 * Automatic reloading of config file.
620 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
621 * Most of the global variables have been moved to a new
622 * struct configuration_spec, accessed through csp->config->globalname
623 * Most of the globals remaining are used by the Win32 GUI.
625 * Revision 1.4 2001/05/22 18:46:04 oes
627 * - Enabled filtering banners by size rather than URL
628 * by adding patterns that replace all standard banner
629 * sizes with the "Junkbuster" gif to the re_filterfile
631 * - Enabled filtering WebBugs by providing a pattern
632 * which kills all 1x1 images
634 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
635 * which is selected by the (nonstandard and therefore
636 * capital) letter 'U' in the option string.
637 * It causes the quantifiers to be ungreedy by default.
638 * Appending a ? turns back to greedy (!).
640 * - Added a new interceptor ijb-send-banner, which
641 * sends back the "Junkbuster" gif. Without imagelist or
642 * MSIE detection support, or if tinygif = 1, or the
643 * URL isn't recognized as an imageurl, a lame HTML
644 * explanation is sent instead.
646 * - Added new feature, which permits blocking remote
647 * script redirects and firing back a local redirect
649 * The feature is conditionally compiled, i.e. it
650 * can be disabled with --disable-fast-redirects,
651 * plus it must be activated by a "fast-redirects"
652 * line in the config file, has its own log level
653 * and of course wants to be displayed by show-proxy-args
654 * Note: Boy, all the #ifdefs in 1001 locations and
655 * all the fumbling with configure.in and acconfig.h
656 * were *way* more work than the feature itself :-(
658 * - Because a generic redirect template was needed for
659 * this, tinygif = 3 now uses the same.
661 * - Moved GIFs, and other static HTTP response templates
666 * - Removed some >400 CRs again (Jon, you really worked
669 * Revision 1.3 2001/05/20 01:21:20 jongfoster
670 * Version 2.9.4 checkin.
671 * - Merged popupfile and cookiefile, and added control over PCRS
672 * filtering, in new "permissionsfile".
673 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
674 * file error you now get a message box (in the Win32 GUI) rather
675 * than the program exiting with no explanation.
676 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
678 * - Removed tabs from "config"
679 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
680 * - Bumped up version number.
682 * Revision 1.2 2001/05/17 23:02:36 oes
683 * - Made referrer option accept 'L' as a substitute for '§'
685 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
686 * Initial import of version 2.9.3 source tree
689 *********************************************************************/
696 #include <sys/types.h>
706 * Convince GNU's libc to provide a strptime prototype.
709 #endif /*__GLIBC__ */
716 #if !defined(_WIN32) && !defined(__OS2__)
722 #ifdef FEATURE_PTHREAD
724 /* jcc.h is for mutex semapores only */
725 #endif /* def FEATURE_PTHREAD */
731 #include "jbsockets.h"
732 #include "miscutil.h"
737 #ifndef HAVE_STRPTIME
738 #include "strptime.h"
741 const char parsers_h_rcs[] = PARSERS_H_VERSION;
743 /* Fix a problem with Solaris. There should be no effect on other
745 * Solaris's isspace() is a macro which uses its argument directly
746 * as an array index. Therefore we need to make sure that high-bit
747 * characters generate +ve values, and ideally we also want to make
748 * the argument match the declared parameter type of "int".
750 * Why did they write a character function that can't take a simple
751 * "char" argument? Doh!
753 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
754 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
756 static jb_err scan_headers(struct client_state *csp);
757 static jb_err header_tagger(struct client_state *csp, char *header);
758 static jb_err parse_header_time(const char *header_time, time_t *result);
760 static jb_err crumble (struct client_state *csp, char **header);
761 static jb_err connection (struct client_state *csp, char **header);
762 static jb_err filter_header (struct client_state *csp, char **header);
763 static jb_err client_referrer (struct client_state *csp, char **header);
764 static jb_err client_uagent (struct client_state *csp, char **header);
765 static jb_err client_ua (struct client_state *csp, char **header);
766 static jb_err client_from (struct client_state *csp, char **header);
767 static jb_err client_send_cookie (struct client_state *csp, char **header);
768 static jb_err client_x_forwarded (struct client_state *csp, char **header);
769 static jb_err client_accept_encoding (struct client_state *csp, char **header);
770 static jb_err client_te (struct client_state *csp, char **header);
771 static jb_err client_max_forwards (struct client_state *csp, char **header);
772 static jb_err client_host (struct client_state *csp, char **header);
773 static jb_err client_if_modified_since (struct client_state *csp, char **header);
774 static jb_err client_accept_language (struct client_state *csp, char **header);
775 static jb_err client_if_none_match (struct client_state *csp, char **header);
776 static jb_err crunch_client_header (struct client_state *csp, char **header);
777 static jb_err client_x_filter (struct client_state *csp, char **header);
778 static jb_err server_set_cookie (struct client_state *csp, char **header);
779 static jb_err server_content_type (struct client_state *csp, char **header);
780 static jb_err server_content_length (struct client_state *csp, char **header);
781 static jb_err server_content_md5 (struct client_state *csp, char **header);
782 static jb_err server_content_encoding (struct client_state *csp, char **header);
783 static jb_err server_transfer_coding (struct client_state *csp, char **header);
784 static jb_err server_http (struct client_state *csp, char **header);
785 static jb_err crunch_server_header (struct client_state *csp, char **header);
786 static jb_err server_last_modified (struct client_state *csp, char **header);
787 static jb_err server_content_disposition(struct client_state *csp, char **header);
789 static jb_err client_host_adder (struct client_state *csp);
790 static jb_err client_cookie_adder (struct client_state *csp);
791 static jb_err client_xtra_adder (struct client_state *csp);
792 static jb_err client_x_forwarded_adder(struct client_state *csp);
793 static jb_err connection_close_adder (struct client_state *csp);
795 const struct parsers client_patterns[] = {
796 { "referer:", 8, client_referrer },
797 { "user-agent:", 11, client_uagent },
798 { "ua-", 3, client_ua },
799 { "from:", 5, client_from },
800 { "cookie:", 7, client_send_cookie },
801 { "x-forwarded-for:", 16, client_x_forwarded },
802 { "Accept-Encoding:", 16, client_accept_encoding },
803 { "TE:", 3, client_te },
804 { "Host:", 5, client_host },
805 { "if-modified-since:", 18, client_if_modified_since },
806 { "Keep-Alive:", 11, crumble },
807 { "connection:", 11, connection },
808 { "proxy-connection:", 17, crumble },
809 { "max-forwards:", 13, client_max_forwards },
810 { "Accept-Language:", 16, client_accept_language },
811 { "if-none-match:", 14, client_if_none_match },
812 { "X-Filter:", 9, client_x_filter },
813 { "*", 0, crunch_client_header },
814 { "*", 0, filter_header },
818 const struct parsers server_patterns[] = {
819 { "HTTP", 4, server_http },
820 { "set-cookie:", 11, server_set_cookie },
821 { "connection:", 11, connection },
822 { "Content-Type:", 13, server_content_type },
823 { "Content-MD5:", 12, server_content_md5 },
824 { "Content-Encoding:", 17, server_content_encoding },
825 { "Transfer-Encoding:", 18, server_transfer_coding },
826 { "Keep-Alive:", 11, crumble },
827 { "content-disposition:", 20, server_content_disposition },
828 { "Last-Modified:", 14, server_last_modified },
829 { "*", 0, crunch_server_header },
830 { "*", 0, filter_header },
834 const struct parsers server_patterns_light[] = {
835 { "Content-Length:", 15, server_content_length },
836 { "Transfer-Encoding:", 18, server_transfer_coding },
838 { "Content-Encoding:", 17, server_content_encoding },
839 #endif /* def FEATURE_ZLIB */
843 const add_header_func_ptr add_client_headers[] = {
846 client_x_forwarded_adder,
848 /* Temporarily disabled: client_accept_encoding_adder, */
849 connection_close_adder,
854 const add_header_func_ptr add_server_headers[] = {
855 connection_close_adder,
859 /*********************************************************************
861 * Function : flush_socket
863 * Description : Write any pending "buffered" content.
866 * 1 : fd = file descriptor of the socket to read
867 * 2 : csp = Current client state (buffers, headers, etc...)
869 * Returns : On success, the number of bytes written are returned (zero
870 * indicates nothing was written). On error, -1 is returned,
871 * and errno is set appropriately. If count is zero and the
872 * file descriptor refers to a regular file, 0 will be
873 * returned without causing any other effect. For a special
874 * file, the results are not portable.
876 *********************************************************************/
877 int flush_socket(jb_socket fd, struct client_state *csp)
879 struct iob *iob = csp->iob;
880 int len = iob->eod - iob->cur;
887 if (write_socket(fd, iob->cur, (size_t)len))
891 iob->eod = iob->cur = iob->buf;
897 /*********************************************************************
899 * Function : add_to_iob
901 * Description : Add content to the buffered page, expanding the
902 * buffer if necessary.
905 * 1 : csp = Current client state (buffers, headers, etc...)
906 * 2 : buf = holds the content to be added to the page
907 * 3 : n = number of bytes to be added
909 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
910 * or buffer limit reached.
912 *********************************************************************/
913 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
915 struct iob *iob = csp->iob;
916 size_t used, offset, need, want;
919 if (n <= 0) return JB_ERR_OK;
921 used = (size_t)(iob->eod - iob->buf);
922 offset = (size_t)(iob->cur - iob->buf);
923 need = used + (size_t)n + 1;
926 * If the buffer can't hold the new data, extend it first.
927 * Use the next power of two if possible, else use the actual need.
929 if (need > csp->config->buffer_limit)
931 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
932 return JB_ERR_MEMORY;
935 if (need > iob->size)
937 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
939 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
943 else if (NULL != (p = (char *)realloc(iob->buf, need)))
949 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
950 return JB_ERR_MEMORY;
953 /* Update the iob pointers */
954 iob->cur = p + offset;
959 /* copy the new data into the iob buffer */
960 memcpy(iob->eod, buf, (size_t)n);
962 /* point to the end of the data */
965 /* null terminate == cheap insurance */
974 /*********************************************************************
976 * Function : decompress_iob
978 * Description : Decompress buffered page, expanding the
979 * buffer as necessary. csp->iob->cur
980 * should point to the the beginning of the
981 * compressed data block.
984 * 1 : csp = Current client state (buffers, headers, etc...)
986 * Returns : JB_ERR_OK on success,
987 * JB_ERR_MEMORY if out-of-memory limit reached, and
988 * JB_ERR_COMPRESS if error decompressing buffer.
990 *********************************************************************/
991 jb_err decompress_iob(struct client_state *csp)
993 char *buf; /* new, uncompressed buffer */
994 char *cur; /* Current iob position (to keep the original
995 * iob->cur unmodified if we return early) */
996 size_t bufsize; /* allocated size of the new buffer */
997 size_t old_size; /* Content size before decompression */
998 size_t skip_size; /* Number of bytes at the beginning of the iob
999 that we should NOT decompress. */
1000 int status; /* return status of the inflate() call */
1001 z_stream zstr; /* used by calls to zlib */
1003 assert(csp->iob->cur - csp->iob->buf > 0);
1004 assert(csp->iob->eod - csp->iob->cur > 0);
1006 bufsize = csp->iob->size;
1007 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1008 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1010 cur = csp->iob->cur;
1015 * This is to protect the parsing of gzipped data,
1016 * but it should(?) be valid for deflated data also.
1018 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1019 return JB_ERR_COMPRESS;
1022 if (csp->content_type & CT_GZIP)
1025 * Our task is slightly complicated by the facts that data
1026 * compressed by gzip does not include a zlib header, and
1027 * that there is no easily accessible interface in zlib to
1028 * handle a gzip header. We strip off the gzip header by
1029 * hand, and later inform zlib not to expect a header.
1033 * Strip off the gzip header. Please see RFC 1952 for more
1034 * explanation of the appropriate fields.
1036 if ((*cur++ != (char)0x1f)
1037 || (*cur++ != (char)0x8b)
1038 || (*cur++ != Z_DEFLATED))
1040 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1041 return JB_ERR_COMPRESS;
1047 * XXX: These magic numbers should be replaced
1048 * with macros to give a better idea what they do.
1052 /* The gzip header has reserved bits set; bail out. */
1053 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1054 return JB_ERR_COMPRESS;
1058 /* Skip extra fields if necessary. */
1062 * Skip a given number of bytes, specified
1063 * as a 16-bit little-endian value.
1066 * XXX: This code used to be:
1068 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1070 * which I had to change into:
1072 * cur += *cur++ + (*cur++ << 8);
1074 * at which point gcc43 finally noticed that the value
1075 * of cur is undefined (it depends on which of the
1076 * summands is evaluated first).
1078 * I haven't come across a site where this
1079 * code is actually executed yet, but I hope
1083 skip_bytes = *cur++;
1084 skip_bytes = *cur++ << 8;
1086 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1089 * The number of bytes to skip should be positive
1090 * and we'd like to stay in the buffer.
1092 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1094 log_error (LOG_LEVEL_ERROR,
1095 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1097 return JB_ERR_COMPRESS;
1099 log_error (LOG_LEVEL_INFO,
1100 "Skipping %d bytes for gzip compression. Does this sound right?",
1105 /* Skip the filename if necessary. */
1108 /* A null-terminated string is supposed to follow. */
1109 while (*cur++ && (cur < csp->iob->eod));
1113 /* Skip the comment if necessary. */
1116 /* A null-terminated string is supposed to follow. */
1117 while (*cur++ && (cur < csp->iob->eod));
1120 /* Skip the CRC if necessary. */
1126 if (cur >= csp->iob->eod)
1129 * If the current position pointer reached or passed
1130 * the buffer end, we were obviously tricked to skip
1133 log_error (LOG_LEVEL_ERROR,
1134 "Malformed gzip header detected. Aborting decompression.");
1135 return JB_ERR_COMPRESS;
1139 else if (csp->content_type & CT_DEFLATE)
1142 * XXX: The debug level should be lowered
1143 * before the next stable release.
1145 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1147 * In theory (that is, according to RFC 1950), deflate-compressed
1148 * data should begin with a two-byte zlib header and have an
1149 * adler32 checksum at the end. It seems that in practice only
1150 * the raw compressed data is sent. Note that this means that
1151 * we are not RFC 1950-compliant here, but the advantage is that
1152 * this actually works. :)
1154 * We add a dummy null byte to tell zlib where the data ends,
1155 * and later inform it not to expect a header.
1157 * Fortunately, add_to_iob() has thoughtfully null-terminated
1158 * the buffer; we can just increment the end pointer to include
1165 log_error (LOG_LEVEL_ERROR,
1166 "Unable to determine compression format for decompression");
1167 return JB_ERR_COMPRESS;
1170 /* Set up the fields required by zlib. */
1171 zstr.next_in = (Bytef *)cur;
1172 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1173 zstr.zalloc = Z_NULL;
1174 zstr.zfree = Z_NULL;
1175 zstr.opaque = Z_NULL;
1178 * Passing -MAX_WBITS to inflateInit2 tells the library
1179 * that there is no zlib header.
1181 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1183 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1184 return JB_ERR_COMPRESS;
1188 * Next, we allocate new storage for the inflated data.
1189 * We don't modify the existing iob yet, so in case there
1190 * is error in decompression we can recover gracefully.
1192 buf = zalloc (bufsize);
1195 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1196 return JB_ERR_MEMORY;
1199 assert(bufsize >= skip_size);
1200 memcpy(buf, csp->iob->buf, skip_size);
1201 zstr.avail_out = bufsize - skip_size;
1202 zstr.next_out = (Bytef *)buf + skip_size;
1204 /* Try to decompress the whole stream in one shot. */
1205 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1207 /* We need to allocate more memory for the output buffer. */
1209 char *tmpbuf; /* used for realloc'ing the buffer */
1210 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1213 * If zlib wants more data then there's a problem, because
1214 * the complete compressed file should have been buffered.
1216 if (0 == zstr.avail_in)
1218 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1219 return JB_ERR_COMPRESS;
1223 * If we tried the limit and still didn't have enough
1224 * memory, just give up.
1226 if (bufsize == csp->config->buffer_limit)
1228 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1229 return JB_ERR_MEMORY;
1232 /* Try doubling the buffer size each time. */
1235 /* Don't exceed the buffer limit. */
1236 if (bufsize > csp->config->buffer_limit)
1238 bufsize = csp->config->buffer_limit;
1241 /* Try to allocate the new buffer. */
1242 tmpbuf = realloc(buf, bufsize);
1245 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1247 return JB_ERR_MEMORY;
1251 char *oldnext_out = (char *)zstr.next_out;
1254 * Update the fields for inflate() to use the new
1255 * buffer, which may be in a location different from
1258 zstr.avail_out += bufsize - oldbufsize;
1259 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1262 * Compare with an uglier method of calculating these values
1263 * that doesn't require the extra oldbufsize variable.
1265 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1266 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1267 assert(zstr.avail_out > 0);
1273 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1275 log_error(LOG_LEVEL_ERROR,
1276 "Inconsistent stream state after decompression: %s", zstr.msg);
1278 * XXX: Intentionally no return.
1280 * According to zlib.h, Z_STREAM_ERROR is returned
1281 * "if the stream state was inconsistent".
1283 * I assume in this case inflate()'s status
1284 * would also be something different than Z_STREAM_END
1285 * so this check should be redundant, but lets see.
1289 if (status != Z_STREAM_END)
1291 /* We failed to decompress the stream. */
1292 log_error(LOG_LEVEL_ERROR,
1293 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1294 return JB_ERR_COMPRESS;
1298 * Finally, we can actually update the iob, since the
1299 * decompression was successful. First, free the old
1302 freez(csp->iob->buf);
1304 /* Now, update the iob to use the new buffer. */
1305 csp->iob->buf = buf;
1306 csp->iob->cur = csp->iob->buf + skip_size;
1307 csp->iob->eod = (char *)zstr.next_out;
1308 csp->iob->size = bufsize;
1311 * Make sure the new uncompressed iob obeys some minimal
1312 * consistency conditions.
1314 if ((csp->iob->buf < csp->iob->cur)
1315 && (csp->iob->cur <= csp->iob->eod)
1316 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1318 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1321 log_error(LOG_LEVEL_RE_FILTER,
1322 "Decompression successful. Old size: %d, new size: %d.",
1323 old_size, new_size);
1327 /* zlib thinks this is OK, so lets do the same. */
1328 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1333 /* It seems that zlib did something weird. */
1334 log_error(LOG_LEVEL_ERROR,
1335 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1336 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1337 csp->iob->eod, csp->iob->buf + csp->iob->size);
1338 return JB_ERR_COMPRESS;
1344 #endif /* defined(FEATURE_ZLIB) */
1347 /*********************************************************************
1349 * Function : get_header
1351 * Description : This (odd) routine will parse the csp->iob
1354 * 1 : csp = Current client state (buffers, headers, etc...)
1356 * Returns : Any one of the following:
1358 * 1) a pointer to a dynamically allocated string that contains a header line
1359 * 2) NULL indicating that the end of the header was reached
1360 * 3) "" indicating that the end of the iob was reached before finding
1361 * a complete header line.
1363 *********************************************************************/
1364 char *get_header(struct client_state *csp)
1370 if ((iob->cur == NULL)
1371 || ((p = strchr(iob->cur, '\n')) == NULL))
1373 return(""); /* couldn't find a complete header */
1378 ret = strdup(iob->cur);
1381 /* FIXME No way to handle error properly */
1382 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1387 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1389 /* is this a blank line (i.e. the end of the header) ? */
1401 /*********************************************************************
1403 * Function : get_header_value
1405 * Description : Get the value of a given header from a chained list
1406 * of header lines or return NULL if no such header is
1407 * present in the list.
1410 * 1 : header_list = pointer to list
1411 * 2 : header_name = string with name of header to look for.
1412 * Trailing colon required, capitalization
1415 * Returns : NULL if not found, else value of header
1417 *********************************************************************/
1418 char *get_header_value(const struct list *header_list, const char *header_name)
1420 struct list_entry *cur_entry;
1424 assert(header_list);
1425 assert(header_name);
1426 length = strlen(header_name);
1428 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1432 if (!strncmpic(cur_entry->str, header_name, length))
1435 * Found: return pointer to start of value
1437 ret = (char *) (cur_entry->str + length);
1438 while (*ret && ijb_isspace(*ret)) ret++;
1452 /*********************************************************************
1454 * Function : scan_headers
1456 * Description : Scans headers, applies tags and updates action bits.
1459 * 1 : csp = Current client state (buffers, headers, etc...)
1461 * Returns : JB_ERR_OK
1463 *********************************************************************/
1464 static jb_err scan_headers(struct client_state *csp)
1466 struct list_entry *h; /* Header */
1467 jb_err err = JB_ERR_OK;
1469 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1471 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1473 /* Header crunch()ed in previous run? -> ignore */
1474 if (h->str == NULL) continue;
1475 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1476 err = header_tagger(csp, h->str);
1483 /*********************************************************************
1487 * Description : add, delete or modify lines in the HTTP header streams.
1488 * On entry, it receives a linked list of headers space
1489 * that was allocated dynamically (both the list nodes
1490 * and the header contents).
1492 * As a side effect it frees the space used by the original
1496 * 1 : pats = list of patterns to match against headers
1497 * 2 : more_headers = list of functions to add more
1498 * headers (client or server)
1499 * 3 : csp = Current client state (buffers, headers, etc...)
1501 * Returns : JB_ERR_OK in case off success, or
1502 * JB_ERR_MEMORY on out-of-memory error.
1504 *********************************************************************/
1505 jb_err sed(const struct parsers pats[],
1506 const add_header_func_ptr more_headers[],
1507 struct client_state *csp)
1509 struct list_entry *p;
1510 const struct parsers *v;
1511 const add_header_func_ptr *f;
1512 jb_err err = JB_ERR_OK;
1516 * If filtering is enabled, sed is run twice,
1517 * but most of the work needs to be done only once.
1519 first_run = (more_headers != NULL ) ? 1 : 0;
1521 if (first_run) /* Parse and print */
1525 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1527 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1529 /* Header crunch()ed in previous run? -> ignore */
1530 if (p->str == NULL) continue;
1532 /* Does the current parser handle this header? */
1533 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1535 err = v->parser(csp, (char **)&(p->str));
1539 /* place any additional headers on the csp->headers list */
1540 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1545 else /* Parse only */
1548 * The second run is only needed if the body was modified
1549 * and the content-lenght has changed.
1551 if (strncmpic(csp->http->cmd, "HEAD", 4))
1553 /*XXX: Code duplication */
1554 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1556 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1558 /* Header crunch()ed in previous run? -> ignore */
1559 if (p->str == NULL) continue;
1561 /* Does the current parser handle this header? */
1562 if (strncmpic(p->str, v->str, v->len) == 0)
1564 err = v->parser(csp, (char **)&(p->str));
1576 /*********************************************************************
1578 * Function : header_tagger
1580 * Description : Executes all text substitutions from applying
1581 * tag actions and saves the result as tag.
1583 * XXX: Shares enough code with filter_header() and
1584 * pcrs_filter_response() to warrant some helper functions.
1587 * 1 : csp = Current client state (buffers, headers, etc...)
1588 * 2 : header = Header that is used as tagger input
1590 * Returns : JB_ERR_OK on success and always succeeds
1592 *********************************************************************/
1593 static jb_err header_tagger(struct client_state *csp, char *header)
1595 int wanted_filter_type;
1596 int multi_action_index;
1600 struct file_list *fl;
1601 struct re_filterfile_spec *b;
1602 struct list_entry *tag_name;
1604 int found_filters = 0;
1605 const size_t header_length = strlen(header);
1607 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1609 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1610 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1614 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1615 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1618 /* Check if there are any filters */
1619 for (i = 0; i < MAX_AF_FILES; i++)
1632 if (0 == found_filters)
1634 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1638 for (i = 0; i < MAX_AF_FILES; i++)
1641 if ((NULL == fl) || (NULL == fl->f))
1644 * Either there are no filter files
1645 * left, or this filter file just
1646 * contains no valid filters.
1648 * Continue to be sure we don't miss
1649 * valid filter files that are chained
1650 * after empty or invalid ones.
1655 /* For all filters, */
1656 for (b = fl->f; b; b = b->next)
1658 if (b->type != wanted_filter_type)
1660 /* skip the ones we don't care about, */
1663 /* leaving only taggers that could apply, of which we use the ones, */
1664 for (tag_name = csp->action->multi[multi_action_index]->first;
1665 NULL != tag_name; tag_name = tag_name->next)
1667 /* that do apply, and */
1668 if (strcmp(b->name, tag_name->str) == 0)
1670 char *modified_tag = NULL;
1672 size_t size = header_length;
1673 pcrs_job *joblist = b->joblist;
1675 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1677 if (NULL == joblist)
1679 log_error(LOG_LEVEL_RE_FILTER,
1680 "Tagger %s has empty joblist. Nothing to do.", b->name);
1684 /* execute their pcrs_joblist on the header. */
1685 for (job = joblist; NULL != job; job = job->next)
1687 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1691 /* Success, continue with the modified version. */
1700 /* Tagger doesn't match */
1703 /* Regex failure, log it but continue anyway. */
1704 log_error(LOG_LEVEL_ERROR,
1705 "Problems with tagger \'%s\' and header \'%s\': %s",
1706 b->name, *header, pcrs_strerror(hits));
1708 freez(modified_tag);
1712 if (b->dynamic) pcrs_free_joblist(joblist);
1714 /* If this tagger matched */
1720 * There is to technical limitation which makes
1721 * it impossible to use empty tags, but I assume
1722 * no one would do it intentionally.
1725 log_error(LOG_LEVEL_INFO,
1726 "Tagger \'%s\' created an empty tag. Ignored.",
1731 if (!list_contains_item(csp->tags, tag))
1733 if (JB_ERR_OK != enlist(csp->tags, tag))
1735 log_error(LOG_LEVEL_ERROR,
1736 "Insufficient memory to add tag \'%s\', "
1737 "based on tagger \'%s\' and header \'%s\'",
1738 tag, b->name, *header);
1742 char *action_message;
1744 * update the action bits right away, to make
1745 * tagging based on tags set by earlier taggers
1746 * of the same kind possible.
1748 if (update_action_bits_for_tag(csp, tag))
1750 action_message = "Action bits updated accordingly.";
1754 action_message = "No action bits update necessary.";
1757 log_error(LOG_LEVEL_HEADER,
1758 "Tagger \'%s\' added tag \'%s\'. %s",
1759 b->name, tag, action_message);
1764 /* XXX: Is this log-worthy? */
1765 log_error(LOG_LEVEL_HEADER,
1766 "Tagger \'%s\' didn't add tag \'%s\'. "
1767 "Tag already present", b->name, tag);
1770 } /* if the tagger matched */
1771 } /* if the tagger applies */
1772 } /* for every tagger that could apply */
1773 } /* for all filters */
1774 } /* for all filter files */
1779 /* here begins the family of parser functions that reformat header lines */
1781 /*********************************************************************
1783 * Function : filter_header
1785 * Description : Executes all text substitutions from all applying
1786 * +(server|client)-header-filter actions on the header.
1787 * Most of the code was copied from pcrs_filter_response,
1788 * including the rather short variable names
1791 * 1 : csp = Current client state (buffers, headers, etc...)
1792 * 2 : header = On input, pointer to header to modify.
1793 * On output, pointer to the modified header, or NULL
1794 * to remove the header. This function frees the
1795 * original string if necessary.
1797 * Returns : JB_ERR_OK on success and always succeeds
1799 *********************************************************************/
1800 static jb_err filter_header(struct client_state *csp, char **header)
1804 size_t size = strlen(*header);
1806 char *newheader = NULL;
1809 struct file_list *fl;
1810 struct re_filterfile_spec *b;
1811 struct list_entry *filtername;
1813 int i, found_filters = 0;
1814 int wanted_filter_type;
1815 int multi_action_index;
1817 if (csp->flags & CSP_FLAG_NO_FILTERING)
1822 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1824 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1825 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1829 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1830 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1834 * Need to check the set of re_filterfiles...
1836 for (i = 0; i < MAX_AF_FILES; i++)
1849 if (0 == found_filters)
1851 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1855 for (i = 0; i < MAX_AF_FILES; i++)
1858 if ((NULL == fl) || (NULL == fl->f))
1861 * Either there are no filter files
1862 * left, or this filter file just
1863 * contains no valid filters.
1865 * Continue to be sure we don't miss
1866 * valid filter files that are chained
1867 * after empty or invalid ones.
1872 * For all applying +filter actions, look if a filter by that
1873 * name exists and if yes, execute its pcrs_joblist on the
1876 for (b = fl->f; b; b = b->next)
1878 if (b->type != wanted_filter_type)
1880 /* Skip other filter types */
1884 for (filtername = csp->action->multi[multi_action_index]->first;
1885 filtername ; filtername = filtername->next)
1887 if (strcmp(b->name, filtername->str) == 0)
1889 int current_hits = 0;
1890 pcrs_job *joblist = b->joblist;
1892 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1894 if (NULL == joblist)
1896 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1900 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1901 *header, size, b->name);
1903 /* Apply all jobs from the joblist */
1904 for (job = joblist; NULL != job; job = job->next)
1906 matches = pcrs_execute(job, *header, size, &newheader, &size);
1909 current_hits += matches;
1910 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1912 *header = newheader;
1914 else if ( 0 == matches )
1916 /* Filter doesn't change header */
1922 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1923 *header, b->name, pcrs_strerror(matches));
1924 if( newheader != NULL)
1926 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1932 if (b->dynamic) pcrs_free_joblist(joblist);
1934 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1935 hits += current_hits;
1942 * Additionally checking for hits is important because if
1943 * the continue hack is triggered, server headers can
1944 * arrive empty to separate multiple heads from each other.
1946 if ((0 == size) && hits)
1948 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1956 /*********************************************************************
1958 * Function : connection
1960 * Description : Makes sure that the value of the Connection: header
1961 * is "close" and signals connection_close_adder
1965 * 1 : csp = Current client state (buffers, headers, etc...)
1966 * 2 : header = On input, pointer to header to modify.
1967 * On output, pointer to the modified header, or NULL
1968 * to remove the header. This function frees the
1969 * original string if necessary.
1971 * Returns : JB_ERR_OK on success, or
1972 * JB_ERR_MEMORY on out-of-memory error.
1974 *********************************************************************/
1975 static jb_err connection(struct client_state *csp, char **header)
1977 char *old_header = *header;
1979 /* Do we have a 'Connection: close' header? */
1980 if (strcmpic(*header, "Connection: close"))
1982 /* No, create one */
1983 *header = strdup("Connection: close");
1986 return JB_ERR_MEMORY;
1988 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1992 /* Signal connection_close_adder() to return early. */
1993 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1995 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
1999 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2006 /*********************************************************************
2008 * Function : crumble
2010 * Description : This is called if a header matches a pattern to "crunch"
2013 * 1 : csp = Current client state (buffers, headers, etc...)
2014 * 2 : header = On input, pointer to header to modify.
2015 * On output, pointer to the modified header, or NULL
2016 * to remove the header. This function frees the
2017 * original string if necessary.
2019 * Returns : JB_ERR_OK on success, or
2020 * JB_ERR_MEMORY on out-of-memory error.
2022 *********************************************************************/
2023 static jb_err crumble(struct client_state *csp, char **header)
2025 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2030 /*********************************************************************
2032 * Function : crunch_server_header
2034 * Description : Crunch server header if it matches a string supplied by the
2035 * user. Called from `sed'.
2038 * 1 : csp = Current client state (buffers, headers, etc...)
2039 * 2 : header = On input, pointer to header to modify.
2040 * On output, pointer to the modified header, or NULL
2041 * to remove the header. This function frees the
2042 * original string if necessary.
2044 * Returns : JB_ERR_OK on success and always succeeds
2046 *********************************************************************/
2047 static jb_err crunch_server_header(struct client_state *csp, char **header)
2049 const char *crunch_pattern;
2051 /* Do we feel like crunching? */
2052 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2054 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2056 /* Is the current header the lucky one? */
2057 if (strstr(*header, crunch_pattern))
2059 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2068 /*********************************************************************
2070 * Function : server_content_type
2072 * Description : Set the content-type for filterable types (text/.*,
2073 * .*xml.*, javascript and image/gif) unless filtering has been
2074 * forbidden (CT_TABOO) while parsing earlier headers.
2075 * NOTE: Since text/plain is commonly used by web servers
2076 * for files whose correct type is unknown, we don't
2077 * set CT_TEXT for it.
2080 * 1 : csp = Current client state (buffers, headers, etc...)
2081 * 2 : header = On input, pointer to header to modify.
2082 * On output, pointer to the modified header, or NULL
2083 * to remove the header. This function frees the
2084 * original string if necessary.
2086 * Returns : JB_ERR_OK on success, or
2087 * JB_ERR_MEMORY on out-of-memory error.
2089 *********************************************************************/
2090 static jb_err server_content_type(struct client_state *csp, char **header)
2092 /* Remove header if it isn't the first Content-Type header */
2093 if ((csp->content_type & CT_DECLARED))
2096 * Another, slightly slower, way to see if
2097 * we already parsed another Content-Type header.
2099 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2101 log_error(LOG_LEVEL_ERROR,
2102 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2110 * Signal that the Content-Type has been set.
2112 csp->content_type |= CT_DECLARED;
2114 if (!(csp->content_type & CT_TABOO))
2116 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2117 || strstr(*header, "xml")
2118 || strstr(*header, "application/x-javascript"))
2120 csp->content_type |= CT_TEXT;
2122 else if (strstr(*header, " image/gif"))
2124 csp->content_type |= CT_GIF;
2126 else if (strstr(*header, " image/jpeg"))
2128 csp->content_type |= CT_JPEG;
2133 * Are we messing with the content type?
2135 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2138 * Make sure the user doesn't accidently
2139 * change the content type of binary documents.
2141 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2144 *header = strdup("Content-Type: ");
2145 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2149 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2150 return JB_ERR_MEMORY;
2152 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2156 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2157 "Enable force-text-mode if you know what you're doing.", *header);
2165 /*********************************************************************
2167 * Function : server_transfer_coding
2169 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2170 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2171 * - Remove header if body was chunked but has been
2172 * de-chunked for filtering.
2175 * 1 : csp = Current client state (buffers, headers, etc...)
2176 * 2 : header = On input, pointer to header to modify.
2177 * On output, pointer to the modified header, or NULL
2178 * to remove the header. This function frees the
2179 * original string if necessary.
2181 * Returns : JB_ERR_OK on success, or
2182 * JB_ERR_MEMORY on out-of-memory error.
2184 *********************************************************************/
2185 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2188 * Turn off pcrs and gif filtering if body compressed
2190 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2194 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2196 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2197 csp->http->cmd, *header);
2198 #endif /* def FEATURE_ZLIB */
2199 csp->content_type = CT_TABOO;
2203 * Raise flag if body chunked
2205 if (strstr(*header, "chunked"))
2207 csp->flags |= CSP_FLAG_CHUNKED;
2210 * If the body was modified, it has been de-chunked first
2211 * and the header must be removed.
2213 * FIXME: If there is more than one transfer encoding,
2214 * only the "chunked" part should be removed here.
2216 if (csp->flags & CSP_FLAG_MODIFIED)
2218 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2227 /*********************************************************************
2229 * Function : server_content_encoding
2231 * Description : This function is run twice for each request,
2232 * unless FEATURE_ZLIB and filtering are disabled.
2234 * The first run is used to check if the content
2235 * is compressed, if FEATURE_ZLIB is disabled
2236 * filtering is then disabled as well, if FEATURE_ZLIB
2237 * is enabled the content is marked for decompression.
2239 * The second run is used to remove the Content-Encoding
2240 * header if the decompression was successful.
2243 * 1 : csp = Current client state (buffers, headers, etc...)
2244 * 2 : header = On input, pointer to header to modify.
2245 * On output, pointer to the modified header, or NULL
2246 * to remove the header. This function frees the
2247 * original string if necessary.
2249 * Returns : JB_ERR_OK on success, or
2250 * JB_ERR_MEMORY on out-of-memory error.
2252 *********************************************************************/
2253 static jb_err server_content_encoding(struct client_state *csp, char **header)
2256 if ((csp->flags & CSP_FLAG_MODIFIED)
2257 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2260 * We successfully decompressed the content,
2261 * and have to clean the header now, so the
2262 * client no longer expects compressed data..
2264 * XXX: There is a difference between cleaning
2265 * and removing it completely.
2267 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2270 else if (strstr(*header, "gzip"))
2272 /* Mark for gzip decompression */
2273 csp->content_type |= CT_GZIP;
2275 else if (strstr(*header, "deflate"))
2277 /* Mark for zlib decompression */
2278 csp->content_type |= CT_DEFLATE;
2280 else if (strstr(*header, "compress"))
2283 * We can't decompress this; therefore we can't filter
2286 csp->content_type |= CT_TABOO;
2288 #else /* !defined(FEATURE_ZLIB) */
2289 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2292 * Body is compressed, turn off pcrs and gif filtering.
2294 csp->content_type |= CT_TABOO;
2297 * Log a warning if the user expects the content to be filtered.
2299 if ((csp->rlist != NULL) &&
2300 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2302 log_error(LOG_LEVEL_INFO,
2303 "Compressed content detected, content filtering disabled. "
2304 "Consider recompiling Privoxy with zlib support or "
2305 "enable the prevent-compression action.");
2308 #endif /* defined(FEATURE_ZLIB) */
2315 /*********************************************************************
2317 * Function : server_content_length
2319 * Description : Adjust Content-Length header if we modified
2323 * 1 : csp = Current client state (buffers, headers, etc...)
2324 * 2 : header = On input, pointer to header to modify.
2325 * On output, pointer to the modified header, or NULL
2326 * to remove the header. This function frees the
2327 * original string if necessary.
2329 * Returns : JB_ERR_OK on success, or
2330 * JB_ERR_MEMORY on out-of-memory error.
2332 *********************************************************************/
2333 static jb_err server_content_length(struct client_state *csp, char **header)
2335 const size_t max_header_length = 80;
2337 /* Regenerate header if the content was modified. */
2338 if (csp->flags & CSP_FLAG_MODIFIED)
2341 *header = (char *) zalloc(max_header_length);
2342 if (*header == NULL)
2344 return JB_ERR_MEMORY;
2347 snprintf(*header, max_header_length, "Content-Length: %d",
2348 (int)csp->content_length);
2349 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2350 (int)csp->content_length);
2357 /*********************************************************************
2359 * Function : server_content_md5
2361 * Description : Crumble any Content-MD5 headers if the document was
2362 * modified. FIXME: Should we re-compute instead?
2365 * 1 : csp = Current client state (buffers, headers, etc...)
2366 * 2 : header = On input, pointer to header to modify.
2367 * On output, pointer to the modified header, or NULL
2368 * to remove the header. This function frees the
2369 * original string if necessary.
2371 * Returns : JB_ERR_OK on success, or
2372 * JB_ERR_MEMORY on out-of-memory error.
2374 *********************************************************************/
2375 static jb_err server_content_md5(struct client_state *csp, char **header)
2377 if (csp->flags & CSP_FLAG_MODIFIED)
2379 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2386 /*********************************************************************
2388 * Function : server_content_disposition
2390 * Description : If enabled, blocks or modifies the "content-disposition" header.
2391 * Called from `sed'.
2394 * 1 : csp = Current client state (buffers, headers, etc...)
2395 * 2 : header = On input, pointer to header to modify.
2396 * On output, pointer to the modified header, or NULL
2397 * to remove the header. This function frees the
2398 * original string if necessary.
2400 * Returns : JB_ERR_OK on success, or
2401 * JB_ERR_MEMORY on out-of-memory error.
2403 *********************************************************************/
2404 static jb_err server_content_disposition(struct client_state *csp, char **header)
2409 * Are we messing with the content-disposition header?
2411 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2417 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2419 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2422 * Blocking content-disposition header
2424 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2431 * Replacing content-disposition header
2434 *header = strdup("content-disposition: ");
2435 string_append(header, newval);
2437 if (*header == NULL)
2439 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2443 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2446 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2449 /*********************************************************************
2451 * Function : server_last_modified
2453 * Description : Changes Last-Modified header to the actual date
2454 * to help hide-if-modified-since.
2455 * Called from `sed'.
2458 * 1 : csp = Current client state (buffers, headers, etc...)
2459 * 2 : header = On input, pointer to header to modify.
2460 * On output, pointer to the modified header, or NULL
2461 * to remove the header. This function frees the
2462 * original string if necessary.
2464 * Returns : JB_ERR_OK on success, or
2465 * JB_ERR_MEMORY on out-of-memory error.
2467 *********************************************************************/
2468 static jb_err server_last_modified(struct client_state *csp, char **header)
2471 char buf[BUFFER_SIZE];
2474 #ifdef HAVE_GMTIME_R
2477 struct tm *timeptr = NULL;
2478 time_t now, last_modified;
2480 long int days, hours, minutes, seconds;
2483 * Are we messing with the Last-Modified header?
2485 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2491 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2493 if (0 == strcmpic(newval, "block") )
2496 * Blocking Last-Modified header. Useless but why not.
2498 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2502 else if (0 == strcmpic(newval, "reset-to-request-time"))
2505 * Setting Last-Modified Header to now.
2507 get_http_time(0, buf);
2509 *header = strdup("Last-Modified: ");
2510 string_append(header, buf);
2512 if (*header == NULL)
2514 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2518 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2521 else if (0 == strcmpic(newval, "randomize"))
2523 const char *header_time = *header + sizeof("Last-Modified:");
2525 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2527 #ifdef HAVE_GMTIME_R
2528 timeptr = gmtime_r(&now, &gmt);
2529 #elif FEATURE_PTHREAD
2530 pthread_mutex_lock(&gmtime_mutex);
2531 timeptr = gmtime(&now);
2532 pthread_mutex_unlock(&gmtime_mutex);
2534 timeptr = gmtime(&now);
2536 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2538 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2543 rtime = (long int)difftime(now, last_modified);
2546 rtime = pick_from_range(rtime);
2547 last_modified += rtime;
2548 #ifdef HAVE_GMTIME_R
2549 timeptr = gmtime_r(&last_modified, &gmt);
2550 #elif FEATURE_PTHREAD
2551 pthread_mutex_lock(&gmtime_mutex);
2552 timeptr = gmtime(&last_modified);
2553 pthread_mutex_unlock(&gmtime_mutex);
2555 timeptr = gmtime(&last_modified);
2557 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2559 *header = strdup("Last-Modified: ");
2560 string_append(header, newheader);
2562 if (*header == NULL)
2564 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2565 return JB_ERR_MEMORY;
2568 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2570 days = rtime / (3600 * 24);
2571 hours = rtime / 3600 % 24;
2572 minutes = rtime / 60 % 60;
2573 seconds = rtime % 60;
2575 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2576 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2577 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2582 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2591 /*********************************************************************
2593 * Function : client_accept_encoding
2595 * Description : Rewrite the client's Accept-Encoding header so that
2596 * if doesn't allow compression, if the action applies.
2597 * Note: For HTTP/1.0 the absence of the header is enough.
2600 * 1 : csp = Current client state (buffers, headers, etc...)
2601 * 2 : header = On input, pointer to header to modify.
2602 * On output, pointer to the modified header, or NULL
2603 * to remove the header. This function frees the
2604 * original string if necessary.
2606 * Returns : JB_ERR_OK on success, or
2607 * JB_ERR_MEMORY on out-of-memory error.
2609 *********************************************************************/
2610 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2612 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2614 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2618 /* Temporarily disable the correct behaviour to
2619 * work around a PHP bug.
2621 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2623 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2624 * if (*header == NULL)
2626 * return JB_ERR_MEMORY;
2637 /*********************************************************************
2639 * Function : client_te
2641 * Description : Rewrite the client's TE header so that
2642 * if doesn't allow compression, if the action applies.
2645 * 1 : csp = Current client state (buffers, headers, etc...)
2646 * 2 : header = On input, pointer to header to modify.
2647 * On output, pointer to the modified header, or NULL
2648 * to remove the header. This function frees the
2649 * original string if necessary.
2651 * Returns : JB_ERR_OK on success, or
2652 * JB_ERR_MEMORY on out-of-memory error.
2654 *********************************************************************/
2655 static jb_err client_te(struct client_state *csp, char **header)
2657 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2660 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2666 /*********************************************************************
2668 * Function : client_referrer
2670 * Description : Handle the "referer" config setting properly.
2671 * Called from `sed'.
2674 * 1 : csp = Current client state (buffers, headers, etc...)
2675 * 2 : header = On input, pointer to header to modify.
2676 * On output, pointer to the modified header, or NULL
2677 * to remove the header. This function frees the
2678 * original string if necessary.
2680 * Returns : JB_ERR_OK on success, or
2681 * JB_ERR_MEMORY on out-of-memory error.
2683 *********************************************************************/
2684 static jb_err client_referrer(struct client_state *csp, char **header)
2691 #ifdef FEATURE_FORCE_LOAD
2692 /* Since the referrer can include the prefix even
2693 * if the request itself is non-forced, we must
2694 * clean it unconditionally
2696 strclean(*header, FORCE_PREFIX);
2697 #endif /* def FEATURE_FORCE_LOAD */
2700 * Are we sending referer?
2702 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2707 newval = csp->action->string[ACTION_STRING_REFERER];
2709 if ((0 != strcmpic(newval, "conditional-block")))
2713 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2718 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2721 else if (0 == strcmpic(newval, "conditional-block"))
2724 * Block referer if host has changed.
2727 if (NULL == (host = strdup(csp->http->hostport)))
2730 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2731 return JB_ERR_MEMORY;
2733 if (NULL == (referer = strdup(*header)))
2737 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2738 return JB_ERR_MEMORY;
2740 hostlenght = strlen(host);
2741 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2743 /*Shorten referer to make sure the referer is blocked
2744 *if www.example.org/www.example.com-shall-see-the-referer/
2745 *links to www.example.com/
2747 referer[hostlenght+17] = '\0';
2749 if ( 0 == strstr(referer, host)) /*Host has changed*/
2751 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2756 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2762 else if (0 != strcmpic(newval, "forge"))
2765 * We have a specific (fixed) referer we want to send.
2767 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2769 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2771 *header = strdup("Referer: ");
2772 string_append(header, newval);
2773 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2775 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2780 * Forge a referer as http://[hostname:port of REQUEST]/
2781 * to fool stupid checks for in-site links
2784 *header = strdup("Referer: http://");
2785 string_append(header, csp->http->hostport);
2786 string_append(header, "/");
2787 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2789 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2793 /*********************************************************************
2795 * Function : client_accept_language
2797 * Description : Handle the "Accept-Language" config setting properly.
2798 * Called from `sed'.
2801 * 1 : csp = Current client state (buffers, headers, etc...)
2802 * 2 : header = On input, pointer to header to modify.
2803 * On output, pointer to the modified header, or NULL
2804 * to remove the header. This function frees the
2805 * original string if necessary.
2807 * Returns : JB_ERR_OK on success, or
2808 * JB_ERR_MEMORY on out-of-memory error.
2810 *********************************************************************/
2811 static jb_err client_accept_language(struct client_state *csp, char **header)
2816 * Are we messing with the Accept-Language?
2818 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2820 /*I don't think so*/
2824 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2826 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2829 * Blocking Accept-Language header
2831 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2838 * Replacing Accept-Language header
2841 *header = strdup("Accept-Language: ");
2842 string_append(header, newval);
2844 if (*header == NULL)
2846 log_error(LOG_LEVEL_ERROR,
2847 "Insufficent memory. Accept-Language header crunched without replacement.");
2851 log_error(LOG_LEVEL_HEADER,
2852 "Accept-Language header crunched and replaced with: %s", *header);
2855 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2859 /*********************************************************************
2861 * Function : crunch_client_header
2863 * Description : Crunch client header if it matches a string supplied by the
2864 * user. Called from `sed'.
2867 * 1 : csp = Current client state (buffers, headers, etc...)
2868 * 2 : header = On input, pointer to header to modify.
2869 * On output, pointer to the modified header, or NULL
2870 * to remove the header. This function frees the
2871 * original string if necessary.
2873 * Returns : JB_ERR_OK on success and always succeeds
2875 *********************************************************************/
2876 static jb_err crunch_client_header(struct client_state *csp, char **header)
2878 const char *crunch_pattern;
2880 /* Do we feel like crunching? */
2881 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2883 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2885 /* Is the current header the lucky one? */
2886 if (strstr(*header, crunch_pattern))
2888 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2896 /*********************************************************************
2898 * Function : client_uagent
2900 * Description : Handle the "user-agent" config setting properly
2901 * and remember its original value to enable browser
2902 * bug workarounds. Called from `sed'.
2905 * 1 : csp = Current client state (buffers, headers, etc...)
2906 * 2 : header = On input, pointer to header to modify.
2907 * On output, pointer to the modified header, or NULL
2908 * to remove the header. This function frees the
2909 * original string if necessary.
2911 * Returns : JB_ERR_OK on success, or
2912 * JB_ERR_MEMORY on out-of-memory error.
2914 *********************************************************************/
2915 static jb_err client_uagent(struct client_state *csp, char **header)
2919 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2924 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2931 *header = strdup("User-Agent: ");
2932 string_append(header, newval);
2934 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2936 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2939 /*********************************************************************
2941 * Function : client_ua
2943 * Description : Handle "ua-" headers properly. Called from `sed'.
2946 * 1 : csp = Current client state (buffers, headers, etc...)
2947 * 2 : header = On input, pointer to header to modify.
2948 * On output, pointer to the modified header, or NULL
2949 * to remove the header. This function frees the
2950 * original string if necessary.
2952 * Returns : JB_ERR_OK on success, or
2953 * JB_ERR_MEMORY on out-of-memory error.
2955 *********************************************************************/
2956 static jb_err client_ua(struct client_state *csp, char **header)
2958 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2960 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2968 /*********************************************************************
2970 * Function : client_from
2972 * Description : Handle the "from" config setting properly.
2973 * Called from `sed'.
2976 * 1 : csp = Current client state (buffers, headers, etc...)
2977 * 2 : header = On input, pointer to header to modify.
2978 * On output, pointer to the modified header, or NULL
2979 * to remove the header. This function frees the
2980 * original string if necessary.
2982 * Returns : JB_ERR_OK on success, or
2983 * JB_ERR_MEMORY on out-of-memory error.
2985 *********************************************************************/
2986 static jb_err client_from(struct client_state *csp, char **header)
2990 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2997 newval = csp->action->string[ACTION_STRING_FROM];
3000 * Are we blocking the e-mail address?
3002 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3004 log_error(LOG_LEVEL_HEADER, "crunched From!");
3008 log_error(LOG_LEVEL_HEADER, " modified");
3010 *header = strdup("From: ");
3011 string_append(header, newval);
3013 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3017 /*********************************************************************
3019 * Function : client_send_cookie
3021 * Description : Crunches the "cookie" header if necessary.
3022 * Called from `sed'.
3024 * XXX: Stupid name, doesn't send squat.
3027 * 1 : csp = Current client state (buffers, headers, etc...)
3028 * 2 : header = On input, pointer to header to modify.
3029 * On output, pointer to the modified header, or NULL
3030 * to remove the header. This function frees the
3031 * original string if necessary.
3033 * Returns : JB_ERR_OK on success, or
3034 * JB_ERR_MEMORY on out-of-memory error.
3036 *********************************************************************/
3037 static jb_err client_send_cookie(struct client_state *csp, char **header)
3039 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3041 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3049 /*********************************************************************
3051 * Function : client_x_forwarded
3053 * Description : Handle the "x-forwarded-for" config setting properly,
3054 * also used in the add_client_headers list. Called from `sed'.
3057 * 1 : csp = Current client state (buffers, headers, etc...)
3058 * 2 : header = On input, pointer to header to modify.
3059 * On output, pointer to the modified header, or NULL
3060 * to remove the header. This function frees the
3061 * original string if necessary.
3063 * Returns : JB_ERR_OK on success, or
3064 * JB_ERR_MEMORY on out-of-memory error.
3066 *********************************************************************/
3067 jb_err client_x_forwarded(struct client_state *csp, char **header)
3069 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3071 /* Save it so we can re-add it later */
3072 freez(csp->x_forwarded);
3073 csp->x_forwarded = *header;
3076 * Always set *header = NULL, since this information
3077 * will be sent at the end of the header.
3084 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3091 /*********************************************************************
3093 * Function : client_max_forwards
3095 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3096 * from the value of the Max-Forwards header field.
3099 * 1 : csp = Current client state (buffers, headers, etc...)
3100 * 2 : header = On input, pointer to header to modify.
3101 * On output, pointer to the modified header, or NULL
3102 * to remove the header. This function frees the
3103 * original string if necessary.
3105 * Returns : JB_ERR_OK on success, or
3106 * JB_ERR_MEMORY on out-of-memory error.
3108 *********************************************************************/
3109 static jb_err client_max_forwards(struct client_state *csp, char **header)
3113 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3114 (0 == strcmpic(csp->http->gpc, "options")))
3116 assert(*(*header+12) == ':');
3117 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3119 if (max_forwards > 0)
3121 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3122 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3123 csp->http->gpc, max_forwards);
3125 else if (max_forwards < 0)
3127 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3133 * Not supposed to be reached. direct_response() which
3134 * was already called earlier in chat() should have
3135 * intercepted the request.
3137 log_error(LOG_LEVEL_ERROR,
3138 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3139 assert(max_forwards != 0);
3144 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3153 /*********************************************************************
3155 * Function : client_host
3157 * Description : If the request URI did not contain host and
3158 * port information, parse and evaluate the Host
3161 * Also, kill ill-formed HOST: headers as sent by
3162 * Apple's iTunes software when used with a proxy.
3165 * 1 : csp = Current client state (buffers, headers, etc...)
3166 * 2 : header = On input, pointer to header to modify.
3167 * On output, pointer to the modified header, or NULL
3168 * to remove the header. This function frees the
3169 * original string if necessary.
3171 * Returns : JB_ERR_OK on success, or
3172 * JB_ERR_MEMORY on out-of-memory error.
3174 *********************************************************************/
3175 static jb_err client_host(struct client_state *csp, char **header)
3180 * If the header field name is all upper-case, chances are that it's
3181 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3182 * not a problem -- they are regenerated later.
3184 if ((*header)[1] == 'O')
3186 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3191 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3192 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3195 if (NULL == (p = strdup((*header)+6)))
3197 return JB_ERR_MEMORY;
3200 if (NULL == (q = strdup(p)))
3203 return JB_ERR_MEMORY;
3206 freez(csp->http->hostport);
3207 csp->http->hostport = p;
3208 freez(csp->http->host);
3209 csp->http->host = q;
3210 q = strchr(csp->http->host, ':');
3213 /* Terminate hostname and evaluate port string */
3215 csp->http->port = atoi(q);
3219 csp->http->port = csp->http->ssl ? 443 : 80;
3222 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3223 csp->http->hostport, csp->http->host, csp->http->port);
3226 /* Signal client_host_adder() to return right away */
3227 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3232 /*********************************************************************
3234 * Function : client_if_modified_since
3236 * Description : Remove or modify the If-Modified-Since header.
3239 * 1 : csp = Current client state (buffers, headers, etc...)
3240 * 2 : header = On input, pointer to header to modify.
3241 * On output, pointer to the modified header, or NULL
3242 * to remove the header. This function frees the
3243 * original string if necessary.
3245 * Returns : JB_ERR_OK on success, or
3246 * JB_ERR_MEMORY on out-of-memory error.
3248 *********************************************************************/
3249 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3252 #ifdef HAVE_GMTIME_R
3255 struct tm *timeptr = NULL;
3259 long int hours, minutes, seconds;
3263 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3266 * The client got an error message because of a temporary problem,
3267 * the problem is gone and the client now tries to revalidate our
3268 * error message on the real server. The revalidation would always
3269 * end with the transmission of the whole document and there is
3270 * no need to expose the bogus If-Modified-Since header.
3272 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3275 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3277 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3279 if ((0 == strcmpic(newval, "block")))
3281 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3284 else /* add random value */
3286 const char *header_time = *header + sizeof("If-Modified-Since:");
3288 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3290 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3295 rtime = strtol(newval, &endptr, 0);
3298 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3299 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3306 rtime = pick_from_range(rtime);
3310 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3313 tm += rtime * (negative ? -1 : 1);
3314 #ifdef HAVE_GMTIME_R
3315 timeptr = gmtime_r(&tm, &gmt);
3316 #elif FEATURE_PTHREAD
3317 pthread_mutex_lock(&gmtime_mutex);
3318 timeptr = gmtime(&tm);
3319 pthread_mutex_unlock(&gmtime_mutex);
3321 timeptr = gmtime(&tm);
3323 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3326 *header = strdup("If-Modified-Since: ");
3327 string_append(header, newheader);
3329 if (*header == NULL)
3331 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3332 return JB_ERR_MEMORY;
3335 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3337 hours = rtime / 3600;
3338 minutes = rtime / 60 % 60;
3339 seconds = rtime % 60;
3341 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3342 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3343 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3352 /*********************************************************************
3354 * Function : client_if_none_match
3356 * Description : Remove the If-None-Match header.
3359 * 1 : csp = Current client state (buffers, headers, etc...)
3360 * 2 : header = On input, pointer to header to modify.
3361 * On output, pointer to the modified header, or NULL
3362 * to remove the header. This function frees the
3363 * original string if necessary.
3365 * Returns : JB_ERR_OK on success, or
3366 * JB_ERR_MEMORY on out-of-memory error.
3368 *********************************************************************/
3369 static jb_err client_if_none_match(struct client_state *csp, char **header)
3371 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3373 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3380 /*********************************************************************
3382 * Function : client_x_filter
3384 * Description : Disables filtering if the client set "X-Filter: No".
3385 * Called from `sed'.
3388 * 1 : csp = Current client state (buffers, headers, etc...)
3389 * 2 : header = On input, pointer to header to modify.
3390 * On output, pointer to the modified header, or NULL
3391 * to remove the header. This function frees the
3392 * original string if necessary.
3394 * Returns : JB_ERR_OK on success
3396 *********************************************************************/
3397 jb_err client_x_filter(struct client_state *csp, char **header)
3399 if ( 0 == strcmpic(*header, "X-Filter: No"))
3401 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3403 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3407 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3409 log_error(LOG_LEVEL_HEADER,
3410 "force-text-mode overruled the client's request to fetch without filtering!");
3414 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3415 csp->flags |= CSP_FLAG_NO_FILTERING;
3416 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3418 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3425 /* the following functions add headers directly to the header list */
3427 /*********************************************************************
3429 * Function : client_host_adder
3431 * Description : Adds the Host: header field if it is missing.
3432 * Called from `sed'.
3435 * 1 : csp = Current client state (buffers, headers, etc...)
3437 * Returns : JB_ERR_OK on success, or
3438 * JB_ERR_MEMORY on out-of-memory error.
3440 *********************************************************************/
3441 static jb_err client_host_adder(struct client_state *csp)
3446 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3448 /* Header already set by the client, nothing to do. */
3452 if ( !csp->http->hostport || !*(csp->http->hostport))
3454 /* XXX: When does this happen and why is it OK? */
3455 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3460 * remove 'user:pass@' from 'proto://user:pass@host'
3462 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3468 p = csp->http->hostport;
3471 /* XXX: Just add it, we already made sure that it will be unique */
3472 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3473 err = enlist_unique_header(csp->headers, "Host", p);
3479 /*********************************************************************
3481 * Function : client_cookie_adder
3483 * Description : Used in the add_client_headers list to add "wafers".
3484 * Called from `sed'.
3487 * 1 : csp = Current client state (buffers, headers, etc...)
3489 * Returns : JB_ERR_OK on success, or
3490 * JB_ERR_MEMORY on out-of-memory error.
3492 *********************************************************************/
3493 jb_err client_cookie_adder(struct client_state *csp)
3496 struct list_entry *wafer;
3497 struct list_entry *wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3500 if (NULL == wafer_list)
3506 tmp = strdup("Cookie: ");
3508 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3510 if (wafer != wafer_list)
3512 /* As this isn't the first wafer, we need a delimiter. */
3513 string_append(&tmp, "; ");
3515 string_join(&tmp, cookie_encode(wafer->str));
3520 return JB_ERR_MEMORY;
3523 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3524 err = enlist(csp->headers, tmp);
3530 /*********************************************************************
3532 * Function : client_accept_encoding_adder
3534 * Description : Add an Accept-Encoding header to the client's request
3535 * that disables compression if the action applies, and
3536 * the header is not already there. Called from `sed'.
3537 * Note: For HTTP/1.0, the absence of the header is enough.
3540 * 1 : csp = Current client state (buffers, headers, etc...)
3542 * Returns : JB_ERR_OK on success, or
3543 * JB_ERR_MEMORY on out-of-memory error.
3545 *********************************************************************/
3546 static jb_err client_accept_encoding_adder(struct client_state *csp)
3548 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3549 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3551 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3558 /*********************************************************************
3560 * Function : client_xtra_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 static jb_err client_xtra_adder(struct client_state *csp)
3573 struct list_entry *lst;
3576 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3577 lst ; lst = lst->next)
3579 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3580 err = enlist(csp->headers, lst->str);
3592 /*********************************************************************
3594 * Function : client_x_forwarded_adder
3596 * Description : Used in the add_client_headers list. Called from `sed'.
3599 * 1 : csp = Current client state (buffers, headers, etc...)
3601 * Returns : JB_ERR_OK on success, or
3602 * JB_ERR_MEMORY on out-of-memory error.
3604 *********************************************************************/
3605 static jb_err client_x_forwarded_adder(struct client_state *csp)
3610 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3615 if (csp->x_forwarded)
3617 p = strdup(csp->x_forwarded);
3618 string_append(&p, ", ");
3622 p = strdup("X-Forwarded-For: ");
3624 string_append(&p, csp->ip_addr_str);
3628 return JB_ERR_MEMORY;
3631 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3632 err = enlist(csp->headers, p);
3639 /*********************************************************************
3641 * Function : connection_close_adder
3643 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3644 * support. Adds a "Connection: close" header to csp->headers
3645 * unless the header was already present. Called from `sed'.
3647 * FIXME: This whole function shouldn't be neccessary!
3650 * 1 : csp = Current client state (buffers, headers, etc...)
3652 * Returns : JB_ERR_OK on success, or
3653 * JB_ERR_MEMORY on out-of-memory error.
3655 *********************************************************************/
3656 static jb_err connection_close_adder(struct client_state *csp)
3658 const unsigned int flags = csp->flags;
3661 * Return right away if
3663 * - we're parsing server headers and the server header
3664 * "Connection: close" is already set, or if
3666 * - we're parsing client headers and the client header
3667 * "Connection: close" is already set.
3669 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3670 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3671 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3672 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3677 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3679 return enlist(csp->headers, "Connection: close");
3683 /*********************************************************************
3685 * Function : server_http
3687 * Description : - Save the HTTP Status into csp->http->status
3688 * - Set CT_TABOO to prevent filtering if the answer
3689 * is a partial range (HTTP status 206)
3690 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3694 * 1 : csp = Current client state (buffers, headers, etc...)
3695 * 2 : header = On input, pointer to header to modify.
3696 * On output, pointer to the modified header, or NULL
3697 * to remove the header. This function frees the
3698 * original string if necessary.
3700 * Returns : JB_ERR_OK on success, or
3701 * JB_ERR_MEMORY on out-of-memory error.
3703 *********************************************************************/
3704 static jb_err server_http(struct client_state *csp, char **header)
3706 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3707 if (csp->http->status == 206)
3709 csp->content_type = CT_TABOO;
3712 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3715 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3722 /*********************************************************************
3724 * Function : server_set_cookie
3726 * Description : Handle the server "cookie" header properly.
3727 * Log cookie to the jar file. Then "crunch",
3728 * accept or rewrite it to a session cookie.
3729 * Called from `sed'.
3731 * TODO: Allow the user to specify a new expiration
3732 * time to cause the cookie to expire even before the
3733 * browser is closed.
3736 * 1 : csp = Current client state (buffers, headers, etc...)
3737 * 2 : header = On input, pointer to header to modify.
3738 * On output, pointer to the modified header, or NULL
3739 * to remove the header. This function frees the
3740 * original string if necessary.
3742 * Returns : JB_ERR_OK on success, or
3743 * JB_ERR_MEMORY on out-of-memory error.
3745 *********************************************************************/
3746 static jb_err server_set_cookie(struct client_state *csp, char **header)
3753 #ifdef FEATURE_COOKIE_JAR
3754 if (csp->config->jar)
3757 * Write timestamp into outbuf.
3759 * Complex because not all OSs have tm_gmtoff or
3760 * the %z field in strftime()
3762 char tempbuf[ BUFFER_SIZE ];
3764 #ifdef HAVE_LOCALTIME_R
3765 tm_now = *localtime_r(&now, &tm_now);
3766 #elif FEATURE_PTHREAD
3767 pthread_mutex_lock(&localtime_mutex);
3768 tm_now = *localtime (&now);
3769 pthread_mutex_unlock(&localtime_mutex);
3771 tm_now = *localtime (&now);
3773 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3775 /* strlen("set-cookie: ") = 12 */
3776 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3778 #endif /* def FEATURE_COOKIE_JAR */
3780 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3782 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3785 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3787 /* Flag whether or not to log a message */
3790 /* A variable to store the tag we're working on */
3793 /* Skip "Set-Cookie:" (11 characters) in header */
3794 cur_tag = *header + 11;
3796 /* skip whitespace between "Set-Cookie:" and value */
3797 while (*cur_tag && ijb_isspace(*cur_tag))
3802 /* Loop through each tag in the cookie */
3806 char *next_tag = strchr(cur_tag, ';');
3807 if (next_tag != NULL)
3809 /* Skip the ';' character itself */
3812 /* skip whitespace ";" and start of tag */
3813 while (*next_tag && ijb_isspace(*next_tag))
3820 /* "Next tag" is the end of the string */
3821 next_tag = cur_tag + strlen(cur_tag);
3825 * Check the expiration date to see
3826 * if the cookie is still valid, if yes,
3827 * rewrite it to a session cookie.
3829 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3831 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3833 /* Did we detect the date properly? */
3834 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3837 * Nope, treat it as if it was still valid.
3839 * XXX: Should we remove the whole cookie instead?
3841 log_error(LOG_LEVEL_ERROR,
3842 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3843 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3849 * Yes. Check if the cookie is still valid.
3851 * If the cookie is already expired it's probably
3852 * a delete cookie and even if it isn't, the browser
3853 * will discard it anyway.
3857 * XXX: timegm() isn't available on some AmigaOS
3858 * versions and our replacement doesn't work.
3860 * Our options are to either:
3862 * - disable session-cookies-only completely if timegm
3865 * - to simply remove all expired tags, like it has
3866 * been done until Privoxy 3.0.6 and to live with
3867 * the consequence that it can cause login/logout
3868 * problems on servers that don't validate their
3869 * input properly, or
3871 * - to replace it with mktime in which
3872 * case there is a slight chance of valid cookies
3873 * passing as already expired.
3875 * This is the way it's currently done and it's not
3876 * as bad as it sounds. If the missing GMT offset is
3877 * enough to change the result of the expiration check
3878 * the cookie will be only valid for a few hours
3879 * anyway, which in many cases will be shorter
3880 * than a browser session.
3882 if (cookie_time - now < 0)
3884 log_error(LOG_LEVEL_HEADER,
3885 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3886 /* Just in case some clown sets more then one expiration date */
3892 * Still valid, delete expiration date by copying
3893 * the rest of the string over it.
3895 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3896 * since the behaviour of strcpy is undefined for overlapping
3899 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3901 /* That changed the header, need to issue a log message */
3905 * Note that the next tag has now been moved to *cur_tag,
3906 * so we do not need to update the cur_tag pointer.
3914 /* Move on to next cookie tag */
3921 assert(NULL != *header);
3922 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3931 #ifdef FEATURE_FORCE_LOAD
3932 /*********************************************************************
3934 * Function : strclean
3936 * Description : In-Situ-Eliminate all occurances of substring in
3940 * 1 : string = string to clean
3941 * 2 : substring = substring to eliminate
3943 * Returns : Number of eliminations
3945 *********************************************************************/
3946 int strclean(const char *string, const char *substring)
3952 len = strlen(substring);
3954 while((pos = strstr(string, substring)) != NULL)
3961 while (*p++ != '\0');
3968 #endif /* def FEATURE_FORCE_LOAD */
3970 /*********************************************************************
3972 * Function : parse_header_time
3974 * Description : Parses time formats used in HTTP header strings
3975 * to get the numerical respresentation.
3978 * 1 : header_time = HTTP header time as string.
3979 * 2 : result = storage for header_time in seconds
3981 * Returns : JB_ERR_OK if the time format was recognized, or
3982 * JB_ERR_PARSE otherwise.
3984 *********************************************************************/
3985 static jb_err parse_header_time(const char *header_time, time_t *result)
3990 * Zero out gmt to prevent time zone offsets.
3992 * While this is only necessary on some platforms
3993 * (mingw32 for example), I don't know how to
3994 * detect these automatically and doing it everywhere
3997 memset(&gmt, 0, sizeof(gmt));
3999 /* Tue, 02 Jun 2037 20:00:00 */
4000 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4001 /* Tue, 02-Jun-2037 20:00:00 */
4002 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4003 /* Tue, 02-Jun-37 20:00:00 */
4004 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4005 /* Tuesday, 02-Jun-2037 20:00:00 */
4006 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4007 /* Tuesday Jun 02 20:00:00 2037 */
4008 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4010 return JB_ERR_PARSE;
4013 *result = timegm(&gmt);
4019 /*********************************************************************
4021 * Function : get_destination_from_headers
4023 * Description : Parse the "Host:" header to get the request's destination.
4024 * Only needed if the client's request was forcefully
4025 * redirected into Privoxy.
4027 * Code mainly copied from client_host() which is currently
4028 * run too late for this purpose.
4031 * 1 : headers = List of headers (one of them hopefully being
4032 * the "Host:" header)
4033 * 2 : http = storage for the result (host, port and hostport).
4035 * Returns : JB_ERR_MEMORY in case of memory problems,
4036 * JB_ERR_PARSE if the host header couldn't be found,
4037 * JB_ERR_OK otherwise.
4039 *********************************************************************/
4040 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4046 host = get_header_value(headers, "Host:");
4050 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4051 return JB_ERR_PARSE;
4054 if (NULL == (p = strdup((host))))
4056 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4057 return JB_ERR_MEMORY;
4060 if (NULL == (q = strdup(p)))
4063 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4064 return JB_ERR_MEMORY;
4067 freez(http->hostport);
4071 q = strchr(http->host, ':');
4074 /* Terminate hostname and evaluate port string */
4076 http->port = atoi(q);
4080 http->port = http->ssl ? 443 : 80;
4083 /* Rebuild request URL */
4085 http->url = strdup(http->ssl ? "https://" : "http://");
4086 string_append(&http->url, http->hostport);
4087 string_append(&http->url, http->path);
4088 if (http->url == NULL)
4090 return JB_ERR_MEMORY;
4093 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",