1 const char parsers_rcs[] = "$Id: parsers.c,v 1.146 2008/10/12 16:46:35 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-2008 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.146 2008/10/12 16:46:35 fabiankeil
48 * Remove obsolete warning about delayed delivery with chunked
49 * transfer encoding and FEATURE_CONNECTION_KEEP_ALIVE enabled.
51 * Revision 1.145 2008/10/09 18:21:41 fabiankeil
52 * Flush work-in-progress changes to keep outgoing connections
53 * alive where possible. Incomplete and mostly #ifdef'd out.
55 * Revision 1.144 2008/09/21 13:59:33 fabiankeil
56 * Treat unknown change-x-forwarded-for parameters as fatal errors.
58 * Revision 1.143 2008/09/21 13:36:52 fabiankeil
59 * If change-x-forwarded-for{add} is used and the client
60 * sends multiple X-Forwarded-For headers, append the client's
61 * IP address to each one of them. "Traditionally" we would
62 * lose all but the last one.
64 * Revision 1.142 2008/09/20 10:04:33 fabiankeil
65 * Remove hide-forwarded-for-headers action which has
66 * been obsoleted by change-x-forwarded-for{block}.
68 * Revision 1.141 2008/09/19 15:26:28 fabiankeil
69 * Add change-x-forwarded-for{} action to block or add
70 * X-Forwarded-For headers. Mostly based on code removed
73 * Revision 1.140 2008/09/12 17:51:43 fabiankeil
74 * - A few style fixes.
75 * - Remove a pointless cast.
77 * Revision 1.139 2008/09/04 08:13:58 fabiankeil
78 * Prepare for critical sections on Windows by adding a
79 * layer of indirection before the pthread mutex functions.
81 * Revision 1.138 2008/08/30 12:03:07 fabiankeil
82 * Remove FEATURE_COOKIE_JAR.
84 * Revision 1.137 2008/05/30 15:50:08 fabiankeil
85 * Remove questionable micro-optimizations
86 * whose usefulness has never been measured.
88 * Revision 1.136 2008/05/26 16:02:24 fabiankeil
89 * s@Insufficent@Insufficient@
91 * Revision 1.135 2008/05/21 20:12:10 fabiankeil
92 * The whole point of strclean() is to modify the
93 * first parameter, so don't mark it immutable,
94 * even though the compiler lets us get away with it.
96 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
97 * As the wafer actions are gone, we can stop including encode.h.
99 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
100 * Ditch cast from (char **) to (char **).
102 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
103 * Streamline sed()'s prototype and declare
104 * the header parse and add structures static.
106 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
107 * Factor update_server_headers() out of sed(), ditch the
108 * first_run hack and make server_patterns_light static.
110 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
111 * Wrap memmove() calls in string_move()
112 * to document the purpose in one place.
114 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
115 * Normalize linear header white space.
117 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
118 * If a header is split across multiple lines,
119 * merge them to a single line before parsing them.
121 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
122 * Don't provide get_header() with the whole client state
123 * structure when it only needs access to csp->iob.
125 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
126 * Change content_filters_enabled()'s parameter from
127 * csp->action to action so it can be also used in the
128 * CGI code. Don't bother checking if there are filters
129 * loaded, as that's somewhat besides the point.
131 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
132 * Provide get_http_time() with the buffer size so it doesn't
133 * have to blindly assume that the buffer is big enough.
135 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
136 * Don't pass the whole csp structure to flush_socket()
137 * when it only needs a file descriptor and a buffer.
139 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
140 * Remove send-wafer and send-vanilla-wafer actions.
142 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
143 * Remove inspect-jpegs action.
145 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
146 * Let client_range() also handle Request-Range headers
147 * which apparently are still supported by many servers.
149 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
150 * Improve the warning messages that get logged if the action files
151 * "enable" filters but no filters of that type have been loaded.
153 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
154 * In server_content_type():
155 * - Don't require leading white space when detecting image content types.
156 * - Change '... not replaced ...' message to sound less crazy if the text
157 * type actually is 'text/plain'.
158 * - Mark the 'text/plain == binary data' assumption for removal.
159 * - Remove a bunch of trailing white space.
161 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
162 * Minor server_content_disposition() changes:
163 * - Don't regenerate the header name all lower-case.
164 * - Some white space fixes.
165 * - Remove useless log message in case of ENOMEM.
167 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
168 * Garbage-collect the code to add a X-Forwarded-For
169 * header as it seems to be mostly used by accident.
171 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
172 * Fix a crash on mingw32 with some Last Modified times in the future.
174 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
175 * Remove a "can't happen" error block which, over
176 * time, mutated into a "guaranteed to happen" block.
178 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
179 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
180 * - Use shiny new content_filters_enabled() in client_range().
182 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
183 * I forgot about Poland.
185 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
186 * Remove Range and If-Range headers if content filtering is enabled.
188 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
189 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
190 * client_cookie_adder() to make sure send-vanilla-wafer can be
191 * controlled through tags (and thus regression-tested).
193 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
194 * - Remove "scanning headers for" log message again.
195 * - Some more whitespace fixes.
197 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
198 * Refactor client_referrer() and add conditional-forge parameter.
200 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
201 * A bunch of whitespace fixes, pointy hat to me.
203 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
204 * Fix possible memory corruption in server_http, make sure it's not
205 * executed for ordinary server headers and mark some problems for later.
207 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
208 * Let content-type-overwrite{} honour force-text-mode again.
210 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
211 * - Add prototpyes for the header parsers and make them static.
212 * - Comment out client_accept_encoding_adder() which isn't used right now.
214 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
215 * Move the ACTION_FORCE_TEXT_MODE check out of
216 * server_content_type(). Signal other functions
217 * whether or not a content type has been declared.
218 * Part of the fix for BR#1750917.
220 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
221 * Change sed() to return a jb_err in preparation for forward-override{}.
223 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
224 * Adjust "X-Filter: No" to disable dedicated header filters.
226 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
227 * Streamline client_cookie_adder().
229 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
230 * Make sure filters with dynamic jobs actually use them.
232 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
233 * - Introduce dynamic pcrs jobs that can resolve variables.
234 * - Remove unnecessary update_action_bits_for_all_tags() call.
236 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
237 * - Make tagging based on tags set by earlier taggers
238 * of the same kind possible.
239 * - Log whether or not new tags cause action bits updates
240 * (in which case a matching tag-pattern section exists).
241 * - Log if the user tries to set a tag that is already set.
243 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
244 * Introduce tags as alternative way to specify which
245 * actions apply to a request. At the moment tags can be
246 * created based on client and server headers.
248 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
249 * Log a warning if the content is compressed, filtering is
250 * enabled and Privoxy was compiled without zlib support.
253 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
254 * - Fix warnings when compiled with glibc.
255 * - Don't use crumble() for cookie crunching.
256 * - Move cookie time parsing into parse_header_time().
257 * - Let parse_header_time() return a jb_err code
258 * instead of a pointer that can only be used to
259 * check for NULL anyway.
261 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
262 * - Add better protection against malicious gzip headers.
263 * - Stop logging the first hundred bytes of decompressed content.
264 * It looks like it's working and there is always debug 16.
265 * - Log the content size after decompression in decompress_iob()
266 * instead of pcrs_filter_response().
268 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
269 * - Use dedicated header filter actions instead of abusing "filter".
270 * Replace "filter-client-headers" and "filter-client-headers"
271 * with "server-header-filter" and "client-header-filter".
272 * - Remove filter_client_header() and filter_client_header(),
273 * filter_header() now checks the shiny new
274 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
276 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
277 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
278 * - Handle "Cookie:" and "Connection:" headers a bit smarter
279 * (don't crunch them just to recreate them later on).
280 * - Add another non-standard time format for the cookie
281 * expiration date detection.
282 * - Fix a valgrind warning.
284 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
285 * Improve cookie expiration date detection.
287 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
288 * Don't run server_content_length() the first time
289 * sed() parses server headers; only adjust the
290 * Content-Length header if the page was modified.
292 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
293 * Fix log messages regarding the cookie time format
294 * (cookie and request URL were mixed up).
296 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
297 * - Let decompress_iob()
298 * - not corrupt the content if decompression fails
299 * early. (the first byte(s) were lost).
300 * - use pointer arithmetics with defined outcome for
302 * - Use a different kludge to remember a failed decompression.
304 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
305 * Search for Max-Forwards headers case-insensitive,
306 * don't generate the "501 unsupported" message for invalid
307 * Max-Forwards values and don't increase negative ones.
309 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
310 * - Let server_set_cookie() check the expiration date
311 * of cookies and don't touch the ones that are already
312 * expired. Fixes problems with low quality web applications
313 * as described in BR 932612.
315 * - Adjust comment in client_max_forwards to reality;
316 * remove invalid Max-Forwards headers.
318 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
319 * Stop filter_header() from unintentionally removing
320 * empty header lines that were enlisted by the continue
323 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
324 * - Repeat the request URL before logging any headers.
325 * Makes reading the log easier in case of simultaneous requests.
326 * - If there are more than one Content-Type headers in one request,
327 * use the first one and remove the others.
328 * - Remove "newval" variable in server_content_type().
329 * It's only used once.
331 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
332 * Correct a cast, check inflateEnd() exit code
333 * to see if we have to, replace sprintf calls
336 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
337 * Integrate a modified version of Wil Mahan's
338 * zlib patch (PR #895531).
340 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
341 * Skip empty filter files in filter_header()
342 * but don't ignore the ones that come afterwards.
343 * Fixes BR 1619208, this time for real.
345 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
346 * Reverted parts of my last commit
347 * to keep error handling working.
349 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
350 * Fixed gcc43 conversion warnings.
352 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
353 * Bringing back the "useless" localtime() call
354 * I removed in revision 1.67. On some platforms
355 * it's necessary to prevent time zone offsets.
357 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
358 * Rebuild request URL in get_destination_from_headers()
359 * to make sure redirect{pcrs command} works as expected
360 * for intercepted requests.
362 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
363 * Added get_destination_from_headers().
365 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
366 * Make pthread mutex locking more generic. Instead of
367 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
368 * and use mutex locking unless there is an _r function
369 * available. Better safe than sorry.
371 * Fixes "./configure --disable-pthread" and should result
372 * in less threading-related problems on pthread-using platforms,
373 * but it still doesn't fix BR#1122404.
375 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
376 * The special header "X-Filter: No" now disables
377 * header filtering as well.
379 * Revision 1.73 2006/09/23 13:26:38 roro
380 * Replace TABs by spaces in source code.
382 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
383 * Don't print a log message every time filter_headers is
384 * entered or left. It only creates noise without any real
387 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
388 * Fix +hide-if-modified-since{-n}.
390 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
391 * Have hide-if-modified-since interpret the random
392 * range value as minutes instead of hours. Allows
393 * more fine-grained configuration.
395 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
396 * Always have parse_header_time return a pointer
397 * that actual makes sense, even though we currently
398 * only need it to detect problems.
400 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
401 * Added config option enable-remote-http-toggle
402 * to specify if Privoxy should recognize special
403 * headers (currently only X-Filter) to change its
404 * behaviour. Disabled by default.
406 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
407 * After filtering de-chunked instances, remove
408 * "Transfer-Encoding" header entirely instead of changing
409 * it to "Transfer-Encoding: identity", which is invalid.
410 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
412 * Don't use localtime in parse_header_time. An empty time struct
413 * is good enough, it gets overwritten by strptime anyway.
415 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
416 * Use gmtime_r if available, fallback to gmtime with mutex
417 * protection for MacOSX and use vanilla gmtime for the rest.
419 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
420 * Changed client_referrer to use the right type (size_t) for
421 * hostlenght and to shorten the temporary referrer string with
422 * '\0' instead of adding a useless line break.
424 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
425 * - Back to timegm() using GnuPG's replacement if necessary.
426 * Using mktime() and localtime() could add a on hour offset if
427 * the randomize factor was big enough to lead to a summer/wintertime
430 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
432 * - Moved randomization code into pick_from_range().
434 * - Changed parse_header_time definition.
435 * time_t isn't guaranteed to be signed and
436 * if it isn't, -1 isn't available as error code.
437 * Changed some variable types in client_if_modified_since()
438 * because of the same reason.
440 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
441 * OS/2 compilation compatibility fixups
443 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
444 * Changed include from strptime.c to strptime.h
446 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
447 * Split filter-headers{} into filter-client-headers{}
448 * and filter-server-headers{}.
449 * Added parse_header_time() to share some code.
450 * Replaced timegm() with mktime().
452 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
453 * Windows service integration
455 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
456 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
458 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
459 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
460 * with what was really the latest development (the v_3_0_branch branch)
462 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
463 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
465 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
466 * Add the ability to check jpeg images for invalid
467 * lengths of comment blocks. Defensive strategy
468 * against the exploit:
469 * Microsoft Security Bulletin MS04-028
470 * Buffer Overrun in JPEG Processing (GDI+) Could
471 * Allow Code Execution (833987)
472 * Enabled with +inspect-jpegs in actions files.
474 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
475 * Excluded text/plain objects from filtering. This fixes a
476 * couple of client-crashing, download corruption and
477 * Privoxy performance issues, whose root cause lies in
478 * web servers labelling content of unknown type as text/plain.
480 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
481 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
483 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
484 * Completing the previous change
486 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
487 * Added temporary workaround for bug in PHP < 4.2.3
489 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
490 * 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.
492 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
493 * Fix typo: supressed -> suppressed
495 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
496 * Improved cookie logging
498 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
499 * Added basic support for OPTIONS and TRACE HTTP methods:
500 * - New parser function client_max_forwards which decrements
501 * the Max-Forwards HTTP header field of OPTIONS and TRACE
502 * requests by one before forwarding
503 * - New parser function client_host which extracts the host
504 * and port information from the HTTP header field if the
505 * request URI was not absolute
506 * - Don't crumble and re-add the Host: header, but only generate
507 * and append if missing
509 * Revision 1.56 2002/05/12 15:34:22 jongfoster
510 * Fixing typo in a comment
512 * Revision 1.55 2002/05/08 16:01:07 oes
513 * Optimized add_to_iob:
514 * - Use realloc instead of malloc(), memcpy(), free()
515 * - Expand to powers of two if possible, to get
516 * O(log n) reallocs instead of O(n).
517 * - Moved check for buffer limit here from chat
518 * - Report failure via returncode
520 * Revision 1.54 2002/04/02 15:03:16 oes
521 * Tiny code cosmetics
523 * Revision 1.53 2002/03/26 22:29:55 swa
524 * we have a new homepage!
526 * Revision 1.52 2002/03/24 13:25:43 swa
527 * name change related issues
529 * Revision 1.51 2002/03/13 00:27:05 jongfoster
532 * Revision 1.50 2002/03/12 01:45:35 oes
533 * More verbose logging
535 * Revision 1.49 2002/03/09 20:03:52 jongfoster
536 * - Making various functions return int rather than size_t.
537 * (Undoing a recent change). Since size_t is unsigned on
538 * Windows, functions like read_socket that return -1 on
539 * error cannot return a size_t.
541 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
542 * crashes, and also frequently caused JB to jump to 100%
543 * CPU and stay there. (Because it thought it had just
544 * read ((unsigned)-1) == 4Gb of data...)
546 * - The signature of write_socket has changed, it now simply
547 * returns success=0/failure=nonzero.
549 * - Trying to get rid of a few warnings --with-debug on
550 * Windows, I've introduced a new type "jb_socket". This is
551 * used for the socket file descriptors. On Windows, this
552 * is SOCKET (a typedef for unsigned). Everywhere else, it's
553 * an int. The error value can't be -1 any more, so it's
554 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
555 * Windows it maps to the #define INVALID_SOCKET.)
557 * - The signature of bind_port has changed.
559 * Revision 1.48 2002/03/07 03:46:53 oes
560 * Fixed compiler warnings etc
562 * Revision 1.47 2002/02/20 23:15:13 jongfoster
563 * Parsing functions now handle out-of-memory gracefully by returning
566 * Revision 1.46 2002/01/17 21:03:47 jongfoster
567 * Moving all our URL and URL pattern parsing code to urlmatch.c.
569 * Revision 1.45 2002/01/09 14:33:03 oes
570 * Added support for localtime_r.
572 * Revision 1.44 2001/12/14 01:22:54 steudten
573 * Remove 'user:pass@' from 'proto://user:pass@host' for the
574 * new added header 'Host: ..'. (See Req ID 491818)
576 * Revision 1.43 2001/11/23 00:26:38 jongfoster
577 * Fixing two really stupid errors in my previous commit
579 * Revision 1.42 2001/11/22 21:59:30 jongfoster
580 * Adding code to handle +no-cookies-keep
582 * Revision 1.41 2001/11/05 23:43:05 steudten
583 * Add time+date to log files.
585 * Revision 1.40 2001/10/26 20:13:09 jongfoster
586 * ctype.h is needed in Windows, too.
588 * Revision 1.39 2001/10/26 17:40:04 oes
589 * Introduced get_header_value()
590 * Removed http->user_agent, csp->referrer and csp->accept_types
591 * Removed client_accept()
593 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
594 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
595 * threads to call select() simultaneously. So, it's time to do a real, live,
596 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
597 * (native). Both versions will work, but using __OS2__ offers multi-threading.
599 * Revision 1.37 2001/10/23 21:36:02 jongfoster
600 * Documenting sed()'s error behaviou (doc change only)
602 * Revision 1.36 2001/10/13 12:51:51 joergs
603 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
604 * force-load), instead crumble Host: and add it (again) in client_host_adder
605 * (in case we get a HTTP/1.0 request without Host: header and forward it to
606 * a HTTP/1.1 server/proxy).
608 * Revision 1.35 2001/10/09 22:39:21 jongfoster
609 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
612 * Revision 1.34 2001/10/07 18:50:55 oes
613 * Added server_content_encoding, renamed server_transfer_encoding
615 * Revision 1.33 2001/10/07 18:04:49 oes
616 * Changed server_http11 to server_http and its pattern to "HTTP".
617 * Additional functionality: it now saves the HTTP status into
618 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
620 * Revision 1.32 2001/10/07 15:43:28 oes
621 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
622 * client_te and client_accept_encoding_adder, triggered by the new
623 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
624 * changed to allow only identity and chunked, and the TE header is
625 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
627 * parse_http_request no longer does anything than parsing. The rewriting
628 * of http->cmd and version mangling are gone. It now also recognizes
629 * the put and delete methods and saves the url in http->url. Removed
632 * renamed content_type and content_length to have the server_ prefix
634 * server_content_type now only works if csp->content_type != CT_TABOO
636 * added server_transfer_encoding, which
637 * - Sets CT_TABOO to prohibit filtering if encoding compresses
638 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
639 * - Change from "chunked" to "identity" if body was chunked
640 * but has been de-chunked for filtering.
642 * added server_content_md5 which crunches any Content-MD5 headers
643 * if the body was modified.
645 * made server_http11 conditional on +downgrade action
647 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
649 * Revision 1.31 2001/10/05 14:25:02 oes
650 * Crumble Keep-Alive from Server
652 * Revision 1.30 2001/09/29 12:56:03 joergs
653 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
655 * Revision 1.29 2001/09/24 21:09:24 jongfoster
656 * Fixing 2 memory leaks that Guy spotted, where the paramater to
657 * enlist() was not being free()d.
659 * Revision 1.28 2001/09/22 16:32:28 jongfoster
660 * Removing unused #includes.
662 * Revision 1.27 2001/09/20 15:45:25 steudten
664 * add casting from size_t to int for printf()
665 * remove local variable shadow s2
667 * Revision 1.26 2001/09/16 17:05:14 jongfoster
668 * Removing unused #include showarg.h
670 * Revision 1.25 2001/09/16 13:21:27 jongfoster
671 * Changes to use new list functions.
673 * Revision 1.24 2001/09/13 23:05:50 jongfoster
674 * Changing the string paramater to the header parsers a "const".
676 * Revision 1.23 2001/09/12 18:08:19 steudten
678 * In parse_http_request() header rewriting miss the host value, so
679 * from http://www.mydomain.com the result was just " / " not
680 * http://www.mydomain.com/ in case we forward.
682 * Revision 1.22 2001/09/10 10:58:53 oes
683 * Silenced compiler warnings
685 * Revision 1.21 2001/07/31 14:46:00 oes
686 * - Persistant connections now suppressed
687 * - sed() no longer appends empty header to csp->headers
689 * Revision 1.20 2001/07/30 22:08:36 jongfoster
690 * Tidying up #defines:
691 * - All feature #defines are now of the form FEATURE_xxx
692 * - Permanently turned off WIN_GUI_EDIT
693 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
695 * Revision 1.19 2001/07/25 17:21:54 oes
696 * client_uagent now saves copy of User-Agent: header value
698 * Revision 1.18 2001/07/13 14:02:46 oes
699 * - Included fix to repair broken HTTP requests that
700 * don't contain a path, not even '/'.
701 * - Removed all #ifdef PCRS
702 * - content_type now always inspected and classified as
703 * text, gif or other.
704 * - formatting / comments
706 * Revision 1.17 2001/06/29 21:45:41 oes
707 * Indentation, CRLF->LF, Tab-> Space
709 * Revision 1.16 2001/06/29 13:32:42 oes
711 * - Adapted free_http_request
712 * - Removed logentry from cancelled commit
714 * Revision 1.15 2001/06/03 19:12:38 oes
715 * deleted const struct interceptors
717 * Revision 1.14 2001/06/01 18:49:17 jongfoster
718 * Replaced "list_share" with "list" - the tiny memory gain was not
719 * worth the extra complexity.
721 * Revision 1.13 2001/05/31 21:30:33 jongfoster
722 * Removed list code - it's now in list.[ch]
723 * Renamed "permission" to "action", and changed many features
724 * to use the actions file rather than the global config.
726 * Revision 1.12 2001/05/31 17:33:13 oes
730 * Revision 1.11 2001/05/29 20:11:19 joergs
731 * '/ * inside comment' warning removed.
733 * Revision 1.10 2001/05/29 09:50:24 jongfoster
734 * Unified blocklist/imagelist/permissionslist.
735 * File format is still under discussion, but the internal changes
738 * Also modified interceptor behaviour:
739 * - We now intercept all URLs beginning with one of the following
740 * prefixes (and *only* these prefixes):
742 * * http://ijbswa.sf.net/config/
743 * * http://ijbswa.sourceforge.net/config/
744 * - New interceptors "home page" - go to http://i.j.b/ to see it.
745 * - Internal changes so that intercepted and fast redirect pages
746 * are not replaced with an image.
747 * - Interceptors now have the option to send a binary page direct
748 * to the client. (i.e. ijb-send-banner uses this)
749 * - Implemented show-url-info interceptor. (Which is why I needed
750 * the above interceptors changes - a typical URL is
751 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
752 * The previous mechanism would not have intercepted that, and
753 * if it had been intercepted then it then it would have replaced
756 * Revision 1.9 2001/05/28 17:26:33 jongfoster
757 * Fixing segfault if last header was crunched.
758 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
759 * can use the cross-platform sprintf() instead.)
761 * Revision 1.8 2001/05/27 22:17:04 oes
763 * - re_process_buffer no longer writes the modified buffer
764 * to the client, which was very ugly. It now returns the
765 * buffer, which it is then written by chat.
767 * - content_length now adjusts the Content-Length: header
768 * for modified documents rather than crunch()ing it.
769 * (Length info in csp->content_length, which is 0 for
770 * unmodified documents)
772 * - For this to work, sed() is called twice when filtering.
774 * Revision 1.7 2001/05/27 13:19:06 oes
775 * Patched Joergs solution for the content-length in.
777 * Revision 1.6 2001/05/26 13:39:32 jongfoster
778 * Only crunches Content-Length header if applying RE filtering.
779 * Without this fix, Microsoft Windows Update wouldn't work.
781 * Revision 1.5 2001/05/26 00:28:36 jongfoster
782 * Automatic reloading of config file.
783 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
784 * Most of the global variables have been moved to a new
785 * struct configuration_spec, accessed through csp->config->globalname
786 * Most of the globals remaining are used by the Win32 GUI.
788 * Revision 1.4 2001/05/22 18:46:04 oes
790 * - Enabled filtering banners by size rather than URL
791 * by adding patterns that replace all standard banner
792 * sizes with the "Junkbuster" gif to the re_filterfile
794 * - Enabled filtering WebBugs by providing a pattern
795 * which kills all 1x1 images
797 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
798 * which is selected by the (nonstandard and therefore
799 * capital) letter 'U' in the option string.
800 * It causes the quantifiers to be ungreedy by default.
801 * Appending a ? turns back to greedy (!).
803 * - Added a new interceptor ijb-send-banner, which
804 * sends back the "Junkbuster" gif. Without imagelist or
805 * MSIE detection support, or if tinygif = 1, or the
806 * URL isn't recognized as an imageurl, a lame HTML
807 * explanation is sent instead.
809 * - Added new feature, which permits blocking remote
810 * script redirects and firing back a local redirect
812 * The feature is conditionally compiled, i.e. it
813 * can be disabled with --disable-fast-redirects,
814 * plus it must be activated by a "fast-redirects"
815 * line in the config file, has its own log level
816 * and of course wants to be displayed by show-proxy-args
817 * Note: Boy, all the #ifdefs in 1001 locations and
818 * all the fumbling with configure.in and acconfig.h
819 * were *way* more work than the feature itself :-(
821 * - Because a generic redirect template was needed for
822 * this, tinygif = 3 now uses the same.
824 * - Moved GIFs, and other static HTTP response templates
829 * - Removed some >400 CRs again (Jon, you really worked
832 * Revision 1.3 2001/05/20 01:21:20 jongfoster
833 * Version 2.9.4 checkin.
834 * - Merged popupfile and cookiefile, and added control over PCRS
835 * filtering, in new "permissionsfile".
836 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
837 * file error you now get a message box (in the Win32 GUI) rather
838 * than the program exiting with no explanation.
839 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
841 * - Removed tabs from "config"
842 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
843 * - Bumped up version number.
845 * Revision 1.2 2001/05/17 23:02:36 oes
846 * - Made referrer option accept 'L' as a substitute for '§'
848 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
849 * Initial import of version 2.9.3 source tree
852 *********************************************************************/
859 #include <sys/types.h>
869 * Convince GNU's libc to provide a strptime prototype.
872 #endif /*__GLIBC__ */
879 #if !defined(_WIN32) && !defined(__OS2__)
885 #ifdef FEATURE_PTHREAD
887 /* jcc.h is for mutex semapores only */
888 #endif /* def FEATURE_PTHREAD */
893 #include "jbsockets.h"
894 #include "miscutil.h"
899 #ifndef HAVE_STRPTIME
900 #include "strptime.h"
903 const char parsers_h_rcs[] = PARSERS_H_VERSION;
905 /* Fix a problem with Solaris. There should be no effect on other
907 * Solaris's isspace() is a macro which uses its argument directly
908 * as an array index. Therefore we need to make sure that high-bit
909 * characters generate +ve values, and ideally we also want to make
910 * the argument match the declared parameter type of "int".
912 * Why did they write a character function that can't take a simple
913 * "char" argument? Doh!
915 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
916 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
918 static char *get_header_line(struct iob *iob);
919 static jb_err scan_headers(struct client_state *csp);
920 static jb_err header_tagger(struct client_state *csp, char *header);
921 static jb_err parse_header_time(const char *header_time, time_t *result);
923 static jb_err crumble (struct client_state *csp, char **header);
924 static jb_err filter_header (struct client_state *csp, char **header);
925 static jb_err client_connection (struct client_state *csp, char **header);
926 static jb_err client_referrer (struct client_state *csp, char **header);
927 static jb_err client_uagent (struct client_state *csp, char **header);
928 static jb_err client_ua (struct client_state *csp, char **header);
929 static jb_err client_from (struct client_state *csp, char **header);
930 static jb_err client_send_cookie (struct client_state *csp, char **header);
931 static jb_err client_x_forwarded (struct client_state *csp, char **header);
932 static jb_err client_accept_encoding (struct client_state *csp, char **header);
933 static jb_err client_te (struct client_state *csp, char **header);
934 static jb_err client_max_forwards (struct client_state *csp, char **header);
935 static jb_err client_host (struct client_state *csp, char **header);
936 static jb_err client_if_modified_since (struct client_state *csp, char **header);
937 static jb_err client_accept_language (struct client_state *csp, char **header);
938 static jb_err client_if_none_match (struct client_state *csp, char **header);
939 static jb_err crunch_client_header (struct client_state *csp, char **header);
940 static jb_err client_x_filter (struct client_state *csp, char **header);
941 static jb_err client_range (struct client_state *csp, char **header);
942 static jb_err server_set_cookie (struct client_state *csp, char **header);
943 static jb_err server_connection (struct client_state *csp, char **header);
944 static jb_err server_content_type (struct client_state *csp, char **header);
945 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
946 static jb_err server_content_md5 (struct client_state *csp, char **header);
947 static jb_err server_content_encoding (struct client_state *csp, char **header);
948 static jb_err server_transfer_coding (struct client_state *csp, char **header);
949 static jb_err server_http (struct client_state *csp, char **header);
950 static jb_err crunch_server_header (struct client_state *csp, char **header);
951 static jb_err server_last_modified (struct client_state *csp, char **header);
952 static jb_err server_content_disposition(struct client_state *csp, char **header);
954 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
955 static jb_err server_save_content_length(struct client_state *csp, char **header);
956 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
958 static jb_err client_host_adder (struct client_state *csp);
959 static jb_err client_xtra_adder (struct client_state *csp);
960 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
961 static jb_err client_connection_header_adder(struct client_state *csp);
962 static jb_err server_connection_close_adder(struct client_state *csp);
964 static jb_err create_forged_referrer(char **header, const char *hostport);
965 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
966 static jb_err handle_conditional_hide_referrer_parameter(char **header,
967 const char *host, const int parameter_conditional_block);
970 * List of functions to run on a list of headers.
974 /** The header prefix to match */
977 /** The length of the prefix to match */
980 /** The function to apply to this line */
981 const parser_func_ptr parser;
984 static const struct parsers client_patterns[] = {
985 { "referer:", 8, client_referrer },
986 { "user-agent:", 11, client_uagent },
987 { "ua-", 3, client_ua },
988 { "from:", 5, client_from },
989 { "cookie:", 7, client_send_cookie },
990 { "x-forwarded-for:", 16, client_x_forwarded },
991 { "Accept-Encoding:", 16, client_accept_encoding },
992 { "TE:", 3, client_te },
993 { "Host:", 5, client_host },
994 { "if-modified-since:", 18, client_if_modified_since },
995 { "Keep-Alive:", 11, crumble },
996 { "connection:", 11, client_connection },
997 { "proxy-connection:", 17, crumble },
998 { "max-forwards:", 13, client_max_forwards },
999 { "Accept-Language:", 16, client_accept_language },
1000 { "if-none-match:", 14, client_if_none_match },
1001 { "Range:", 6, client_range },
1002 { "Request-Range:", 14, client_range },
1003 { "If-Range:", 9, client_range },
1004 { "X-Filter:", 9, client_x_filter },
1005 { "*", 0, crunch_client_header },
1006 { "*", 0, filter_header },
1010 static const struct parsers server_patterns[] = {
1011 { "HTTP/", 5, server_http },
1012 { "set-cookie:", 11, server_set_cookie },
1013 { "connection:", 11, server_connection },
1014 { "Content-Type:", 13, server_content_type },
1015 { "Content-MD5:", 12, server_content_md5 },
1016 { "Content-Encoding:", 17, server_content_encoding },
1017 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1018 { "Content-Length:", 15, server_save_content_length },
1019 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1020 { "Transfer-Encoding:", 18, server_transfer_coding },
1021 { "Keep-Alive:", 11, crumble },
1022 { "content-disposition:", 20, server_content_disposition },
1023 { "Last-Modified:", 14, server_last_modified },
1024 { "*", 0, crunch_server_header },
1025 { "*", 0, filter_header },
1029 static const add_header_func_ptr add_client_headers[] = {
1031 client_x_forwarded_for_adder,
1033 /* Temporarily disabled: client_accept_encoding_adder, */
1034 client_connection_header_adder,
1038 static const add_header_func_ptr add_server_headers[] = {
1039 server_connection_close_adder,
1043 /*********************************************************************
1045 * Function : flush_socket
1047 * Description : Write any pending "buffered" content.
1050 * 1 : fd = file descriptor of the socket to read
1051 * 2 : iob = The I/O buffer to flush, usually csp->iob.
1053 * Returns : On success, the number of bytes written are returned (zero
1054 * indicates nothing was written). On error, -1 is returned,
1055 * and errno is set appropriately. If count is zero and the
1056 * file descriptor refers to a regular file, 0 will be
1057 * returned without causing any other effect. For a special
1058 * file, the results are not portable.
1060 *********************************************************************/
1061 int flush_socket(jb_socket fd, struct iob *iob)
1063 int len = iob->eod - iob->cur;
1070 if (write_socket(fd, iob->cur, (size_t)len))
1074 iob->eod = iob->cur = iob->buf;
1080 /*********************************************************************
1082 * Function : add_to_iob
1084 * Description : Add content to the buffered page, expanding the
1085 * buffer if necessary.
1088 * 1 : csp = Current client state (buffers, headers, etc...)
1089 * 2 : buf = holds the content to be added to the page
1090 * 3 : n = number of bytes to be added
1092 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1093 * or buffer limit reached.
1095 *********************************************************************/
1096 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1098 struct iob *iob = csp->iob;
1099 size_t used, offset, need, want;
1102 if (n <= 0) return JB_ERR_OK;
1104 used = (size_t)(iob->eod - iob->buf);
1105 offset = (size_t)(iob->cur - iob->buf);
1106 need = used + (size_t)n + 1;
1109 * If the buffer can't hold the new data, extend it first.
1110 * Use the next power of two if possible, else use the actual need.
1112 if (need > csp->config->buffer_limit)
1114 log_error(LOG_LEVEL_INFO,
1115 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
1116 need, csp->config->buffer_limit);
1117 return JB_ERR_MEMORY;
1120 if (need > iob->size)
1122 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1124 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1128 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1134 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1135 return JB_ERR_MEMORY;
1138 /* Update the iob pointers */
1139 iob->cur = p + offset;
1140 iob->eod = p + used;
1144 /* copy the new data into the iob buffer */
1145 memcpy(iob->eod, buf, (size_t)n);
1147 /* point to the end of the data */
1150 /* null terminate == cheap insurance */
1159 /*********************************************************************
1161 * Function : decompress_iob
1163 * Description : Decompress buffered page, expanding the
1164 * buffer as necessary. csp->iob->cur
1165 * should point to the the beginning of the
1166 * compressed data block.
1169 * 1 : csp = Current client state (buffers, headers, etc...)
1171 * Returns : JB_ERR_OK on success,
1172 * JB_ERR_MEMORY if out-of-memory limit reached, and
1173 * JB_ERR_COMPRESS if error decompressing buffer.
1175 *********************************************************************/
1176 jb_err decompress_iob(struct client_state *csp)
1178 char *buf; /* new, uncompressed buffer */
1179 char *cur; /* Current iob position (to keep the original
1180 * iob->cur unmodified if we return early) */
1181 size_t bufsize; /* allocated size of the new buffer */
1182 size_t old_size; /* Content size before decompression */
1183 size_t skip_size; /* Number of bytes at the beginning of the iob
1184 that we should NOT decompress. */
1185 int status; /* return status of the inflate() call */
1186 z_stream zstr; /* used by calls to zlib */
1188 assert(csp->iob->cur - csp->iob->buf > 0);
1189 assert(csp->iob->eod - csp->iob->cur > 0);
1191 bufsize = csp->iob->size;
1192 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1193 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1195 cur = csp->iob->cur;
1200 * This is to protect the parsing of gzipped data,
1201 * but it should(?) be valid for deflated data also.
1203 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1204 return JB_ERR_COMPRESS;
1207 if (csp->content_type & CT_GZIP)
1210 * Our task is slightly complicated by the facts that data
1211 * compressed by gzip does not include a zlib header, and
1212 * that there is no easily accessible interface in zlib to
1213 * handle a gzip header. We strip off the gzip header by
1214 * hand, and later inform zlib not to expect a header.
1218 * Strip off the gzip header. Please see RFC 1952 for more
1219 * explanation of the appropriate fields.
1221 if ((*cur++ != (char)0x1f)
1222 || (*cur++ != (char)0x8b)
1223 || (*cur++ != Z_DEFLATED))
1225 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1226 return JB_ERR_COMPRESS;
1232 * XXX: These magic numbers should be replaced
1233 * with macros to give a better idea what they do.
1237 /* The gzip header has reserved bits set; bail out. */
1238 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1239 return JB_ERR_COMPRESS;
1243 /* Skip extra fields if necessary. */
1247 * Skip a given number of bytes, specified
1248 * as a 16-bit little-endian value.
1251 * XXX: This code used to be:
1253 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1255 * which I had to change into:
1257 * cur += *cur++ + (*cur++ << 8);
1259 * at which point gcc43 finally noticed that the value
1260 * of cur is undefined (it depends on which of the
1261 * summands is evaluated first).
1263 * I haven't come across a site where this
1264 * code is actually executed yet, but I hope
1268 skip_bytes = *cur++;
1269 skip_bytes = *cur++ << 8;
1271 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1274 * The number of bytes to skip should be positive
1275 * and we'd like to stay in the buffer.
1277 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1279 log_error(LOG_LEVEL_ERROR,
1280 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1282 return JB_ERR_COMPRESS;
1284 log_error(LOG_LEVEL_INFO,
1285 "Skipping %d bytes for gzip compression. Does this sound right?",
1290 /* Skip the filename if necessary. */
1293 /* A null-terminated string is supposed to follow. */
1294 while (*cur++ && (cur < csp->iob->eod));
1298 /* Skip the comment if necessary. */
1301 /* A null-terminated string is supposed to follow. */
1302 while (*cur++ && (cur < csp->iob->eod));
1305 /* Skip the CRC if necessary. */
1311 if (cur >= csp->iob->eod)
1314 * If the current position pointer reached or passed
1315 * the buffer end, we were obviously tricked to skip
1318 log_error(LOG_LEVEL_ERROR,
1319 "Malformed gzip header detected. Aborting decompression.");
1320 return JB_ERR_COMPRESS;
1324 else if (csp->content_type & CT_DEFLATE)
1327 * XXX: The debug level should be lowered
1328 * before the next stable release.
1330 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1332 * In theory (that is, according to RFC 1950), deflate-compressed
1333 * data should begin with a two-byte zlib header and have an
1334 * adler32 checksum at the end. It seems that in practice only
1335 * the raw compressed data is sent. Note that this means that
1336 * we are not RFC 1950-compliant here, but the advantage is that
1337 * this actually works. :)
1339 * We add a dummy null byte to tell zlib where the data ends,
1340 * and later inform it not to expect a header.
1342 * Fortunately, add_to_iob() has thoughtfully null-terminated
1343 * the buffer; we can just increment the end pointer to include
1350 log_error(LOG_LEVEL_ERROR,
1351 "Unable to determine compression format for decompression");
1352 return JB_ERR_COMPRESS;
1355 /* Set up the fields required by zlib. */
1356 zstr.next_in = (Bytef *)cur;
1357 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1358 zstr.zalloc = Z_NULL;
1359 zstr.zfree = Z_NULL;
1360 zstr.opaque = Z_NULL;
1363 * Passing -MAX_WBITS to inflateInit2 tells the library
1364 * that there is no zlib header.
1366 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1368 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1369 return JB_ERR_COMPRESS;
1373 * Next, we allocate new storage for the inflated data.
1374 * We don't modify the existing iob yet, so in case there
1375 * is error in decompression we can recover gracefully.
1377 buf = zalloc(bufsize);
1380 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1381 return JB_ERR_MEMORY;
1384 assert(bufsize >= skip_size);
1385 memcpy(buf, csp->iob->buf, skip_size);
1386 zstr.avail_out = bufsize - skip_size;
1387 zstr.next_out = (Bytef *)buf + skip_size;
1389 /* Try to decompress the whole stream in one shot. */
1390 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1392 /* We need to allocate more memory for the output buffer. */
1394 char *tmpbuf; /* used for realloc'ing the buffer */
1395 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1398 * If zlib wants more data then there's a problem, because
1399 * the complete compressed file should have been buffered.
1401 if (0 == zstr.avail_in)
1403 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1404 return JB_ERR_COMPRESS;
1408 * If we tried the limit and still didn't have enough
1409 * memory, just give up.
1411 if (bufsize == csp->config->buffer_limit)
1413 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1414 return JB_ERR_MEMORY;
1417 /* Try doubling the buffer size each time. */
1420 /* Don't exceed the buffer limit. */
1421 if (bufsize > csp->config->buffer_limit)
1423 bufsize = csp->config->buffer_limit;
1426 /* Try to allocate the new buffer. */
1427 tmpbuf = realloc(buf, bufsize);
1430 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1432 return JB_ERR_MEMORY;
1436 char *oldnext_out = (char *)zstr.next_out;
1439 * Update the fields for inflate() to use the new
1440 * buffer, which may be in a location different from
1443 zstr.avail_out += bufsize - oldbufsize;
1444 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1447 * Compare with an uglier method of calculating these values
1448 * that doesn't require the extra oldbufsize variable.
1450 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1451 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1452 assert(zstr.avail_out > 0);
1458 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1460 log_error(LOG_LEVEL_ERROR,
1461 "Inconsistent stream state after decompression: %s", zstr.msg);
1463 * XXX: Intentionally no return.
1465 * According to zlib.h, Z_STREAM_ERROR is returned
1466 * "if the stream state was inconsistent".
1468 * I assume in this case inflate()'s status
1469 * would also be something different than Z_STREAM_END
1470 * so this check should be redundant, but lets see.
1474 if (status != Z_STREAM_END)
1476 /* We failed to decompress the stream. */
1477 log_error(LOG_LEVEL_ERROR,
1478 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1479 return JB_ERR_COMPRESS;
1483 * Finally, we can actually update the iob, since the
1484 * decompression was successful. First, free the old
1487 freez(csp->iob->buf);
1489 /* Now, update the iob to use the new buffer. */
1490 csp->iob->buf = buf;
1491 csp->iob->cur = csp->iob->buf + skip_size;
1492 csp->iob->eod = (char *)zstr.next_out;
1493 csp->iob->size = bufsize;
1496 * Make sure the new uncompressed iob obeys some minimal
1497 * consistency conditions.
1499 if ((csp->iob->buf < csp->iob->cur)
1500 && (csp->iob->cur <= csp->iob->eod)
1501 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1503 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1506 log_error(LOG_LEVEL_RE_FILTER,
1507 "Decompression successful. Old size: %d, new size: %d.",
1508 old_size, new_size);
1512 /* zlib thinks this is OK, so lets do the same. */
1513 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1518 /* It seems that zlib did something weird. */
1519 log_error(LOG_LEVEL_ERROR,
1520 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1521 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1522 csp->iob->eod, csp->iob->buf + csp->iob->size);
1523 return JB_ERR_COMPRESS;
1529 #endif /* defined(FEATURE_ZLIB) */
1532 /*********************************************************************
1534 * Function : string_move
1536 * Description : memmove wrapper to move the last part of a string
1537 * towards the beginning, overwriting the part in
1538 * the middle. strlcpy() can't be used here as the
1542 * 1 : dst = Destination to overwrite
1543 * 2 : src = Source to move.
1547 *********************************************************************/
1548 static void string_move(char *dst, char *src)
1552 /* +1 to copy the terminating nul as well. */
1553 memmove(dst, src, strlen(src)+1);
1557 /*********************************************************************
1559 * Function : normalize_lws
1561 * Description : Reduces unquoted linear white space in headers
1562 * to a single space in accordance with RFC 2616 2.2.
1563 * This simplifies parsing and filtering later on.
1565 * XXX: Remove log messages before
1566 * the next stable release?
1569 * 1 : header = A header with linear white space to reduce.
1573 *********************************************************************/
1574 static void normalize_lws(char *header)
1580 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1584 while (ijb_isspace(*q))
1588 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1589 string_move(p+1, q);
1594 log_error(LOG_LEVEL_HEADER,
1595 "Converting tab to space in '%s'", header);
1600 char *end_of_token = strstr(p+1, "\"");
1602 if (NULL != end_of_token)
1604 /* Don't mess with quoted text. */
1609 log_error(LOG_LEVEL_HEADER,
1610 "Ignoring single quote in '%s'", header);
1616 p = strchr(header, ':');
1617 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1620 * There's still space before the colon.
1623 string_move(p-1, p);
1628 /*********************************************************************
1630 * Function : get_header
1632 * Description : This (odd) routine will parse the csp->iob
1633 * to get the next complete header.
1636 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1638 * Returns : Any one of the following:
1640 * 1) a pointer to a dynamically allocated string that contains a header line
1641 * 2) NULL indicating that the end of the header was reached
1642 * 3) "" indicating that the end of the iob was reached before finding
1643 * a complete header line.
1645 *********************************************************************/
1646 char *get_header(struct iob *iob)
1650 header = get_header_line(iob);
1652 if ((header == NULL) || (*header == '\0'))
1655 * No complete header read yet, tell the client.
1660 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1663 * Header spans multiple lines, append the next one.
1665 char *continued_header;
1667 continued_header = get_header_line(iob);
1668 if ((continued_header == NULL) || (*continued_header == '\0'))
1671 * No complete header read yet, return what we got.
1672 * XXX: Should "unread" header instead.
1674 log_error(LOG_LEVEL_INFO,
1675 "Failed to read a multi-line header properly: '%s'",
1680 if (JB_ERR_OK != string_join(&header, continued_header))
1682 log_error(LOG_LEVEL_FATAL,
1683 "Out of memory while appending multiple headers.");
1687 /* XXX: remove before next stable release. */
1688 log_error(LOG_LEVEL_HEADER,
1689 "Merged multiple header lines to: '%s'",
1694 normalize_lws(header);
1701 /*********************************************************************
1703 * Function : get_header_line
1705 * Description : This (odd) routine will parse the csp->iob
1706 * to get the next header line.
1709 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1711 * Returns : Any one of the following:
1713 * 1) a pointer to a dynamically allocated string that contains a header line
1714 * 2) NULL indicating that the end of the header was reached
1715 * 3) "" indicating that the end of the iob was reached before finding
1716 * a complete header line.
1718 *********************************************************************/
1719 static char *get_header_line(struct iob *iob)
1723 if ((iob->cur == NULL)
1724 || ((p = strchr(iob->cur, '\n')) == NULL))
1726 return(""); /* couldn't find a complete header */
1731 ret = strdup(iob->cur);
1734 /* FIXME No way to handle error properly */
1735 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1740 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1742 /* is this a blank line (i.e. the end of the header) ? */
1754 /*********************************************************************
1756 * Function : get_header_value
1758 * Description : Get the value of a given header from a chained list
1759 * of header lines or return NULL if no such header is
1760 * present in the list.
1763 * 1 : header_list = pointer to list
1764 * 2 : header_name = string with name of header to look for.
1765 * Trailing colon required, capitalization
1768 * Returns : NULL if not found, else value of header
1770 *********************************************************************/
1771 char *get_header_value(const struct list *header_list, const char *header_name)
1773 struct list_entry *cur_entry;
1777 assert(header_list);
1778 assert(header_name);
1779 length = strlen(header_name);
1781 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1785 if (!strncmpic(cur_entry->str, header_name, length))
1788 * Found: return pointer to start of value
1790 ret = cur_entry->str + length;
1791 while (*ret && ijb_isspace(*ret)) ret++;
1805 /*********************************************************************
1807 * Function : scan_headers
1809 * Description : Scans headers, applies tags and updates action bits.
1812 * 1 : csp = Current client state (buffers, headers, etc...)
1814 * Returns : JB_ERR_OK
1816 *********************************************************************/
1817 static jb_err scan_headers(struct client_state *csp)
1819 struct list_entry *h; /* Header */
1820 jb_err err = JB_ERR_OK;
1822 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1824 /* Header crunch()ed in previous run? -> ignore */
1825 if (h->str == NULL) continue;
1826 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1827 err = header_tagger(csp, h->str);
1834 /*********************************************************************
1838 * Description : add, delete or modify lines in the HTTP header streams.
1839 * On entry, it receives a linked list of headers space
1840 * that was allocated dynamically (both the list nodes
1841 * and the header contents).
1843 * As a side effect it frees the space used by the original
1847 * 1 : csp = Current client state (buffers, headers, etc...)
1848 * 2 : filter_server_headers = Boolean to switch between
1849 * server and header filtering.
1851 * Returns : JB_ERR_OK in case off success, or
1852 * JB_ERR_MEMORY on out-of-memory error.
1854 *********************************************************************/
1855 jb_err sed(struct client_state *csp, int filter_server_headers)
1857 /* XXX: use more descriptive names. */
1858 struct list_entry *p;
1859 const struct parsers *v;
1860 const add_header_func_ptr *f;
1861 jb_err err = JB_ERR_OK;
1863 if (filter_server_headers)
1865 v = server_patterns;
1866 f = add_server_headers;
1870 v = client_patterns;
1871 f = add_client_headers;
1876 while ((err == JB_ERR_OK) && (v->str != NULL))
1878 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1880 /* Header crunch()ed in previous run? -> ignore */
1881 if (p->str == NULL) continue;
1883 /* Does the current parser handle this header? */
1884 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1885 (v->len == CHECK_EVERY_HEADER_REMAINING))
1887 err = v->parser(csp, &(p->str));
1893 /* place additional headers on the csp->headers list */
1894 while ((err == JB_ERR_OK) && (*f))
1904 /*********************************************************************
1906 * Function : update_server_headers
1908 * Description : Updates server headers after the body has been modified.
1911 * 1 : csp = Current client state (buffers, headers, etc...)
1913 * Returns : JB_ERR_OK in case off success, or
1914 * JB_ERR_MEMORY on out-of-memory error.
1916 *********************************************************************/
1917 jb_err update_server_headers(struct client_state *csp)
1919 jb_err err = JB_ERR_OK;
1921 static const struct parsers server_patterns_light[] = {
1922 { "Content-Length:", 15, server_adjust_content_length },
1923 { "Transfer-Encoding:", 18, server_transfer_coding },
1925 { "Content-Encoding:", 17, server_content_encoding },
1926 #endif /* def FEATURE_ZLIB */
1930 if (strncmpic(csp->http->cmd, "HEAD", 4))
1932 const struct parsers *v;
1933 struct list_entry *p;
1935 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1937 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1939 /* Header crunch()ed in previous run? -> ignore */
1940 if (p->str == NULL) continue;
1942 /* Does the current parser handle this header? */
1943 if (strncmpic(p->str, v->str, v->len) == 0)
1945 err = v->parser(csp, (char **)&(p->str));
1955 /*********************************************************************
1957 * Function : header_tagger
1959 * Description : Executes all text substitutions from applying
1960 * tag actions and saves the result as tag.
1962 * XXX: Shares enough code with filter_header() and
1963 * pcrs_filter_response() to warrant some helper functions.
1966 * 1 : csp = Current client state (buffers, headers, etc...)
1967 * 2 : header = Header that is used as tagger input
1969 * Returns : JB_ERR_OK on success and always succeeds
1971 *********************************************************************/
1972 static jb_err header_tagger(struct client_state *csp, char *header)
1974 int wanted_filter_type;
1975 int multi_action_index;
1979 struct file_list *fl;
1980 struct re_filterfile_spec *b;
1981 struct list_entry *tag_name;
1983 int found_filters = 0;
1984 const size_t header_length = strlen(header);
1986 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1988 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1989 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1993 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1994 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1997 /* Check if there are any filters */
1998 for (i = 0; i < MAX_AF_FILES; i++)
2011 if (0 == found_filters)
2013 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2014 "tagging enabled, but no taggers available.");
2018 for (i = 0; i < MAX_AF_FILES; i++)
2021 if ((NULL == fl) || (NULL == fl->f))
2024 * Either there are no filter files
2025 * left, or this filter file just
2026 * contains no valid filters.
2028 * Continue to be sure we don't miss
2029 * valid filter files that are chained
2030 * after empty or invalid ones.
2035 /* For all filters, */
2036 for (b = fl->f; b; b = b->next)
2038 if (b->type != wanted_filter_type)
2040 /* skip the ones we don't care about, */
2043 /* leaving only taggers that could apply, of which we use the ones, */
2044 for (tag_name = csp->action->multi[multi_action_index]->first;
2045 NULL != tag_name; tag_name = tag_name->next)
2047 /* that do apply, and */
2048 if (strcmp(b->name, tag_name->str) == 0)
2050 char *modified_tag = NULL;
2052 size_t size = header_length;
2053 pcrs_job *joblist = b->joblist;
2055 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2057 if (NULL == joblist)
2059 log_error(LOG_LEVEL_RE_FILTER,
2060 "Tagger %s has empty joblist. Nothing to do.", b->name);
2064 /* execute their pcrs_joblist on the header. */
2065 for (job = joblist; NULL != job; job = job->next)
2067 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2071 /* Success, continue with the modified version. */
2080 /* Tagger doesn't match */
2083 /* Regex failure, log it but continue anyway. */
2084 log_error(LOG_LEVEL_ERROR,
2085 "Problems with tagger \'%s\' and header \'%s\': %s",
2086 b->name, *header, pcrs_strerror(hits));
2088 freez(modified_tag);
2092 if (b->dynamic) pcrs_free_joblist(joblist);
2094 /* If this tagger matched */
2100 * There is to technical limitation which makes
2101 * it impossible to use empty tags, but I assume
2102 * no one would do it intentionally.
2105 log_error(LOG_LEVEL_INFO,
2106 "Tagger \'%s\' created an empty tag. Ignored.",
2111 if (!list_contains_item(csp->tags, tag))
2113 if (JB_ERR_OK != enlist(csp->tags, tag))
2115 log_error(LOG_LEVEL_ERROR,
2116 "Insufficient memory to add tag \'%s\', "
2117 "based on tagger \'%s\' and header \'%s\'",
2118 tag, b->name, *header);
2122 char *action_message;
2124 * update the action bits right away, to make
2125 * tagging based on tags set by earlier taggers
2126 * of the same kind possible.
2128 if (update_action_bits_for_tag(csp, tag))
2130 action_message = "Action bits updated accordingly.";
2134 action_message = "No action bits update necessary.";
2137 log_error(LOG_LEVEL_HEADER,
2138 "Tagger \'%s\' added tag \'%s\'. %s",
2139 b->name, tag, action_message);
2144 /* XXX: Is this log-worthy? */
2145 log_error(LOG_LEVEL_HEADER,
2146 "Tagger \'%s\' didn't add tag \'%s\'. "
2147 "Tag already present", b->name, tag);
2150 } /* if the tagger matched */
2151 } /* if the tagger applies */
2152 } /* for every tagger that could apply */
2153 } /* for all filters */
2154 } /* for all filter files */
2159 /* here begins the family of parser functions that reformat header lines */
2161 /*********************************************************************
2163 * Function : filter_header
2165 * Description : Executes all text substitutions from all applying
2166 * +(server|client)-header-filter actions on the header.
2167 * Most of the code was copied from pcrs_filter_response,
2168 * including the rather short variable names
2171 * 1 : csp = Current client state (buffers, headers, etc...)
2172 * 2 : header = On input, pointer to header to modify.
2173 * On output, pointer to the modified header, or NULL
2174 * to remove the header. This function frees the
2175 * original string if necessary.
2177 * Returns : JB_ERR_OK on success and always succeeds
2179 *********************************************************************/
2180 static jb_err filter_header(struct client_state *csp, char **header)
2184 size_t size = strlen(*header);
2186 char *newheader = NULL;
2189 struct file_list *fl;
2190 struct re_filterfile_spec *b;
2191 struct list_entry *filtername;
2193 int i, found_filters = 0;
2194 int wanted_filter_type;
2195 int multi_action_index;
2197 if (csp->flags & CSP_FLAG_NO_FILTERING)
2202 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2204 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2205 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2209 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2210 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2214 * Need to check the set of re_filterfiles...
2216 for (i = 0; i < MAX_AF_FILES; i++)
2229 if (0 == found_filters)
2231 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2232 "header filtering enabled, but no matching filters available.");
2236 for (i = 0; i < MAX_AF_FILES; i++)
2239 if ((NULL == fl) || (NULL == fl->f))
2242 * Either there are no filter files
2243 * left, or this filter file just
2244 * contains no valid filters.
2246 * Continue to be sure we don't miss
2247 * valid filter files that are chained
2248 * after empty or invalid ones.
2253 * For all applying +filter actions, look if a filter by that
2254 * name exists and if yes, execute its pcrs_joblist on the
2257 for (b = fl->f; b; b = b->next)
2259 if (b->type != wanted_filter_type)
2261 /* Skip other filter types */
2265 for (filtername = csp->action->multi[multi_action_index]->first;
2266 filtername ; filtername = filtername->next)
2268 if (strcmp(b->name, filtername->str) == 0)
2270 int current_hits = 0;
2271 pcrs_job *joblist = b->joblist;
2273 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2275 if (NULL == joblist)
2277 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2281 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2282 *header, size, b->name);
2284 /* Apply all jobs from the joblist */
2285 for (job = joblist; NULL != job; job = job->next)
2287 matches = pcrs_execute(job, *header, size, &newheader, &size);
2290 current_hits += matches;
2291 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2293 *header = newheader;
2295 else if ( 0 == matches )
2297 /* Filter doesn't change header */
2303 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2304 *header, b->name, pcrs_strerror(matches));
2305 if (newheader != NULL)
2307 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2313 if (b->dynamic) pcrs_free_joblist(joblist);
2315 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2316 hits += current_hits;
2323 * Additionally checking for hits is important because if
2324 * the continue hack is triggered, server headers can
2325 * arrive empty to separate multiple heads from each other.
2327 if ((0 == size) && hits)
2329 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2337 /*********************************************************************
2339 * Function : server_connection
2341 * Description : Makes sure that the value of the Connection: header
2342 * is "close" and signals server_connection_close_adder
2346 * 1 : csp = Current client state (buffers, headers, etc...)
2347 * 2 : header = On input, pointer to header to modify.
2348 * On output, pointer to the modified header, or NULL
2349 * to remove the header. This function frees the
2350 * original string if necessary.
2352 * Returns : JB_ERR_OK on success, or
2353 * JB_ERR_MEMORY on out-of-memory error.
2355 *********************************************************************/
2356 static jb_err server_connection(struct client_state *csp, char **header)
2358 char *old_header = *header;
2360 /* Do we have a 'Connection: close' header? */
2361 if (strcmpic(*header, "Connection: close"))
2363 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2364 if (!strcmpic(*header, "Connection: keep-alive"))
2366 /* Remember to keep the connection alive. */
2367 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
2369 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2371 *header = strdup("Connection: close");
2374 return JB_ERR_MEMORY;
2376 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2380 /* Signal server_connection_close_adder() to return early. */
2381 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2386 /*********************************************************************
2388 * Function : client_connection
2390 * Description : Makes sure a proper "Connection:" header is
2391 * set and signals connection_header_adder
2395 * 1 : csp = Current client state (buffers, headers, etc...)
2396 * 2 : header = On input, pointer to header to modify.
2397 * On output, pointer to the modified header, or NULL
2398 * to remove the header. This function frees the
2399 * original string if necessary.
2401 * Returns : JB_ERR_OK on success, or
2402 * JB_ERR_MEMORY on out-of-memory error.
2404 *********************************************************************/
2405 static jb_err client_connection(struct client_state *csp, char **header)
2407 char *old_header = *header;
2408 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2409 static const char wanted_header[] = "Connection: keep-alive";
2411 static const char wanted_header[] = "Connection: close";
2412 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2414 if (strcmpic(*header, wanted_header))
2416 *header = strdup(wanted_header);
2419 return JB_ERR_MEMORY;
2421 log_error(LOG_LEVEL_HEADER,
2422 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2426 /* Signal client_connection_close_adder() to return early. */
2427 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2433 /*********************************************************************
2435 * Function : crumble
2437 * Description : This is called if a header matches a pattern to "crunch"
2440 * 1 : csp = Current client state (buffers, headers, etc...)
2441 * 2 : header = On input, pointer to header to modify.
2442 * On output, pointer to the modified header, or NULL
2443 * to remove the header. This function frees the
2444 * original string if necessary.
2446 * Returns : JB_ERR_OK on success, or
2447 * JB_ERR_MEMORY on out-of-memory error.
2449 *********************************************************************/
2450 static jb_err crumble(struct client_state *csp, char **header)
2452 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2458 /*********************************************************************
2460 * Function : crunch_server_header
2462 * Description : Crunch server header if it matches a string supplied by the
2463 * user. Called from `sed'.
2466 * 1 : csp = Current client state (buffers, headers, etc...)
2467 * 2 : header = On input, pointer to header to modify.
2468 * On output, pointer to the modified header, or NULL
2469 * to remove the header. This function frees the
2470 * original string if necessary.
2472 * Returns : JB_ERR_OK on success and always succeeds
2474 *********************************************************************/
2475 static jb_err crunch_server_header(struct client_state *csp, char **header)
2477 const char *crunch_pattern;
2479 /* Do we feel like crunching? */
2480 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2482 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2484 /* Is the current header the lucky one? */
2485 if (strstr(*header, crunch_pattern))
2487 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2496 /*********************************************************************
2498 * Function : server_content_type
2500 * Description : Set the content-type for filterable types (text/.*,
2501 * .*xml.*, javascript and image/gif) unless filtering has been
2502 * forbidden (CT_TABOO) while parsing earlier headers.
2503 * NOTE: Since text/plain is commonly used by web servers
2504 * for files whose correct type is unknown, we don't
2505 * set CT_TEXT for it.
2508 * 1 : csp = Current client state (buffers, headers, etc...)
2509 * 2 : header = On input, pointer to header to modify.
2510 * On output, pointer to the modified header, or NULL
2511 * to remove the header. This function frees the
2512 * original string if necessary.
2514 * Returns : JB_ERR_OK on success, or
2515 * JB_ERR_MEMORY on out-of-memory error.
2517 *********************************************************************/
2518 static jb_err server_content_type(struct client_state *csp, char **header)
2520 /* Remove header if it isn't the first Content-Type header */
2521 if ((csp->content_type & CT_DECLARED))
2524 * Another, slightly slower, way to see if
2525 * we already parsed another Content-Type header.
2527 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2529 log_error(LOG_LEVEL_ERROR,
2530 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2538 * Signal that the Content-Type has been set.
2540 csp->content_type |= CT_DECLARED;
2542 if (!(csp->content_type & CT_TABOO))
2545 * XXX: The assumption that text/plain is a sign of
2546 * binary data seems to be somewhat unreasonable nowadays
2547 * and should be dropped after 3.0.8 is out.
2549 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2550 || strstr(*header, "xml")
2551 || strstr(*header, "application/x-javascript"))
2553 csp->content_type |= CT_TEXT;
2555 else if (strstr(*header, "image/gif"))
2557 csp->content_type |= CT_GIF;
2562 * Are we messing with the content type?
2564 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2567 * Make sure the user doesn't accidently
2568 * change the content type of binary documents.
2570 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2573 *header = strdup("Content-Type: ");
2574 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2578 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2579 return JB_ERR_MEMORY;
2581 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2585 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2586 "It doesn't look like a content type that should be filtered. "
2587 "Enable force-text-mode if you know what you're doing.", *header);
2595 /*********************************************************************
2597 * Function : server_transfer_coding
2599 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2600 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2601 * - Remove header if body was chunked but has been
2602 * de-chunked for filtering.
2605 * 1 : csp = Current client state (buffers, headers, etc...)
2606 * 2 : header = On input, pointer to header to modify.
2607 * On output, pointer to the modified header, or NULL
2608 * to remove the header. This function frees the
2609 * original string if necessary.
2611 * Returns : JB_ERR_OK on success, or
2612 * JB_ERR_MEMORY on out-of-memory error.
2614 *********************************************************************/
2615 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2618 * Turn off pcrs and gif filtering if body compressed
2620 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2624 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2626 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2627 csp->http->cmd, *header);
2628 #endif /* def FEATURE_ZLIB */
2629 csp->content_type = CT_TABOO;
2633 * Raise flag if body chunked
2635 if (strstr(*header, "chunked"))
2637 csp->flags |= CSP_FLAG_CHUNKED;
2640 * If the body was modified, it has been de-chunked first
2641 * and the header must be removed.
2643 * FIXME: If there is more than one transfer encoding,
2644 * only the "chunked" part should be removed here.
2646 if (csp->flags & CSP_FLAG_MODIFIED)
2648 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2657 /*********************************************************************
2659 * Function : server_content_encoding
2661 * Description : This function is run twice for each request,
2662 * unless FEATURE_ZLIB and filtering are disabled.
2664 * The first run is used to check if the content
2665 * is compressed, if FEATURE_ZLIB is disabled
2666 * filtering is then disabled as well, if FEATURE_ZLIB
2667 * is enabled the content is marked for decompression.
2669 * The second run is used to remove the Content-Encoding
2670 * header if the decompression was successful.
2673 * 1 : csp = Current client state (buffers, headers, etc...)
2674 * 2 : header = On input, pointer to header to modify.
2675 * On output, pointer to the modified header, or NULL
2676 * to remove the header. This function frees the
2677 * original string if necessary.
2679 * Returns : JB_ERR_OK on success, or
2680 * JB_ERR_MEMORY on out-of-memory error.
2682 *********************************************************************/
2683 static jb_err server_content_encoding(struct client_state *csp, char **header)
2686 if ((csp->flags & CSP_FLAG_MODIFIED)
2687 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2690 * We successfully decompressed the content,
2691 * and have to clean the header now, so the
2692 * client no longer expects compressed data..
2694 * XXX: There is a difference between cleaning
2695 * and removing it completely.
2697 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2700 else if (strstr(*header, "gzip"))
2702 /* Mark for gzip decompression */
2703 csp->content_type |= CT_GZIP;
2705 else if (strstr(*header, "deflate"))
2707 /* Mark for zlib decompression */
2708 csp->content_type |= CT_DEFLATE;
2710 else if (strstr(*header, "compress"))
2713 * We can't decompress this; therefore we can't filter
2716 csp->content_type |= CT_TABOO;
2718 #else /* !defined(FEATURE_ZLIB) */
2719 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2722 * Body is compressed, turn off pcrs and gif filtering.
2724 csp->content_type |= CT_TABOO;
2727 * Log a warning if the user expects the content to be filtered.
2729 if ((csp->rlist != NULL) &&
2730 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2732 log_error(LOG_LEVEL_INFO,
2733 "Compressed content detected, content filtering disabled. "
2734 "Consider recompiling Privoxy with zlib support or "
2735 "enable the prevent-compression action.");
2738 #endif /* defined(FEATURE_ZLIB) */
2745 /*********************************************************************
2747 * Function : server_adjust_content_length
2749 * Description : Adjust Content-Length header if we modified
2753 * 1 : csp = Current client state (buffers, headers, etc...)
2754 * 2 : header = On input, pointer to header to modify.
2755 * On output, pointer to the modified header, or NULL
2756 * to remove the header. This function frees the
2757 * original string if necessary.
2759 * Returns : JB_ERR_OK on success, or
2760 * JB_ERR_MEMORY on out-of-memory error.
2762 *********************************************************************/
2763 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2765 const size_t max_header_length = 80;
2767 /* Regenerate header if the content was modified. */
2768 if (csp->flags & CSP_FLAG_MODIFIED)
2771 *header = (char *) zalloc(max_header_length);
2772 if (*header == NULL)
2774 return JB_ERR_MEMORY;
2777 snprintf(*header, max_header_length, "Content-Length: %d",
2778 (int)csp->content_length);
2779 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2780 (int)csp->content_length);
2787 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2788 /*********************************************************************
2790 * Function : server_save_content_length
2792 * Description : Save the Content-Length sent by the server.
2795 * 1 : csp = Current client state (buffers, headers, etc...)
2796 * 2 : header = On input, pointer to header to modify.
2797 * On output, pointer to the modified header, or NULL
2798 * to remove the header. This function frees the
2799 * original string if necessary.
2801 * Returns : JB_ERR_OK on success, or
2802 * JB_ERR_MEMORY on out-of-memory error.
2804 *********************************************************************/
2805 static jb_err server_save_content_length(struct client_state *csp, char **header)
2807 unsigned int content_length = 0;
2809 assert(*(*header+14) == ':');
2811 if (1 != sscanf(*header+14, ": %u", &content_length))
2813 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2818 csp->expected_content_length = content_length;
2819 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2824 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2827 /*********************************************************************
2829 * Function : server_content_md5
2831 * Description : Crumble any Content-MD5 headers if the document was
2832 * modified. FIXME: Should we re-compute instead?
2835 * 1 : csp = Current client state (buffers, headers, etc...)
2836 * 2 : header = On input, pointer to header to modify.
2837 * On output, pointer to the modified header, or NULL
2838 * to remove the header. This function frees the
2839 * original string if necessary.
2841 * Returns : JB_ERR_OK on success, or
2842 * JB_ERR_MEMORY on out-of-memory error.
2844 *********************************************************************/
2845 static jb_err server_content_md5(struct client_state *csp, char **header)
2847 if (csp->flags & CSP_FLAG_MODIFIED)
2849 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2857 /*********************************************************************
2859 * Function : server_content_disposition
2861 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2862 * Called from `sed'.
2865 * 1 : csp = Current client state (buffers, headers, etc...)
2866 * 2 : header = On input, pointer to header to modify.
2867 * On output, pointer to the modified header, or NULL
2868 * to remove the header. This function frees the
2869 * original string if necessary.
2871 * Returns : JB_ERR_OK on success, or
2872 * JB_ERR_MEMORY on out-of-memory error.
2874 *********************************************************************/
2875 static jb_err server_content_disposition(struct client_state *csp, char **header)
2880 * Are we messing with the Content-Disposition header?
2882 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2888 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2890 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2893 * Blocking content-disposition header
2895 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2902 * Replacing Content-Disposition header
2905 *header = strdup("Content-Disposition: ");
2906 string_append(header, newval);
2908 if (*header != NULL)
2910 log_error(LOG_LEVEL_HEADER,
2911 "Content-Disposition header crunched and replaced with: %s", *header);
2914 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2918 /*********************************************************************
2920 * Function : server_last_modified
2922 * Description : Changes Last-Modified header to the actual date
2923 * to help hide-if-modified-since.
2924 * Called from `sed'.
2927 * 1 : csp = Current client state (buffers, headers, etc...)
2928 * 2 : header = On input, pointer to header to modify.
2929 * On output, pointer to the modified header, or NULL
2930 * to remove the header. This function frees the
2931 * original string if necessary.
2933 * Returns : JB_ERR_OK on success, or
2934 * JB_ERR_MEMORY on out-of-memory error.
2936 *********************************************************************/
2937 static jb_err server_last_modified(struct client_state *csp, char **header)
2940 char buf[BUFFER_SIZE];
2943 #ifdef HAVE_GMTIME_R
2946 struct tm *timeptr = NULL;
2947 time_t now, last_modified;
2949 long int days, hours, minutes, seconds;
2952 * Are we messing with the Last-Modified header?
2954 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2960 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2962 if (0 == strcmpic(newval, "block") )
2965 * Blocking Last-Modified header. Useless but why not.
2967 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2971 else if (0 == strcmpic(newval, "reset-to-request-time"))
2974 * Setting Last-Modified Header to now.
2976 get_http_time(0, buf, sizeof(buf));
2978 *header = strdup("Last-Modified: ");
2979 string_append(header, buf);
2981 if (*header == NULL)
2983 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2987 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2990 else if (0 == strcmpic(newval, "randomize"))
2992 const char *header_time = *header + sizeof("Last-Modified:");
2994 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2996 #ifdef HAVE_GMTIME_R
2997 timeptr = gmtime_r(&now, &gmt);
2998 #elif FEATURE_PTHREAD
2999 privoxy_mutex_lock(&gmtime_mutex);
3000 timeptr = gmtime(&now);
3001 privoxy_mutex_unlock(&gmtime_mutex);
3003 timeptr = gmtime(&now);
3005 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
3007 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3012 rtime = (long int)difftime(now, last_modified);
3021 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
3023 rtime = pick_from_range(rtime);
3024 if (negative) rtime *= -1;
3025 last_modified += rtime;
3026 #ifdef HAVE_GMTIME_R
3027 timeptr = gmtime_r(&last_modified, &gmt);
3028 #elif FEATURE_PTHREAD
3029 privoxy_mutex_lock(&gmtime_mutex);
3030 timeptr = gmtime(&last_modified);
3031 privoxy_mutex_unlock(&gmtime_mutex);
3033 timeptr = gmtime(&last_modified);
3035 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3037 *header = strdup("Last-Modified: ");
3038 string_append(header, newheader);
3040 if (*header == NULL)
3042 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
3043 return JB_ERR_MEMORY;
3046 days = rtime / (3600 * 24);
3047 hours = rtime / 3600 % 24;
3048 minutes = rtime / 60 % 60;
3049 seconds = rtime % 60;
3051 log_error(LOG_LEVEL_HEADER,
3052 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
3053 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
3054 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3058 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
3067 /*********************************************************************
3069 * Function : client_accept_encoding
3071 * Description : Rewrite the client's Accept-Encoding header so that
3072 * if doesn't allow compression, if the action applies.
3073 * Note: For HTTP/1.0 the absence of the header is enough.
3076 * 1 : csp = Current client state (buffers, headers, etc...)
3077 * 2 : header = On input, pointer to header to modify.
3078 * On output, pointer to the modified header, or NULL
3079 * to remove the header. This function frees the
3080 * original string if necessary.
3082 * Returns : JB_ERR_OK on success, or
3083 * JB_ERR_MEMORY on out-of-memory error.
3085 *********************************************************************/
3086 static jb_err client_accept_encoding(struct client_state *csp, char **header)
3088 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3090 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
3094 /* Temporarily disable the correct behaviour to
3095 * work around a PHP bug.
3097 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
3099 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
3100 * if (*header == NULL)
3102 * return JB_ERR_MEMORY;
3113 /*********************************************************************
3115 * Function : client_te
3117 * Description : Rewrite the client's TE header so that
3118 * if doesn't allow compression, if the action applies.
3121 * 1 : csp = Current client state (buffers, headers, etc...)
3122 * 2 : header = On input, pointer to header to modify.
3123 * On output, pointer to the modified header, or NULL
3124 * to remove the header. This function frees the
3125 * original string if necessary.
3127 * Returns : JB_ERR_OK on success, or
3128 * JB_ERR_MEMORY on out-of-memory error.
3130 *********************************************************************/
3131 static jb_err client_te(struct client_state *csp, char **header)
3133 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3136 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3143 /*********************************************************************
3145 * Function : client_referrer
3147 * Description : Handle the "referer" config setting properly.
3148 * Called from `sed'.
3151 * 1 : csp = Current client state (buffers, headers, etc...)
3152 * 2 : header = On input, pointer to header to modify.
3153 * On output, pointer to the modified header, or NULL
3154 * to remove the header. This function frees the
3155 * original string if necessary.
3157 * Returns : JB_ERR_OK on success, or
3158 * JB_ERR_MEMORY on out-of-memory error.
3160 *********************************************************************/
3161 static jb_err client_referrer(struct client_state *csp, char **header)
3163 const char *parameter;
3164 /* booleans for parameters we have to check multiple times */
3165 int parameter_conditional_block;
3166 int parameter_conditional_forge;
3168 #ifdef FEATURE_FORCE_LOAD
3170 * Since the referrer can include the prefix even
3171 * if the request itself is non-forced, we must
3172 * clean it unconditionally.
3174 * XXX: strclean is too broad
3176 strclean(*header, FORCE_PREFIX);
3177 #endif /* def FEATURE_FORCE_LOAD */
3179 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3181 /* Nothing left to do */
3185 parameter = csp->action->string[ACTION_STRING_REFERER];
3186 assert(parameter != NULL);
3187 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3188 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3190 if (!parameter_conditional_block && !parameter_conditional_forge)
3193 * As conditional-block and conditional-forge are the only
3194 * parameters that rely on the original referrer, we can
3195 * remove it now for all the others.
3200 if (0 == strcmpic(parameter, "block"))
3202 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3205 else if (parameter_conditional_block || parameter_conditional_forge)
3207 return handle_conditional_hide_referrer_parameter(header,
3208 csp->http->hostport, parameter_conditional_block);
3210 else if (0 == strcmpic(parameter, "forge"))
3212 return create_forged_referrer(header, csp->http->hostport);
3216 /* interpret parameter as user-supplied referer to fake */
3217 return create_fake_referrer(header, parameter);
3222 /*********************************************************************
3224 * Function : client_accept_language
3226 * Description : Handle the "Accept-Language" config setting properly.
3227 * Called from `sed'.
3230 * 1 : csp = Current client state (buffers, headers, etc...)
3231 * 2 : header = On input, pointer to header to modify.
3232 * On output, pointer to the modified header, or NULL
3233 * to remove the header. This function frees the
3234 * original string if necessary.
3236 * Returns : JB_ERR_OK on success, or
3237 * JB_ERR_MEMORY on out-of-memory error.
3239 *********************************************************************/
3240 static jb_err client_accept_language(struct client_state *csp, char **header)
3245 * Are we messing with the Accept-Language?
3247 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3249 /*I don't think so*/
3253 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3255 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3258 * Blocking Accept-Language header
3260 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3267 * Replacing Accept-Language header
3270 *header = strdup("Accept-Language: ");
3271 string_append(header, newval);
3273 if (*header == NULL)
3275 log_error(LOG_LEVEL_ERROR,
3276 "Insufficient memory. Accept-Language header crunched without replacement.");
3280 log_error(LOG_LEVEL_HEADER,
3281 "Accept-Language header crunched and replaced with: %s", *header);
3284 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3288 /*********************************************************************
3290 * Function : crunch_client_header
3292 * Description : Crunch client header if it matches a string supplied by the
3293 * user. Called from `sed'.
3296 * 1 : csp = Current client state (buffers, headers, etc...)
3297 * 2 : header = On input, pointer to header to modify.
3298 * On output, pointer to the modified header, or NULL
3299 * to remove the header. This function frees the
3300 * original string if necessary.
3302 * Returns : JB_ERR_OK on success and always succeeds
3304 *********************************************************************/
3305 static jb_err crunch_client_header(struct client_state *csp, char **header)
3307 const char *crunch_pattern;
3309 /* Do we feel like crunching? */
3310 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3312 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3314 /* Is the current header the lucky one? */
3315 if (strstr(*header, crunch_pattern))
3317 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3325 /*********************************************************************
3327 * Function : client_uagent
3329 * Description : Handle the "user-agent" config setting properly
3330 * and remember its original value to enable browser
3331 * bug workarounds. Called from `sed'.
3334 * 1 : csp = Current client state (buffers, headers, etc...)
3335 * 2 : header = On input, pointer to header to modify.
3336 * On output, pointer to the modified header, or NULL
3337 * to remove the header. This function frees the
3338 * original string if necessary.
3340 * Returns : JB_ERR_OK on success, or
3341 * JB_ERR_MEMORY on out-of-memory error.
3343 *********************************************************************/
3344 static jb_err client_uagent(struct client_state *csp, char **header)
3348 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3353 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3360 *header = strdup("User-Agent: ");
3361 string_append(header, newval);
3363 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3365 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3369 /*********************************************************************
3371 * Function : client_ua
3373 * Description : Handle "ua-" headers properly. Called from `sed'.
3376 * 1 : csp = Current client state (buffers, headers, etc...)
3377 * 2 : header = On input, pointer to header to modify.
3378 * On output, pointer to the modified header, or NULL
3379 * to remove the header. This function frees the
3380 * original string if necessary.
3382 * Returns : JB_ERR_OK on success, or
3383 * JB_ERR_MEMORY on out-of-memory error.
3385 *********************************************************************/
3386 static jb_err client_ua(struct client_state *csp, char **header)
3388 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3390 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3398 /*********************************************************************
3400 * Function : client_from
3402 * Description : Handle the "from" config setting properly.
3403 * Called from `sed'.
3406 * 1 : csp = Current client state (buffers, headers, etc...)
3407 * 2 : header = On input, pointer to header to modify.
3408 * On output, pointer to the modified header, or NULL
3409 * to remove the header. This function frees the
3410 * original string if necessary.
3412 * Returns : JB_ERR_OK on success, or
3413 * JB_ERR_MEMORY on out-of-memory error.
3415 *********************************************************************/
3416 static jb_err client_from(struct client_state *csp, char **header)
3420 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3427 newval = csp->action->string[ACTION_STRING_FROM];
3430 * Are we blocking the e-mail address?
3432 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3434 log_error(LOG_LEVEL_HEADER, "crunched From!");
3438 log_error(LOG_LEVEL_HEADER, " modified");
3440 *header = strdup("From: ");
3441 string_append(header, newval);
3443 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3447 /*********************************************************************
3449 * Function : client_send_cookie
3451 * Description : Crunches the "cookie" header if necessary.
3452 * Called from `sed'.
3454 * XXX: Stupid name, doesn't send squat.
3457 * 1 : csp = Current client state (buffers, headers, etc...)
3458 * 2 : header = On input, pointer to header to modify.
3459 * On output, pointer to the modified header, or NULL
3460 * to remove the header. This function frees the
3461 * original string if necessary.
3463 * Returns : JB_ERR_OK on success, or
3464 * JB_ERR_MEMORY on out-of-memory error.
3466 *********************************************************************/
3467 static jb_err client_send_cookie(struct client_state *csp, char **header)
3469 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3471 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3479 /*********************************************************************
3481 * Function : client_x_forwarded
3483 * Description : Handle the "x-forwarded-for" config setting properly,
3484 * also used in the add_client_headers list. Called from `sed'.
3487 * 1 : csp = Current client state (buffers, headers, etc...)
3488 * 2 : header = On input, pointer to header to modify.
3489 * On output, pointer to the modified header, or NULL
3490 * to remove the header. This function frees the
3491 * original string if necessary.
3493 * Returns : JB_ERR_OK on success, or
3494 * JB_ERR_MEMORY on out-of-memory error.
3496 *********************************************************************/
3497 jb_err client_x_forwarded(struct client_state *csp, char **header)
3499 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3501 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3503 if (0 == strcmpic(parameter, "block"))
3506 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3508 else if (0 == strcmpic(parameter, "add"))
3510 string_append(header, ", ");
3511 string_append(header, csp->ip_addr_str);
3513 if (*header == NULL)
3515 return JB_ERR_MEMORY;
3517 log_error(LOG_LEVEL_HEADER,
3518 "Appended client IP address to %s", *header);
3519 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3523 log_error(LOG_LEVEL_FATAL,
3524 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3532 /*********************************************************************
3534 * Function : client_max_forwards
3536 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3537 * from the value of the Max-Forwards header field.
3540 * 1 : csp = Current client state (buffers, headers, etc...)
3541 * 2 : header = On input, pointer to header to modify.
3542 * On output, pointer to the modified header, or NULL
3543 * to remove the header. This function frees the
3544 * original string if necessary.
3546 * Returns : JB_ERR_OK on success, or
3547 * JB_ERR_MEMORY on out-of-memory error.
3549 *********************************************************************/
3550 static jb_err client_max_forwards(struct client_state *csp, char **header)
3554 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3555 (0 == strcmpic(csp->http->gpc, "options")))
3557 assert(*(*header+12) == ':');
3558 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3560 if (max_forwards > 0)
3562 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3563 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3564 csp->http->gpc, max_forwards);
3566 else if (max_forwards < 0)
3568 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3574 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3583 /*********************************************************************
3585 * Function : client_host
3587 * Description : If the request URI did not contain host and
3588 * port information, parse and evaluate the Host
3591 * Also, kill ill-formed HOST: headers as sent by
3592 * Apple's iTunes software when used with a proxy.
3595 * 1 : csp = Current client state (buffers, headers, etc...)
3596 * 2 : header = On input, pointer to header to modify.
3597 * On output, pointer to the modified header, or NULL
3598 * to remove the header. This function frees the
3599 * original string if necessary.
3601 * Returns : JB_ERR_OK on success, or
3602 * JB_ERR_MEMORY on out-of-memory error.
3604 *********************************************************************/
3605 static jb_err client_host(struct client_state *csp, char **header)
3610 * If the header field name is all upper-case, chances are that it's
3611 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3612 * not a problem -- they are regenerated later.
3614 if ((*header)[1] == 'O')
3616 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3621 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3622 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3625 if (NULL == (p = strdup((*header)+6)))
3627 return JB_ERR_MEMORY;
3630 if (NULL == (q = strdup(p)))
3633 return JB_ERR_MEMORY;
3636 freez(csp->http->hostport);
3637 csp->http->hostport = p;
3638 freez(csp->http->host);
3639 csp->http->host = q;
3640 q = strchr(csp->http->host, ':');
3643 /* Terminate hostname and evaluate port string */
3645 csp->http->port = atoi(q);
3649 csp->http->port = csp->http->ssl ? 443 : 80;
3652 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3653 csp->http->hostport, csp->http->host, csp->http->port);
3656 /* Signal client_host_adder() to return right away */
3657 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3663 /*********************************************************************
3665 * Function : client_if_modified_since
3667 * Description : Remove or modify the If-Modified-Since header.
3670 * 1 : csp = Current client state (buffers, headers, etc...)
3671 * 2 : header = On input, pointer to header to modify.
3672 * On output, pointer to the modified header, or NULL
3673 * to remove the header. This function frees the
3674 * original string if necessary.
3676 * Returns : JB_ERR_OK on success, or
3677 * JB_ERR_MEMORY on out-of-memory error.
3679 *********************************************************************/
3680 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3683 #ifdef HAVE_GMTIME_R
3686 struct tm *timeptr = NULL;
3690 long int hours, minutes, seconds;