1 const char parsers_rcs[] = "$Id: parsers.c,v 1.154 2009/03/13 14:10:07 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-2009 the
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.154 2009/03/13 14:10:07 fabiankeil
48 * Fix some more harmless warnings on amd64.
50 * Revision 1.153 2009/03/07 13:09:17 fabiankeil
51 * Change csp->expected_content and_csp->expected_content_length from
52 * size_t to unsigned long long to reduce the likelihood of integer
53 * overflows that would let us close the connection prematurely.
54 * Bug found while investigating #2669131, reported by cyberpatrol.
56 * Revision 1.152 2009/03/01 18:43:48 fabiankeil
57 * Help clang understand that we aren't dereferencing
60 * Revision 1.151 2009/02/15 14:46:35 fabiankeil
61 * Don't let hide-referrer{conditional-*}} pass
62 * Referer headers without http URLs.
64 * Revision 1.150 2008/12/04 18:12:19 fabiankeil
65 * Fix some cparser warnings.
67 * Revision 1.149 2008/11/21 18:39:53 fabiankeil
68 * In case of CONNECT requests there's no point
69 * in trying to keep the connection alive.
71 * Revision 1.148 2008/11/16 12:43:49 fabiankeil
72 * Turn keep-alive support into a runtime feature
73 * that is disabled by setting keep-alive-timeout
74 * to a negative value.
76 * Revision 1.147 2008/11/04 17:20:31 fabiankeil
77 * HTTP/1.1 responses without Connection
78 * header imply keep-alive. Act accordingly.
80 * Revision 1.146 2008/10/12 16:46:35 fabiankeil
81 * Remove obsolete warning about delayed delivery with chunked
82 * transfer encoding and FEATURE_CONNECTION_KEEP_ALIVE enabled.
84 * Revision 1.145 2008/10/09 18:21:41 fabiankeil
85 * Flush work-in-progress changes to keep outgoing connections
86 * alive where possible. Incomplete and mostly #ifdef'd out.
88 * Revision 1.144 2008/09/21 13:59:33 fabiankeil
89 * Treat unknown change-x-forwarded-for parameters as fatal errors.
91 * Revision 1.143 2008/09/21 13:36:52 fabiankeil
92 * If change-x-forwarded-for{add} is used and the client
93 * sends multiple X-Forwarded-For headers, append the client's
94 * IP address to each one of them. "Traditionally" we would
95 * lose all but the last one.
97 * Revision 1.142 2008/09/20 10:04:33 fabiankeil
98 * Remove hide-forwarded-for-headers action which has
99 * been obsoleted by change-x-forwarded-for{block}.
101 * Revision 1.141 2008/09/19 15:26:28 fabiankeil
102 * Add change-x-forwarded-for{} action to block or add
103 * X-Forwarded-For headers. Mostly based on code removed
106 * Revision 1.140 2008/09/12 17:51:43 fabiankeil
107 * - A few style fixes.
108 * - Remove a pointless cast.
110 * Revision 1.139 2008/09/04 08:13:58 fabiankeil
111 * Prepare for critical sections on Windows by adding a
112 * layer of indirection before the pthread mutex functions.
114 * Revision 1.138 2008/08/30 12:03:07 fabiankeil
115 * Remove FEATURE_COOKIE_JAR.
117 * Revision 1.137 2008/05/30 15:50:08 fabiankeil
118 * Remove questionable micro-optimizations
119 * whose usefulness has never been measured.
121 * Revision 1.136 2008/05/26 16:02:24 fabiankeil
122 * s@Insufficent@Insufficient@
124 * Revision 1.135 2008/05/21 20:12:10 fabiankeil
125 * The whole point of strclean() is to modify the
126 * first parameter, so don't mark it immutable,
127 * even though the compiler lets us get away with it.
129 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
130 * As the wafer actions are gone, we can stop including encode.h.
132 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
133 * Ditch cast from (char **) to (char **).
135 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
136 * Streamline sed()'s prototype and declare
137 * the header parse and add structures static.
139 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
140 * Factor update_server_headers() out of sed(), ditch the
141 * first_run hack and make server_patterns_light static.
143 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
144 * Wrap memmove() calls in string_move()
145 * to document the purpose in one place.
147 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
148 * Normalize linear header white space.
150 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
151 * If a header is split across multiple lines,
152 * merge them to a single line before parsing them.
154 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
155 * Don't provide get_header() with the whole client state
156 * structure when it only needs access to csp->iob.
158 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
159 * Change content_filters_enabled()'s parameter from
160 * csp->action to action so it can be also used in the
161 * CGI code. Don't bother checking if there are filters
162 * loaded, as that's somewhat besides the point.
164 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
165 * Provide get_http_time() with the buffer size so it doesn't
166 * have to blindly assume that the buffer is big enough.
168 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
169 * Don't pass the whole csp structure to flush_socket()
170 * when it only needs a file descriptor and a buffer.
172 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
173 * Remove send-wafer and send-vanilla-wafer actions.
175 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
176 * Remove inspect-jpegs action.
178 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
179 * Let client_range() also handle Request-Range headers
180 * which apparently are still supported by many servers.
182 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
183 * Improve the warning messages that get logged if the action files
184 * "enable" filters but no filters of that type have been loaded.
186 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
187 * In server_content_type():
188 * - Don't require leading white space when detecting image content types.
189 * - Change '... not replaced ...' message to sound less crazy if the text
190 * type actually is 'text/plain'.
191 * - Mark the 'text/plain == binary data' assumption for removal.
192 * - Remove a bunch of trailing white space.
194 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
195 * Minor server_content_disposition() changes:
196 * - Don't regenerate the header name all lower-case.
197 * - Some white space fixes.
198 * - Remove useless log message in case of ENOMEM.
200 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
201 * Garbage-collect the code to add a X-Forwarded-For
202 * header as it seems to be mostly used by accident.
204 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
205 * Fix a crash on mingw32 with some Last Modified times in the future.
207 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
208 * Remove a "can't happen" error block which, over
209 * time, mutated into a "guaranteed to happen" block.
211 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
212 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
213 * - Use shiny new content_filters_enabled() in client_range().
215 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
216 * I forgot about Poland.
218 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
219 * Remove Range and If-Range headers if content filtering is enabled.
221 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
222 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
223 * client_cookie_adder() to make sure send-vanilla-wafer can be
224 * controlled through tags (and thus regression-tested).
226 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
227 * - Remove "scanning headers for" log message again.
228 * - Some more whitespace fixes.
230 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
231 * Refactor client_referrer() and add conditional-forge parameter.
233 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
234 * A bunch of whitespace fixes, pointy hat to me.
236 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
237 * Fix possible memory corruption in server_http, make sure it's not
238 * executed for ordinary server headers and mark some problems for later.
240 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
241 * Let content-type-overwrite{} honour force-text-mode again.
243 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
244 * - Add prototpyes for the header parsers and make them static.
245 * - Comment out client_accept_encoding_adder() which isn't used right now.
247 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
248 * Move the ACTION_FORCE_TEXT_MODE check out of
249 * server_content_type(). Signal other functions
250 * whether or not a content type has been declared.
251 * Part of the fix for BR#1750917.
253 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
254 * Change sed() to return a jb_err in preparation for forward-override{}.
256 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
257 * Adjust "X-Filter: No" to disable dedicated header filters.
259 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
260 * Streamline client_cookie_adder().
262 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
263 * Make sure filters with dynamic jobs actually use them.
265 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
266 * - Introduce dynamic pcrs jobs that can resolve variables.
267 * - Remove unnecessary update_action_bits_for_all_tags() call.
269 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
270 * - Make tagging based on tags set by earlier taggers
271 * of the same kind possible.
272 * - Log whether or not new tags cause action bits updates
273 * (in which case a matching tag-pattern section exists).
274 * - Log if the user tries to set a tag that is already set.
276 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
277 * Introduce tags as alternative way to specify which
278 * actions apply to a request. At the moment tags can be
279 * created based on client and server headers.
281 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
282 * Log a warning if the content is compressed, filtering is
283 * enabled and Privoxy was compiled without zlib support.
286 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
287 * - Fix warnings when compiled with glibc.
288 * - Don't use crumble() for cookie crunching.
289 * - Move cookie time parsing into parse_header_time().
290 * - Let parse_header_time() return a jb_err code
291 * instead of a pointer that can only be used to
292 * check for NULL anyway.
294 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
295 * - Add better protection against malicious gzip headers.
296 * - Stop logging the first hundred bytes of decompressed content.
297 * It looks like it's working and there is always debug 16.
298 * - Log the content size after decompression in decompress_iob()
299 * instead of pcrs_filter_response().
301 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
302 * - Use dedicated header filter actions instead of abusing "filter".
303 * Replace "filter-client-headers" and "filter-client-headers"
304 * with "server-header-filter" and "client-header-filter".
305 * - Remove filter_client_header() and filter_client_header(),
306 * filter_header() now checks the shiny new
307 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
309 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
310 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
311 * - Handle "Cookie:" and "Connection:" headers a bit smarter
312 * (don't crunch them just to recreate them later on).
313 * - Add another non-standard time format for the cookie
314 * expiration date detection.
315 * - Fix a valgrind warning.
317 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
318 * Improve cookie expiration date detection.
320 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
321 * Don't run server_content_length() the first time
322 * sed() parses server headers; only adjust the
323 * Content-Length header if the page was modified.
325 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
326 * Fix log messages regarding the cookie time format
327 * (cookie and request URL were mixed up).
329 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
330 * - Let decompress_iob()
331 * - not corrupt the content if decompression fails
332 * early. (the first byte(s) were lost).
333 * - use pointer arithmetics with defined outcome for
335 * - Use a different kludge to remember a failed decompression.
337 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
338 * Search for Max-Forwards headers case-insensitive,
339 * don't generate the "501 unsupported" message for invalid
340 * Max-Forwards values and don't increase negative ones.
342 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
343 * - Let server_set_cookie() check the expiration date
344 * of cookies and don't touch the ones that are already
345 * expired. Fixes problems with low quality web applications
346 * as described in BR 932612.
348 * - Adjust comment in client_max_forwards to reality;
349 * remove invalid Max-Forwards headers.
351 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
352 * Stop filter_header() from unintentionally removing
353 * empty header lines that were enlisted by the continue
356 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
357 * - Repeat the request URL before logging any headers.
358 * Makes reading the log easier in case of simultaneous requests.
359 * - If there are more than one Content-Type headers in one request,
360 * use the first one and remove the others.
361 * - Remove "newval" variable in server_content_type().
362 * It's only used once.
364 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
365 * Correct a cast, check inflateEnd() exit code
366 * to see if we have to, replace sprintf calls
369 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
370 * Integrate a modified version of Wil Mahan's
371 * zlib patch (PR #895531).
373 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
374 * Skip empty filter files in filter_header()
375 * but don't ignore the ones that come afterwards.
376 * Fixes BR 1619208, this time for real.
378 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
379 * Reverted parts of my last commit
380 * to keep error handling working.
382 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
383 * Fixed gcc43 conversion warnings.
385 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
386 * Bringing back the "useless" localtime() call
387 * I removed in revision 1.67. On some platforms
388 * it's necessary to prevent time zone offsets.
390 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
391 * Rebuild request URL in get_destination_from_headers()
392 * to make sure redirect{pcrs command} works as expected
393 * for intercepted requests.
395 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
396 * Added get_destination_from_headers().
398 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
399 * Make pthread mutex locking more generic. Instead of
400 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
401 * and use mutex locking unless there is an _r function
402 * available. Better safe than sorry.
404 * Fixes "./configure --disable-pthread" and should result
405 * in less threading-related problems on pthread-using platforms,
406 * but it still doesn't fix BR#1122404.
408 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
409 * The special header "X-Filter: No" now disables
410 * header filtering as well.
412 * Revision 1.73 2006/09/23 13:26:38 roro
413 * Replace TABs by spaces in source code.
415 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
416 * Don't print a log message every time filter_headers is
417 * entered or left. It only creates noise without any real
420 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
421 * Fix +hide-if-modified-since{-n}.
423 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
424 * Have hide-if-modified-since interpret the random
425 * range value as minutes instead of hours. Allows
426 * more fine-grained configuration.
428 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
429 * Always have parse_header_time return a pointer
430 * that actual makes sense, even though we currently
431 * only need it to detect problems.
433 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
434 * Added config option enable-remote-http-toggle
435 * to specify if Privoxy should recognize special
436 * headers (currently only X-Filter) to change its
437 * behaviour. Disabled by default.
439 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
440 * After filtering de-chunked instances, remove
441 * "Transfer-Encoding" header entirely instead of changing
442 * it to "Transfer-Encoding: identity", which is invalid.
443 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
445 * Don't use localtime in parse_header_time. An empty time struct
446 * is good enough, it gets overwritten by strptime anyway.
448 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
449 * Use gmtime_r if available, fallback to gmtime with mutex
450 * protection for MacOSX and use vanilla gmtime for the rest.
452 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
453 * Changed client_referrer to use the right type (size_t) for
454 * hostlenght and to shorten the temporary referrer string with
455 * '\0' instead of adding a useless line break.
457 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
458 * - Back to timegm() using GnuPG's replacement if necessary.
459 * Using mktime() and localtime() could add a on hour offset if
460 * the randomize factor was big enough to lead to a summer/wintertime
463 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
465 * - Moved randomization code into pick_from_range().
467 * - Changed parse_header_time definition.
468 * time_t isn't guaranteed to be signed and
469 * if it isn't, -1 isn't available as error code.
470 * Changed some variable types in client_if_modified_since()
471 * because of the same reason.
473 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
474 * OS/2 compilation compatibility fixups
476 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
477 * Changed include from strptime.c to strptime.h
479 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
480 * Split filter-headers{} into filter-client-headers{}
481 * and filter-server-headers{}.
482 * Added parse_header_time() to share some code.
483 * Replaced timegm() with mktime().
485 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
486 * Windows service integration
488 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
489 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
491 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
492 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
493 * with what was really the latest development (the v_3_0_branch branch)
495 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
496 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
498 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
499 * Add the ability to check jpeg images for invalid
500 * lengths of comment blocks. Defensive strategy
501 * against the exploit:
502 * Microsoft Security Bulletin MS04-028
503 * Buffer Overrun in JPEG Processing (GDI+) Could
504 * Allow Code Execution (833987)
505 * Enabled with +inspect-jpegs in actions files.
507 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
508 * Excluded text/plain objects from filtering. This fixes a
509 * couple of client-crashing, download corruption and
510 * Privoxy performance issues, whose root cause lies in
511 * web servers labelling content of unknown type as text/plain.
513 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
514 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
516 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
517 * Completing the previous change
519 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
520 * Added temporary workaround for bug in PHP < 4.2.3
522 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
523 * 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.
525 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
526 * Fix typo: supressed -> suppressed
528 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
529 * Improved cookie logging
531 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
532 * Added basic support for OPTIONS and TRACE HTTP methods:
533 * - New parser function client_max_forwards which decrements
534 * the Max-Forwards HTTP header field of OPTIONS and TRACE
535 * requests by one before forwarding
536 * - New parser function client_host which extracts the host
537 * and port information from the HTTP header field if the
538 * request URI was not absolute
539 * - Don't crumble and re-add the Host: header, but only generate
540 * and append if missing
542 * Revision 1.56 2002/05/12 15:34:22 jongfoster
543 * Fixing typo in a comment
545 * Revision 1.55 2002/05/08 16:01:07 oes
546 * Optimized add_to_iob:
547 * - Use realloc instead of malloc(), memcpy(), free()
548 * - Expand to powers of two if possible, to get
549 * O(log n) reallocs instead of O(n).
550 * - Moved check for buffer limit here from chat
551 * - Report failure via returncode
553 * Revision 1.54 2002/04/02 15:03:16 oes
554 * Tiny code cosmetics
556 * Revision 1.53 2002/03/26 22:29:55 swa
557 * we have a new homepage!
559 * Revision 1.52 2002/03/24 13:25:43 swa
560 * name change related issues
562 * Revision 1.51 2002/03/13 00:27:05 jongfoster
565 * Revision 1.50 2002/03/12 01:45:35 oes
566 * More verbose logging
568 * Revision 1.49 2002/03/09 20:03:52 jongfoster
569 * - Making various functions return int rather than size_t.
570 * (Undoing a recent change). Since size_t is unsigned on
571 * Windows, functions like read_socket that return -1 on
572 * error cannot return a size_t.
574 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
575 * crashes, and also frequently caused JB to jump to 100%
576 * CPU and stay there. (Because it thought it had just
577 * read ((unsigned)-1) == 4Gb of data...)
579 * - The signature of write_socket has changed, it now simply
580 * returns success=0/failure=nonzero.
582 * - Trying to get rid of a few warnings --with-debug on
583 * Windows, I've introduced a new type "jb_socket". This is
584 * used for the socket file descriptors. On Windows, this
585 * is SOCKET (a typedef for unsigned). Everywhere else, it's
586 * an int. The error value can't be -1 any more, so it's
587 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
588 * Windows it maps to the #define INVALID_SOCKET.)
590 * - The signature of bind_port has changed.
592 * Revision 1.48 2002/03/07 03:46:53 oes
593 * Fixed compiler warnings etc
595 * Revision 1.47 2002/02/20 23:15:13 jongfoster
596 * Parsing functions now handle out-of-memory gracefully by returning
599 * Revision 1.46 2002/01/17 21:03:47 jongfoster
600 * Moving all our URL and URL pattern parsing code to urlmatch.c.
602 * Revision 1.45 2002/01/09 14:33:03 oes
603 * Added support for localtime_r.
605 * Revision 1.44 2001/12/14 01:22:54 steudten
606 * Remove 'user:pass@' from 'proto://user:pass@host' for the
607 * new added header 'Host: ..'. (See Req ID 491818)
609 * Revision 1.43 2001/11/23 00:26:38 jongfoster
610 * Fixing two really stupid errors in my previous commit
612 * Revision 1.42 2001/11/22 21:59:30 jongfoster
613 * Adding code to handle +no-cookies-keep
615 * Revision 1.41 2001/11/05 23:43:05 steudten
616 * Add time+date to log files.
618 * Revision 1.40 2001/10/26 20:13:09 jongfoster
619 * ctype.h is needed in Windows, too.
621 * Revision 1.39 2001/10/26 17:40:04 oes
622 * Introduced get_header_value()
623 * Removed http->user_agent, csp->referrer and csp->accept_types
624 * Removed client_accept()
626 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
627 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
628 * threads to call select() simultaneously. So, it's time to do a real, live,
629 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
630 * (native). Both versions will work, but using __OS2__ offers multi-threading.
632 * Revision 1.37 2001/10/23 21:36:02 jongfoster
633 * Documenting sed()'s error behaviou (doc change only)
635 * Revision 1.36 2001/10/13 12:51:51 joergs
636 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
637 * force-load), instead crumble Host: and add it (again) in client_host_adder
638 * (in case we get a HTTP/1.0 request without Host: header and forward it to
639 * a HTTP/1.1 server/proxy).
641 * Revision 1.35 2001/10/09 22:39:21 jongfoster
642 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
645 * Revision 1.34 2001/10/07 18:50:55 oes
646 * Added server_content_encoding, renamed server_transfer_encoding
648 * Revision 1.33 2001/10/07 18:04:49 oes
649 * Changed server_http11 to server_http and its pattern to "HTTP".
650 * Additional functionality: it now saves the HTTP status into
651 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
653 * Revision 1.32 2001/10/07 15:43:28 oes
654 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
655 * client_te and client_accept_encoding_adder, triggered by the new
656 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
657 * changed to allow only identity and chunked, and the TE header is
658 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
660 * parse_http_request no longer does anything than parsing. The rewriting
661 * of http->cmd and version mangling are gone. It now also recognizes
662 * the put and delete methods and saves the url in http->url. Removed
665 * renamed content_type and content_length to have the server_ prefix
667 * server_content_type now only works if csp->content_type != CT_TABOO
669 * added server_transfer_encoding, which
670 * - Sets CT_TABOO to prohibit filtering if encoding compresses
671 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
672 * - Change from "chunked" to "identity" if body was chunked
673 * but has been de-chunked for filtering.
675 * added server_content_md5 which crunches any Content-MD5 headers
676 * if the body was modified.
678 * made server_http11 conditional on +downgrade action
680 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
682 * Revision 1.31 2001/10/05 14:25:02 oes
683 * Crumble Keep-Alive from Server
685 * Revision 1.30 2001/09/29 12:56:03 joergs
686 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
688 * Revision 1.29 2001/09/24 21:09:24 jongfoster
689 * Fixing 2 memory leaks that Guy spotted, where the paramater to
690 * enlist() was not being free()d.
692 * Revision 1.28 2001/09/22 16:32:28 jongfoster
693 * Removing unused #includes.
695 * Revision 1.27 2001/09/20 15:45:25 steudten
697 * add casting from size_t to int for printf()
698 * remove local variable shadow s2
700 * Revision 1.26 2001/09/16 17:05:14 jongfoster
701 * Removing unused #include showarg.h
703 * Revision 1.25 2001/09/16 13:21:27 jongfoster
704 * Changes to use new list functions.
706 * Revision 1.24 2001/09/13 23:05:50 jongfoster
707 * Changing the string paramater to the header parsers a "const".
709 * Revision 1.23 2001/09/12 18:08:19 steudten
711 * In parse_http_request() header rewriting miss the host value, so
712 * from http://www.mydomain.com the result was just " / " not
713 * http://www.mydomain.com/ in case we forward.
715 * Revision 1.22 2001/09/10 10:58:53 oes
716 * Silenced compiler warnings
718 * Revision 1.21 2001/07/31 14:46:00 oes
719 * - Persistant connections now suppressed
720 * - sed() no longer appends empty header to csp->headers
722 * Revision 1.20 2001/07/30 22:08:36 jongfoster
723 * Tidying up #defines:
724 * - All feature #defines are now of the form FEATURE_xxx
725 * - Permanently turned off WIN_GUI_EDIT
726 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
728 * Revision 1.19 2001/07/25 17:21:54 oes
729 * client_uagent now saves copy of User-Agent: header value
731 * Revision 1.18 2001/07/13 14:02:46 oes
732 * - Included fix to repair broken HTTP requests that
733 * don't contain a path, not even '/'.
734 * - Removed all #ifdef PCRS
735 * - content_type now always inspected and classified as
736 * text, gif or other.
737 * - formatting / comments
739 * Revision 1.17 2001/06/29 21:45:41 oes
740 * Indentation, CRLF->LF, Tab-> Space
742 * Revision 1.16 2001/06/29 13:32:42 oes
744 * - Adapted free_http_request
745 * - Removed logentry from cancelled commit
747 * Revision 1.15 2001/06/03 19:12:38 oes
748 * deleted const struct interceptors
750 * Revision 1.14 2001/06/01 18:49:17 jongfoster
751 * Replaced "list_share" with "list" - the tiny memory gain was not
752 * worth the extra complexity.
754 * Revision 1.13 2001/05/31 21:30:33 jongfoster
755 * Removed list code - it's now in list.[ch]
756 * Renamed "permission" to "action", and changed many features
757 * to use the actions file rather than the global config.
759 * Revision 1.12 2001/05/31 17:33:13 oes
763 * Revision 1.11 2001/05/29 20:11:19 joergs
764 * '/ * inside comment' warning removed.
766 * Revision 1.10 2001/05/29 09:50:24 jongfoster
767 * Unified blocklist/imagelist/permissionslist.
768 * File format is still under discussion, but the internal changes
771 * Also modified interceptor behaviour:
772 * - We now intercept all URLs beginning with one of the following
773 * prefixes (and *only* these prefixes):
775 * * http://ijbswa.sf.net/config/
776 * * http://ijbswa.sourceforge.net/config/
777 * - New interceptors "home page" - go to http://i.j.b/ to see it.
778 * - Internal changes so that intercepted and fast redirect pages
779 * are not replaced with an image.
780 * - Interceptors now have the option to send a binary page direct
781 * to the client. (i.e. ijb-send-banner uses this)
782 * - Implemented show-url-info interceptor. (Which is why I needed
783 * the above interceptors changes - a typical URL is
784 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
785 * The previous mechanism would not have intercepted that, and
786 * if it had been intercepted then it then it would have replaced
789 * Revision 1.9 2001/05/28 17:26:33 jongfoster
790 * Fixing segfault if last header was crunched.
791 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
792 * can use the cross-platform sprintf() instead.)
794 * Revision 1.8 2001/05/27 22:17:04 oes
796 * - re_process_buffer no longer writes the modified buffer
797 * to the client, which was very ugly. It now returns the
798 * buffer, which it is then written by chat.
800 * - content_length now adjusts the Content-Length: header
801 * for modified documents rather than crunch()ing it.
802 * (Length info in csp->content_length, which is 0 for
803 * unmodified documents)
805 * - For this to work, sed() is called twice when filtering.
807 * Revision 1.7 2001/05/27 13:19:06 oes
808 * Patched Joergs solution for the content-length in.
810 * Revision 1.6 2001/05/26 13:39:32 jongfoster
811 * Only crunches Content-Length header if applying RE filtering.
812 * Without this fix, Microsoft Windows Update wouldn't work.
814 * Revision 1.5 2001/05/26 00:28:36 jongfoster
815 * Automatic reloading of config file.
816 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
817 * Most of the global variables have been moved to a new
818 * struct configuration_spec, accessed through csp->config->globalname
819 * Most of the globals remaining are used by the Win32 GUI.
821 * Revision 1.4 2001/05/22 18:46:04 oes
823 * - Enabled filtering banners by size rather than URL
824 * by adding patterns that replace all standard banner
825 * sizes with the "Junkbuster" gif to the re_filterfile
827 * - Enabled filtering WebBugs by providing a pattern
828 * which kills all 1x1 images
830 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
831 * which is selected by the (nonstandard and therefore
832 * capital) letter 'U' in the option string.
833 * It causes the quantifiers to be ungreedy by default.
834 * Appending a ? turns back to greedy (!).
836 * - Added a new interceptor ijb-send-banner, which
837 * sends back the "Junkbuster" gif. Without imagelist or
838 * MSIE detection support, or if tinygif = 1, or the
839 * URL isn't recognized as an imageurl, a lame HTML
840 * explanation is sent instead.
842 * - Added new feature, which permits blocking remote
843 * script redirects and firing back a local redirect
845 * The feature is conditionally compiled, i.e. it
846 * can be disabled with --disable-fast-redirects,
847 * plus it must be activated by a "fast-redirects"
848 * line in the config file, has its own log level
849 * and of course wants to be displayed by show-proxy-args
850 * Note: Boy, all the #ifdefs in 1001 locations and
851 * all the fumbling with configure.in and acconfig.h
852 * were *way* more work than the feature itself :-(
854 * - Because a generic redirect template was needed for
855 * this, tinygif = 3 now uses the same.
857 * - Moved GIFs, and other static HTTP response templates
862 * - Removed some >400 CRs again (Jon, you really worked
865 * Revision 1.3 2001/05/20 01:21:20 jongfoster
866 * Version 2.9.4 checkin.
867 * - Merged popupfile and cookiefile, and added control over PCRS
868 * filtering, in new "permissionsfile".
869 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
870 * file error you now get a message box (in the Win32 GUI) rather
871 * than the program exiting with no explanation.
872 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
874 * - Removed tabs from "config"
875 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
876 * - Bumped up version number.
878 * Revision 1.2 2001/05/17 23:02:36 oes
879 * - Made referrer option accept 'L' as a substitute for '§'
881 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
882 * Initial import of version 2.9.3 source tree
885 *********************************************************************/
892 #include <sys/types.h>
902 * Convince GNU's libc to provide a strptime prototype.
905 #endif /*__GLIBC__ */
912 #if !defined(_WIN32) && !defined(__OS2__)
918 #ifdef FEATURE_PTHREAD
920 /* jcc.h is for mutex semapores only */
921 #endif /* def FEATURE_PTHREAD */
926 #include "jbsockets.h"
927 #include "miscutil.h"
932 #ifndef HAVE_STRPTIME
933 #include "strptime.h"
936 const char parsers_h_rcs[] = PARSERS_H_VERSION;
938 /* Fix a problem with Solaris. There should be no effect on other
940 * Solaris's isspace() is a macro which uses its argument directly
941 * as an array index. Therefore we need to make sure that high-bit
942 * characters generate +ve values, and ideally we also want to make
943 * the argument match the declared parameter type of "int".
945 * Why did they write a character function that can't take a simple
946 * "char" argument? Doh!
948 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
949 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
951 static char *get_header_line(struct iob *iob);
952 static jb_err scan_headers(struct client_state *csp);
953 static jb_err header_tagger(struct client_state *csp, char *header);
954 static jb_err parse_header_time(const char *header_time, time_t *result);
956 static jb_err crumble (struct client_state *csp, char **header);
957 static jb_err filter_header (struct client_state *csp, char **header);
958 static jb_err client_connection (struct client_state *csp, char **header);
959 static jb_err client_referrer (struct client_state *csp, char **header);
960 static jb_err client_uagent (struct client_state *csp, char **header);
961 static jb_err client_ua (struct client_state *csp, char **header);
962 static jb_err client_from (struct client_state *csp, char **header);
963 static jb_err client_send_cookie (struct client_state *csp, char **header);
964 static jb_err client_x_forwarded (struct client_state *csp, char **header);
965 static jb_err client_accept_encoding (struct client_state *csp, char **header);
966 static jb_err client_te (struct client_state *csp, char **header);
967 static jb_err client_max_forwards (struct client_state *csp, char **header);
968 static jb_err client_host (struct client_state *csp, char **header);
969 static jb_err client_if_modified_since (struct client_state *csp, char **header);
970 static jb_err client_accept_language (struct client_state *csp, char **header);
971 static jb_err client_if_none_match (struct client_state *csp, char **header);
972 static jb_err crunch_client_header (struct client_state *csp, char **header);
973 static jb_err client_x_filter (struct client_state *csp, char **header);
974 static jb_err client_range (struct client_state *csp, char **header);
975 static jb_err server_set_cookie (struct client_state *csp, char **header);
976 static jb_err server_connection (struct client_state *csp, char **header);
977 static jb_err server_content_type (struct client_state *csp, char **header);
978 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
979 static jb_err server_content_md5 (struct client_state *csp, char **header);
980 static jb_err server_content_encoding (struct client_state *csp, char **header);
981 static jb_err server_transfer_coding (struct client_state *csp, char **header);
982 static jb_err server_http (struct client_state *csp, char **header);
983 static jb_err crunch_server_header (struct client_state *csp, char **header);
984 static jb_err server_last_modified (struct client_state *csp, char **header);
985 static jb_err server_content_disposition(struct client_state *csp, char **header);
987 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
988 static jb_err server_save_content_length(struct client_state *csp, char **header);
989 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
991 static jb_err client_host_adder (struct client_state *csp);
992 static jb_err client_xtra_adder (struct client_state *csp);
993 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
994 static jb_err client_connection_header_adder(struct client_state *csp);
995 static jb_err server_connection_adder(struct client_state *csp);
996 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
997 static jb_err server_proxy_connection_adder(struct client_state *csp);
998 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1000 static jb_err create_forged_referrer(char **header, const char *hostport);
1001 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
1002 static jb_err handle_conditional_hide_referrer_parameter(char **header,
1003 const char *host, const int parameter_conditional_block);
1004 static const char *get_appropiate_connection_header(const struct client_state *csp);
1007 * List of functions to run on a list of headers.
1011 /** The header prefix to match */
1014 /** The length of the prefix to match */
1017 /** The function to apply to this line */
1018 const parser_func_ptr parser;
1021 static const struct parsers client_patterns[] = {
1022 { "referer:", 8, client_referrer },
1023 { "user-agent:", 11, client_uagent },
1024 { "ua-", 3, client_ua },
1025 { "from:", 5, client_from },
1026 { "cookie:", 7, client_send_cookie },
1027 { "x-forwarded-for:", 16, client_x_forwarded },
1028 { "Accept-Encoding:", 16, client_accept_encoding },
1029 { "TE:", 3, client_te },
1030 { "Host:", 5, client_host },
1031 { "if-modified-since:", 18, client_if_modified_since },
1032 #ifndef FEATURE_CONNECTION_KEEP_ALIVE
1033 { "Keep-Alive:", 11, crumble },
1035 { "connection:", 11, client_connection },
1036 { "proxy-connection:", 17, crumble },
1037 { "max-forwards:", 13, client_max_forwards },
1038 { "Accept-Language:", 16, client_accept_language },
1039 { "if-none-match:", 14, client_if_none_match },
1040 { "Range:", 6, client_range },
1041 { "Request-Range:", 14, client_range },
1042 { "If-Range:", 9, client_range },
1043 { "X-Filter:", 9, client_x_filter },
1044 { "*", 0, crunch_client_header },
1045 { "*", 0, filter_header },
1049 static const struct parsers server_patterns[] = {
1050 { "HTTP/", 5, server_http },
1051 { "set-cookie:", 11, server_set_cookie },
1052 { "connection:", 11, server_connection },
1053 { "Content-Type:", 13, server_content_type },
1054 { "Content-MD5:", 12, server_content_md5 },
1055 { "Content-Encoding:", 17, server_content_encoding },
1056 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1057 { "Content-Length:", 15, server_save_content_length },
1059 { "Keep-Alive:", 11, crumble },
1060 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1061 { "Transfer-Encoding:", 18, server_transfer_coding },
1062 { "content-disposition:", 20, server_content_disposition },
1063 { "Last-Modified:", 14, server_last_modified },
1064 { "*", 0, crunch_server_header },
1065 { "*", 0, filter_header },
1069 static const add_header_func_ptr add_client_headers[] = {
1071 client_x_forwarded_for_adder,
1073 /* Temporarily disabled: client_accept_encoding_adder, */
1074 client_connection_header_adder,
1078 static const add_header_func_ptr add_server_headers[] = {
1079 server_connection_adder,
1080 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1081 server_proxy_connection_adder,
1082 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1086 /*********************************************************************
1088 * Function : flush_socket
1090 * Description : Write any pending "buffered" content.
1093 * 1 : fd = file descriptor of the socket to read
1094 * 2 : iob = The I/O buffer to flush, usually csp->iob.
1096 * Returns : On success, the number of bytes written are returned (zero
1097 * indicates nothing was written). On error, -1 is returned,
1098 * and errno is set appropriately. If count is zero and the
1099 * file descriptor refers to a regular file, 0 will be
1100 * returned without causing any other effect. For a special
1101 * file, the results are not portable.
1103 *********************************************************************/
1104 long flush_socket(jb_socket fd, struct iob *iob)
1106 long len = iob->eod - iob->cur;
1113 if (write_socket(fd, iob->cur, (size_t)len))
1117 iob->eod = iob->cur = iob->buf;
1123 /*********************************************************************
1125 * Function : add_to_iob
1127 * Description : Add content to the buffered page, expanding the
1128 * buffer if necessary.
1131 * 1 : csp = Current client state (buffers, headers, etc...)
1132 * 2 : buf = holds the content to be added to the page
1133 * 3 : n = number of bytes to be added
1135 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1136 * or buffer limit reached.
1138 *********************************************************************/
1139 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
1141 struct iob *iob = csp->iob;
1142 size_t used, offset, need, want;
1145 if (n <= 0) return JB_ERR_OK;
1147 used = (size_t)(iob->eod - iob->buf);
1148 offset = (size_t)(iob->cur - iob->buf);
1149 need = used + (size_t)n + 1;
1152 * If the buffer can't hold the new data, extend it first.
1153 * Use the next power of two if possible, else use the actual need.
1155 if (need > csp->config->buffer_limit)
1157 log_error(LOG_LEVEL_INFO,
1158 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
1159 need, csp->config->buffer_limit);
1160 return JB_ERR_MEMORY;
1163 if (need > iob->size)
1165 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1167 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1171 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1177 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1178 return JB_ERR_MEMORY;
1181 /* Update the iob pointers */
1182 iob->cur = p + offset;
1183 iob->eod = p + used;
1187 /* copy the new data into the iob buffer */
1188 memcpy(iob->eod, buf, (size_t)n);
1190 /* point to the end of the data */
1193 /* null terminate == cheap insurance */
1202 /*********************************************************************
1204 * Function : decompress_iob
1206 * Description : Decompress buffered page, expanding the
1207 * buffer as necessary. csp->iob->cur
1208 * should point to the the beginning of the
1209 * compressed data block.
1212 * 1 : csp = Current client state (buffers, headers, etc...)
1214 * Returns : JB_ERR_OK on success,
1215 * JB_ERR_MEMORY if out-of-memory limit reached, and
1216 * JB_ERR_COMPRESS if error decompressing buffer.
1218 *********************************************************************/
1219 jb_err decompress_iob(struct client_state *csp)
1221 char *buf; /* new, uncompressed buffer */
1222 char *cur; /* Current iob position (to keep the original
1223 * iob->cur unmodified if we return early) */
1224 size_t bufsize; /* allocated size of the new buffer */
1225 size_t old_size; /* Content size before decompression */
1226 size_t skip_size; /* Number of bytes at the beginning of the iob
1227 that we should NOT decompress. */
1228 int status; /* return status of the inflate() call */
1229 z_stream zstr; /* used by calls to zlib */
1231 assert(csp->iob->cur - csp->iob->buf > 0);
1232 assert(csp->iob->eod - csp->iob->cur > 0);
1234 bufsize = csp->iob->size;
1235 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1236 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1238 cur = csp->iob->cur;
1240 if (bufsize < (size_t)10)
1243 * This is to protect the parsing of gzipped data,
1244 * but it should(?) be valid for deflated data also.
1246 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1247 return JB_ERR_COMPRESS;
1250 if (csp->content_type & CT_GZIP)
1253 * Our task is slightly complicated by the facts that data
1254 * compressed by gzip does not include a zlib header, and
1255 * that there is no easily accessible interface in zlib to
1256 * handle a gzip header. We strip off the gzip header by
1257 * hand, and later inform zlib not to expect a header.
1261 * Strip off the gzip header. Please see RFC 1952 for more
1262 * explanation of the appropriate fields.
1264 if ((*cur++ != (char)0x1f)
1265 || (*cur++ != (char)0x8b)
1266 || (*cur++ != Z_DEFLATED))
1268 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1269 return JB_ERR_COMPRESS;
1275 * XXX: These magic numbers should be replaced
1276 * with macros to give a better idea what they do.
1280 /* The gzip header has reserved bits set; bail out. */
1281 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1282 return JB_ERR_COMPRESS;
1286 /* Skip extra fields if necessary. */
1290 * Skip a given number of bytes, specified
1291 * as a 16-bit little-endian value.
1294 * XXX: This code used to be:
1296 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1298 * which I had to change into:
1300 * cur += *cur++ + (*cur++ << 8);
1302 * at which point gcc43 finally noticed that the value
1303 * of cur is undefined (it depends on which of the
1304 * summands is evaluated first).
1306 * I haven't come across a site where this
1307 * code is actually executed yet, but I hope
1311 skip_bytes = *cur++;
1312 skip_bytes = *cur++ << 8;
1314 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1317 * The number of bytes to skip should be positive
1318 * and we'd like to stay in the buffer.
1320 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1322 log_error(LOG_LEVEL_ERROR,
1323 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1325 return JB_ERR_COMPRESS;
1327 log_error(LOG_LEVEL_INFO,
1328 "Skipping %d bytes for gzip compression. Does this sound right?",
1333 /* Skip the filename if necessary. */
1336 /* A null-terminated string is supposed to follow. */
1337 while (*cur++ && (cur < csp->iob->eod));
1341 /* Skip the comment if necessary. */
1344 /* A null-terminated string is supposed to follow. */
1345 while (*cur++ && (cur < csp->iob->eod));
1348 /* Skip the CRC if necessary. */
1354 if (cur >= csp->iob->eod)
1357 * If the current position pointer reached or passed
1358 * the buffer end, we were obviously tricked to skip
1361 log_error(LOG_LEVEL_ERROR,
1362 "Malformed gzip header detected. Aborting decompression.");
1363 return JB_ERR_COMPRESS;
1367 else if (csp->content_type & CT_DEFLATE)
1370 * XXX: The debug level should be lowered
1371 * before the next stable release.
1373 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1375 * In theory (that is, according to RFC 1950), deflate-compressed
1376 * data should begin with a two-byte zlib header and have an
1377 * adler32 checksum at the end. It seems that in practice only
1378 * the raw compressed data is sent. Note that this means that
1379 * we are not RFC 1950-compliant here, but the advantage is that
1380 * this actually works. :)
1382 * We add a dummy null byte to tell zlib where the data ends,
1383 * and later inform it not to expect a header.
1385 * Fortunately, add_to_iob() has thoughtfully null-terminated
1386 * the buffer; we can just increment the end pointer to include
1393 log_error(LOG_LEVEL_ERROR,
1394 "Unable to determine compression format for decompression");
1395 return JB_ERR_COMPRESS;
1398 /* Set up the fields required by zlib. */
1399 zstr.next_in = (Bytef *)cur;
1400 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1401 zstr.zalloc = Z_NULL;
1402 zstr.zfree = Z_NULL;
1403 zstr.opaque = Z_NULL;
1406 * Passing -MAX_WBITS to inflateInit2 tells the library
1407 * that there is no zlib header.
1409 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1411 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1412 return JB_ERR_COMPRESS;
1416 * Next, we allocate new storage for the inflated data.
1417 * We don't modify the existing iob yet, so in case there
1418 * is error in decompression we can recover gracefully.
1420 buf = zalloc(bufsize);
1423 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1424 return JB_ERR_MEMORY;
1427 assert(bufsize >= skip_size);
1428 memcpy(buf, csp->iob->buf, skip_size);
1429 zstr.avail_out = bufsize - skip_size;
1430 zstr.next_out = (Bytef *)buf + skip_size;
1432 /* Try to decompress the whole stream in one shot. */
1433 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1435 /* We need to allocate more memory for the output buffer. */
1437 char *tmpbuf; /* used for realloc'ing the buffer */
1438 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1441 * If zlib wants more data then there's a problem, because
1442 * the complete compressed file should have been buffered.
1444 if (0 == zstr.avail_in)
1446 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1447 return JB_ERR_COMPRESS;
1451 * If we tried the limit and still didn't have enough
1452 * memory, just give up.
1454 if (bufsize == csp->config->buffer_limit)
1456 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1457 return JB_ERR_MEMORY;
1460 /* Try doubling the buffer size each time. */
1463 /* Don't exceed the buffer limit. */
1464 if (bufsize > csp->config->buffer_limit)
1466 bufsize = csp->config->buffer_limit;
1469 /* Try to allocate the new buffer. */
1470 tmpbuf = realloc(buf, bufsize);
1473 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1475 return JB_ERR_MEMORY;
1479 char *oldnext_out = (char *)zstr.next_out;
1482 * Update the fields for inflate() to use the new
1483 * buffer, which may be in a location different from
1486 zstr.avail_out += bufsize - oldbufsize;
1487 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1490 * Compare with an uglier method of calculating these values
1491 * that doesn't require the extra oldbufsize variable.
1493 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1494 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1495 assert(zstr.avail_out > 0U);
1501 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1503 log_error(LOG_LEVEL_ERROR,
1504 "Inconsistent stream state after decompression: %s", zstr.msg);
1506 * XXX: Intentionally no return.
1508 * According to zlib.h, Z_STREAM_ERROR is returned
1509 * "if the stream state was inconsistent".
1511 * I assume in this case inflate()'s status
1512 * would also be something different than Z_STREAM_END
1513 * so this check should be redundant, but lets see.
1517 if (status != Z_STREAM_END)
1519 /* We failed to decompress the stream. */
1520 log_error(LOG_LEVEL_ERROR,
1521 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1522 return JB_ERR_COMPRESS;
1526 * Finally, we can actually update the iob, since the
1527 * decompression was successful. First, free the old
1530 freez(csp->iob->buf);
1532 /* Now, update the iob to use the new buffer. */
1533 csp->iob->buf = buf;
1534 csp->iob->cur = csp->iob->buf + skip_size;
1535 csp->iob->eod = (char *)zstr.next_out;
1536 csp->iob->size = bufsize;
1539 * Make sure the new uncompressed iob obeys some minimal
1540 * consistency conditions.
1542 if ((csp->iob->buf < csp->iob->cur)
1543 && (csp->iob->cur <= csp->iob->eod)
1544 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1546 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1547 if (new_size > (size_t)0)
1549 log_error(LOG_LEVEL_RE_FILTER,
1550 "Decompression successful. Old size: %d, new size: %d.",
1551 old_size, new_size);
1555 /* zlib thinks this is OK, so lets do the same. */
1556 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1561 /* It seems that zlib did something weird. */
1562 log_error(LOG_LEVEL_ERROR,
1563 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1564 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1565 csp->iob->eod, csp->iob->buf + csp->iob->size);
1566 return JB_ERR_COMPRESS;
1572 #endif /* defined(FEATURE_ZLIB) */
1575 /*********************************************************************
1577 * Function : string_move
1579 * Description : memmove wrapper to move the last part of a string
1580 * towards the beginning, overwriting the part in
1581 * the middle. strlcpy() can't be used here as the
1585 * 1 : dst = Destination to overwrite
1586 * 2 : src = Source to move.
1590 *********************************************************************/
1591 static void string_move(char *dst, char *src)
1595 /* +1 to copy the terminating nul as well. */
1596 memmove(dst, src, strlen(src)+1);
1600 /*********************************************************************
1602 * Function : normalize_lws
1604 * Description : Reduces unquoted linear white space in headers
1605 * to a single space in accordance with RFC 2616 2.2.
1606 * This simplifies parsing and filtering later on.
1608 * XXX: Remove log messages before
1609 * the next stable release?
1612 * 1 : header = A header with linear white space to reduce.
1616 *********************************************************************/
1617 static void normalize_lws(char *header)
1623 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1627 while (ijb_isspace(*q))
1631 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1632 string_move(p+1, q);
1637 log_error(LOG_LEVEL_HEADER,
1638 "Converting tab to space in '%s'", header);
1643 char *end_of_token = strstr(p+1, "\"");
1645 if (NULL != end_of_token)
1647 /* Don't mess with quoted text. */
1652 log_error(LOG_LEVEL_HEADER,
1653 "Ignoring single quote in '%s'", header);
1659 p = strchr(header, ':');
1660 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1663 * There's still space before the colon.
1666 string_move(p-1, p);
1671 /*********************************************************************
1673 * Function : get_header
1675 * Description : This (odd) routine will parse the csp->iob
1676 * to get the next complete header.
1679 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1681 * Returns : Any one of the following:
1683 * 1) a pointer to a dynamically allocated string that contains a header line
1684 * 2) NULL indicating that the end of the header was reached
1685 * 3) "" indicating that the end of the iob was reached before finding
1686 * a complete header line.
1688 *********************************************************************/
1689 char *get_header(struct iob *iob)
1693 header = get_header_line(iob);
1695 if ((header == NULL) || (*header == '\0'))
1698 * No complete header read yet, tell the client.
1703 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1706 * Header spans multiple lines, append the next one.
1708 char *continued_header;
1710 continued_header = get_header_line(iob);
1711 if ((continued_header == NULL) || (*continued_header == '\0'))
1714 * No complete header read yet, return what we got.
1715 * XXX: Should "unread" header instead.
1717 log_error(LOG_LEVEL_INFO,
1718 "Failed to read a multi-line header properly: '%s'",
1723 if (JB_ERR_OK != string_join(&header, continued_header))
1725 log_error(LOG_LEVEL_FATAL,
1726 "Out of memory while appending multiple headers.");
1730 /* XXX: remove before next stable release. */
1731 log_error(LOG_LEVEL_HEADER,
1732 "Merged multiple header lines to: '%s'",
1737 normalize_lws(header);
1744 /*********************************************************************
1746 * Function : get_header_line
1748 * Description : This (odd) routine will parse the csp->iob
1749 * to get the next header line.
1752 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1754 * Returns : Any one of the following:
1756 * 1) a pointer to a dynamically allocated string that contains a header line
1757 * 2) NULL indicating that the end of the header was reached
1758 * 3) "" indicating that the end of the iob was reached before finding
1759 * a complete header line.
1761 *********************************************************************/
1762 static char *get_header_line(struct iob *iob)
1766 if ((iob->cur == NULL)
1767 || ((p = strchr(iob->cur, '\n')) == NULL))
1769 return(""); /* couldn't find a complete header */
1774 ret = strdup(iob->cur);
1777 /* FIXME No way to handle error properly */
1778 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1780 assert(ret != NULL);
1784 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1786 /* is this a blank line (i.e. the end of the header) ? */
1798 /*********************************************************************
1800 * Function : get_header_value
1802 * Description : Get the value of a given header from a chained list
1803 * of header lines or return NULL if no such header is
1804 * present in the list.
1807 * 1 : header_list = pointer to list
1808 * 2 : header_name = string with name of header to look for.
1809 * Trailing colon required, capitalization
1812 * Returns : NULL if not found, else value of header
1814 *********************************************************************/
1815 char *get_header_value(const struct list *header_list, const char *header_name)
1817 struct list_entry *cur_entry;
1821 assert(header_list);
1822 assert(header_name);
1823 length = strlen(header_name);
1825 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1829 if (!strncmpic(cur_entry->str, header_name, length))
1832 * Found: return pointer to start of value
1834 ret = cur_entry->str + length;
1835 while (*ret && ijb_isspace(*ret)) ret++;
1849 /*********************************************************************
1851 * Function : scan_headers
1853 * Description : Scans headers, applies tags and updates action bits.
1856 * 1 : csp = Current client state (buffers, headers, etc...)
1858 * Returns : JB_ERR_OK
1860 *********************************************************************/
1861 static jb_err scan_headers(struct client_state *csp)
1863 struct list_entry *h; /* Header */
1864 jb_err err = JB_ERR_OK;
1866 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1868 /* Header crunch()ed in previous run? -> ignore */
1869 if (h->str == NULL) continue;
1870 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1871 err = header_tagger(csp, h->str);
1878 /*********************************************************************
1882 * Description : add, delete or modify lines in the HTTP header streams.
1883 * On entry, it receives a linked list of headers space
1884 * that was allocated dynamically (both the list nodes
1885 * and the header contents).
1887 * As a side effect it frees the space used by the original
1891 * 1 : csp = Current client state (buffers, headers, etc...)
1892 * 2 : filter_server_headers = Boolean to switch between
1893 * server and header filtering.
1895 * Returns : JB_ERR_OK in case off success, or
1896 * JB_ERR_MEMORY on out-of-memory error.
1898 *********************************************************************/
1899 jb_err sed(struct client_state *csp, int filter_server_headers)
1901 /* XXX: use more descriptive names. */
1902 struct list_entry *p;
1903 const struct parsers *v;
1904 const add_header_func_ptr *f;
1905 jb_err err = JB_ERR_OK;
1907 if (filter_server_headers)
1909 v = server_patterns;
1910 f = add_server_headers;
1914 v = client_patterns;
1915 f = add_client_headers;
1920 while ((err == JB_ERR_OK) && (v->str != NULL))
1922 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1924 /* Header crunch()ed in previous run? -> ignore */
1925 if (p->str == NULL) continue;
1927 /* Does the current parser handle this header? */
1928 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1929 (v->len == CHECK_EVERY_HEADER_REMAINING))
1931 err = v->parser(csp, &(p->str));
1937 /* place additional headers on the csp->headers list */
1938 while ((err == JB_ERR_OK) && (*f))
1948 /*********************************************************************
1950 * Function : update_server_headers
1952 * Description : Updates server headers after the body has been modified.
1955 * 1 : csp = Current client state (buffers, headers, etc...)
1957 * Returns : JB_ERR_OK in case off success, or
1958 * JB_ERR_MEMORY on out-of-memory error.
1960 *********************************************************************/
1961 jb_err update_server_headers(struct client_state *csp)
1963 jb_err err = JB_ERR_OK;
1965 static const struct parsers server_patterns_light[] = {
1966 { "Content-Length:", 15, server_adjust_content_length },
1967 { "Transfer-Encoding:", 18, server_transfer_coding },
1969 { "Content-Encoding:", 17, server_content_encoding },
1970 #endif /* def FEATURE_ZLIB */
1974 if (strncmpic(csp->http->cmd, "HEAD", 4))
1976 const struct parsers *v;
1977 struct list_entry *p;
1979 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1981 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1983 /* Header crunch()ed in previous run? -> ignore */
1984 if (p->str == NULL) continue;
1986 /* Does the current parser handle this header? */
1987 if (strncmpic(p->str, v->str, v->len) == 0)
1989 err = v->parser(csp, (char **)&(p->str));
1999 /*********************************************************************
2001 * Function : header_tagger
2003 * Description : Executes all text substitutions from applying
2004 * tag actions and saves the result as tag.
2006 * XXX: Shares enough code with filter_header() and
2007 * pcrs_filter_response() to warrant some helper functions.
2010 * 1 : csp = Current client state (buffers, headers, etc...)
2011 * 2 : header = Header that is used as tagger input
2013 * Returns : JB_ERR_OK on success and always succeeds
2015 *********************************************************************/
2016 static jb_err header_tagger(struct client_state *csp, char *header)
2018 int wanted_filter_type;
2019 int multi_action_index;
2023 struct file_list *fl;
2024 struct re_filterfile_spec *b;
2025 struct list_entry *tag_name;
2027 int found_filters = 0;
2028 const size_t header_length = strlen(header);
2030 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2032 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
2033 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
2037 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
2038 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
2041 /* Check if there are any filters */
2042 for (i = 0; i < MAX_AF_FILES; i++)
2055 if (0 == found_filters)
2057 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2058 "tagging enabled, but no taggers available.");
2062 for (i = 0; i < MAX_AF_FILES; i++)
2065 if ((NULL == fl) || (NULL == fl->f))
2068 * Either there are no filter files
2069 * left, or this filter file just
2070 * contains no valid filters.
2072 * Continue to be sure we don't miss
2073 * valid filter files that are chained
2074 * after empty or invalid ones.
2079 /* For all filters, */
2080 for (b = fl->f; b; b = b->next)
2082 if (b->type != wanted_filter_type)
2084 /* skip the ones we don't care about, */
2087 /* leaving only taggers that could apply, of which we use the ones, */
2088 for (tag_name = csp->action->multi[multi_action_index]->first;
2089 NULL != tag_name; tag_name = tag_name->next)
2091 /* that do apply, and */
2092 if (strcmp(b->name, tag_name->str) == 0)
2094 char *modified_tag = NULL;
2096 size_t size = header_length;
2097 pcrs_job *joblist = b->joblist;
2099 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2101 if (NULL == joblist)
2103 log_error(LOG_LEVEL_RE_FILTER,
2104 "Tagger %s has empty joblist. Nothing to do.", b->name);
2108 /* execute their pcrs_joblist on the header. */
2109 for (job = joblist; NULL != job; job = job->next)
2111 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2115 /* Success, continue with the modified version. */
2124 /* Tagger doesn't match */
2127 /* Regex failure, log it but continue anyway. */
2128 assert(NULL != header);
2129 log_error(LOG_LEVEL_ERROR,
2130 "Problems with tagger \'%s\' and header \'%s\': %s",
2131 b->name, *header, pcrs_strerror(hits));
2133 freez(modified_tag);
2137 if (b->dynamic) pcrs_free_joblist(joblist);
2139 /* If this tagger matched */
2145 * There is to technical limitation which makes
2146 * it impossible to use empty tags, but I assume
2147 * no one would do it intentionally.
2150 log_error(LOG_LEVEL_INFO,
2151 "Tagger \'%s\' created an empty tag. Ignored.",
2156 if (!list_contains_item(csp->tags, tag))
2158 if (JB_ERR_OK != enlist(csp->tags, tag))
2160 log_error(LOG_LEVEL_ERROR,
2161 "Insufficient memory to add tag \'%s\', "
2162 "based on tagger \'%s\' and header \'%s\'",
2163 tag, b->name, *header);
2167 char *action_message;
2169 * update the action bits right away, to make
2170 * tagging based on tags set by earlier taggers
2171 * of the same kind possible.
2173 if (update_action_bits_for_tag(csp, tag))
2175 action_message = "Action bits updated accordingly.";
2179 action_message = "No action bits update necessary.";
2182 log_error(LOG_LEVEL_HEADER,
2183 "Tagger \'%s\' added tag \'%s\'. %s",
2184 b->name, tag, action_message);
2189 /* XXX: Is this log-worthy? */
2190 log_error(LOG_LEVEL_HEADER,
2191 "Tagger \'%s\' didn't add tag \'%s\'. "
2192 "Tag already present", b->name, tag);
2195 } /* if the tagger matched */
2196 } /* if the tagger applies */
2197 } /* for every tagger that could apply */
2198 } /* for all filters */
2199 } /* for all filter files */
2204 /* here begins the family of parser functions that reformat header lines */
2206 /*********************************************************************
2208 * Function : filter_header
2210 * Description : Executes all text substitutions from all applying
2211 * +(server|client)-header-filter actions on the header.
2212 * Most of the code was copied from pcrs_filter_response,
2213 * including the rather short variable names
2216 * 1 : csp = Current client state (buffers, headers, etc...)
2217 * 2 : header = On input, pointer to header to modify.
2218 * On output, pointer to the modified header, or NULL
2219 * to remove the header. This function frees the
2220 * original string if necessary.
2222 * Returns : JB_ERR_OK on success and always succeeds
2224 *********************************************************************/
2225 static jb_err filter_header(struct client_state *csp, char **header)
2229 size_t size = strlen(*header);
2231 char *newheader = NULL;
2234 struct file_list *fl;
2235 struct re_filterfile_spec *b;
2236 struct list_entry *filtername;
2238 int i, found_filters = 0;
2239 int wanted_filter_type;
2240 int multi_action_index;
2242 if (csp->flags & CSP_FLAG_NO_FILTERING)
2247 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2249 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2250 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2254 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2255 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2259 * Need to check the set of re_filterfiles...
2261 for (i = 0; i < MAX_AF_FILES; i++)
2274 if (0 == found_filters)
2276 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2277 "header filtering enabled, but no matching filters available.");
2281 for (i = 0; i < MAX_AF_FILES; i++)
2284 if ((NULL == fl) || (NULL == fl->f))
2287 * Either there are no filter files
2288 * left, or this filter file just
2289 * contains no valid filters.
2291 * Continue to be sure we don't miss
2292 * valid filter files that are chained
2293 * after empty or invalid ones.
2298 * For all applying +filter actions, look if a filter by that
2299 * name exists and if yes, execute its pcrs_joblist on the
2302 for (b = fl->f; b; b = b->next)
2304 if (b->type != wanted_filter_type)
2306 /* Skip other filter types */
2310 for (filtername = csp->action->multi[multi_action_index]->first;
2311 filtername ; filtername = filtername->next)
2313 if (strcmp(b->name, filtername->str) == 0)
2315 int current_hits = 0;
2316 pcrs_job *joblist = b->joblist;
2318 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2320 if (NULL == joblist)
2322 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2326 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2327 *header, size, b->name);
2329 /* Apply all jobs from the joblist */
2330 for (job = joblist; NULL != job; job = job->next)
2332 matches = pcrs_execute(job, *header, size, &newheader, &size);
2335 current_hits += matches;
2336 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2338 *header = newheader;
2340 else if ( 0 == matches )
2342 /* Filter doesn't change header */
2348 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2349 *header, b->name, pcrs_strerror(matches));
2350 if (newheader != NULL)
2352 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2358 if (b->dynamic) pcrs_free_joblist(joblist);
2360 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2361 hits += current_hits;
2368 * Additionally checking for hits is important because if
2369 * the continue hack is triggered, server headers can
2370 * arrive empty to separate multiple heads from each other.
2372 if ((0 == size) && hits)
2374 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2382 /*********************************************************************
2384 * Function : server_connection
2386 * Description : Makes sure a proper "Connection:" header is
2387 * set and signals connection_header_adder to
2391 * 1 : csp = Current client state (buffers, headers, etc...)
2392 * 2 : header = On input, pointer to header to modify.
2393 * On output, pointer to the modified header, or NULL
2394 * to remove the header. This function frees the
2395 * original string if necessary.
2397 * Returns : JB_ERR_OK on success, or
2398 * JB_ERR_MEMORY on out-of-memory error.
2400 *********************************************************************/
2401 static jb_err server_connection(struct client_state *csp, char **header)
2403 /* Do we have a 'Connection: close' header? */
2404 if (strcmpic(*header, "Connection: close"))
2406 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2407 if ((csp->config->feature_flags &
2408 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2409 && !strcmpic(*header, "Connection: keep-alive"))
2411 /* Remember to keep the connection alive. */
2412 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
2414 log_error(LOG_LEVEL_HEADER,
2415 "Keeping the server header '%s' around.", *header);
2417 char *old_header = *header;
2419 *header = strdup("Connection: close");
2422 return JB_ERR_MEMORY;
2424 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2426 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2429 /* Signal server_connection_adder() to return early. */
2430 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
2435 /*********************************************************************
2437 * Function : client_connection
2439 * Description : Makes sure a proper "Connection:" header is
2440 * set and signals connection_header_adder
2444 * 1 : csp = Current client state (buffers, headers, etc...)
2445 * 2 : header = On input, pointer to header to modify.
2446 * On output, pointer to the modified header, or NULL
2447 * to remove the header. This function frees the
2448 * original string if necessary.
2450 * Returns : JB_ERR_OK on success, or
2451 * JB_ERR_MEMORY on out-of-memory error.
2453 *********************************************************************/
2454 static jb_err client_connection(struct client_state *csp, char **header)
2456 const char *wanted_header = get_appropiate_connection_header(csp);
2458 if (strcmpic(*header, wanted_header))
2460 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2461 log_error(LOG_LEVEL_HEADER,
2462 "Keeping the client header '%s' around. "
2463 "The connection will not be kept alive.",
2466 char *old_header = *header;
2468 *header = strdup(wanted_header);
2471 return JB_ERR_MEMORY;
2473 log_error(LOG_LEVEL_HEADER,
2474 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2476 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2478 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2481 log_error(LOG_LEVEL_HEADER,
2482 "Keeping the client header '%s' around. "
2483 "The server connection will be kept alive if possible.",
2485 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2487 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2489 /* Signal client_connection_adder() to return early. */
2490 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2496 /*********************************************************************
2498 * Function : crumble
2500 * Description : This is called if a header matches a pattern to "crunch"
2503 * 1 : csp = Current client state (buffers, headers, etc...)
2504 * 2 : header = On input, pointer to header to modify.
2505 * On output, pointer to the modified header, or NULL
2506 * to remove the header. This function frees the
2507 * original string if necessary.
2509 * Returns : JB_ERR_OK on success, or
2510 * JB_ERR_MEMORY on out-of-memory error.
2512 *********************************************************************/
2513 static jb_err crumble(struct client_state *csp, char **header)
2516 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2522 /*********************************************************************
2524 * Function : crunch_server_header
2526 * Description : Crunch server header if it matches a string supplied by the
2527 * user. Called from `sed'.
2530 * 1 : csp = Current client state (buffers, headers, etc...)
2531 * 2 : header = On input, pointer to header to modify.
2532 * On output, pointer to the modified header, or NULL
2533 * to remove the header. This function frees the
2534 * original string if necessary.
2536 * Returns : JB_ERR_OK on success and always succeeds
2538 *********************************************************************/
2539 static jb_err crunch_server_header(struct client_state *csp, char **header)
2541 const char *crunch_pattern;
2543 /* Do we feel like crunching? */
2544 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2546 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2548 /* Is the current header the lucky one? */
2549 if (strstr(*header, crunch_pattern))
2551 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2560 /*********************************************************************
2562 * Function : server_content_type
2564 * Description : Set the content-type for filterable types (text/.*,
2565 * .*xml.*, javascript and image/gif) unless filtering has been
2566 * forbidden (CT_TABOO) while parsing earlier headers.
2567 * NOTE: Since text/plain is commonly used by web servers
2568 * for files whose correct type is unknown, we don't
2569 * set CT_TEXT for it.
2572 * 1 : csp = Current client state (buffers, headers, etc...)
2573 * 2 : header = On input, pointer to header to modify.
2574 * On output, pointer to the modified header, or NULL
2575 * to remove the header. This function frees the
2576 * original string if necessary.
2578 * Returns : JB_ERR_OK on success, or
2579 * JB_ERR_MEMORY on out-of-memory error.
2581 *********************************************************************/
2582 static jb_err server_content_type(struct client_state *csp, char **header)
2584 /* Remove header if it isn't the first Content-Type header */
2585 if ((csp->content_type & CT_DECLARED))
2588 * Another, slightly slower, way to see if
2589 * we already parsed another Content-Type header.
2591 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2593 log_error(LOG_LEVEL_ERROR,
2594 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2602 * Signal that the Content-Type has been set.
2604 csp->content_type |= CT_DECLARED;
2606 if (!(csp->content_type & CT_TABOO))
2609 * XXX: The assumption that text/plain is a sign of
2610 * binary data seems to be somewhat unreasonable nowadays
2611 * and should be dropped after 3.0.8 is out.
2613 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2614 || strstr(*header, "xml")
2615 || strstr(*header, "application/x-javascript"))
2617 csp->content_type |= CT_TEXT;
2619 else if (strstr(*header, "image/gif"))
2621 csp->content_type |= CT_GIF;
2626 * Are we messing with the content type?
2628 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2631 * Make sure the user doesn't accidently
2632 * change the content type of binary documents.
2634 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2637 *header = strdup("Content-Type: ");
2638 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2642 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2643 return JB_ERR_MEMORY;
2645 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2649 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2650 "It doesn't look like a content type that should be filtered. "
2651 "Enable force-text-mode if you know what you're doing.", *header);
2659 /*********************************************************************
2661 * Function : server_transfer_coding
2663 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2664 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2665 * - Remove header if body was chunked but has been
2666 * de-chunked for filtering.
2669 * 1 : csp = Current client state (buffers, headers, etc...)
2670 * 2 : header = On input, pointer to header to modify.
2671 * On output, pointer to the modified header, or NULL
2672 * to remove the header. This function frees the
2673 * original string if necessary.
2675 * Returns : JB_ERR_OK on success, or
2676 * JB_ERR_MEMORY on out-of-memory error.
2678 *********************************************************************/
2679 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2682 * Turn off pcrs and gif filtering if body compressed
2684 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2688 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2690 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2691 csp->http->cmd, *header);
2692 #endif /* def FEATURE_ZLIB */
2693 csp->content_type = CT_TABOO;
2697 * Raise flag if body chunked
2699 if (strstr(*header, "chunked"))
2701 csp->flags |= CSP_FLAG_CHUNKED;
2704 * If the body was modified, it has been de-chunked first
2705 * and the header must be removed.
2707 * FIXME: If there is more than one transfer encoding,
2708 * only the "chunked" part should be removed here.
2710 if (csp->flags & CSP_FLAG_MODIFIED)
2712 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2721 /*********************************************************************
2723 * Function : server_content_encoding
2725 * Description : This function is run twice for each request,
2726 * unless FEATURE_ZLIB and filtering are disabled.
2728 * The first run is used to check if the content
2729 * is compressed, if FEATURE_ZLIB is disabled
2730 * filtering is then disabled as well, if FEATURE_ZLIB
2731 * is enabled the content is marked for decompression.
2733 * The second run is used to remove the Content-Encoding
2734 * header if the decompression was successful.
2737 * 1 : csp = Current client state (buffers, headers, etc...)
2738 * 2 : header = On input, pointer to header to modify.
2739 * On output, pointer to the modified header, or NULL
2740 * to remove the header. This function frees the
2741 * original string if necessary.
2743 * Returns : JB_ERR_OK on success, or
2744 * JB_ERR_MEMORY on out-of-memory error.
2746 *********************************************************************/
2747 static jb_err server_content_encoding(struct client_state *csp, char **header)
2750 if ((csp->flags & CSP_FLAG_MODIFIED)
2751 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2754 * We successfully decompressed the content,
2755 * and have to clean the header now, so the
2756 * client no longer expects compressed data..
2758 * XXX: There is a difference between cleaning
2759 * and removing it completely.
2761 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2764 else if (strstr(*header, "gzip"))
2766 /* Mark for gzip decompression */
2767 csp->content_type |= CT_GZIP;
2769 else if (strstr(*header, "deflate"))
2771 /* Mark for zlib decompression */
2772 csp->content_type |= CT_DEFLATE;
2774 else if (strstr(*header, "compress"))
2777 * We can't decompress this; therefore we can't filter
2780 csp->content_type |= CT_TABOO;
2782 #else /* !defined(FEATURE_ZLIB) */
2783 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2786 * Body is compressed, turn off pcrs and gif filtering.
2788 csp->content_type |= CT_TABOO;
2791 * Log a warning if the user expects the content to be filtered.
2793 if ((csp->rlist != NULL) &&
2794 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2796 log_error(LOG_LEVEL_INFO,
2797 "Compressed content detected, content filtering disabled. "
2798 "Consider recompiling Privoxy with zlib support or "
2799 "enable the prevent-compression action.");
2802 #endif /* defined(FEATURE_ZLIB) */
2809 /*********************************************************************
2811 * Function : server_adjust_content_length
2813 * Description : Adjust Content-Length header if we modified
2817 * 1 : csp = Current client state (buffers, headers, etc...)
2818 * 2 : header = On input, pointer to header to modify.
2819 * On output, pointer to the modified header, or NULL
2820 * to remove the header. This function frees the
2821 * original string if necessary.
2823 * Returns : JB_ERR_OK on success, or
2824 * JB_ERR_MEMORY on out-of-memory error.
2826 *********************************************************************/
2827 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2829 const size_t max_header_length = 80;
2831 /* Regenerate header if the content was modified. */
2832 if (csp->flags & CSP_FLAG_MODIFIED)
2835 *header = (char *) zalloc(max_header_length);
2836 if (*header == NULL)
2838 return JB_ERR_MEMORY;
2841 snprintf(*header, max_header_length, "Content-Length: %d",
2842 (int)csp->content_length);
2843 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2844 (int)csp->content_length);
2851 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2852 /*********************************************************************
2854 * Function : server_save_content_length
2856 * Description : Save the Content-Length sent by the server.
2859 * 1 : csp = Current client state (buffers, headers, etc...)
2860 * 2 : header = On input, pointer to header to modify.
2861 * On output, pointer to the modified header, or NULL
2862 * to remove the header. This function frees the
2863 * original string if necessary.
2865 * Returns : JB_ERR_OK on success, or
2866 * JB_ERR_MEMORY on out-of-memory error.
2868 *********************************************************************/
2869 static jb_err server_save_content_length(struct client_state *csp, char **header)
2871 unsigned long long content_length = 0;
2873 assert(*(*header+14) == ':');
2875 if (1 != sscanf(*header+14, ": %llu", &content_length))
2877 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2882 csp->expected_content_length = content_length;
2883 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2888 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2891 /*********************************************************************
2893 * Function : server_content_md5
2895 * Description : Crumble any Content-MD5 headers if the document was
2896 * modified. FIXME: Should we re-compute instead?
2899 * 1 : csp = Current client state (buffers, headers, etc...)
2900 * 2 : header = On input, pointer to header to modify.
2901 * On output, pointer to the modified header, or NULL
2902 * to remove the header. This function frees the
2903 * original string if necessary.
2905 * Returns : JB_ERR_OK on success, or
2906 * JB_ERR_MEMORY on out-of-memory error.
2908 *********************************************************************/
2909 static jb_err server_content_md5(struct client_state *csp, char **header)
2911 if (csp->flags & CSP_FLAG_MODIFIED)
2913 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2921 /*********************************************************************
2923 * Function : server_content_disposition
2925 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2926 * Called from `sed'.
2929 * 1 : csp = Current client state (buffers, headers, etc...)
2930 * 2 : header = On input, pointer to header to modify.
2931 * On output, pointer to the modified header, or NULL
2932 * to remove the header. This function frees the
2933 * original string if necessary.
2935 * Returns : JB_ERR_OK on success, or
2936 * JB_ERR_MEMORY on out-of-memory error.
2938 *********************************************************************/
2939 static jb_err server_content_disposition(struct client_state *csp, char **header)
2944 * Are we messing with the Content-Disposition header?
2946 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2952 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2954 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2957 * Blocking content-disposition header
2959 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2966 * Replacing Content-Disposition header
2969 *header = strdup("Content-Disposition: ");
2970 string_append(header, newval);
2972 if (*header != NULL)
2974 log_error(LOG_LEVEL_HEADER,
2975 "Content-Disposition header crunched and replaced with: %s", *header);
2978 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2982 /*********************************************************************
2984 * Function : server_last_modified
2986 * Description : Changes Last-Modified header to the actual date
2987 * to help hide-if-modified-since.
2988 * Called from `sed'.
2991 * 1 : csp = Current client state (buffers, headers, etc...)
2992 * 2 : header = On input, pointer to header to modify.
2993 * On output, pointer to the modified header, or NULL
2994 * to remove the header. This function frees the
2995 * original string if necessary.
2997 * Returns : JB_ERR_OK on success, or
2998 * JB_ERR_MEMORY on out-of-memory error.
3000 *********************************************************************/
3001 static jb_err server_last_modified(struct client_state *csp, char **header)
3004 char buf[BUFFER_SIZE];
3007 #ifdef HAVE_GMTIME_R
3010 struct tm *timeptr = NULL;
3011 time_t now, last_modified;
3013 long int days, hours, minutes, seconds;
3016 * Are we messing with the Last-Modified header?
3018 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
3024 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
3026 if (0 == strcmpic(newval, "block") )
3029 * Blocking Last-Modified header. Useless but why not.
3031 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
3035 else if (0 == strcmpic(newval, "reset-to-request-time"))
3038 * Setting Last-Modified Header to now.
3040 get_http_time(0, buf, sizeof(buf));
3042 *header = strdup("Last-Modified: ");
3043 string_append(header, buf);
3045 if (*header == NULL)
3047 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
3051 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
3054 else if (0 == strcmpic(newval, "randomize"))
3056 const char *header_time = *header + sizeof("Last-Modified:");
3058 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
3060 #ifdef HAVE_GMTIME_R
3061 timeptr = gmtime_r(&now, &gmt);
3062 #elif FEATURE_PTHREAD
3063 privoxy_mutex_lock(&gmtime_mutex);
3064 timeptr = gmtime(&now);
3065 privoxy_mutex_unlock(&gmtime_mutex);
3067 timeptr = gmtime(&now);
3069 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
3071 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3076 rtime = (long int)difftime(now, last_modified);
3085 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
3087 rtime = pick_from_range(rtime);
3088 if (negative) rtime *= -1;
3089 last_modified += rtime;
3090 #ifdef HAVE_GMTIME_R
3091 timeptr = gmtime_r(&last_modified, &gmt);
3092 #elif FEATURE_PTHREAD
3093 privoxy_mutex_lock(&gmtime_mutex);
3094 timeptr = gmtime(&last_modified);
3095 privoxy_mutex_unlock(&gmtime_mutex);
3097 timeptr = gmtime(&last_modified);
3099 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3101 *header = strdup("Last-Modified: ");
3102 string_append(header, newheader);
3104 if (*header == NULL)
3106 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
3107 return JB_ERR_MEMORY;
3110 days = rtime / (3600 * 24);
3111 hours = rtime / 3600 % 24;
3112 minutes = rtime / 60 % 60;
3113 seconds = rtime % 60;
3115 log_error(LOG_LEVEL_HEADER,
3116 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
3117 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
3118 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3122 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
3131 /*********************************************************************
3133 * Function : client_accept_encoding
3135 * Description : Rewrite the client's Accept-Encoding header so that
3136 * if doesn't allow compression, if the action applies.
3137 * Note: For HTTP/1.0 the absence of the header is enough.
3140 * 1 : csp = Current client state (buffers, headers, etc...)
3141 * 2 : header = On input, pointer to header to modify.
3142 * On output, pointer to the modified header, or NULL
3143 * to remove the header. This function frees the
3144 * original string if necessary.
3146 * Returns : JB_ERR_OK on success, or
3147 * JB_ERR_MEMORY on out-of-memory error.
3149 *********************************************************************/
3150 static jb_err client_accept_encoding(struct client_state *csp, char **header)
3152 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3154 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
3158 /* Temporarily disable the correct behaviour to
3159 * work around a PHP bug.
3161 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
3163 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
3164 * if (*header == NULL)
3166 * return JB_ERR_MEMORY;
3177 /*********************************************************************
3179 * Function : client_te
3181 * Description : Rewrite the client's TE header so that
3182 * if doesn't allow compression, if the action applies.
3185 * 1 : csp = Current client state (buffers, headers, etc...)
3186 * 2 : header = On input, pointer to header to modify.
3187 * On output, pointer to the modified header, or NULL
3188 * to remove the header. This function frees the
3189 * original string if necessary.
3191 * Returns : JB_ERR_OK on success, or
3192 * JB_ERR_MEMORY on out-of-memory error.
3194 *********************************************************************/
3195 static jb_err client_te(struct client_state *csp, char **header)
3197 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3200 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3207 /*********************************************************************
3209 * Function : client_referrer
3211 * Description : Handle the "referer" config setting properly.
3212 * Called from `sed'.
3215 * 1 : csp = Current client state (buffers, headers, etc...)
3216 * 2 : header = On input, pointer to header to modify.
3217 * On output, pointer to the modified header, or NULL
3218 * to remove the header. This function frees the
3219 * original string if necessary.
3221 * Returns : JB_ERR_OK on success, or
3222 * JB_ERR_MEMORY on out-of-memory error.
3224 *********************************************************************/
3225 static jb_err client_referrer(struct client_state *csp, char **header)
3227 const char *parameter;
3228 /* booleans for parameters we have to check multiple times */
3229 int parameter_conditional_block;
3230 int parameter_conditional_forge;
3232 #ifdef FEATURE_FORCE_LOAD
3234 * Since the referrer can include the prefix even
3235 * if the request itself is non-forced, we must
3236 * clean it unconditionally.
3238 * XXX: strclean is too broad
3240 strclean(*header, FORCE_PREFIX);
3241 #endif /* def FEATURE_FORCE_LOAD */
3243 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3245 /* Nothing left to do */
3249 parameter = csp->action->string[ACTION_STRING_REFERER];
3250 assert(parameter != NULL);
3251 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3252 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3254 if (!parameter_conditional_block && !parameter_conditional_forge)
3257 * As conditional-block and conditional-forge are the only
3258 * parameters that rely on the original referrer, we can
3259 * remove it now for all the others.
3264 if (0 == strcmpic(parameter, "block"))
3266 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3269 else if (parameter_conditional_block || parameter_conditional_forge)
3271 return handle_conditional_hide_referrer_parameter(header,
3272 csp->http->hostport, parameter_conditional_block);
3274 else if (0 == strcmpic(parameter, "forge"))
3276 return create_forged_referrer(header, csp->http->hostport);
3280 /* interpret parameter as user-supplied referer to fake */
3281 return create_fake_referrer(header, parameter);
3286 /*********************************************************************
3288 * Function : client_accept_language
3290 * Description : Handle the "Accept-Language" config setting properly.
3291 * Called from `sed'.
3294 * 1 : csp = Current client state (buffers, headers, etc...)
3295 * 2 : header = On input, pointer to header to modify.
3296 * On output, pointer to the modified header, or NULL
3297 * to remove the header. This function frees the
3298 * original string if necessary.
3300 * Returns : JB_ERR_OK on success, or
3301 * JB_ERR_MEMORY on out-of-memory error.
3303 *********************************************************************/
3304 static jb_err client_accept_language(struct client_state *csp, char **header)
3309 * Are we messing with the Accept-Language?
3311 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3313 /*I don't think so*/
3317 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3319 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3322 * Blocking Accept-Language header
3324 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3331 * Replacing Accept-Language header
3334 *header = strdup("Accept-Language: ");
3335 string_append(header, newval);
3337 if (*header == NULL)
3339 log_error(LOG_LEVEL_ERROR,
3340 "Insufficient memory. Accept-Language header crunched without replacement.");
3344 log_error(LOG_LEVEL_HEADER,
3345 "Accept-Language header crunched and replaced with: %s", *header);
3348 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3352 /*********************************************************************
3354 * Function : crunch_client_header
3356 * Description : Crunch client header if it matches a string supplied by the
3357 * user. Called from `sed'.
3360 * 1 : csp = Current client state (buffers, headers, etc...)
3361 * 2 : header = On input, pointer to header to modify.
3362 * On output, pointer to the modified header, or NULL
3363 * to remove the header. This function frees the
3364 * original string if necessary.
3366 * Returns : JB_ERR_OK on success and always succeeds
3368 *********************************************************************/
3369 static jb_err crunch_client_header(struct client_state *csp, char **header)
3371 const char *crunch_pattern;
3373 /* Do we feel like crunching? */
3374 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3376 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3378 /* Is the current header the lucky one? */
3379 if (strstr(*header, crunch_pattern))
3381 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3389 /*********************************************************************
3391 * Function : client_uagent
3393 * Description : Handle the "user-agent" config setting properly
3394 * and remember its original value to enable browser
3395 * bug workarounds. Called from `sed'.
3398 * 1 : csp = Current client state (buffers, headers, etc...)
3399 * 2 : header = On input, pointer to header to modify.
3400 * On output, pointer to the modified header, or NULL
3401 * to remove the header. This function frees the
3402 * original string if necessary.
3404 * Returns : JB_ERR_OK on success, or
3405 * JB_ERR_MEMORY on out-of-memory error.
3407 *********************************************************************/
3408 static jb_err client_uagent(struct client_state *csp, char **header)
3412 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3417 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3424 *header = strdup("User-Agent: ");
3425 string_append(header, newval);
3427 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3429 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3433 /*********************************************************************
3435 * Function : client_ua
3437 * Description : Handle "ua-" headers properly. Called from `sed'.
3440 * 1 : csp = Current client state (buffers, headers, etc...)
3441 * 2 : header = On input, pointer to header to modify.
3442 * On output, pointer to the modified header, or NULL
3443 * to remove the header. This function frees the
3444 * original string if necessary.
3446 * Returns : JB_ERR_OK on success, or
3447 * JB_ERR_MEMORY on out-of-memory error.
3449 *********************************************************************/
3450 static jb_err client_ua(struct client_state *csp, char **header)
3452 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3454 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3462 /*********************************************************************
3464 * Function : client_from
3466 * Description : Handle the "from" config setting properly.
3467 * Called from `sed'.
3470 * 1 : csp = Current client state (buffers, headers, etc...)
3471 * 2 : header = On input, pointer to header to modify.
3472 * On output, pointer to the modified header, or NULL
3473 * to remove the header. This function frees the
3474 * original string if necessary.
3476 * Returns : JB_ERR_OK on success, or
3477 * JB_ERR_MEMORY on out-of-memory error.
3479 *********************************************************************/
3480 static jb_err client_from(struct client_state *csp, char **header)
3484 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3491 newval = csp->action->string[ACTION_STRING_FROM];
3494 * Are we blocking the e-mail address?
3496 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3498 log_error(LOG_LEVEL_HEADER, "crunched From!");
3502 log_error(LOG_LEVEL_HEADER, " modified");
3504 *header = strdup("From: ");
3505 string_append(header, newval);
3507 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3511 /*********************************************************************
3513 * Function : client_send_cookie
3515 * Description : Crunches the "cookie" header if necessary.
3516 * Called from `sed'.
3518 * XXX: Stupid name, doesn't send squat.
3521 * 1 : csp = Current client state (buffers, headers, etc...)
3522 * 2 : header = On input, pointer to header to modify.
3523 * On output, pointer to the modified header, or NULL
3524 * to remove the header. This function frees the
3525 * original string if necessary.
3527 * Returns : JB_ERR_OK on success, or
3528 * JB_ERR_MEMORY on out-of-memory error.
3530 *********************************************************************/
3531 static jb_err client_send_cookie(struct client_state *csp, char **header)
3533 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3535 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3543 /*********************************************************************
3545 * Function : client_x_forwarded
3547 * Description : Handle the "x-forwarded-for" config setting properly,
3548 * also used in the add_client_headers list. Called from `sed'.
3551 * 1 : csp = Current client state (buffers, headers, etc...)
3552 * 2 : header = On input, pointer to header to modify.
3553 * On output, pointer to the modified header, or NULL
3554 * to remove the header. This function frees the
3555 * original string if necessary.
3557 * Returns : JB_ERR_OK on success, or
3558 * JB_ERR_MEMORY on out-of-memory error.
3560 *********************************************************************/
3561 jb_err client_x_forwarded(struct client_state *csp, char **header)
3563 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3565 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3567 if (0 == strcmpic(parameter, "block"))
3570 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3572 else if (0 == strcmpic(parameter, "add"))
3574 string_append(header, ", ");
3575 string_append(header, csp->ip_addr_str);
3577 if (*header == NULL)
3579 return JB_ERR_MEMORY;
3581 log_error(LOG_LEVEL_HEADER,
3582 "Appended client IP address to %s", *header);
3583 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3587 log_error(LOG_LEVEL_FATAL,
3588 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3596 /*********************************************************************
3598 * Function : client_max_forwards
3600 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3601 * from the value of the Max-Forwards header field.
3604 * 1 : csp = Current client state (buffers, headers, etc...)
3605 * 2 : header = On input, pointer to header to modify.
3606 * On output, pointer to the modified header, or NULL
3607 * to remove the header. This function frees the
3608 * original string if necessary.
3610 * Returns : JB_ERR_OK on success, or
3611 * JB_ERR_MEMORY on out-of-memory error.
3613 *********************************************************************/
3614 static jb_err client_max_forwards(struct client_state *csp, char **header)
3618 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3619 (0 == strcmpic(csp->http->gpc, "options")))
3621 assert(*(*header+12) == ':');
3622 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3624 if (max_forwards > 0)
3626 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3627 log_error(LOG_LEVEL_HEADER,
3628 "Max-Forwards value for %s request reduced to %d.",
3629 csp->http->gpc, max_forwards);
3631 else if (max_forwards < 0)
3633 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3639 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3648 /*********************************************************************
3650 * Function : client_host
3652 * Description : If the request URI did not contain host and
3653 * port information, parse and evaluate the Host
3656 * Also, kill ill-formed HOST: headers as sent by
3657 * Apple's iTunes software when used with a proxy.
3660 * 1 : csp = Current client state (buffers, headers, etc...)
3661 * 2 : header = On input, pointer to header to modify.
3662 * On output, pointer to the modified header, or NULL
3663 * to remove the header. This function frees the
3664 * original string if necessary.
3666 * Returns : JB_ERR_OK on success, or
3667 * JB_ERR_MEMORY on out-of-memory error.
3669 *********************************************************************/
3670 static jb_err client_host(struct client_state *csp, char **header)
3675 * If the header field name is all upper-case, chances are that it's
3676 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3677 * not a problem -- they are regenerated later.
3679 if ((*header)[1] == 'O')
3681 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3686 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3687 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3690 if (NULL == (p = strdup((*header)+6)))
3692 return JB_ERR_MEMORY;
3695 if (NULL == (q = strdup(p)))
3698 return JB_ERR_MEMORY;
3701 freez(csp->http->hostport);
3702 csp->http->hostport = p;
3703 freez(csp->http->host);
3704 csp->http->host = q;
3705 q = strchr(csp->http->host, ':');
3708 /* Terminate hostname and evaluate port string */
3710 csp->http->port = atoi(q);
3714 csp->http->port = csp->http->ssl ? 443 : 80;
3717 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3718 csp->http->hostport, csp->http->host, csp->http->port);
3721 /* Signal client_host_adder() to return right away */
3722 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3728 /*********************************************************************
3730 * Function : client_if_modified_since
3732 * Description : Remove or modify the If-Modified-Since header.
3735 * 1 : csp = Current client state (buffers, headers, etc...)
3736 * 2 : header = On input, pointer to header to modify.
3737 * On output, pointer to the modified header, or NULL
3738 * to remove the header. This function frees the
3739 * original string if necessary.
3741 * Returns : JB_ERR_OK on success, or
3742 * JB_ERR_MEMORY on out-of-memory error.
3744 *********************************************************************/
3745 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3748 #ifdef HAVE_GMTIME_R
3751 struct tm *timeptr = NULL;
3755 long int hours, minutes, seconds;
3759 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3762 * The client got an error message because of a temporary problem,
3763 * the problem is gone and the client now tries to revalidate our
3764 * error message on the real server. The revalidation would always
3765 * end with the transmission of the whole document and there is
3766 * no need to expose the bogus If-Modified-Since header.
3768 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3771 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3773 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3775 if ((0 == strcmpic(newval, "block")))
3777 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3780 else /* add random value */
3782 const char *header_time = *header + sizeof("If-Modified-Since:");
3784 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3786 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3791 rtime = strtol(newval, &endptr, 0);
3794 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3795 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3802 rtime = pick_from_range(rtime);
3806 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3809 tm += rtime * (negative ? -1 : 1);
3810 #ifdef HAVE_GMTIME_R
3811 timeptr = gmtime_r(&tm, &gmt);
3812 #elif FEATURE_PTHREAD
3813 privoxy_mutex_lock(&gmtime_mutex);
3814 timeptr = gmtime(&tm);
3815 privoxy_mutex_unlock(&gmtime_mutex);
3817 timeptr = gmtime(&tm);
3819 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3822 *header = strdup("If-Modified-Since: ");
3823 string_append(header, newheader);
3825 if (*header == NULL)
3827 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3828 return JB_ERR_MEMORY;
3831 hours = rtime / 3600;
3832 minutes = rtime / 60 % 60;
3833 seconds = rtime % 60;
3835 log_error(LOG_LEVEL_HEADER,
3836 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3837 *header, (negative) ? "subtracted" : "added", hours,
3838 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3839 seconds, (seconds == 1) ? ")" : "s)");
3848 /*********************************************************************
3850 * Function : client_if_none_match
3852 * Description : Remove the If-None-Match header.
3855 * 1 : csp = Current client state (buffers, headers, etc...)
3856 * 2 : header = On input, pointer to header to modify.
3857 * On output, pointer to the modified header, or NULL
3858 * to remove the header. This function frees the
3859 * original string if necessary.
3861 * Returns : JB_ERR_OK on success, or
3862 * JB_ERR_MEMORY on out-of-memory error.
3864 *********************************************************************/
3865 static jb_err client_if_none_match(struct client_state *csp, char **header)
3867 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3869 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3877 /*********************************************************************
3879 * Function : client_x_filter
3881 * Description : Disables filtering if the client set "X-Filter: No".
3882 * Called from `sed'.
3885 * 1 : csp = Current client state (buffers, headers, etc...)
3886 * 2 : header = On input, pointer to header to modify.
3887 * On output, pointer to the modified header, or NULL
3888 * to remove the header. This function frees the
3889 * original string if necessary.
3891 * Returns : JB_ERR_OK on success
3893 *********************************************************************/
3894 jb_err client_x_filter(struct client_state *csp, char **header)
3896 if ( 0 == strcmpic(*header, "X-Filter: No"))
3898 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3900 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3904 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3906 log_error(LOG_LEVEL_HEADER,
3907 "force-text-mode overruled the client's request to fetch without filtering!");
3911 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3912 csp->flags |= CSP_FLAG_NO_FILTERING;
3913 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3915 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3923 /*********************************************************************
3925 * Function : client_range
3927 * Description : Removes Range, Request-Range and If-Range headers if
3928 * content filtering is enabled. If the client's version
3929 * of the document has been altered by Privoxy, the server
3930 * could interpret the range differently than the client
3931 * intended in which case the user could end up with
3932 * corrupted content.
3935 * 1 : csp = Current client state (buffers, headers, etc...)
3936 * 2 : header = On input, pointer to header to modify.
3937 * On output, pointer to the modified header, or NULL
3938 * to remove the header. This function frees the
3939 * original string if necessary.
3941 * Returns : JB_ERR_OK
3943 *********************************************************************/
3944 static jb_err client_range(struct client_state *csp, char **header)
3946 if (content_filters_enabled(csp->action))
3948 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3949 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3956 /* the following functions add headers directly to the header list */
3958 /*********************************************************************
3960 * Function : client_host_adder
3962 * Description : Adds the Host: header field if it is missing.
3963 * Called from `sed'.
3966 * 1 : csp = Current client state (buffers, headers, etc...)
3968 * Returns : JB_ERR_OK on success, or
3969 * JB_ERR_MEMORY on out-of-memory error.
3971 *********************************************************************/
3972 static jb_err client_host_adder(struct client_state *csp)
3977 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3979 /* Header already set by the client, nothing to do. */
3983 if ( !csp->http->hostport || !*(csp->http->hostport))
3985 /* XXX: When does this happen and why is it OK? */
3986 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3991 * remove 'user:pass@' from 'proto://user:pass@host'
3993 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3999 p = csp->http->hostport;
4002 /* XXX: Just add it, we already made sure that it will be unique */
4003 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
4004 err = enlist_unique_header(csp->headers, "Host", p);
4011 /*********************************************************************
4013 * Function : client_accept_encoding_adder
4015 * Description : Add an Accept-Encoding header to the client's request
4016 * that disables compression if the action applies, and
4017 * the header is not already there. Called from `sed'.
4018 * Note: For HTTP/1.0, the absence of the header is enough.
4021 * 1 : csp = Current client state (buffers, headers, etc...)
4023 * Returns : JB_ERR_OK on success, or
4024 * JB_ERR_MEMORY on out-of-memory error.
4026 *********************************************************************/
4027 static jb_err client_accept_encoding_adder(struct client_state *csp)
4029 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
4030 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
4032 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
4040 /*********************************************************************
4042 * Function : client_xtra_adder
4044 * Description : Used in the add_client_headers list. Called from `sed'.
4047 * 1 : csp = Current client state (buffers, headers, etc...)
4049 * Returns : JB_ERR_OK on success, or
4050 * JB_ERR_MEMORY on out-of-memory error.
4052 *********************************************************************/
4053 static jb_err client_xtra_adder(struct client_state *csp)
4055 struct list_entry *lst;
4058 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
4059 lst ; lst = lst->next)
4061 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
4062 err = enlist(csp->headers, lst->str);
4074 /*********************************************************************
4076 * Function : client_x_forwarded_for_adder
4078 * Description : Used in the add_client_headers list. Called from `sed'.
4081 * 1 : csp = Current client state (buffers, headers, etc...)
4083 * Returns : JB_ERR_OK on success, or
4084 * JB_ERR_MEMORY on out-of-memory error.
4086 *********************************************************************/
4087 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
4089 char *header = NULL;
4092 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
4093 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
4094 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
4097 * If we aren't adding X-Forwarded-For headers,
4098 * or we already appended an existing X-Forwarded-For
4099 * header, there's nothing left to do here.
4104 header = strdup("X-Forwarded-For: ");
4105 string_append(&header, csp->ip_addr_str);
4109 return JB_ERR_MEMORY;
4112 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
4113 err = enlist(csp->headers, header);
4120 /*********************************************************************
4122 * Function : server_connection_adder
4124 * Description : Adds an appropiate "Connection:" header to csp->headers
4125 * unless the header was already present. Called from `sed'.
4128 * 1 : csp = Current client state (buffers, headers, etc...)
4130 * Returns : JB_ERR_OK on success, or
4131 * JB_ERR_MEMORY on out-of-memory error.
4133 *********************************************************************/
4134 static jb_err server_connection_adder(struct client_state *csp)
4136 const unsigned int flags = csp->flags;
4137 const char *response_status_line = csp->headers->first->str;
4138 const char *wanted_header = get_appropiate_connection_header(csp);
4140 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4141 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
4147 * XXX: if we downgraded the response, this check will fail.
4149 if ((csp->config->feature_flags &
4150 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4151 && (NULL != response_status_line)
4152 && !strncmpic(response_status_line, "HTTP/1.1", 8))
4154 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
4155 "without Connection header implies keep-alive.");
4156 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
4159 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
4161 return enlist(csp->headers, wanted_header);
4165 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4166 /*********************************************************************
4168 * Function : server_proxy_connection_adder
4170 * Description : Adds a "Proxy-Connection: keep-alive" header to
4171 * csp->headers. XXX: We should reuse existant ones.
4174 * 1 : csp = Current client state (buffers, headers, etc...)
4176 * Returns : JB_ERR_OK on success, or
4177 * JB_ERR_MEMORY on out-of-memory error.
4179 *********************************************************************/
4180 static jb_err server_proxy_connection_adder(struct client_state *csp)
4182 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
4183 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
4184 return enlist(csp->headers, proxy_connection_header);
4186 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4189 /*********************************************************************
4191 * Function : client_connection_header_adder
4193 * Description : Adds a proper "Connection:" header to csp->headers
4194 * unless the header was already present. Called from `sed'.
4197 * 1 : csp = Current client state (buffers, headers, etc...)
4199 * Returns : JB_ERR_OK on success, or
4200 * JB_ERR_MEMORY on out-of-memory error.
4202 *********************************************************************/
4203 static jb_err client_connection_header_adder(struct client_state *csp)
4205 const unsigned int flags = csp->flags;
4206 const char *wanted_header = get_appropiate_connection_header(csp);
4208 if (!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4209 && (flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
4214 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
4216 return enlist(csp->headers, wanted_header);
4220 /*********************************************************************
4222 * Function : server_http
4224 * Description : - Save the HTTP Status into csp->http->status
4225 * - Set CT_TABOO to prevent filtering if the answer
4226 * is a partial range (HTTP status 206)
4227 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4231 * 1 : csp = Current client state (buffers, headers, etc...)
4232 * 2 : header = On input, pointer to header to modify.
4233 * On output, pointer to the modified header, or NULL
4234 * to remove the header. This function frees the
4235 * original string if necessary.
4237 * Returns : JB_ERR_OK on success, or
4238 * JB_ERR_MEMORY on out-of-memory error.
4240 *********************************************************************/
4241 static jb_err server_http(struct client_state *csp, char **header)
4243 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
4244 if (csp->http->status == 206)
4246 csp->content_type = CT_TABOO;
4249 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
4251 /* XXX: Should we do a real validity check here? */
4252 if (strlen(*header) > 8)
4255 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
4260 * XXX: Should we block the request or
4261 * enlist a valid status code line here?
4263 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
4264 "Downgrading to HTTP/1.0 impossible.");
4272 /*********************************************************************
4274 * Function : server_set_cookie
4276 * Description : Handle the server "cookie" header properly.
4277 * Log cookie to the jar file. Then "crunch",
4278 * accept or rewrite it to a session cookie.
4279 * Called from `sed'.
4281 * TODO: Allow the user to specify a new expiration
4282 * time to cause the cookie to expire even before the
4283 * browser is closed.
4286 * 1 : csp = Current client state (buffers, headers, etc...)
4287 * 2 : header = On input, pointer to header to modify.
4288 * On output, pointer to the modified header, or NULL
4289 * to remove the header. This function frees the
4290 * original string if necessary.
4292 * Returns : JB_ERR_OK on success, or
4293 * JB_ERR_MEMORY on out-of-memory error.
4295 *********************************************************************/
4296 static jb_err server_set_cookie(struct client_state *csp, char **header)
4303 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
4305 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4308 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
4310 /* Flag whether or not to log a message */
4313 /* A variable to store the tag we're working on */
4316 /* Skip "Set-Cookie:" (11 characters) in header */
4317 cur_tag = *header + 11;
4319 /* skip whitespace between "Set-Cookie:" and value */
4320 while (*cur_tag && ijb_isspace(*cur_tag))
4325 /* Loop through each tag in the cookie */
4329 char *next_tag = strchr(cur_tag, ';');
4330 if (next_tag != NULL)
4332 /* Skip the ';' character itself */
4335 /* skip whitespace ";" and start of tag */
4336 while (*next_tag && ijb_isspace(*next_tag))
4343 /* "Next tag" is the end of the string */
4344 next_tag = cur_tag + strlen(cur_tag);
4348 * Check the expiration date to see
4349 * if the cookie is still valid, if yes,
4350 * rewrite it to a session cookie.
4352 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4354 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4356 /* Did we detect the date properly? */
4357 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4360 * Nope, treat it as if it was still valid.
4362 * XXX: Should we remove the whole cookie instead?
4364 log_error(LOG_LEVEL_ERROR,
4365 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4366 string_move(cur_tag, next_tag);
4372 * Yes. Check if the cookie is still valid.
4374 * If the cookie is already expired it's probably
4375 * a delete cookie and even if it isn't, the browser
4376 * will discard it anyway.
4380 * XXX: timegm() isn't available on some AmigaOS
4381 * versions and our replacement doesn't work.
4383 * Our options are to either:
4385 * - disable session-cookies-only completely if timegm
4388 * - to simply remove all expired tags, like it has
4389 * been done until Privoxy 3.0.6 and to live with
4390 * the consequence that it can cause login/logout
4391 * problems on servers that don't validate their
4392 * input properly, or
4394 * - to replace it with mktime in which
4395 * case there is a slight chance of valid cookies
4396 * passing as already expired.
4398 * This is the way it's currently done and it's not
4399 * as bad as it sounds. If the missing GMT offset is
4400 * enough to change the result of the expiration check
4401 * the cookie will be only valid for a few hours
4402 * anyway, which in many cases will be shorter
4403 * than a browser session.
4405 if (cookie_time - now < 0)
4407 log_error(LOG_LEVEL_HEADER,
4408 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4409 /* Just in case some clown sets more then one expiration date */
4415 * Still valid, delete expiration date by copying
4416 * the rest of the string over it.
4418 string_move(cur_tag, next_tag);
4420 /* That changed the header, need to issue a log message */
4424 * Note that the next tag has now been moved to *cur_tag,
4425 * so we do not need to update the cur_tag pointer.
4433 /* Move on to next cookie tag */
4440 assert(NULL != *header);
4441 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4450 #ifdef FEATURE_FORCE_LOAD
4451 /*********************************************************************
4453 * Function : strclean
4455 * Description : In-Situ-Eliminate all occurances of substring in
4459 * 1 : string = string to clean
4460 * 2 : substring = substring to eliminate
4462 * Returns : Number of eliminations
4464 *********************************************************************/
4465 int strclean(char *string, const char *substring)
4471 len = strlen(substring);
4473 while((pos = strstr(string, substring)) != NULL)
4480 while (*p++ != '\0');
4487 #endif /* def FEATURE_FORCE_LOAD */
4490 /*********************************************************************
4492 * Function : parse_header_time
4494 * Description : Parses time formats used in HTTP header strings
4495 * to get the numerical respresentation.
4498 * 1 : header_time = HTTP header time as string.
4499 * 2 : result = storage for header_time in seconds
4501 * Returns : JB_ERR_OK if the time format was recognized, or
4502 * JB_ERR_PARSE otherwise.
4504 *********************************************************************/
4505 static jb_err parse_header_time(const char *header_time, time_t *result)
4510 * Zero out gmt to prevent time zone offsets.
4512 * While this is only necessary on some platforms
4513 * (mingw32 for example), I don't know how to
4514 * detect these automatically and doing it everywhere
4517 memset(&gmt, 0, sizeof(gmt));
4519 /* Tue, 02 Jun 2037 20:00:00 */
4520 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4521 /* Tue, 02-Jun-2037 20:00:00 */
4522 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4523 /* Tue, 02-Jun-37 20:00:00 */
4524 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4525 /* Tuesday, 02-Jun-2037 20:00:00 */
4526 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4527 /* Tuesday Jun 02 20:00:00 2037 */
4528 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4530 return JB_ERR_PARSE;
4533 *result = timegm(&gmt);
4540 /*********************************************************************
4542 * Function : get_destination_from_headers
4544 * Description : Parse the "Host:" header to get the request's destination.
4545 * Only needed if the client's request was forcefully
4546 * redirected into Privoxy.
4548 * Code mainly copied from client_host() which is currently
4549 * run too late for this purpose.
4552 * 1 : headers = List of headers (one of them hopefully being
4553 * the "Host:" header)
4554 * 2 : http = storage for the result (host, port and hostport).
4556 * Returns : JB_ERR_MEMORY in case of memory problems,
4557 * JB_ERR_PARSE if the host header couldn't be found,
4558 * JB_ERR_OK otherwise.
4560 *********************************************************************/
4561 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4567 host = get_header_value(headers, "Host:");
4571 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4572 return JB_ERR_PARSE;
4575 if (NULL == (p = strdup((host))))
4577 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4578 return JB_ERR_MEMORY;
4581 if (NULL == (q = strdup(p)))
4584 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4585 return JB_ERR_MEMORY;
4588 freez(http->hostport);
4592 q = strchr(http->host, ':');
4595 /* Terminate hostname and evaluate port string */
4597 http->port = atoi(q);
4601 http->port = http->ssl ? 443 : 80;
4604 /* Rebuild request URL */
4606 http->url = strdup(http->ssl ? "https://" : "http://");
4607 string_append(&http->url, http->hostport);
4608 string_append(&http->url, http->path);
4609 if (http->url == NULL)
4611 return JB_ERR_MEMORY;
4614 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4622 /*********************************************************************
4624 * Function : create_forged_referrer
4626 * Description : Helper for client_referrer to forge a referer as
4627 * 'http://[hostname:port/' to fool stupid
4628 * checks for in-site links
4631 * 1 : header = Pointer to header pointer
4632 * 2 : hostport = Host and optionally port as string
4634 * Returns : JB_ERR_OK in case of success, or
4635 * JB_ERR_MEMORY in case of memory problems.
4637 *********************************************************************/
4638 static jb_err create_forged_referrer(char **header, const char *hostport)
4640 assert(NULL == *header);
4642 *header = strdup("Referer: http://");
4643 string_append(header, hostport);
4644 string_append(header, "/");
4646 if (NULL == *header)
4648 return JB_ERR_MEMORY;
4651 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4658 /*********************************************************************
4660 * Function : create_fake_referrer
4662 * Description : Helper for client_referrer to create a fake referrer
4663 * based on a string supplied by the user.
4666 * 1 : header = Pointer to header pointer
4667 * 2 : hosthost = Referrer to fake
4669 * Returns : JB_ERR_OK in case of success, or
4670 * JB_ERR_MEMORY in case of memory problems.
4672 *********************************************************************/
4673 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4675 assert(NULL == *header);
4677 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4679 log_error(LOG_LEVEL_HEADER,
4680 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4682 *header = strdup("Referer: ");
4683 string_append(header, fake_referrer);
4685 if (NULL == *header)
4687 return JB_ERR_MEMORY;
4690 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4697 /*********************************************************************
4699 * Function : handle_conditional_hide_referrer_parameter
4701 * Description : Helper for client_referrer to crunch or forge
4702 * the referrer header if the host has changed.
4705 * 1 : header = Pointer to header pointer
4706 * 2 : host = The target host (may include the port)
4707 * 3 : parameter_conditional_block = Boolean to signal
4708 * if we're in conditional-block mode. If not set,
4709 * we're in conditional-forge mode.
4711 * Returns : JB_ERR_OK in case of success, or
4712 * JB_ERR_MEMORY in case of memory problems.
4714 *********************************************************************/
4715 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4716 const char *host, const int parameter_conditional_block)
4718 char *referer = strdup(*header);
4719 const size_t hostlenght = strlen(host);
4720 const char *referer_url = NULL;
4722 if (NULL == referer)
4725 return JB_ERR_MEMORY;
4728 /* referer begins with 'Referer: http[s]://' */
4729 if ((hostlenght+17) < strlen(referer))
4732 * Shorten referer to make sure the referer is blocked
4733 * if www.example.org/www.example.com-shall-see-the-referer/
4734 * links to www.example.com/
4736 referer[hostlenght+17] = '\0';
4738 referer_url = strstr(referer, "http://");
4739 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4741 /* Host has changed, Referer is invalid or a https URL. */
4742 if (parameter_conditional_block)
4744 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4751 return create_forged_referrer(header, host);
4761 /*********************************************************************
4763 * Function : get_appropiate_connection_header
4765 * Description : Returns an appropiate Connection header
4766 * depending on whether or not we try to keep
4767 * the connection to the server alive.
4770 * 1 : csp = Current client state (buffers, headers, etc...)
4772 * Returns : Pointer to statically allocated header buffer.
4774 *********************************************************************/
4775 static const char *get_appropiate_connection_header(const struct client_state *csp)
4777 static const char connection_keep_alive[] = "Connection: keep-alive";
4778 static const char connection_close[] = "Connection: close";
4780 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4781 && (csp->http->ssl == 0))
4783 return connection_keep_alive;
4785 return connection_close;