1 const char jcc_rcs[] = "$Id: jcc.c,v 1.135 2007/05/24 17:03:50 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-2007 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.135 2007/05/24 17:03:50 fabiankeil
37 * - Let usage() mention the --chroot parameter.
38 * - Use read_socket() consistently and always leave
39 * the last buffer byte alone, even in cases where
40 * null termination (currently) doesn't matter.
42 * Revision 1.134 2007/05/16 14:59:46 fabiankeil
43 * - Fix config file loading on Unix if no config file is specified.
44 * Since r1.97 Privoxy would always interpret the last argument as
45 * config file, even if it's a valid command line option.
46 * - Abort in case of unrecognized command line options. Closes #1719696.
47 * - Remove a bunch of unnecessary strcpy() calls (yay for c&p without thinking).
48 * - Replace the remaining strcpy() and strcat() calls with strlcpy() and strcat().
50 * Revision 1.133 2007/05/04 11:23:19 fabiankeil
51 * - Don't rerun crunchers that only depend on the request URL.
52 * - Don't count redirects and CGI requests as "blocked requests".
54 * Revision 1.132 2007/04/25 15:15:17 fabiankeil
55 * Support crunching based on tags created by server-header taggers.
57 * Revision 1.131 2007/04/22 13:24:50 fabiankeil
58 * Make HTTP snippets static (again). Add a Content-Type for those
59 * with content so the browser doesn't guess it based on the URL.
61 * Revision 1.130 2007/04/19 13:47:34 fabiankeil
62 * Move crunching and request line rebuilding out of chat().
64 * Revision 1.129 2007/04/15 16:39:20 fabiankeil
65 * Introduce tags as alternative way to specify which
66 * actions apply to a request. At the moment tags can be
67 * created based on client and server headers.
69 * Revision 1.128 2007/03/25 16:55:54 fabiankeil
70 * Don't CLF-log CONNECT requests twice.
72 * Revision 1.127 2007/03/20 13:53:17 fabiankeil
73 * Log the source address for ACL-related connection drops.
75 * Revision 1.126 2007/03/17 15:20:05 fabiankeil
76 * New config option: enforce-blocks.
78 * Revision 1.125 2007/03/09 14:12:00 fabiankeil
79 * - Move null byte check into separate function.
80 * - Don't confuse the client with error pages
81 * if a CONNECT request was already confirmed.
83 * Revision 1.124 2007/02/23 14:59:54 fabiankeil
84 * Speed up NULL byte escaping and only log the complete
85 * NULL byte requests with header debugging enabled.
87 * Revision 1.123 2007/02/21 18:42:10 fabiankeil
88 * Answer requests that contain NULL bytes with
89 * a custom response instead of waiting for more
90 * data until the client eventually hangs up.
92 * Revision 1.122 2007/02/07 11:12:02 fabiankeil
93 * - Move delivery and logging of crunched responses
94 * from chat() into send_crunch_response().
95 * - Display the reason for generating http_responses.
96 * - Log the content length for LOG_LEVEL_CLF correctly
97 * (still incorrect for some fixed responses).
98 * - Reword an incorrect comment about
99 * treat-forbidden-connects-like-blocks violating
101 * - Add some log messages.
103 * Revision 1.121 2007/01/27 10:52:56 fabiankeil
104 * Move mutex initialization into separate
105 * function and exit in case of errors.
107 * Revision 1.120 2007/01/26 14:18:42 fabiankeil
108 * - Start to reduce chat()'s line count and move
109 * parts of it into separate functions.
110 * - Add "HTTP/1.1 100 Continue" hack for BR 756734.
112 * Revision 1.119 2007/01/25 14:02:30 fabiankeil
113 * - Add Proxy-Agent header to HTTP snippets that are
114 * supposed to reach HTTP clients only.
115 * - Made a few CONNECT log messages more descriptive.
116 * - Catch completely empty server responses (as seen
117 * with Tor's fake ".noconnect" top level domain).
118 * - Use shiny new "forwarding-failed" template for socks errors.
120 * Revision 1.118 2007/01/07 07:43:43 joergs
121 * AmigaOS4 support added.
123 * Revision 1.117 2006/12/31 17:56:37 fabiankeil
124 * Added config option accept-intercepted-requests
125 * and disabled it by default.
127 * Revision 1.116 2006/12/29 19:08:22 fabiankeil
128 * Reverted parts of my last commit
129 * to keep error handling working.
131 * Revision 1.115 2006/12/29 17:38:57 fabiankeil
132 * Fixed gcc43 conversion warnings.
134 * Revision 1.114 2006/12/27 18:52:02 fabiankeil
135 * Fix -pedantic ISO C warning about converting
136 * from function pointer to object pointer.
138 * Revision 1.113 2006/12/26 17:38:50 fabiankeil
139 * Silence compiler warning I introduced with my last commit.
141 * Revision 1.112 2006/12/26 17:31:41 fabiankeil
142 * Mutex protect rand() if POSIX threading
143 * is used, warn the user if that's not possible
144 * and stop using it on _WIN32 where it could
147 * Revision 1.111 2006/12/23 16:15:06 fabiankeil
148 * Don't prevent core dumps by catching SIGABRT.
149 * It's rude and makes debugging unreasonable painful.
151 * Revision 1.110 2006/12/13 14:52:53 etresoft
152 * Fix build failure on MacOS X. Global symbols can be either static or extern, but not both.
154 * Revision 1.109 2006/12/06 19:41:40 fabiankeil
155 * Privoxy is now able to run as intercepting
156 * proxy in combination with any packet filter
157 * that does the port redirection. The destination
158 * is extracted from the "Host:" header which
159 * should be available for nearly all requests.
161 * Moved HTTP snipplets into jcc.c.
162 * Added error message for gopher proxy requests.
164 * Revision 1.108 2006/11/28 15:38:51 fabiankeil
165 * Only unlink the pidfile if it's actually used.
167 * Change order of interception checks to make
168 * it possible to block or redirect requests for
171 * Revision 1.107 2006/11/13 19:05:51 fabiankeil
172 * Make pthread mutex locking more generic. Instead of
173 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
174 * and use mutex locking unless there is an _r function
175 * available. Better safe than sorry.
177 * Fixes "./configure --disable-pthread" and should result
178 * in less threading-related problems on pthread-using platforms,
179 * but it still doesn't fix BR#1122404.
181 * Revision 1.106 2006/11/06 19:58:23 fabiankeil
182 * Move pthread.h inclusion from jcc.c to jcc.h.
183 * Fixes build on x86-freebsd1 (FreeBSD 5.4-RELEASE).
185 * Revision 1.105 2006/11/06 14:26:02 fabiankeil
186 * Don't exit after receiving the second SIGHUP on Solaris.
188 * Fixes BR 1052235, but the same problem may exist on other
189 * systems. Once 3.0.6 is out we should use sigset()
190 * where available and see if it breaks anything.
192 * Revision 1.104 2006/09/23 13:26:38 roro
193 * Replace TABs by spaces in source code.
195 * Revision 1.103 2006/09/21 12:54:43 fabiankeil
196 * Fix +redirect{}. Didn't work with -fast-redirects.
198 * Revision 1.102 2006/09/06 13:03:04 fabiankeil
199 * Respond with 400 and a short text message
200 * if the client tries to use Privoxy as FTP proxy.
202 * Revision 1.101 2006/09/06 09:23:37 fabiankeil
203 * Make number of retries in case of forwarded-connect problems
204 * a config file option (forwarded-connect-retries) and use 0 as
207 * Revision 1.100 2006/09/03 19:42:59 fabiankeil
208 * Set random(3) seed.
210 * Revision 1.99 2006/09/02 15:36:42 fabiankeil
211 * Follow the OpenBSD port's lead and protect the resolve
212 * functions on OpenBSD as well.
214 * Revision 1.98 2006/08/24 11:01:34 fabiankeil
215 * --user fix. Only use the user as group if no group is specified.
216 * Solves BR 1492612. Thanks to Spinor S. and David Laight.
218 * Revision 1.97 2006/08/18 15:23:17 david__schmidt
219 * Windows service (re-)integration
223 * --install[:service_name]
224 * --uninstall[:service_name]
227 * They work as follows:
228 * --install will create a service for you and then terminate.
229 * By default the service name will be "privoxy" (without the quotes).
230 * However you can run multiple services if you wish, just by adding
231 * a colon and then a name (no spaces).
233 * --uninstall follows the exact same rules a --install.
235 * --service is used when the program is executed by the service
236 * control manager, and in normal circumstances would never be
237 * used as a command line argument.
239 * Revision 1.96 2006/08/15 20:12:36 david__schmidt
240 * Windows service integration
242 * Revision 1.95 2006/08/03 02:46:41 david__schmidt
243 * Incorporate Fabian Keil's patch work:
244 http://www.fabiankeil.de/sourcecode/privoxy/
246 * Revision 1.94 2006/07/18 14:48:46 david__schmidt
247 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
248 * with what was really the latest development (the v_3_0_branch branch)
250 * Revision 1.92.2.16 2005/04/03 20:10:50 david__schmidt
251 * Thanks to Jindrich Makovicka for a race condition fix for the log
252 * file. The race condition remains for non-pthread implementations.
253 * Reference patch #1175720.
255 * Revision 1.92.2.15 2004/10/03 12:53:32 david__schmidt
256 * Add the ability to check jpeg images for invalid
257 * lengths of comment blocks. Defensive strategy
258 * against the exploit:
259 * Microsoft Security Bulletin MS04-028
260 * Buffer Overrun in JPEG Processing (GDI+) Could
261 * Allow Code Execution (833987)
262 * Enabled with +inspect-jpegs in actions files.
264 * Revision 1.92.2.14 2003/12/12 12:52:53 oes
265 * - Fixed usage info for non-unix platforms
266 * - Fixed small cmdline parsing bug
268 * Revision 1.92.2.13 2003/11/27 19:20:27 oes
269 * Diagnostics: Now preserve the returncode of pthread_create
270 * in errno. Closes BR #775721. Thanks to Geoffrey Hausheer.
272 * Revision 1.92.2.12 2003/07/11 11:34:19 oes
273 * No longer ignore SIGCHLD. Fixes bug #769381
275 * Revision 1.92.2.11 2003/05/14 12:32:02 oes
276 * Close jarfile on graceful exit, remove stray line
278 * Revision 1.92.2.10 2003/05/08 15:13:46 oes
279 * Cosmetics: Killed a warning, a typo and an allocation left at exit
281 * Revision 1.92.2.9 2003/04/03 15:08:42 oes
282 * No longer rely on non-POSIX.1 extensions of getcwd().
285 * Revision 1.92.2.8 2003/03/31 13:12:32 oes
286 * Replaced setenv() by posix-compliant putenv()
287 * Thanks to Neil McCalden (nmcc AT users.sf.net).
289 * Revision 1.92.2.7 2003/03/17 16:48:59 oes
290 * Added chroot ability, thanks to patch by Sviatoslav Sviridov
292 * Revision 1.92.2.6 2003/03/11 11:55:00 oes
293 * Clean-up and extension of improvements for forked mode:
294 * - Child's return code now consists of flags RC_FLAG_*
295 * - Reporting toggle to parent now properly #ifdef'ed
296 * - Children now report blocking to parent. This enables
297 * statistics in forked mode
299 * Revision 1.92.2.5 2003/03/10 23:45:32 oes
300 * Fixed bug #700381: Non-Threaded version now capable of being toggled.
301 * Children now report having been toggled through _exit(17), parents
302 * watch for that code and toggle themselves if found.
304 * Revision 1.92.2.4 2003/03/07 03:41:04 david__schmidt
305 * Wrapping all *_r functions (the non-_r versions of them) with
306 * mutex semaphores for OSX. Hopefully this will take care of all
307 * of those pesky crash reports.
309 * Revision 1.92.2.3 2003/02/28 12:53:06 oes
310 * Fixed two mostly harmless mem leaks
312 * Revision 1.92.2.2 2002/11/20 14:37:47 oes
313 * Fix: Head of global clients list now initialized to NULL
315 * Revision 1.92.2.1 2002/09/25 14:52:24 oes
316 * Added basic support for OPTIONS and TRACE HTTP methods:
317 * - New interceptor direct_response() added in chat().
318 * - sed() moved to earlier in the process, so that the
319 * Host: header is evaluated before actions and forwarding
322 * Revision 1.92 2002/05/08 16:00:46 oes
323 * Chat's buffer handling:
324 * - Fixed bug with unchecked out-of-mem conditions
325 * while reading client request & server headers
326 * - No longer predict if the buffer limit will be exceeded
327 * in the next read -- check add_to_iob's new
328 * return code. If buffer couldn't be extended
329 * (policy or out-of-mem) while
330 * - reading from client: abort
331 * - reading server headers: send error page
332 * - buffering server body for filter: flush,
333 * and if that fails: send error page
335 * Revision 1.91 2002/04/08 20:35:58 swa
338 * Revision 1.90 2002/04/02 14:57:28 oes
339 * Made sending wafers independent of FEATURE_COOKIE_JAR
341 * Revision 1.89 2002/03/31 17:18:59 jongfoster
342 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
344 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
345 * More compiler warning message maintenance
347 * Revision 1.87 2002/03/26 22:29:54 swa
348 * we have a new homepage!
350 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
351 * Workaround for closing the jarfile before load_config() comes around again
353 * Revision 1.85 2002/03/24 15:23:33 jongfoster
356 * Revision 1.84 2002/03/24 13:25:43 swa
357 * name change related issues
359 * Revision 1.83 2002/03/16 23:54:06 jongfoster
360 * Adding graceful termination feature, to help look for memory leaks.
361 * If you enable this (which, by design, has to be done by hand
362 * editing config.h) and then go to http://i.j.b/die, then the program
363 * will exit cleanly after the *next* request. It should free all the
364 * memory that was used.
366 * Revision 1.82 2002/03/13 00:27:05 jongfoster
369 * Revision 1.81 2002/03/12 01:42:50 oes
370 * Introduced modular filters
372 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
373 * OS/2 port maintenance:
374 * - Fixed EMX build - it had decayed a little
375 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
376 * substituted a memset for now.
378 * Revision 1.79 2002/03/09 20:03:52 jongfoster
379 * - Making various functions return int rather than size_t.
380 * (Undoing a recent change). Since size_t is unsigned on
381 * Windows, functions like read_socket that return -1 on
382 * error cannot return a size_t.
384 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
385 * crashes, and also frequently caused JB to jump to 100%
386 * CPU and stay there. (Because it thought it had just
387 * read ((unsigned)-1) == 4Gb of data...)
389 * - The signature of write_socket has changed, it now simply
390 * returns success=0/failure=nonzero.
392 * - Trying to get rid of a few warnings --with-debug on
393 * Windows, I've introduced a new type "jb_socket". This is
394 * used for the socket file descriptors. On Windows, this
395 * is SOCKET (a typedef for unsigned). Everywhere else, it's
396 * an int. The error value can't be -1 any more, so it's
397 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
398 * Windows it maps to the #define INVALID_SOCKET.)
400 * - The signature of bind_port has changed.
402 * Revision 1.78 2002/03/08 21:35:04 oes
403 * Added optional group supplement to --user option. Will now use default group of user if no group given
405 * Revision 1.77 2002/03/07 03:52:06 oes
406 * - Fixed compiler warnings etc
407 * - Improved handling of failed DNS lookups
409 * Revision 1.76 2002/03/06 22:54:35 jongfoster
410 * Automated function-comment nitpicking.
412 * Revision 1.75 2002/03/06 10:02:19 oes
413 * Fixed stupid bug when --user was not given
415 * Revision 1.74 2002/03/06 00:49:31 jongfoster
416 * Fixing warning on Windows
417 * Making #ifdefs that refer to the same variable consistently
418 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
420 * Revision 1.73 2002/03/05 23:57:30 hal9
421 * Stray character 's' on line 1618 was breaking build.
423 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
424 * - Re-enable OS/2 building after new parms were added
425 * - Fix false out of memory report when resolving CGI templates when no IP
426 * address is available of failed attempt (a la no such domain)
428 * Revision 1.71 2002/03/05 18:13:56 oes
429 * Added --user option
431 * Revision 1.70 2002/03/05 04:52:42 oes
432 * Deleted non-errlog debugging code
434 * Revision 1.69 2002/03/04 23:50:00 jongfoster
435 * Splitting off bind_port() call into bind_port_helper(), with
438 * Revision 1.68 2002/03/04 20:17:32 oes
441 * Revision 1.67 2002/03/04 18:18:57 oes
442 * - Removed _DEBUG mode
443 * - Cleand up cmdline parsing
444 * - Introduced --no-daemon, --pidfile options
445 * - Cleaned up signal handling:
446 * - Terminate cleanly on INT, TERM and ABRT
447 * - Schedule logfile for re-opening on HUP
448 * - Ignore CHLD and PIPE
449 * - Leave the rest with their default handlers
450 * - Uniform handler registration
451 * - Added usage() function
452 * - Played styleguide police
454 * Revision 1.66 2002/03/03 15:06:55 oes
455 * Re-enabled automatic config reloading
457 * Revision 1.65 2002/03/03 14:49:11 oes
458 * Fixed CLF logging: Now uses client's original HTTP request
460 * Revision 1.64 2002/03/03 09:18:03 joergs
461 * Made jumbjuster work on AmigaOS again.
463 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
464 * Clean up a little CRLF unpleasantness that suddenly appeared
466 * Revision 1.62 2002/02/20 23:17:23 jongfoster
467 * Detecting some out-of memory conditions and exiting with a log message.
469 * Revision 1.61 2002/01/17 21:01:52 jongfoster
470 * Moving all our URL and URL pattern parsing code to urlmatch.c.
472 * Revision 1.60 2001/12/30 14:07:32 steudten
473 * - Add signal handling (unix)
474 * - Add SIGHUP handler (unix)
475 * - Add creation of pidfile (unix)
476 * - Add action 'top' in rc file (RH)
477 * - Add entry 'SIGNALS' to manpage
478 * - Add exit message to logfile (unix)
480 * Revision 1.59 2001/12/13 14:07:18 oes
481 * Fixed Bug: 503 error page now sent OK
483 * Revision 1.58 2001/11/30 23:37:24 jongfoster
484 * Renaming the Win32 config file to config.txt - this is almost the
485 * same as the corresponding UNIX name "config"
487 * Revision 1.57 2001/11/16 00:47:43 jongfoster
488 * Changing the tty-disconnection code to use setsid().
490 * Revision 1.56 2001/11/13 20:20:54 jongfoster
491 * Tabs->spaces, fixing a bug with missing {} around an if()
493 * Revision 1.55 2001/11/13 20:14:53 jongfoster
494 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
496 * Revision 1.54 2001/11/07 00:03:14 steudten
497 * Give reliable return value if an error
498 * occurs not just 0 with new daemon mode.
500 * Revision 1.53 2001/11/05 21:41:43 steudten
501 * Add changes to be a real daemon just for unix os.
502 * (change cwd to /, detach from controlling tty, set
503 * process group and session leader to the own process.
505 * Add some fatal-error log message for failed malloc().
506 * Add '-d' if compiled with 'configure --with-debug' to
507 * enable debug output.
509 * Revision 1.52 2001/10/26 20:11:20 jongfoster
510 * Fixing type mismatch
512 * Revision 1.51 2001/10/26 17:38:28 oes
515 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
516 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
517 * threads to call select() simultaneously. So, it's time to do a real, live,
518 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
519 * (native). Both versions will work, but using __OS2__ offers multi-threading.
521 * Revision 1.49 2001/10/23 21:41:35 jongfoster
522 * Added call to initialize the (statically-allocated of course)
523 * "out of memory" CGI response.
525 * Revision 1.48 2001/10/10 19:56:46 jongfoster
526 * Moving some code that wasn't cookie-related out of an #ifdef
529 * Revision 1.47 2001/10/10 16:44:36 oes
530 * Added CONNECT destination port limitation check
532 * Revision 1.46 2001/10/08 15:17:41 oes
533 * Re-enabled SSL forwarding
535 * Revision 1.45 2001/10/07 15:42:11 oes
536 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
538 * Moved downgrading of the HTTP version from parse_http_request to
539 * chat(), since we can't decide if it is necessary before we have
540 * determined the actions for the URL. The HTTP command is now
541 * *always* re-built so the repairs need no longer be special-cased.
543 * filter_popups now gets a csp pointer so it can raise the new
544 * CSP_FLAG_MODIFIED flag.
548 * Added configurable size limit for the IOB. If the IOB grows so
549 * large that the next read would exceed the limit, the header
550 * is generated, and the header & unfiltered buffer are flushed
551 * to the client. Chat then continues in non-buffering,
552 * non-filtering body mode.
554 * Revision 1.44 2001/10/02 18:13:57 oes
557 * Revision 1.43 2001/10/02 15:32:13 oes
558 * Moved generation of hdr
560 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
561 * Cleaning up 2 compiler warnings on OS/2.
563 * Revision 1.41 2001/09/16 17:05:14 jongfoster
564 * Removing unused #include showarg.h
566 * Revision 1.40 2001/09/16 15:41:45 jongfoster
567 * Fixing signed/unsigned comparison warning.
569 * Revision 1.39 2001/09/16 13:21:27 jongfoster
570 * Changes to use new list functions.
572 * Revision 1.38 2001/09/16 13:01:46 jongfoster
573 * Removing redundant function call that zeroed zalloc()'d memory.
575 * Revision 1.37 2001/09/10 11:12:24 oes
576 * Deleted unused variable
578 * Revision 1.36 2001/09/10 10:56:15 oes
579 * Silenced compiler warnings
581 * Revision 1.35 2001/07/31 14:44:22 oes
582 * Deleted unused size parameter from filter_popups()
584 * Revision 1.34 2001/07/30 22:08:36 jongfoster
585 * Tidying up #defines:
586 * - All feature #defines are now of the form FEATURE_xxx
587 * - Permanently turned off WIN_GUI_EDIT
588 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
590 * Revision 1.33 2001/07/29 19:32:00 jongfoster
591 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
593 * Revision 1.32 2001/07/29 18:47:05 jongfoster
594 * Adding missing #include "loadcfg.h"
596 * Revision 1.31 2001/07/29 12:17:48 oes
597 * Applied pthread fix by Paul Lieverse
599 * Revision 1.30 2001/07/25 22:57:13 jongfoster
600 * __BEOS__ no longer overrides FEATURE_PTHREAD.
601 * This is because FEATURE_PTHREAD will soon be widely used, so I
602 * want to keep it simple.
604 * Revision 1.29 2001/07/24 12:47:06 oes
605 * Applied BeOS support update by Eugenia
607 * Revision 1.28 2001/07/23 13:26:12 oes
608 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
610 * Revision 1.27 2001/07/19 19:09:47 haroon
611 * - Added code to take care of the situation where while processing the first
612 * server response (which includes the server header), after finding the end
613 * of the headers we were not looking past the end of the headers for
614 * content modification. I enabled it for filter_popups.
615 * Someone else should look to see if other similar operations should be
616 * done to the discarded portion of the buffer.
618 * Note 2001/07/20: No, the other content modification mechanisms will process
619 * the whole iob later anyway. --oes
621 * Revision 1.26 2001/07/18 12:31:36 oes
624 * Revision 1.25 2001/07/15 19:43:49 jongfoster
625 * Supports POSIX threads.
626 * Also removed some unused #includes.
628 * Revision 1.24 2001/07/13 14:00:40 oes
629 * - Generic content modification scheme:
630 * Each feature has its own applicability flag that is set
631 * from csp->action->flags.
632 * Replaced the "filtering" int flag , by a function pointer
633 * "content_filter" to the function that will do the content
634 * modification. If it is != NULL, the document will be buffered
635 * and processed through *content_filter, which must set
636 * csp->content_length and return a modified copy of the body
637 * or return NULL (on failiure).
638 * - Changed csp->is_text to the more generic bitmap csp->content_type
639 * which can currently take the valued CT_TEXT or CT_GIF
641 * - Removed all #ifdef PCRS
643 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
644 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
645 * the `block_acl' call. This prevents a compilation error when the user
646 * does not wish to use the "ACL" feature.
648 * Revision 1.22 2001/06/29 21:45:41 oes
649 * Indentation, CRLF->LF, Tab-> Space
651 * Revision 1.21 2001/06/29 13:29:36 oes
652 * - Cleaned up, improved comments
653 * - Unified all possible interceptors (CGI,
654 * block, trust, fast_redirect) in one
655 * place, with one (CGI) answer generation
656 * mechansim. Much clearer now.
657 * - Removed the GIF image generation, which
658 * is now done in filters.c:block_url()
659 * - Made error conditions like domain lookup
660 * failiure or (various) problems while talking
661 * to the server use cgi.c:error_response()
662 * instead of generating HTML/HTTP in chat() (yuck!)
663 * - Removed logentry from cancelled commit
665 * Revision 1.20 2001/06/09 10:55:28 jongfoster
666 * Changing BUFSIZ ==> BUFFER_SIZE
668 * Revision 1.19 2001/06/07 23:12:52 jongfoster
669 * Replacing function pointer in struct gateway with a directly
670 * called function forwarded_connect().
671 * Replacing struct gateway with struct forward_spec
673 * Revision 1.18 2001/06/03 19:12:16 oes
674 * introduced new cgi handling
676 * Revision 1.17 2001/06/01 20:07:23 jongfoster
677 * Now uses action +image-blocker{} rather than config->tinygif
679 * Revision 1.16 2001/06/01 18:49:17 jongfoster
680 * Replaced "list_share" with "list" - the tiny memory gain was not
681 * worth the extra complexity.
683 * Revision 1.15 2001/05/31 21:24:47 jongfoster
684 * Changed "permission" to "action" throughout.
685 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
686 * Moved vanilla wafer check into chat(), since we must now
687 * decide whether or not to add it based on the URL.
689 * Revision 1.14 2001/05/29 20:14:01 joergs
690 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
693 * Revision 1.13 2001/05/29 09:50:24 jongfoster
694 * Unified blocklist/imagelist/permissionslist.
695 * File format is still under discussion, but the internal changes
698 * Also modified interceptor behaviour:
699 * - We now intercept all URLs beginning with one of the following
700 * prefixes (and *only* these prefixes):
702 * * http://ijbswa.sf.net/config/
703 * * http://ijbswa.sourceforge.net/config/
704 * - New interceptors "home page" - go to http://i.j.b/ to see it.
705 * - Internal changes so that intercepted and fast redirect pages
706 * are not replaced with an image.
707 * - Interceptors now have the option to send a binary page direct
708 * to the client. (i.e. ijb-send-banner uses this)
709 * - Implemented show-url-info interceptor. (Which is why I needed
710 * the above interceptors changes - a typical URL is
711 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
712 * The previous mechanism would not have intercepted that, and
713 * if it had been intercepted then it then it would have replaced
716 * Revision 1.12 2001/05/27 22:17:04 oes
718 * - re_process_buffer no longer writes the modified buffer
719 * to the client, which was very ugly. It now returns the
720 * buffer, which it is then written by chat.
722 * - content_length now adjusts the Content-Length: header
723 * for modified documents rather than crunch()ing it.
724 * (Length info in csp->content_length, which is 0 for
725 * unmodified documents)
727 * - For this to work, sed() is called twice when filtering.
729 * Revision 1.11 2001/05/26 17:27:53 jongfoster
730 * Added support for CLF and fixed LOG_LEVEL_LOG.
731 * Also did CRLF->LF fix of my previous patch.
733 * Revision 1.10 2001/05/26 15:26:15 jongfoster
734 * ACL feature now provides more security by immediately dropping
735 * connections from untrusted hosts.
737 * Revision 1.9 2001/05/26 00:28:36 jongfoster
738 * Automatic reloading of config file.
739 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
740 * Most of the global variables have been moved to a new
741 * struct configuration_spec, accessed through csp->config->globalname
742 * Most of the globals remaining are used by the Win32 GUI.
744 * Revision 1.8 2001/05/25 22:43:18 jongfoster
745 * Fixing minor memory leak and buffer overflow.
747 * Revision 1.7 2001/05/25 22:34:30 jongfoster
750 * Revision 1.6 2001/05/23 00:13:58 joergs
751 * AmigaOS support fixed.
753 * Revision 1.5 2001/05/22 18:46:04 oes
755 * - Enabled filtering banners by size rather than URL
756 * by adding patterns that replace all standard banner
757 * sizes with the "Junkbuster" gif to the re_filterfile
759 * - Enabled filtering WebBugs by providing a pattern
760 * which kills all 1x1 images
762 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
763 * which is selected by the (nonstandard and therefore
764 * capital) letter 'U' in the option string.
765 * It causes the quantifiers to be ungreedy by default.
766 * Appending a ? turns back to greedy (!).
768 * - Added a new interceptor ijb-send-banner, which
769 * sends back the "Junkbuster" gif. Without imagelist or
770 * MSIE detection support, or if tinygif = 1, or the
771 * URL isn't recognized as an imageurl, a lame HTML
772 * explanation is sent instead.
774 * - Added new feature, which permits blocking remote
775 * script redirects and firing back a local redirect
777 * The feature is conditionally compiled, i.e. it
778 * can be disabled with --disable-fast-redirects,
779 * plus it must be activated by a "fast-redirects"
780 * line in the config file, has its own log level
781 * and of course wants to be displayed by show-proxy-args
782 * Note: Boy, all the #ifdefs in 1001 locations and
783 * all the fumbling with configure.in and acconfig.h
784 * were *way* more work than the feature itself :-(
786 * - Because a generic redirect template was needed for
787 * this, tinygif = 3 now uses the same.
789 * - Moved GIFs, and other static HTTP response templates
794 * - Removed some >400 CRs again (Jon, you really worked
797 * Revision 1.4 2001/05/21 19:34:01 jongfoster
798 * Made failure to bind() a fatal error.
800 * Revision 1.3 2001/05/20 01:21:20 jongfoster
801 * Version 2.9.4 checkin.
802 * - Merged popupfile and cookiefile, and added control over PCRS
803 * filtering, in new "permissionsfile".
804 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
805 * file error you now get a message box (in the Win32 GUI) rather
806 * than the program exiting with no explanation.
807 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
809 * - Removed tabs from "config"
810 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
811 * - Bumped up version number.
813 * Revision 1.2 2001/05/17 22:34:44 oes
814 * - Added hint on GIF char array generation to jcc.c
815 * - Cleaned CRLF's from the sources and related files
816 * - Repaired logging for REF and FRC
818 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
819 * Initial import of version 2.9.3 source tree
822 *********************************************************************/
828 #include <sys/types.h>
837 # ifndef FEATURE_PTHREAD
841 # include <windows.h>
842 # include <process.h>
843 # endif /* ndef FEATURE_PTHREAD */
846 # ifndef _WIN_CONSOLE
848 # endif /* ndef _WIN_CONSOLE */
849 # include "w32svrapi.h"
851 #else /* ifndef _WIN32 */
853 # if !defined (__OS2__)
855 # include <sys/wait.h>
856 # endif /* ndef __OS2__ */
857 # include <sys/time.h>
858 # include <sys/stat.h>
859 # include <sys/ioctl.h>
862 #include <sys/termios.h>
873 # include <socket.h> /* BeOS has select() for sockets only. */
874 # include <OS.h> /* declarations for threads and stuff. */
877 # if defined(__EMX__) || defined(__OS2__)
878 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
883 #define bzero(B,N) memset(B,0x00,n)
898 #include "killpopup.h"
899 #include "miscutil.h"
901 #include "jbsockets.h"
906 #include "urlmatch.h"
908 const char jcc_h_rcs[] = JCC_H_VERSION;
909 const char project_h_rcs[] = PROJECT_H_VERSION;
912 struct client_state clients[1];
913 struct file_list files[1];
915 #ifdef FEATURE_STATISTICS
916 int urls_read = 0; /* total nr of urls read inc rejected */
917 int urls_rejected = 0; /* total nr of urls rejected */
918 #endif /* def FEATURE_STATISTICS */
920 #ifdef FEATURE_GRACEFUL_TERMINATION
924 static void listen_loop(void);
925 static void chat(struct client_state *csp);
927 void serve(struct client_state *csp);
928 #else /* ifndef AMIGA */
929 static void serve(struct client_state *csp);
930 #endif /* def AMIGA */
933 static int32 server_thread(void *data);
934 #endif /* def __BEOS__ */
937 #define sleep(N) Sleep(((N) * 1000))
941 #define sleep(N) DosSleep(((N) * 100))
944 #ifdef FEATURE_PTHREAD
945 pthread_mutex_t log_mutex;
946 pthread_mutex_t log_init_mutex;
948 #ifndef HAVE_GMTIME_R
949 pthread_mutex_t gmtime_mutex;
950 #endif /* ndef HAVE_GMTIME_R */
952 #ifndef HAVE_LOCALTIME_R
953 pthread_mutex_t localtime_mutex;
954 #endif /* ndef HAVE_GMTIME_R */
956 #ifndef HAVE_GETHOSTBYADDR_R
957 pthread_mutex_t gethostbyaddr_mutex;
958 #endif /* ndef HAVE_GETHOSTBYADDR_R */
960 #ifndef HAVE_GETHOSTBYNAME_R
961 pthread_mutex_t gethostbyname_mutex;
962 #endif /* ndef HAVE_GETHOSTBYNAME_R */
965 pthread_mutex_t rand_mutex;
966 #endif /* ndef HAVE_RANDOM */
968 #endif /* FEATURE_PTHREAD */
970 #if defined(unix) || defined(__EMX__)
971 const char *basedir = NULL;
972 const char *pidfile = NULL;
973 int received_hup_signal = 0;
974 #endif /* defined unix */
976 /* The vanilla wafer. */
977 static const char VANILLA_WAFER[] =
978 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
979 "Do_not_send_me_any_copyrighted_information_other_than_the_"
980 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
981 "In_particular_do_not_send_me_any_cookies_that_"
982 "are_subject_to_a_claim_of_copyright_by_anybody._"
983 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
984 "(copyright_or_otherwise)_applying_to_any_cookie._";
986 /* HTTP snipplets. */
987 const static char CSUCCEED[] =
988 "HTTP/1.0 200 Connection established\n"
989 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
991 const static char CHEADER[] =
992 "HTTP/1.0 400 Invalid header received from browser\r\n"
993 "Proxy-Agent: Privoxy " VERSION "\r\n"
994 "Content-Type: text/plain\r\n"
995 "Connection: close\r\n\r\n"
996 "Invalid header received from browser.\r\n";
998 const static char CFORBIDDEN[] =
999 "HTTP/1.0 403 Connection not allowable\r\n"
1000 "Proxy-Agent: Privoxy " VERSION "\r\n"
1001 "X-Hint: If you read this message interactively, then you know why this happens ,-)\r\n"
1002 "Connection: close\r\n\r\n";
1004 const static char FTP_RESPONSE[] =
1005 "HTTP/1.0 400 Invalid request received from browser\r\n"
1006 "Content-Type: text/plain\r\n"
1007 "Connection: close\r\n\r\n"
1008 "Invalid request. Privoxy doesn't support FTP.\r\n";
1010 const static char GOPHER_RESPONSE[] =
1011 "HTTP/1.0 400 Invalid request received from browser\r\n"
1012 "Content-Type: text/plain\r\n"
1013 "Connection: close\r\n\r\n"
1014 "Invalid request. Privoxy doesn't support gopher.\r\n";
1016 /* XXX: should be a template */
1017 const static char MISSING_DESTINATION_RESPONSE[] =
1018 "HTTP/1.0 400 Bad request received from browser\r\n"
1019 "Proxy-Agent: Privoxy " VERSION "\r\n"
1020 "Content-Type: text/plain\r\n"
1021 "Connection: close\r\n\r\n"
1022 "Bad request. Privoxy was unable to extract the destination.\r\n";
1024 /* XXX: should be a template */
1025 const static char NO_SERVER_DATA_RESPONSE[] =
1026 "HTTP/1.0 502 Server or forwarder response empty\r\n"
1027 "Proxy-Agent: Privoxy " VERSION "\r\n"
1028 "Content-Type: text/plain\r\n"
1029 "Connection: close\r\n\r\n"
1030 "Empty server or forwarder response.\r\n"
1031 "The connection was closed without sending any data.\r\n";
1033 /* XXX: should be a template */
1034 const static char NULL_BYTE_RESPONSE[] =
1035 "HTTP/1.0 400 Bad request received from browser\r\n"
1036 "Proxy-Agent: Privoxy " VERSION "\r\n"
1037 "Content-Type: text/plain\r\n"
1038 "Connection: close\r\n\r\n"
1039 "Bad request. Null byte(s) before end of request.\r\n";
1041 /* A function to crunch a response */
1042 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
1044 /* Crunch function flags */
1045 #define CF_NO_FLAGS 0
1046 /* Cruncher applies to forced requests as well */
1047 #define CF_IGNORE_FORCE 1
1048 /* Crunched requests are counted for the block statistics */
1049 #define CF_COUNT_AS_REJECT 2
1051 /* A crunch function and its flags */
1054 const crunch_func_ptr cruncher;
1058 /* Complete list of cruncher functions */
1059 const static struct cruncher crunchers_all[] = {
1060 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
1061 { block_url, CF_COUNT_AS_REJECT },
1062 #ifdef FEATURE_TRUST
1063 { trust_url, CF_COUNT_AS_REJECT },
1064 #endif /* def FEATURE_TRUST */
1065 { redirect_url, CF_NO_FLAGS },
1066 { dispatch_cgi, CF_IGNORE_FORCE},
1070 /* Light version, used after tags are applied */
1071 const static struct cruncher crunchers_light[] = {
1072 { block_url, CF_COUNT_AS_REJECT },
1073 { redirect_url, CF_NO_FLAGS },
1078 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1079 /*********************************************************************
1081 * Function : sig_handler
1083 * Description : Signal handler for different signals.
1084 * Exit gracefully on TERM and INT
1085 * or set a flag that will cause the errlog
1086 * to be reopened by the main thread on HUP.
1089 * 1 : the_signal = the signal cause this function to call
1093 *********************************************************************/
1094 static void sig_handler(int the_signal)
1100 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
1111 received_hup_signal = 1;
1116 * We shouldn't be here, unless we catch signals
1117 * in main() that we can't handle here!
1119 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
1127 /*********************************************************************
1129 * Function : client_protocol_is_unsupported
1131 * Description : Checks if the client used a known unsupported
1132 * protocol and deals with it by sending an error
1136 * 1 : csp = Current client state (buffers, headers, etc...)
1137 * 2 : req = the first request line send by the client
1139 * Returns : TRUE if an error response has been generated, or
1140 * FALSE if the request doesn't look invalid.
1142 *********************************************************************/
1143 int client_protocol_is_unsupported(const struct client_state *csp, char *req)
1145 char buf[BUFFER_SIZE];
1148 * If it's a FTP or gopher request, we don't support it.
1150 * These checks are better than nothing, but they might
1151 * not work in all configurations and some clients might
1152 * have problems digesting the answer.
1154 * They should, however, never cause more problems than
1155 * Privoxy's old behaviour (returning the misleading HTML
1158 * "Could not resolve http://(ftp|gopher)://example.org").
1160 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
1162 if (!strncmpic(req, "GET ftp://", 10))
1164 strlcpy(buf, FTP_RESPONSE, sizeof(buf));
1165 log_error(LOG_LEVEL_ERROR, "%s tried to use Privoxy as FTP proxy: %s",
1166 csp->ip_addr_str, req);
1170 strlcpy(buf, GOPHER_RESPONSE, sizeof(buf));
1171 log_error(LOG_LEVEL_ERROR, "%s tried to use Privoxy as gopher proxy: %s",
1172 csp->ip_addr_str, req);
1174 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
1176 write_socket(csp->cfd, buf, strlen(buf));
1185 /*********************************************************************
1187 * Function : get_request_destination_elsewhere
1189 * Description : If the client's request was redirected into
1190 * Privoxy without the client's knowledge,
1191 * the request line lacks the destination host.
1193 * This function tries to get it elsewhere,
1194 * provided accept-intercepted-requests is enabled.
1196 * "Elsewhere" currently only means "Host: header",
1197 * but in the future we may ask the redirecting
1198 * packet filter to look the destination up.
1200 * If the destination stays unknown, an error
1201 * response is send to the client and headers
1202 * are freed so that chat() can return directly.
1205 * 1 : csp = Current client state (buffers, headers, etc...)
1206 * 2 : headers = a header list
1208 * Returns : JB_ERR_OK if the destination is now known, or
1209 * JB_ERR_PARSE if it isn't.
1211 *********************************************************************/
1212 jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
1216 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
1218 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
1219 " Privoxy isn't configured to accept intercepted requests.",
1220 csp->ip_addr_str, csp->http->cmd);
1221 /* XXX: Use correct size */
1222 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1223 csp->ip_addr_str, csp->http->cmd);
1225 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1226 destroy_list(headers);
1228 return JB_ERR_PARSE;
1230 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
1232 /* Split the domain we just got for pattern matching */
1233 init_domain_components(csp->http);
1239 /* We can't work without destination. Go spread the news.*/
1241 req = list_to_text(headers);
1243 /* XXX: Use correct size */
1244 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1245 csp->ip_addr_str, csp->http->cmd);
1246 log_error(LOG_LEVEL_ERROR,
1247 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
1248 csp->ip_addr_str, csp->http->cmd, req);
1251 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
1252 destroy_list(headers);
1254 return JB_ERR_PARSE;
1257 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
1258 * to get the destination IP address, use it as host directly
1259 * or do a reverse DNS lookup first.
1264 /*********************************************************************
1266 * Function : get_server_headers
1268 * Description : Parses server headers in iob and fills them
1269 * into csp->headers so that they can later be
1273 * 1 : csp = Current client state (buffers, headers, etc...)
1275 * Returns : JB_ERR_OK if everything went fine, or
1276 * JB_ERR_PARSE if the headers were incomplete.
1278 *********************************************************************/
1279 jb_err get_server_headers(struct client_state *csp)
1281 int continue_hack_in_da_house = 0;
1284 while (((header = get_header(csp)) != NULL) || continue_hack_in_da_house)
1289 * continue hack in da house. Ignore the ending of
1290 * this head and continue enlisting header lines.
1291 * The reason is described below.
1293 enlist(csp->headers, "");
1294 continue_hack_in_da_house = 0;
1297 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
1300 * It's a bodyless continue response, don't
1301 * stop header parsing after reaching it's end.
1303 * As a result Privoxy will concatenate the
1304 * next response's head and parse and deliver
1305 * the headers as if they belonged to one request.
1307 * The client will separate them because of the
1308 * empty line between them.
1310 * XXX: What we're doing here is clearly against
1311 * the intended purpose of the continue header,
1312 * and under some conditions (HTTP/1.0 client request)
1313 * it's a standard violation.
1315 * Anyway, "sort of against the spec" is preferable
1316 * to "always getting confused by Continue responses"
1317 * (Privoxy's behaviour before this hack was added)
1319 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
1320 continue_hack_in_da_house = 1;
1322 else if (*header == '\0')
1325 * If the header is empty, but the Continue hack
1326 * isn't active, we can assume that we reached the
1327 * end of the buffer before we hit the end of the
1330 * Inform the caller an let it decide how to handle it.
1332 return JB_ERR_PARSE;
1336 if (JB_ERR_MEMORY == enlist(csp->headers, header))
1339 * XXX: Should we quit the request and return a
1340 * out of memory error page instead?
1342 log_error(LOG_LEVEL_ERROR,
1343 "Out of memory while enlisting server headers. %s lost.",
1353 /*********************************************************************
1355 * Function : crunch_reason
1357 * Description : Translates the crunch reason code into a string.
1360 * 1 : rsp = a http_response
1362 * Returns : A string with the crunch reason or an error description.
1364 *********************************************************************/
1365 const char *crunch_reason(const struct http_response *rsp)
1367 char * reason = NULL;
1369 assert(rsp != NULL);
1372 return "Internal error while searching for crunch reason";
1375 switch (rsp->reason)
1377 case RSP_REASON_UNSUPPORTED:
1378 reason = "Unsupported HTTP feature";
1380 case RSP_REASON_BLOCKED:
1383 case RSP_REASON_UNTRUSTED:
1384 reason = "Untrusted";
1386 case RSP_REASON_REDIRECTED:
1387 reason = "Redirected";
1389 case RSP_REASON_CGI_CALL:
1390 reason = "CGI Call";
1392 case RSP_REASON_NO_SUCH_DOMAIN:
1393 reason = "DNS failure";
1395 case RSP_REASON_FORWARDING_FAILED:
1396 reason = "Forwarding failed";
1398 case RSP_REASON_CONNECT_FAILED:
1399 reason = "Connection failure";
1401 case RSP_REASON_OUT_OF_MEMORY:
1402 reason = "Out of memory (may mask other reasons)";
1405 reason = "No reason recorded";
1413 /*********************************************************************
1415 * Function : send_crunch_response
1417 * Description : Delivers already prepared response for
1418 * intercepted requests, logs the interception
1419 * and frees the response.
1422 * 1 : csp = Current client state (buffers, headers, etc...)
1423 * 1 : rsp = Fully prepared response. Will be freed on exit.
1425 * Returns : Nothing.
1427 *********************************************************************/
1428 void send_crunch_response(struct client_state *csp, struct http_response *rsp)
1430 const struct http_request *http = csp->http;
1431 char status_code[4];
1433 assert(rsp != NULL);
1434 assert(rsp->head != NULL);
1439 * Not supposed to happen. If it does
1440 * anyway, treat it as an unknown error.
1442 cgi_error_unknown(csp, rsp, RSP_REASON_INTERNAL_ERROR);
1443 /* return code doesn't matter */
1448 /* If rsp is still NULL, we have serious internal problems. */
1449 log_error(LOG_LEVEL_FATAL,
1450 "NULL response in send_crunch_response and cgi_error_unknown failed as well.");
1454 * Extract the status code from the actual head
1455 * that was send to the client. It is the only
1456 * way to get it right for all requests, including
1457 * the fixed ones for out-of-memory problems.
1459 * A head starts like this: 'HTTP/1.1 200...'
1463 status_code[0] = rsp->head[9];
1464 status_code[1] = rsp->head[10];
1465 status_code[2] = rsp->head[11];
1466 status_code[3] = '\0';
1468 /* Write the answer to the client */
1469 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1470 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1472 /* There is nothing we can do about it. */
1473 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
1476 /* Log that the request was crunched and why. */
1477 log_error(LOG_LEVEL_GPC, "%s%s crunch! (%s)",
1478 http->hostport, http->path, crunch_reason(rsp));
1479 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %d",
1480 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
1482 /* Clean up and return */
1483 if (cgi_error_memory() != rsp)
1485 free_http_response(rsp);
1491 /*********************************************************************
1493 * Function : request_contains_null_bytes
1495 * Description : Checks for NULL bytes in the request and sends
1496 * an error message to the client if any were found.
1499 * 1 : csp = Current client state (buffers, headers, etc...)
1500 * 2 : buf = Data from the client's request to check.
1501 * 3 : len = The data length.
1503 * Returns : TRUE if the request contained one or more NULL bytes, or
1506 *********************************************************************/
1507 int request_contains_null_bytes(const struct client_state *csp, char *buf, int len)
1509 size_t c_len; /* Request lenght when treated as C string */
1511 c_len = strlen(buf);
1516 * Null byte(s) found. Log the request,
1517 * return an error response and hang up.
1519 size_t tmp_len = c_len;
1524 * Replace NULL byte(s) with '°' characters
1525 * so the request can be logged as string.
1526 * XXX: Is there a better replacement character?
1529 tmp_len += strlen(buf+tmp_len);
1530 } while (tmp_len < len);
1532 log_error(LOG_LEVEL_ERROR, "%s\'s request contains at least one NULL byte "
1533 "(length=%d, strlen=%d).", csp->ip_addr_str, len, c_len);
1534 log_error(LOG_LEVEL_HEADER,
1535 "Offending request data with NULL bytes turned into \'°\' characters: %s", buf);
1537 write_socket(csp->cfd, NULL_BYTE_RESPONSE, strlen(NULL_BYTE_RESPONSE));
1539 /* XXX: Log correct size */
1540 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1549 /*********************************************************************
1551 * Function : crunch_response_triggered
1553 * Description : Checks if the request has to be crunched,
1554 * and delivers the crunch response if necessary.
1557 * 1 : csp = Current client state (buffers, headers, etc...)
1558 * 2 : crunchers = list of cruncher functions to run
1560 * Returns : TRUE if the request was answered with a crunch response
1563 *********************************************************************/
1564 int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
1566 struct http_response *rsp = NULL;
1567 const struct cruncher *c;
1569 for (c = crunchers; c->cruncher != NULL; c++)
1572 * Check the cruncher if either Privoxy is toggled
1573 * on and the request isn't forced, or if the cruncher
1574 * applies to forced requests as well.
1576 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
1577 !(csp->flags & CSP_FLAG_FORCED)) ||
1578 (c->flags & CF_IGNORE_FORCE))
1580 rsp = c->cruncher(csp);
1583 /* Deliver, log and free the interception response. */
1584 send_crunch_response(csp, rsp);
1585 #ifdef FEATURE_STATISTICS
1586 if (c->flags & CF_COUNT_AS_REJECT)
1588 csp->flags |= CSP_FLAG_REJECTED;
1590 #endif /* def FEATURE_STATISTICS */
1601 /*********************************************************************
1603 * Function : build_request_line
1605 * Description : Builds the HTTP request line.
1607 * If a HTTP forwarder is used it expects the whole URL,
1608 * web servers only get the path.
1611 * 1 : csp = Current client state (buffers, headers, etc...)
1612 * 2 : fwd = The forwarding spec used for the request
1613 * XXX: Should use http->fwd instead.
1614 * 3 : request_line = The old request line which will be replaced.
1616 * Returns : Nothing. Terminates in case of memory problems.
1618 *********************************************************************/
1619 void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
1621 struct http_request *http = csp->http;
1623 assert(http->ssl == 0);
1626 * Downgrade http version from 1.1 to 1.0
1627 * if +downgrade action applies.
1629 if ( (csp->action->flags & ACTION_DOWNGRADE)
1630 && (!strcmpic(http->ver, "HTTP/1.1")))
1633 http->ver = strdup("HTTP/1.0");
1635 if (http->ver == NULL)
1637 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
1642 * Rebuild the request line.
1644 freez(*request_line);
1645 *request_line = strdup(http->gpc);
1646 string_append(request_line, " ");
1648 if (fwd->forward_host)
1650 string_append(request_line, http->url);
1654 string_append(request_line, http->path);
1656 string_append(request_line, " ");
1657 string_append(request_line, http->ver);
1659 if (*request_line == NULL)
1661 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1663 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1667 /*********************************************************************
1671 * Description : Once a connection to the client has been accepted,
1672 * this function is called (via serve()) to handle the
1673 * main business of the communication. When this
1674 * function returns, the caller must close the client
1677 * FIXME: chat is nearly thousand lines long.
1681 * 1 : csp = Current client state (buffers, headers, etc...)
1683 * Returns : Nothing.
1685 *********************************************************************/
1686 static void chat(struct client_state *csp)
1688 char buf[BUFFER_SIZE];
1696 int ms_iis5_hack = 0;
1697 size_t byte_count = 0;
1698 int forwarded_connect_retries = 0;
1699 int max_forwarded_connect_retries = csp->config->forwarded_connect_retries;
1700 const struct forward_spec * fwd;
1701 struct http_request *http;
1702 int len; /* for buffer sizes (and negative error codes) */
1703 #ifdef FEATURE_KILL_POPUPS
1704 int block_popups; /* bool, 1==will block popups */
1705 int block_popups_now = 0; /* bool, 1==currently blocking popups */
1706 #endif /* def FEATURE_KILL_POPUPS */
1708 int pcrs_filter; /* bool, 1==will filter through pcrs */
1709 int gif_deanimate; /* bool, 1==will deanimate gifs */
1710 int jpeg_inspect; /* bool, 1==will inspect jpegs */
1712 /* Function that does the content filtering for the current request */
1713 char *(*content_filter)() = NULL;
1715 /* Skeleton for HTTP response, if we should intercept the request */
1716 struct http_response *rsp;
1718 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1719 struct list header_list;
1720 struct list *headers = &header_list;
1724 memset(buf, 0, sizeof(buf));
1727 * Read the client's request. Note that since we're not using select() we
1728 * could get blocked here if a client connected, then didn't say anything!
1733 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1735 if (len <= 0) break; /* error! */
1737 if (request_contains_null_bytes(csp, buf, len))
1739 /* NULL bytes found and dealt with, just hang up. */
1744 * If there is no memory left for buffering the
1745 * request, there is nothing we can do but hang up
1747 if (add_to_iob(csp, buf, len))
1752 req = get_header(csp);
1756 break; /* no HTTP request! */
1761 continue; /* more to come! */
1764 /* Does the request line look invalid? */
1765 if (client_protocol_is_unsupported(csp, req))
1768 * Yes. The request has already been
1769 * answered with a error response, the buffers
1770 * were freed and we're done with chatting.
1775 #ifdef FEATURE_FORCE_LOAD
1777 * If this request contains the FORCE_PREFIX and blocks
1778 * aren't enforced, get rid of it and set the force flag.
1780 if (strstr(req, FORCE_PREFIX))
1782 if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1784 log_error(LOG_LEVEL_FORCE,
1785 "Ignored force prefix in request: \"%s\".", req);
1789 strclean(req, FORCE_PREFIX);
1790 log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1791 csp->flags |= CSP_FLAG_FORCED;
1795 #endif /* def FEATURE_FORCE_LOAD */
1797 switch( parse_http_request(req, http, csp) )
1800 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing request.");
1803 log_error(LOG_LEVEL_ERROR, "Couldn't parse request: %s.", req);
1811 if (http->cmd == NULL)
1813 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1814 /* XXX: Use correct size */
1815 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1816 log_error(LOG_LEVEL_ERROR, "Invalid header received from %s.", csp->ip_addr_str);
1818 free_http_request(http);
1822 /* grab the rest of the client's headers */
1826 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
1828 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1831 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1836 * If there is no memory left for buffering the
1837 * request, there is nothing we can do but hang up
1839 if (add_to_iob(csp, buf, len))
1846 if (p == NULL) break;
1853 if (http->host == NULL)
1856 * If we still don't know the request destination,
1857 * the request is invalid or the client uses
1858 * Privoxy without its knowledge.
1860 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1863 * Our attempts to get the request destination
1864 * elsewhere failed or Privoxy is configured
1865 * to only accept proxy requests.
1867 * An error response has already been send
1868 * and we're done here.
1875 * Determine the actions for this URL
1877 #ifdef FEATURE_TOGGLE
1878 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1880 /* Most compatible set of actions (i.e. none) */
1881 init_current_action(csp->action);
1884 #endif /* ndef FEATURE_TOGGLE */
1886 url_actions(http, csp);
1890 * Save a copy of the original request for logging
1892 http->ocmd = strdup(http->cmd);
1894 if (http->ocmd == NULL)
1896 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
1899 enlist(csp->headers, http->cmd);
1901 /* Append the previously read headers */
1902 list_append_list_unique(csp->headers, headers);
1903 destroy_list(headers);
1906 * If the user has not supplied any wafers, and the user has not
1907 * told us to suppress the vanilla wafer, then send the vanilla wafer.
1909 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
1910 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
1912 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
1915 if (JB_ERR_OK != sed(client_patterns, add_client_headers, csp))
1917 log_error(LOG_LEVEL_FATAL, "Failed to parse client headers");
1919 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1921 /* decide how to route the HTTP request */
1922 if (NULL == (fwd = forward_url(http, csp)))
1924 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1925 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1928 /* build the http request to send to the server
1929 * we have to do one of the following:
1931 * create = use the original HTTP request to create a new
1932 * HTTP request that has either the path component
1933 * without the http://domainspec (w/path) or the
1934 * full orininal URL (w/url)
1935 * Note that the path and/or the HTTP version may
1936 * have been altered by now.
1938 * connect = Open a socket to the host:port of the server
1939 * and short-circuit server and client socket.
1941 * pass = Pass the request unchanged if forwarding a CONNECT
1942 * request to a parent proxy. Note that we'll be sending
1943 * the CFAIL message ourselves if connecting to the parent
1944 * fails, but we won't send a CSUCCEED message if it works,
1945 * since that would result in a double message (ours and the
1946 * parent's). After sending the request to the parent, we simply
1949 * here's the matrix:
1952 * +--------+--------+
1954 * 0 | create | connect|
1956 * Forwarding +--------+--------+
1958 * 1 | create | pass |
1960 * +--------+--------+
1965 * Check if a CONNECT request is allowable:
1966 * In the absence of a +limit-connect action, allow only port 443.
1967 * If there is an action, allow whatever matches the specificaton.
1971 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
1972 || (csp->action->flags & ACTION_LIMIT_CONNECT
1973 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
1975 if (csp->action->flags & ACTION_TREAT_FORBIDDEN_CONNECTS_LIKE_BLOCKS)
1978 * The response may confuse some clients,
1979 * but makes unblocking easier.
1981 log_error(LOG_LEVEL_ERROR, "Marking suspicious CONNECT request from %s for blocking.",
1983 csp->action->flags |= ACTION_BLOCK;
1988 write_socket(csp->cfd, CFORBIDDEN, strlen(CFORBIDDEN));
1989 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
1990 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
1992 list_remove_all(csp->headers);
2001 freez(csp->headers->first->str);
2002 build_request_line(csp, fwd, &csp->headers->first->str);
2005 hdr = list_to_text(csp->headers);
2008 /* FIXME Should handle error properly */
2009 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2012 #ifdef FEATURE_KILL_POPUPS
2013 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
2014 #endif /* def FEATURE_KILL_POPUPS */
2016 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
2017 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
2019 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
2021 jpeg_inspect = ((csp->action->flags & ACTION_JPEG_INSPECT) != 0);
2024 * We have a request. Check if one of the crunchers wants it.
2026 if (crunch_response_triggered(csp, crunchers_all))
2029 * Yes. The client got the crunch response
2030 * and we are done here after cleaning up.
2033 list_remove_all(csp->headers);
2039 * The headers can't be removed earlier because
2040 * they were still needed for the referrer check
2041 * in case of CGI crunches.
2043 * XXX: Would it be worth to move the referrer check
2044 * into client_referrer() and set a flag if it's trusted?
2046 list_remove_all(csp->headers);
2048 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
2050 if (fwd->forward_host)
2052 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
2053 fwd->forward_host, fwd->forward_port, http->hostport);
2057 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
2060 /* here we connect to the server, gateway, or the forwarder */
2062 while ( (csp->sfd = forwarded_connect(fwd, http, csp))
2063 && (errno == EINVAL) && (forwarded_connect_retries++ < max_forwarded_connect_retries))
2065 log_error(LOG_LEVEL_ERROR, "failed request #%u to connect to %s. Trying again.",
2066 forwarded_connect_retries, http->hostport);
2069 if (csp->sfd == JB_INVALID_SOCKET)
2071 if (fwd->type != SOCKS_NONE)
2074 rsp = error_response(csp, "forwarding-failed", errno);
2076 else if (errno == EINVAL)
2078 rsp = error_response(csp, "no-such-domain", errno);
2082 rsp = error_response(csp, "connect-failed", errno);
2083 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
2088 /* Write the answer to the client */
2091 send_crunch_response(csp, rsp);
2098 if (fwd->forward_host || (http->ssl == 0))
2100 /* write the client's (modified) header to the server
2101 * (along with anything else that may be in the buffer)
2104 if (write_socket(csp->sfd, hdr, strlen(hdr))
2105 || (flush_socket(csp->sfd, csp) < 0))
2107 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
2110 rsp = error_response(csp, "connect-failed", errno);
2114 send_crunch_response(csp, rsp);
2124 * We're running an SSL tunnel and we're not forwarding,
2125 * so just send the "connect succeeded" message to the
2126 * client, flush the rest, and get out of the way.
2128 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
2136 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
2138 /* we're finished with the client's header */
2141 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
2143 /* pass data between the client and server
2144 * until one or the other shuts down the connection.
2153 * FD_ZERO here seems to point to an errant macro which crashes.
2154 * So do this by hand for now...
2156 memset(&rfds,0x00,sizeof(fd_set));
2160 FD_SET(csp->cfd, &rfds);
2161 FD_SET(csp->sfd, &rfds);
2163 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
2167 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2171 /* this is the body of the browser's request
2172 * just read it and write it.
2175 if (FD_ISSET(csp->cfd, &rfds))
2177 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
2181 break; /* "game over, man" */
2184 if (write_socket(csp->sfd, buf, (size_t)len))
2186 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2193 * The server wants to talk. It could be the header or the body.
2194 * If `hdr' is null, then it's the header otherwise it's the body.
2195 * FIXME: Does `hdr' really mean `host'? No.
2199 if (FD_ISSET(csp->sfd, &rfds))
2202 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
2206 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2208 if (http->ssl && (fwd->forward_host == NULL))
2211 * Just hang up. We already confirmed the client's CONNECT
2212 * request with status code 200 and unencrypted content is
2213 * no longer welcome.
2215 log_error(LOG_LEVEL_ERROR,
2216 "CONNECT already confirmed. Unable to tell the client about the problem.");
2220 rsp = error_response(csp, "connect-failed", errno);
2224 send_crunch_response(csp, rsp);
2230 /* Add a trailing zero. This lets filter_popups
2231 * use string operations.
2235 #ifdef FEATURE_KILL_POPUPS
2236 /* Filter the popups on this read. */
2237 if (block_popups_now)
2239 filter_popups(buf, csp);
2241 #endif /* def FEATURE_KILL_POPUPS */
2243 /* Normally, this would indicate that we've read
2244 * as much as the server has sent us and we can
2245 * close the client connection. However, Microsoft
2246 * in its wisdom has released IIS/5 with a bug that
2247 * prevents it from sending the trailing \r\n in
2248 * a 302 redirect header (and possibly other headers).
2249 * To work around this if we've haven't parsed
2250 * a full header we'll append a trailing \r\n
2251 * and see if this now generates a valid one.
2253 * This hack shouldn't have any impacts. If we've
2254 * already transmitted the header or if this is a
2255 * SSL connection, then we won't bother with this
2256 * hack. So we only work on partially received
2257 * headers. If we append a \r\n and this still
2258 * doesn't generate a valid header, then we won't
2259 * transmit anything to the client.
2264 if (server_body || http->ssl)
2267 * If we have been buffering up the document,
2268 * now is the time to apply content modification
2269 * and send the result to the client.
2274 * If the content filter fails, use the original
2275 * buffer and length.
2276 * (see p != NULL ? p : csp->iob->cur below)
2278 if (NULL == (p = (*content_filter)(csp)))
2280 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2283 if (JB_ERR_OK != sed(server_patterns_light, NULL, csp))
2285 log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2288 hdr = list_to_text(csp->headers);
2291 /* FIXME Should handle error properly */
2292 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2296 * Shouldn't happen because this was the second sed run
2297 * and tags are only created for the first one.
2299 assert(!crunch_response_triggered(csp, crunchers_all));
2301 if (write_socket(csp->cfd, hdr, strlen(hdr))
2302 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
2304 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2314 break; /* "game over, man" */
2318 * This is NOT the body, so
2319 * Let's pretend the server just sent us a blank line.
2321 snprintf(buf, sizeof(buf), "\r\n");
2322 len = (int)strlen(buf);
2325 * Now, let the normal header parsing algorithm below do its
2326 * job. If it fails, we'll exit instead of continuing.
2333 * If this is an SSL connection or we're in the body
2334 * of the server document, just write it to the client,
2335 * unless we need to buffer the body for later content-filtering
2338 if (server_body || http->ssl)
2343 * If there is no memory left for buffering the content, or the buffer limit
2344 * has been reached, switch to non-filtering mode, i.e. make & write the
2345 * header, flush the iob and buf, and get out of the way.
2347 if (add_to_iob(csp, buf, len))
2352 log_error(LOG_LEVEL_ERROR, "Flushing header and buffers. Stepping back from filtering.");
2353 if (JB_ERR_OK != sed(server_patterns, add_server_headers, csp))
2355 log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2357 hdr = list_to_text(csp->headers);
2361 * Memory is too tight to even generate the header.
2362 * Send our static "Out-of-memory" page.
2364 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2365 rsp = cgi_error_memory();
2366 send_crunch_response(csp, rsp);
2371 if (crunch_response_triggered(csp, crunchers_light))
2374 * One of the tags created by a server-header
2375 * tagger triggered a crunch. We already
2376 * delivered the crunch response to the client
2377 * and are done here after cleaning up.
2383 hdrlen = strlen(hdr);
2385 if (write_socket(csp->cfd, hdr, hdrlen)
2386 || ((flushed = flush_socket(csp->cfd, csp)) < 0)
2387 || (write_socket(csp->cfd, buf, (size_t)len)))
2389 log_error(LOG_LEVEL_CONNECT, "Flush header and buffers to client failed: %E");
2395 byte_count += hdrlen + (size_t)flushed + (size_t)len;
2397 content_filter = NULL;
2404 if (write_socket(csp->cfd, buf, (size_t)len))
2406 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2410 byte_count += (size_t)len;
2415 /* we're still looking for the end of the
2416 * server's header ... (does that make header
2417 * parsing an "out of body experience" ?
2421 * buffer up the data we just read. If that fails,
2422 * there's little we can do but send our static
2423 * out-of-memory page.
2425 if (add_to_iob(csp, buf, len))
2427 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2428 rsp = cgi_error_memory();
2429 send_crunch_response(csp, rsp);
2434 /* Convert iob into something sed() can digest */
2435 if (JB_ERR_PARSE == get_server_headers(csp))
2439 /* Well, we tried our MS IIS/5
2440 * hack and it didn't work.
2441 * The header is incomplete
2442 * and there isn't anything
2443 * we can do about it.
2449 /* Since we have to wait for
2450 * more from the server before
2451 * we can parse the headers
2452 * we just continue here.
2458 /* Did we actually get anything? */
2459 if (NULL == csp->headers->first)
2461 log_error(LOG_LEVEL_ERROR, "Empty server or forwarder response.");
2462 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2463 write_socket(csp->cfd, NO_SERVER_DATA_RESPONSE, strlen(NO_SERVER_DATA_RESPONSE));
2464 free_http_request(http);
2468 /* we have now received the entire header.
2469 * filter it and send the result to the client
2471 if (JB_ERR_OK != sed(server_patterns, add_server_headers, csp))
2473 log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2475 hdr = list_to_text(csp->headers);
2478 /* FIXME Should handle error properly */
2479 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2482 if (crunch_response_triggered(csp, crunchers_light))
2485 * One of the tags created by a server-header
2486 * tagger triggered a crunch. We already
2487 * delivered the crunch response to the client
2488 * and are done here after cleaning up.
2493 #ifdef FEATURE_KILL_POPUPS
2494 /* Start blocking popups if appropriate. */
2496 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
2497 !http->ssl && /* We talk plaintext */
2498 block_popups) /* Policy allows */
2500 block_popups_now = 1;
2502 * Filter the part of the body that came in the same read
2503 * as the last headers:
2505 filter_popups(csp->iob->cur, csp);
2508 #endif /* def FEATURE_KILL_POPUPS */
2510 /* Buffer and pcrs filter this if appropriate. */
2512 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
2513 !http->ssl && /* We talk plaintext */
2514 pcrs_filter) /* Policy allows */
2516 content_filter = pcrs_filter_response;
2519 /* Buffer and gif_deanimate this if appropriate. */
2521 if ((csp->content_type & CT_GIF) && /* It's an image/gif MIME-Type */
2522 !http->ssl && /* We talk plaintext */
2523 gif_deanimate) /* Policy allows */
2525 content_filter = gif_deanimate_response;
2528 /* Buffer and jpg_inspect this if appropriate. */
2530 if ((csp->content_type & CT_JPEG) && /* It's an image/jpeg MIME-Type */
2531 !http->ssl && /* We talk plaintext */
2532 jpeg_inspect) /* Policy allows */
2534 content_filter = jpeg_inspect_response;
2538 * Only write if we're not buffering for content modification
2540 if (!content_filter)
2542 /* write the server's (modified) header to
2543 * the client (along with anything else that
2544 * may be in the buffer)
2547 if (write_socket(csp->cfd, hdr, strlen(hdr))
2548 || ((len = flush_socket(csp->cfd, csp)) < 0))
2550 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2552 /* the write failed, so don't bother
2553 * mentioning it to the client...
2554 * it probably can't hear us anyway.
2560 byte_count += (size_t)len;
2563 /* we're finished with the server's header */
2568 /* If this was a MS IIS/5 hack then it means
2569 * the server has already closed the
2570 * connection. Nothing more to read. Time
2581 return; /* huh? we should never get here */
2584 if (csp->content_length == 0)
2587 * If Privoxy didn't recalculate the
2588 * Content-Lenght, byte_count is still
2591 csp->content_length = byte_count;
2594 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
2595 csp->ip_addr_str, http->ocmd, csp->content_length);
2599 /*********************************************************************
2603 * Description : This is little more than chat. We only "serve" to
2604 * to close any socket that chat may have opened.
2607 * 1 : csp = Current client state (buffers, headers, etc...)
2611 *********************************************************************/
2613 void serve(struct client_state *csp)
2614 #else /* ifndef AMIGA */
2615 static void serve(struct client_state *csp)
2616 #endif /* def AMIGA */
2619 close_socket(csp->cfd);
2621 if (csp->sfd != JB_INVALID_SOCKET)
2623 close_socket(csp->sfd);
2626 csp->flags &= ~CSP_FLAG_ACTIVE;
2632 /*********************************************************************
2634 * Function : server_thread
2636 * Description : We only exist to call `serve' in a threaded environment.
2639 * 1 : data = Current client state (buffers, headers, etc...)
2641 * Returns : Always 0.
2643 *********************************************************************/
2644 static int32 server_thread(void *data)
2646 serve((struct client_state *) data);
2653 /*********************************************************************
2657 * Description : Print usage info & exit.
2659 * Parameters : Pointer to argv[0] for identifying ourselves
2663 *********************************************************************/
2664 void usage(const char *myname)
2666 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
2670 #endif /* defined(unix) */
2673 "[--no-daemon] [--pidfile pidfile] [--user user[.group]] "
2674 #endif /* defined(unix) */
2675 "[--version] [configfile]\n"
2676 "Aborting\n", myname);
2683 /*********************************************************************
2685 * Function : initialize_mutexes
2687 * Description : Prepares mutexes if mutex support is available.
2691 * Returns : Void, exits in case of errors.
2693 *********************************************************************/
2694 void initialize_mutexes()
2698 #ifdef FEATURE_PTHREAD
2700 * Prepare global mutex semaphores
2702 err = pthread_mutex_init(&log_mutex, 0);
2704 if (!err) err = pthread_mutex_init(&log_init_mutex, 0);
2707 * XXX: The assumptions below are a bit naive
2708 * and can cause locks that aren't necessary.
2710 * For example older FreeBSD versions (< 6.x?)
2711 * have no gethostbyname_r, but gethostbyname is
2714 #ifndef HAVE_GMTIME_R
2715 if (!err) err = pthread_mutex_init(&gmtime_mutex, 0);
2716 #endif /* ndef HAVE_GMTIME_R */
2718 #ifndef HAVE_LOCALTIME_R
2719 if (!err) err = pthread_mutex_init(&localtime_mutex, 0);
2720 #endif /* ndef HAVE_GMTIME_R */
2722 #ifndef HAVE_GETHOSTBYADDR_R
2723 if (!err) err = pthread_mutex_init(&gethostbyaddr_mutex, 0);
2724 #endif /* ndef HAVE_GETHOSTBYADDR_R */
2726 #ifndef HAVE_GETHOSTBYNAME_R
2727 if (!err) err = pthread_mutex_init(&gethostbyname_mutex, 0);
2728 #endif /* ndef HAVE_GETHOSTBYNAME_R */
2731 if (!err) err = pthread_mutex_init(&rand_mutex, 0);
2732 #endif /* ndef HAVE_RANDOM */
2733 #endif /* FEATURE_PTHREAD */
2736 * TODO: mutex support for mingw32 would be swell.
2741 printf("Fatal error. Mutex initialization failed: %s.\n",
2750 /*********************************************************************
2754 * Description : Load the config file and start the listen loop.
2755 * This function is a lot more *sane* with the `load_config'
2756 * and `listen_loop' functions; although it stills does
2757 * a *little* too much for my taste.
2760 * 1 : argc = Number of parameters (including $0).
2761 * 2 : argv = Array of (char *)'s to the parameters.
2763 * Returns : 1 if : can't open config file, unrecognized directive,
2764 * stats requested in multi-thread mode, can't open the
2765 * log file, can't open the jar file, listen port is invalid,
2766 * any load fails, and can't bind port.
2768 * Else main never returns, the process must be signaled
2769 * to terminate execution. Or, on Windows, use the
2770 * "File", "Exit" menu option.
2772 *********************************************************************/
2774 int real_main(int argc, const char *argv[])
2776 int main(int argc, const char *argv[])
2780 unsigned int random_seed;
2782 struct passwd *pw = NULL;
2783 struct group *grp = NULL;
2792 #if !defined(_WIN32)
2800 * Parse the command line arguments
2802 * XXX: simply printing usage information in case of
2803 * invalid arguments isn't particular user friendly.
2805 while (++argc_pos < argc)
2808 /* Check to see if the service must be installed or uninstalled */
2809 if (strncmp(argv[argc_pos], "--install", 9) == 0)
2811 const char *pName = argv[argc_pos] + 9;
2814 exit( (install_service(pName)) ? 0 : 1 );
2816 else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
2818 const char *pName = argv[argc_pos] + 11;
2821 exit((uninstall_service(pName)) ? 0 : 1);
2823 else if (strcmp(argv[argc_pos], "--service" ) == 0)
2825 bRunAsService = TRUE;
2826 w32_set_service_cwd();
2827 atexit(w32_service_exit_notify);
2830 #endif /* defined(_WIN32) */
2833 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2835 if (strcmp(argv[argc_pos], "--help") == 0)
2840 else if(strcmp(argv[argc_pos], "--version") == 0)
2842 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2848 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
2853 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
2855 if (++argc_pos == argc) usage(argv[0]);
2856 pidfile = strdup(argv[argc_pos]);
2859 else if (strcmp(argv[argc_pos], "--user" ) == 0)
2861 if (++argc_pos == argc) usage(argv[argc_pos]);
2863 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
2866 if (NULL == (grp = getgrnam(p)))
2868 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
2872 if (NULL == (pw = getpwnam(argv[argc_pos])))
2874 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
2877 if (p != NULL) *--p = '\0';
2880 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
2884 #endif /* defined(unix) */
2886 else if (argc_pos + 1 != argc)
2889 * This is neither the last command line
2890 * option, nor was it recognized before,
2891 * therefore it must be invalid.
2897 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
2899 configfile = argv[argc_pos];
2902 } /* -END- while (more arguments) */
2905 if ( *configfile != '/' )
2907 char cwd[BUFFER_SIZE];
2909 size_t abs_file_size;
2911 /* make config-filename absolute here */
2912 if (NULL == getcwd(cwd, sizeof(cwd)))
2914 perror("failed to get current working directory");
2919 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
2920 basedir = strdup(cwd);
2922 if (NULL == basedir ||
2923 NULL == (abs_file = malloc(abs_file_size)))
2925 perror("malloc failed");
2928 strlcpy(abs_file, basedir, abs_file_size);
2929 strlcat(abs_file, "/", abs_file_size );
2930 strlcat(abs_file, configfile, abs_file_size);
2931 configfile = abs_file;
2933 #endif /* defined unix */
2937 clients->next = NULL;
2941 #elif defined(_WIN32)
2945 /* Prepare mutexes if supported and necessary. */
2946 initialize_mutexes();
2948 random_seed = (unsigned int)time(NULL);
2950 srandom(random_seed);
2953 #endif /* ifdef HAVE_RANDOM */
2956 * Unix signal handling
2958 * Catch the abort, interrupt and terminate signals for a graceful exit
2959 * Catch the hangup signal so the errlog can be reopened.
2960 * Ignore the broken pipe signals (FIXME: Why?)
2962 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
2965 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP, 0 };
2966 const int ignored_signals[] = { SIGPIPE, 0 };
2968 for (idx = 0; catched_signals[idx] != 0; idx++)
2970 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
2971 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
2973 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
2974 #endif /* ifdef sun */
2976 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
2980 for (idx = 0; ignored_signals[idx] != 0; idx++)
2982 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
2984 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
2989 #else /* ifdef _WIN32 */
2990 # ifdef _WIN_CONSOLE
2992 * We *are* in a windows console app.
2993 * Print a verbose messages about FAQ's and such
2995 printf("%s", win32_blurb);
2996 # endif /* def _WIN_CONSOLE */
2997 #endif /* def _WIN32 */
3000 /* Initialize the CGI subsystem */
3001 cgi_init_error_messages();
3004 * If runnig on unix and without the --nodaemon
3005 * option, become a daemon. I.e. fork, detach
3006 * from tty and get process group leadership
3019 if ( pid < 0 ) /* error */
3024 else if ( pid != 0 ) /* parent */
3029 * must check for errors
3030 * child died due to missing files aso
3033 wpid = waitpid( pid, &status, WNOHANG );
3042 /* Should be more portable, but not as well tested */
3047 #else /* ndef __FreeBSD__ */
3049 #endif /* ndef __FreeBSD__ */
3050 fd = open("/dev/tty", O_RDONLY);
3053 /* no error check here */
3054 ioctl( fd, TIOCNOTTY,0 );
3058 /* FIXME: should close stderr (fd 2) here too, but the test
3060 * and load config file is done in listen_loop() and puts
3061 * some messages on stderr there.
3068 } /* -END- if (!no_daemon) */
3071 * As soon as we have written the PID file, we can switch
3072 * to the user and group ID indicated by the --user option
3078 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3080 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3086 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3088 if (chroot(pw->pw_dir) < 0)
3090 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3094 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3097 if (setuid(pw->pw_uid))
3099 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3103 char putenv_dummy[64];
3105 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3106 if (putenv(putenv_dummy) != 0)
3108 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3111 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3112 if (putenv(putenv_dummy) != 0)
3114 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3120 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3123 #endif /* defined unix */
3126 /* This will be FALSE unless the command line specified --service
3130 /* Yup, so now we must attempt to establish a connection
3131 * with the service dispatcher. This will only work if this
3132 * process was launched by the service control manager to
3133 * actually run as a service. If this isn't the case, i've
3134 * known it take around 30 seconds or so for the call to return.
3137 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3138 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3140 /* Service has run, and at this point is now being stopped, so just return */
3145 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3147 /* An error occurred. Usually it's because --service was wrongly specified
3148 * and we were unable to connect to the Service Control Dispatcher because
3149 * it wasn't expecting us and is therefore not listening.
3151 * For now, just continue below to call the listen_loop function.
3154 #endif /* def _WIN32 */
3164 /*********************************************************************
3166 * Function : bind_port_helper
3168 * Description : Bind the listen port. Handles logging, and aborts
3172 * 1 : config = Privoxy configuration. Specifies port
3175 * Returns : Port that was opened.
3177 *********************************************************************/
3178 static jb_socket bind_port_helper(struct configuration_spec * config)
3183 if ( (config->haddr != NULL)
3184 && (config->haddr[0] == '1')
3185 && (config->haddr[1] == '2')
3186 && (config->haddr[2] == '7')
3187 && (config->haddr[3] == '.') )
3189 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
3192 else if (config->haddr == NULL)
3194 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3199 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3200 config->hport, config->haddr);
3203 result = bind_port(config->haddr, config->hport, &bfd);
3210 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
3211 "There may be another Privoxy or some other "
3212 "proxy running on port %d",
3213 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
3214 config->hport, config->hport);
3217 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
3218 "The hostname is not resolvable",
3219 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3222 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
3223 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3226 /* shouldn't get here */
3227 return JB_INVALID_SOCKET;
3230 config->need_bind = 0;
3237 /* Without this simple workaround we get this compiler warning from _beginthread
3238 * warning C4028: formal parameter 1 different from declaration
3240 void w32_service_listen_loop(void *p)
3244 #endif /* def _WIN32 */
3247 /*********************************************************************
3249 * Function : listen_loop
3251 * Description : bind the listen port and enter a "FOREVER" listening loop.
3257 *********************************************************************/
3258 static void listen_loop(void)
3260 struct client_state *csp = NULL;
3262 struct configuration_spec * config;
3264 config = load_config();
3266 bfd = bind_port_helper(config);
3268 #ifdef FEATURE_GRACEFUL_TERMINATION
3269 while (!g_terminate)
3274 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3275 while (waitpid(-1, NULL, WNOHANG) > 0)
3277 /* zombie children */
3279 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3282 * Free data that was used by died threads
3288 * Re-open the errlog after HUP signal
3290 if (received_hup_signal)
3292 init_error_log(Argv[0], config->logfile, config->debug);
3293 received_hup_signal = 0;
3298 #ifdef FEATURE_COOKIE_JAR
3300 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
3301 * already open. I think unload_configfile() is not being run, which should do
3302 * this work. Until that can get resolved, we'll use this workaround.
3306 if (csp->config->jar)
3308 fclose(csp->config->jar);
3309 csp->config->jar = NULL;
3311 #endif /* FEATURE_COOKIE_JAR */
3312 #endif /* __OS2__ */
3314 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
3316 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
3320 csp->flags |= CSP_FLAG_ACTIVE;
3321 csp->sfd = JB_INVALID_SOCKET;
3323 csp->config = config = load_config();
3325 if ( config->need_bind )
3328 * Since we were listening to the "old port", we will not see
3329 * a "listen" param change until the next IJB request. So, at
3330 * least 1 more request must be made for us to find the new
3331 * setting. I am simply closing the old socket and binding the
3334 * Which-ever is correct, we will serve 1 more page via the
3335 * old settings. This should probably be a "show-proxy-args"
3336 * request. This should not be a so common of an operation
3337 * that this will hurt people's feelings.
3342 bfd = bind_port_helper(config);
3345 log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
3347 if (!accept_connection(csp, bfd))
3349 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3362 log_error(LOG_LEVEL_CONNECT, "accepted connection from %s", csp->ip_addr_str);
3365 #ifdef FEATURE_TOGGLE
3366 if (global_toggle_state)
3368 csp->flags |= CSP_FLAG_TOGGLED_ON;
3370 #endif /* def FEATURE_TOGGLE */
3372 if (run_loader(csp))
3374 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3375 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3379 if (block_acl(NULL,csp))
3381 log_error(LOG_LEVEL_CONNECT, "Connection from %s dropped due to ACL", csp->ip_addr_str);
3382 close_socket(csp->cfd);
3386 #endif /* def FEATURE_ACL */
3388 /* add it to the list of clients */
3389 csp->next = clients->next;
3390 clients->next = csp;
3392 if (config->multi_threaded)
3396 /* this is a switch () statment in the C preprocessor - ugh */
3397 #undef SELECTED_ONE_OPTION
3399 /* Use Pthreads in preference to native code */
3400 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
3401 #define SELECTED_ONE_OPTION
3403 pthread_t the_thread;
3404 pthread_attr_t attrs;
3406 pthread_attr_init(&attrs);
3407 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
3408 errno = pthread_create(&the_thread, &attrs,
3409 (void * (*)(void *))serve, csp);
3410 child_id = errno ? -1 : 0;
3411 pthread_attr_destroy(&attrs);
3415 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
3416 #define SELECTED_ONE_OPTION
3417 child_id = _beginthread(
3418 (void (*)(void *))serve,
3423 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
3424 #define SELECTED_ONE_OPTION
3425 child_id = _beginthread(
3426 (void(* _Optlink)(void*))serve,
3432 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
3433 #define SELECTED_ONE_OPTION
3435 thread_id tid = spawn_thread
3436 (server_thread, "server", B_NORMAL_PRIORITY, csp);
3438 if ((tid >= 0) && (resume_thread(tid) == B_OK))
3440 child_id = (int) tid;
3449 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
3450 #define SELECTED_ONE_OPTION
3451 csp->cfd = ReleaseSocket(csp->cfd, -1);
3454 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3455 NP_Output, Output(),
3456 NP_CloseOutput, FALSE,
3457 NP_Name, (ULONG)"privoxy child",
3461 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3462 NP_Output, Output(),
3463 NP_CloseOutput, FALSE,
3464 NP_Name, (ULONG)"privoxy child",
3465 NP_StackSize, 200*1024,
3471 ((struct Task *)child_id)->tc_UserData = csp;
3472 Signal((struct Task *)child_id, SIGF_SINGLE);
3477 #if !defined(SELECTED_ONE_OPTION)
3480 /* This block is only needed when using fork().
3481 * When using threads, the server thread was
3482 * created and run by the call to _beginthread().
3484 if (child_id == 0) /* child */
3487 #ifdef FEATURE_TOGGLE
3488 int inherited_toggle_state = global_toggle_state;
3489 #endif /* def FEATURE_TOGGLE */
3494 * If we've been toggled or we've blocked the request, tell Mom
3497 #ifdef FEATURE_TOGGLE
3498 if (inherited_toggle_state != global_toggle_state)
3500 rc |= RC_FLAG_TOGGLED;
3502 #endif /* def FEATURE_TOGGLE */
3504 #ifdef FEATURE_STATISTICS
3505 if (csp->flags & CSP_FLAG_REJECTED)
3507 rc |= RC_FLAG_BLOCKED;
3509 #endif /* ndef FEATURE_STATISTICS */
3513 else if (child_id > 0) /* parent */
3515 /* in a fork()'d environment, the parent's
3516 * copy of the client socket and the CSP
3520 #if !defined(_WIN32) && !defined(__CYGWIN__)
3522 wait( &child_status );
3525 * Evaluate child's return code: If the child has
3526 * - been toggled, toggle ourselves
3527 * - blocked its request, bump up the stats counter
3530 #ifdef FEATURE_TOGGLE
3531 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
3533 global_toggle_state = !global_toggle_state;
3535 #endif /* def FEATURE_TOGGLE */
3537 #ifdef FEATURE_STATISTICS
3539 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
3543 #endif /* def FEATURE_STATISTICS */
3545 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
3546 close_socket(csp->cfd);
3547 csp->flags &= ~CSP_FLAG_ACTIVE;
3551 #undef SELECTED_ONE_OPTION
3552 /* end of cpp switch () */
3554 if (child_id < 0) /* failed */
3556 char buf[BUFFER_SIZE];
3558 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
3560 snprintf(buf , sizeof(buf), "Privoxy: can't fork: errno = %d", errno);
3562 write_socket(csp->cfd, buf, strlen(buf));
3563 close_socket(csp->cfd);
3564 csp->flags &= ~CSP_FLAG_ACTIVE;
3575 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
3577 /* Clean up. Aim: free all memory (no leaks) */
3578 #ifdef FEATURE_GRACEFUL_TERMINATION
3580 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
3582 unload_current_config_file();
3583 unload_current_actions_file();
3584 unload_current_re_filterfile();
3585 #ifdef FEATURE_TRUST
3586 unload_current_trust_file();
3589 if (config->multi_threaded)
3596 } while ((clients->next != NULL) && (--i > 0));
3600 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
3611 #ifdef FEATURE_COOKIE_JAR
3612 if (NULL != config->jar)
3614 fclose(config->jar);
3618 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
3619 /* Cleanup - remove taskbar icon etc. */
3624 #endif /* FEATURE_GRACEFUL_TERMINATION */