1 const char jcc_rcs[] = "$Id: jcc.c,v 1.108 2006/11/28 15:38: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.108 2006/11/28 15:38:51 fabiankeil
37 * Only unlink the pidfile if it's actually used.
39 * Change order of interception checks to make
40 * it possible to block or redirect requests for
43 * Revision 1.107 2006/11/13 19:05:51 fabiankeil
44 * Make pthread mutex locking more generic. Instead of
45 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
46 * and use mutex locking unless there is an _r function
47 * available. Better safe than sorry.
49 * Fixes "./configure --disable-pthread" and should result
50 * in less threading-related problems on pthread-using platforms,
51 * but it still doesn't fix BR#1122404.
53 * Revision 1.106 2006/11/06 19:58:23 fabiankeil
54 * Move pthread.h inclusion from jcc.c to jcc.h.
55 * Fixes build on x86-freebsd1 (FreeBSD 5.4-RELEASE).
57 * Revision 1.105 2006/11/06 14:26:02 fabiankeil
58 * Don't exit after receiving the second SIGHUP on Solaris.
60 * Fixes BR 1052235, but the same problem may exist on other
61 * systems. Once 3.0.6 is out we should use sigset()
62 * where available and see if it breaks anything.
64 * Revision 1.104 2006/09/23 13:26:38 roro
65 * Replace TABs by spaces in source code.
67 * Revision 1.103 2006/09/21 12:54:43 fabiankeil
68 * Fix +redirect{}. Didn't work with -fast-redirects.
70 * Revision 1.102 2006/09/06 13:03:04 fabiankeil
71 * Respond with 400 and a short text message
72 * if the client tries to use Privoxy as FTP proxy.
74 * Revision 1.101 2006/09/06 09:23:37 fabiankeil
75 * Make number of retries in case of forwarded-connect problems
76 * a config file option (forwarded-connect-retries) and use 0 as
79 * Revision 1.100 2006/09/03 19:42:59 fabiankeil
82 * Revision 1.99 2006/09/02 15:36:42 fabiankeil
83 * Follow the OpenBSD port's lead and protect the resolve
84 * functions on OpenBSD as well.
86 * Revision 1.98 2006/08/24 11:01:34 fabiankeil
87 * --user fix. Only use the user as group if no group is specified.
88 * Solves BR 1492612. Thanks to Spinor S. and David Laight.
90 * Revision 1.97 2006/08/18 15:23:17 david__schmidt
91 * Windows service (re-)integration
95 * --install[:service_name]
96 * --uninstall[:service_name]
99 * They work as follows:
100 * --install will create a service for you and then terminate.
101 * By default the service name will be "privoxy" (without the quotes).
102 * However you can run multiple services if you wish, just by adding
103 * a colon and then a name (no spaces).
105 * --uninstall follows the exact same rules a --install.
107 * --service is used when the program is executed by the service
108 * control manager, and in normal circumstances would never be
109 * used as a command line argument.
111 * Revision 1.96 2006/08/15 20:12:36 david__schmidt
112 * Windows service integration
114 * Revision 1.95 2006/08/03 02:46:41 david__schmidt
115 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
117 * Revision 1.94 2006/07/18 14:48:46 david__schmidt
118 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
119 * with what was really the latest development (the v_3_0_branch branch)
121 * Revision 1.92.2.16 2005/04/03 20:10:50 david__schmidt
122 * Thanks to Jindrich Makovicka for a race condition fix for the log
123 * file. The race condition remains for non-pthread implementations.
124 * Reference patch #1175720.
126 * Revision 1.92.2.15 2004/10/03 12:53:32 david__schmidt
127 * Add the ability to check jpeg images for invalid
128 * lengths of comment blocks. Defensive strategy
129 * against the exploit:
130 * Microsoft Security Bulletin MS04-028
131 * Buffer Overrun in JPEG Processing (GDI+) Could
132 * Allow Code Execution (833987)
133 * Enabled with +inspect-jpegs in actions files.
135 * Revision 1.92.2.14 2003/12/12 12:52:53 oes
136 * - Fixed usage info for non-unix platforms
137 * - Fixed small cmdline parsing bug
139 * Revision 1.92.2.13 2003/11/27 19:20:27 oes
140 * Diagnostics: Now preserve the returncode of pthread_create
141 * in errno. Closes BR #775721. Thanks to Geoffrey Hausheer.
143 * Revision 1.92.2.12 2003/07/11 11:34:19 oes
144 * No longer ignore SIGCHLD. Fixes bug #769381
146 * Revision 1.92.2.11 2003/05/14 12:32:02 oes
147 * Close jarfile on graceful exit, remove stray line
149 * Revision 1.92.2.10 2003/05/08 15:13:46 oes
150 * Cosmetics: Killed a warning, a typo and an allocation left at exit
152 * Revision 1.92.2.9 2003/04/03 15:08:42 oes
153 * No longer rely on non-POSIX.1 extensions of getcwd().
156 * Revision 1.92.2.8 2003/03/31 13:12:32 oes
157 * Replaced setenv() by posix-compliant putenv()
158 * Thanks to Neil McCalden (nmcc AT users.sf.net).
160 * Revision 1.92.2.7 2003/03/17 16:48:59 oes
161 * Added chroot ability, thanks to patch by Sviatoslav Sviridov
163 * Revision 1.92.2.6 2003/03/11 11:55:00 oes
164 * Clean-up and extension of improvements for forked mode:
165 * - Child's return code now consists of flags RC_FLAG_*
166 * - Reporting toggle to parent now properly #ifdef'ed
167 * - Children now report blocking to parent. This enables
168 * statistics in forked mode
170 * Revision 1.92.2.5 2003/03/10 23:45:32 oes
171 * Fixed bug #700381: Non-Threaded version now capable of being toggled.
172 * Children now report having been toggled through _exit(17), parents
173 * watch for that code and toggle themselves if found.
175 * Revision 1.92.2.4 2003/03/07 03:41:04 david__schmidt
176 * Wrapping all *_r functions (the non-_r versions of them) with
177 * mutex semaphores for OSX. Hopefully this will take care of all
178 * of those pesky crash reports.
180 * Revision 1.92.2.3 2003/02/28 12:53:06 oes
181 * Fixed two mostly harmless mem leaks
183 * Revision 1.92.2.2 2002/11/20 14:37:47 oes
184 * Fix: Head of global clients list now initialized to NULL
186 * Revision 1.92.2.1 2002/09/25 14:52:24 oes
187 * Added basic support for OPTIONS and TRACE HTTP methods:
188 * - New interceptor direct_response() added in chat().
189 * - sed() moved to earlier in the process, so that the
190 * Host: header is evaluated before actions and forwarding
193 * Revision 1.92 2002/05/08 16:00:46 oes
194 * Chat's buffer handling:
195 * - Fixed bug with unchecked out-of-mem conditions
196 * while reading client request & server headers
197 * - No longer predict if the buffer limit will be exceeded
198 * in the next read -- check add_to_iob's new
199 * return code. If buffer couldn't be extended
200 * (policy or out-of-mem) while
201 * - reading from client: abort
202 * - reading server headers: send error page
203 * - buffering server body for filter: flush,
204 * and if that fails: send error page
206 * Revision 1.91 2002/04/08 20:35:58 swa
209 * Revision 1.90 2002/04/02 14:57:28 oes
210 * Made sending wafers independent of FEATURE_COOKIE_JAR
212 * Revision 1.89 2002/03/31 17:18:59 jongfoster
213 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
215 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
216 * More compiler warning message maintenance
218 * Revision 1.87 2002/03/26 22:29:54 swa
219 * we have a new homepage!
221 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
222 * Workaround for closing the jarfile before load_config() comes around again
224 * Revision 1.85 2002/03/24 15:23:33 jongfoster
227 * Revision 1.84 2002/03/24 13:25:43 swa
228 * name change related issues
230 * Revision 1.83 2002/03/16 23:54:06 jongfoster
231 * Adding graceful termination feature, to help look for memory leaks.
232 * If you enable this (which, by design, has to be done by hand
233 * editing config.h) and then go to http://i.j.b/die, then the program
234 * will exit cleanly after the *next* request. It should free all the
235 * memory that was used.
237 * Revision 1.82 2002/03/13 00:27:05 jongfoster
240 * Revision 1.81 2002/03/12 01:42:50 oes
241 * Introduced modular filters
243 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
244 * OS/2 port maintenance:
245 * - Fixed EMX build - it had decayed a little
246 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
247 * substituted a memset for now.
249 * Revision 1.79 2002/03/09 20:03:52 jongfoster
250 * - Making various functions return int rather than size_t.
251 * (Undoing a recent change). Since size_t is unsigned on
252 * Windows, functions like read_socket that return -1 on
253 * error cannot return a size_t.
255 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
256 * crashes, and also frequently caused JB to jump to 100%
257 * CPU and stay there. (Because it thought it had just
258 * read ((unsigned)-1) == 4Gb of data...)
260 * - The signature of write_socket has changed, it now simply
261 * returns success=0/failure=nonzero.
263 * - Trying to get rid of a few warnings --with-debug on
264 * Windows, I've introduced a new type "jb_socket". This is
265 * used for the socket file descriptors. On Windows, this
266 * is SOCKET (a typedef for unsigned). Everywhere else, it's
267 * an int. The error value can't be -1 any more, so it's
268 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
269 * Windows it maps to the #define INVALID_SOCKET.)
271 * - The signature of bind_port has changed.
273 * Revision 1.78 2002/03/08 21:35:04 oes
274 * Added optional group supplement to --user option. Will now use default group of user if no group given
276 * Revision 1.77 2002/03/07 03:52:06 oes
277 * - Fixed compiler warnings etc
278 * - Improved handling of failed DNS lookups
280 * Revision 1.76 2002/03/06 22:54:35 jongfoster
281 * Automated function-comment nitpicking.
283 * Revision 1.75 2002/03/06 10:02:19 oes
284 * Fixed stupid bug when --user was not given
286 * Revision 1.74 2002/03/06 00:49:31 jongfoster
287 * Fixing warning on Windows
288 * Making #ifdefs that refer to the same variable consistently
289 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
291 * Revision 1.73 2002/03/05 23:57:30 hal9
292 * Stray character 's' on line 1618 was breaking build.
294 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
295 * - Re-enable OS/2 building after new parms were added
296 * - Fix false out of memory report when resolving CGI templates when no IP
297 * address is available of failed attempt (a la no such domain)
299 * Revision 1.71 2002/03/05 18:13:56 oes
300 * Added --user option
302 * Revision 1.70 2002/03/05 04:52:42 oes
303 * Deleted non-errlog debugging code
305 * Revision 1.69 2002/03/04 23:50:00 jongfoster
306 * Splitting off bind_port() call into bind_port_helper(), with
309 * Revision 1.68 2002/03/04 20:17:32 oes
312 * Revision 1.67 2002/03/04 18:18:57 oes
313 * - Removed _DEBUG mode
314 * - Cleand up cmdline parsing
315 * - Introduced --no-daemon, --pidfile options
316 * - Cleaned up signal handling:
317 * - Terminate cleanly on INT, TERM and ABRT
318 * - Schedule logfile for re-opening on HUP
319 * - Ignore CHLD and PIPE
320 * - Leave the rest with their default handlers
321 * - Uniform handler registration
322 * - Added usage() function
323 * - Played styleguide police
325 * Revision 1.66 2002/03/03 15:06:55 oes
326 * Re-enabled automatic config reloading
328 * Revision 1.65 2002/03/03 14:49:11 oes
329 * Fixed CLF logging: Now uses client's original HTTP request
331 * Revision 1.64 2002/03/03 09:18:03 joergs
332 * Made jumbjuster work on AmigaOS again.
334 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
335 * Clean up a little CRLF unpleasantness that suddenly appeared
337 * Revision 1.62 2002/02/20 23:17:23 jongfoster
338 * Detecting some out-of memory conditions and exiting with a log message.
340 * Revision 1.61 2002/01/17 21:01:52 jongfoster
341 * Moving all our URL and URL pattern parsing code to urlmatch.c.
343 * Revision 1.60 2001/12/30 14:07:32 steudten
344 * - Add signal handling (unix)
345 * - Add SIGHUP handler (unix)
346 * - Add creation of pidfile (unix)
347 * - Add action 'top' in rc file (RH)
348 * - Add entry 'SIGNALS' to manpage
349 * - Add exit message to logfile (unix)
351 * Revision 1.59 2001/12/13 14:07:18 oes
352 * Fixed Bug: 503 error page now sent OK
354 * Revision 1.58 2001/11/30 23:37:24 jongfoster
355 * Renaming the Win32 config file to config.txt - this is almost the
356 * same as the corresponding UNIX name "config"
358 * Revision 1.57 2001/11/16 00:47:43 jongfoster
359 * Changing the tty-disconnection code to use setsid().
361 * Revision 1.56 2001/11/13 20:20:54 jongfoster
362 * Tabs->spaces, fixing a bug with missing {} around an if()
364 * Revision 1.55 2001/11/13 20:14:53 jongfoster
365 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
367 * Revision 1.54 2001/11/07 00:03:14 steudten
368 * Give reliable return value if an error
369 * occurs not just 0 with new daemon mode.
371 * Revision 1.53 2001/11/05 21:41:43 steudten
372 * Add changes to be a real daemon just for unix os.
373 * (change cwd to /, detach from controlling tty, set
374 * process group and session leader to the own process.
376 * Add some fatal-error log message for failed malloc().
377 * Add '-d' if compiled with 'configure --with-debug' to
378 * enable debug output.
380 * Revision 1.52 2001/10/26 20:11:20 jongfoster
381 * Fixing type mismatch
383 * Revision 1.51 2001/10/26 17:38:28 oes
386 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
387 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
388 * threads to call select() simultaneously. So, it's time to do a real, live,
389 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
390 * (native). Both versions will work, but using __OS2__ offers multi-threading.
392 * Revision 1.49 2001/10/23 21:41:35 jongfoster
393 * Added call to initialize the (statically-allocated of course)
394 * "out of memory" CGI response.
396 * Revision 1.48 2001/10/10 19:56:46 jongfoster
397 * Moving some code that wasn't cookie-related out of an #ifdef
400 * Revision 1.47 2001/10/10 16:44:36 oes
401 * Added CONNECT destination port limitation check
403 * Revision 1.46 2001/10/08 15:17:41 oes
404 * Re-enabled SSL forwarding
406 * Revision 1.45 2001/10/07 15:42:11 oes
407 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
409 * Moved downgrading of the HTTP version from parse_http_request to
410 * chat(), since we can't decide if it is necessary before we have
411 * determined the actions for the URL. The HTTP command is now
412 * *always* re-built so the repairs need no longer be special-cased.
414 * filter_popups now gets a csp pointer so it can raise the new
415 * CSP_FLAG_MODIFIED flag.
419 * Added configurable size limit for the IOB. If the IOB grows so
420 * large that the next read would exceed the limit, the header
421 * is generated, and the header & unfiltered buffer are flushed
422 * to the client. Chat then continues in non-buffering,
423 * non-filtering body mode.
425 * Revision 1.44 2001/10/02 18:13:57 oes
428 * Revision 1.43 2001/10/02 15:32:13 oes
429 * Moved generation of hdr
431 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
432 * Cleaning up 2 compiler warnings on OS/2.
434 * Revision 1.41 2001/09/16 17:05:14 jongfoster
435 * Removing unused #include showarg.h
437 * Revision 1.40 2001/09/16 15:41:45 jongfoster
438 * Fixing signed/unsigned comparison warning.
440 * Revision 1.39 2001/09/16 13:21:27 jongfoster
441 * Changes to use new list functions.
443 * Revision 1.38 2001/09/16 13:01:46 jongfoster
444 * Removing redundant function call that zeroed zalloc()'d memory.
446 * Revision 1.37 2001/09/10 11:12:24 oes
447 * Deleted unused variable
449 * Revision 1.36 2001/09/10 10:56:15 oes
450 * Silenced compiler warnings
452 * Revision 1.35 2001/07/31 14:44:22 oes
453 * Deleted unused size parameter from filter_popups()
455 * Revision 1.34 2001/07/30 22:08:36 jongfoster
456 * Tidying up #defines:
457 * - All feature #defines are now of the form FEATURE_xxx
458 * - Permanently turned off WIN_GUI_EDIT
459 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
461 * Revision 1.33 2001/07/29 19:32:00 jongfoster
462 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
464 * Revision 1.32 2001/07/29 18:47:05 jongfoster
465 * Adding missing #include "loadcfg.h"
467 * Revision 1.31 2001/07/29 12:17:48 oes
468 * Applied pthread fix by Paul Lieverse
470 * Revision 1.30 2001/07/25 22:57:13 jongfoster
471 * __BEOS__ no longer overrides FEATURE_PTHREAD.
472 * This is because FEATURE_PTHREAD will soon be widely used, so I
473 * want to keep it simple.
475 * Revision 1.29 2001/07/24 12:47:06 oes
476 * Applied BeOS support update by Eugenia
478 * Revision 1.28 2001/07/23 13:26:12 oes
479 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
481 * Revision 1.27 2001/07/19 19:09:47 haroon
482 * - Added code to take care of the situation where while processing the first
483 * server response (which includes the server header), after finding the end
484 * of the headers we were not looking past the end of the headers for
485 * content modification. I enabled it for filter_popups.
486 * Someone else should look to see if other similar operations should be
487 * done to the discarded portion of the buffer.
489 * Note 2001/07/20: No, the other content modification mechanisms will process
490 * the whole iob later anyway. --oes
492 * Revision 1.26 2001/07/18 12:31:36 oes
495 * Revision 1.25 2001/07/15 19:43:49 jongfoster
496 * Supports POSIX threads.
497 * Also removed some unused #includes.
499 * Revision 1.24 2001/07/13 14:00:40 oes
500 * - Generic content modification scheme:
501 * Each feature has its own applicability flag that is set
502 * from csp->action->flags.
503 * Replaced the "filtering" int flag , by a function pointer
504 * "content_filter" to the function that will do the content
505 * modification. If it is != NULL, the document will be buffered
506 * and processed through *content_filter, which must set
507 * csp->content_length and return a modified copy of the body
508 * or return NULL (on failiure).
509 * - Changed csp->is_text to the more generic bitmap csp->content_type
510 * which can currently take the valued CT_TEXT or CT_GIF
512 * - Removed all #ifdef PCRS
514 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
515 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
516 * the `block_acl' call. This prevents a compilation error when the user
517 * does not wish to use the "ACL" feature.
519 * Revision 1.22 2001/06/29 21:45:41 oes
520 * Indentation, CRLF->LF, Tab-> Space
522 * Revision 1.21 2001/06/29 13:29:36 oes
523 * - Cleaned up, improved comments
524 * - Unified all possible interceptors (CGI,
525 * block, trust, fast_redirect) in one
526 * place, with one (CGI) answer generation
527 * mechansim. Much clearer now.
528 * - Removed the GIF image generation, which
529 * is now done in filters.c:block_url()
530 * - Made error conditions like domain lookup
531 * failiure or (various) problems while talking
532 * to the server use cgi.c:error_response()
533 * instead of generating HTML/HTTP in chat() (yuck!)
534 * - Removed logentry from cancelled commit
536 * Revision 1.20 2001/06/09 10:55:28 jongfoster
537 * Changing BUFSIZ ==> BUFFER_SIZE
539 * Revision 1.19 2001/06/07 23:12:52 jongfoster
540 * Replacing function pointer in struct gateway with a directly
541 * called function forwarded_connect().
542 * Replacing struct gateway with struct forward_spec
544 * Revision 1.18 2001/06/03 19:12:16 oes
545 * introduced new cgi handling
547 * Revision 1.17 2001/06/01 20:07:23 jongfoster
548 * Now uses action +image-blocker{} rather than config->tinygif
550 * Revision 1.16 2001/06/01 18:49:17 jongfoster
551 * Replaced "list_share" with "list" - the tiny memory gain was not
552 * worth the extra complexity.
554 * Revision 1.15 2001/05/31 21:24:47 jongfoster
555 * Changed "permission" to "action" throughout.
556 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
557 * Moved vanilla wafer check into chat(), since we must now
558 * decide whether or not to add it based on the URL.
560 * Revision 1.14 2001/05/29 20:14:01 joergs
561 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
564 * Revision 1.13 2001/05/29 09:50:24 jongfoster
565 * Unified blocklist/imagelist/permissionslist.
566 * File format is still under discussion, but the internal changes
569 * Also modified interceptor behaviour:
570 * - We now intercept all URLs beginning with one of the following
571 * prefixes (and *only* these prefixes):
573 * * http://ijbswa.sf.net/config/
574 * * http://ijbswa.sourceforge.net/config/
575 * - New interceptors "home page" - go to http://i.j.b/ to see it.
576 * - Internal changes so that intercepted and fast redirect pages
577 * are not replaced with an image.
578 * - Interceptors now have the option to send a binary page direct
579 * to the client. (i.e. ijb-send-banner uses this)
580 * - Implemented show-url-info interceptor. (Which is why I needed
581 * the above interceptors changes - a typical URL is
582 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
583 * The previous mechanism would not have intercepted that, and
584 * if it had been intercepted then it then it would have replaced
587 * Revision 1.12 2001/05/27 22:17:04 oes
589 * - re_process_buffer no longer writes the modified buffer
590 * to the client, which was very ugly. It now returns the
591 * buffer, which it is then written by chat.
593 * - content_length now adjusts the Content-Length: header
594 * for modified documents rather than crunch()ing it.
595 * (Length info in csp->content_length, which is 0 for
596 * unmodified documents)
598 * - For this to work, sed() is called twice when filtering.
600 * Revision 1.11 2001/05/26 17:27:53 jongfoster
601 * Added support for CLF and fixed LOG_LEVEL_LOG.
602 * Also did CRLF->LF fix of my previous patch.
604 * Revision 1.10 2001/05/26 15:26:15 jongfoster
605 * ACL feature now provides more security by immediately dropping
606 * connections from untrusted hosts.
608 * Revision 1.9 2001/05/26 00:28:36 jongfoster
609 * Automatic reloading of config file.
610 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
611 * Most of the global variables have been moved to a new
612 * struct configuration_spec, accessed through csp->config->globalname
613 * Most of the globals remaining are used by the Win32 GUI.
615 * Revision 1.8 2001/05/25 22:43:18 jongfoster
616 * Fixing minor memory leak and buffer overflow.
618 * Revision 1.7 2001/05/25 22:34:30 jongfoster
621 * Revision 1.6 2001/05/23 00:13:58 joergs
622 * AmigaOS support fixed.
624 * Revision 1.5 2001/05/22 18:46:04 oes
626 * - Enabled filtering banners by size rather than URL
627 * by adding patterns that replace all standard banner
628 * sizes with the "Junkbuster" gif to the re_filterfile
630 * - Enabled filtering WebBugs by providing a pattern
631 * which kills all 1x1 images
633 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
634 * which is selected by the (nonstandard and therefore
635 * capital) letter 'U' in the option string.
636 * It causes the quantifiers to be ungreedy by default.
637 * Appending a ? turns back to greedy (!).
639 * - Added a new interceptor ijb-send-banner, which
640 * sends back the "Junkbuster" gif. Without imagelist or
641 * MSIE detection support, or if tinygif = 1, or the
642 * URL isn't recognized as an imageurl, a lame HTML
643 * explanation is sent instead.
645 * - Added new feature, which permits blocking remote
646 * script redirects and firing back a local redirect
648 * The feature is conditionally compiled, i.e. it
649 * can be disabled with --disable-fast-redirects,
650 * plus it must be activated by a "fast-redirects"
651 * line in the config file, has its own log level
652 * and of course wants to be displayed by show-proxy-args
653 * Note: Boy, all the #ifdefs in 1001 locations and
654 * all the fumbling with configure.in and acconfig.h
655 * were *way* more work than the feature itself :-(
657 * - Because a generic redirect template was needed for
658 * this, tinygif = 3 now uses the same.
660 * - Moved GIFs, and other static HTTP response templates
665 * - Removed some >400 CRs again (Jon, you really worked
668 * Revision 1.4 2001/05/21 19:34:01 jongfoster
669 * Made failure to bind() a fatal error.
671 * Revision 1.3 2001/05/20 01:21:20 jongfoster
672 * Version 2.9.4 checkin.
673 * - Merged popupfile and cookiefile, and added control over PCRS
674 * filtering, in new "permissionsfile".
675 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
676 * file error you now get a message box (in the Win32 GUI) rather
677 * than the program exiting with no explanation.
678 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
680 * - Removed tabs from "config"
681 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
682 * - Bumped up version number.
684 * Revision 1.2 2001/05/17 22:34:44 oes
685 * - Added hint on GIF char array generation to jcc.c
686 * - Cleaned CRLF's from the sources and related files
687 * - Repaired logging for REF and FRC
689 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
690 * Initial import of version 2.9.3 source tree
693 *********************************************************************/
699 #include <sys/types.h>
707 # ifndef FEATURE_PTHREAD
711 # include <windows.h>
712 # include <process.h>
713 # endif /* ndef FEATURE_PTHREAD */
716 # ifndef _WIN_CONSOLE
718 # endif /* ndef _WIN_CONSOLE */
719 # include "w32svrapi.h"
721 #else /* ifndef _WIN32 */
723 # if !defined (__OS2__)
725 # include <sys/wait.h>
726 # endif /* ndef __OS2__ */
727 # include <sys/time.h>
728 # include <sys/stat.h>
729 # include <sys/ioctl.h>
732 #include <sys/termios.h>
743 # include <socket.h> /* BeOS has select() for sockets only. */
744 # include <OS.h> /* declarations for threads and stuff. */
747 # if defined(__EMX__) || defined(__OS2__)
748 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
753 #define bzero(B,N) memset(B,0x00,n)
768 #include "killpopup.h"
769 #include "miscutil.h"
771 #include "jbsockets.h"
776 #include "urlmatch.h"
778 const char jcc_h_rcs[] = JCC_H_VERSION;
779 const char project_h_rcs[] = PROJECT_H_VERSION;
782 struct client_state clients[1];
783 struct file_list files[1];
785 #ifdef FEATURE_STATISTICS
786 int urls_read = 0; /* total nr of urls read inc rejected */
787 int urls_rejected = 0; /* total nr of urls rejected */
788 #endif /* def FEATURE_STATISTICS */
790 #ifdef FEATURE_GRACEFUL_TERMINATION
794 static void listen_loop(void);
795 static void chat(struct client_state *csp);
797 void serve(struct client_state *csp);
798 #else /* ifndef AMIGA */
799 static void serve(struct client_state *csp);
800 #endif /* def AMIGA */
803 static int32 server_thread(void *data);
804 #endif /* def __BEOS__ */
807 #define sleep(N) Sleep(((N) * 1000))
811 #define sleep(N) DosSleep(((N) * 100))
814 #ifdef FEATURE_PTHREAD
815 pthread_mutex_t log_mutex;
816 pthread_mutex_t log_init_mutex;
818 #ifndef HAVE_GMTIME_R
819 pthread_mutex_t gmtime_mutex;
820 #endif /* ndef HAVE_GMTIME_R */
822 #ifndef HAVE_LOCALTIME_R
823 pthread_mutex_t localtime_mutex;
824 #endif /* ndef HAVE_GMTIME_R */
826 #ifndef HAVE_GETHOSTBYADDR_R
827 pthread_mutex_t gethostbyaddr_mutex;
828 #endif /* ndef HAVE_GETHOSTBYADDR_R */
830 #ifndef HAVE_GETHOSTBYNAME_R
831 pthread_mutex_t gethostbyname_mutex;
832 #endif /* ndef HAVE_GETHOSTBYNAME_R */
833 #endif /* FEATURE_PTHREAD */
835 #if defined(unix) || defined(__EMX__)
836 const char *basedir = NULL;
837 const char *pidfile = NULL;
838 int received_hup_signal = 0;
839 #endif /* defined unix */
841 /* The vanilla wafer. */
842 static const char VANILLA_WAFER[] =
843 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
844 "Do_not_send_me_any_copyrighted_information_other_than_the_"
845 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
846 "In_particular_do_not_send_me_any_cookies_that_"
847 "are_subject_to_a_claim_of_copyright_by_anybody._"
848 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
849 "(copyright_or_otherwise)_applying_to_any_cookie._";
851 /* HTTP snipplets. */
852 static const char CSUCCEED[] =
853 "HTTP/1.0 200 Connection established\n"
854 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
856 static const char CHEADER[] =
857 "HTTP/1.0 400 Invalid header received from browser\r\n"
858 "Connection: close\r\n\r\n"
859 "Invalid header received from browser.";
861 static const char CFORBIDDEN[] =
862 "HTTP/1.0 403 Connection not allowable\r\n"
863 "X-Hint: If you read this message interactively, then you know why this happens ,-)\r\n"
864 "Connection: close\r\n\r\n";
866 static const char FTP_RESPONSE[] =
867 "HTTP/1.0 400 Invalid request received from browser\r\n"
868 "Connection: close\r\n\r\n"
869 "Invalid request. Privoxy doesn't support FTP.\r\n";
871 static const char GOPHER_RESPONSE[] =
872 "HTTP/1.0 400 Invalid request received from browser\r\n"
873 "Connection: close\r\n\r\n"
874 "Invalid request. Privoxy doesn't support gopher.\r\n";
876 static const char MISSING_DESTINATION_RESPONSE[] =
877 "HTTP/1.0 400 Bad request received from browser\r\n"
878 "Connection: close\r\n\r\n"
879 "Bad request. Privoxy was unable to extract the destination.\r\n";
882 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
883 /*********************************************************************
885 * Function : sig_handler
887 * Description : Signal handler for different signals.
888 * Exit gracefully on ABRT, TERM and INT
889 * or set a flag that will cause the errlog
890 * to be reopened by the main thread on HUP.
893 * 1 : the_signal = the signal cause this function to call
897 *********************************************************************/
898 static void sig_handler(int the_signal)
905 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
916 received_hup_signal = 1;
921 * We shouldn't be here, unless we catch signals
922 * in main() that we can't handle here!
924 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
932 /*********************************************************************
936 * Description : Once a connection to the client has been accepted,
937 * this function is called (via serve()) to handle the
938 * main business of the communication. When this
939 * function returns, the caller must close the client
943 * 1 : csp = Current client state (buffers, headers, etc...)
945 * Returns : On success, the number of bytes written are returned (zero
946 * indicates nothing was written). On error, -1 is returned,
947 * and errno is set appropriately. If count is zero and the
948 * file descriptor refers to a regular file, 0 will be
949 * returned without causing any other effect. For a special
950 * file, the results are not portable.
952 *********************************************************************/
953 static void chat(struct client_state *csp)
956 * This next lines are a little ugly, but they simplifies the if statements
957 * below. Basically if TOGGLE, then we want the if to test if the
958 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
959 * then we want the if to test for CSP_FLAG_FORCED , else we don't
961 #ifdef FEATURE_TOGGLE
962 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
963 #else /* ifndef FEATURE_TOGGLE */
964 # define IS_TOGGLED_ON_AND
965 #endif /* ndef FEATURE_TOGGLE */
966 #ifdef FEATURE_FORCE_LOAD
967 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
968 #else /* ifndef FEATURE_FORCE_LOAD */
969 # define IS_NOT_FORCED_AND
970 #endif /* def FEATURE_FORCE_LOAD */
972 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
974 char buf[BUFFER_SIZE];
982 int ms_iis5_hack = 0;
984 unsigned int forwarded_connect_retries = 0;
985 unsigned int max_forwarded_connect_retries = csp->config->forwarded_connect_retries;
986 const struct forward_spec * fwd;
987 struct http_request *http;
988 int len; /* for buffer sizes */
989 #ifdef FEATURE_KILL_POPUPS
990 int block_popups; /* bool, 1==will block popups */
991 int block_popups_now = 0; /* bool, 1==currently blocking popups */
992 #endif /* def FEATURE_KILL_POPUPS */
994 int pcrs_filter; /* bool, 1==will filter through pcrs */
995 int gif_deanimate; /* bool, 1==will deanimate gifs */
996 int jpeg_inspect; /* bool, 1==will inspect jpegs */
998 /* Function that does the content filtering for the current request */
999 char *(*content_filter)() = NULL;
1001 /* Skeleton for HTTP response, if we should intercept the request */
1002 struct http_response *rsp;
1004 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1005 struct list header_list;
1006 struct list *headers = &header_list;
1011 * Read the client's request. Note that since we're not using select() we
1012 * could get blocked here if a client connected, then didn't say anything!
1017 len = read_socket(csp->cfd, buf, sizeof(buf));
1019 if (len <= 0) break; /* error! */
1022 * If there is no memory left for buffering the
1023 * request, there is nothing we can do but hang up
1025 if (add_to_iob(csp, buf, len))
1030 req = get_header(csp);
1034 break; /* no HTTP request! */
1039 continue; /* more to come! */
1043 * If it's a FTP or gopher request, we don't support it.
1045 * These checks are better than nothing, but they might
1046 * not work in all configurations and some clients might
1047 * have problems digesting the answer.
1049 * They should, however, never cause more problems than
1050 * Privoxy's old behaviour (returning the misleading HTML error message:
1051 * "Could not resolve http://(ftp|gopher)://example.org").
1053 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
1055 if (!strncmpic(req, "GET ftp://", 10))
1057 strcpy(buf, FTP_RESPONSE);
1058 log_error(LOG_LEVEL_ERROR, "%s tried to use Privoxy as FTP proxy: %s",
1059 csp->ip_addr_str, req);
1063 strcpy(buf, GOPHER_RESPONSE);
1064 log_error(LOG_LEVEL_ERROR, "%s tried to use Privoxy as gopher proxy: %s",
1065 csp->ip_addr_str, req);
1067 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
1069 write_socket(csp->cfd, buf, strlen(buf));
1070 free_http_request(http);
1074 #ifdef FEATURE_FORCE_LOAD
1075 /* If this request contains the FORCE_PREFIX,
1076 * better get rid of it now and set the force flag --oes
1079 if (strstr(req, FORCE_PREFIX))
1081 strclean(req, FORCE_PREFIX);
1082 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
1083 csp->flags |= CSP_FLAG_FORCED;
1086 #endif /* def FEATURE_FORCE_LOAD */
1088 switch( parse_http_request(req, http, csp) )
1091 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing request.");
1094 log_error(LOG_LEVEL_ERROR, "Couldn't parse request: %s.", req);
1102 if (http->cmd == NULL)
1104 strcpy(buf, CHEADER);
1105 write_socket(csp->cfd, buf, strlen(buf));
1107 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
1109 free_http_request(http);
1113 /* grab the rest of the client's headers */
1117 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
1119 len = read_socket(csp->cfd, buf, sizeof(buf));
1122 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1127 * If there is no memory left for buffering the
1128 * request, there is nothing we can do but hang up
1130 if (add_to_iob(csp, buf, len))
1137 if (p == NULL) break;
1144 if (http->host == NULL)
1147 * Intercepted or invalid request without domain
1148 * inside the request line. Try to get it another way.
1150 if (JB_ERR_OK == get_destination_from_headers(headers, http))
1152 /* Split the domain we just got for pattern matching */
1153 init_domain_components(http);
1157 /* We can't work without destination. Go spread the news.*/
1159 req = list_to_text(headers);
1161 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, http->cmd);
1162 log_error(LOG_LEVEL_ERROR,
1163 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
1164 csp->ip_addr_str, http->cmd, req);
1167 strcpy(buf, MISSING_DESTINATION_RESPONSE);
1168 write_socket(csp->cfd, buf, strlen(buf));
1169 free_http_request(http);
1170 destroy_list(headers);
1174 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
1175 * to get the destination IP address, use it as host directly
1176 * or do a reverse DNS lookup first.
1180 /* decide how to route the HTTP request */
1182 if ((fwd = forward_url(http, csp)) == NULL)
1184 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1185 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1188 /* build the http request to send to the server
1189 * we have to do one of the following:
1191 * create = use the original HTTP request to create a new
1192 * HTTP request that has either the path component
1193 * without the http://domainspec (w/path) or the
1194 * full orininal URL (w/url)
1195 * Note that the path and/or the HTTP version may
1196 * have been altered by now.
1198 * connect = Open a socket to the host:port of the server
1199 * and short-circuit server and client socket.
1201 * pass = Pass the request unchanged if forwarding a CONNECT
1202 * request to a parent proxy. Note that we'll be sending
1203 * the CFAIL message ourselves if connecting to the parent
1204 * fails, but we won't send a CSUCCEED message if it works,
1205 * since that would result in a double message (ours and the
1206 * parent's). After sending the request to the parent, we simply
1209 * here's the matrix:
1212 * +--------+--------+
1214 * 0 | create | connect|
1216 * Forwarding +--------+--------+
1218 * 1 | create | pass |
1220 * +--------+--------+
1225 * Determine the actions for this URL
1227 #ifdef FEATURE_TOGGLE
1228 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1230 /* Most compatible set of actions (i.e. none) */
1231 init_current_action(csp->action);
1234 #endif /* ndef FEATURE_TOGGLE */
1236 url_actions(http, csp);
1241 * Check if a CONNECT request is allowable:
1242 * In the absence of a +limit-connect action, allow only port 443.
1243 * If there is an action, allow whatever matches the specificaton.
1247 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
1248 || (csp->action->flags & ACTION_LIMIT_CONNECT
1249 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
1251 if (csp->action->flags & ACTION_TREAT_FORBIDDEN_CONNECTS_LIKE_BLOCKS)
1253 /* The response will violate the specs, but makes unblocking easier. */
1254 log_error(LOG_LEVEL_ERROR, "Marking suspicious CONNECT request from %s for blocking.",
1256 csp->action->flags |= ACTION_BLOCK;
1261 strcpy(buf, CFORBIDDEN);
1262 write_socket(csp->cfd, buf, strlen(buf));
1263 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
1264 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
1272 * Downgrade http version from 1.1 to 1.0 if +downgrade
1275 if ( (http->ssl == 0)
1276 && (!strcmpic(http->ver, "HTTP/1.1"))
1277 && (csp->action->flags & ACTION_DOWNGRADE))
1280 http->ver = strdup("HTTP/1.0");
1282 if (http->ver == NULL)
1284 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
1289 * Save a copy of the original request for logging
1291 http->ocmd = strdup(http->cmd);
1293 if (http->ocmd == NULL)
1295 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
1299 * (Re)build the HTTP request for non-SSL requests.
1300 * If forwarding, use the whole URL, else, use only the path.
1306 http->cmd = strdup(http->gpc);
1307 string_append(&http->cmd, " ");
1309 if (fwd->forward_host)
1311 string_append(&http->cmd, http->url);
1315 string_append(&http->cmd, http->path);
1317 string_append(&http->cmd, " ");
1318 string_append(&http->cmd, http->ver);
1320 if (http->cmd == NULL)
1322 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1324 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", http->cmd);
1326 enlist(csp->headers, http->cmd);
1328 /* Append the previously read headers */
1329 list_append_list_unique(csp->headers, headers);
1330 destroy_list(headers);
1333 * If the user has not supplied any wafers, and the user has not
1334 * told us to suppress the vanilla wafer, then send the vanilla wafer.
1336 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
1337 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
1339 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
1343 #ifdef FEATURE_KILL_POPUPS
1344 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1345 #endif /* def FEATURE_KILL_POPUPS */
1347 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
1348 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1350 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1352 jpeg_inspect = ((csp->action->flags & ACTION_JPEG_INSPECT) != 0);
1355 * We have a request. Now, check to see if we need to
1356 * intercept it, i.e. If ..
1360 /* We may not forward the request by rfc2616 sect 14.31 */
1361 (NULL != (rsp = direct_response(csp)))
1363 /* or we are enabled and... */
1364 || (IS_ENABLED_AND (
1366 /* ..the request was blocked */
1367 ( NULL != (rsp = block_url(csp)))
1369 /* ..or untrusted */
1370 #ifdef FEATURE_TRUST
1371 || ( NULL != (rsp = trust_url(csp)))
1372 #endif /* def FEATURE_TRUST */
1374 /* ..or a redirect kicked in */
1375 || ( NULL != (rsp = redirect_url(csp)))
1379 * .. or a CGI call was detected and answered.
1381 * This check comes last to give the user the power
1382 * to deny acces to some (or all) of the cgi pages.
1384 || (NULL != (rsp = dispatch_cgi(csp)))
1388 /* Write the answer to the client */
1389 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1390 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1392 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1395 #ifdef FEATURE_STATISTICS
1396 /* Count as a rejected request */
1397 csp->flags |= CSP_FLAG_REJECTED;
1398 #endif /* def FEATURE_STATISTICS */
1400 /* Log (FIXME: All intercept reasons appear as "crunch" with Status 200) */
1401 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1402 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1404 /* Clean up and return */
1405 free_http_response(rsp);
1409 hdr = sed(client_patterns, add_client_headers, csp);
1412 /* FIXME Should handle error properly */
1413 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1416 list_remove_all(csp->headers);
1418 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1420 if (fwd->forward_host)
1422 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1423 fwd->forward_host, fwd->forward_port, http->hostport);
1427 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1430 /* here we connect to the server, gateway, or the forwarder */
1432 while ( (csp->sfd = forwarded_connect(fwd, http, csp))
1433 && (errno == EINVAL) && (forwarded_connect_retries++ < max_forwarded_connect_retries))
1435 log_error(LOG_LEVEL_ERROR, "failed request #%u to connect to %s. Trying again.",
1436 forwarded_connect_retries, http->hostport);
1439 if (csp->sfd == JB_INVALID_SOCKET)
1441 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1444 if (errno == EINVAL)
1446 rsp = error_response(csp, "no-such-domain", errno);
1448 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1449 csp->ip_addr_str, http->ocmd);
1453 rsp = error_response(csp, "connect-failed", errno);
1455 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1456 csp->ip_addr_str, http->ocmd);
1460 /* Write the answer to the client */
1463 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1464 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1466 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1470 free_http_response(rsp);
1475 log_error(LOG_LEVEL_CONNECT, "OK");
1477 if (fwd->forward_host || (http->ssl == 0))
1479 /* write the client's (modified) header to the server
1480 * (along with anything else that may be in the buffer)
1483 if (write_socket(csp->sfd, hdr, strlen(hdr))
1484 || (flush_socket(csp->sfd, csp) < 0))
1486 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1489 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1490 csp->ip_addr_str, http->ocmd);
1492 rsp = error_response(csp, "connect-failed", errno);
1496 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1497 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1499 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1503 free_http_response(rsp);
1511 * We're running an SSL tunnel and we're not forwarding,
1512 * so just send the "connect succeeded" message to the
1513 * client, flush the rest, and get out of the way.
1515 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1516 csp->ip_addr_str, http->ocmd);
1518 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1526 /* we're finished with the client's header */
1529 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1531 /* pass data between the client and server
1532 * until one or the other shuts down the connection.
1541 * FD_ZERO here seems to point to an errant macro which crashes.
1542 * So do this by hand for now...
1544 memset(&rfds,0x00,sizeof(fd_set));
1548 FD_SET(csp->cfd, &rfds);
1549 FD_SET(csp->sfd, &rfds);
1551 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1555 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1559 /* this is the body of the browser's request
1560 * just read it and write it.
1563 if (FD_ISSET(csp->cfd, &rfds))
1565 len = read_socket(csp->cfd, buf, sizeof(buf));
1569 break; /* "game over, man" */
1572 if (write_socket(csp->sfd, buf, (size_t)len))
1574 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1581 * The server wants to talk. It could be the header or the body.
1582 * If `hdr' is null, then it's the header otherwise it's the body.
1583 * FIXME: Does `hdr' really mean `host'? No.
1587 if (FD_ISSET(csp->sfd, &rfds))
1590 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1594 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1596 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1597 csp->ip_addr_str, http->ocmd);
1599 rsp = error_response(csp, "connect-failed", errno);
1603 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1604 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1606 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1610 free_http_response(rsp);
1614 /* Add a trailing zero. This lets filter_popups
1615 * use string operations.
1619 #ifdef FEATURE_KILL_POPUPS
1620 /* Filter the popups on this read. */
1621 if (block_popups_now)
1623 filter_popups(buf, csp);
1625 #endif /* def FEATURE_KILL_POPUPS */
1627 /* Normally, this would indicate that we've read
1628 * as much as the server has sent us and we can
1629 * close the client connection. However, Microsoft
1630 * in its wisdom has released IIS/5 with a bug that
1631 * prevents it from sending the trailing \r\n in
1632 * a 302 redirect header (and possibly other headers).
1633 * To work around this if we've haven't parsed
1634 * a full header we'll append a trailing \r\n
1635 * and see if this now generates a valid one.
1637 * This hack shouldn't have any impacts. If we've
1638 * already transmitted the header or if this is a
1639 * SSL connection, then we won't bother with this
1640 * hack. So we only work on partially received
1641 * headers. If we append a \r\n and this still
1642 * doesn't generate a valid header, then we won't
1643 * transmit anything to the client.
1648 if (server_body || http->ssl)
1651 * If we have been buffering up the document,
1652 * now is the time to apply content modification
1653 * and send the result to the client.
1658 * If the content filter fails, use the original
1659 * buffer and length.
1660 * (see p != NULL ? p : csp->iob->cur below)
1662 if (NULL == (p = (*content_filter)(csp)))
1664 csp->content_length = csp->iob->eod - csp->iob->cur;
1667 hdr = sed(server_patterns_light, NULL, csp);
1671 /* FIXME Should handle error properly */
1672 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1675 if (write_socket(csp->cfd, hdr, strlen(hdr))
1676 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1678 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1688 break; /* "game over, man" */
1692 * This is NOT the body, so
1693 * Let's pretend the server just sent us a blank line.
1695 len = sprintf(buf, "\r\n");
1698 * Now, let the normal header parsing algorithm below do its
1699 * job. If it fails, we'll exit instead of continuing.
1706 * If this is an SSL connection or we're in the body
1707 * of the server document, just write it to the client,
1708 * unless we need to buffer the body for later content-filtering
1711 if (server_body || http->ssl)
1716 * If there is no memory left for buffering the content, or the buffer limit
1717 * has been reached, switch to non-filtering mode, i.e. make & write the
1718 * header, flush the iob and buf, and get out of the way.
1720 if (add_to_iob(csp, buf, len))
1725 log_error(LOG_LEVEL_ERROR, "Flushing header and buffers. Stepping back from filtering.");
1727 hdr = sed(server_patterns, add_server_headers, csp);
1731 * Memory is too tight to even generate the header.
1732 * Send our static "Out-of-memory" page.
1734 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
1735 rsp = cgi_error_memory();
1737 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1738 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1740 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1745 hdrlen = strlen(hdr);
1747 if (write_socket(csp->cfd, hdr, hdrlen)
1748 || ((flushed = flush_socket(csp->cfd, csp)) < 0)
1749 || (write_socket(csp->cfd, buf, (size_t) len)))
1751 log_error(LOG_LEVEL_CONNECT, "Flush header and buffers to client failed: %E");
1757 byte_count += hdrlen + flushed + len;
1759 content_filter = NULL;
1766 if (write_socket(csp->cfd, buf, (size_t)len))
1768 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1777 /* we're still looking for the end of the
1778 * server's header ... (does that make header
1779 * parsing an "out of body experience" ?
1783 * buffer up the data we just read. If that fails,
1784 * there's little we can do but send our static
1785 * out-of-memory page.
1787 if (add_to_iob(csp, buf, len))
1789 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
1790 rsp = cgi_error_memory();
1792 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1793 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1795 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1800 /* get header lines from the iob */
1802 while ((p = get_header(csp)) != NULL)
1806 /* see following note */
1809 enlist(csp->headers, p);
1813 /* NOTE: there are no "empty" headers so
1814 * if the pointer `p' is not NULL we must
1815 * assume that we reached the end of the
1816 * buffer before we hit the end of the header.
1823 /* Well, we tried our MS IIS/5
1824 * hack and it didn't work.
1825 * The header is incomplete
1826 * and there isn't anything
1827 * we can do about it.
1833 /* Since we have to wait for
1834 * more from the server before
1835 * we can parse the headers
1836 * we just continue here.
1842 /* we have now received the entire header.
1843 * filter it and send the result to the client
1846 hdr = sed(server_patterns, add_server_headers, csp);
1849 /* FIXME Should handle error properly */
1850 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1853 #ifdef FEATURE_KILL_POPUPS
1854 /* Start blocking popups if appropriate. */
1856 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1857 !http->ssl && /* We talk plaintext */
1858 block_popups) /* Policy allows */
1860 block_popups_now = 1;
1862 * Filter the part of the body that came in the same read
1863 * as the last headers:
1865 filter_popups(csp->iob->cur, csp);
1868 #endif /* def FEATURE_KILL_POPUPS */
1870 /* Buffer and pcrs filter this if appropriate. */
1872 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1873 !http->ssl && /* We talk plaintext */
1874 pcrs_filter) /* Policy allows */
1876 content_filter = pcrs_filter_response;
1879 /* Buffer and gif_deanimate this if appropriate. */
1881 if ((csp->content_type & CT_GIF) && /* It's an image/gif MIME-Type */
1882 !http->ssl && /* We talk plaintext */
1883 gif_deanimate) /* Policy allows */
1885 content_filter = gif_deanimate_response;
1888 /* Buffer and jpg_inspect this if appropriate. */
1890 if ((csp->content_type & CT_JPEG) && /* It's an image/jpeg MIME-Type */
1891 !http->ssl && /* We talk plaintext */
1892 jpeg_inspect) /* Policy allows */
1894 content_filter = jpeg_inspect_response;
1898 * Only write if we're not buffering for content modification
1900 if (!content_filter)
1902 /* write the server's (modified) header to
1903 * the client (along with anything else that
1904 * may be in the buffer)
1907 if (write_socket(csp->cfd, hdr, strlen(hdr))
1908 || ((len = flush_socket(csp->cfd, csp)) < 0))
1910 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1912 /* the write failed, so don't bother
1913 * mentioning it to the client...
1914 * it probably can't hear us anyway.
1923 /* we're finished with the server's header */
1928 /* If this was a MS IIS/5 hack then it means
1929 * the server has already closed the
1930 * connection. Nothing more to read. Time
1941 return; /* huh? we should never get here */
1944 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1945 csp->ip_addr_str, http->ocmd, byte_count);
1949 /*********************************************************************
1953 * Description : This is little more than chat. We only "serve" to
1954 * to close any socket that chat may have opened.
1957 * 1 : csp = Current client state (buffers, headers, etc...)
1961 *********************************************************************/
1963 void serve(struct client_state *csp)
1964 #else /* ifndef AMIGA */
1965 static void serve(struct client_state *csp)
1966 #endif /* def AMIGA */
1969 close_socket(csp->cfd);
1971 if (csp->sfd != JB_INVALID_SOCKET)
1973 close_socket(csp->sfd);
1976 csp->flags &= ~CSP_FLAG_ACTIVE;
1982 /*********************************************************************
1984 * Function : server_thread
1986 * Description : We only exist to call `serve' in a threaded environment.
1989 * 1 : data = Current client state (buffers, headers, etc...)
1991 * Returns : Always 0.
1993 *********************************************************************/
1994 static int32 server_thread(void *data)
1996 serve((struct client_state *) data);
2003 /*********************************************************************
2007 * Description : Print usage info & exit.
2009 * Parameters : Pointer to argv[0] for identifying ourselves
2013 *********************************************************************/
2014 void usage(const char *myname)
2016 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
2018 "Usage: %s [--help] [--version] [configfile]\n"
2020 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
2022 "Aborting.\n", myname);
2029 /*********************************************************************
2033 * Description : Load the config file and start the listen loop.
2034 * This function is a lot more *sane* with the `load_config'
2035 * and `listen_loop' functions; although it stills does
2036 * a *little* too much for my taste.
2039 * 1 : argc = Number of parameters (including $0).
2040 * 2 : argv = Array of (char *)'s to the parameters.
2042 * Returns : 1 if : can't open config file, unrecognized directive,
2043 * stats requested in multi-thread mode, can't open the
2044 * log file, can't open the jar file, listen port is invalid,
2045 * any load fails, and can't bind port.
2047 * Else main never returns, the process must be signaled
2048 * to terminate execution. Or, on Windows, use the
2049 * "File", "Exit" menu option.
2051 *********************************************************************/
2053 int real_main(int argc, const char *argv[])
2055 int main(int argc, const char *argv[])
2060 unsigned int random_seed;
2061 #endif /* ifdef HAVE_RANDOM */
2063 struct passwd *pw = NULL;
2064 struct group *grp = NULL;
2073 #if !defined(_WIN32)
2081 * Parse the command line arguments
2083 while (++argc_pos < argc)
2086 /* Check to see if the service must be installed or uninstalled */
2087 if (strncmp(argv[argc_pos], "--install", 9) == 0)
2089 const char *pName = argv[argc_pos] + 9;
2092 exit( (install_service(pName)) ? 0 : 1 );
2094 else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
2096 const char *pName = argv[argc_pos] + 11;
2099 exit((uninstall_service(pName)) ? 0 : 1);
2101 else if (strcmp(argv[argc_pos], "--service" ) == 0)
2103 bRunAsService = TRUE;
2104 w32_set_service_cwd();
2105 atexit(w32_service_exit_notify);
2108 #endif /* defined(_WIN32) */
2111 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2113 if (strcmp(argv[argc_pos], "--help") == 0)
2118 else if(strcmp(argv[argc_pos], "--version") == 0)
2120 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2126 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
2131 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
2133 if (++argc_pos == argc) usage(argv[0]);
2134 pidfile = strdup(argv[argc_pos]);
2137 else if (strcmp(argv[argc_pos], "--user" ) == 0)
2139 if (++argc_pos == argc) usage(argv[argc_pos]);
2141 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
2144 if (NULL == (grp = getgrnam(p)))
2146 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
2150 if (NULL == (pw = getpwnam(argv[argc_pos])))
2152 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
2155 if (p != NULL) *--p = '\0';
2158 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
2163 #endif /* defined(unix) */
2164 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
2166 configfile = argv[argc_pos];
2169 } /* -END- while (more arguments) */
2172 if ( *configfile != '/' )
2174 char *abs_file, cwd[1024];
2176 /* make config-filename absolute here */
2177 if ( !(getcwd(cwd, sizeof(cwd))))
2179 perror("get working dir failed");
2183 if (!(basedir = strdup(cwd))
2184 || (!(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 ))))
2186 perror("malloc failed");
2189 strcpy( abs_file, basedir );
2190 strcat( abs_file, "/" );
2191 strcat( abs_file, configfile );
2192 configfile = abs_file;
2194 #endif /* defined unix */
2198 clients->next = NULL;
2202 #elif defined(_WIN32)
2206 #ifdef FEATURE_PTHREAD
2208 * Prepare global mutex semaphores
2210 pthread_mutex_init(&log_mutex,0);
2211 pthread_mutex_init(&log_init_mutex,0);
2213 #ifndef HAVE_GMTIME_R
2214 pthread_mutex_init(&gmtime_mutex,0);
2215 #endif /* ndef HAVE_GMTIME_R */
2217 #ifndef HAVE_LOCALTIME_R
2218 pthread_mutex_init(&localtime_mutex,0);
2219 #endif /* ndef HAVE_GMTIME_R */
2221 #ifndef HAVE_GETHOSTBYADDR_R
2222 pthread_mutex_init(&gethostbyaddr_mutex,0);
2223 #endif /* ndef HAVE_GETHOSTBYADDR_R */
2225 #ifndef HAVE_GETHOSTBYNAME_R
2226 pthread_mutex_init(&gethostbyname_mutex,0);
2227 #endif /* ndef HAVE_GETHOSTBYNAME_R */
2228 #endif /* FEATURE_PTHREAD */
2231 random_seed = (unsigned int)time(NULL);
2232 srandom(random_seed);
2233 #endif /* ifdef HAVE_RANDOM */
2236 * Unix signal handling
2238 * Catch the abort, interrupt and terminate signals for a graceful exit
2239 * Catch the hangup signal so the errlog can be reopened.
2240 * Ignore the broken pipe signals (FIXME: Why?)
2242 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
2245 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
2246 const int ignored_signals[] = { SIGPIPE, 0 };
2248 for (idx = 0; catched_signals[idx] != 0; idx++)
2250 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
2251 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
2253 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
2254 #endif /* ifdef sun */
2256 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
2260 for (idx = 0; ignored_signals[idx] != 0; idx++)
2262 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
2264 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
2269 #else /* ifdef _WIN32 */
2270 # ifdef _WIN_CONSOLE
2272 * We *are* in a windows console app.
2273 * Print a verbose messages about FAQ's and such
2275 printf(win32_blurb);
2276 # endif /* def _WIN_CONSOLE */
2277 #endif /* def _WIN32 */
2280 /* Initialize the CGI subsystem */
2281 cgi_init_error_messages();
2284 * If runnig on unix and without the --nodaemon
2285 * option, become a daemon. I.e. fork, detach
2286 * from tty and get process group leadership
2299 if ( pid < 0 ) /* error */
2304 else if ( pid != 0 ) /* parent */
2309 * must check for errors
2310 * child died due to missing files aso
2313 wpid = waitpid( pid, &status, WNOHANG );
2322 /* Should be more portable, but not as well tested */
2327 #else /* ndef __FreeBSD__ */
2329 #endif /* ndef __FreeBSD__ */
2330 fd = open("/dev/tty", O_RDONLY);
2333 /* no error check here */
2334 ioctl( fd, TIOCNOTTY,0 );
2338 /* FIXME: should close stderr (fd 2) here too, but the test
2340 * and load config file is done in listen_loop() and puts
2341 * some messages on stderr there.
2348 } /* -END- if (!no_daemon) */
2351 * As soon as we have written the PID file, we can switch
2352 * to the user and group ID indicated by the --user option
2358 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
2360 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
2366 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
2368 if (chroot(pw->pw_dir) < 0)
2370 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
2374 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
2377 if (setuid(pw->pw_uid))
2379 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
2383 char putenv_dummy[64];
2385 strcpy(putenv_dummy, "HOME=/");
2386 if (putenv(putenv_dummy) != 0)
2388 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
2391 snprintf(putenv_dummy, 64, "USER=%s", pw->pw_name);
2392 if (putenv(putenv_dummy) != 0)
2394 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
2400 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
2403 #endif /* defined unix */
2406 /* This will be FALSE unless the command line specified --service
2410 /* Yup, so now we must attempt to establish a connection
2411 * with the service dispatcher. This will only work if this
2412 * process was launched by the service control manager to
2413 * actually run as a service. If this isn't the case, i've
2414 * known it take around 30 seconds or so for the call to return.
2417 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
2418 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
2420 /* Service has run, and at this point is now being stopped, so just return */
2425 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
2427 /* An error occurred. Usually it's because --service was wrongly specified
2428 * and we were unable to connect to the Service Control Dispatcher because
2429 * it wasn't expecting us and is therefore not listening.
2431 * For now, just continue below to call the listen_loop function.
2434 #endif /* def _WIN32 */
2444 /*********************************************************************
2446 * Function : bind_port_helper
2448 * Description : Bind the listen port. Handles logging, and aborts
2452 * 1 : config = Privoxy configuration. Specifies port
2455 * Returns : Port that was opened.
2457 *********************************************************************/
2458 static jb_socket bind_port_helper(struct configuration_spec * config)
2463 if ( (config->haddr != NULL)
2464 && (config->haddr[0] == '1')
2465 && (config->haddr[1] == '2')
2466 && (config->haddr[2] == '7')
2467 && (config->haddr[3] == '.') )
2469 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
2472 else if (config->haddr == NULL)
2474 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
2479 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
2480 config->hport, config->haddr);
2483 result = bind_port(config->haddr, config->hport, &bfd);
2490 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2491 "There may be another Privoxy or some other "
2492 "proxy running on port %d",
2493 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
2494 config->hport, config->hport);
2497 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2498 "The hostname is not resolvable",
2499 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2502 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
2503 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2506 /* shouldn't get here */
2507 return JB_INVALID_SOCKET;
2510 config->need_bind = 0;
2517 /* Without this simple workaround we get this compiler warning from _beginthread
2518 * warning C4028: formal parameter 1 different from declaration
2520 void w32_service_listen_loop(void *p)
2524 #endif /* def _WIN32 */
2527 /*********************************************************************
2529 * Function : listen_loop
2531 * Description : bind the listen port and enter a "FOREVER" listening loop.
2537 *********************************************************************/
2538 static void listen_loop(void)
2540 struct client_state *csp = NULL;
2542 struct configuration_spec * config;
2544 config = load_config();
2546 bfd = bind_port_helper(config);
2548 #ifdef FEATURE_GRACEFUL_TERMINATION
2549 while (!g_terminate)
2554 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
2555 while (waitpid(-1, NULL, WNOHANG) > 0)
2557 /* zombie children */
2559 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2562 * Free data that was used by died threads
2568 * Re-open the errlog after HUP signal
2570 if (received_hup_signal)
2572 init_error_log(Argv[0], config->logfile, config->debug);
2573 received_hup_signal = 0;
2578 #ifdef FEATURE_COOKIE_JAR
2580 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
2581 * already open. I think unload_configfile() is not being run, which should do
2582 * this work. Until that can get resolved, we'll use this workaround.
2586 if (csp->config->jar)
2588 fclose(csp->config->jar);
2589 csp->config->jar = NULL;
2591 #endif /* FEATURE_COOKIE_JAR */
2592 #endif /* __OS2__ */
2594 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2596 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2600 csp->flags |= CSP_FLAG_ACTIVE;
2601 csp->sfd = JB_INVALID_SOCKET;
2603 csp->config = config = load_config();
2605 if ( config->need_bind )
2608 * Since we were listening to the "old port", we will not see
2609 * a "listen" param change until the next IJB request. So, at
2610 * least 1 more request must be made for us to find the new
2611 * setting. I am simply closing the old socket and binding the
2614 * Which-ever is correct, we will serve 1 more page via the
2615 * old settings. This should probably be a "show-proxy-args"
2616 * request. This should not be a so common of an operation
2617 * that this will hurt people's feelings.
2622 bfd = bind_port_helper(config);
2625 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2627 if (!accept_connection(csp, bfd))
2629 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2642 log_error(LOG_LEVEL_CONNECT, "OK");
2645 #ifdef FEATURE_TOGGLE
2646 if (global_toggle_state)
2648 csp->flags |= CSP_FLAG_TOGGLED_ON;
2650 #endif /* def FEATURE_TOGGLE */
2652 if (run_loader(csp))
2654 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2655 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2659 if (block_acl(NULL,csp))
2661 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2662 close_socket(csp->cfd);
2666 #endif /* def FEATURE_ACL */
2668 /* add it to the list of clients */
2669 csp->next = clients->next;
2670 clients->next = csp;
2672 if (config->multi_threaded)
2676 /* this is a switch () statment in the C preprocessor - ugh */
2677 #undef SELECTED_ONE_OPTION
2679 /* Use Pthreads in preference to native code */
2680 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2681 #define SELECTED_ONE_OPTION
2683 pthread_t the_thread;
2684 pthread_attr_t attrs;
2686 pthread_attr_init(&attrs);
2687 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2688 errno = pthread_create(&the_thread, &attrs,
2690 child_id = errno ? -1 : 0;
2691 pthread_attr_destroy(&attrs);
2695 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2696 #define SELECTED_ONE_OPTION
2697 child_id = _beginthread(
2698 (void (*)(void *))serve,
2703 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2704 #define SELECTED_ONE_OPTION
2705 child_id = _beginthread(
2706 (void(* _Optlink)(void*))serve,
2712 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2713 #define SELECTED_ONE_OPTION
2715 thread_id tid = spawn_thread
2716 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2718 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2720 child_id = (int) tid;
2729 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2730 #define SELECTED_ONE_OPTION
2731 csp->cfd = ReleaseSocket(csp->cfd, -1);
2733 if((child_id = (int)CreateNewProcTags(
2734 NP_Entry, (ULONG)server_thread,
2735 NP_Output, Output(),
2736 NP_CloseOutput, FALSE,
2737 NP_Name, (ULONG)"privoxy child",
2738 NP_StackSize, 200*1024,
2742 ((struct Task *)child_id)->tc_UserData = csp;
2743 Signal((struct Task *)child_id, SIGF_SINGLE);
2748 #if !defined(SELECTED_ONE_OPTION)
2751 /* This block is only needed when using fork().
2752 * When using threads, the server thread was
2753 * created and run by the call to _beginthread().
2755 if (child_id == 0) /* child */
2758 #ifdef FEATURE_TOGGLE
2759 int inherited_toggle_state = global_toggle_state;
2760 #endif /* def FEATURE_TOGGLE */
2765 * If we've been toggled or we've blocked the request, tell Mom
2768 #ifdef FEATURE_TOGGLE
2769 if (inherited_toggle_state != global_toggle_state)
2771 rc |= RC_FLAG_TOGGLED;
2773 #endif /* def FEATURE_TOGGLE */
2775 #ifdef FEATURE_STATISTICS
2776 if (csp->flags & CSP_FLAG_REJECTED)
2778 rc |= RC_FLAG_BLOCKED;
2780 #endif /* ndef FEATURE_STATISTICS */
2784 else if (child_id > 0) /* parent */
2786 /* in a fork()'d environment, the parent's
2787 * copy of the client socket and the CSP
2791 #if !defined(_WIN32) && !defined(__CYGWIN__)
2793 wait( &child_status );
2796 * Evaluate child's return code: If the child has
2797 * - been toggled, toggle ourselves
2798 * - blocked its request, bump up the stats counter
2801 #ifdef FEATURE_TOGGLE
2802 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
2804 global_toggle_state = !global_toggle_state;
2806 #endif /* def FEATURE_TOGGLE */
2808 #ifdef FEATURE_STATISTICS
2810 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
2814 #endif /* def FEATURE_STATISTICS */
2816 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2817 close_socket(csp->cfd);
2818 csp->flags &= ~CSP_FLAG_ACTIVE;
2822 #undef SELECTED_ONE_OPTION
2823 /* end of cpp switch () */
2825 if (child_id < 0) /* failed */
2827 char buf[BUFFER_SIZE];
2829 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2831 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
2833 write_socket(csp->cfd, buf, strlen(buf));
2834 close_socket(csp->cfd);
2835 csp->flags &= ~CSP_FLAG_ACTIVE;
2846 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2848 /* Clean up. Aim: free all memory (no leaks) */
2849 #ifdef FEATURE_GRACEFUL_TERMINATION
2851 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2853 unload_current_config_file();
2854 unload_current_actions_file();
2855 unload_current_re_filterfile();
2856 #ifdef FEATURE_TRUST
2857 unload_current_trust_file();
2860 if (config->multi_threaded)
2867 } while ((clients->next != NULL) && (--i > 0));
2871 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2882 #ifdef FEATURE_COOKIE_JAR
2883 if (NULL != config->jar)
2885 fclose(config->jar);
2889 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2890 /* Cleanup - remove taskbar icon etc. */
2895 #endif /* FEATURE_GRACEFUL_TERMINATION */