1 const char jcc_rcs[] = "$Id: jcc.c,v 1.231 2009/03/08 14:19:23 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001-2009 the SourceForge
10 * Privoxy team. http://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
36 * Revision 1.231 2009/03/08 14:19:23 fabiankeil
37 * Fix justified (but harmless) compiler warnings
38 * on platforms where sizeof(int) < sizeof(long).
40 * Revision 1.230 2009/03/07 13:09:17 fabiankeil
41 * Change csp->expected_content and_csp->expected_content_length from
42 * size_t to unsigned long long to reduce the likelihood of integer
43 * overflows that would let us close the connection prematurely.
44 * Bug found while investigating #2669131, reported by cyberpatrol.
46 * Revision 1.229 2009/03/07 11:17:01 fabiankeil
47 * Fix compiler warning.
49 * Revision 1.228 2009/03/06 20:30:13 fabiankeil
50 * Log unsigned values as such.
52 * Revision 1.227 2009/03/02 19:18:11 fabiankeil
53 * Streamline parse_http_request()'s prototype. As
54 * cparser pointed out it doesn't actually use csp.
56 * Revision 1.226 2009/03/01 18:28:24 fabiankeil
57 * Help clang understand that we aren't dereferencing
60 * Revision 1.225 2009/02/19 18:09:32 fabiankeil
61 * Unbreak build without FEATURE_CONNECTION_KEEP_ALIVE.
64 * Revision 1.224 2009/02/14 15:32:04 fabiankeil
65 * Add the request URL to the timeout message in chat().
68 * Revision 1.223 2009/02/09 21:21:16 fabiankeil
69 * Now that init_log_module() is called earlier, call show_version()
70 * later on from main() directly so it doesn't get called for --help
73 * Revision 1.222 2009/02/08 12:56:51 fabiankeil
74 * Call initialize_mutexes() before init_log_module() again.
75 * Broken since r220, might be the cause of Lee's #2579448.
77 * Revision 1.221 2009/02/06 18:02:58 fabiankeil
78 * When dropping privileges, also give up membership in supplementary
79 * groups. Thanks to Matthias Drochner for reporting the problem,
80 * providing the initial patch and testing the final version.
82 * Revision 1.220 2009/02/04 18:29:07 fabiankeil
83 * Initialize the log module before parsing arguments.
84 * Thanks to Matthias Drochner for the report.
86 * Revision 1.219 2009/01/31 16:08:21 fabiankeil
87 * Remove redundant error check in receive_client_request().
89 * Revision 1.218 2009/01/31 12:25:54 fabiankeil
90 * Flatten indentation in receive_client_request().
92 * Revision 1.217 2009/01/07 19:50:09 fabiankeil
93 * - If the socket-timeout has been reached and the client
94 * hasn't received any data yet, send an explanation before
95 * closing the connection.
96 * - In get_request_line(), signal timeouts the right way.
98 * Revision 1.216 2008/12/24 22:13:11 ler762
99 * fix GCC 3.4.4 warning
101 * Revision 1.215 2008/12/24 17:06:19 fabiankeil
102 * Keep a thread around to timeout alive connections
103 * even if no new requests are coming in.
105 * Revision 1.214 2008/12/20 14:53:55 fabiankeil
106 * Add config option socket-timeout to control the time
107 * Privoxy waits for data to arrive on a socket. Useful
108 * in case of stale ssh tunnels or when fuzz-testing.
110 * Revision 1.213 2008/12/15 18:45:51 fabiankeil
111 * When logging crunches, log the whole URL, so one can easily
112 * differentiate between vanilla HTTP and CONNECT requests.
114 * Revision 1.212 2008/12/14 15:46:22 fabiankeil
115 * Give crunched requests their own log level.
117 * Revision 1.211 2008/12/06 10:05:03 fabiankeil
118 * Downgrade "Received x bytes while expecting y." message to
119 * LOG_LEVEL_CONNECT as it doesn't necessarily indicate an error.
121 * Revision 1.210 2008/12/02 22:03:18 fabiankeil
122 * Don't miscalculate byte_count if we don't get all the
123 * server headers with one read_socket() call. With keep-alive
124 * support enabled, this caused delays until the server closed
127 * Revision 1.209 2008/11/27 09:44:04 fabiankeil
128 * Cosmetics for the last commit: Don't watch out for
129 * the last chunk if the content isn't chunk-encoded or
130 * if we already determined the content length previously.
132 * Revision 1.208 2008/11/26 18:24:17 fabiankeil
133 * Recognize that the server response is complete if the
134 * last chunk is read together with the server headers.
137 * Revision 1.207 2008/11/25 17:25:16 fabiankeil
138 * Don't convert the client-header list to text until we need to.
140 * Revision 1.206 2008/11/23 17:00:11 fabiankeil
141 * Some more chat() cosmetics.
143 * Revision 1.205 2008/11/16 12:43:49 fabiankeil
144 * Turn keep-alive support into a runtime feature
145 * that is disabled by setting keep-alive-timeout
146 * to a negative value.
148 * Revision 1.204 2008/11/06 19:42:17 fabiankeil
149 * Fix last-chunk detection hack to also apply
150 * if buf[] contains nothing but the last-chunk.
152 * Revision 1.203 2008/11/06 18:34:35 fabiankeil
153 * Factor receive_client_request() and
154 * parse_client_request() out of chat().
156 * Revision 1.202 2008/11/02 18:40:34 fabiankeil
157 * If we received a different amount of data than we expected,
158 * log a warning and make sure the server socket isn't reused.
160 * Revision 1.201 2008/11/02 16:48:20 fabiankeil
161 * Revert revision 1.195 and try again.
163 * Revision 1.200 2008/10/26 16:53:18 fabiankeil
166 * Revision 1.199 2008/10/26 15:36:10 fabiankeil
167 * Remove two debug messages with LOG_LEVEL_INFO.
169 * Revision 1.198 2008/10/22 15:19:55 fabiankeil
170 * Once More, With Feeling: if there is no logfile
171 * because the user didn't specify one, we shouldn't
172 * call init_error_log() after receiving SIGHUP either.
174 * Revision 1.197 2008/10/20 17:02:40 fabiankeil
175 * If SIGHUP is received while we aren't running in daemon
176 * mode, calling init_error_log() would be a mistake.
178 * Revision 1.196 2008/10/16 09:16:41 fabiankeil
179 * - Fix two gcc44 conversion warnings.
180 * - Don't bother logging the last five bytes
183 * Revision 1.195 2008/10/13 16:04:37 fabiankeil
184 * Make sure we don't try to reuse tainted server sockets.
186 * Revision 1.194 2008/10/12 18:35:18 fabiankeil
187 * The last commit was a bit too ambitious, apparently the content
188 * length adjustment is only necessary if we aren't buffering.
190 * Revision 1.193 2008/10/12 15:57:35 fabiankeil
191 * Fix content length calculation if we read headers
192 * and the start of the body at once. Now that we have
193 * FEATURE_CONNECTION_KEEP_ALIVE, it actually matters.
195 * Revision 1.192 2008/10/11 18:19:14 fabiankeil
196 * Even more chat() cosmetics.
198 * Revision 1.191 2008/10/11 18:00:14 fabiankeil
199 * Reformat some comments in chat().
201 * Revision 1.190 2008/10/11 14:58:00 fabiankeil
202 * In case of chunk-encoded content, stop reading if
203 * the buffer looks like it ends with the last chunk.
205 * Revision 1.189 2008/10/11 09:53:00 fabiankeil
206 * Let server_response_is_complete() deal properly with
207 * content that is neither buffered nor read all at once.
209 * Revision 1.188 2008/10/09 18:21:41 fabiankeil
210 * Flush work-in-progress changes to keep outgoing connections
211 * alive where possible. Incomplete and mostly #ifdef'd out.
213 * Revision 1.187 2008/09/07 12:35:05 fabiankeil
214 * Add mutex lock support for _WIN32.
216 * Revision 1.186 2008/09/04 08:13:58 fabiankeil
217 * Prepare for critical sections on Windows by adding a
218 * layer of indirection before the pthread mutex functions.
220 * Revision 1.185 2008/08/30 12:03:07 fabiankeil
221 * Remove FEATURE_COOKIE_JAR.
223 * Revision 1.184 2008/08/22 15:34:45 fabiankeil
224 * - Silence LLVM/Clang complaint.
225 * - Make received_hup_signal static.
226 * - Hide definitions for basedir, pidfile and received_hup_signal
227 * from __EMX__ as they only seem to be used in case of #ifdef unix.
229 * Revision 1.183 2008/08/21 07:09:35 fabiankeil
230 * Accept Shoutcast responses again. Problem reported
231 * and fix suggested by Stefan in #2062860.
233 * Revision 1.182 2008/06/27 11:13:56 fabiankeil
234 * Fix possible NULL-pointer dereference reported
235 * by din_a4 in #2003937. Pointy hat to me.
237 * Revision 1.181 2008/05/21 15:47:15 fabiankeil
238 * Streamline sed()'s prototype and declare
239 * the header parse and add structures static.
241 * Revision 1.180 2008/05/21 15:26:32 fabiankeil
242 * - Mark csp as immutable for send_crunch_response().
243 * - Fix comment spelling.
245 * Revision 1.179 2008/05/20 20:13:32 fabiankeil
246 * Factor update_server_headers() out of sed(), ditch the
247 * first_run hack and make server_patterns_light static.
249 * Revision 1.178 2008/05/10 13:23:38 fabiankeil
250 * Don't provide get_header() with the whole client state
251 * structure when it only needs access to csp->iob.
253 * Revision 1.177 2008/05/10 11:51:12 fabiankeil
254 * Make the "read the rest of the headers" loop a bit more readable.
256 * Revision 1.176 2008/05/10 11:37:57 fabiankeil
257 * - Instead of logging when the IIS5 hack is enabled, log when it fails.
258 * - Remove useless comment.
260 * Revision 1.175 2008/05/09 18:53:59 fabiankeil
261 * Fix comment grammar.
263 * Revision 1.174 2008/05/07 18:05:53 fabiankeil
264 * Remove the pointless buffer in client_protocol_is_unsupported().
266 * Revision 1.173 2008/05/06 15:09:00 fabiankeil
267 * Least-effort fix for bug #1821930 (reported by Lee):
268 * If the response doesn't look like HTTP,
269 * tell the client and log the problem.
271 * Revision 1.172 2008/04/16 16:38:21 fabiankeil
272 * Don't pass the whole csp structure to flush_socket()
273 * when it only needs a file descriptor and a buffer.
275 * Revision 1.171 2008/03/27 18:27:25 fabiankeil
276 * Remove kill-popups action.
278 * Revision 1.170 2008/03/06 16:33:46 fabiankeil
279 * If limit-connect isn't used, don't limit CONNECT requests to port 443.
281 * Revision 1.169 2008/03/04 18:30:39 fabiankeil
282 * Remove the treat-forbidden-connects-like-blocks action. We now
283 * use the "blocked" page for forbidden CONNECT requests by default.
285 * Revision 1.168 2008/03/02 12:25:25 fabiankeil
286 * Also use shiny new connect_port_is_forbidden() in jcc.c.
288 * Revision 1.167 2008/02/23 16:57:12 fabiankeil
289 * Rename url_actions() to get_url_actions() and let it
290 * use the standard parameter ordering.
292 * Revision 1.166 2008/02/23 16:33:43 fabiankeil
293 * Let forward_url() use the standard parameter ordering
294 * and mark its second parameter immutable.
296 * Revision 1.165 2008/02/02 19:36:56 fabiankeil
297 * Remove the "Listening ... for local connections only" log message.
298 * Whether or not remote connections are able to reach Privoxy is up
299 * to the operating system.
301 * Revision 1.164 2007/12/16 18:32:46 fabiankeil
302 * Prevent the log messages for CONNECT requests to unacceptable
303 * ports from printing the limit-connect argument as [null] if
304 * limit-connect hasn't been explicitly enabled.
306 * Revision 1.163 2007/12/13 01:47:11 david__schmidt
307 * Make sure all console-mode apps get a usage() instance
309 * Revision 1.162 2007/12/06 17:54:57 fabiankeil
310 * Reword NO_SERVER_DATA_RESPONSE to make it harder
311 * to misunderstand what the message is all about.
313 * Revision 1.161 2007/12/04 19:44:22 fabiankeil
314 * Unbreak trustfile which previously didn't work without
315 * FEATURE_TOGGLE. Fixes BR#1843585, reported by Lee.
317 * Revision 1.160 2007/11/29 18:00:29 fabiankeil
318 * Plug memory leak. Spotted by Valgrind, triggered by
319 * Privoxy-Regression-Test feeding proxyfuzz.py.
321 * Revision 1.159 2007/11/24 14:34:09 fabiankeil
322 * In the HTTP snipplets, refer to the client as client.
324 * Revision 1.158 2007/11/11 16:44:17 fabiankeil
325 * Emit a log message when activating the MS IIS5 hack.
327 * Revision 1.157 2007/11/03 17:34:49 fabiankeil
328 * Log the "weak randomization factor" warning only
329 * once for mingw32 and provide some more details.
331 * Revision 1.156 2007/11/01 18:20:58 fabiankeil
332 * Initialize log module after initializing mutexes, future
333 * deadlocks in that code should now work cross-platform.
335 * Revision 1.155 2007/10/23 20:12:45 fabiankeil
336 * Fix first CSUCCEED line to end in \r\n as required by RFC1945.
337 * Reported by Bert van Leeuwen in BR#1818808.
339 * Revision 1.154 2007/10/19 17:00:08 fabiankeil
340 * Downgrade "Flushing header and buffers" message to LOG_LEVEL_INFO.
342 * Revision 1.153 2007/10/14 14:12:41 fabiankeil
343 * When in daemon mode, close stderr after the configuration file has been
344 * parsed the first time. If logfile isn't set, stop logging. Fixes BR#897436.
346 * Revision 1.152 2007/10/04 18:03:34 fabiankeil
347 * - Fix a crash when parsing invalid requests whose first header
348 * is rejected by get_header(). Regression (re?)introduced
349 * in r1.143 by yours truly.
350 * - Move ACTION_VANILLA_WAFER handling into parsers.c's
351 * client_cookie_adder() to make sure send-vanilla-wafer can be
352 * controlled through tags (and thus regression-tested).
354 * Revision 1.151 2007/09/29 10:21:16 fabiankeil
355 * - Move get_filter_function() from jcc.c to filters.c
356 * so the filter functions can be static.
357 * - Don't bother filtering body-less responses.
359 * Revision 1.150 2007/09/28 16:39:29 fabiankeil
360 * Execute content filters through execute_content_filter().
362 * Revision 1.149 2007/09/04 15:08:48 fabiankeil
363 * Initialize req to NULL to make sure it's defined if the
364 * first read_socket() call fails. Reported by icmp30.
366 * Revision 1.148 2007/08/26 16:47:13 fabiankeil
367 * Add Stephen Gildea's --pre-chroot-nslookup patch [#1276666],
368 * extensive comments moved to user manual.
370 * Revision 1.147 2007/08/25 14:42:40 fabiankeil
371 * Don't crash if a broken header filter wiped out the request line.
373 * Revision 1.146 2007/08/20 17:09:32 fabiankeil
374 * Fix byte_count calculation in case of flushes
375 * and don't parse the server headers a second time.
377 * Revision 1.145 2007/08/19 13:13:31 fabiankeil
378 * - If there's a connection problem after we already forwarded
379 * parts of the original content, just hang up. Fixes BR#1776724.
380 * - Fix warnings about unused code on mingw32.
381 * - In case of flushes, calculate the byte count
382 * less incorrectly (I think).
384 * Revision 1.144 2007/08/11 14:43:22 fabiankeil
385 * Add some more prototypes for static functions.
387 * Revision 1.143 2007/08/05 13:58:19 fabiankeil
388 * Comment out request_contains_null_bytes() until it's used again.
390 * Revision 1.142 2007/08/05 13:50:26 fabiankeil
391 * #1763173 from Stefan Huehner: s@const static@static const@
392 * and declare some more functions static.
394 * Revision 1.141 2007/08/04 09:56:23 fabiankeil
395 * - Log rejected CONNECT requests with LOG_LEVEL_INFO
396 * and explain why they were rejected in the first place.
397 * - Fix the LOG_LEVEL_CLF message for crunches of unallowed
398 * CONNECT requests. The request line was missing.
399 * - Add two more XXX reminders as we don't have enough already.
401 * Revision 1.140 2007/07/21 11:51:36 fabiankeil
402 * As Hal noticed, checking dispatch_cgi() as the last cruncher
403 * looks like a bug if CGI requests are blocked unintentionally,
404 * so don't do it unless the user enabled the new config option
405 * "allow-cgi-request-crunching".
407 * Revision 1.139 2007/07/14 07:46:41 fabiankeil
408 * - Allow to rewrite the request destination behind the client's back.
409 * - Turn the weird-looking unconditional for loop that
410 * reads the client request into a conditional while loop.
411 * Move the stuff that only runs once out of the loop.
412 * - Move parts of chat(), server_content_type() and the
413 * necessary stuff to fix BR#1750917 into get_filter_function().
415 * Revision 1.138 2007/06/03 18:45:18 fabiankeil
416 * Temporary workaround for BR#1730105.
418 * Revision 1.137 2007/06/01 18:16:36 fabiankeil
419 * Use the same mutex for gethostbyname() and gethostbyaddr() to prevent
420 * deadlocks and crashes on OpenBSD and possibly other OS with neither
421 * gethostbyname_r() nor gethostaddr_r(). Closes BR#1729174.
422 * Thanks to Ralf Horstmann for report and solution.
424 * Revision 1.136 2007/06/01 16:41:11 fabiankeil
425 * Add forward-override{} to change the forwarding settings through
426 * action sections. This is mainly interesting to forward different
427 * clients differently (for example based on User-Agent or request
430 * Revision 1.135 2007/05/24 17:03:50 fabiankeil
431 * - Let usage() mention the --chroot parameter.
432 * - Use read_socket() consistently and always leave
433 * the last buffer byte alone, even in cases where
434 * null termination (currently) doesn't matter.
436 * Revision 1.134 2007/05/16 14:59:46 fabiankeil
437 * - Fix config file loading on Unix if no config file is specified.
438 * Since r1.97 Privoxy would always interpret the last argument as
439 * config file, even if it's a valid command line option.
440 * - Abort in case of unrecognized command line options. Closes #1719696.
441 * - Remove a bunch of unnecessary strcpy() calls (yay for c&p without thinking).
442 * - Replace the remaining strcpy() and strcat() calls with strlcpy() and strcat().
444 * Revision 1.133 2007/05/04 11:23:19 fabiankeil
445 * - Don't rerun crunchers that only depend on the request URL.
446 * - Don't count redirects and CGI requests as "blocked requests".
448 * Revision 1.132 2007/04/25 15:15:17 fabiankeil
449 * Support crunching based on tags created by server-header taggers.
451 * Revision 1.131 2007/04/22 13:24:50 fabiankeil
452 * Make HTTP snippets static (again). Add a Content-Type for those
453 * with content so the browser doesn't guess it based on the URL.
455 * Revision 1.130 2007/04/19 13:47:34 fabiankeil
456 * Move crunching and request line rebuilding out of chat().
458 * Revision 1.129 2007/04/15 16:39:20 fabiankeil
459 * Introduce tags as alternative way to specify which
460 * actions apply to a request. At the moment tags can be
461 * created based on client and server headers.
463 * Revision 1.128 2007/03/25 16:55:54 fabiankeil
464 * Don't CLF-log CONNECT requests twice.
466 * Revision 1.127 2007/03/20 13:53:17 fabiankeil
467 * Log the source address for ACL-related connection drops.
469 * Revision 1.126 2007/03/17 15:20:05 fabiankeil
470 * New config option: enforce-blocks.
472 * Revision 1.125 2007/03/09 14:12:00 fabiankeil
473 * - Move null byte check into separate function.
474 * - Don't confuse the client with error pages
475 * if a CONNECT request was already confirmed.
477 * Revision 1.124 2007/02/23 14:59:54 fabiankeil
478 * Speed up NULL byte escaping and only log the complete
479 * NULL byte requests with header debugging enabled.
481 * Revision 1.123 2007/02/21 18:42:10 fabiankeil
482 * Answer requests that contain NULL bytes with
483 * a custom response instead of waiting for more
484 * data until the client eventually hangs up.
486 * Revision 1.122 2007/02/07 11:12:02 fabiankeil
487 * - Move delivery and logging of crunched responses
488 * from chat() into send_crunch_response().
489 * - Display the reason for generating http_responses.
490 * - Log the content length for LOG_LEVEL_CLF correctly
491 * (still incorrect for some fixed responses).
492 * - Reword an incorrect comment about
493 * treat-forbidden-connects-like-blocks violating
495 * - Add some log messages.
497 * Revision 1.121 2007/01/27 10:52:56 fabiankeil
498 * Move mutex initialization into separate
499 * function and exit in case of errors.
501 * Revision 1.120 2007/01/26 14:18:42 fabiankeil
502 * - Start to reduce chat()'s line count and move
503 * parts of it into separate functions.
504 * - Add "HTTP/1.1 100 Continue" hack for BR 756734.
506 * Revision 1.119 2007/01/25 14:02:30 fabiankeil
507 * - Add Proxy-Agent header to HTTP snippets that are
508 * supposed to reach HTTP clients only.
509 * - Made a few CONNECT log messages more descriptive.
510 * - Catch completely empty server responses (as seen
511 * with Tor's fake ".noconnect" top level domain).
512 * - Use shiny new "forwarding-failed" template for socks errors.
514 * Revision 1.118 2007/01/07 07:43:43 joergs
515 * AmigaOS4 support added.
517 * Revision 1.117 2006/12/31 17:56:37 fabiankeil
518 * Added config option accept-intercepted-requests
519 * and disabled it by default.
521 * Revision 1.116 2006/12/29 19:08:22 fabiankeil
522 * Reverted parts of my last commit
523 * to keep error handling working.
525 * Revision 1.115 2006/12/29 17:38:57 fabiankeil
526 * Fixed gcc43 conversion warnings.
528 * Revision 1.114 2006/12/27 18:52:02 fabiankeil
529 * Fix -pedantic ISO C warning about converting
530 * from function pointer to object pointer.
532 * Revision 1.113 2006/12/26 17:38:50 fabiankeil
533 * Silence compiler warning I introduced with my last commit.
535 * Revision 1.112 2006/12/26 17:31:41 fabiankeil
536 * Mutex protect rand() if POSIX threading
537 * is used, warn the user if that's not possible
538 * and stop using it on _WIN32 where it could
541 * Revision 1.111 2006/12/23 16:15:06 fabiankeil
542 * Don't prevent core dumps by catching SIGABRT.
543 * It's rude and makes debugging unreasonable painful.
545 * Revision 1.110 2006/12/13 14:52:53 etresoft
546 * Fix build failure on MacOS X. Global symbols can be either static or extern, but not both.
548 * Revision 1.109 2006/12/06 19:41:40 fabiankeil
549 * Privoxy is now able to run as intercepting
550 * proxy in combination with any packet filter
551 * that does the port redirection. The destination
552 * is extracted from the "Host:" header which
553 * should be available for nearly all requests.
555 * Moved HTTP snipplets into jcc.c.
556 * Added error message for gopher proxy requests.
558 * Revision 1.108 2006/11/28 15:38:51 fabiankeil
559 * Only unlink the pidfile if it's actually used.
561 * Change order of interception checks to make
562 * it possible to block or redirect requests for
565 * Revision 1.107 2006/11/13 19:05:51 fabiankeil
566 * Make pthread mutex locking more generic. Instead of
567 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
568 * and use mutex locking unless there is an _r function
569 * available. Better safe than sorry.
571 * Fixes "./configure --disable-pthread" and should result
572 * in less threading-related problems on pthread-using platforms,
573 * but it still doesn't fix BR#1122404.
575 * Revision 1.106 2006/11/06 19:58:23 fabiankeil
576 * Move pthread.h inclusion from jcc.c to jcc.h.
577 * Fixes build on x86-freebsd1 (FreeBSD 5.4-RELEASE).
579 * Revision 1.105 2006/11/06 14:26:02 fabiankeil
580 * Don't exit after receiving the second SIGHUP on Solaris.
582 * Fixes BR 1052235, but the same problem may exist on other
583 * systems. Once 3.0.6 is out we should use sigset()
584 * where available and see if it breaks anything.
586 * Revision 1.104 2006/09/23 13:26:38 roro
587 * Replace TABs by spaces in source code.
589 * Revision 1.103 2006/09/21 12:54:43 fabiankeil
590 * Fix +redirect{}. Didn't work with -fast-redirects.
592 * Revision 1.102 2006/09/06 13:03:04 fabiankeil
593 * Respond with 400 and a short text message
594 * if the client tries to use Privoxy as FTP proxy.
596 * Revision 1.101 2006/09/06 09:23:37 fabiankeil
597 * Make number of retries in case of forwarded-connect problems
598 * a config file option (forwarded-connect-retries) and use 0 as
601 * Revision 1.100 2006/09/03 19:42:59 fabiankeil
602 * Set random(3) seed.
604 * Revision 1.99 2006/09/02 15:36:42 fabiankeil
605 * Follow the OpenBSD port's lead and protect the resolve
606 * functions on OpenBSD as well.
608 * Revision 1.98 2006/08/24 11:01:34 fabiankeil
609 * --user fix. Only use the user as group if no group is specified.
610 * Solves BR 1492612. Thanks to Spinor S. and David Laight.
612 * Revision 1.97 2006/08/18 15:23:17 david__schmidt
613 * Windows service (re-)integration
617 * --install[:service_name]
618 * --uninstall[:service_name]
621 * They work as follows:
622 * --install will create a service for you and then terminate.
623 * By default the service name will be "privoxy" (without the quotes).
624 * However you can run multiple services if you wish, just by adding
625 * a colon and then a name (no spaces).
627 * --uninstall follows the exact same rules a --install.
629 * --service is used when the program is executed by the service
630 * control manager, and in normal circumstances would never be
631 * used as a command line argument.
633 * Revision 1.96 2006/08/15 20:12:36 david__schmidt
634 * Windows service integration
636 * Revision 1.95 2006/08/03 02:46:41 david__schmidt
637 * Incorporate Fabian Keil's patch work:
638 http://www.fabiankeil.de/sourcecode/privoxy/
640 * Revision 1.94 2006/07/18 14:48:46 david__schmidt
641 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
642 * with what was really the latest development (the v_3_0_branch branch)
644 * Revision 1.92.2.16 2005/04/03 20:10:50 david__schmidt
645 * Thanks to Jindrich Makovicka for a race condition fix for the log
646 * file. The race condition remains for non-pthread implementations.
647 * Reference patch #1175720.
649 * Revision 1.92.2.15 2004/10/03 12:53:32 david__schmidt
650 * Add the ability to check jpeg images for invalid
651 * lengths of comment blocks. Defensive strategy
652 * against the exploit:
653 * Microsoft Security Bulletin MS04-028
654 * Buffer Overrun in JPEG Processing (GDI+) Could
655 * Allow Code Execution (833987)
656 * Enabled with +inspect-jpegs in actions files.
658 * Revision 1.92.2.14 2003/12/12 12:52:53 oes
659 * - Fixed usage info for non-unix platforms
660 * - Fixed small cmdline parsing bug
662 * Revision 1.92.2.13 2003/11/27 19:20:27 oes
663 * Diagnostics: Now preserve the returncode of pthread_create
664 * in errno. Closes BR #775721. Thanks to Geoffrey Hausheer.
666 * Revision 1.92.2.12 2003/07/11 11:34:19 oes
667 * No longer ignore SIGCHLD. Fixes bug #769381
669 * Revision 1.92.2.11 2003/05/14 12:32:02 oes
670 * Close jarfile on graceful exit, remove stray line
672 * Revision 1.92.2.10 2003/05/08 15:13:46 oes
673 * Cosmetics: Killed a warning, a typo and an allocation left at exit
675 * Revision 1.92.2.9 2003/04/03 15:08:42 oes
676 * No longer rely on non-POSIX.1 extensions of getcwd().
679 * Revision 1.92.2.8 2003/03/31 13:12:32 oes
680 * Replaced setenv() by posix-compliant putenv()
681 * Thanks to Neil McCalden (nmcc AT users.sf.net).
683 * Revision 1.92.2.7 2003/03/17 16:48:59 oes
684 * Added chroot ability, thanks to patch by Sviatoslav Sviridov
686 * Revision 1.92.2.6 2003/03/11 11:55:00 oes
687 * Clean-up and extension of improvements for forked mode:
688 * - Child's return code now consists of flags RC_FLAG_*
689 * - Reporting toggle to parent now properly #ifdef'ed
690 * - Children now report blocking to parent. This enables
691 * statistics in forked mode
693 * Revision 1.92.2.5 2003/03/10 23:45:32 oes
694 * Fixed bug #700381: Non-Threaded version now capable of being toggled.
695 * Children now report having been toggled through _exit(17), parents
696 * watch for that code and toggle themselves if found.
698 * Revision 1.92.2.4 2003/03/07 03:41:04 david__schmidt
699 * Wrapping all *_r functions (the non-_r versions of them) with
700 * mutex semaphores for OSX. Hopefully this will take care of all
701 * of those pesky crash reports.
703 * Revision 1.92.2.3 2003/02/28 12:53:06 oes
704 * Fixed two mostly harmless mem leaks
706 * Revision 1.92.2.2 2002/11/20 14:37:47 oes
707 * Fix: Head of global clients list now initialized to NULL
709 * Revision 1.92.2.1 2002/09/25 14:52:24 oes
710 * Added basic support for OPTIONS and TRACE HTTP methods:
711 * - New interceptor direct_response() added in chat().
712 * - sed() moved to earlier in the process, so that the
713 * Host: header is evaluated before actions and forwarding
716 * Revision 1.92 2002/05/08 16:00:46 oes
717 * Chat's buffer handling:
718 * - Fixed bug with unchecked out-of-mem conditions
719 * while reading client request & server headers
720 * - No longer predict if the buffer limit will be exceeded
721 * in the next read -- check add_to_iob's new
722 * return code. If buffer couldn't be extended
723 * (policy or out-of-mem) while
724 * - reading from client: abort
725 * - reading server headers: send error page
726 * - buffering server body for filter: flush,
727 * and if that fails: send error page
729 * Revision 1.91 2002/04/08 20:35:58 swa
732 * Revision 1.90 2002/04/02 14:57:28 oes
733 * Made sending wafers independent of FEATURE_COOKIE_JAR
735 * Revision 1.89 2002/03/31 17:18:59 jongfoster
736 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
738 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
739 * More compiler warning message maintenance
741 * Revision 1.87 2002/03/26 22:29:54 swa
742 * we have a new homepage!
744 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
745 * Workaround for closing the jarfile before load_config() comes around again
747 * Revision 1.85 2002/03/24 15:23:33 jongfoster
750 * Revision 1.84 2002/03/24 13:25:43 swa
751 * name change related issues
753 * Revision 1.83 2002/03/16 23:54:06 jongfoster
754 * Adding graceful termination feature, to help look for memory leaks.
755 * If you enable this (which, by design, has to be done by hand
756 * editing config.h) and then go to http://i.j.b/die, then the program
757 * will exit cleanly after the *next* request. It should free all the
758 * memory that was used.
760 * Revision 1.82 2002/03/13 00:27:05 jongfoster
763 * Revision 1.81 2002/03/12 01:42:50 oes
764 * Introduced modular filters
766 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
767 * OS/2 port maintenance:
768 * - Fixed EMX build - it had decayed a little
769 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
770 * substituted a memset for now.
772 * Revision 1.79 2002/03/09 20:03:52 jongfoster
773 * - Making various functions return int rather than size_t.
774 * (Undoing a recent change). Since size_t is unsigned on
775 * Windows, functions like read_socket that return -1 on
776 * error cannot return a size_t.
778 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
779 * crashes, and also frequently caused JB to jump to 100%
780 * CPU and stay there. (Because it thought it had just
781 * read ((unsigned)-1) == 4Gb of data...)
783 * - The signature of write_socket has changed, it now simply
784 * returns success=0/failure=nonzero.
786 * - Trying to get rid of a few warnings --with-debug on
787 * Windows, I've introduced a new type "jb_socket". This is
788 * used for the socket file descriptors. On Windows, this
789 * is SOCKET (a typedef for unsigned). Everywhere else, it's
790 * an int. The error value can't be -1 any more, so it's
791 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
792 * Windows it maps to the #define INVALID_SOCKET.)
794 * - The signature of bind_port has changed.
796 * Revision 1.78 2002/03/08 21:35:04 oes
797 * Added optional group supplement to --user option. Will now use default group of user if no group given
799 * Revision 1.77 2002/03/07 03:52:06 oes
800 * - Fixed compiler warnings etc
801 * - Improved handling of failed DNS lookups
803 * Revision 1.76 2002/03/06 22:54:35 jongfoster
804 * Automated function-comment nitpicking.
806 * Revision 1.75 2002/03/06 10:02:19 oes
807 * Fixed stupid bug when --user was not given
809 * Revision 1.74 2002/03/06 00:49:31 jongfoster
810 * Fixing warning on Windows
811 * Making #ifdefs that refer to the same variable consistently
812 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
814 * Revision 1.73 2002/03/05 23:57:30 hal9
815 * Stray character 's' on line 1618 was breaking build.
817 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
818 * - Re-enable OS/2 building after new parms were added
819 * - Fix false out of memory report when resolving CGI templates when no IP
820 * address is available of failed attempt (a la no such domain)
822 * Revision 1.71 2002/03/05 18:13:56 oes
823 * Added --user option
825 * Revision 1.70 2002/03/05 04:52:42 oes
826 * Deleted non-errlog debugging code
828 * Revision 1.69 2002/03/04 23:50:00 jongfoster
829 * Splitting off bind_port() call into bind_port_helper(), with
832 * Revision 1.68 2002/03/04 20:17:32 oes
835 * Revision 1.67 2002/03/04 18:18:57 oes
836 * - Removed _DEBUG mode
837 * - Cleand up cmdline parsing
838 * - Introduced --no-daemon, --pidfile options
839 * - Cleaned up signal handling:
840 * - Terminate cleanly on INT, TERM and ABRT
841 * - Schedule logfile for re-opening on HUP
842 * - Ignore CHLD and PIPE
843 * - Leave the rest with their default handlers
844 * - Uniform handler registration
845 * - Added usage() function
846 * - Played styleguide police
848 * Revision 1.66 2002/03/03 15:06:55 oes
849 * Re-enabled automatic config reloading
851 * Revision 1.65 2002/03/03 14:49:11 oes
852 * Fixed CLF logging: Now uses client's original HTTP request
854 * Revision 1.64 2002/03/03 09:18:03 joergs
855 * Made jumbjuster work on AmigaOS again.
857 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
858 * Clean up a little CRLF unpleasantness that suddenly appeared
860 * Revision 1.62 2002/02/20 23:17:23 jongfoster
861 * Detecting some out-of memory conditions and exiting with a log message.
863 * Revision 1.61 2002/01/17 21:01:52 jongfoster
864 * Moving all our URL and URL pattern parsing code to urlmatch.c.
866 * Revision 1.60 2001/12/30 14:07:32 steudten
867 * - Add signal handling (unix)
868 * - Add SIGHUP handler (unix)
869 * - Add creation of pidfile (unix)
870 * - Add action 'top' in rc file (RH)
871 * - Add entry 'SIGNALS' to manpage
872 * - Add exit message to logfile (unix)
874 * Revision 1.59 2001/12/13 14:07:18 oes
875 * Fixed Bug: 503 error page now sent OK
877 * Revision 1.58 2001/11/30 23:37:24 jongfoster
878 * Renaming the Win32 config file to config.txt - this is almost the
879 * same as the corresponding UNIX name "config"
881 * Revision 1.57 2001/11/16 00:47:43 jongfoster
882 * Changing the tty-disconnection code to use setsid().
884 * Revision 1.56 2001/11/13 20:20:54 jongfoster
885 * Tabs->spaces, fixing a bug with missing {} around an if()
887 * Revision 1.55 2001/11/13 20:14:53 jongfoster
888 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
890 * Revision 1.54 2001/11/07 00:03:14 steudten
891 * Give reliable return value if an error
892 * occurs not just 0 with new daemon mode.
894 * Revision 1.53 2001/11/05 21:41:43 steudten
895 * Add changes to be a real daemon just for unix os.
896 * (change cwd to /, detach from controlling tty, set
897 * process group and session leader to the own process.
899 * Add some fatal-error log message for failed malloc().
900 * Add '-d' if compiled with 'configure --with-debug' to
901 * enable debug output.
903 * Revision 1.52 2001/10/26 20:11:20 jongfoster
904 * Fixing type mismatch
906 * Revision 1.51 2001/10/26 17:38:28 oes
909 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
910 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
911 * threads to call select() simultaneously. So, it's time to do a real, live,
912 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
913 * (native). Both versions will work, but using __OS2__ offers multi-threading.
915 * Revision 1.49 2001/10/23 21:41:35 jongfoster
916 * Added call to initialize the (statically-allocated of course)
917 * "out of memory" CGI response.
919 * Revision 1.48 2001/10/10 19:56:46 jongfoster
920 * Moving some code that wasn't cookie-related out of an #ifdef
923 * Revision 1.47 2001/10/10 16:44:36 oes
924 * Added CONNECT destination port limitation check
926 * Revision 1.46 2001/10/08 15:17:41 oes
927 * Re-enabled SSL forwarding
929 * Revision 1.45 2001/10/07 15:42:11 oes
930 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
932 * Moved downgrading of the HTTP version from parse_http_request to
933 * chat(), since we can't decide if it is necessary before we have
934 * determined the actions for the URL. The HTTP command is now
935 * *always* re-built so the repairs need no longer be special-cased.
937 * filter_popups now gets a csp pointer so it can raise the new
938 * CSP_FLAG_MODIFIED flag.
942 * Added configurable size limit for the IOB. If the IOB grows so
943 * large that the next read would exceed the limit, the header
944 * is generated, and the header & unfiltered buffer are flushed
945 * to the client. Chat then continues in non-buffering,
946 * non-filtering body mode.
948 * Revision 1.44 2001/10/02 18:13:57 oes
951 * Revision 1.43 2001/10/02 15:32:13 oes
952 * Moved generation of hdr
954 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
955 * Cleaning up 2 compiler warnings on OS/2.
957 * Revision 1.41 2001/09/16 17:05:14 jongfoster
958 * Removing unused #include showarg.h
960 * Revision 1.40 2001/09/16 15:41:45 jongfoster
961 * Fixing signed/unsigned comparison warning.
963 * Revision 1.39 2001/09/16 13:21:27 jongfoster
964 * Changes to use new list functions.
966 * Revision 1.38 2001/09/16 13:01:46 jongfoster
967 * Removing redundant function call that zeroed zalloc()'d memory.
969 * Revision 1.37 2001/09/10 11:12:24 oes
970 * Deleted unused variable
972 * Revision 1.36 2001/09/10 10:56:15 oes
973 * Silenced compiler warnings
975 * Revision 1.35 2001/07/31 14:44:22 oes
976 * Deleted unused size parameter from filter_popups()
978 * Revision 1.34 2001/07/30 22:08:36 jongfoster
979 * Tidying up #defines:
980 * - All feature #defines are now of the form FEATURE_xxx
981 * - Permanently turned off WIN_GUI_EDIT
982 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
984 * Revision 1.33 2001/07/29 19:32:00 jongfoster
985 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
987 * Revision 1.32 2001/07/29 18:47:05 jongfoster
988 * Adding missing #include "loadcfg.h"
990 * Revision 1.31 2001/07/29 12:17:48 oes
991 * Applied pthread fix by Paul Lieverse
993 * Revision 1.30 2001/07/25 22:57:13 jongfoster
994 * __BEOS__ no longer overrides FEATURE_PTHREAD.
995 * This is because FEATURE_PTHREAD will soon be widely used, so I
996 * want to keep it simple.
998 * Revision 1.29 2001/07/24 12:47:06 oes
999 * Applied BeOS support update by Eugenia
1001 * Revision 1.28 2001/07/23 13:26:12 oes
1002 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
1004 * Revision 1.27 2001/07/19 19:09:47 haroon
1005 * - Added code to take care of the situation where while processing the first
1006 * server response (which includes the server header), after finding the end
1007 * of the headers we were not looking past the end of the headers for
1008 * content modification. I enabled it for filter_popups.
1009 * Someone else should look to see if other similar operations should be
1010 * done to the discarded portion of the buffer.
1012 * Note 2001/07/20: No, the other content modification mechanisms will process
1013 * the whole iob later anyway. --oes
1015 * Revision 1.26 2001/07/18 12:31:36 oes
1018 * Revision 1.25 2001/07/15 19:43:49 jongfoster
1019 * Supports POSIX threads.
1020 * Also removed some unused #includes.
1022 * Revision 1.24 2001/07/13 14:00:40 oes
1023 * - Generic content modification scheme:
1024 * Each feature has its own applicability flag that is set
1025 * from csp->action->flags.
1026 * Replaced the "filtering" int flag , by a function pointer
1027 * "content_filter" to the function that will do the content
1028 * modification. If it is != NULL, the document will be buffered
1029 * and processed through *content_filter, which must set
1030 * csp->content_length and return a modified copy of the body
1031 * or return NULL (on failiure).
1032 * - Changed csp->is_text to the more generic bitmap csp->content_type
1033 * which can currently take the valued CT_TEXT or CT_GIF
1034 * - Reformatting etc
1035 * - Removed all #ifdef PCRS
1037 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
1038 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
1039 * the `block_acl' call. This prevents a compilation error when the user
1040 * does not wish to use the "ACL" feature.
1042 * Revision 1.22 2001/06/29 21:45:41 oes
1043 * Indentation, CRLF->LF, Tab-> Space
1045 * Revision 1.21 2001/06/29 13:29:36 oes
1046 * - Cleaned up, improved comments
1047 * - Unified all possible interceptors (CGI,
1048 * block, trust, fast_redirect) in one
1049 * place, with one (CGI) answer generation
1050 * mechansim. Much clearer now.
1051 * - Removed the GIF image generation, which
1052 * is now done in filters.c:block_url()
1053 * - Made error conditions like domain lookup
1054 * failiure or (various) problems while talking
1055 * to the server use cgi.c:error_response()
1056 * instead of generating HTML/HTTP in chat() (yuck!)
1057 * - Removed logentry from cancelled commit
1059 * Revision 1.20 2001/06/09 10:55:28 jongfoster
1060 * Changing BUFSIZ ==> BUFFER_SIZE
1062 * Revision 1.19 2001/06/07 23:12:52 jongfoster
1063 * Replacing function pointer in struct gateway with a directly
1064 * called function forwarded_connect().
1065 * Replacing struct gateway with struct forward_spec
1067 * Revision 1.18 2001/06/03 19:12:16 oes
1068 * introduced new cgi handling
1070 * Revision 1.17 2001/06/01 20:07:23 jongfoster
1071 * Now uses action +image-blocker{} rather than config->tinygif
1073 * Revision 1.16 2001/06/01 18:49:17 jongfoster
1074 * Replaced "list_share" with "list" - the tiny memory gain was not
1075 * worth the extra complexity.
1077 * Revision 1.15 2001/05/31 21:24:47 jongfoster
1078 * Changed "permission" to "action" throughout.
1079 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
1080 * Moved vanilla wafer check into chat(), since we must now
1081 * decide whether or not to add it based on the URL.
1083 * Revision 1.14 2001/05/29 20:14:01 joergs
1084 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
1087 * Revision 1.13 2001/05/29 09:50:24 jongfoster
1088 * Unified blocklist/imagelist/permissionslist.
1089 * File format is still under discussion, but the internal changes
1090 * are (mostly) done.
1092 * Also modified interceptor behaviour:
1093 * - We now intercept all URLs beginning with one of the following
1094 * prefixes (and *only* these prefixes):
1096 * * http://ijbswa.sf.net/config/
1097 * * http://ijbswa.sourceforge.net/config/
1098 * - New interceptors "home page" - go to http://i.j.b/ to see it.
1099 * - Internal changes so that intercepted and fast redirect pages
1100 * are not replaced with an image.
1101 * - Interceptors now have the option to send a binary page direct
1102 * to the client. (i.e. ijb-send-banner uses this)
1103 * - Implemented show-url-info interceptor. (Which is why I needed
1104 * the above interceptors changes - a typical URL is
1105 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
1106 * The previous mechanism would not have intercepted that, and
1107 * if it had been intercepted then it then it would have replaced
1108 * it with an image.)
1110 * Revision 1.12 2001/05/27 22:17:04 oes
1112 * - re_process_buffer no longer writes the modified buffer
1113 * to the client, which was very ugly. It now returns the
1114 * buffer, which it is then written by chat.
1116 * - content_length now adjusts the Content-Length: header
1117 * for modified documents rather than crunch()ing it.
1118 * (Length info in csp->content_length, which is 0 for
1119 * unmodified documents)
1121 * - For this to work, sed() is called twice when filtering.
1123 * Revision 1.11 2001/05/26 17:27:53 jongfoster
1124 * Added support for CLF and fixed LOG_LEVEL_LOG.
1125 * Also did CRLF->LF fix of my previous patch.
1127 * Revision 1.10 2001/05/26 15:26:15 jongfoster
1128 * ACL feature now provides more security by immediately dropping
1129 * connections from untrusted hosts.
1131 * Revision 1.9 2001/05/26 00:28:36 jongfoster
1132 * Automatic reloading of config file.
1133 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
1134 * Most of the global variables have been moved to a new
1135 * struct configuration_spec, accessed through csp->config->globalname
1136 * Most of the globals remaining are used by the Win32 GUI.
1138 * Revision 1.8 2001/05/25 22:43:18 jongfoster
1139 * Fixing minor memory leak and buffer overflow.
1141 * Revision 1.7 2001/05/25 22:34:30 jongfoster
1144 * Revision 1.6 2001/05/23 00:13:58 joergs
1145 * AmigaOS support fixed.
1147 * Revision 1.5 2001/05/22 18:46:04 oes
1149 * - Enabled filtering banners by size rather than URL
1150 * by adding patterns that replace all standard banner
1151 * sizes with the "Junkbuster" gif to the re_filterfile
1153 * - Enabled filtering WebBugs by providing a pattern
1154 * which kills all 1x1 images
1156 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
1157 * which is selected by the (nonstandard and therefore
1158 * capital) letter 'U' in the option string.
1159 * It causes the quantifiers to be ungreedy by default.
1160 * Appending a ? turns back to greedy (!).
1162 * - Added a new interceptor ijb-send-banner, which
1163 * sends back the "Junkbuster" gif. Without imagelist or
1164 * MSIE detection support, or if tinygif = 1, or the
1165 * URL isn't recognized as an imageurl, a lame HTML
1166 * explanation is sent instead.
1168 * - Added new feature, which permits blocking remote
1169 * script redirects and firing back a local redirect
1171 * The feature is conditionally compiled, i.e. it
1172 * can be disabled with --disable-fast-redirects,
1173 * plus it must be activated by a "fast-redirects"
1174 * line in the config file, has its own log level
1175 * and of course wants to be displayed by show-proxy-args
1176 * Note: Boy, all the #ifdefs in 1001 locations and
1177 * all the fumbling with configure.in and acconfig.h
1178 * were *way* more work than the feature itself :-(
1180 * - Because a generic redirect template was needed for
1181 * this, tinygif = 3 now uses the same.
1183 * - Moved GIFs, and other static HTTP response templates
1186 * - Some minor fixes
1188 * - Removed some >400 CRs again (Jon, you really worked
1191 * Revision 1.4 2001/05/21 19:34:01 jongfoster
1192 * Made failure to bind() a fatal error.
1194 * Revision 1.3 2001/05/20 01:21:20 jongfoster
1195 * Version 2.9.4 checkin.
1196 * - Merged popupfile and cookiefile, and added control over PCRS
1197 * filtering, in new "permissionsfile".
1198 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
1199 * file error you now get a message box (in the Win32 GUI) rather
1200 * than the program exiting with no explanation.
1201 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
1203 * - Removed tabs from "config"
1204 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
1205 * - Bumped up version number.
1207 * Revision 1.2 2001/05/17 22:34:44 oes
1208 * - Added hint on GIF char array generation to jcc.c
1209 * - Cleaned CRLF's from the sources and related files
1210 * - Repaired logging for REF and FRC
1212 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
1213 * Initial import of version 2.9.3 source tree
1216 *********************************************************************/
1222 #include <sys/types.h>
1231 # ifndef FEATURE_PTHREAD
1235 # include <windows.h>
1236 # include <process.h>
1237 # endif /* ndef FEATURE_PTHREAD */
1240 # ifndef _WIN_CONSOLE
1241 # include "w32log.h"
1242 # endif /* ndef _WIN_CONSOLE */
1243 # include "w32svrapi.h"
1245 #else /* ifndef _WIN32 */
1247 # if !defined (__OS2__)
1248 # include <unistd.h>
1249 # include <sys/wait.h>
1250 # endif /* ndef __OS2__ */
1251 # include <sys/time.h>
1252 # include <sys/stat.h>
1253 # include <sys/ioctl.h>
1256 #include <sys/termios.h>
1264 # include <signal.h>
1267 # include <socket.h> /* BeOS has select() for sockets only. */
1268 # include <OS.h> /* declarations for threads and stuff. */
1271 # if defined(__EMX__) || defined(__OS2__)
1272 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
1277 #define bzero(B,N) memset(B,0x00,n)
1281 # include <select.h>
1286 #include "project.h"
1289 #include "filters.h"
1290 #include "loaders.h"
1291 #include "parsers.h"
1292 #include "miscutil.h"
1294 #include "jbsockets.h"
1295 #include "gateway.h"
1296 #include "actions.h"
1298 #include "loadcfg.h"
1299 #include "urlmatch.h"
1301 const char jcc_h_rcs[] = JCC_H_VERSION;
1302 const char project_h_rcs[] = PROJECT_H_VERSION;
1305 struct client_state clients[1];
1306 struct file_list files[1];
1308 #ifdef FEATURE_STATISTICS
1309 int urls_read = 0; /* total nr of urls read inc rejected */
1310 int urls_rejected = 0; /* total nr of urls rejected */
1311 #endif /* def FEATURE_STATISTICS */
1313 #ifdef FEATURE_GRACEFUL_TERMINATION
1314 int g_terminate = 0;
1317 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1318 static void sig_handler(int the_signal);
1320 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
1321 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
1322 static jb_err get_server_headers(struct client_state *csp);
1323 static const char *crunch_reason(const struct http_response *rsp);
1324 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
1325 static char *get_request_line(struct client_state *csp);
1326 static jb_err receive_client_request(struct client_state *csp);
1327 static jb_err parse_client_request(struct client_state *csp);
1328 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
1329 static jb_err change_request_destination(struct client_state *csp);
1330 static void chat(struct client_state *csp);
1331 static void serve(struct client_state *csp);
1332 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1333 static void usage(const char *myname);
1335 static void initialize_mutexes(void);
1336 static jb_socket bind_port_helper(struct configuration_spec *config);
1337 static void listen_loop(void);
1340 void serve(struct client_state *csp);
1341 #else /* ifndef AMIGA */
1342 static void serve(struct client_state *csp);
1343 #endif /* def AMIGA */
1346 static int32 server_thread(void *data);
1347 #endif /* def __BEOS__ */
1350 #define sleep(N) Sleep(((N) * 1000))
1354 #define sleep(N) DosSleep(((N) * 100))
1357 #ifdef MUTEX_LOCKS_AVAILABLE
1359 * XXX: Does the locking stuff really belong in this file?
1361 privoxy_mutex_t log_mutex;
1362 privoxy_mutex_t log_init_mutex;
1363 privoxy_mutex_t connection_reuse_mutex;
1365 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
1366 privoxy_mutex_t resolver_mutex;
1367 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
1369 #ifndef HAVE_GMTIME_R
1370 privoxy_mutex_t gmtime_mutex;
1371 #endif /* ndef HAVE_GMTIME_R */
1373 #ifndef HAVE_LOCALTIME_R
1374 privoxy_mutex_t localtime_mutex;
1375 #endif /* ndef HAVE_GMTIME_R */
1378 privoxy_mutex_t rand_mutex;
1379 #endif /* ndef HAVE_RANDOM */
1381 #endif /* def MUTEX_LOCKS_AVAILABLE */
1384 const char *basedir = NULL;
1385 const char *pidfile = NULL;
1386 static int received_hup_signal = 0;
1387 #endif /* defined unix */
1389 /* HTTP snipplets. */
1390 static const char CSUCCEED[] =
1391 "HTTP/1.0 200 Connection established\r\n"
1392 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
1394 static const char CHEADER[] =
1395 "HTTP/1.0 400 Invalid header received from client\r\n"
1396 "Proxy-Agent: Privoxy " VERSION "\r\n"
1397 "Content-Type: text/plain\r\n"
1398 "Connection: close\r\n\r\n"
1399 "Invalid header received from client.\r\n";
1401 static const char FTP_RESPONSE[] =
1402 "HTTP/1.0 400 Invalid request received from client\r\n"
1403 "Content-Type: text/plain\r\n"
1404 "Connection: close\r\n\r\n"
1405 "Invalid request. Privoxy doesn't support FTP.\r\n";
1407 static const char GOPHER_RESPONSE[] =
1408 "HTTP/1.0 400 Invalid request received from client\r\n"
1409 "Content-Type: text/plain\r\n"
1410 "Connection: close\r\n\r\n"
1411 "Invalid request. Privoxy doesn't support gopher.\r\n";
1413 /* XXX: should be a template */
1414 static const char MISSING_DESTINATION_RESPONSE[] =
1415 "HTTP/1.0 400 Bad request received from client\r\n"
1416 "Proxy-Agent: Privoxy " VERSION "\r\n"
1417 "Content-Type: text/plain\r\n"
1418 "Connection: close\r\n\r\n"
1419 "Bad request. Privoxy was unable to extract the destination.\r\n";
1421 /* XXX: should be a template */
1422 static const char NO_SERVER_DATA_RESPONSE[] =
1423 "HTTP/1.0 502 Server or forwarder response empty\r\n"
1424 "Proxy-Agent: Privoxy " VERSION "\r\n"
1425 "Content-Type: text/plain\r\n"
1426 "Connection: close\r\n\r\n"
1427 "Empty server or forwarder response.\r\n"
1428 "The connection has been closed but Privoxy didn't receive any data.\r\n";
1430 /* XXX: should be a template */
1431 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
1432 "HTTP/1.0 502 Server or forwarder response invalid\r\n"
1433 "Proxy-Agent: Privoxy " VERSION "\r\n"
1434 "Content-Type: text/plain\r\n"
1435 "Connection: close\r\n\r\n"
1436 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
1439 /* XXX: should be a template */
1440 static const char NULL_BYTE_RESPONSE[] =
1441 "HTTP/1.0 400 Bad request received from client\r\n"
1442 "Proxy-Agent: Privoxy " VERSION "\r\n"
1443 "Content-Type: text/plain\r\n"
1444 "Connection: close\r\n\r\n"
1445 "Bad request. Null byte(s) before end of request.\r\n";
1448 /* XXX: should be a template */
1449 static const char MESSED_UP_REQUEST_RESPONSE[] =
1450 "HTTP/1.0 400 Malformed request after rewriting\r\n"
1451 "Proxy-Agent: Privoxy " VERSION "\r\n"
1452 "Content-Type: text/plain\r\n"
1453 "Connection: close\r\n\r\n"
1454 "Bad request. Messed up with header filters.\r\n";
1456 /* XXX: should be a template */
1457 static const char CONNECTION_TIMEOUT_RESPONSE[] =
1458 "HTTP/1.0 502 Connection timeout\r\n"
1459 "Proxy-Agent: Privoxy " VERSION "\r\n"
1460 "Content-Type: text/plain\r\n"
1461 "Connection: close\r\n\r\n"
1462 "The connection timed out.\r\n";
1464 /* A function to crunch a response */
1465 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
1467 /* Crunch function flags */
1468 #define CF_NO_FLAGS 0
1469 /* Cruncher applies to forced requests as well */
1470 #define CF_IGNORE_FORCE 1
1471 /* Crunched requests are counted for the block statistics */
1472 #define CF_COUNT_AS_REJECT 2
1474 /* A crunch function and its flags */
1477 const crunch_func_ptr cruncher;
1481 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
1483 /* Complete list of cruncher functions */
1484 static const struct cruncher crunchers_all[] = {
1485 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
1486 { block_url, CF_COUNT_AS_REJECT },
1487 #ifdef FEATURE_TRUST
1488 { trust_url, CF_COUNT_AS_REJECT },
1489 #endif /* def FEATURE_TRUST */
1490 { redirect_url, CF_NO_FLAGS },
1491 { dispatch_cgi, CF_IGNORE_FORCE},
1495 /* Light version, used after tags are applied */
1496 static const struct cruncher crunchers_light[] = {
1497 { block_url, CF_COUNT_AS_REJECT },
1498 { redirect_url, CF_NO_FLAGS },
1504 * XXX: Don't we really mean
1510 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1511 /*********************************************************************
1513 * Function : sig_handler
1515 * Description : Signal handler for different signals.
1516 * Exit gracefully on TERM and INT
1517 * or set a flag that will cause the errlog
1518 * to be reopened by the main thread on HUP.
1521 * 1 : the_signal = the signal cause this function to call
1525 *********************************************************************/
1526 static void sig_handler(int the_signal)
1532 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
1544 received_hup_signal = 1;
1550 * We shouldn't be here, unless we catch signals
1551 * in main() that we can't handle here!
1553 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
1561 /*********************************************************************
1563 * Function : client_protocol_is_unsupported
1565 * Description : Checks if the client used a known unsupported
1566 * protocol and deals with it by sending an error
1570 * 1 : csp = Current client state (buffers, headers, etc...)
1571 * 2 : req = the first request line send by the client
1573 * Returns : TRUE if an error response has been generated, or
1574 * FALSE if the request doesn't look invalid.
1576 *********************************************************************/
1577 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
1580 * If it's a FTP or gopher request, we don't support it.
1582 * These checks are better than nothing, but they might
1583 * not work in all configurations and some clients might
1584 * have problems digesting the answer.
1586 * They should, however, never cause more problems than
1587 * Privoxy's old behaviour (returning the misleading HTML
1590 * "Could not resolve http://(ftp|gopher)://example.org").
1592 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
1594 const char *response = NULL;
1595 const char *protocol = NULL;
1597 if (!strncmpic(req, "GET ftp://", 10))
1599 response = FTP_RESPONSE;
1604 response = GOPHER_RESPONSE;
1605 protocol = "GOPHER";
1607 log_error(LOG_LEVEL_ERROR,
1608 "%s tried to use Privoxy as %s proxy: %s",
1609 csp->ip_addr_str, protocol, req);
1610 log_error(LOG_LEVEL_CLF,
1611 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
1613 write_socket(csp->cfd, response, strlen(response));
1622 /*********************************************************************
1624 * Function : get_request_destination_elsewhere
1626 * Description : If the client's request was redirected into
1627 * Privoxy without the client's knowledge,
1628 * the request line lacks the destination host.
1630 * This function tries to get it elsewhere,
1631 * provided accept-intercepted-requests is enabled.
1633 * "Elsewhere" currently only means "Host: header",
1634 * but in the future we may ask the redirecting
1635 * packet filter to look the destination up.
1637 * If the destination stays unknown, an error
1638 * response is send to the client and headers
1639 * are freed so that chat() can return directly.
1642 * 1 : csp = Current client state (buffers, headers, etc...)
1643 * 2 : headers = a header list
1645 * Returns : JB_ERR_OK if the destination is now known, or
1646 * JB_ERR_PARSE if it isn't.
1648 *********************************************************************/
1649 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
1653 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
1655 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
1656 " Privoxy isn't configured to accept intercepted requests.",
1657 csp->ip_addr_str, csp->http->cmd);
1658 /* XXX: Use correct size */
1659 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1660 csp->ip_addr_str, csp->http->cmd);
1662 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1663 destroy_list(headers);
1665 return JB_ERR_PARSE;
1667 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
1669 /* Split the domain we just got for pattern matching */
1670 init_domain_components(csp->http);
1676 /* We can't work without destination. Go spread the news.*/
1678 req = list_to_text(headers);
1680 /* XXX: Use correct size */
1681 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1682 csp->ip_addr_str, csp->http->cmd);
1683 log_error(LOG_LEVEL_ERROR,
1684 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
1685 csp->ip_addr_str, csp->http->cmd, req);
1688 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
1689 destroy_list(headers);
1691 return JB_ERR_PARSE;
1694 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
1695 * to get the destination IP address, use it as host directly
1696 * or do a reverse DNS lookup first.
1701 /*********************************************************************
1703 * Function : get_server_headers
1705 * Description : Parses server headers in iob and fills them
1706 * into csp->headers so that they can later be
1710 * 1 : csp = Current client state (buffers, headers, etc...)
1712 * Returns : JB_ERR_OK if everything went fine, or
1713 * JB_ERR_PARSE if the headers were incomplete.
1715 *********************************************************************/
1716 static jb_err get_server_headers(struct client_state *csp)
1718 int continue_hack_in_da_house = 0;
1721 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
1726 * continue hack in da house. Ignore the ending of
1727 * this head and continue enlisting header lines.
1728 * The reason is described below.
1730 enlist(csp->headers, "");
1731 continue_hack_in_da_house = 0;
1734 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
1737 * It's a bodyless continue response, don't
1738 * stop header parsing after reaching its end.
1740 * As a result Privoxy will concatenate the
1741 * next response's head and parse and deliver
1742 * the headers as if they belonged to one request.
1744 * The client will separate them because of the
1745 * empty line between them.
1747 * XXX: What we're doing here is clearly against
1748 * the intended purpose of the continue header,
1749 * and under some conditions (HTTP/1.0 client request)
1750 * it's a standard violation.
1752 * Anyway, "sort of against the spec" is preferable
1753 * to "always getting confused by Continue responses"
1754 * (Privoxy's behaviour before this hack was added)
1756 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
1757 continue_hack_in_da_house = 1;
1759 else if (*header == '\0')
1762 * If the header is empty, but the Continue hack
1763 * isn't active, we can assume that we reached the
1764 * end of the buffer before we hit the end of the
1767 * Inform the caller an let it decide how to handle it.
1769 return JB_ERR_PARSE;
1772 if (JB_ERR_MEMORY == enlist(csp->headers, header))
1775 * XXX: Should we quit the request and return a
1776 * out of memory error page instead?
1778 log_error(LOG_LEVEL_ERROR,
1779 "Out of memory while enlisting server headers. %s lost.",
1789 /*********************************************************************
1791 * Function : crunch_reason
1793 * Description : Translates the crunch reason code into a string.
1796 * 1 : rsp = a http_response
1798 * Returns : A string with the crunch reason or an error description.
1800 *********************************************************************/
1801 static const char *crunch_reason(const struct http_response *rsp)
1803 char * reason = NULL;
1805 assert(rsp != NULL);
1808 return "Internal error while searching for crunch reason";
1811 switch (rsp->reason)
1813 case RSP_REASON_UNSUPPORTED:
1814 reason = "Unsupported HTTP feature";
1816 case RSP_REASON_BLOCKED:
1819 case RSP_REASON_UNTRUSTED:
1820 reason = "Untrusted";
1822 case RSP_REASON_REDIRECTED:
1823 reason = "Redirected";
1825 case RSP_REASON_CGI_CALL:
1826 reason = "CGI Call";
1828 case RSP_REASON_NO_SUCH_DOMAIN:
1829 reason = "DNS failure";
1831 case RSP_REASON_FORWARDING_FAILED:
1832 reason = "Forwarding failed";
1834 case RSP_REASON_CONNECT_FAILED:
1835 reason = "Connection failure";
1837 case RSP_REASON_OUT_OF_MEMORY:
1838 reason = "Out of memory (may mask other reasons)";
1841 reason = "No reason recorded";
1849 /*********************************************************************
1851 * Function : send_crunch_response
1853 * Description : Delivers already prepared response for
1854 * intercepted requests, logs the interception
1855 * and frees the response.
1858 * 1 : csp = Current client state (buffers, headers, etc...)
1859 * 1 : rsp = Fully prepared response. Will be freed on exit.
1861 * Returns : Nothing.
1863 *********************************************************************/
1864 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
1866 const struct http_request *http = csp->http;
1867 char status_code[4];
1869 assert(rsp != NULL);
1870 assert(rsp->head != NULL);
1875 * Not supposed to happen. If it does
1876 * anyway, treat it as an unknown error.
1878 cgi_error_unknown(csp, rsp, RSP_REASON_INTERNAL_ERROR);
1879 /* return code doesn't matter */
1884 /* If rsp is still NULL, we have serious internal problems. */
1885 log_error(LOG_LEVEL_FATAL,
1886 "NULL response in send_crunch_response and cgi_error_unknown failed as well.");
1890 * Extract the status code from the actual head
1891 * that was send to the client. It is the only
1892 * way to get it right for all requests, including
1893 * the fixed ones for out-of-memory problems.
1895 * A head starts like this: 'HTTP/1.1 200...'
1899 status_code[0] = rsp->head[9];
1900 status_code[1] = rsp->head[10];
1901 status_code[2] = rsp->head[11];
1902 status_code[3] = '\0';
1904 /* Write the answer to the client */
1905 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1906 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1908 /* There is nothing we can do about it. */
1909 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
1912 /* Log that the request was crunched and why. */
1913 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
1914 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
1915 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
1917 /* Clean up and return */
1918 if (cgi_error_memory() != rsp)
1920 free_http_response(rsp);
1927 /*********************************************************************
1929 * Function : request_contains_null_bytes
1931 * Description : Checks for NULL bytes in the request and sends
1932 * an error message to the client if any were found.
1934 * XXX: currently not used, see comment in chat().
1937 * 1 : csp = Current client state (buffers, headers, etc...)
1938 * 2 : buf = Data from the client's request to check.
1939 * 3 : len = The data length.
1941 * Returns : TRUE if the request contained one or more NULL bytes, or
1944 *********************************************************************/
1945 static int request_contains_null_bytes(const struct client_state *csp, char *buf, int len)
1947 size_t c_len; /* Request lenght when treated as C string */
1949 c_len = strlen(buf);
1954 * Null byte(s) found. Log the request,
1955 * return an error response and hang up.
1957 size_t tmp_len = c_len;
1962 * Replace NULL byte(s) with '°' characters
1963 * so the request can be logged as string.
1964 * XXX: Is there a better replacement character?
1967 tmp_len += strlen(buf+tmp_len);
1968 } while (tmp_len < len);
1970 log_error(LOG_LEVEL_ERROR, "%s\'s request contains at least one NULL byte "
1971 "(length=%d, strlen=%u).", csp->ip_addr_str, len, c_len);
1972 log_error(LOG_LEVEL_HEADER,
1973 "Offending request data with NULL bytes turned into \'°\' characters: %s", buf);
1975 write_socket(csp->cfd, NULL_BYTE_RESPONSE, strlen(NULL_BYTE_RESPONSE));
1977 /* XXX: Log correct size */
1978 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1988 /*********************************************************************
1990 * Function : crunch_response_triggered
1992 * Description : Checks if the request has to be crunched,
1993 * and delivers the crunch response if necessary.
1996 * 1 : csp = Current client state (buffers, headers, etc...)
1997 * 2 : crunchers = list of cruncher functions to run
1999 * Returns : TRUE if the request was answered with a crunch response
2002 *********************************************************************/
2003 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
2005 struct http_response *rsp = NULL;
2006 const struct cruncher *c;
2009 * If CGI request crunching is disabled,
2010 * check the CGI dispatcher out of order to
2011 * prevent unintentional blocks or redirects.
2013 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
2014 && (NULL != (rsp = dispatch_cgi(csp))))
2016 /* Deliver, log and free the interception response. */
2017 send_crunch_response(csp, rsp);
2021 for (c = crunchers; c->cruncher != NULL; c++)
2024 * Check the cruncher if either Privoxy is toggled
2025 * on and the request isn't forced, or if the cruncher
2026 * applies to forced requests as well.
2028 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
2029 !(csp->flags & CSP_FLAG_FORCED)) ||
2030 (c->flags & CF_IGNORE_FORCE))
2032 rsp = c->cruncher(csp);
2035 /* Deliver, log and free the interception response. */
2036 send_crunch_response(csp, rsp);
2037 #ifdef FEATURE_STATISTICS
2038 if (c->flags & CF_COUNT_AS_REJECT)
2040 csp->flags |= CSP_FLAG_REJECTED;
2042 #endif /* def FEATURE_STATISTICS */
2053 /*********************************************************************
2055 * Function : build_request_line
2057 * Description : Builds the HTTP request line.
2059 * If a HTTP forwarder is used it expects the whole URL,
2060 * web servers only get the path.
2063 * 1 : csp = Current client state (buffers, headers, etc...)
2064 * 2 : fwd = The forwarding spec used for the request
2065 * XXX: Should use http->fwd instead.
2066 * 3 : request_line = The old request line which will be replaced.
2068 * Returns : Nothing. Terminates in case of memory problems.
2070 *********************************************************************/
2071 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
2073 struct http_request *http = csp->http;
2075 assert(http->ssl == 0);
2078 * Downgrade http version from 1.1 to 1.0
2079 * if +downgrade action applies.
2081 if ( (csp->action->flags & ACTION_DOWNGRADE)
2082 && (!strcmpic(http->ver, "HTTP/1.1")))
2085 http->ver = strdup("HTTP/1.0");
2087 if (http->ver == NULL)
2089 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
2094 * Rebuild the request line.
2096 freez(*request_line);
2097 *request_line = strdup(http->gpc);
2098 string_append(request_line, " ");
2100 if (fwd->forward_host)
2102 string_append(request_line, http->url);
2106 string_append(request_line, http->path);
2108 string_append(request_line, " ");
2109 string_append(request_line, http->ver);
2111 if (*request_line == NULL)
2113 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
2115 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
2119 /*********************************************************************
2121 * Function : change_request_destination
2123 * Description : Parse a (rewritten) request line and regenerate
2124 * the http request data.
2127 * 1 : csp = Current client state (buffers, headers, etc...)
2129 * Returns : Forwards the parse_http_request() return code.
2130 * Terminates in case of memory problems.
2132 *********************************************************************/
2133 static jb_err change_request_destination(struct client_state *csp)
2135 struct http_request *http = csp->http;
2138 log_error(LOG_LEVEL_INFO, "Rewrite detected: %s", csp->headers->first->str);
2139 free_http_request(http);
2140 err = parse_http_request(csp->headers->first->str, http);
2141 if (JB_ERR_OK != err)
2143 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2144 jb_err_to_string(err));
2148 /* XXX: ocmd is a misleading name */
2149 http->ocmd = strdup(http->cmd);
2150 if (http->ocmd == NULL)
2152 log_error(LOG_LEVEL_FATAL,
2153 "Out of memory copying rewritten HTTP request line");
2161 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2162 /*********************************************************************
2164 * Function : server_response_is_complete
2166 * Description : Determines whether we should stop reading
2167 * from the server socket.
2170 * 1 : csp = Current client state (buffers, headers, etc...)
2171 * 2 : content_length = Length of content received so far.
2173 * Returns : TRUE if the response is complete,
2176 *********************************************************************/
2177 static int server_response_is_complete(struct client_state *csp,
2178 unsigned long long content_length)
2180 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
2182 if (!strcmpic(csp->http->gpc, "HEAD"))
2185 * "HEAD" implies no body, we are thus expecting
2186 * no content. XXX: incomplete "list" of methods?
2188 csp->expected_content_length = 0;
2189 content_length_known = TRUE;
2192 if (csp->http->status == 304)
2195 * Expect no body. XXX: incomplete "list" of status codes?
2197 csp->expected_content_length = 0;
2198 content_length_known = TRUE;
2201 return (content_length_known && ((0 == csp->expected_content_length)
2202 || (csp->expected_content_length <= content_length)));
2206 /*********************************************************************
2208 * Function : wait_for_alive_connections
2210 * Description : Waits for alive connections to timeout.
2216 *********************************************************************/
2217 static void wait_for_alive_connections()
2219 int connections_alive = close_unusable_connections();
2221 while (0 < connections_alive)
2223 log_error(LOG_LEVEL_CONNECT,
2224 "Waiting for %d connections to timeout.",
2227 connections_alive = close_unusable_connections();
2230 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
2233 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2236 /*********************************************************************
2238 * Function : mark_server_socket_tainted
2240 * Description : Makes sure we don't reuse a server socket
2241 * (if we didn't read everything the server sent
2242 * us reusing the socket would lead to garbage).
2245 * 1 : csp = Current client state (buffers, headers, etc...)
2249 *********************************************************************/
2250 static void mark_server_socket_tainted(struct client_state *csp)
2252 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE))
2254 log_error(LOG_LEVEL_CONNECT, "Unsetting keep-alive flag.");
2255 csp->flags &= ~CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
2259 /*********************************************************************
2261 * Function : get_request_line
2263 * Description : Read the client request line.
2266 * 1 : csp = Current client state (buffers, headers, etc...)
2268 * Returns : Pointer to request line or NULL in case of errors.
2270 *********************************************************************/
2271 static char *get_request_line(struct client_state *csp)
2273 char buf[BUFFER_SIZE];
2274 char *request_line = NULL;
2277 memset(buf, 0, sizeof(buf));
2281 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
2283 log_error(LOG_LEVEL_ERROR,
2284 "Stopped waiting for the request line.");
2285 write_socket(csp->cfd, CONNECTION_TIMEOUT_RESPONSE,
2286 strlen(CONNECTION_TIMEOUT_RESPONSE));
2290 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
2292 if (len <= 0) return NULL;
2295 * If there is no memory left for buffering the
2296 * request, there is nothing we can do but hang up
2298 if (add_to_iob(csp, buf, len))
2303 request_line = get_header(csp->iob);
2305 } while ((NULL != request_line) && ('\0' == *request_line));
2307 return request_line;
2312 /*********************************************************************
2314 * Function : receive_client_request
2316 * Description : Read the client's request (more precisely the
2317 * client headers) and answer it if necessary.
2319 * Note that since we're not using select() we could get
2320 * blocked here if a client connected, then didn't say
2324 * 1 : csp = Current client state (buffers, headers, etc...)
2326 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
2328 *********************************************************************/
2329 static jb_err receive_client_request(struct client_state *csp)
2331 char buf[BUFFER_SIZE];
2334 struct http_request *http;
2338 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
2339 struct list header_list;
2340 struct list *headers = &header_list;
2344 memset(buf, 0, sizeof(buf));
2346 req = get_request_line(csp);
2349 return JB_ERR_PARSE;
2351 assert(*req != '\0');
2353 if (client_protocol_is_unsupported(csp, req))
2355 return JB_ERR_PARSE;
2358 #ifdef FEATURE_FORCE_LOAD
2360 * If this request contains the FORCE_PREFIX and blocks
2361 * aren't enforced, get rid of it and set the force flag.
2363 if (strstr(req, FORCE_PREFIX))
2365 if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
2367 log_error(LOG_LEVEL_FORCE,
2368 "Ignored force prefix in request: \"%s\".", req);
2372 strclean(req, FORCE_PREFIX);
2373 log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
2374 csp->flags |= CSP_FLAG_FORCED;
2377 #endif /* def FEATURE_FORCE_LOAD */
2379 err = parse_http_request(req, http);
2381 if (JB_ERR_OK != err)
2383 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
2384 /* XXX: Use correct size */
2385 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2386 log_error(LOG_LEVEL_ERROR,
2387 "Couldn't parse request line received from %s: %s",
2388 csp->ip_addr_str, jb_err_to_string(err));
2390 free_http_request(http);
2391 return JB_ERR_PARSE;
2394 /* grab the rest of the client's headers */
2398 p = get_header(csp->iob);
2402 /* There are no additional headers to read. */
2409 * We didn't receive a complete header
2410 * line yet, get the rest of it.
2412 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
2414 log_error(LOG_LEVEL_ERROR,
2415 "Stopped grabbing the client headers.");
2416 return JB_ERR_PARSE;
2419 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
2422 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
2423 destroy_list(headers);
2424 return JB_ERR_PARSE;
2427 if (add_to_iob(csp, buf, len))
2430 * If there is no memory left for buffering the
2431 * request, there is nothing we can do but hang up
2433 destroy_list(headers);
2434 return JB_ERR_MEMORY;
2440 * We were able to read a complete
2441 * header and can finaly enlist it.
2448 if (http->host == NULL)
2451 * If we still don't know the request destination,
2452 * the request is invalid or the client uses
2453 * Privoxy without its knowledge.
2455 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
2458 * Our attempts to get the request destination
2459 * elsewhere failed or Privoxy is configured
2460 * to only accept proxy requests.
2462 * An error response has already been send
2463 * and we're done here.
2465 return JB_ERR_PARSE;
2470 * Determine the actions for this URL
2472 #ifdef FEATURE_TOGGLE
2473 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
2475 /* Most compatible set of actions (i.e. none) */
2476 init_current_action(csp->action);
2479 #endif /* ndef FEATURE_TOGGLE */
2481 get_url_actions(csp, http);
2485 * Save a copy of the original request for logging
2487 http->ocmd = strdup(http->cmd);
2488 if (http->ocmd == NULL)
2490 log_error(LOG_LEVEL_FATAL,
2491 "Out of memory copying HTTP request line");
2493 enlist(csp->headers, http->cmd);
2495 /* Append the previously read headers */
2496 list_append_list_unique(csp->headers, headers);
2497 destroy_list(headers);
2504 /*********************************************************************
2506 * Function : parse_client_request
2508 * Description : Parses the client's request and decides what to do
2511 * Note that since we're not using select() we could get
2512 * blocked here if a client connected, then didn't say
2516 * 1 : csp = Current client state (buffers, headers, etc...)
2518 * Returns : JB_ERR_OK or JB_ERR_PARSE
2520 *********************************************************************/
2521 static jb_err parse_client_request(struct client_state *csp)
2523 struct http_request *http = csp->http;
2526 err = sed(csp, FILTER_CLIENT_HEADERS);
2527 if (JB_ERR_OK != err)
2529 /* XXX: Should be handled in sed(). */
2530 assert(err == JB_ERR_PARSE);
2531 log_error(LOG_LEVEL_FATAL, "Failed to parse client headers.");
2533 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
2535 /* Check request line for rewrites. */
2536 if ((NULL == csp->headers->first->str)
2537 || (strcmp(http->cmd, csp->headers->first->str) &&
2538 (JB_ERR_OK != change_request_destination(csp))))
2541 * A header filter broke the request line - bail out.
2543 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
2544 /* XXX: Use correct size */
2545 log_error(LOG_LEVEL_CLF,
2546 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
2547 log_error(LOG_LEVEL_ERROR,
2548 "Invalid request line after applying header filters.");
2549 free_http_request(http);
2551 return JB_ERR_PARSE;
2559 /*********************************************************************
2563 * Description : Once a connection to the client has been accepted,
2564 * this function is called (via serve()) to handle the
2565 * main business of the communication. When this
2566 * function returns, the caller must close the client
2569 * FIXME: chat is nearly thousand lines long.
2573 * 1 : csp = Current client state (buffers, headers, etc...)
2575 * Returns : Nothing.
2577 *********************************************************************/
2578 static void chat(struct client_state *csp)
2580 char buf[BUFFER_SIZE];
2587 int ms_iis5_hack = 0;
2588 unsigned long long byte_count = 0;
2589 int forwarded_connect_retries = 0;
2590 int max_forwarded_connect_retries = csp->config->forwarded_connect_retries;
2591 const struct forward_spec *fwd;
2592 struct http_request *http;
2593 int len = 0; /* for buffer sizes (and negative error codes) */
2595 /* Function that does the content filtering for the current request */
2596 filter_function_ptr content_filter = NULL;
2598 /* Skeleton for HTTP response, if we should intercept the request */
2599 struct http_response *rsp;
2600 struct timeval timeout;
2602 memset(buf, 0, sizeof(buf));
2606 if (receive_client_request(csp) != JB_ERR_OK)
2610 if (parse_client_request(csp) != JB_ERR_OK)
2615 /* decide how to route the HTTP request */
2616 fwd = forward_url(csp, http);
2619 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2620 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2625 * build the http request to send to the server
2626 * we have to do one of the following:
2628 * create = use the original HTTP request to create a new
2629 * HTTP request that has either the path component
2630 * without the http://domainspec (w/path) or the
2631 * full orininal URL (w/url)
2632 * Note that the path and/or the HTTP version may
2633 * have been altered by now.
2635 * connect = Open a socket to the host:port of the server
2636 * and short-circuit server and client socket.
2638 * pass = Pass the request unchanged if forwarding a CONNECT
2639 * request to a parent proxy. Note that we'll be sending
2640 * the CFAIL message ourselves if connecting to the parent
2641 * fails, but we won't send a CSUCCEED message if it works,
2642 * since that would result in a double message (ours and the
2643 * parent's). After sending the request to the parent, we simply
2646 * here's the matrix:
2649 * +--------+--------+
2651 * 0 | create | connect|
2653 * Forwarding +--------+--------+
2655 * 1 | create | pass |
2657 * +--------+--------+
2661 if (http->ssl && connect_port_is_forbidden(csp))
2663 const char *acceptable_connect_ports =
2664 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
2665 assert(NULL != acceptable_connect_ports);
2666 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
2667 "limit-connect{%s} doesn't allow CONNECT requests to port %d.",
2668 csp->ip_addr_str, acceptable_connect_ports, csp->http->port);
2669 csp->action->flags |= ACTION_BLOCK;
2675 freez(csp->headers->first->str);
2676 build_request_line(csp, fwd, &csp->headers->first->str);
2680 * We have a request. Check if one of the crunchers wants it.
2682 if (crunch_response_triggered(csp, crunchers_all))
2685 * Yes. The client got the crunch response
2686 * and we are done here after cleaning up.
2688 /* XXX: why list_remove_all()? */
2689 list_remove_all(csp->headers);
2694 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
2696 if (fwd->forward_host)
2698 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
2699 fwd->forward_host, fwd->forward_port, http->hostport);
2703 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
2706 /* here we connect to the server, gateway, or the forwarder */
2708 while ((csp->sfd = forwarded_connect(fwd, http, csp))
2709 && (errno == EINVAL)
2710 && (forwarded_connect_retries++ < max_forwarded_connect_retries))
2712 log_error(LOG_LEVEL_ERROR,
2713 "failed request #%u to connect to %s. Trying again.",
2714 forwarded_connect_retries, http->hostport);
2717 if (csp->sfd == JB_INVALID_SOCKET)
2719 if (fwd->type != SOCKS_NONE)
2722 rsp = error_response(csp, "forwarding-failed", errno);
2724 else if (errno == EINVAL)
2726 rsp = error_response(csp, "no-such-domain", errno);
2730 rsp = error_response(csp, "connect-failed", errno);
2731 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
2735 /* Write the answer to the client */
2738 send_crunch_response(csp, rsp);
2744 hdr = list_to_text(csp->headers);
2747 /* FIXME Should handle error properly */
2748 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2750 list_remove_all(csp->headers);
2752 if (fwd->forward_host || (http->ssl == 0))
2755 * Write the client's (modified) header to the server
2756 * (along with anything else that may be in the buffer)
2758 if (write_socket(csp->sfd, hdr, strlen(hdr))
2759 || (flush_socket(csp->sfd, csp->iob) < 0))
2761 log_error(LOG_LEVEL_CONNECT,
2762 "write header to: %s failed: %E", http->hostport);
2764 rsp = error_response(csp, "connect-failed", errno);
2767 send_crunch_response(csp, rsp);
2777 * We're running an SSL tunnel and we're not forwarding,
2778 * so just send the "connect succeeded" message to the
2779 * client, flush the rest, and get out of the way.
2781 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
2789 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
2791 /* we're finished with the client's header */
2794 maxfd = (csp->cfd > csp->sfd) ? csp->cfd : csp->sfd;
2796 /* pass data between the client and server
2797 * until one or the other shuts down the connection.
2806 * FD_ZERO here seems to point to an errant macro which crashes.
2807 * So do this by hand for now...
2809 memset(&rfds,0x00,sizeof(fd_set));
2813 FD_SET(csp->cfd, &rfds);
2814 FD_SET(csp->sfd, &rfds);
2816 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2817 if ((csp->flags & CSP_FLAG_CHUNKED)
2818 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2819 && ((csp->iob->eod - csp->iob->cur) >= 5)
2820 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2822 log_error(LOG_LEVEL_CONNECT,
2823 "Looks like we read the last chunk together with "
2824 "the server headers. We better stop reading.");
2825 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2826 csp->expected_content_length = byte_count;
2827 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2829 if (server_body && server_response_is_complete(csp, byte_count))
2831 log_error(LOG_LEVEL_CONNECT,
2832 "Done reading from server. Expected content length: %llu. "
2833 "Actual content length: %llu. Most recently received: %d.",
2834 csp->expected_content_length, byte_count, len);
2837 * XXX: should not jump around,
2838 * chat() is complicated enough already.
2842 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2844 timeout.tv_sec = csp->config->socket_timeout;
2845 timeout.tv_usec = 0;
2846 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2850 log_error(LOG_LEVEL_ERROR,
2851 "Didn't receive data in time: %s", http->url);
2852 if ((byte_count == 0) && (http->ssl == 0))
2854 write_socket(csp->cfd, CONNECTION_TIMEOUT_RESPONSE,
2855 strlen(CONNECTION_TIMEOUT_RESPONSE));
2857 mark_server_socket_tainted(csp);
2862 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2863 mark_server_socket_tainted(csp);
2868 * This is the body of the browser's request,
2869 * just read and write it.
2871 if (FD_ISSET(csp->cfd, &rfds))
2873 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
2877 /* XXX: not sure if this is necessary. */
2878 mark_server_socket_tainted(csp);
2879 break; /* "game over, man" */
2882 if (write_socket(csp->sfd, buf, (size_t)len))
2884 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2885 mark_server_socket_tainted(csp);
2892 * The server wants to talk. It could be the header or the body.
2893 * If `hdr' is null, then it's the header otherwise it's the body.
2894 * FIXME: Does `hdr' really mean `host'? No.
2896 if (FD_ISSET(csp->sfd, &rfds))
2899 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
2903 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2905 if (http->ssl && (fwd->forward_host == NULL))
2908 * Just hang up. We already confirmed the client's CONNECT
2909 * request with status code 200 and unencrypted content is
2910 * no longer welcome.
2912 log_error(LOG_LEVEL_ERROR,
2913 "CONNECT already confirmed. Unable to tell the client about the problem.");
2916 else if (byte_count)
2919 * Just hang up. We already transmitted the original headers
2920 * and parts of the original content and therefore missed the
2921 * chance to send an error message (without risking data corruption).
2923 * XXX: we could retry with a fancy range request here.
2925 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2926 "Unable to tell the client about the problem.");
2927 mark_server_socket_tainted(csp);
2931 rsp = error_response(csp, "connect-failed", errno);
2934 send_crunch_response(csp, rsp);
2940 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2941 if (csp->flags & CSP_FLAG_CHUNKED)
2943 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2945 /* XXX: this is a temporary hack */
2946 log_error(LOG_LEVEL_CONNECT,
2947 "Looks like we reached the end of the last chunk. "
2948 "We better stop reading.");
2949 csp->expected_content_length = byte_count + (unsigned long long)len;
2950 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2954 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2957 * Add a trailing zero to let be able to use string operations.
2958 * XXX: do we still need this with filter_popups gone?
2963 * Normally, this would indicate that we've read
2964 * as much as the server has sent us and we can
2965 * close the client connection. However, Microsoft
2966 * in its wisdom has released IIS/5 with a bug that
2967 * prevents it from sending the trailing \r\n in
2968 * a 302 redirect header (and possibly other headers).
2969 * To work around this if we've haven't parsed
2970 * a full header we'll append a trailing \r\n
2971 * and see if this now generates a valid one.
2973 * This hack shouldn't have any impacts. If we've
2974 * already transmitted the header or if this is a
2975 * SSL connection, then we won't bother with this
2976 * hack. So we only work on partially received
2977 * headers. If we append a \r\n and this still
2978 * doesn't generate a valid header, then we won't
2979 * transmit anything to the client.
2984 if (server_body || http->ssl)
2987 * If we have been buffering up the document,
2988 * now is the time to apply content modification
2989 * and send the result to the client.
2993 p = execute_content_filter(csp, content_filter);
2995 * If the content filter fails, use the original
2996 * buffer and length.
2997 * (see p != NULL ? p : csp->iob->cur below)
3001 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3004 if (JB_ERR_OK != update_server_headers(csp))
3006 log_error(LOG_LEVEL_FATAL,
3007 "Failed to update server headers. after filtering.");
3010 hdr = list_to_text(csp->headers);
3013 /* FIXME Should handle error properly */
3014 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3017 if (write_socket(csp->cfd, hdr, strlen(hdr))
3018 || write_socket(csp->cfd,
3019 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
3021 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3024 mark_server_socket_tainted(csp);
3032 break; /* "game over, man" */
3036 * This is NOT the body, so
3037 * Let's pretend the server just sent us a blank line.
3039 snprintf(buf, sizeof(buf), "\r\n");
3040 len = (int)strlen(buf);
3043 * Now, let the normal header parsing algorithm below do its
3044 * job. If it fails, we'll exit instead of continuing.
3051 * If this is an SSL connection or we're in the body
3052 * of the server document, just write it to the client,
3053 * unless we need to buffer the body for later content-filtering
3055 if (server_body || http->ssl)
3060 * If there is no memory left for buffering the content, or the buffer limit
3061 * has been reached, switch to non-filtering mode, i.e. make & write the
3062 * header, flush the iob and buf, and get out of the way.
3064 if (add_to_iob(csp, buf, len))
3069 log_error(LOG_LEVEL_INFO,
3070 "Flushing header and buffers. Stepping back from filtering.");
3072 hdr = list_to_text(csp->headers);
3076 * Memory is too tight to even generate the header.
3077 * Send our static "Out-of-memory" page.
3079 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3080 rsp = cgi_error_memory();
3081 send_crunch_response(csp, rsp);
3082 mark_server_socket_tainted(csp);
3085 hdrlen = strlen(hdr);
3087 if (write_socket(csp->cfd, hdr, hdrlen)
3088 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
3089 || (write_socket(csp->cfd, buf, (size_t)len)))
3091 log_error(LOG_LEVEL_CONNECT,
3092 "Flush header and buffers to client failed: %E");
3094 mark_server_socket_tainted(csp);
3099 * Reset the byte_count to the amount of bytes
3100 * we just flushed. len will be added a few lines below,
3101 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3103 byte_count = (unsigned long long)flushed;
3105 content_filter = NULL;
3111 if (write_socket(csp->cfd, buf, (size_t)len))
3113 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3114 mark_server_socket_tainted(csp);
3118 byte_count += (unsigned long long)len;
3123 const char *header_start;
3125 * We're still looking for the end of the server's header.
3126 * Buffer up the data we just read. If that fails, there's
3127 * little we can do but send our static out-of-memory page.
3129 if (add_to_iob(csp, buf, len))
3131 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3132 rsp = cgi_error_memory();
3133 send_crunch_response(csp, rsp);
3134 mark_server_socket_tainted(csp);
3138 header_start = csp->iob->cur;
3140 /* Convert iob into something sed() can digest */
3141 if (JB_ERR_PARSE == get_server_headers(csp))
3146 * Well, we tried our MS IIS/5 hack and it didn't work.
3147 * The header is incomplete and there isn't anything
3148 * we can do about it.
3150 log_error(LOG_LEVEL_INFO,
3151 "MS IIS5 hack didn't produce valid headers.");
3157 * Since we have to wait for more from the server before
3158 * we can parse the headers we just continue here.
3160 long header_offset = csp->iob->cur - header_start;
3161 assert(csp->iob->cur >= header_start);
3162 byte_count += (unsigned long long)(len - header_offset);
3163 log_error(LOG_LEVEL_CONNECT, "Continuing buffering headers. "
3164 "byte_count: %llu. header_offset: %d. len: %d.",
3165 byte_count, header_offset, len);
3170 /* Did we actually get anything? */
3171 if (NULL == csp->headers->first)
3173 log_error(LOG_LEVEL_ERROR, "Empty server or forwarder response.");
3174 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3175 write_socket(csp->cfd, NO_SERVER_DATA_RESPONSE, strlen(NO_SERVER_DATA_RESPONSE));
3176 free_http_request(http);
3177 mark_server_socket_tainted(csp);
3181 assert(csp->headers->first->str);
3183 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3184 strncmpic(csp->headers->first->str, "ICY", 3))
3187 * It doesn't look like a HTTP (or Shoutcast) response:
3188 * tell the client and log the problem.
3190 if (strlen(csp->headers->first->str) > 30)
3192 csp->headers->first->str[30] = '\0';
3194 log_error(LOG_LEVEL_ERROR,
3195 "Invalid server or forwarder response. Starts with: %s",
3196 csp->headers->first->str);
3197 log_error(LOG_LEVEL_CLF,
3198 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3199 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3200 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3201 free_http_request(http);
3202 mark_server_socket_tainted(csp);
3207 * We have now received the entire server header,
3208 * filter it and send the result to the client
3210 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3212 log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
3214 hdr = list_to_text(csp->headers);
3217 /* FIXME Should handle error properly */
3218 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3221 if (crunch_response_triggered(csp, crunchers_light))
3224 * One of the tags created by a server-header
3225 * tagger triggered a crunch. We already
3226 * delivered the crunch response to the client
3227 * and are done here after cleaning up.
3230 mark_server_socket_tainted(csp);
3233 /* Buffer and pcrs filter this if appropriate. */
3235 if (!http->ssl) /* We talk plaintext */
3237 content_filter = get_filter_function(csp);
3240 * Only write if we're not buffering for content modification
3242 if (!content_filter)
3245 * Write the server's (modified) header to
3246 * the client (along with anything else that
3247 * may be in the buffer)
3250 if (write_socket(csp->cfd, hdr, strlen(hdr))
3251 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
3253 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
3256 * The write failed, so don't bother mentioning it
3257 * to the client... it probably can't hear us anyway.
3260 mark_server_socket_tainted(csp);
3264 byte_count += (unsigned long long)len;
3269 * XXX: the header lenght should probably
3270 * be calculated by get_server_headers().
3272 long header_length = csp->iob->cur - header_start;
3273 assert(csp->iob->cur > header_start);
3274 byte_count += (unsigned long long)(len - header_length);
3277 /* we're finished with the server's header */
3283 * If this was a MS IIS/5 hack then it means the server
3284 * has already closed the connection. Nothing more to read.
3289 log_error(LOG_LEVEL_INFO,
3290 "Closed server connection detected with MS IIS5 hack enabled.");
3296 mark_server_socket_tainted(csp);
3297 return; /* huh? we should never get here */
3300 if (csp->content_length == 0)
3303 * If Privoxy didn't recalculate the Content-Lenght,
3304 * byte_count is still correct.
3306 csp->content_length = byte_count;
3309 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3310 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3311 && (csp->expected_content_length != byte_count))
3313 log_error(LOG_LEVEL_CONNECT,
3314 "Received %llu bytes while expecting %llu.",
3315 byte_count, csp->expected_content_length);
3316 mark_server_socket_tainted(csp);
3320 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3321 csp->ip_addr_str, http->ocmd, csp->content_length);
3325 /*********************************************************************
3329 * Description : This is little more than chat. We only "serve" to
3330 * to close any socket that chat may have opened.
3333 * 1 : csp = Current client state (buffers, headers, etc...)
3337 *********************************************************************/
3339 void serve(struct client_state *csp)
3340 #else /* ifndef AMIGA */
3341 static void serve(struct client_state *csp)
3342 #endif /* def AMIGA */
3345 close_socket(csp->cfd);
3347 if (csp->sfd != JB_INVALID_SOCKET)
3349 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3350 static int monitor_thread_running = 0;
3352 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3353 && (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE))
3355 remember_connection(csp->sfd, csp->http, forward_url(csp, csp->http));
3356 privoxy_mutex_lock(&connection_reuse_mutex);
3357 if (!monitor_thread_running)
3359 monitor_thread_running = 1;
3360 privoxy_mutex_unlock(&connection_reuse_mutex);
3361 wait_for_alive_connections();
3362 privoxy_mutex_lock(&connection_reuse_mutex);
3363 monitor_thread_running = 0;
3365 privoxy_mutex_unlock(&connection_reuse_mutex);
3369 forget_connection(csp->sfd);
3370 close_socket(csp->sfd);
3373 close_socket(csp->sfd);
3374 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3377 csp->flags &= ~CSP_FLAG_ACTIVE;
3383 /*********************************************************************
3385 * Function : server_thread
3387 * Description : We only exist to call `serve' in a threaded environment.
3390 * 1 : data = Current client state (buffers, headers, etc...)
3392 * Returns : Always 0.
3394 *********************************************************************/
3395 static int32 server_thread(void *data)
3397 serve((struct client_state *) data);
3404 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3405 /*********************************************************************
3409 * Description : Print usage info & exit.
3411 * Parameters : Pointer to argv[0] for identifying ourselves
3415 *********************************************************************/
3416 static void usage(const char *myname)
3418 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3422 #endif /* defined(unix) */
3425 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3426 #endif /* defined(unix) */
3427 "[--version] [configfile]\n"
3428 "Aborting\n", myname);
3433 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3436 #ifdef MUTEX_LOCKS_AVAILABLE
3437 /*********************************************************************
3439 * Function : privoxy_mutex_lock
3441 * Description : Locks a mutex.
3444 * 1 : mutex = The mutex to lock.
3446 * Returns : Void. May exit in case of errors.
3448 *********************************************************************/
3449 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3451 #ifdef FEATURE_PTHREAD
3452 int err = pthread_mutex_lock(mutex);
3455 if (mutex != &log_mutex)
3457 log_error(LOG_LEVEL_FATAL,
3458 "Mutex locking failed: %s.\n", strerror(err));
3463 EnterCriticalSection(mutex);
3464 #endif /* def FEATURE_PTHREAD */
3468 /*********************************************************************
3470 * Function : privoxy_mutex_unlock
3472 * Description : Unlocks a mutex.
3475 * 1 : mutex = The mutex to unlock.
3477 * Returns : Void. May exit in case of errors.
3479 *********************************************************************/
3480 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3482 #ifdef FEATURE_PTHREAD
3483 int err = pthread_mutex_unlock(mutex);
3486 if (mutex != &log_mutex)
3488 log_error(LOG_LEVEL_FATAL,
3489 "Mutex unlocking failed: %s.\n", strerror(err));
3494 LeaveCriticalSection(mutex);
3495 #endif /* def FEATURE_PTHREAD */
3499 /*********************************************************************
3501 * Function : privoxy_mutex_init
3503 * Description : Prepares a mutex.
3506 * 1 : mutex = The mutex to initialize.
3508 * Returns : Void. May exit in case of errors.
3510 *********************************************************************/
3511 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3513 #ifdef FEATURE_PTHREAD
3514 int err = pthread_mutex_init(mutex, 0);
3517 printf("Fatal error. Mutex initialization failed: %s.\n",
3522 InitializeCriticalSection(mutex);
3523 #endif /* def FEATURE_PTHREAD */
3525 #endif /* def MUTEX_LOCKS_AVAILABLE */
3527 /*********************************************************************
3529 * Function : initialize_mutexes
3531 * Description : Prepares mutexes if mutex support is available.
3535 * Returns : Void, exits in case of errors.
3537 *********************************************************************/
3538 static void initialize_mutexes(void)
3540 #ifdef MUTEX_LOCKS_AVAILABLE
3542 * Prepare global mutex semaphores
3544 privoxy_mutex_init(&log_mutex);
3545 privoxy_mutex_init(&log_init_mutex);
3546 privoxy_mutex_init(&connection_reuse_mutex);
3549 * XXX: The assumptions below are a bit naive
3550 * and can cause locks that aren't necessary.
3552 * For example older FreeBSD versions (< 6.x?)
3553 * have no gethostbyname_r, but gethostbyname is
3556 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3557 privoxy_mutex_init(&resolver_mutex);
3558 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3560 * XXX: should we use a single mutex for
3561 * localtime() and gmtime() as well?
3563 #ifndef HAVE_GMTIME_R
3564 privoxy_mutex_init(&gmtime_mutex);
3565 #endif /* ndef HAVE_GMTIME_R */
3567 #ifndef HAVE_LOCALTIME_R
3568 privoxy_mutex_init(&localtime_mutex);
3569 #endif /* ndef HAVE_GMTIME_R */
3572 privoxy_mutex_init(&rand_mutex);
3573 #endif /* ndef HAVE_RANDOM */
3574 #endif /* def MUTEX_LOCKS_AVAILABLE */
3578 /*********************************************************************
3582 * Description : Load the config file and start the listen loop.
3583 * This function is a lot more *sane* with the `load_config'
3584 * and `listen_loop' functions; although it stills does
3585 * a *little* too much for my taste.
3588 * 1 : argc = Number of parameters (including $0).
3589 * 2 : argv = Array of (char *)'s to the parameters.
3591 * Returns : 1 if : can't open config file, unrecognized directive,
3592 * stats requested in multi-thread mode, can't open the
3593 * log file, can't open the jar file, listen port is invalid,
3594 * any load fails, and can't bind port.
3596 * Else main never returns, the process must be signaled
3597 * to terminate execution. Or, on Windows, use the
3598 * "File", "Exit" menu option.
3600 *********************************************************************/
3602 int real_main(int argc, const char *argv[])
3604 int main(int argc, const char *argv[])
3608 unsigned int random_seed;
3610 struct passwd *pw = NULL;
3611 struct group *grp = NULL;
3614 char *pre_chroot_nslookup_to_load_resolver = NULL;
3621 #if !defined(_WIN32)
3628 /* Prepare mutexes if supported and necessary. */
3629 initialize_mutexes();
3631 /* Enable logging until further notice. */
3635 * Parse the command line arguments
3637 * XXX: simply printing usage information in case of
3638 * invalid arguments isn't particularly user friendly.
3640 while (++argc_pos < argc)
3643 /* Check to see if the service must be installed or uninstalled */
3644 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3646 const char *pName = argv[argc_pos] + 9;
3649 exit( (install_service(pName)) ? 0 : 1 );
3651 else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
3653 const char *pName = argv[argc_pos] + 11;
3656 exit((uninstall_service(pName)) ? 0 : 1);
3658 else if (strcmp(argv[argc_pos], "--service" ) == 0)
3660 bRunAsService = TRUE;
3661 w32_set_service_cwd();
3662 atexit(w32_service_exit_notify);
3665 #endif /* defined(_WIN32) */
3668 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3670 if (strcmp(argv[argc_pos], "--help") == 0)
3675 else if(strcmp(argv[argc_pos], "--version") == 0)
3677 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3683 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
3688 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
3690 if (++argc_pos == argc) usage(argv[0]);
3691 pidfile = strdup(argv[argc_pos]);
3694 else if (strcmp(argv[argc_pos], "--user" ) == 0)
3696 if (++argc_pos == argc) usage(argv[argc_pos]);
3698 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
3701 if (NULL == (grp = getgrnam(p)))
3703 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
3707 if (NULL == (pw = getpwnam(argv[argc_pos])))
3709 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
3712 if (p != NULL) *--p = '\0';
3715 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup" ) == 0)
3717 if (++argc_pos == argc) usage(argv[0]);
3718 pre_chroot_nslookup_to_load_resolver = strdup(argv[argc_pos]);
3721 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
3725 #endif /* defined(unix) */
3727 else if (argc_pos + 1 != argc)
3730 * This is neither the last command line
3731 * option, nor was it recognized before,
3732 * therefore it must be invalid.
3738 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3740 configfile = argv[argc_pos];
3743 } /* -END- while (more arguments) */
3745 show_version(Argv[0]);
3748 if ( *configfile != '/' )
3750 char cwd[BUFFER_SIZE];
3752 size_t abs_file_size;
3754 /* make config-filename absolute here */
3755 if (NULL == getcwd(cwd, sizeof(cwd)))
3757 perror("failed to get current working directory");
3762 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3763 basedir = strdup(cwd);
3765 if (NULL == basedir ||
3766 NULL == (abs_file = malloc(abs_file_size)))
3768 perror("malloc failed");
3771 strlcpy(abs_file, basedir, abs_file_size);
3772 strlcat(abs_file, "/", abs_file_size );
3773 strlcat(abs_file, configfile, abs_file_size);
3774 configfile = abs_file;
3776 #endif /* defined unix */
3780 clients->next = NULL;
3782 /* XXX: factor out initialising after the next stable release. */
3785 #elif defined(_WIN32)
3789 random_seed = (unsigned int)time(NULL);
3791 srandom(random_seed);
3794 #endif /* ifdef HAVE_RANDOM */
3797 * Unix signal handling
3799 * Catch the abort, interrupt and terminate signals for a graceful exit
3800 * Catch the hangup signal so the errlog can be reopened.
3801 * Ignore the broken pipe signals (FIXME: Why?)
3803 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3806 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP, 0 };
3807 const int ignored_signals[] = { SIGPIPE, 0 };
3809 for (idx = 0; catched_signals[idx] != 0; idx++)
3811 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3812 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3814 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3815 #endif /* ifdef sun */
3817 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3821 for (idx = 0; ignored_signals[idx] != 0; idx++)
3823 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
3825 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
3830 #else /* ifdef _WIN32 */
3831 # ifdef _WIN_CONSOLE
3833 * We *are* in a windows console app.
3834 * Print a verbose messages about FAQ's and such
3836 printf("%s", win32_blurb);
3837 # endif /* def _WIN_CONSOLE */
3838 #endif /* def _WIN32 */
3841 /* Initialize the CGI subsystem */
3842 cgi_init_error_messages();
3845 * If runnig on unix and without the --nodaemon
3846 * option, become a daemon. I.e. fork, detach
3847 * from tty and get process group leadership
3860 if ( pid < 0 ) /* error */
3865 else if ( pid != 0 ) /* parent */
3870 * must check for errors
3871 * child died due to missing files aso
3874 wpid = waitpid( pid, &status, WNOHANG );
3883 /* Should be more portable, but not as well tested */
3888 #else /* ndef __FreeBSD__ */
3890 #endif /* ndef __FreeBSD__ */
3891 fd = open("/dev/tty", O_RDONLY);
3894 /* no error check here */
3895 ioctl( fd, TIOCNOTTY,0 );
3900 * stderr (fd 2) will be closed later on, when the
3901 * log file has been parsed.
3908 } /* -END- if (!no_daemon) */
3911 * As soon as we have written the PID file, we can switch
3912 * to the user and group ID indicated by the --user option
3918 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3920 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3924 if (setgroups(1, &grp->gr_gid))
3926 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3929 else if (initgroups(pw->pw_name, pw->pw_gid))
3931 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3937 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3939 /* Read the time zone file from /etc before doing chroot. */
3941 if (NULL != pre_chroot_nslookup_to_load_resolver
3942 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3944 /* Initialize resolver library. */
3945 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3947 if (chroot(pw->pw_dir) < 0)
3949 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3953 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3956 if (setuid(pw->pw_uid))
3958 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3962 char putenv_dummy[64];
3964 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3965 if (putenv(putenv_dummy) != 0)
3967 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3970 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3971 if (putenv(putenv_dummy) != 0)
3973 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3979 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3982 #endif /* defined unix */
3985 /* This will be FALSE unless the command line specified --service
3989 /* Yup, so now we must attempt to establish a connection
3990 * with the service dispatcher. This will only work if this
3991 * process was launched by the service control manager to
3992 * actually run as a service. If this isn't the case, i've
3993 * known it take around 30 seconds or so for the call to return.
3996 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3997 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3999 /* Service has run, and at this point is now being stopped, so just return */
4004 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
4006 /* An error occurred. Usually it's because --service was wrongly specified
4007 * and we were unable to connect to the Service Control Dispatcher because
4008 * it wasn't expecting us and is therefore not listening.
4010 * For now, just continue below to call the listen_loop function.
4013 #endif /* def _WIN32 */
4023 /*********************************************************************
4025 * Function : bind_port_helper
4027 * Description : Bind the listen port. Handles logging, and aborts
4031 * 1 : config = Privoxy configuration. Specifies port
4034 * Returns : Port that was opened.
4036 *********************************************************************/
4037 static jb_socket bind_port_helper(struct configuration_spec * config)
4042 if (config->haddr == NULL)
4044 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
4049 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
4050 config->hport, config->haddr);
4053 result = bind_port(config->haddr, config->hport, &bfd);
4060 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
4061 "There may be another Privoxy or some other "
4062 "proxy running on port %d",
4063 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
4064 config->hport, config->hport);
4067 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
4068 "The hostname is not resolvable",
4069 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
4072 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
4073 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
4076 /* shouldn't get here */
4077 return JB_INVALID_SOCKET;
4080 config->need_bind = 0;
4087 /* Without this simple workaround we get this compiler warning from _beginthread
4088 * warning C4028: formal parameter 1 different from declaration
4090 void w32_service_listen_loop(void *p)
4094 #endif /* def _WIN32 */
4097 /*********************************************************************
4099 * Function : listen_loop
4101 * Description : bind the listen port and enter a "FOREVER" listening loop.
4107 *********************************************************************/
4108 static void listen_loop(void)
4110 struct client_state *csp = NULL;
4112 struct configuration_spec * config;
4114 config = load_config();
4116 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4118 * XXX: Should be relocated once it no
4119 * longer needs to emit log messages.
4121 initialize_reusable_connections();
4122 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4124 bfd = bind_port_helper(config);
4126 #ifdef FEATURE_GRACEFUL_TERMINATION
4127 while (!g_terminate)
4132 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
4133 while (waitpid(-1, NULL, WNOHANG) > 0)
4135 /* zombie children */
4137 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
4140 * Free data that was used by died threads
4146 * Re-open the errlog after HUP signal
4148 if (received_hup_signal)
4150 if (NULL != config->logfile)
4152 init_error_log(Argv[0], config->logfile);
4154 received_hup_signal = 0;
4158 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
4160 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
4164 csp->flags |= CSP_FLAG_ACTIVE;
4165 csp->sfd = JB_INVALID_SOCKET;
4167 csp->config = config = load_config();
4169 if ( config->need_bind )
4172 * Since we were listening to the "old port", we will not see
4173 * a "listen" param change until the next IJB request. So, at
4174 * least 1 more request must be made for us to find the new
4175 * setting. I am simply closing the old socket and binding the
4178 * Which-ever is correct, we will serve 1 more page via the
4179 * old settings. This should probably be a "show-proxy-args"
4180 * request. This should not be a so common of an operation
4181 * that this will hurt people's feelings.
4186 bfd = bind_port_helper(config);
4189 log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
4191 if (!accept_connection(csp, bfd))
4193 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
4206 log_error(LOG_LEVEL_CONNECT, "accepted connection from %s", csp->ip_addr_str);
4209 #ifdef FEATURE_TOGGLE
4210 if (global_toggle_state)
4211 #endif /* def FEATURE_TOGGLE */
4213 csp->flags |= CSP_FLAG_TOGGLED_ON;
4216 if (run_loader(csp))
4218 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
4219 /* Never get here - LOG_LEVEL_FATAL causes program exit */
4223 if (block_acl(NULL,csp))
4225 log_error(LOG_LEVEL_CONNECT, "Connection from %s dropped due to ACL", csp->ip_addr_str);
4226 close_socket(csp->cfd);
4230 #endif /* def FEATURE_ACL */
4232 /* add it to the list of clients */
4233 csp->next = clients->next;
4234 clients->next = csp;
4236 if (config->multi_threaded)
4240 /* this is a switch () statment in the C preprocessor - ugh */
4241 #undef SELECTED_ONE_OPTION
4243 /* Use Pthreads in preference to native code */
4244 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
4245 #define SELECTED_ONE_OPTION
4247 pthread_t the_thread;
4248 pthread_attr_t attrs;
4250 pthread_attr_init(&attrs);
4251 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4252 errno = pthread_create(&the_thread, &attrs,
4253 (void * (*)(void *))serve, csp);
4254 child_id = errno ? -1 : 0;
4255 pthread_attr_destroy(&attrs);
4259 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
4260 #define SELECTED_ONE_OPTION
4261 child_id = _beginthread(
4262 (void (*)(void *))serve,
4267 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
4268 #define SELECTED_ONE_OPTION
4269 child_id = _beginthread(
4270 (void(* _Optlink)(void*))serve,
4276 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
4277 #define SELECTED_ONE_OPTION
4279 thread_id tid = spawn_thread
4280 (server_thread, "server", B_NORMAL_PRIORITY, csp);
4282 if ((tid >= 0) && (resume_thread(tid) == B_OK))
4284 child_id = (int) tid;
4293 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
4294 #define SELECTED_ONE_OPTION
4295 csp->cfd = ReleaseSocket(csp->cfd, -1);
4298 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4299 NP_Output, Output(),
4300 NP_CloseOutput, FALSE,
4301 NP_Name, (ULONG)"privoxy child",
4305 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4306 NP_Output, Output(),
4307 NP_CloseOutput, FALSE,
4308 NP_Name, (ULONG)"privoxy child",
4309 NP_StackSize, 200*1024,
4315 ((struct Task *)child_id)->tc_UserData = csp;
4316 Signal((struct Task *)child_id, SIGF_SINGLE);
4321 #if !defined(SELECTED_ONE_OPTION)
4324 /* This block is only needed when using fork().
4325 * When using threads, the server thread was
4326 * created and run by the call to _beginthread().
4328 if (child_id == 0) /* child */
4331 #ifdef FEATURE_TOGGLE
4332 int inherited_toggle_state = global_toggle_state;
4333 #endif /* def FEATURE_TOGGLE */
4338 * If we've been toggled or we've blocked the request, tell Mom
4341 #ifdef FEATURE_TOGGLE
4342 if (inherited_toggle_state != global_toggle_state)
4344 rc |= RC_FLAG_TOGGLED;
4346 #endif /* def FEATURE_TOGGLE */
4348 #ifdef FEATURE_STATISTICS
4349 if (csp->flags & CSP_FLAG_REJECTED)
4351 rc |= RC_FLAG_BLOCKED;
4353 #endif /* ndef FEATURE_STATISTICS */
4357 else if (child_id > 0) /* parent */
4359 /* in a fork()'d environment, the parent's
4360 * copy of the client socket and the CSP
4364 #if !defined(_WIN32) && !defined(__CYGWIN__)
4366 wait( &child_status );
4369 * Evaluate child's return code: If the child has
4370 * - been toggled, toggle ourselves
4371 * - blocked its request, bump up the stats counter
4374 #ifdef FEATURE_TOGGLE
4375 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4377 global_toggle_state = !global_toggle_state;
4379 #endif /* def FEATURE_TOGGLE */
4381 #ifdef FEATURE_STATISTICS
4383 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4387 #endif /* def FEATURE_STATISTICS */
4389 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4390 close_socket(csp->cfd);
4391 csp->flags &= ~CSP_FLAG_ACTIVE;
4395 #undef SELECTED_ONE_OPTION
4396 /* end of cpp switch () */
4398 if (child_id < 0) /* failed */
4400 char buf[BUFFER_SIZE];
4402 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
4404 snprintf(buf , sizeof(buf), "Privoxy: can't fork: errno = %d", errno);
4406 write_socket(csp->cfd, buf, strlen(buf));
4407 close_socket(csp->cfd);
4408 csp->flags &= ~CSP_FLAG_ACTIVE;
4419 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4421 /* Clean up. Aim: free all memory (no leaks) */
4422 #ifdef FEATURE_GRACEFUL_TERMINATION
4424 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4426 unload_current_config_file();
4427 unload_current_actions_file();
4428 unload_current_re_filterfile();
4429 #ifdef FEATURE_TRUST
4430 unload_current_trust_file();
4433 if (config->multi_threaded)
4440 } while ((clients->next != NULL) && (--i > 0));
4444 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4455 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4456 /* Cleanup - remove taskbar icon etc. */
4461 #endif /* FEATURE_GRACEFUL_TERMINATION */