1 const char jcc_rcs[] = "$Id: jcc.c,v 1.107 2006/11/13 19:05:51 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.107 2006/11/13 19:05:51 fabiankeil
37 * Make pthread mutex locking more generic. Instead of
38 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
39 * and use mutex locking unless there is an _r function
40 * available. Better safe than sorry.
42 * Fixes "./configure --disable-pthread" and should result
43 * in less threading-related problems on pthread-using platforms,
44 * but it still doesn't fix BR#1122404.
46 * Revision 1.106 2006/11/06 19:58:23 fabiankeil
47 * Move pthread.h inclusion from jcc.c to jcc.h.
48 * Fixes build on x86-freebsd1 (FreeBSD 5.4-RELEASE).
50 * Revision 1.105 2006/11/06 14:26:02 fabiankeil
51 * Don't exit after receiving the second SIGHUP on Solaris.
53 * Fixes BR 1052235, but the same problem may exist on other
54 * systems. Once 3.0.6 is out we should use sigset()
55 * where available and see if it breaks anything.
57 * Revision 1.104 2006/09/23 13:26:38 roro
58 * Replace TABs by spaces in source code.
60 * Revision 1.103 2006/09/21 12:54:43 fabiankeil
61 * Fix +redirect{}. Didn't work with -fast-redirects.
63 * Revision 1.102 2006/09/06 13:03:04 fabiankeil
64 * Respond with 400 and a short text message
65 * if the client tries to use Privoxy as FTP proxy.
67 * Revision 1.101 2006/09/06 09:23:37 fabiankeil
68 * Make number of retries in case of forwarded-connect problems
69 * a config file option (forwarded-connect-retries) and use 0 as
72 * Revision 1.100 2006/09/03 19:42:59 fabiankeil
75 * Revision 1.99 2006/09/02 15:36:42 fabiankeil
76 * Follow the OpenBSD port's lead and protect the resolve
77 * functions on OpenBSD as well.
79 * Revision 1.98 2006/08/24 11:01:34 fabiankeil
80 * --user fix. Only use the user as group if no group is specified.
81 * Solves BR 1492612. Thanks to Spinor S. and David Laight.
83 * Revision 1.97 2006/08/18 15:23:17 david__schmidt
84 * Windows service (re-)integration
88 * --install[:service_name]
89 * --uninstall[:service_name]
92 * They work as follows:
93 * --install will create a service for you and then terminate.
94 * By default the service name will be "privoxy" (without the quotes).
95 * However you can run multiple services if you wish, just by adding
96 * a colon and then a name (no spaces).
98 * --uninstall follows the exact same rules a --install.
100 * --service is used when the program is executed by the service
101 * control manager, and in normal circumstances would never be
102 * used as a command line argument.
104 * Revision 1.96 2006/08/15 20:12:36 david__schmidt
105 * Windows service integration
107 * Revision 1.95 2006/08/03 02:46:41 david__schmidt
108 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
110 * Revision 1.94 2006/07/18 14:48:46 david__schmidt
111 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
112 * with what was really the latest development (the v_3_0_branch branch)
114 * Revision 1.92.2.16 2005/04/03 20:10:50 david__schmidt
115 * Thanks to Jindrich Makovicka for a race condition fix for the log
116 * file. The race condition remains for non-pthread implementations.
117 * Reference patch #1175720.
119 * Revision 1.92.2.15 2004/10/03 12:53:32 david__schmidt
120 * Add the ability to check jpeg images for invalid
121 * lengths of comment blocks. Defensive strategy
122 * against the exploit:
123 * Microsoft Security Bulletin MS04-028
124 * Buffer Overrun in JPEG Processing (GDI+) Could
125 * Allow Code Execution (833987)
126 * Enabled with +inspect-jpegs in actions files.
128 * Revision 1.92.2.14 2003/12/12 12:52:53 oes
129 * - Fixed usage info for non-unix platforms
130 * - Fixed small cmdline parsing bug
132 * Revision 1.92.2.13 2003/11/27 19:20:27 oes
133 * Diagnostics: Now preserve the returncode of pthread_create
134 * in errno. Closes BR #775721. Thanks to Geoffrey Hausheer.
136 * Revision 1.92.2.12 2003/07/11 11:34:19 oes
137 * No longer ignore SIGCHLD. Fixes bug #769381
139 * Revision 1.92.2.11 2003/05/14 12:32:02 oes
140 * Close jarfile on graceful exit, remove stray line
142 * Revision 1.92.2.10 2003/05/08 15:13:46 oes
143 * Cosmetics: Killed a warning, a typo and an allocation left at exit
145 * Revision 1.92.2.9 2003/04/03 15:08:42 oes
146 * No longer rely on non-POSIX.1 extensions of getcwd().
149 * Revision 1.92.2.8 2003/03/31 13:12:32 oes
150 * Replaced setenv() by posix-compliant putenv()
151 * Thanks to Neil McCalden (nmcc AT users.sf.net).
153 * Revision 1.92.2.7 2003/03/17 16:48:59 oes
154 * Added chroot ability, thanks to patch by Sviatoslav Sviridov
156 * Revision 1.92.2.6 2003/03/11 11:55:00 oes
157 * Clean-up and extension of improvements for forked mode:
158 * - Child's return code now consists of flags RC_FLAG_*
159 * - Reporting toggle to parent now properly #ifdef'ed
160 * - Children now report blocking to parent. This enables
161 * statistics in forked mode
163 * Revision 1.92.2.5 2003/03/10 23:45:32 oes
164 * Fixed bug #700381: Non-Threaded version now capable of being toggled.
165 * Children now report having been toggled through _exit(17), parents
166 * watch for that code and toggle themselves if found.
168 * Revision 1.92.2.4 2003/03/07 03:41:04 david__schmidt
169 * Wrapping all *_r functions (the non-_r versions of them) with
170 * mutex semaphores for OSX. Hopefully this will take care of all
171 * of those pesky crash reports.
173 * Revision 1.92.2.3 2003/02/28 12:53:06 oes
174 * Fixed two mostly harmless mem leaks
176 * Revision 1.92.2.2 2002/11/20 14:37:47 oes
177 * Fix: Head of global clients list now initialized to NULL
179 * Revision 1.92.2.1 2002/09/25 14:52:24 oes
180 * Added basic support for OPTIONS and TRACE HTTP methods:
181 * - New interceptor direct_response() added in chat().
182 * - sed() moved to earlier in the process, so that the
183 * Host: header is evaluated before actions and forwarding
186 * Revision 1.92 2002/05/08 16:00:46 oes
187 * Chat's buffer handling:
188 * - Fixed bug with unchecked out-of-mem conditions
189 * while reading client request & server headers
190 * - No longer predict if the buffer limit will be exceeded
191 * in the next read -- check add_to_iob's new
192 * return code. If buffer couldn't be extended
193 * (policy or out-of-mem) while
194 * - reading from client: abort
195 * - reading server headers: send error page
196 * - buffering server body for filter: flush,
197 * and if that fails: send error page
199 * Revision 1.91 2002/04/08 20:35:58 swa
202 * Revision 1.90 2002/04/02 14:57:28 oes
203 * Made sending wafers independent of FEATURE_COOKIE_JAR
205 * Revision 1.89 2002/03/31 17:18:59 jongfoster
206 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
208 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
209 * More compiler warning message maintenance
211 * Revision 1.87 2002/03/26 22:29:54 swa
212 * we have a new homepage!
214 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
215 * Workaround for closing the jarfile before load_config() comes around again
217 * Revision 1.85 2002/03/24 15:23:33 jongfoster
220 * Revision 1.84 2002/03/24 13:25:43 swa
221 * name change related issues
223 * Revision 1.83 2002/03/16 23:54:06 jongfoster
224 * Adding graceful termination feature, to help look for memory leaks.
225 * If you enable this (which, by design, has to be done by hand
226 * editing config.h) and then go to http://i.j.b/die, then the program
227 * will exit cleanly after the *next* request. It should free all the
228 * memory that was used.
230 * Revision 1.82 2002/03/13 00:27:05 jongfoster
233 * Revision 1.81 2002/03/12 01:42:50 oes
234 * Introduced modular filters
236 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
237 * OS/2 port maintenance:
238 * - Fixed EMX build - it had decayed a little
239 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
240 * substituted a memset for now.
242 * Revision 1.79 2002/03/09 20:03:52 jongfoster
243 * - Making various functions return int rather than size_t.
244 * (Undoing a recent change). Since size_t is unsigned on
245 * Windows, functions like read_socket that return -1 on
246 * error cannot return a size_t.
248 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
249 * crashes, and also frequently caused JB to jump to 100%
250 * CPU and stay there. (Because it thought it had just
251 * read ((unsigned)-1) == 4Gb of data...)
253 * - The signature of write_socket has changed, it now simply
254 * returns success=0/failure=nonzero.
256 * - Trying to get rid of a few warnings --with-debug on
257 * Windows, I've introduced a new type "jb_socket". This is
258 * used for the socket file descriptors. On Windows, this
259 * is SOCKET (a typedef for unsigned). Everywhere else, it's
260 * an int. The error value can't be -1 any more, so it's
261 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
262 * Windows it maps to the #define INVALID_SOCKET.)
264 * - The signature of bind_port has changed.
266 * Revision 1.78 2002/03/08 21:35:04 oes
267 * Added optional group supplement to --user option. Will now use default group of user if no group given
269 * Revision 1.77 2002/03/07 03:52:06 oes
270 * - Fixed compiler warnings etc
271 * - Improved handling of failed DNS lookups
273 * Revision 1.76 2002/03/06 22:54:35 jongfoster
274 * Automated function-comment nitpicking.
276 * Revision 1.75 2002/03/06 10:02:19 oes
277 * Fixed stupid bug when --user was not given
279 * Revision 1.74 2002/03/06 00:49:31 jongfoster
280 * Fixing warning on Windows
281 * Making #ifdefs that refer to the same variable consistently
282 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
284 * Revision 1.73 2002/03/05 23:57:30 hal9
285 * Stray character 's' on line 1618 was breaking build.
287 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
288 * - Re-enable OS/2 building after new parms were added
289 * - Fix false out of memory report when resolving CGI templates when no IP
290 * address is available of failed attempt (a la no such domain)
292 * Revision 1.71 2002/03/05 18:13:56 oes
293 * Added --user option
295 * Revision 1.70 2002/03/05 04:52:42 oes
296 * Deleted non-errlog debugging code
298 * Revision 1.69 2002/03/04 23:50:00 jongfoster
299 * Splitting off bind_port() call into bind_port_helper(), with
302 * Revision 1.68 2002/03/04 20:17:32 oes
305 * Revision 1.67 2002/03/04 18:18:57 oes
306 * - Removed _DEBUG mode
307 * - Cleand up cmdline parsing
308 * - Introduced --no-daemon, --pidfile options
309 * - Cleaned up signal handling:
310 * - Terminate cleanly on INT, TERM and ABRT
311 * - Schedule logfile for re-opening on HUP
312 * - Ignore CHLD and PIPE
313 * - Leave the rest with their default handlers
314 * - Uniform handler registration
315 * - Added usage() function
316 * - Played styleguide police
318 * Revision 1.66 2002/03/03 15:06:55 oes
319 * Re-enabled automatic config reloading
321 * Revision 1.65 2002/03/03 14:49:11 oes
322 * Fixed CLF logging: Now uses client's original HTTP request
324 * Revision 1.64 2002/03/03 09:18:03 joergs
325 * Made jumbjuster work on AmigaOS again.
327 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
328 * Clean up a little CRLF unpleasantness that suddenly appeared
330 * Revision 1.62 2002/02/20 23:17:23 jongfoster
331 * Detecting some out-of memory conditions and exiting with a log message.
333 * Revision 1.61 2002/01/17 21:01:52 jongfoster
334 * Moving all our URL and URL pattern parsing code to urlmatch.c.
336 * Revision 1.60 2001/12/30 14:07:32 steudten
337 * - Add signal handling (unix)
338 * - Add SIGHUP handler (unix)
339 * - Add creation of pidfile (unix)
340 * - Add action 'top' in rc file (RH)
341 * - Add entry 'SIGNALS' to manpage
342 * - Add exit message to logfile (unix)
344 * Revision 1.59 2001/12/13 14:07:18 oes
345 * Fixed Bug: 503 error page now sent OK
347 * Revision 1.58 2001/11/30 23:37:24 jongfoster
348 * Renaming the Win32 config file to config.txt - this is almost the
349 * same as the corresponding UNIX name "config"
351 * Revision 1.57 2001/11/16 00:47:43 jongfoster
352 * Changing the tty-disconnection code to use setsid().
354 * Revision 1.56 2001/11/13 20:20:54 jongfoster
355 * Tabs->spaces, fixing a bug with missing {} around an if()
357 * Revision 1.55 2001/11/13 20:14:53 jongfoster
358 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
360 * Revision 1.54 2001/11/07 00:03:14 steudten
361 * Give reliable return value if an error
362 * occurs not just 0 with new daemon mode.
364 * Revision 1.53 2001/11/05 21:41:43 steudten
365 * Add changes to be a real daemon just for unix os.
366 * (change cwd to /, detach from controlling tty, set
367 * process group and session leader to the own process.
369 * Add some fatal-error log message for failed malloc().
370 * Add '-d' if compiled with 'configure --with-debug' to
371 * enable debug output.
373 * Revision 1.52 2001/10/26 20:11:20 jongfoster
374 * Fixing type mismatch
376 * Revision 1.51 2001/10/26 17:38:28 oes
379 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
380 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
381 * threads to call select() simultaneously. So, it's time to do a real, live,
382 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
383 * (native). Both versions will work, but using __OS2__ offers multi-threading.
385 * Revision 1.49 2001/10/23 21:41:35 jongfoster
386 * Added call to initialize the (statically-allocated of course)
387 * "out of memory" CGI response.
389 * Revision 1.48 2001/10/10 19:56:46 jongfoster
390 * Moving some code that wasn't cookie-related out of an #ifdef
393 * Revision 1.47 2001/10/10 16:44:36 oes
394 * Added CONNECT destination port limitation check
396 * Revision 1.46 2001/10/08 15:17:41 oes
397 * Re-enabled SSL forwarding
399 * Revision 1.45 2001/10/07 15:42:11 oes
400 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
402 * Moved downgrading of the HTTP version from parse_http_request to
403 * chat(), since we can't decide if it is necessary before we have
404 * determined the actions for the URL. The HTTP command is now
405 * *always* re-built so the repairs need no longer be special-cased.
407 * filter_popups now gets a csp pointer so it can raise the new
408 * CSP_FLAG_MODIFIED flag.
412 * Added configurable size limit for the IOB. If the IOB grows so
413 * large that the next read would exceed the limit, the header
414 * is generated, and the header & unfiltered buffer are flushed
415 * to the client. Chat then continues in non-buffering,
416 * non-filtering body mode.
418 * Revision 1.44 2001/10/02 18:13:57 oes
421 * Revision 1.43 2001/10/02 15:32:13 oes
422 * Moved generation of hdr
424 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
425 * Cleaning up 2 compiler warnings on OS/2.
427 * Revision 1.41 2001/09/16 17:05:14 jongfoster
428 * Removing unused #include showarg.h
430 * Revision 1.40 2001/09/16 15:41:45 jongfoster
431 * Fixing signed/unsigned comparison warning.
433 * Revision 1.39 2001/09/16 13:21:27 jongfoster
434 * Changes to use new list functions.
436 * Revision 1.38 2001/09/16 13:01:46 jongfoster
437 * Removing redundant function call that zeroed zalloc()'d memory.
439 * Revision 1.37 2001/09/10 11:12:24 oes
440 * Deleted unused variable
442 * Revision 1.36 2001/09/10 10:56:15 oes
443 * Silenced compiler warnings
445 * Revision 1.35 2001/07/31 14:44:22 oes
446 * Deleted unused size parameter from filter_popups()
448 * Revision 1.34 2001/07/30 22:08:36 jongfoster
449 * Tidying up #defines:
450 * - All feature #defines are now of the form FEATURE_xxx
451 * - Permanently turned off WIN_GUI_EDIT
452 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
454 * Revision 1.33 2001/07/29 19:32:00 jongfoster
455 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
457 * Revision 1.32 2001/07/29 18:47:05 jongfoster
458 * Adding missing #include "loadcfg.h"
460 * Revision 1.31 2001/07/29 12:17:48 oes
461 * Applied pthread fix by Paul Lieverse
463 * Revision 1.30 2001/07/25 22:57:13 jongfoster
464 * __BEOS__ no longer overrides FEATURE_PTHREAD.
465 * This is because FEATURE_PTHREAD will soon be widely used, so I
466 * want to keep it simple.
468 * Revision 1.29 2001/07/24 12:47:06 oes
469 * Applied BeOS support update by Eugenia
471 * Revision 1.28 2001/07/23 13:26:12 oes
472 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
474 * Revision 1.27 2001/07/19 19:09:47 haroon
475 * - Added code to take care of the situation where while processing the first
476 * server response (which includes the server header), after finding the end
477 * of the headers we were not looking past the end of the headers for
478 * content modification. I enabled it for filter_popups.
479 * Someone else should look to see if other similar operations should be
480 * done to the discarded portion of the buffer.
482 * Note 2001/07/20: No, the other content modification mechanisms will process
483 * the whole iob later anyway. --oes
485 * Revision 1.26 2001/07/18 12:31:36 oes
488 * Revision 1.25 2001/07/15 19:43:49 jongfoster
489 * Supports POSIX threads.
490 * Also removed some unused #includes.
492 * Revision 1.24 2001/07/13 14:00:40 oes
493 * - Generic content modification scheme:
494 * Each feature has its own applicability flag that is set
495 * from csp->action->flags.
496 * Replaced the "filtering" int flag , by a function pointer
497 * "content_filter" to the function that will do the content
498 * modification. If it is != NULL, the document will be buffered
499 * and processed through *content_filter, which must set
500 * csp->content_length and return a modified copy of the body
501 * or return NULL (on failiure).
502 * - Changed csp->is_text to the more generic bitmap csp->content_type
503 * which can currently take the valued CT_TEXT or CT_GIF
505 * - Removed all #ifdef PCRS
507 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
508 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
509 * the `block_acl' call. This prevents a compilation error when the user
510 * does not wish to use the "ACL" feature.
512 * Revision 1.22 2001/06/29 21:45:41 oes
513 * Indentation, CRLF->LF, Tab-> Space
515 * Revision 1.21 2001/06/29 13:29:36 oes
516 * - Cleaned up, improved comments
517 * - Unified all possible interceptors (CGI,
518 * block, trust, fast_redirect) in one
519 * place, with one (CGI) answer generation
520 * mechansim. Much clearer now.
521 * - Removed the GIF image generation, which
522 * is now done in filters.c:block_url()
523 * - Made error conditions like domain lookup
524 * failiure or (various) problems while talking
525 * to the server use cgi.c:error_response()
526 * instead of generating HTML/HTTP in chat() (yuck!)
527 * - Removed logentry from cancelled commit
529 * Revision 1.20 2001/06/09 10:55:28 jongfoster
530 * Changing BUFSIZ ==> BUFFER_SIZE
532 * Revision 1.19 2001/06/07 23:12:52 jongfoster
533 * Replacing function pointer in struct gateway with a directly
534 * called function forwarded_connect().
535 * Replacing struct gateway with struct forward_spec
537 * Revision 1.18 2001/06/03 19:12:16 oes
538 * introduced new cgi handling
540 * Revision 1.17 2001/06/01 20:07:23 jongfoster
541 * Now uses action +image-blocker{} rather than config->tinygif
543 * Revision 1.16 2001/06/01 18:49:17 jongfoster
544 * Replaced "list_share" with "list" - the tiny memory gain was not
545 * worth the extra complexity.
547 * Revision 1.15 2001/05/31 21:24:47 jongfoster
548 * Changed "permission" to "action" throughout.
549 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
550 * Moved vanilla wafer check into chat(), since we must now
551 * decide whether or not to add it based on the URL.
553 * Revision 1.14 2001/05/29 20:14:01 joergs
554 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
557 * Revision 1.13 2001/05/29 09:50:24 jongfoster
558 * Unified blocklist/imagelist/permissionslist.
559 * File format is still under discussion, but the internal changes
562 * Also modified interceptor behaviour:
563 * - We now intercept all URLs beginning with one of the following
564 * prefixes (and *only* these prefixes):
566 * * http://ijbswa.sf.net/config/
567 * * http://ijbswa.sourceforge.net/config/
568 * - New interceptors "home page" - go to http://i.j.b/ to see it.
569 * - Internal changes so that intercepted and fast redirect pages
570 * are not replaced with an image.
571 * - Interceptors now have the option to send a binary page direct
572 * to the client. (i.e. ijb-send-banner uses this)
573 * - Implemented show-url-info interceptor. (Which is why I needed
574 * the above interceptors changes - a typical URL is
575 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
576 * The previous mechanism would not have intercepted that, and
577 * if it had been intercepted then it then it would have replaced
580 * Revision 1.12 2001/05/27 22:17:04 oes
582 * - re_process_buffer no longer writes the modified buffer
583 * to the client, which was very ugly. It now returns the
584 * buffer, which it is then written by chat.
586 * - content_length now adjusts the Content-Length: header
587 * for modified documents rather than crunch()ing it.
588 * (Length info in csp->content_length, which is 0 for
589 * unmodified documents)
591 * - For this to work, sed() is called twice when filtering.
593 * Revision 1.11 2001/05/26 17:27:53 jongfoster
594 * Added support for CLF and fixed LOG_LEVEL_LOG.
595 * Also did CRLF->LF fix of my previous patch.
597 * Revision 1.10 2001/05/26 15:26:15 jongfoster
598 * ACL feature now provides more security by immediately dropping
599 * connections from untrusted hosts.
601 * Revision 1.9 2001/05/26 00:28:36 jongfoster
602 * Automatic reloading of config file.
603 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
604 * Most of the global variables have been moved to a new
605 * struct configuration_spec, accessed through csp->config->globalname
606 * Most of the globals remaining are used by the Win32 GUI.
608 * Revision 1.8 2001/05/25 22:43:18 jongfoster
609 * Fixing minor memory leak and buffer overflow.
611 * Revision 1.7 2001/05/25 22:34:30 jongfoster
614 * Revision 1.6 2001/05/23 00:13:58 joergs
615 * AmigaOS support fixed.
617 * Revision 1.5 2001/05/22 18:46:04 oes
619 * - Enabled filtering banners by size rather than URL
620 * by adding patterns that replace all standard banner
621 * sizes with the "Junkbuster" gif to the re_filterfile
623 * - Enabled filtering WebBugs by providing a pattern
624 * which kills all 1x1 images
626 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
627 * which is selected by the (nonstandard and therefore
628 * capital) letter 'U' in the option string.
629 * It causes the quantifiers to be ungreedy by default.
630 * Appending a ? turns back to greedy (!).
632 * - Added a new interceptor ijb-send-banner, which
633 * sends back the "Junkbuster" gif. Without imagelist or
634 * MSIE detection support, or if tinygif = 1, or the
635 * URL isn't recognized as an imageurl, a lame HTML
636 * explanation is sent instead.
638 * - Added new feature, which permits blocking remote
639 * script redirects and firing back a local redirect
641 * The feature is conditionally compiled, i.e. it
642 * can be disabled with --disable-fast-redirects,
643 * plus it must be activated by a "fast-redirects"
644 * line in the config file, has its own log level
645 * and of course wants to be displayed by show-proxy-args
646 * Note: Boy, all the #ifdefs in 1001 locations and
647 * all the fumbling with configure.in and acconfig.h
648 * were *way* more work than the feature itself :-(
650 * - Because a generic redirect template was needed for
651 * this, tinygif = 3 now uses the same.
653 * - Moved GIFs, and other static HTTP response templates
658 * - Removed some >400 CRs again (Jon, you really worked
661 * Revision 1.4 2001/05/21 19:34:01 jongfoster
662 * Made failure to bind() a fatal error.
664 * Revision 1.3 2001/05/20 01:21:20 jongfoster
665 * Version 2.9.4 checkin.
666 * - Merged popupfile and cookiefile, and added control over PCRS
667 * filtering, in new "permissionsfile".
668 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
669 * file error you now get a message box (in the Win32 GUI) rather
670 * than the program exiting with no explanation.
671 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
673 * - Removed tabs from "config"
674 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
675 * - Bumped up version number.
677 * Revision 1.2 2001/05/17 22:34:44 oes
678 * - Added hint on GIF char array generation to jcc.c
679 * - Cleaned CRLF's from the sources and related files
680 * - Repaired logging for REF and FRC
682 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
683 * Initial import of version 2.9.3 source tree
686 *********************************************************************/
692 #include <sys/types.h>
700 # ifndef FEATURE_PTHREAD
704 # include <windows.h>
705 # include <process.h>
706 # endif /* ndef FEATURE_PTHREAD */
709 # ifndef _WIN_CONSOLE
711 # endif /* ndef _WIN_CONSOLE */
712 # include "w32svrapi.h"
714 #else /* ifndef _WIN32 */
716 # if !defined (__OS2__)
718 # include <sys/wait.h>
719 # endif /* ndef __OS2__ */
720 # include <sys/time.h>
721 # include <sys/stat.h>
722 # include <sys/ioctl.h>
725 #include <sys/termios.h>
736 # include <socket.h> /* BeOS has select() for sockets only. */
737 # include <OS.h> /* declarations for threads and stuff. */
740 # if defined(__EMX__) || defined(__OS2__)
741 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
746 #define bzero(B,N) memset(B,0x00,n)
761 #include "killpopup.h"
762 #include "miscutil.h"
764 #include "jbsockets.h"
769 #include "urlmatch.h"
771 const char jcc_h_rcs[] = JCC_H_VERSION;
772 const char project_h_rcs[] = PROJECT_H_VERSION;
775 struct client_state clients[1];
776 struct file_list files[1];
778 #ifdef FEATURE_STATISTICS
779 int urls_read = 0; /* total nr of urls read inc rejected */
780 int urls_rejected = 0; /* total nr of urls rejected */
781 #endif /* def FEATURE_STATISTICS */
783 #ifdef FEATURE_GRACEFUL_TERMINATION
787 static void listen_loop(void);
788 static void chat(struct client_state *csp);
790 void serve(struct client_state *csp);
791 #else /* ifndef AMIGA */
792 static void serve(struct client_state *csp);
793 #endif /* def AMIGA */
796 static int32 server_thread(void *data);
797 #endif /* def __BEOS__ */
800 #define sleep(N) Sleep(((N) * 1000))
804 #define sleep(N) DosSleep(((N) * 100))
807 #ifdef FEATURE_PTHREAD
808 pthread_mutex_t log_mutex;
809 pthread_mutex_t log_init_mutex;
811 #ifndef HAVE_GMTIME_R
812 pthread_mutex_t gmtime_mutex;
813 #endif /* ndef HAVE_GMTIME_R */
815 #ifndef HAVE_LOCALTIME_R
816 pthread_mutex_t localtime_mutex;
817 #endif /* ndef HAVE_GMTIME_R */
819 #ifndef HAVE_GETHOSTBYADDR_R
820 pthread_mutex_t gethostbyaddr_mutex;
821 #endif /* ndef HAVE_GETHOSTBYADDR_R */
823 #ifndef HAVE_GETHOSTBYNAME_R
824 pthread_mutex_t gethostbyname_mutex;
825 #endif /* ndef HAVE_GETHOSTBYNAME_R */
826 #endif /* FEATURE_PTHREAD */
828 #if defined(unix) || defined(__EMX__)
829 const char *basedir = NULL;
830 const char *pidfile = NULL;
831 int received_hup_signal = 0;
832 #endif /* defined unix */
834 /* The vanilla wafer. */
835 static const char VANILLA_WAFER[] =
836 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
837 "Do_not_send_me_any_copyrighted_information_other_than_the_"
838 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
839 "In_particular_do_not_send_me_any_cookies_that_"
840 "are_subject_to_a_claim_of_copyright_by_anybody._"
841 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
842 "(copyright_or_otherwise)_applying_to_any_cookie._";
845 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
846 /*********************************************************************
848 * Function : sig_handler
850 * Description : Signal handler for different signals.
851 * Exit gracefully on ABRT, TERM and INT
852 * or set a flag that will cause the errlog
853 * to be reopened by the main thread on HUP.
856 * 1 : the_signal = the signal cause this function to call
860 *********************************************************************/
861 static void sig_handler(int the_signal)
868 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
879 received_hup_signal = 1;
884 * We shouldn't be here, unless we catch signals
885 * in main() that we can't handle here!
887 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
895 /*********************************************************************
899 * Description : Once a connection to the client has been accepted,
900 * this function is called (via serve()) to handle the
901 * main business of the communication. When this
902 * function returns, the caller must close the client
906 * 1 : csp = Current client state (buffers, headers, etc...)
908 * Returns : On success, the number of bytes written are returned (zero
909 * indicates nothing was written). On error, -1 is returned,
910 * and errno is set appropriately. If count is zero and the
911 * file descriptor refers to a regular file, 0 will be
912 * returned without causing any other effect. For a special
913 * file, the results are not portable.
915 *********************************************************************/
916 static void chat(struct client_state *csp)
919 * This next lines are a little ugly, but they simplifies the if statements
920 * below. Basically if TOGGLE, then we want the if to test if the
921 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
922 * then we want the if to test for CSP_FLAG_FORCED , else we don't
924 #ifdef FEATURE_TOGGLE
925 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
926 #else /* ifndef FEATURE_TOGGLE */
927 # define IS_TOGGLED_ON_AND
928 #endif /* ndef FEATURE_TOGGLE */
929 #ifdef FEATURE_FORCE_LOAD
930 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
931 #else /* ifndef FEATURE_FORCE_LOAD */
932 # define IS_NOT_FORCED_AND
933 #endif /* def FEATURE_FORCE_LOAD */
935 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
937 char buf[BUFFER_SIZE];
945 int ms_iis5_hack = 0;
947 unsigned int forwarded_connect_retries = 0;
948 unsigned int max_forwarded_connect_retries = csp->config->forwarded_connect_retries;
949 const struct forward_spec * fwd;
950 struct http_request *http;
951 int len; /* for buffer sizes */
952 #ifdef FEATURE_KILL_POPUPS
953 int block_popups; /* bool, 1==will block popups */
954 int block_popups_now = 0; /* bool, 1==currently blocking popups */
955 #endif /* def FEATURE_KILL_POPUPS */
957 int pcrs_filter; /* bool, 1==will filter through pcrs */
958 int gif_deanimate; /* bool, 1==will deanimate gifs */
959 int jpeg_inspect; /* bool, 1==will inspect jpegs */
961 /* Function that does the content filtering for the current request */
962 char *(*content_filter)() = NULL;
964 /* Skeleton for HTTP response, if we should intercept the request */
965 struct http_response *rsp;
970 * Read the client's request. Note that since we're not using select() we
971 * could get blocked here if a client connected, then didn't say anything!
976 len = read_socket(csp->cfd, buf, sizeof(buf));
978 if (len <= 0) break; /* error! */
981 * If there is no memory left for buffering the
982 * request, there is nothing we can do but hang up
984 if (add_to_iob(csp, buf, len))
989 req = get_header(csp);
993 break; /* no HTTP request! */
998 continue; /* more to come! */
1001 #ifdef FEATURE_FORCE_LOAD
1002 /* If this request contains the FORCE_PREFIX,
1003 * better get rid of it now and set the force flag --oes
1006 if (strstr(req, FORCE_PREFIX))
1008 strclean(req, FORCE_PREFIX);
1009 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
1010 csp->flags |= CSP_FLAG_FORCED;
1013 #endif /* def FEATURE_FORCE_LOAD */
1015 parse_http_request(req, http, csp);
1020 if (http->cmd == NULL)
1022 strcpy(buf, CHEADER);
1023 write_socket(csp->cfd, buf, strlen(buf));
1025 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
1027 free_http_request(http);
1031 if (!strncmpic(http->cmd, "GET ftp://", 10))
1033 strcpy(buf, FTP_RESPONSE);
1034 write_socket(csp->cfd, buf, strlen(buf));
1036 log_error(LOG_LEVEL_ERROR, "%s tried to use Privoxy as FTP proxy: %s",
1037 csp->ip_addr_str, http->cmd);
1039 free_http_request(http);
1043 /* decide how to route the HTTP request */
1045 if ((fwd = forward_url(http, csp)) == NULL)
1047 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1048 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1051 /* build the http request to send to the server
1052 * we have to do one of the following:
1054 * create = use the original HTTP request to create a new
1055 * HTTP request that has either the path component
1056 * without the http://domainspec (w/path) or the
1057 * full orininal URL (w/url)
1058 * Note that the path and/or the HTTP version may
1059 * have been altered by now.
1061 * connect = Open a socket to the host:port of the server
1062 * and short-circuit server and client socket.
1064 * pass = Pass the request unchanged if forwarding a CONNECT
1065 * request to a parent proxy. Note that we'll be sending
1066 * the CFAIL message ourselves if connecting to the parent
1067 * fails, but we won't send a CSUCCEED message if it works,
1068 * since that would result in a double message (ours and the
1069 * parent's). After sending the request to the parent, we simply
1072 * here's the matrix:
1075 * +--------+--------+
1077 * 0 | create | connect|
1079 * Forwarding +--------+--------+
1081 * 1 | create | pass |
1083 * +--------+--------+
1088 * Determine the actions for this URL
1090 #ifdef FEATURE_TOGGLE
1091 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1093 /* Most compatible set of actions (i.e. none) */
1094 init_current_action(csp->action);
1097 #endif /* ndef FEATURE_TOGGLE */
1099 url_actions(http, csp);
1104 * Check if a CONNECT request is allowable:
1105 * In the absence of a +limit-connect action, allow only port 443.
1106 * If there is an action, allow whatever matches the specificaton.
1110 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
1111 || (csp->action->flags & ACTION_LIMIT_CONNECT
1112 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
1114 if (csp->action->flags & ACTION_TREAT_FORBIDDEN_CONNECTS_LIKE_BLOCKS)
1116 /* The response will violate the specs, but makes unblocking easier. */
1117 log_error(LOG_LEVEL_ERROR, "Marking suspicious CONNECT request from %s for blocking.",
1119 csp->action->flags |= ACTION_BLOCK;
1124 strcpy(buf, CFORBIDDEN);
1125 write_socket(csp->cfd, buf, strlen(buf));
1126 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
1127 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
1135 * Downgrade http version from 1.1 to 1.0 if +downgrade
1138 if ( (http->ssl == 0)
1139 && (!strcmpic(http->ver, "HTTP/1.1"))
1140 && (csp->action->flags & ACTION_DOWNGRADE))
1143 http->ver = strdup("HTTP/1.0");
1145 if (http->ver == NULL)
1147 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
1152 * Save a copy of the original request for logging
1154 http->ocmd = strdup(http->cmd);
1156 if (http->ocmd == NULL)
1158 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
1162 * (Re)build the HTTP request for non-SSL requests.
1163 * If forwarding, use the whole URL, else, use only the path.
1169 http->cmd = strdup(http->gpc);
1170 string_append(&http->cmd, " ");
1172 if (fwd->forward_host)
1174 string_append(&http->cmd, http->url);
1178 string_append(&http->cmd, http->path);
1180 string_append(&http->cmd, " ");
1181 string_append(&http->cmd, http->ver);
1183 if (http->cmd == NULL)
1185 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1187 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", http->cmd);
1189 enlist(csp->headers, http->cmd);
1193 * If the user has not supplied any wafers, and the user has not
1194 * told us to suppress the vanilla wafer, then send the vanilla wafer.
1196 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
1197 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
1199 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
1203 #ifdef FEATURE_KILL_POPUPS
1204 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1205 #endif /* def FEATURE_KILL_POPUPS */
1207 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
1208 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1210 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1212 jpeg_inspect = ((csp->action->flags & ACTION_JPEG_INSPECT) != 0);
1214 /* grab the rest of the client's headers */
1218 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
1220 len = read_socket(csp->cfd, buf, sizeof(buf));
1223 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1228 * If there is no memory left for buffering the
1229 * request, there is nothing we can do but hang up
1231 if (add_to_iob(csp, buf, len))
1238 if (p == NULL) break;
1240 enlist(csp->headers, p);
1245 * We have a request. Now, check to see if we need to
1246 * intercept it, i.e. If ..
1250 /* We may not forward the request by rfc2616 sect 14.31 */
1251 (NULL != (rsp = direct_response(csp)))
1253 /* or we are enabled and... */
1254 || (IS_ENABLED_AND (
1256 /* ..the request was blocked */
1257 ( NULL != (rsp = block_url(csp)))
1259 /* ..or untrusted */
1260 #ifdef FEATURE_TRUST
1261 || ( NULL != (rsp = trust_url(csp)))
1262 #endif /* def FEATURE_TRUST */
1264 /* ..or a redirect kicked in */
1265 || ( NULL != (rsp = redirect_url(csp)))
1269 * .. or a CGI call was detected and answered.
1271 * This check comes last to give the user the power
1272 * to deny acces to some (or all) of the cgi pages.
1274 || (NULL != (rsp = dispatch_cgi(csp)))
1278 /* Write the answer to the client */
1279 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1280 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1282 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1285 #ifdef FEATURE_STATISTICS
1286 /* Count as a rejected request */
1287 csp->flags |= CSP_FLAG_REJECTED;
1288 #endif /* def FEATURE_STATISTICS */
1290 /* Log (FIXME: All intercept reasons appear as "crunch" with Status 200) */
1291 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1292 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1294 /* Clean up and return */
1295 free_http_response(rsp);
1299 hdr = sed(client_patterns, add_client_headers, csp);
1302 /* FIXME Should handle error properly */
1303 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1306 list_remove_all(csp->headers);
1308 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1310 if (fwd->forward_host)
1312 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1313 fwd->forward_host, fwd->forward_port, http->hostport);
1317 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1320 /* here we connect to the server, gateway, or the forwarder */
1322 while ( (csp->sfd = forwarded_connect(fwd, http, csp))
1323 && (errno == EINVAL) && (forwarded_connect_retries++ < max_forwarded_connect_retries))
1325 log_error(LOG_LEVEL_ERROR, "failed request #%u to connect to %s. Trying again.",
1326 forwarded_connect_retries, http->hostport);
1329 if (csp->sfd == JB_INVALID_SOCKET)
1331 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1334 if (errno == EINVAL)
1336 rsp = error_response(csp, "no-such-domain", errno);
1338 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1339 csp->ip_addr_str, http->ocmd);
1343 rsp = error_response(csp, "connect-failed", errno);
1345 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1346 csp->ip_addr_str, http->ocmd);
1350 /* Write the answer to the client */
1353 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1354 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1356 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1360 free_http_response(rsp);
1365 log_error(LOG_LEVEL_CONNECT, "OK");
1367 if (fwd->forward_host || (http->ssl == 0))
1369 /* write the client's (modified) header to the server
1370 * (along with anything else that may be in the buffer)
1373 if (write_socket(csp->sfd, hdr, strlen(hdr))
1374 || (flush_socket(csp->sfd, csp) < 0))
1376 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1379 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1380 csp->ip_addr_str, http->ocmd);
1382 rsp = error_response(csp, "connect-failed", errno);
1386 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1387 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1389 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1393 free_http_response(rsp);
1401 * We're running an SSL tunnel and we're not forwarding,
1402 * so just send the "connect succeeded" message to the
1403 * client, flush the rest, and get out of the way.
1405 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1406 csp->ip_addr_str, http->ocmd);
1408 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1416 /* we're finished with the client's header */
1419 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1421 /* pass data between the client and server
1422 * until one or the other shuts down the connection.
1431 * FD_ZERO here seems to point to an errant macro which crashes.
1432 * So do this by hand for now...
1434 memset(&rfds,0x00,sizeof(fd_set));
1438 FD_SET(csp->cfd, &rfds);
1439 FD_SET(csp->sfd, &rfds);
1441 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1445 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1449 /* this is the body of the browser's request
1450 * just read it and write it.
1453 if (FD_ISSET(csp->cfd, &rfds))
1455 len = read_socket(csp->cfd, buf, sizeof(buf));
1459 break; /* "game over, man" */
1462 if (write_socket(csp->sfd, buf, (size_t)len))
1464 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1471 * The server wants to talk. It could be the header or the body.
1472 * If `hdr' is null, then it's the header otherwise it's the body.
1473 * FIXME: Does `hdr' really mean `host'? No.
1477 if (FD_ISSET(csp->sfd, &rfds))
1480 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1484 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1486 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1487 csp->ip_addr_str, http->ocmd);
1489 rsp = error_response(csp, "connect-failed", errno);
1493 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1494 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1496 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1500 free_http_response(rsp);
1504 /* Add a trailing zero. This lets filter_popups
1505 * use string operations.
1509 #ifdef FEATURE_KILL_POPUPS
1510 /* Filter the popups on this read. */
1511 if (block_popups_now)
1513 filter_popups(buf, csp);
1515 #endif /* def FEATURE_KILL_POPUPS */
1517 /* Normally, this would indicate that we've read
1518 * as much as the server has sent us and we can
1519 * close the client connection. However, Microsoft
1520 * in its wisdom has released IIS/5 with a bug that
1521 * prevents it from sending the trailing \r\n in
1522 * a 302 redirect header (and possibly other headers).
1523 * To work around this if we've haven't parsed
1524 * a full header we'll append a trailing \r\n
1525 * and see if this now generates a valid one.
1527 * This hack shouldn't have any impacts. If we've
1528 * already transmitted the header or if this is a
1529 * SSL connection, then we won't bother with this
1530 * hack. So we only work on partially received
1531 * headers. If we append a \r\n and this still
1532 * doesn't generate a valid header, then we won't
1533 * transmit anything to the client.
1538 if (server_body || http->ssl)
1541 * If we have been buffering up the document,
1542 * now is the time to apply content modification
1543 * and send the result to the client.
1548 * If the content filter fails, use the original
1549 * buffer and length.
1550 * (see p != NULL ? p : csp->iob->cur below)
1552 if (NULL == (p = (*content_filter)(csp)))
1554 csp->content_length = csp->iob->eod - csp->iob->cur;
1557 hdr = sed(server_patterns_light, NULL, csp);
1561 /* FIXME Should handle error properly */
1562 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1565 if (write_socket(csp->cfd, hdr, strlen(hdr))
1566 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1568 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1578 break; /* "game over, man" */
1582 * This is NOT the body, so
1583 * Let's pretend the server just sent us a blank line.
1585 len = sprintf(buf, "\r\n");
1588 * Now, let the normal header parsing algorithm below do its
1589 * job. If it fails, we'll exit instead of continuing.
1596 * If this is an SSL connection or we're in the body
1597 * of the server document, just write it to the client,
1598 * unless we need to buffer the body for later content-filtering
1601 if (server_body || http->ssl)
1606 * If there is no memory left for buffering the content, or the buffer limit
1607 * has been reached, switch to non-filtering mode, i.e. make & write the
1608 * header, flush the iob and buf, and get out of the way.
1610 if (add_to_iob(csp, buf, len))
1615 log_error(LOG_LEVEL_ERROR, "Flushing header and buffers. Stepping back from filtering.");
1617 hdr = sed(server_patterns, add_server_headers, csp);
1621 * Memory is too tight to even generate the header.
1622 * Send our static "Out-of-memory" page.
1624 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
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 hdrlen = strlen(hdr);
1637 if (write_socket(csp->cfd, hdr, hdrlen)
1638 || ((flushed = flush_socket(csp->cfd, csp)) < 0)
1639 || (write_socket(csp->cfd, buf, (size_t) len)))
1641 log_error(LOG_LEVEL_CONNECT, "Flush header and buffers to client failed: %E");
1647 byte_count += hdrlen + flushed + len;
1649 content_filter = NULL;
1656 if (write_socket(csp->cfd, buf, (size_t)len))
1658 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1667 /* we're still looking for the end of the
1668 * server's header ... (does that make header
1669 * parsing an "out of body experience" ?
1673 * buffer up the data we just read. If that fails,
1674 * there's little we can do but send our static
1675 * out-of-memory page.
1677 if (add_to_iob(csp, buf, len))
1679 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
1680 rsp = cgi_error_memory();
1682 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1683 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1685 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1690 /* get header lines from the iob */
1692 while ((p = get_header(csp)) != NULL)
1696 /* see following note */
1699 enlist(csp->headers, p);
1703 /* NOTE: there are no "empty" headers so
1704 * if the pointer `p' is not NULL we must
1705 * assume that we reached the end of the
1706 * buffer before we hit the end of the header.
1713 /* Well, we tried our MS IIS/5
1714 * hack and it didn't work.
1715 * The header is incomplete
1716 * and there isn't anything
1717 * we can do about it.
1723 /* Since we have to wait for
1724 * more from the server before
1725 * we can parse the headers
1726 * we just continue here.
1732 /* we have now received the entire header.
1733 * filter it and send the result to the client
1736 hdr = sed(server_patterns, add_server_headers, csp);
1739 /* FIXME Should handle error properly */
1740 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1743 #ifdef FEATURE_KILL_POPUPS
1744 /* Start blocking popups if appropriate. */
1746 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1747 !http->ssl && /* We talk plaintext */
1748 block_popups) /* Policy allows */
1750 block_popups_now = 1;
1752 * Filter the part of the body that came in the same read
1753 * as the last headers:
1755 filter_popups(csp->iob->cur, csp);
1758 #endif /* def FEATURE_KILL_POPUPS */
1760 /* Buffer and pcrs filter this if appropriate. */
1762 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1763 !http->ssl && /* We talk plaintext */
1764 pcrs_filter) /* Policy allows */
1766 content_filter = pcrs_filter_response;
1769 /* Buffer and gif_deanimate this if appropriate. */
1771 if ((csp->content_type & CT_GIF) && /* It's an image/gif MIME-Type */
1772 !http->ssl && /* We talk plaintext */
1773 gif_deanimate) /* Policy allows */
1775 content_filter = gif_deanimate_response;
1778 /* Buffer and jpg_inspect this if appropriate. */
1780 if ((csp->content_type & CT_JPEG) && /* It's an image/jpeg MIME-Type */
1781 !http->ssl && /* We talk plaintext */
1782 jpeg_inspect) /* Policy allows */
1784 content_filter = jpeg_inspect_response;
1788 * Only write if we're not buffering for content modification
1790 if (!content_filter)
1792 /* write the server's (modified) header to
1793 * the client (along with anything else that
1794 * may be in the buffer)
1797 if (write_socket(csp->cfd, hdr, strlen(hdr))
1798 || ((len = flush_socket(csp->cfd, csp)) < 0))
1800 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1802 /* the write failed, so don't bother
1803 * mentioning it to the client...
1804 * it probably can't hear us anyway.
1813 /* we're finished with the server's header */
1818 /* If this was a MS IIS/5 hack then it means
1819 * the server has already closed the
1820 * connection. Nothing more to read. Time
1831 return; /* huh? we should never get here */
1834 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1835 csp->ip_addr_str, http->ocmd, byte_count);
1839 /*********************************************************************
1843 * Description : This is little more than chat. We only "serve" to
1844 * to close any socket that chat may have opened.
1847 * 1 : csp = Current client state (buffers, headers, etc...)
1851 *********************************************************************/
1853 void serve(struct client_state *csp)
1854 #else /* ifndef AMIGA */
1855 static void serve(struct client_state *csp)
1856 #endif /* def AMIGA */
1859 close_socket(csp->cfd);
1861 if (csp->sfd != JB_INVALID_SOCKET)
1863 close_socket(csp->sfd);
1866 csp->flags &= ~CSP_FLAG_ACTIVE;
1872 /*********************************************************************
1874 * Function : server_thread
1876 * Description : We only exist to call `serve' in a threaded environment.
1879 * 1 : data = Current client state (buffers, headers, etc...)
1881 * Returns : Always 0.
1883 *********************************************************************/
1884 static int32 server_thread(void *data)
1886 serve((struct client_state *) data);
1893 /*********************************************************************
1897 * Description : Print usage info & exit.
1899 * Parameters : Pointer to argv[0] for identifying ourselves
1903 *********************************************************************/
1904 void usage(const char *myname)
1906 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
1908 "Usage: %s [--help] [--version] [configfile]\n"
1910 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1912 "Aborting.\n", myname);
1919 /*********************************************************************
1923 * Description : Load the config file and start the listen loop.
1924 * This function is a lot more *sane* with the `load_config'
1925 * and `listen_loop' functions; although it stills does
1926 * a *little* too much for my taste.
1929 * 1 : argc = Number of parameters (including $0).
1930 * 2 : argv = Array of (char *)'s to the parameters.
1932 * Returns : 1 if : can't open config file, unrecognized directive,
1933 * stats requested in multi-thread mode, can't open the
1934 * log file, can't open the jar file, listen port is invalid,
1935 * any load fails, and can't bind port.
1937 * Else main never returns, the process must be signaled
1938 * to terminate execution. Or, on Windows, use the
1939 * "File", "Exit" menu option.
1941 *********************************************************************/
1943 int real_main(int argc, const char *argv[])
1945 int main(int argc, const char *argv[])
1950 unsigned int random_seed;
1951 #endif /* ifdef HAVE_RANDOM */
1953 struct passwd *pw = NULL;
1954 struct group *grp = NULL;
1963 #if !defined(_WIN32)
1971 * Parse the command line arguments
1973 while (++argc_pos < argc)
1976 /* Check to see if the service must be installed or uninstalled */
1977 if (strncmp(argv[argc_pos], "--install", 9) == 0)
1979 const char *pName = argv[argc_pos] + 9;
1982 exit( (install_service(pName)) ? 0 : 1 );
1984 else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
1986 const char *pName = argv[argc_pos] + 11;
1989 exit((uninstall_service(pName)) ? 0 : 1);
1991 else if (strcmp(argv[argc_pos], "--service" ) == 0)
1993 bRunAsService = TRUE;
1994 w32_set_service_cwd();
1995 atexit(w32_service_exit_notify);
1998 #endif /* defined(_WIN32) */
2001 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2003 if (strcmp(argv[argc_pos], "--help") == 0)
2008 else if(strcmp(argv[argc_pos], "--version") == 0)
2010 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2016 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
2021 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
2023 if (++argc_pos == argc) usage(argv[0]);
2024 pidfile = strdup(argv[argc_pos]);
2027 else if (strcmp(argv[argc_pos], "--user" ) == 0)
2029 if (++argc_pos == argc) usage(argv[argc_pos]);
2031 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
2034 if (NULL == (grp = getgrnam(p)))
2036 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
2040 if (NULL == (pw = getpwnam(argv[argc_pos])))
2042 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
2045 if (p != NULL) *--p = '\0';
2048 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
2053 #endif /* defined(unix) */
2054 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
2056 configfile = argv[argc_pos];
2059 } /* -END- while (more arguments) */
2062 if ( *configfile != '/' )
2064 char *abs_file, cwd[1024];
2066 /* make config-filename absolute here */
2067 if ( !(getcwd(cwd, sizeof(cwd))))
2069 perror("get working dir failed");
2073 if (!(basedir = strdup(cwd))
2074 || (!(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 ))))
2076 perror("malloc failed");
2079 strcpy( abs_file, basedir );
2080 strcat( abs_file, "/" );
2081 strcat( abs_file, configfile );
2082 configfile = abs_file;
2084 #endif /* defined unix */
2088 clients->next = NULL;
2092 #elif defined(_WIN32)
2096 #ifdef FEATURE_PTHREAD
2098 * Prepare global mutex semaphores
2100 pthread_mutex_init(&log_mutex,0);
2101 pthread_mutex_init(&log_init_mutex,0);
2103 #ifndef HAVE_GMTIME_R
2104 pthread_mutex_init(&gmtime_mutex,0);
2105 #endif /* ndef HAVE_GMTIME_R */
2107 #ifndef HAVE_LOCALTIME_R
2108 pthread_mutex_init(&localtime_mutex,0);
2109 #endif /* ndef HAVE_GMTIME_R */
2111 #ifndef HAVE_GETHOSTBYADDR_R
2112 pthread_mutex_init(&gethostbyaddr_mutex,0);
2113 #endif /* ndef HAVE_GETHOSTBYADDR_R */
2115 #ifndef HAVE_GETHOSTBYNAME_R
2116 pthread_mutex_init(&gethostbyname_mutex,0);
2117 #endif /* ndef HAVE_GETHOSTBYNAME_R */
2118 #endif /* FEATURE_PTHREAD */
2121 random_seed = (unsigned int)time(NULL);
2122 srandom(random_seed);
2123 #endif /* ifdef HAVE_RANDOM */
2126 * Unix signal handling
2128 * Catch the abort, interrupt and terminate signals for a graceful exit
2129 * Catch the hangup signal so the errlog can be reopened.
2130 * Ignore the broken pipe signals (FIXME: Why?)
2132 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
2135 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
2136 const int ignored_signals[] = { SIGPIPE, 0 };
2138 for (idx = 0; catched_signals[idx] != 0; idx++)
2140 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
2141 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
2143 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
2144 #endif /* ifdef sun */
2146 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
2150 for (idx = 0; ignored_signals[idx] != 0; idx++)
2152 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
2154 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
2159 #else /* ifdef _WIN32 */
2160 # ifdef _WIN_CONSOLE
2162 * We *are* in a windows console app.
2163 * Print a verbose messages about FAQ's and such
2165 printf(win32_blurb);
2166 # endif /* def _WIN_CONSOLE */
2167 #endif /* def _WIN32 */
2170 /* Initialize the CGI subsystem */
2171 cgi_init_error_messages();
2174 * If runnig on unix and without the --nodaemon
2175 * option, become a daemon. I.e. fork, detach
2176 * from tty and get process group leadership
2189 if ( pid < 0 ) /* error */
2194 else if ( pid != 0 ) /* parent */
2199 * must check for errors
2200 * child died due to missing files aso
2203 wpid = waitpid( pid, &status, WNOHANG );
2212 /* Should be more portable, but not as well tested */
2217 #else /* ndef __FreeBSD__ */
2219 #endif /* ndef __FreeBSD__ */
2220 fd = open("/dev/tty", O_RDONLY);
2223 /* no error check here */
2224 ioctl( fd, TIOCNOTTY,0 );
2228 /* FIXME: should close stderr (fd 2) here too, but the test
2230 * and load config file is done in listen_loop() and puts
2231 * some messages on stderr there.
2238 } /* -END- if (!no_daemon) */
2241 * As soon as we have written the PID file, we can switch
2242 * to the user and group ID indicated by the --user option
2248 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
2250 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
2256 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
2258 if (chroot(pw->pw_dir) < 0)
2260 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
2264 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
2267 if (setuid(pw->pw_uid))
2269 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
2273 char putenv_dummy[64];
2275 strcpy(putenv_dummy, "HOME=/");
2276 if (putenv(putenv_dummy) != 0)
2278 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
2281 snprintf(putenv_dummy, 64, "USER=%s", pw->pw_name);
2282 if (putenv(putenv_dummy) != 0)
2284 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
2290 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
2293 #endif /* defined unix */
2296 /* This will be FALSE unless the command line specified --service
2300 /* Yup, so now we must attempt to establish a connection
2301 * with the service dispatcher. This will only work if this
2302 * process was launched by the service control manager to
2303 * actually run as a service. If this isn't the case, i've
2304 * known it take around 30 seconds or so for the call to return.
2307 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
2308 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
2310 /* Service has run, and at this point is now being stopped, so just return */
2315 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
2317 /* An error occurred. Usually it's because --service was wrongly specified
2318 * and we were unable to connect to the Service Control Dispatcher because
2319 * it wasn't expecting us and is therefore not listening.
2321 * For now, just continue below to call the listen_loop function.
2324 #endif /* def _WIN32 */
2334 /*********************************************************************
2336 * Function : bind_port_helper
2338 * Description : Bind the listen port. Handles logging, and aborts
2342 * 1 : config = Privoxy configuration. Specifies port
2345 * Returns : Port that was opened.
2347 *********************************************************************/
2348 static jb_socket bind_port_helper(struct configuration_spec * config)
2353 if ( (config->haddr != NULL)
2354 && (config->haddr[0] == '1')
2355 && (config->haddr[1] == '2')
2356 && (config->haddr[2] == '7')
2357 && (config->haddr[3] == '.') )
2359 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
2362 else if (config->haddr == NULL)
2364 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
2369 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
2370 config->hport, config->haddr);
2373 result = bind_port(config->haddr, config->hport, &bfd);
2380 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2381 "There may be another Privoxy or some other "
2382 "proxy running on port %d",
2383 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
2384 config->hport, config->hport);
2387 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2388 "The hostname is not resolvable",
2389 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2392 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
2393 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2396 /* shouldn't get here */
2397 return JB_INVALID_SOCKET;
2400 config->need_bind = 0;
2407 /* Without this simple workaround we get this compiler warning from _beginthread
2408 * warning C4028: formal parameter 1 different from declaration
2410 void w32_service_listen_loop(void *p)
2414 #endif /* def _WIN32 */
2417 /*********************************************************************
2419 * Function : listen_loop
2421 * Description : bind the listen port and enter a "FOREVER" listening loop.
2427 *********************************************************************/
2428 static void listen_loop(void)
2430 struct client_state *csp = NULL;
2432 struct configuration_spec * config;
2434 config = load_config();
2436 bfd = bind_port_helper(config);
2438 #ifdef FEATURE_GRACEFUL_TERMINATION
2439 while (!g_terminate)
2444 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
2445 while (waitpid(-1, NULL, WNOHANG) > 0)
2447 /* zombie children */
2449 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2452 * Free data that was used by died threads
2458 * Re-open the errlog after HUP signal
2460 if (received_hup_signal)
2462 init_error_log(Argv[0], config->logfile, config->debug);
2463 received_hup_signal = 0;
2468 #ifdef FEATURE_COOKIE_JAR
2470 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
2471 * already open. I think unload_configfile() is not being run, which should do
2472 * this work. Until that can get resolved, we'll use this workaround.
2476 if (csp->config->jar)
2478 fclose(csp->config->jar);
2479 csp->config->jar = NULL;
2481 #endif /* FEATURE_COOKIE_JAR */
2482 #endif /* __OS2__ */
2484 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2486 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2490 csp->flags |= CSP_FLAG_ACTIVE;
2491 csp->sfd = JB_INVALID_SOCKET;
2493 csp->config = config = load_config();
2495 if ( config->need_bind )
2498 * Since we were listening to the "old port", we will not see
2499 * a "listen" param change until the next IJB request. So, at
2500 * least 1 more request must be made for us to find the new
2501 * setting. I am simply closing the old socket and binding the
2504 * Which-ever is correct, we will serve 1 more page via the
2505 * old settings. This should probably be a "show-proxy-args"
2506 * request. This should not be a so common of an operation
2507 * that this will hurt people's feelings.
2512 bfd = bind_port_helper(config);
2515 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2517 if (!accept_connection(csp, bfd))
2519 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2532 log_error(LOG_LEVEL_CONNECT, "OK");
2535 #ifdef FEATURE_TOGGLE
2536 if (global_toggle_state)
2538 csp->flags |= CSP_FLAG_TOGGLED_ON;
2540 #endif /* def FEATURE_TOGGLE */
2542 if (run_loader(csp))
2544 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2545 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2549 if (block_acl(NULL,csp))
2551 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2552 close_socket(csp->cfd);
2556 #endif /* def FEATURE_ACL */
2558 /* add it to the list of clients */
2559 csp->next = clients->next;
2560 clients->next = csp;
2562 if (config->multi_threaded)
2566 /* this is a switch () statment in the C preprocessor - ugh */
2567 #undef SELECTED_ONE_OPTION
2569 /* Use Pthreads in preference to native code */
2570 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2571 #define SELECTED_ONE_OPTION
2573 pthread_t the_thread;
2574 pthread_attr_t attrs;
2576 pthread_attr_init(&attrs);
2577 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2578 errno = pthread_create(&the_thread, &attrs,
2580 child_id = errno ? -1 : 0;
2581 pthread_attr_destroy(&attrs);
2585 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2586 #define SELECTED_ONE_OPTION
2587 child_id = _beginthread(
2588 (void (*)(void *))serve,
2593 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2594 #define SELECTED_ONE_OPTION
2595 child_id = _beginthread(
2596 (void(* _Optlink)(void*))serve,
2602 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2603 #define SELECTED_ONE_OPTION
2605 thread_id tid = spawn_thread
2606 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2608 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2610 child_id = (int) tid;
2619 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2620 #define SELECTED_ONE_OPTION
2621 csp->cfd = ReleaseSocket(csp->cfd, -1);
2623 if((child_id = (int)CreateNewProcTags(
2624 NP_Entry, (ULONG)server_thread,
2625 NP_Output, Output(),
2626 NP_CloseOutput, FALSE,
2627 NP_Name, (ULONG)"privoxy child",
2628 NP_StackSize, 200*1024,
2632 ((struct Task *)child_id)->tc_UserData = csp;
2633 Signal((struct Task *)child_id, SIGF_SINGLE);
2638 #if !defined(SELECTED_ONE_OPTION)
2641 /* This block is only needed when using fork().
2642 * When using threads, the server thread was
2643 * created and run by the call to _beginthread().
2645 if (child_id == 0) /* child */
2648 #ifdef FEATURE_TOGGLE
2649 int inherited_toggle_state = global_toggle_state;
2650 #endif /* def FEATURE_TOGGLE */
2655 * If we've been toggled or we've blocked the request, tell Mom
2658 #ifdef FEATURE_TOGGLE
2659 if (inherited_toggle_state != global_toggle_state)
2661 rc |= RC_FLAG_TOGGLED;
2663 #endif /* def FEATURE_TOGGLE */
2665 #ifdef FEATURE_STATISTICS
2666 if (csp->flags & CSP_FLAG_REJECTED)
2668 rc |= RC_FLAG_BLOCKED;
2670 #endif /* ndef FEATURE_STATISTICS */
2674 else if (child_id > 0) /* parent */
2676 /* in a fork()'d environment, the parent's
2677 * copy of the client socket and the CSP
2681 #if !defined(_WIN32) && !defined(__CYGWIN__)
2683 wait( &child_status );
2686 * Evaluate child's return code: If the child has
2687 * - been toggled, toggle ourselves
2688 * - blocked its request, bump up the stats counter
2691 #ifdef FEATURE_TOGGLE
2692 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
2694 global_toggle_state = !global_toggle_state;
2696 #endif /* def FEATURE_TOGGLE */
2698 #ifdef FEATURE_STATISTICS
2700 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
2704 #endif /* def FEATURE_STATISTICS */
2706 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2707 close_socket(csp->cfd);
2708 csp->flags &= ~CSP_FLAG_ACTIVE;
2712 #undef SELECTED_ONE_OPTION
2713 /* end of cpp switch () */
2715 if (child_id < 0) /* failed */
2717 char buf[BUFFER_SIZE];
2719 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2721 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
2723 write_socket(csp->cfd, buf, strlen(buf));
2724 close_socket(csp->cfd);
2725 csp->flags &= ~CSP_FLAG_ACTIVE;
2736 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2738 /* Clean up. Aim: free all memory (no leaks) */
2739 #ifdef FEATURE_GRACEFUL_TERMINATION
2741 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2743 unload_current_config_file();
2744 unload_current_actions_file();
2745 unload_current_re_filterfile();
2746 #ifdef FEATURE_TRUST
2747 unload_current_trust_file();
2750 if (config->multi_threaded)
2757 } while ((clients->next != NULL) && (--i > 0));
2761 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2772 #ifdef FEATURE_COOKIE_JAR
2773 if (NULL != config->jar)
2775 fclose(config->jar);
2779 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2780 /* Cleanup - remove taskbar icon etc. */
2785 #endif /* FEATURE_GRACEFUL_TERMINATION */