1 const char jcc_rcs[] = "$Id: jcc.c,v 1.99 2006/09/02 15:36:42 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 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.99 2006/09/02 15:36:42 fabiankeil
37 * Follow the OpenBSD port's lead and protect the resolve
38 * functions on OpenBSD as well.
40 * Revision 1.98 2006/08/24 11:01:34 fabiankeil
41 * --user fix. Only use the user as group if no group is specified.
42 * Solves BR 1492612. Thanks to Spinor S. and David Laight.
44 * Revision 1.97 2006/08/18 15:23:17 david__schmidt
45 * Windows service (re-)integration
49 * --install[:service_name]
50 * --uninstall[:service_name]
53 * They work as follows:
54 * --install will create a service for you and then terminate.
55 * By default the service name will be "privoxy" (without the quotes).
56 * However you can run multiple services if you wish, just by adding
57 * a colon and then a name (no spaces).
59 * --uninstall follows the exact same rules a --install.
61 * --service is used when the program is executed by the service
62 * control manager, and in normal circumstances would never be
63 * used as a command line argument.
65 * Revision 1.96 2006/08/15 20:12:36 david__schmidt
66 * Windows service integration
68 * Revision 1.95 2006/08/03 02:46:41 david__schmidt
69 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
71 * Revision 1.94 2006/07/18 14:48:46 david__schmidt
72 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
73 * with what was really the latest development (the v_3_0_branch branch)
75 * Revision 1.92.2.16 2005/04/03 20:10:50 david__schmidt
76 * Thanks to Jindrich Makovicka for a race condition fix for the log
77 * file. The race condition remains for non-pthread implementations.
78 * Reference patch #1175720.
80 * Revision 1.92.2.15 2004/10/03 12:53:32 david__schmidt
81 * Add the ability to check jpeg images for invalid
82 * lengths of comment blocks. Defensive strategy
83 * against the exploit:
84 * Microsoft Security Bulletin MS04-028
85 * Buffer Overrun in JPEG Processing (GDI+) Could
86 * Allow Code Execution (833987)
87 * Enabled with +inspect-jpegs in actions files.
89 * Revision 1.92.2.14 2003/12/12 12:52:53 oes
90 * - Fixed usage info for non-unix platforms
91 * - Fixed small cmdline parsing bug
93 * Revision 1.92.2.13 2003/11/27 19:20:27 oes
94 * Diagnostics: Now preserve the returncode of pthread_create
95 * in errno. Closes BR #775721. Thanks to Geoffrey Hausheer.
97 * Revision 1.92.2.12 2003/07/11 11:34:19 oes
98 * No longer ignore SIGCHLD. Fixes bug #769381
100 * Revision 1.92.2.11 2003/05/14 12:32:02 oes
101 * Close jarfile on graceful exit, remove stray line
103 * Revision 1.92.2.10 2003/05/08 15:13:46 oes
104 * Cosmetics: Killed a warning, a typo and an allocation left at exit
106 * Revision 1.92.2.9 2003/04/03 15:08:42 oes
107 * No longer rely on non-POSIX.1 extensions of getcwd().
110 * Revision 1.92.2.8 2003/03/31 13:12:32 oes
111 * Replaced setenv() by posix-compliant putenv()
112 * Thanks to Neil McCalden (nmcc AT users.sf.net).
114 * Revision 1.92.2.7 2003/03/17 16:48:59 oes
115 * Added chroot ability, thanks to patch by Sviatoslav Sviridov
117 * Revision 1.92.2.6 2003/03/11 11:55:00 oes
118 * Clean-up and extension of improvements for forked mode:
119 * - Child's return code now consists of flags RC_FLAG_*
120 * - Reporting toggle to parent now properly #ifdef'ed
121 * - Children now report blocking to parent. This enables
122 * statistics in forked mode
124 * Revision 1.92.2.5 2003/03/10 23:45:32 oes
125 * Fixed bug #700381: Non-Threaded version now capable of being toggled.
126 * Children now report having been toggled through _exit(17), parents
127 * watch for that code and toggle themselves if found.
129 * Revision 1.92.2.4 2003/03/07 03:41:04 david__schmidt
130 * Wrapping all *_r functions (the non-_r versions of them) with
131 * mutex semaphores for OSX. Hopefully this will take care of all
132 * of those pesky crash reports.
134 * Revision 1.92.2.3 2003/02/28 12:53:06 oes
135 * Fixed two mostly harmless mem leaks
137 * Revision 1.92.2.2 2002/11/20 14:37:47 oes
138 * Fix: Head of global clients list now initialized to NULL
140 * Revision 1.92.2.1 2002/09/25 14:52:24 oes
141 * Added basic support for OPTIONS and TRACE HTTP methods:
142 * - New interceptor direct_response() added in chat().
143 * - sed() moved to earlier in the process, so that the
144 * Host: header is evaluated before actions and forwarding
147 * Revision 1.92 2002/05/08 16:00:46 oes
148 * Chat's buffer handling:
149 * - Fixed bug with unchecked out-of-mem conditions
150 * while reading client request & server headers
151 * - No longer predict if the buffer limit will be exceeded
152 * in the next read -- check add_to_iob's new
153 * return code. If buffer couldn't be extended
154 * (policy or out-of-mem) while
155 * - reading from client: abort
156 * - reading server headers: send error page
157 * - buffering server body for filter: flush,
158 * and if that fails: send error page
160 * Revision 1.91 2002/04/08 20:35:58 swa
163 * Revision 1.90 2002/04/02 14:57:28 oes
164 * Made sending wafers independent of FEATURE_COOKIE_JAR
166 * Revision 1.89 2002/03/31 17:18:59 jongfoster
167 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
169 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
170 * More compiler warning message maintenance
172 * Revision 1.87 2002/03/26 22:29:54 swa
173 * we have a new homepage!
175 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
176 * Workaround for closing the jarfile before load_config() comes around again
178 * Revision 1.85 2002/03/24 15:23:33 jongfoster
181 * Revision 1.84 2002/03/24 13:25:43 swa
182 * name change related issues
184 * Revision 1.83 2002/03/16 23:54:06 jongfoster
185 * Adding graceful termination feature, to help look for memory leaks.
186 * If you enable this (which, by design, has to be done by hand
187 * editing config.h) and then go to http://i.j.b/die, then the program
188 * will exit cleanly after the *next* request. It should free all the
189 * memory that was used.
191 * Revision 1.82 2002/03/13 00:27:05 jongfoster
194 * Revision 1.81 2002/03/12 01:42:50 oes
195 * Introduced modular filters
197 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
198 * OS/2 port maintenance:
199 * - Fixed EMX build - it had decayed a little
200 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
201 * substituted a memset for now.
203 * Revision 1.79 2002/03/09 20:03:52 jongfoster
204 * - Making various functions return int rather than size_t.
205 * (Undoing a recent change). Since size_t is unsigned on
206 * Windows, functions like read_socket that return -1 on
207 * error cannot return a size_t.
209 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
210 * crashes, and also frequently caused JB to jump to 100%
211 * CPU and stay there. (Because it thought it had just
212 * read ((unsigned)-1) == 4Gb of data...)
214 * - The signature of write_socket has changed, it now simply
215 * returns success=0/failure=nonzero.
217 * - Trying to get rid of a few warnings --with-debug on
218 * Windows, I've introduced a new type "jb_socket". This is
219 * used for the socket file descriptors. On Windows, this
220 * is SOCKET (a typedef for unsigned). Everywhere else, it's
221 * an int. The error value can't be -1 any more, so it's
222 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
223 * Windows it maps to the #define INVALID_SOCKET.)
225 * - The signature of bind_port has changed.
227 * Revision 1.78 2002/03/08 21:35:04 oes
228 * Added optional group supplement to --user option. Will now use default group of user if no group given
230 * Revision 1.77 2002/03/07 03:52:06 oes
231 * - Fixed compiler warnings etc
232 * - Improved handling of failed DNS lookups
234 * Revision 1.76 2002/03/06 22:54:35 jongfoster
235 * Automated function-comment nitpicking.
237 * Revision 1.75 2002/03/06 10:02:19 oes
238 * Fixed stupid bug when --user was not given
240 * Revision 1.74 2002/03/06 00:49:31 jongfoster
241 * Fixing warning on Windows
242 * Making #ifdefs that refer to the same variable consistently
243 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
245 * Revision 1.73 2002/03/05 23:57:30 hal9
246 * Stray character 's' on line 1618 was breaking build.
248 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
249 * - Re-enable OS/2 building after new parms were added
250 * - Fix false out of memory report when resolving CGI templates when no IP
251 * address is available of failed attempt (a la no such domain)
253 * Revision 1.71 2002/03/05 18:13:56 oes
254 * Added --user option
256 * Revision 1.70 2002/03/05 04:52:42 oes
257 * Deleted non-errlog debugging code
259 * Revision 1.69 2002/03/04 23:50:00 jongfoster
260 * Splitting off bind_port() call into bind_port_helper(), with
263 * Revision 1.68 2002/03/04 20:17:32 oes
266 * Revision 1.67 2002/03/04 18:18:57 oes
267 * - Removed _DEBUG mode
268 * - Cleand up cmdline parsing
269 * - Introduced --no-daemon, --pidfile options
270 * - Cleaned up signal handling:
271 * - Terminate cleanly on INT, TERM and ABRT
272 * - Schedule logfile for re-opening on HUP
273 * - Ignore CHLD and PIPE
274 * - Leave the rest with their default handlers
275 * - Uniform handler registration
276 * - Added usage() function
277 * - Played styleguide police
279 * Revision 1.66 2002/03/03 15:06:55 oes
280 * Re-enabled automatic config reloading
282 * Revision 1.65 2002/03/03 14:49:11 oes
283 * Fixed CLF logging: Now uses client's original HTTP request
285 * Revision 1.64 2002/03/03 09:18:03 joergs
286 * Made jumbjuster work on AmigaOS again.
288 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
289 * Clean up a little CRLF unpleasantness that suddenly appeared
291 * Revision 1.62 2002/02/20 23:17:23 jongfoster
292 * Detecting some out-of memory conditions and exiting with a log message.
294 * Revision 1.61 2002/01/17 21:01:52 jongfoster
295 * Moving all our URL and URL pattern parsing code to urlmatch.c.
297 * Revision 1.60 2001/12/30 14:07:32 steudten
298 * - Add signal handling (unix)
299 * - Add SIGHUP handler (unix)
300 * - Add creation of pidfile (unix)
301 * - Add action 'top' in rc file (RH)
302 * - Add entry 'SIGNALS' to manpage
303 * - Add exit message to logfile (unix)
305 * Revision 1.59 2001/12/13 14:07:18 oes
306 * Fixed Bug: 503 error page now sent OK
308 * Revision 1.58 2001/11/30 23:37:24 jongfoster
309 * Renaming the Win32 config file to config.txt - this is almost the
310 * same as the corresponding UNIX name "config"
312 * Revision 1.57 2001/11/16 00:47:43 jongfoster
313 * Changing the tty-disconnection code to use setsid().
315 * Revision 1.56 2001/11/13 20:20:54 jongfoster
316 * Tabs->spaces, fixing a bug with missing {} around an if()
318 * Revision 1.55 2001/11/13 20:14:53 jongfoster
319 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
321 * Revision 1.54 2001/11/07 00:03:14 steudten
322 * Give reliable return value if an error
323 * occurs not just 0 with new daemon mode.
325 * Revision 1.53 2001/11/05 21:41:43 steudten
326 * Add changes to be a real daemon just for unix os.
327 * (change cwd to /, detach from controlling tty, set
328 * process group and session leader to the own process.
330 * Add some fatal-error log message for failed malloc().
331 * Add '-d' if compiled with 'configure --with-debug' to
332 * enable debug output.
334 * Revision 1.52 2001/10/26 20:11:20 jongfoster
335 * Fixing type mismatch
337 * Revision 1.51 2001/10/26 17:38:28 oes
340 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
341 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
342 * threads to call select() simultaneously. So, it's time to do a real, live,
343 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
344 * (native). Both versions will work, but using __OS2__ offers multi-threading.
346 * Revision 1.49 2001/10/23 21:41:35 jongfoster
347 * Added call to initialize the (statically-allocated of course)
348 * "out of memory" CGI response.
350 * Revision 1.48 2001/10/10 19:56:46 jongfoster
351 * Moving some code that wasn't cookie-related out of an #ifdef
354 * Revision 1.47 2001/10/10 16:44:36 oes
355 * Added CONNECT destination port limitation check
357 * Revision 1.46 2001/10/08 15:17:41 oes
358 * Re-enabled SSL forwarding
360 * Revision 1.45 2001/10/07 15:42:11 oes
361 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
363 * Moved downgrading of the HTTP version from parse_http_request to
364 * chat(), since we can't decide if it is necessary before we have
365 * determined the actions for the URL. The HTTP command is now
366 * *always* re-built so the repairs need no longer be special-cased.
368 * filter_popups now gets a csp pointer so it can raise the new
369 * CSP_FLAG_MODIFIED flag.
373 * Added configurable size limit for the IOB. If the IOB grows so
374 * large that the next read would exceed the limit, the header
375 * is generated, and the header & unfiltered buffer are flushed
376 * to the client. Chat then continues in non-buffering,
377 * non-filtering body mode.
379 * Revision 1.44 2001/10/02 18:13:57 oes
382 * Revision 1.43 2001/10/02 15:32:13 oes
383 * Moved generation of hdr
385 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
386 * Cleaning up 2 compiler warnings on OS/2.
388 * Revision 1.41 2001/09/16 17:05:14 jongfoster
389 * Removing unused #include showarg.h
391 * Revision 1.40 2001/09/16 15:41:45 jongfoster
392 * Fixing signed/unsigned comparison warning.
394 * Revision 1.39 2001/09/16 13:21:27 jongfoster
395 * Changes to use new list functions.
397 * Revision 1.38 2001/09/16 13:01:46 jongfoster
398 * Removing redundant function call that zeroed zalloc()'d memory.
400 * Revision 1.37 2001/09/10 11:12:24 oes
401 * Deleted unused variable
403 * Revision 1.36 2001/09/10 10:56:15 oes
404 * Silenced compiler warnings
406 * Revision 1.35 2001/07/31 14:44:22 oes
407 * Deleted unused size parameter from filter_popups()
409 * Revision 1.34 2001/07/30 22:08:36 jongfoster
410 * Tidying up #defines:
411 * - All feature #defines are now of the form FEATURE_xxx
412 * - Permanently turned off WIN_GUI_EDIT
413 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
415 * Revision 1.33 2001/07/29 19:32:00 jongfoster
416 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
418 * Revision 1.32 2001/07/29 18:47:05 jongfoster
419 * Adding missing #include "loadcfg.h"
421 * Revision 1.31 2001/07/29 12:17:48 oes
422 * Applied pthread fix by Paul Lieverse
424 * Revision 1.30 2001/07/25 22:57:13 jongfoster
425 * __BEOS__ no longer overrides FEATURE_PTHREAD.
426 * This is because FEATURE_PTHREAD will soon be widely used, so I
427 * want to keep it simple.
429 * Revision 1.29 2001/07/24 12:47:06 oes
430 * Applied BeOS support update by Eugenia
432 * Revision 1.28 2001/07/23 13:26:12 oes
433 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
435 * Revision 1.27 2001/07/19 19:09:47 haroon
436 * - Added code to take care of the situation where while processing the first
437 * server response (which includes the server header), after finding the end
438 * of the headers we were not looking past the end of the headers for
439 * content modification. I enabled it for filter_popups.
440 * Someone else should look to see if other similar operations should be
441 * done to the discarded portion of the buffer.
443 * Note 2001/07/20: No, the other content modification mechanisms will process
444 * the whole iob later anyway. --oes
446 * Revision 1.26 2001/07/18 12:31:36 oes
449 * Revision 1.25 2001/07/15 19:43:49 jongfoster
450 * Supports POSIX threads.
451 * Also removed some unused #includes.
453 * Revision 1.24 2001/07/13 14:00:40 oes
454 * - Generic content modification scheme:
455 * Each feature has its own applicability flag that is set
456 * from csp->action->flags.
457 * Replaced the "filtering" int flag , by a function pointer
458 * "content_filter" to the function that will do the content
459 * modification. If it is != NULL, the document will be buffered
460 * and processed through *content_filter, which must set
461 * csp->content_length and return a modified copy of the body
462 * or return NULL (on failiure).
463 * - Changed csp->is_text to the more generic bitmap csp->content_type
464 * which can currently take the valued CT_TEXT or CT_GIF
466 * - Removed all #ifdef PCRS
468 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
469 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
470 * the `block_acl' call. This prevents a compilation error when the user
471 * does not wish to use the "ACL" feature.
473 * Revision 1.22 2001/06/29 21:45:41 oes
474 * Indentation, CRLF->LF, Tab-> Space
476 * Revision 1.21 2001/06/29 13:29:36 oes
477 * - Cleaned up, improved comments
478 * - Unified all possible interceptors (CGI,
479 * block, trust, fast_redirect) in one
480 * place, with one (CGI) answer generation
481 * mechansim. Much clearer now.
482 * - Removed the GIF image generation, which
483 * is now done in filters.c:block_url()
484 * - Made error conditions like domain lookup
485 * failiure or (various) problems while talking
486 * to the server use cgi.c:error_response()
487 * instead of generating HTML/HTTP in chat() (yuck!)
488 * - Removed logentry from cancelled commit
490 * Revision 1.20 2001/06/09 10:55:28 jongfoster
491 * Changing BUFSIZ ==> BUFFER_SIZE
493 * Revision 1.19 2001/06/07 23:12:52 jongfoster
494 * Replacing function pointer in struct gateway with a directly
495 * called function forwarded_connect().
496 * Replacing struct gateway with struct forward_spec
498 * Revision 1.18 2001/06/03 19:12:16 oes
499 * introduced new cgi handling
501 * Revision 1.17 2001/06/01 20:07:23 jongfoster
502 * Now uses action +image-blocker{} rather than config->tinygif
504 * Revision 1.16 2001/06/01 18:49:17 jongfoster
505 * Replaced "list_share" with "list" - the tiny memory gain was not
506 * worth the extra complexity.
508 * Revision 1.15 2001/05/31 21:24:47 jongfoster
509 * Changed "permission" to "action" throughout.
510 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
511 * Moved vanilla wafer check into chat(), since we must now
512 * decide whether or not to add it based on the URL.
514 * Revision 1.14 2001/05/29 20:14:01 joergs
515 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
518 * Revision 1.13 2001/05/29 09:50:24 jongfoster
519 * Unified blocklist/imagelist/permissionslist.
520 * File format is still under discussion, but the internal changes
523 * Also modified interceptor behaviour:
524 * - We now intercept all URLs beginning with one of the following
525 * prefixes (and *only* these prefixes):
527 * * http://ijbswa.sf.net/config/
528 * * http://ijbswa.sourceforge.net/config/
529 * - New interceptors "home page" - go to http://i.j.b/ to see it.
530 * - Internal changes so that intercepted and fast redirect pages
531 * are not replaced with an image.
532 * - Interceptors now have the option to send a binary page direct
533 * to the client. (i.e. ijb-send-banner uses this)
534 * - Implemented show-url-info interceptor. (Which is why I needed
535 * the above interceptors changes - a typical URL is
536 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
537 * The previous mechanism would not have intercepted that, and
538 * if it had been intercepted then it then it would have replaced
541 * Revision 1.12 2001/05/27 22:17:04 oes
543 * - re_process_buffer no longer writes the modified buffer
544 * to the client, which was very ugly. It now returns the
545 * buffer, which it is then written by chat.
547 * - content_length now adjusts the Content-Length: header
548 * for modified documents rather than crunch()ing it.
549 * (Length info in csp->content_length, which is 0 for
550 * unmodified documents)
552 * - For this to work, sed() is called twice when filtering.
554 * Revision 1.11 2001/05/26 17:27:53 jongfoster
555 * Added support for CLF and fixed LOG_LEVEL_LOG.
556 * Also did CRLF->LF fix of my previous patch.
558 * Revision 1.10 2001/05/26 15:26:15 jongfoster
559 * ACL feature now provides more security by immediately dropping
560 * connections from untrusted hosts.
562 * Revision 1.9 2001/05/26 00:28:36 jongfoster
563 * Automatic reloading of config file.
564 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
565 * Most of the global variables have been moved to a new
566 * struct configuration_spec, accessed through csp->config->globalname
567 * Most of the globals remaining are used by the Win32 GUI.
569 * Revision 1.8 2001/05/25 22:43:18 jongfoster
570 * Fixing minor memory leak and buffer overflow.
572 * Revision 1.7 2001/05/25 22:34:30 jongfoster
575 * Revision 1.6 2001/05/23 00:13:58 joergs
576 * AmigaOS support fixed.
578 * Revision 1.5 2001/05/22 18:46:04 oes
580 * - Enabled filtering banners by size rather than URL
581 * by adding patterns that replace all standard banner
582 * sizes with the "Junkbuster" gif to the re_filterfile
584 * - Enabled filtering WebBugs by providing a pattern
585 * which kills all 1x1 images
587 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
588 * which is selected by the (nonstandard and therefore
589 * capital) letter 'U' in the option string.
590 * It causes the quantifiers to be ungreedy by default.
591 * Appending a ? turns back to greedy (!).
593 * - Added a new interceptor ijb-send-banner, which
594 * sends back the "Junkbuster" gif. Without imagelist or
595 * MSIE detection support, or if tinygif = 1, or the
596 * URL isn't recognized as an imageurl, a lame HTML
597 * explanation is sent instead.
599 * - Added new feature, which permits blocking remote
600 * script redirects and firing back a local redirect
602 * The feature is conditionally compiled, i.e. it
603 * can be disabled with --disable-fast-redirects,
604 * plus it must be activated by a "fast-redirects"
605 * line in the config file, has its own log level
606 * and of course wants to be displayed by show-proxy-args
607 * Note: Boy, all the #ifdefs in 1001 locations and
608 * all the fumbling with configure.in and acconfig.h
609 * were *way* more work than the feature itself :-(
611 * - Because a generic redirect template was needed for
612 * this, tinygif = 3 now uses the same.
614 * - Moved GIFs, and other static HTTP response templates
619 * - Removed some >400 CRs again (Jon, you really worked
622 * Revision 1.4 2001/05/21 19:34:01 jongfoster
623 * Made failure to bind() a fatal error.
625 * Revision 1.3 2001/05/20 01:21:20 jongfoster
626 * Version 2.9.4 checkin.
627 * - Merged popupfile and cookiefile, and added control over PCRS
628 * filtering, in new "permissionsfile".
629 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
630 * file error you now get a message box (in the Win32 GUI) rather
631 * than the program exiting with no explanation.
632 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
634 * - Removed tabs from "config"
635 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
636 * - Bumped up version number.
638 * Revision 1.2 2001/05/17 22:34:44 oes
639 * - Added hint on GIF char array generation to jcc.c
640 * - Cleaned CRLF's from the sources and related files
641 * - Repaired logging for REF and FRC
643 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
644 * Initial import of version 2.9.3 source tree
647 *********************************************************************/
653 #include <sys/types.h>
660 #ifdef FEATURE_PTHREAD
662 #endif /* def FEATURE_PTHREAD */
665 # ifndef FEATURE_PTHREAD
669 # include <windows.h>
670 # include <process.h>
671 # endif /* ndef FEATURE_PTHREAD */
674 # ifndef _WIN_CONSOLE
676 # endif /* ndef _WIN_CONSOLE */
677 # include "w32svrapi.h"
679 #else /* ifndef _WIN32 */
681 # if !defined (__OS2__)
683 # include <sys/wait.h>
684 # endif /* ndef __OS2__ */
685 # include <sys/time.h>
686 # include <sys/stat.h>
687 # include <sys/ioctl.h>
690 #include <sys/termios.h>
701 # include <socket.h> /* BeOS has select() for sockets only. */
702 # include <OS.h> /* declarations for threads and stuff. */
705 # if defined(__EMX__) || defined(__OS2__)
706 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
711 #define bzero(B,N) memset(B,0x00,n)
726 #include "killpopup.h"
727 #include "miscutil.h"
729 #include "jbsockets.h"
734 #include "urlmatch.h"
736 const char jcc_h_rcs[] = JCC_H_VERSION;
737 const char project_h_rcs[] = PROJECT_H_VERSION;
740 struct client_state clients[1];
741 struct file_list files[1];
743 #ifdef FEATURE_STATISTICS
744 int urls_read = 0; /* total nr of urls read inc rejected */
745 int urls_rejected = 0; /* total nr of urls rejected */
746 #endif /* def FEATURE_STATISTICS */
748 #ifdef FEATURE_GRACEFUL_TERMINATION
752 static void listen_loop(void);
753 static void chat(struct client_state *csp);
755 void serve(struct client_state *csp);
756 #else /* ifndef AMIGA */
757 static void serve(struct client_state *csp);
758 #endif /* def AMIGA */
761 static int32 server_thread(void *data);
762 #endif /* def __BEOS__ */
765 #define sleep(N) Sleep(((N) * 1000))
769 #define sleep(N) DosSleep(((N) * 100))
772 #if defined(OSX_DARWIN) || defined(__OpenBSD__)
775 * Hit OSX over the head with a hammer. Protect all *_r functions.
777 pthread_mutex_t gmtime_mutex;
778 pthread_mutex_t localtime_mutex;
779 #endif /* def OSX_DARWIN */
781 * Protect only the resolve functions for OpenBSD.
783 pthread_mutex_t gethostbyaddr_mutex;
784 pthread_mutex_t gethostbyname_mutex;
785 #endif /* defined(OSX_DARWIN) || defined(__OpenBSD__) */
787 #ifdef FEATURE_PTHREAD
788 pthread_mutex_t log_mutex;
789 pthread_mutex_t log_init_mutex;
790 #endif /* FEATURE_PTHREAD */
792 #if defined(unix) || defined(__EMX__)
793 const char *basedir = NULL;
794 const char *pidfile = NULL;
795 int received_hup_signal = 0;
796 #endif /* defined unix */
798 /* The vanilla wafer. */
799 static const char VANILLA_WAFER[] =
800 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
801 "Do_not_send_me_any_copyrighted_information_other_than_the_"
802 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
803 "In_particular_do_not_send_me_any_cookies_that_"
804 "are_subject_to_a_claim_of_copyright_by_anybody._"
805 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
806 "(copyright_or_otherwise)_applying_to_any_cookie._";
809 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
810 /*********************************************************************
812 * Function : sig_handler
814 * Description : Signal handler for different signals.
815 * Exit gracefully on ABRT, TERM and INT
816 * or set a flag that will cause the errlog
817 * to be reopened by the main thread on HUP.
820 * 1 : the_signal = the signal cause this function to call
824 *********************************************************************/
825 static void sig_handler(int the_signal)
832 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
840 received_hup_signal = 1;
845 * We shouldn't be here, unless we catch signals
846 * in main() that we can't handle here!
848 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
856 /*********************************************************************
860 * Description : Once a connection to the client has been accepted,
861 * this function is called (via serve()) to handle the
862 * main business of the communication. When this
863 * function returns, the caller must close the client
867 * 1 : csp = Current client state (buffers, headers, etc...)
869 * Returns : On success, the number of bytes written are returned (zero
870 * indicates nothing was written). On error, -1 is returned,
871 * and errno is set appropriately. If count is zero and the
872 * file descriptor refers to a regular file, 0 will be
873 * returned without causing any other effect. For a special
874 * file, the results are not portable.
876 *********************************************************************/
877 static void chat(struct client_state *csp)
880 * This next lines are a little ugly, but they simplifies the if statements
881 * below. Basically if TOGGLE, then we want the if to test if the
882 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
883 * then we want the if to test for CSP_FLAG_FORCED , else we don't
885 #ifdef FEATURE_TOGGLE
886 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
887 #else /* ifndef FEATURE_TOGGLE */
888 # define IS_TOGGLED_ON_AND
889 #endif /* ndef FEATURE_TOGGLE */
890 #ifdef FEATURE_FORCE_LOAD
891 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
892 #else /* ifndef FEATURE_FORCE_LOAD */
893 # define IS_NOT_FORCED_AND
894 #endif /* def FEATURE_FORCE_LOAD */
896 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
898 char buf[BUFFER_SIZE];
906 int ms_iis5_hack = 0;
908 unsigned int socks_retries = 0;
909 const struct forward_spec * fwd;
910 struct http_request *http;
911 int len; /* for buffer sizes */
912 #ifdef FEATURE_KILL_POPUPS
913 int block_popups; /* bool, 1==will block popups */
914 int block_popups_now = 0; /* bool, 1==currently blocking popups */
915 #endif /* def FEATURE_KILL_POPUPS */
917 int pcrs_filter; /* bool, 1==will filter through pcrs */
918 int gif_deanimate; /* bool, 1==will deanimate gifs */
919 int jpeg_inspect; /* bool, 1==will inspect jpegs */
921 /* Function that does the content filtering for the current request */
922 char *(*content_filter)() = NULL;
924 /* Skeleton for HTTP response, if we should intercept the request */
925 struct http_response *rsp;
930 * Read the client's request. Note that since we're not using select() we
931 * could get blocked here if a client connected, then didn't say anything!
936 len = read_socket(csp->cfd, buf, sizeof(buf));
938 if (len <= 0) break; /* error! */
941 * If there is no memory left for buffering the
942 * request, there is nothing we can do but hang up
944 if (add_to_iob(csp, buf, len))
949 req = get_header(csp);
953 break; /* no HTTP request! */
958 continue; /* more to come! */
961 #ifdef FEATURE_FORCE_LOAD
962 /* If this request contains the FORCE_PREFIX,
963 * better get rid of it now and set the force flag --oes
966 if (strstr(req, FORCE_PREFIX))
968 strclean(req, FORCE_PREFIX);
969 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
970 csp->flags |= CSP_FLAG_FORCED;
973 #endif /* def FEATURE_FORCE_LOAD */
975 parse_http_request(req, http, csp);
980 if (http->cmd == NULL)
982 strcpy(buf, CHEADER);
983 write_socket(csp->cfd, buf, strlen(buf));
985 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
987 free_http_request(http);
991 /* decide how to route the HTTP request */
993 if ((fwd = forward_url(http, csp)) == NULL)
995 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
996 /* Never get here - LOG_LEVEL_FATAL causes program exit */
999 /* build the http request to send to the server
1000 * we have to do one of the following:
1002 * create = use the original HTTP request to create a new
1003 * HTTP request that has either the path component
1004 * without the http://domainspec (w/path) or the
1005 * full orininal URL (w/url)
1006 * Note that the path and/or the HTTP version may
1007 * have been altered by now.
1009 * connect = Open a socket to the host:port of the server
1010 * and short-circuit server and client socket.
1012 * pass = Pass the request unchanged if forwarding a CONNECT
1013 * request to a parent proxy. Note that we'll be sending
1014 * the CFAIL message ourselves if connecting to the parent
1015 * fails, but we won't send a CSUCCEED message if it works,
1016 * since that would result in a double message (ours and the
1017 * parent's). After sending the request to the parent, we simply
1020 * here's the matrix:
1023 * +--------+--------+
1025 * 0 | create | connect|
1027 * Forwarding +--------+--------+
1029 * 1 | create | pass |
1031 * +--------+--------+
1036 * Determine the actions for this URL
1038 #ifdef FEATURE_TOGGLE
1039 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1041 /* Most compatible set of actions (i.e. none) */
1042 init_current_action(csp->action);
1045 #endif /* ndef FEATURE_TOGGLE */
1047 url_actions(http, csp);
1052 * Check if a CONNECT request is allowable:
1053 * In the absence of a +limit-connect action, allow only port 443.
1054 * If there is an action, allow whatever matches the specificaton.
1058 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
1059 || (csp->action->flags & ACTION_LIMIT_CONNECT
1060 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
1062 if (csp->action->flags & ACTION_TREAT_FORBIDDEN_CONNECTS_LIKE_BLOCKS)
1064 /* The response will violate the specs, but makes unblocking easier. */
1065 log_error(LOG_LEVEL_ERROR, "Marking suspicious CONNECT request from %s for blocking.",
1067 csp->action->flags |= ACTION_BLOCK;
1072 strcpy(buf, CFORBIDDEN);
1073 write_socket(csp->cfd, buf, strlen(buf));
1074 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
1075 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
1083 * Downgrade http version from 1.1 to 1.0 if +downgrade
1086 if ( (http->ssl == 0)
1087 && (!strcmpic(http->ver, "HTTP/1.1"))
1088 && (csp->action->flags & ACTION_DOWNGRADE))
1091 http->ver = strdup("HTTP/1.0");
1093 if (http->ver == NULL)
1095 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
1100 * Save a copy of the original request for logging
1102 http->ocmd = strdup(http->cmd);
1104 if (http->ocmd == NULL)
1106 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
1110 * (Re)build the HTTP request for non-SSL requests.
1111 * If forwarding, use the whole URL, else, use only the path.
1117 http->cmd = strdup(http->gpc);
1118 string_append(&http->cmd, " ");
1120 if (fwd->forward_host)
1122 string_append(&http->cmd, http->url);
1126 string_append(&http->cmd, http->path);
1128 string_append(&http->cmd, " ");
1129 string_append(&http->cmd, http->ver);
1131 if (http->cmd == NULL)
1133 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1135 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", http->cmd);
1137 enlist(csp->headers, http->cmd);
1141 * If the user has not supplied any wafers, and the user has not
1142 * told us to suppress the vanilla wafer, then send the vanilla wafer.
1144 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
1145 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
1147 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
1151 #ifdef FEATURE_KILL_POPUPS
1152 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1153 #endif /* def FEATURE_KILL_POPUPS */
1155 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
1156 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1158 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1160 jpeg_inspect = ((csp->action->flags & ACTION_JPEG_INSPECT) != 0);
1162 /* grab the rest of the client's headers */
1166 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
1168 len = read_socket(csp->cfd, buf, sizeof(buf));
1171 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1176 * If there is no memory left for buffering the
1177 * request, there is nothing we can do but hang up
1179 if (add_to_iob(csp, buf, len))
1186 if (p == NULL) break;
1188 enlist(csp->headers, p);
1193 * We have a request. Now, check to see if we need to
1194 * intercept it, i.e. If ..
1198 /* We may not forward the request by rfc2616 sect 14.31 */
1199 (NULL != (rsp = direct_response(csp)))
1201 /* or a CGI call was detected and answered */
1202 || (NULL != (rsp = dispatch_cgi(csp)))
1204 /* or we are enabled and... */
1205 || (IS_ENABLED_AND (
1207 /* ..the request was blocked */
1208 ( NULL != (rsp = block_url(csp)))
1210 /* ..or untrusted */
1211 #ifdef FEATURE_TRUST
1212 || ( NULL != (rsp = trust_url(csp)))
1213 #endif /* def FEATURE_TRUST */
1215 /* ..or a fast redirect kicked in */
1216 #ifdef FEATURE_FAST_REDIRECTS
1217 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
1218 (NULL != (rsp = redirect_url(csp))))
1219 #endif /* def FEATURE_FAST_REDIRECTS */
1223 /* Write the answer to the client */
1224 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1225 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1227 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1230 #ifdef FEATURE_STATISTICS
1231 /* Count as a rejected request */
1232 csp->flags |= CSP_FLAG_REJECTED;
1233 #endif /* def FEATURE_STATISTICS */
1235 /* Log (FIXME: All intercept reasons appear as "crunch" with Status 200) */
1236 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1237 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1239 /* Clean up and return */
1240 free_http_response(rsp);
1244 hdr = sed(client_patterns, add_client_headers, csp);
1247 /* FIXME Should handle error properly */
1248 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1251 list_remove_all(csp->headers);
1253 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1255 if (fwd->forward_host)
1257 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1258 fwd->forward_host, fwd->forward_port, http->hostport);
1262 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1265 /* here we connect to the server, gateway, or the forwarder */
1267 while ( (csp->sfd = forwarded_connect(fwd, http, csp))
1268 && (errno == EINVAL) && (socks_retries++ < 3))
1270 log_error(LOG_LEVEL_ERROR, "failed request #%u to connect to %s. Trying again.",
1271 socks_retries, http->hostport);
1274 if (csp->sfd == JB_INVALID_SOCKET)
1276 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1279 if (errno == EINVAL)
1281 rsp = error_response(csp, "no-such-domain", errno);
1283 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1284 csp->ip_addr_str, http->ocmd);
1288 rsp = error_response(csp, "connect-failed", errno);
1290 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1291 csp->ip_addr_str, http->ocmd);
1295 /* Write the answer to the client */
1298 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1299 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1301 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1305 free_http_response(rsp);
1310 log_error(LOG_LEVEL_CONNECT, "OK");
1312 if (fwd->forward_host || (http->ssl == 0))
1314 /* write the client's (modified) header to the server
1315 * (along with anything else that may be in the buffer)
1318 if (write_socket(csp->sfd, hdr, strlen(hdr))
1319 || (flush_socket(csp->sfd, csp) < 0))
1321 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1324 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1325 csp->ip_addr_str, http->ocmd);
1327 rsp = error_response(csp, "connect-failed", errno);
1331 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1332 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1334 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1338 free_http_response(rsp);
1346 * We're running an SSL tunnel and we're not forwarding,
1347 * so just send the "connect succeeded" message to the
1348 * client, flush the rest, and get out of the way.
1350 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1351 csp->ip_addr_str, http->ocmd);
1353 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1361 /* we're finished with the client's header */
1364 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1366 /* pass data between the client and server
1367 * until one or the other shuts down the connection.
1376 * FD_ZERO here seems to point to an errant macro which crashes.
1377 * So do this by hand for now...
1379 memset(&rfds,0x00,sizeof(fd_set));
1383 FD_SET(csp->cfd, &rfds);
1384 FD_SET(csp->sfd, &rfds);
1386 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1390 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1394 /* this is the body of the browser's request
1395 * just read it and write it.
1398 if (FD_ISSET(csp->cfd, &rfds))
1400 len = read_socket(csp->cfd, buf, sizeof(buf));
1404 break; /* "game over, man" */
1407 if (write_socket(csp->sfd, buf, (size_t)len))
1409 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1416 * The server wants to talk. It could be the header or the body.
1417 * If `hdr' is null, then it's the header otherwise it's the body.
1418 * FIXME: Does `hdr' really mean `host'? No.
1422 if (FD_ISSET(csp->sfd, &rfds))
1425 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1429 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1431 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1432 csp->ip_addr_str, http->ocmd);
1434 rsp = error_response(csp, "connect-failed", errno);
1438 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1439 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1441 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1445 free_http_response(rsp);
1449 /* Add a trailing zero. This lets filter_popups
1450 * use string operations.
1454 #ifdef FEATURE_KILL_POPUPS
1455 /* Filter the popups on this read. */
1456 if (block_popups_now)
1458 filter_popups(buf, csp);
1460 #endif /* def FEATURE_KILL_POPUPS */
1462 /* Normally, this would indicate that we've read
1463 * as much as the server has sent us and we can
1464 * close the client connection. However, Microsoft
1465 * in its wisdom has released IIS/5 with a bug that
1466 * prevents it from sending the trailing \r\n in
1467 * a 302 redirect header (and possibly other headers).
1468 * To work around this if we've haven't parsed
1469 * a full header we'll append a trailing \r\n
1470 * and see if this now generates a valid one.
1472 * This hack shouldn't have any impacts. If we've
1473 * already transmitted the header or if this is a
1474 * SSL connection, then we won't bother with this
1475 * hack. So we only work on partially received
1476 * headers. If we append a \r\n and this still
1477 * doesn't generate a valid header, then we won't
1478 * transmit anything to the client.
1483 if (server_body || http->ssl)
1486 * If we have been buffering up the document,
1487 * now is the time to apply content modification
1488 * and send the result to the client.
1493 * If the content filter fails, use the original
1494 * buffer and length.
1495 * (see p != NULL ? p : csp->iob->cur below)
1497 if (NULL == (p = (*content_filter)(csp)))
1499 csp->content_length = csp->iob->eod - csp->iob->cur;
1502 hdr = sed(server_patterns_light, NULL, csp);
1506 /* FIXME Should handle error properly */
1507 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1510 if (write_socket(csp->cfd, hdr, strlen(hdr))
1511 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1513 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1523 break; /* "game over, man" */
1527 * This is NOT the body, so
1528 * Let's pretend the server just sent us a blank line.
1530 len = sprintf(buf, "\r\n");
1533 * Now, let the normal header parsing algorithm below do its
1534 * job. If it fails, we'll exit instead of continuing.
1541 * If this is an SSL connection or we're in the body
1542 * of the server document, just write it to the client,
1543 * unless we need to buffer the body for later content-filtering
1546 if (server_body || http->ssl)
1551 * If there is no memory left for buffering the content, or the buffer limit
1552 * has been reached, switch to non-filtering mode, i.e. make & write the
1553 * header, flush the iob and buf, and get out of the way.
1555 if (add_to_iob(csp, buf, len))
1560 log_error(LOG_LEVEL_ERROR, "Flushing header and buffers. Stepping back from filtering.");
1562 hdr = sed(server_patterns, add_server_headers, csp);
1566 * Memory is too tight to even generate the header.
1567 * Send our static "Out-of-memory" page.
1569 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
1570 rsp = cgi_error_memory();
1572 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1573 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1575 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1580 hdrlen = strlen(hdr);
1582 if (write_socket(csp->cfd, hdr, hdrlen)
1583 || ((flushed = flush_socket(csp->cfd, csp)) < 0)
1584 || (write_socket(csp->cfd, buf, (size_t) len)))
1586 log_error(LOG_LEVEL_CONNECT, "Flush header and buffers to client failed: %E");
1592 byte_count += hdrlen + flushed + len;
1594 content_filter = NULL;
1601 if (write_socket(csp->cfd, buf, (size_t)len))
1603 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1612 /* we're still looking for the end of the
1613 * server's header ... (does that make header
1614 * parsing an "out of body experience" ?
1618 * buffer up the data we just read. If that fails,
1619 * there's little we can do but send our static
1620 * out-of-memory page.
1622 if (add_to_iob(csp, buf, len))
1624 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
1625 rsp = cgi_error_memory();
1627 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1628 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1630 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1635 /* get header lines from the iob */
1637 while ((p = get_header(csp)) != NULL)
1641 /* see following note */
1644 enlist(csp->headers, p);
1648 /* NOTE: there are no "empty" headers so
1649 * if the pointer `p' is not NULL we must
1650 * assume that we reached the end of the
1651 * buffer before we hit the end of the header.
1658 /* Well, we tried our MS IIS/5
1659 * hack and it didn't work.
1660 * The header is incomplete
1661 * and there isn't anything
1662 * we can do about it.
1668 /* Since we have to wait for
1669 * more from the server before
1670 * we can parse the headers
1671 * we just continue here.
1677 /* we have now received the entire header.
1678 * filter it and send the result to the client
1681 hdr = sed(server_patterns, add_server_headers, csp);
1684 /* FIXME Should handle error properly */
1685 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1688 #ifdef FEATURE_KILL_POPUPS
1689 /* Start blocking popups if appropriate. */
1691 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1692 !http->ssl && /* We talk plaintext */
1693 block_popups) /* Policy allows */
1695 block_popups_now = 1;
1697 * Filter the part of the body that came in the same read
1698 * as the last headers:
1700 filter_popups(csp->iob->cur, csp);
1703 #endif /* def FEATURE_KILL_POPUPS */
1705 /* Buffer and pcrs filter this if appropriate. */
1707 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1708 !http->ssl && /* We talk plaintext */
1709 pcrs_filter) /* Policy allows */
1711 content_filter = pcrs_filter_response;
1714 /* Buffer and gif_deanimate this if appropriate. */
1716 if ((csp->content_type & CT_GIF) && /* It's an image/gif MIME-Type */
1717 !http->ssl && /* We talk plaintext */
1718 gif_deanimate) /* Policy allows */
1720 content_filter = gif_deanimate_response;
1723 /* Buffer and jpg_inspect this if appropriate. */
1725 if ((csp->content_type & CT_JPEG) && /* It's an image/jpeg MIME-Type */
1726 !http->ssl && /* We talk plaintext */
1727 jpeg_inspect) /* Policy allows */
1729 content_filter = jpeg_inspect_response;
1733 * Only write if we're not buffering for content modification
1735 if (!content_filter)
1737 /* write the server's (modified) header to
1738 * the client (along with anything else that
1739 * may be in the buffer)
1742 if (write_socket(csp->cfd, hdr, strlen(hdr))
1743 || ((len = flush_socket(csp->cfd, csp)) < 0))
1745 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1747 /* the write failed, so don't bother
1748 * mentioning it to the client...
1749 * it probably can't hear us anyway.
1758 /* we're finished with the server's header */
1763 /* If this was a MS IIS/5 hack then it means
1764 * the server has already closed the
1765 * connection. Nothing more to read. Time
1776 return; /* huh? we should never get here */
1779 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1780 csp->ip_addr_str, http->ocmd, byte_count);
1784 /*********************************************************************
1788 * Description : This is little more than chat. We only "serve" to
1789 * to close any socket that chat may have opened.
1792 * 1 : csp = Current client state (buffers, headers, etc...)
1796 *********************************************************************/
1798 void serve(struct client_state *csp)
1799 #else /* ifndef AMIGA */
1800 static void serve(struct client_state *csp)
1801 #endif /* def AMIGA */
1804 close_socket(csp->cfd);
1806 if (csp->sfd != JB_INVALID_SOCKET)
1808 close_socket(csp->sfd);
1811 csp->flags &= ~CSP_FLAG_ACTIVE;
1817 /*********************************************************************
1819 * Function : server_thread
1821 * Description : We only exist to call `serve' in a threaded environment.
1824 * 1 : data = Current client state (buffers, headers, etc...)
1826 * Returns : Always 0.
1828 *********************************************************************/
1829 static int32 server_thread(void *data)
1831 serve((struct client_state *) data);
1838 /*********************************************************************
1842 * Description : Print usage info & exit.
1844 * Parameters : Pointer to argv[0] for identifying ourselves
1848 *********************************************************************/
1849 void usage(const char *myname)
1851 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
1853 "Usage: %s [--help] [--version] [configfile]\n"
1855 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1857 "Aborting.\n", myname);
1864 /*********************************************************************
1868 * Description : Load the config file and start the listen loop.
1869 * This function is a lot more *sane* with the `load_config'
1870 * and `listen_loop' functions; although it stills does
1871 * a *little* too much for my taste.
1874 * 1 : argc = Number of parameters (including $0).
1875 * 2 : argv = Array of (char *)'s to the parameters.
1877 * Returns : 1 if : can't open config file, unrecognized directive,
1878 * stats requested in multi-thread mode, can't open the
1879 * log file, can't open the jar file, listen port is invalid,
1880 * any load fails, and can't bind port.
1882 * Else main never returns, the process must be signaled
1883 * to terminate execution. Or, on Windows, use the
1884 * "File", "Exit" menu option.
1886 *********************************************************************/
1888 int real_main(int argc, const char *argv[])
1890 int main(int argc, const char *argv[])
1895 unsigned int random_seed;
1896 #endif /* ifdef HAVE_RANDOM */
1898 struct passwd *pw = NULL;
1899 struct group *grp = NULL;
1908 #if !defined(_WIN32)
1916 * Parse the command line arguments
1918 while (++argc_pos < argc)
1921 /* Check to see if the service must be installed or uninstalled */
1922 if (strncmp(argv[argc_pos], "--install", 9) == 0)
1924 const char *pName = argv[argc_pos] + 9;
1927 exit( (install_service(pName)) ? 0 : 1 );
1929 else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
1931 const char *pName = argv[argc_pos] + 11;
1934 exit((uninstall_service(pName)) ? 0 : 1);
1936 else if (strcmp(argv[argc_pos], "--service" ) == 0)
1938 bRunAsService = TRUE;
1939 w32_set_service_cwd();
1940 atexit(w32_service_exit_notify);
1943 #endif /* defined(_WIN32) */
1946 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1948 if (strcmp(argv[argc_pos], "--help") == 0)
1953 else if(strcmp(argv[argc_pos], "--version") == 0)
1955 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1961 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1966 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1968 if (++argc_pos == argc) usage(argv[0]);
1969 pidfile = strdup(argv[argc_pos]);
1972 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1974 if (++argc_pos == argc) usage(argv[argc_pos]);
1976 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1979 if (NULL == (grp = getgrnam(p)))
1981 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1985 if (NULL == (pw = getpwnam(argv[argc_pos])))
1987 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1990 if (p != NULL) *--p = '\0';
1993 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
1998 #endif /* defined(unix) */
1999 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
2001 configfile = argv[argc_pos];
2004 } /* -END- while (more arguments) */
2007 if ( *configfile != '/' )
2009 char *abs_file, cwd[1024];
2011 /* make config-filename absolute here */
2012 if ( !(getcwd(cwd, sizeof(cwd))))
2014 perror("get working dir failed");
2018 if (!(basedir = strdup(cwd))
2019 || (!(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 ))))
2021 perror("malloc failed");
2024 strcpy( abs_file, basedir );
2025 strcat( abs_file, "/" );
2026 strcat( abs_file, configfile );
2027 configfile = abs_file;
2029 #endif /* defined unix */
2033 clients->next = NULL;
2037 #elif defined(_WIN32)
2041 #if defined(OSX_DARWIN) || defined(__OpenBSD__)
2043 * Prepare global mutex semaphores
2046 pthread_mutex_init(&gmtime_mutex,0);
2047 pthread_mutex_init(&localtime_mutex,0);
2048 #endif /* def OSX_DARWIN */
2049 pthread_mutex_init(&gethostbyaddr_mutex,0);
2050 pthread_mutex_init(&gethostbyname_mutex,0);
2051 #endif /* defined(OSX_DARWIN) || defined(__OpenBSD__) */
2053 #ifdef FEATURE_PTHREAD
2054 pthread_mutex_init(&log_mutex,0);
2055 pthread_mutex_init(&log_init_mutex,0);
2056 #endif /* FEATURE_PTHREAD */
2059 random_seed = (unsigned int)time(NULL);
2060 srandom(random_seed);
2061 #endif /* ifdef HAVE_RANDOM */
2064 * Unix signal handling
2066 * Catch the abort, interrupt and terminate signals for a graceful exit
2067 * Catch the hangup signal so the errlog can be reopened.
2068 * Ignore the broken pipe signals (FIXME: Why?)
2070 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
2073 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
2074 const int ignored_signals[] = { SIGPIPE, 0 };
2076 for (idx = 0; catched_signals[idx] != 0; idx++)
2078 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
2080 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
2084 for (idx = 0; ignored_signals[idx] != 0; idx++)
2086 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
2088 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
2093 #else /* ifdef _WIN32 */
2094 # ifdef _WIN_CONSOLE
2096 * We *are* in a windows console app.
2097 * Print a verbose messages about FAQ's and such
2099 printf(win32_blurb);
2100 # endif /* def _WIN_CONSOLE */
2101 #endif /* def _WIN32 */
2104 /* Initialize the CGI subsystem */
2105 cgi_init_error_messages();
2108 * If runnig on unix and without the --nodaemon
2109 * option, become a daemon. I.e. fork, detach
2110 * from tty and get process group leadership
2123 if ( pid < 0 ) /* error */
2128 else if ( pid != 0 ) /* parent */
2133 * must check for errors
2134 * child died due to missing files aso
2137 wpid = waitpid( pid, &status, WNOHANG );
2146 /* Should be more portable, but not as well tested */
2151 #else /* ndef __FreeBSD__ */
2153 #endif /* ndef __FreeBSD__ */
2154 fd = open("/dev/tty", O_RDONLY);
2157 /* no error check here */
2158 ioctl( fd, TIOCNOTTY,0 );
2162 /* FIXME: should close stderr (fd 2) here too, but the test
2164 * and load config file is done in listen_loop() and puts
2165 * some messages on stderr there.
2172 } /* -END- if (!no_daemon) */
2175 * As soon as we have written the PID file, we can switch
2176 * to the user and group ID indicated by the --user option
2182 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
2184 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
2190 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
2192 if (chroot(pw->pw_dir) < 0)
2194 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
2198 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
2201 if (setuid(pw->pw_uid))
2203 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
2207 char putenv_dummy[64];
2209 strcpy(putenv_dummy, "HOME=/");
2210 if (putenv(putenv_dummy) != 0)
2212 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
2215 snprintf(putenv_dummy, 64, "USER=%s", pw->pw_name);
2216 if (putenv(putenv_dummy) != 0)
2218 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
2224 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
2227 #endif /* defined unix */
2230 /* This will be FALSE unless the command line specified --service
2234 /* Yup, so now we must attempt to establish a connection
2235 * with the service dispatcher. This will only work if this
2236 * process was launched by the service control manager to
2237 * actually run as a service. If this isn't the case, i've
2238 * known it take around 30 seconds or so for the call to return.
2241 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
2242 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
2244 /* Service has run, and at this point is now being stopped, so just return */
2249 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
2251 /* An error occurred. Usually it's because --service was wrongly specified
2252 * and we were unable to connect to the Service Control Dispatcher because
2253 * it wasn't expecting us and is therefore not listening.
2255 * For now, just continue below to call the listen_loop function.
2258 #endif /* def _WIN32 */
2268 /*********************************************************************
2270 * Function : bind_port_helper
2272 * Description : Bind the listen port. Handles logging, and aborts
2276 * 1 : config = Privoxy configuration. Specifies port
2279 * Returns : Port that was opened.
2281 *********************************************************************/
2282 static jb_socket bind_port_helper(struct configuration_spec * config)
2287 if ( (config->haddr != NULL)
2288 && (config->haddr[0] == '1')
2289 && (config->haddr[1] == '2')
2290 && (config->haddr[2] == '7')
2291 && (config->haddr[3] == '.') )
2293 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
2296 else if (config->haddr == NULL)
2298 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
2303 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
2304 config->hport, config->haddr);
2307 result = bind_port(config->haddr, config->hport, &bfd);
2314 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2315 "There may be another Privoxy or some other "
2316 "proxy running on port %d",
2317 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
2318 config->hport, config->hport);
2321 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2322 "The hostname is not resolvable",
2323 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2326 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
2327 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2330 /* shouldn't get here */
2331 return JB_INVALID_SOCKET;
2334 config->need_bind = 0;
2341 /* Without this simple workaround we get this compiler warning from _beginthread
2342 * warning C4028: formal parameter 1 different from declaration
2344 void w32_service_listen_loop(void *p)
2348 #endif /* def _WIN32 */
2351 /*********************************************************************
2353 * Function : listen_loop
2355 * Description : bind the listen port and enter a "FOREVER" listening loop.
2361 *********************************************************************/
2362 static void listen_loop(void)
2364 struct client_state *csp = NULL;
2366 struct configuration_spec * config;
2368 config = load_config();
2370 bfd = bind_port_helper(config);
2372 #ifdef FEATURE_GRACEFUL_TERMINATION
2373 while (!g_terminate)
2378 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
2379 while (waitpid(-1, NULL, WNOHANG) > 0)
2381 /* zombie children */
2383 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2386 * Free data that was used by died threads
2392 * Re-open the errlog after HUP signal
2394 if (received_hup_signal)
2396 init_error_log(Argv[0], config->logfile, config->debug);
2397 received_hup_signal = 0;
2402 #ifdef FEATURE_COOKIE_JAR
2404 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
2405 * already open. I think unload_configfile() is not being run, which should do
2406 * this work. Until that can get resolved, we'll use this workaround.
2410 if (csp->config->jar)
2412 fclose(csp->config->jar);
2413 csp->config->jar = NULL;
2415 #endif /* FEATURE_COOKIE_JAR */
2416 #endif /* __OS2__ */
2418 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2420 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2424 csp->flags |= CSP_FLAG_ACTIVE;
2425 csp->sfd = JB_INVALID_SOCKET;
2427 csp->config = config = load_config();
2429 if ( config->need_bind )
2432 * Since we were listening to the "old port", we will not see
2433 * a "listen" param change until the next IJB request. So, at
2434 * least 1 more request must be made for us to find the new
2435 * setting. I am simply closing the old socket and binding the
2438 * Which-ever is correct, we will serve 1 more page via the
2439 * old settings. This should probably be a "show-proxy-args"
2440 * request. This should not be a so common of an operation
2441 * that this will hurt people's feelings.
2446 bfd = bind_port_helper(config);
2449 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2451 if (!accept_connection(csp, bfd))
2453 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2466 log_error(LOG_LEVEL_CONNECT, "OK");
2469 #ifdef FEATURE_TOGGLE
2470 if (global_toggle_state)
2472 csp->flags |= CSP_FLAG_TOGGLED_ON;
2474 #endif /* def FEATURE_TOGGLE */
2476 if (run_loader(csp))
2478 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2479 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2483 if (block_acl(NULL,csp))
2485 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2486 close_socket(csp->cfd);
2490 #endif /* def FEATURE_ACL */
2492 /* add it to the list of clients */
2493 csp->next = clients->next;
2494 clients->next = csp;
2496 if (config->multi_threaded)
2500 /* this is a switch () statment in the C preprocessor - ugh */
2501 #undef SELECTED_ONE_OPTION
2503 /* Use Pthreads in preference to native code */
2504 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2505 #define SELECTED_ONE_OPTION
2507 pthread_t the_thread;
2508 pthread_attr_t attrs;
2510 pthread_attr_init(&attrs);
2511 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2512 errno = pthread_create(&the_thread, &attrs,
2514 child_id = errno ? -1 : 0;
2515 pthread_attr_destroy(&attrs);
2519 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2520 #define SELECTED_ONE_OPTION
2521 child_id = _beginthread(
2522 (void (*)(void *))serve,
2527 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2528 #define SELECTED_ONE_OPTION
2529 child_id = _beginthread(
2530 (void(* _Optlink)(void*))serve,
2536 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2537 #define SELECTED_ONE_OPTION
2539 thread_id tid = spawn_thread
2540 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2542 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2544 child_id = (int) tid;
2553 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2554 #define SELECTED_ONE_OPTION
2555 csp->cfd = ReleaseSocket(csp->cfd, -1);
2557 if((child_id = (int)CreateNewProcTags(
2558 NP_Entry, (ULONG)server_thread,
2559 NP_Output, Output(),
2560 NP_CloseOutput, FALSE,
2561 NP_Name, (ULONG)"privoxy child",
2562 NP_StackSize, 200*1024,
2566 ((struct Task *)child_id)->tc_UserData = csp;
2567 Signal((struct Task *)child_id, SIGF_SINGLE);
2572 #if !defined(SELECTED_ONE_OPTION)
2575 /* This block is only needed when using fork().
2576 * When using threads, the server thread was
2577 * created and run by the call to _beginthread().
2579 if (child_id == 0) /* child */
2582 #ifdef FEATURE_TOGGLE
2583 int inherited_toggle_state = global_toggle_state;
2584 #endif /* def FEATURE_TOGGLE */
2589 * If we've been toggled or we've blocked the request, tell Mom
2592 #ifdef FEATURE_TOGGLE
2593 if (inherited_toggle_state != global_toggle_state)
2595 rc |= RC_FLAG_TOGGLED;
2597 #endif /* def FEATURE_TOGGLE */
2599 #ifdef FEATURE_STATISTICS
2600 if (csp->flags & CSP_FLAG_REJECTED)
2602 rc |= RC_FLAG_BLOCKED;
2604 #endif /* ndef FEATURE_STATISTICS */
2608 else if (child_id > 0) /* parent */
2610 /* in a fork()'d environment, the parent's
2611 * copy of the client socket and the CSP
2615 #if !defined(_WIN32) && !defined(__CYGWIN__)
2617 wait( &child_status );
2620 * Evaluate child's return code: If the child has
2621 * - been toggled, toggle ourselves
2622 * - blocked its request, bump up the stats counter
2625 #ifdef FEATURE_TOGGLE
2626 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
2628 global_toggle_state = !global_toggle_state;
2630 #endif /* def FEATURE_TOGGLE */
2632 #ifdef FEATURE_STATISTICS
2634 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
2638 #endif /* def FEATURE_STATISTICS */
2640 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2641 close_socket(csp->cfd);
2642 csp->flags &= ~CSP_FLAG_ACTIVE;
2646 #undef SELECTED_ONE_OPTION
2647 /* end of cpp switch () */
2649 if (child_id < 0) /* failed */
2651 char buf[BUFFER_SIZE];
2653 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2655 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
2657 write_socket(csp->cfd, buf, strlen(buf));
2658 close_socket(csp->cfd);
2659 csp->flags &= ~CSP_FLAG_ACTIVE;
2670 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2672 /* Clean up. Aim: free all memory (no leaks) */
2673 #ifdef FEATURE_GRACEFUL_TERMINATION
2675 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2677 unload_current_config_file();
2678 unload_current_actions_file();
2679 unload_current_re_filterfile();
2680 #ifdef FEATURE_TRUST
2681 unload_current_trust_file();
2684 if (config->multi_threaded)
2691 } while ((clients->next != NULL) && (--i > 0));
2695 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2706 #ifdef FEATURE_COOKIE_JAR
2707 if (NULL != config->jar)
2709 fclose(config->jar);
2713 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2714 /* Cleanup - remove taskbar icon etc. */
2719 #endif /* FEATURE_GRACEFUL_TERMINATION */