1 const char jcc_rcs[] = "$Id: jcc.c,v 1.112 2006/12/26 17:31:41 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.112 2006/12/26 17:31:41 fabiankeil
37 * Mutex protect rand() if POSIX threading
38 * is used, warn the user if that's not possible
39 * and stop using it on _WIN32 where it could
42 * Revision 1.111 2006/12/23 16:15:06 fabiankeil
43 * Don't prevent core dumps by catching SIGABRT.
44 * It's rude and makes debugging unreasonable painful.
46 * Revision 1.110 2006/12/13 14:52:53 etresoft
47 * Fix build failure on MacOS X. Global symbols can be either static or extern, but not both.
49 * Revision 1.109 2006/12/06 19:41:40 fabiankeil
50 * Privoxy is now able to run as intercepting
51 * proxy in combination with any packet filter
52 * that does the port redirection. The destination
53 * is extracted from the "Host:" header which
54 * should be available for nearly all requests.
56 * Moved HTTP snipplets into jcc.c.
57 * Added error message for gopher proxy requests.
59 * Revision 1.108 2006/11/28 15:38:51 fabiankeil
60 * Only unlink the pidfile if it's actually used.
62 * Change order of interception checks to make
63 * it possible to block or redirect requests for
66 * Revision 1.107 2006/11/13 19:05:51 fabiankeil
67 * Make pthread mutex locking more generic. Instead of
68 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
69 * and use mutex locking unless there is an _r function
70 * available. Better safe than sorry.
72 * Fixes "./configure --disable-pthread" and should result
73 * in less threading-related problems on pthread-using platforms,
74 * but it still doesn't fix BR#1122404.
76 * Revision 1.106 2006/11/06 19:58:23 fabiankeil
77 * Move pthread.h inclusion from jcc.c to jcc.h.
78 * Fixes build on x86-freebsd1 (FreeBSD 5.4-RELEASE).
80 * Revision 1.105 2006/11/06 14:26:02 fabiankeil
81 * Don't exit after receiving the second SIGHUP on Solaris.
83 * Fixes BR 1052235, but the same problem may exist on other
84 * systems. Once 3.0.6 is out we should use sigset()
85 * where available and see if it breaks anything.
87 * Revision 1.104 2006/09/23 13:26:38 roro
88 * Replace TABs by spaces in source code.
90 * Revision 1.103 2006/09/21 12:54:43 fabiankeil
91 * Fix +redirect{}. Didn't work with -fast-redirects.
93 * Revision 1.102 2006/09/06 13:03:04 fabiankeil
94 * Respond with 400 and a short text message
95 * if the client tries to use Privoxy as FTP proxy.
97 * Revision 1.101 2006/09/06 09:23:37 fabiankeil
98 * Make number of retries in case of forwarded-connect problems
99 * a config file option (forwarded-connect-retries) and use 0 as
102 * Revision 1.100 2006/09/03 19:42:59 fabiankeil
103 * Set random(3) seed.
105 * Revision 1.99 2006/09/02 15:36:42 fabiankeil
106 * Follow the OpenBSD port's lead and protect the resolve
107 * functions on OpenBSD as well.
109 * Revision 1.98 2006/08/24 11:01:34 fabiankeil
110 * --user fix. Only use the user as group if no group is specified.
111 * Solves BR 1492612. Thanks to Spinor S. and David Laight.
113 * Revision 1.97 2006/08/18 15:23:17 david__schmidt
114 * Windows service (re-)integration
118 * --install[:service_name]
119 * --uninstall[:service_name]
122 * They work as follows:
123 * --install will create a service for you and then terminate.
124 * By default the service name will be "privoxy" (without the quotes).
125 * However you can run multiple services if you wish, just by adding
126 * a colon and then a name (no spaces).
128 * --uninstall follows the exact same rules a --install.
130 * --service is used when the program is executed by the service
131 * control manager, and in normal circumstances would never be
132 * used as a command line argument.
134 * Revision 1.96 2006/08/15 20:12:36 david__schmidt
135 * Windows service integration
137 * Revision 1.95 2006/08/03 02:46:41 david__schmidt
138 * Incorporate Fabian Keil's patch work:
139 http://www.fabiankeil.de/sourcecode/privoxy/
141 * Revision 1.94 2006/07/18 14:48:46 david__schmidt
142 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
143 * with what was really the latest development (the v_3_0_branch branch)
145 * Revision 1.92.2.16 2005/04/03 20:10:50 david__schmidt
146 * Thanks to Jindrich Makovicka for a race condition fix for the log
147 * file. The race condition remains for non-pthread implementations.
148 * Reference patch #1175720.
150 * Revision 1.92.2.15 2004/10/03 12:53:32 david__schmidt
151 * Add the ability to check jpeg images for invalid
152 * lengths of comment blocks. Defensive strategy
153 * against the exploit:
154 * Microsoft Security Bulletin MS04-028
155 * Buffer Overrun in JPEG Processing (GDI+) Could
156 * Allow Code Execution (833987)
157 * Enabled with +inspect-jpegs in actions files.
159 * Revision 1.92.2.14 2003/12/12 12:52:53 oes
160 * - Fixed usage info for non-unix platforms
161 * - Fixed small cmdline parsing bug
163 * Revision 1.92.2.13 2003/11/27 19:20:27 oes
164 * Diagnostics: Now preserve the returncode of pthread_create
165 * in errno. Closes BR #775721. Thanks to Geoffrey Hausheer.
167 * Revision 1.92.2.12 2003/07/11 11:34:19 oes
168 * No longer ignore SIGCHLD. Fixes bug #769381
170 * Revision 1.92.2.11 2003/05/14 12:32:02 oes
171 * Close jarfile on graceful exit, remove stray line
173 * Revision 1.92.2.10 2003/05/08 15:13:46 oes
174 * Cosmetics: Killed a warning, a typo and an allocation left at exit
176 * Revision 1.92.2.9 2003/04/03 15:08:42 oes
177 * No longer rely on non-POSIX.1 extensions of getcwd().
180 * Revision 1.92.2.8 2003/03/31 13:12:32 oes
181 * Replaced setenv() by posix-compliant putenv()
182 * Thanks to Neil McCalden (nmcc AT users.sf.net).
184 * Revision 1.92.2.7 2003/03/17 16:48:59 oes
185 * Added chroot ability, thanks to patch by Sviatoslav Sviridov
187 * Revision 1.92.2.6 2003/03/11 11:55:00 oes
188 * Clean-up and extension of improvements for forked mode:
189 * - Child's return code now consists of flags RC_FLAG_*
190 * - Reporting toggle to parent now properly #ifdef'ed
191 * - Children now report blocking to parent. This enables
192 * statistics in forked mode
194 * Revision 1.92.2.5 2003/03/10 23:45:32 oes
195 * Fixed bug #700381: Non-Threaded version now capable of being toggled.
196 * Children now report having been toggled through _exit(17), parents
197 * watch for that code and toggle themselves if found.
199 * Revision 1.92.2.4 2003/03/07 03:41:04 david__schmidt
200 * Wrapping all *_r functions (the non-_r versions of them) with
201 * mutex semaphores for OSX. Hopefully this will take care of all
202 * of those pesky crash reports.
204 * Revision 1.92.2.3 2003/02/28 12:53:06 oes
205 * Fixed two mostly harmless mem leaks
207 * Revision 1.92.2.2 2002/11/20 14:37:47 oes
208 * Fix: Head of global clients list now initialized to NULL
210 * Revision 1.92.2.1 2002/09/25 14:52:24 oes
211 * Added basic support for OPTIONS and TRACE HTTP methods:
212 * - New interceptor direct_response() added in chat().
213 * - sed() moved to earlier in the process, so that the
214 * Host: header is evaluated before actions and forwarding
217 * Revision 1.92 2002/05/08 16:00:46 oes
218 * Chat's buffer handling:
219 * - Fixed bug with unchecked out-of-mem conditions
220 * while reading client request & server headers
221 * - No longer predict if the buffer limit will be exceeded
222 * in the next read -- check add_to_iob's new
223 * return code. If buffer couldn't be extended
224 * (policy or out-of-mem) while
225 * - reading from client: abort
226 * - reading server headers: send error page
227 * - buffering server body for filter: flush,
228 * and if that fails: send error page
230 * Revision 1.91 2002/04/08 20:35:58 swa
233 * Revision 1.90 2002/04/02 14:57:28 oes
234 * Made sending wafers independent of FEATURE_COOKIE_JAR
236 * Revision 1.89 2002/03/31 17:18:59 jongfoster
237 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
239 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
240 * More compiler warning message maintenance
242 * Revision 1.87 2002/03/26 22:29:54 swa
243 * we have a new homepage!
245 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
246 * Workaround for closing the jarfile before load_config() comes around again
248 * Revision 1.85 2002/03/24 15:23:33 jongfoster
251 * Revision 1.84 2002/03/24 13:25:43 swa
252 * name change related issues
254 * Revision 1.83 2002/03/16 23:54:06 jongfoster
255 * Adding graceful termination feature, to help look for memory leaks.
256 * If you enable this (which, by design, has to be done by hand
257 * editing config.h) and then go to http://i.j.b/die, then the program
258 * will exit cleanly after the *next* request. It should free all the
259 * memory that was used.
261 * Revision 1.82 2002/03/13 00:27:05 jongfoster
264 * Revision 1.81 2002/03/12 01:42:50 oes
265 * Introduced modular filters
267 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
268 * OS/2 port maintenance:
269 * - Fixed EMX build - it had decayed a little
270 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
271 * substituted a memset for now.
273 * Revision 1.79 2002/03/09 20:03:52 jongfoster
274 * - Making various functions return int rather than size_t.
275 * (Undoing a recent change). Since size_t is unsigned on
276 * Windows, functions like read_socket that return -1 on
277 * error cannot return a size_t.
279 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
280 * crashes, and also frequently caused JB to jump to 100%
281 * CPU and stay there. (Because it thought it had just
282 * read ((unsigned)-1) == 4Gb of data...)
284 * - The signature of write_socket has changed, it now simply
285 * returns success=0/failure=nonzero.
287 * - Trying to get rid of a few warnings --with-debug on
288 * Windows, I've introduced a new type "jb_socket". This is
289 * used for the socket file descriptors. On Windows, this
290 * is SOCKET (a typedef for unsigned). Everywhere else, it's
291 * an int. The error value can't be -1 any more, so it's
292 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
293 * Windows it maps to the #define INVALID_SOCKET.)
295 * - The signature of bind_port has changed.
297 * Revision 1.78 2002/03/08 21:35:04 oes
298 * Added optional group supplement to --user option. Will now use default group of user if no group given
300 * Revision 1.77 2002/03/07 03:52:06 oes
301 * - Fixed compiler warnings etc
302 * - Improved handling of failed DNS lookups
304 * Revision 1.76 2002/03/06 22:54:35 jongfoster
305 * Automated function-comment nitpicking.
307 * Revision 1.75 2002/03/06 10:02:19 oes
308 * Fixed stupid bug when --user was not given
310 * Revision 1.74 2002/03/06 00:49:31 jongfoster
311 * Fixing warning on Windows
312 * Making #ifdefs that refer to the same variable consistently
313 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
315 * Revision 1.73 2002/03/05 23:57:30 hal9
316 * Stray character 's' on line 1618 was breaking build.
318 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
319 * - Re-enable OS/2 building after new parms were added
320 * - Fix false out of memory report when resolving CGI templates when no IP
321 * address is available of failed attempt (a la no such domain)
323 * Revision 1.71 2002/03/05 18:13:56 oes
324 * Added --user option
326 * Revision 1.70 2002/03/05 04:52:42 oes
327 * Deleted non-errlog debugging code
329 * Revision 1.69 2002/03/04 23:50:00 jongfoster
330 * Splitting off bind_port() call into bind_port_helper(), with
333 * Revision 1.68 2002/03/04 20:17:32 oes
336 * Revision 1.67 2002/03/04 18:18:57 oes
337 * - Removed _DEBUG mode
338 * - Cleand up cmdline parsing
339 * - Introduced --no-daemon, --pidfile options
340 * - Cleaned up signal handling:
341 * - Terminate cleanly on INT, TERM and ABRT
342 * - Schedule logfile for re-opening on HUP
343 * - Ignore CHLD and PIPE
344 * - Leave the rest with their default handlers
345 * - Uniform handler registration
346 * - Added usage() function
347 * - Played styleguide police
349 * Revision 1.66 2002/03/03 15:06:55 oes
350 * Re-enabled automatic config reloading
352 * Revision 1.65 2002/03/03 14:49:11 oes
353 * Fixed CLF logging: Now uses client's original HTTP request
355 * Revision 1.64 2002/03/03 09:18:03 joergs
356 * Made jumbjuster work on AmigaOS again.
358 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
359 * Clean up a little CRLF unpleasantness that suddenly appeared
361 * Revision 1.62 2002/02/20 23:17:23 jongfoster
362 * Detecting some out-of memory conditions and exiting with a log message.
364 * Revision 1.61 2002/01/17 21:01:52 jongfoster
365 * Moving all our URL and URL pattern parsing code to urlmatch.c.
367 * Revision 1.60 2001/12/30 14:07:32 steudten
368 * - Add signal handling (unix)
369 * - Add SIGHUP handler (unix)
370 * - Add creation of pidfile (unix)
371 * - Add action 'top' in rc file (RH)
372 * - Add entry 'SIGNALS' to manpage
373 * - Add exit message to logfile (unix)
375 * Revision 1.59 2001/12/13 14:07:18 oes
376 * Fixed Bug: 503 error page now sent OK
378 * Revision 1.58 2001/11/30 23:37:24 jongfoster
379 * Renaming the Win32 config file to config.txt - this is almost the
380 * same as the corresponding UNIX name "config"
382 * Revision 1.57 2001/11/16 00:47:43 jongfoster
383 * Changing the tty-disconnection code to use setsid().
385 * Revision 1.56 2001/11/13 20:20:54 jongfoster
386 * Tabs->spaces, fixing a bug with missing {} around an if()
388 * Revision 1.55 2001/11/13 20:14:53 jongfoster
389 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
391 * Revision 1.54 2001/11/07 00:03:14 steudten
392 * Give reliable return value if an error
393 * occurs not just 0 with new daemon mode.
395 * Revision 1.53 2001/11/05 21:41:43 steudten
396 * Add changes to be a real daemon just for unix os.
397 * (change cwd to /, detach from controlling tty, set
398 * process group and session leader to the own process.
400 * Add some fatal-error log message for failed malloc().
401 * Add '-d' if compiled with 'configure --with-debug' to
402 * enable debug output.
404 * Revision 1.52 2001/10/26 20:11:20 jongfoster
405 * Fixing type mismatch
407 * Revision 1.51 2001/10/26 17:38:28 oes
410 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
411 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
412 * threads to call select() simultaneously. So, it's time to do a real, live,
413 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
414 * (native). Both versions will work, but using __OS2__ offers multi-threading.
416 * Revision 1.49 2001/10/23 21:41:35 jongfoster
417 * Added call to initialize the (statically-allocated of course)
418 * "out of memory" CGI response.
420 * Revision 1.48 2001/10/10 19:56:46 jongfoster
421 * Moving some code that wasn't cookie-related out of an #ifdef
424 * Revision 1.47 2001/10/10 16:44:36 oes
425 * Added CONNECT destination port limitation check
427 * Revision 1.46 2001/10/08 15:17:41 oes
428 * Re-enabled SSL forwarding
430 * Revision 1.45 2001/10/07 15:42:11 oes
431 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
433 * Moved downgrading of the HTTP version from parse_http_request to
434 * chat(), since we can't decide if it is necessary before we have
435 * determined the actions for the URL. The HTTP command is now
436 * *always* re-built so the repairs need no longer be special-cased.
438 * filter_popups now gets a csp pointer so it can raise the new
439 * CSP_FLAG_MODIFIED flag.
443 * Added configurable size limit for the IOB. If the IOB grows so
444 * large that the next read would exceed the limit, the header
445 * is generated, and the header & unfiltered buffer are flushed
446 * to the client. Chat then continues in non-buffering,
447 * non-filtering body mode.
449 * Revision 1.44 2001/10/02 18:13:57 oes
452 * Revision 1.43 2001/10/02 15:32:13 oes
453 * Moved generation of hdr
455 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
456 * Cleaning up 2 compiler warnings on OS/2.
458 * Revision 1.41 2001/09/16 17:05:14 jongfoster
459 * Removing unused #include showarg.h
461 * Revision 1.40 2001/09/16 15:41:45 jongfoster
462 * Fixing signed/unsigned comparison warning.
464 * Revision 1.39 2001/09/16 13:21:27 jongfoster
465 * Changes to use new list functions.
467 * Revision 1.38 2001/09/16 13:01:46 jongfoster
468 * Removing redundant function call that zeroed zalloc()'d memory.
470 * Revision 1.37 2001/09/10 11:12:24 oes
471 * Deleted unused variable
473 * Revision 1.36 2001/09/10 10:56:15 oes
474 * Silenced compiler warnings
476 * Revision 1.35 2001/07/31 14:44:22 oes
477 * Deleted unused size parameter from filter_popups()
479 * Revision 1.34 2001/07/30 22:08:36 jongfoster
480 * Tidying up #defines:
481 * - All feature #defines are now of the form FEATURE_xxx
482 * - Permanently turned off WIN_GUI_EDIT
483 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
485 * Revision 1.33 2001/07/29 19:32:00 jongfoster
486 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
488 * Revision 1.32 2001/07/29 18:47:05 jongfoster
489 * Adding missing #include "loadcfg.h"
491 * Revision 1.31 2001/07/29 12:17:48 oes
492 * Applied pthread fix by Paul Lieverse
494 * Revision 1.30 2001/07/25 22:57:13 jongfoster
495 * __BEOS__ no longer overrides FEATURE_PTHREAD.
496 * This is because FEATURE_PTHREAD will soon be widely used, so I
497 * want to keep it simple.
499 * Revision 1.29 2001/07/24 12:47:06 oes
500 * Applied BeOS support update by Eugenia
502 * Revision 1.28 2001/07/23 13:26:12 oes
503 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
505 * Revision 1.27 2001/07/19 19:09:47 haroon
506 * - Added code to take care of the situation where while processing the first
507 * server response (which includes the server header), after finding the end
508 * of the headers we were not looking past the end of the headers for
509 * content modification. I enabled it for filter_popups.
510 * Someone else should look to see if other similar operations should be
511 * done to the discarded portion of the buffer.
513 * Note 2001/07/20: No, the other content modification mechanisms will process
514 * the whole iob later anyway. --oes
516 * Revision 1.26 2001/07/18 12:31:36 oes
519 * Revision 1.25 2001/07/15 19:43:49 jongfoster
520 * Supports POSIX threads.
521 * Also removed some unused #includes.
523 * Revision 1.24 2001/07/13 14:00:40 oes
524 * - Generic content modification scheme:
525 * Each feature has its own applicability flag that is set
526 * from csp->action->flags.
527 * Replaced the "filtering" int flag , by a function pointer
528 * "content_filter" to the function that will do the content
529 * modification. If it is != NULL, the document will be buffered
530 * and processed through *content_filter, which must set
531 * csp->content_length and return a modified copy of the body
532 * or return NULL (on failiure).
533 * - Changed csp->is_text to the more generic bitmap csp->content_type
534 * which can currently take the valued CT_TEXT or CT_GIF
536 * - Removed all #ifdef PCRS
538 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
539 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
540 * the `block_acl' call. This prevents a compilation error when the user
541 * does not wish to use the "ACL" feature.
543 * Revision 1.22 2001/06/29 21:45:41 oes
544 * Indentation, CRLF->LF, Tab-> Space
546 * Revision 1.21 2001/06/29 13:29:36 oes
547 * - Cleaned up, improved comments
548 * - Unified all possible interceptors (CGI,
549 * block, trust, fast_redirect) in one
550 * place, with one (CGI) answer generation
551 * mechansim. Much clearer now.
552 * - Removed the GIF image generation, which
553 * is now done in filters.c:block_url()
554 * - Made error conditions like domain lookup
555 * failiure or (various) problems while talking
556 * to the server use cgi.c:error_response()
557 * instead of generating HTML/HTTP in chat() (yuck!)
558 * - Removed logentry from cancelled commit
560 * Revision 1.20 2001/06/09 10:55:28 jongfoster
561 * Changing BUFSIZ ==> BUFFER_SIZE
563 * Revision 1.19 2001/06/07 23:12:52 jongfoster
564 * Replacing function pointer in struct gateway with a directly
565 * called function forwarded_connect().
566 * Replacing struct gateway with struct forward_spec
568 * Revision 1.18 2001/06/03 19:12:16 oes
569 * introduced new cgi handling
571 * Revision 1.17 2001/06/01 20:07:23 jongfoster
572 * Now uses action +image-blocker{} rather than config->tinygif
574 * Revision 1.16 2001/06/01 18:49:17 jongfoster
575 * Replaced "list_share" with "list" - the tiny memory gain was not
576 * worth the extra complexity.
578 * Revision 1.15 2001/05/31 21:24:47 jongfoster
579 * Changed "permission" to "action" throughout.
580 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
581 * Moved vanilla wafer check into chat(), since we must now
582 * decide whether or not to add it based on the URL.
584 * Revision 1.14 2001/05/29 20:14:01 joergs
585 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
588 * Revision 1.13 2001/05/29 09:50:24 jongfoster
589 * Unified blocklist/imagelist/permissionslist.
590 * File format is still under discussion, but the internal changes
593 * Also modified interceptor behaviour:
594 * - We now intercept all URLs beginning with one of the following
595 * prefixes (and *only* these prefixes):
597 * * http://ijbswa.sf.net/config/
598 * * http://ijbswa.sourceforge.net/config/
599 * - New interceptors "home page" - go to http://i.j.b/ to see it.
600 * - Internal changes so that intercepted and fast redirect pages
601 * are not replaced with an image.
602 * - Interceptors now have the option to send a binary page direct
603 * to the client. (i.e. ijb-send-banner uses this)
604 * - Implemented show-url-info interceptor. (Which is why I needed
605 * the above interceptors changes - a typical URL is
606 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
607 * The previous mechanism would not have intercepted that, and
608 * if it had been intercepted then it then it would have replaced
611 * Revision 1.12 2001/05/27 22:17:04 oes
613 * - re_process_buffer no longer writes the modified buffer
614 * to the client, which was very ugly. It now returns the
615 * buffer, which it is then written by chat.
617 * - content_length now adjusts the Content-Length: header
618 * for modified documents rather than crunch()ing it.
619 * (Length info in csp->content_length, which is 0 for
620 * unmodified documents)
622 * - For this to work, sed() is called twice when filtering.
624 * Revision 1.11 2001/05/26 17:27:53 jongfoster
625 * Added support for CLF and fixed LOG_LEVEL_LOG.
626 * Also did CRLF->LF fix of my previous patch.
628 * Revision 1.10 2001/05/26 15:26:15 jongfoster
629 * ACL feature now provides more security by immediately dropping
630 * connections from untrusted hosts.
632 * Revision 1.9 2001/05/26 00:28:36 jongfoster
633 * Automatic reloading of config file.
634 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
635 * Most of the global variables have been moved to a new
636 * struct configuration_spec, accessed through csp->config->globalname
637 * Most of the globals remaining are used by the Win32 GUI.
639 * Revision 1.8 2001/05/25 22:43:18 jongfoster
640 * Fixing minor memory leak and buffer overflow.
642 * Revision 1.7 2001/05/25 22:34:30 jongfoster
645 * Revision 1.6 2001/05/23 00:13:58 joergs
646 * AmigaOS support fixed.
648 * Revision 1.5 2001/05/22 18:46:04 oes
650 * - Enabled filtering banners by size rather than URL
651 * by adding patterns that replace all standard banner
652 * sizes with the "Junkbuster" gif to the re_filterfile
654 * - Enabled filtering WebBugs by providing a pattern
655 * which kills all 1x1 images
657 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
658 * which is selected by the (nonstandard and therefore
659 * capital) letter 'U' in the option string.
660 * It causes the quantifiers to be ungreedy by default.
661 * Appending a ? turns back to greedy (!).
663 * - Added a new interceptor ijb-send-banner, which
664 * sends back the "Junkbuster" gif. Without imagelist or
665 * MSIE detection support, or if tinygif = 1, or the
666 * URL isn't recognized as an imageurl, a lame HTML
667 * explanation is sent instead.
669 * - Added new feature, which permits blocking remote
670 * script redirects and firing back a local redirect
672 * The feature is conditionally compiled, i.e. it
673 * can be disabled with --disable-fast-redirects,
674 * plus it must be activated by a "fast-redirects"
675 * line in the config file, has its own log level
676 * and of course wants to be displayed by show-proxy-args
677 * Note: Boy, all the #ifdefs in 1001 locations and
678 * all the fumbling with configure.in and acconfig.h
679 * were *way* more work than the feature itself :-(
681 * - Because a generic redirect template was needed for
682 * this, tinygif = 3 now uses the same.
684 * - Moved GIFs, and other static HTTP response templates
689 * - Removed some >400 CRs again (Jon, you really worked
692 * Revision 1.4 2001/05/21 19:34:01 jongfoster
693 * Made failure to bind() a fatal error.
695 * Revision 1.3 2001/05/20 01:21:20 jongfoster
696 * Version 2.9.4 checkin.
697 * - Merged popupfile and cookiefile, and added control over PCRS
698 * filtering, in new "permissionsfile".
699 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
700 * file error you now get a message box (in the Win32 GUI) rather
701 * than the program exiting with no explanation.
702 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
704 * - Removed tabs from "config"
705 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
706 * - Bumped up version number.
708 * Revision 1.2 2001/05/17 22:34:44 oes
709 * - Added hint on GIF char array generation to jcc.c
710 * - Cleaned CRLF's from the sources and related files
711 * - Repaired logging for REF and FRC
713 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
714 * Initial import of version 2.9.3 source tree
717 *********************************************************************/
723 #include <sys/types.h>
731 # ifndef FEATURE_PTHREAD
735 # include <windows.h>
736 # include <process.h>
737 # endif /* ndef FEATURE_PTHREAD */
740 # ifndef _WIN_CONSOLE
742 # endif /* ndef _WIN_CONSOLE */
743 # include "w32svrapi.h"
745 #else /* ifndef _WIN32 */
747 # if !defined (__OS2__)
749 # include <sys/wait.h>
750 # endif /* ndef __OS2__ */
751 # include <sys/time.h>
752 # include <sys/stat.h>
753 # include <sys/ioctl.h>
756 #include <sys/termios.h>
767 # include <socket.h> /* BeOS has select() for sockets only. */
768 # include <OS.h> /* declarations for threads and stuff. */
771 # if defined(__EMX__) || defined(__OS2__)
772 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
777 #define bzero(B,N) memset(B,0x00,n)
792 #include "killpopup.h"
793 #include "miscutil.h"
795 #include "jbsockets.h"
800 #include "urlmatch.h"
802 const char jcc_h_rcs[] = JCC_H_VERSION;
803 const char project_h_rcs[] = PROJECT_H_VERSION;
806 struct client_state clients[1];
807 struct file_list files[1];
809 #ifdef FEATURE_STATISTICS
810 int urls_read = 0; /* total nr of urls read inc rejected */
811 int urls_rejected = 0; /* total nr of urls rejected */
812 #endif /* def FEATURE_STATISTICS */
814 #ifdef FEATURE_GRACEFUL_TERMINATION
818 static void listen_loop(void);
819 static void chat(struct client_state *csp);
821 void serve(struct client_state *csp);
822 #else /* ifndef AMIGA */
823 static void serve(struct client_state *csp);
824 #endif /* def AMIGA */
827 static int32 server_thread(void *data);
828 #endif /* def __BEOS__ */
831 #define sleep(N) Sleep(((N) * 1000))
835 #define sleep(N) DosSleep(((N) * 100))
838 #ifdef FEATURE_PTHREAD
839 pthread_mutex_t log_mutex;
840 pthread_mutex_t log_init_mutex;
842 #ifndef HAVE_GMTIME_R
843 pthread_mutex_t gmtime_mutex;
844 #endif /* ndef HAVE_GMTIME_R */
846 #ifndef HAVE_LOCALTIME_R
847 pthread_mutex_t localtime_mutex;
848 #endif /* ndef HAVE_GMTIME_R */
850 #ifndef HAVE_GETHOSTBYADDR_R
851 pthread_mutex_t gethostbyaddr_mutex;
852 #endif /* ndef HAVE_GETHOSTBYADDR_R */
854 #ifndef HAVE_GETHOSTBYNAME_R
855 pthread_mutex_t gethostbyname_mutex;
856 #endif /* ndef HAVE_GETHOSTBYNAME_R */
859 pthread_mutex_t rand_mutex;
860 #endif /* ndef HAVE_RANDOM */
862 #endif /* FEATURE_PTHREAD */
864 #if defined(unix) || defined(__EMX__)
865 const char *basedir = NULL;
866 const char *pidfile = NULL;
867 int received_hup_signal = 0;
868 #endif /* defined unix */
870 /* The vanilla wafer. */
871 static const char VANILLA_WAFER[] =
872 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
873 "Do_not_send_me_any_copyrighted_information_other_than_the_"
874 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
875 "In_particular_do_not_send_me_any_cookies_that_"
876 "are_subject_to_a_claim_of_copyright_by_anybody._"
877 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
878 "(copyright_or_otherwise)_applying_to_any_cookie._";
880 /* HTTP snipplets. */
881 const char CSUCCEED[] =
882 "HTTP/1.0 200 Connection established\n"
883 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
885 const char CHEADER[] =
886 "HTTP/1.0 400 Invalid header received from browser\r\n"
887 "Connection: close\r\n\r\n"
888 "Invalid header received from browser.";
890 const char CFORBIDDEN[] =
891 "HTTP/1.0 403 Connection not allowable\r\n"
892 "X-Hint: If you read this message interactively, then you know why this happens ,-)\r\n"
893 "Connection: close\r\n\r\n";
895 const char FTP_RESPONSE[] =
896 "HTTP/1.0 400 Invalid request received from browser\r\n"
897 "Connection: close\r\n\r\n"
898 "Invalid request. Privoxy doesn't support FTP.\r\n";
900 const char GOPHER_RESPONSE[] =
901 "HTTP/1.0 400 Invalid request received from browser\r\n"
902 "Connection: close\r\n\r\n"
903 "Invalid request. Privoxy doesn't support gopher.\r\n";
905 const char MISSING_DESTINATION_RESPONSE[] =
906 "HTTP/1.0 400 Bad request received from browser\r\n"
907 "Connection: close\r\n\r\n"
908 "Bad request. Privoxy was unable to extract the destination.\r\n";
911 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
912 /*********************************************************************
914 * Function : sig_handler
916 * Description : Signal handler for different signals.
917 * Exit gracefully on TERM and INT
918 * or set a flag that will cause the errlog
919 * to be reopened by the main thread on HUP.
922 * 1 : the_signal = the signal cause this function to call
926 *********************************************************************/
927 static void sig_handler(int the_signal)
933 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
944 received_hup_signal = 1;
949 * We shouldn't be here, unless we catch signals
950 * in main() that we can't handle here!
952 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
960 /*********************************************************************
964 * Description : Once a connection to the client has been accepted,
965 * this function is called (via serve()) to handle the
966 * main business of the communication. When this
967 * function returns, the caller must close the client
971 * 1 : csp = Current client state (buffers, headers, etc...)
973 * Returns : On success, the number of bytes written are returned (zero
974 * indicates nothing was written). On error, -1 is returned,
975 * and errno is set appropriately. If count is zero and the
976 * file descriptor refers to a regular file, 0 will be
977 * returned without causing any other effect. For a special
978 * file, the results are not portable.
980 *********************************************************************/
981 static void chat(struct client_state *csp)
984 * This next lines are a little ugly, but they simplifies the if statements
985 * below. Basically if TOGGLE, then we want the if to test if the
986 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
987 * then we want the if to test for CSP_FLAG_FORCED , else we don't
989 #ifdef FEATURE_TOGGLE
990 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
991 #else /* ifndef FEATURE_TOGGLE */
992 # define IS_TOGGLED_ON_AND
993 #endif /* ndef FEATURE_TOGGLE */
994 #ifdef FEATURE_FORCE_LOAD
995 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
996 #else /* ifndef FEATURE_FORCE_LOAD */
997 # define IS_NOT_FORCED_AND
998 #endif /* def FEATURE_FORCE_LOAD */
1000 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
1002 char buf[BUFFER_SIZE];
1010 int ms_iis5_hack = 0;
1012 unsigned int forwarded_connect_retries = 0;
1013 unsigned int max_forwarded_connect_retries = csp->config->forwarded_connect_retries;
1014 const struct forward_spec * fwd;
1015 struct http_request *http;
1016 int len; /* for buffer sizes */
1017 #ifdef FEATURE_KILL_POPUPS
1018 int block_popups; /* bool, 1==will block popups */
1019 int block_popups_now = 0; /* bool, 1==currently blocking popups */
1020 #endif /* def FEATURE_KILL_POPUPS */
1022 int pcrs_filter; /* bool, 1==will filter through pcrs */
1023 int gif_deanimate; /* bool, 1==will deanimate gifs */
1024 int jpeg_inspect; /* bool, 1==will inspect jpegs */
1026 /* Function that does the content filtering for the current request */
1027 char *(*content_filter)() = NULL;
1029 /* Skeleton for HTTP response, if we should intercept the request */
1030 struct http_response *rsp;
1032 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1033 struct list header_list;
1034 struct list *headers = &header_list;
1039 * Read the client's request. Note that since we're not using select() we
1040 * could get blocked here if a client connected, then didn't say anything!
1045 len = read_socket(csp->cfd, buf, sizeof(buf));
1047 if (len <= 0) break; /* error! */
1050 * If there is no memory left for buffering the
1051 * request, there is nothing we can do but hang up
1053 if (add_to_iob(csp, buf, len))
1058 req = get_header(csp);
1062 break; /* no HTTP request! */
1067 continue; /* more to come! */
1071 * If it's a FTP or gopher request, we don't support it.
1073 * These checks are better than nothing, but they might
1074 * not work in all configurations and some clients might
1075 * have problems digesting the answer.
1077 * They should, however, never cause more problems than
1078 * Privoxy's old behaviour (returning the misleading HTML error message:
1079 * "Could not resolve http://(ftp|gopher)://example.org").
1081 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
1083 if (!strncmpic(req, "GET ftp://", 10))
1085 strcpy(buf, FTP_RESPONSE);
1086 log_error(LOG_LEVEL_ERROR, "%s tried to use Privoxy as FTP proxy: %s",
1087 csp->ip_addr_str, req);
1091 strcpy(buf, GOPHER_RESPONSE);
1092 log_error(LOG_LEVEL_ERROR, "%s tried to use Privoxy as gopher proxy: %s",
1093 csp->ip_addr_str, req);
1095 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
1097 write_socket(csp->cfd, buf, strlen(buf));
1098 free_http_request(http);
1102 #ifdef FEATURE_FORCE_LOAD
1103 /* If this request contains the FORCE_PREFIX,
1104 * better get rid of it now and set the force flag --oes
1107 if (strstr(req, FORCE_PREFIX))
1109 strclean(req, FORCE_PREFIX);
1110 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
1111 csp->flags |= CSP_FLAG_FORCED;
1114 #endif /* def FEATURE_FORCE_LOAD */
1116 switch( parse_http_request(req, http, csp) )
1119 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing request.");
1122 log_error(LOG_LEVEL_ERROR, "Couldn't parse request: %s.", req);
1130 if (http->cmd == NULL)
1132 strcpy(buf, CHEADER);
1133 write_socket(csp->cfd, buf, strlen(buf));
1135 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
1137 free_http_request(http);
1141 /* grab the rest of the client's headers */
1145 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
1147 len = read_socket(csp->cfd, buf, sizeof(buf));
1150 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1155 * If there is no memory left for buffering the
1156 * request, there is nothing we can do but hang up
1158 if (add_to_iob(csp, buf, len))
1165 if (p == NULL) break;
1172 if (http->host == NULL)
1175 * Intercepted or invalid request without domain
1176 * inside the request line. Try to get it another way.
1178 if (JB_ERR_OK == get_destination_from_headers(headers, http))
1180 /* Split the domain we just got for pattern matching */
1181 init_domain_components(http);
1185 /* We can't work without destination. Go spread the news.*/
1187 req = list_to_text(headers);
1189 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, http->cmd);
1190 log_error(LOG_LEVEL_ERROR,
1191 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
1192 csp->ip_addr_str, http->cmd, req);
1195 strcpy(buf, MISSING_DESTINATION_RESPONSE);
1196 write_socket(csp->cfd, buf, strlen(buf));
1197 free_http_request(http);
1198 destroy_list(headers);
1202 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
1203 * to get the destination IP address, use it as host directly
1204 * or do a reverse DNS lookup first.
1208 /* decide how to route the HTTP request */
1210 if ((fwd = forward_url(http, csp)) == NULL)
1212 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1213 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1216 /* build the http request to send to the server
1217 * we have to do one of the following:
1219 * create = use the original HTTP request to create a new
1220 * HTTP request that has either the path component
1221 * without the http://domainspec (w/path) or the
1222 * full orininal URL (w/url)
1223 * Note that the path and/or the HTTP version may
1224 * have been altered by now.
1226 * connect = Open a socket to the host:port of the server
1227 * and short-circuit server and client socket.
1229 * pass = Pass the request unchanged if forwarding a CONNECT
1230 * request to a parent proxy. Note that we'll be sending
1231 * the CFAIL message ourselves if connecting to the parent
1232 * fails, but we won't send a CSUCCEED message if it works,
1233 * since that would result in a double message (ours and the
1234 * parent's). After sending the request to the parent, we simply
1237 * here's the matrix:
1240 * +--------+--------+
1242 * 0 | create | connect|
1244 * Forwarding +--------+--------+
1246 * 1 | create | pass |
1248 * +--------+--------+
1253 * Determine the actions for this URL
1255 #ifdef FEATURE_TOGGLE
1256 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1258 /* Most compatible set of actions (i.e. none) */
1259 init_current_action(csp->action);
1262 #endif /* ndef FEATURE_TOGGLE */
1264 url_actions(http, csp);
1269 * Check if a CONNECT request is allowable:
1270 * In the absence of a +limit-connect action, allow only port 443.
1271 * If there is an action, allow whatever matches the specificaton.
1275 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
1276 || (csp->action->flags & ACTION_LIMIT_CONNECT
1277 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
1279 if (csp->action->flags & ACTION_TREAT_FORBIDDEN_CONNECTS_LIKE_BLOCKS)
1281 /* The response will violate the specs, but makes unblocking easier. */
1282 log_error(LOG_LEVEL_ERROR, "Marking suspicious CONNECT request from %s for blocking.",
1284 csp->action->flags |= ACTION_BLOCK;
1289 strcpy(buf, CFORBIDDEN);
1290 write_socket(csp->cfd, buf, strlen(buf));
1291 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
1292 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
1300 * Downgrade http version from 1.1 to 1.0 if +downgrade
1303 if ( (http->ssl == 0)
1304 && (!strcmpic(http->ver, "HTTP/1.1"))
1305 && (csp->action->flags & ACTION_DOWNGRADE))
1308 http->ver = strdup("HTTP/1.0");
1310 if (http->ver == NULL)
1312 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
1317 * Save a copy of the original request for logging
1319 http->ocmd = strdup(http->cmd);
1321 if (http->ocmd == NULL)
1323 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
1327 * (Re)build the HTTP request for non-SSL requests.
1328 * If forwarding, use the whole URL, else, use only the path.
1334 http->cmd = strdup(http->gpc);
1335 string_append(&http->cmd, " ");
1337 if (fwd->forward_host)
1339 string_append(&http->cmd, http->url);
1343 string_append(&http->cmd, http->path);
1345 string_append(&http->cmd, " ");
1346 string_append(&http->cmd, http->ver);
1348 if (http->cmd == NULL)
1350 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1352 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", http->cmd);
1354 enlist(csp->headers, http->cmd);
1356 /* Append the previously read headers */
1357 list_append_list_unique(csp->headers, headers);
1358 destroy_list(headers);
1361 * If the user has not supplied any wafers, and the user has not
1362 * told us to suppress the vanilla wafer, then send the vanilla wafer.
1364 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
1365 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
1367 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
1371 #ifdef FEATURE_KILL_POPUPS
1372 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1373 #endif /* def FEATURE_KILL_POPUPS */
1375 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
1376 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1378 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1380 jpeg_inspect = ((csp->action->flags & ACTION_JPEG_INSPECT) != 0);
1383 * We have a request. Now, check to see if we need to
1384 * intercept it, i.e. If ..
1388 /* We may not forward the request by rfc2616 sect 14.31 */
1389 (NULL != (rsp = direct_response(csp)))
1391 /* or we are enabled and... */
1392 || (IS_ENABLED_AND (
1394 /* ..the request was blocked */
1395 ( NULL != (rsp = block_url(csp)))
1397 /* ..or untrusted */
1398 #ifdef FEATURE_TRUST
1399 || ( NULL != (rsp = trust_url(csp)))
1400 #endif /* def FEATURE_TRUST */
1402 /* ..or a redirect kicked in */
1403 || ( NULL != (rsp = redirect_url(csp)))
1407 * .. or a CGI call was detected and answered.
1409 * This check comes last to give the user the power
1410 * to deny acces to some (or all) of the cgi pages.
1412 || (NULL != (rsp = dispatch_cgi(csp)))
1416 /* Write the answer to the client */
1417 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1418 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1420 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1423 #ifdef FEATURE_STATISTICS
1424 /* Count as a rejected request */
1425 csp->flags |= CSP_FLAG_REJECTED;
1426 #endif /* def FEATURE_STATISTICS */
1428 /* Log (FIXME: All intercept reasons appear as "crunch" with Status 200) */
1429 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1430 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1432 /* Clean up and return */
1433 free_http_response(rsp);
1437 hdr = sed(client_patterns, add_client_headers, csp);
1440 /* FIXME Should handle error properly */
1441 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1444 list_remove_all(csp->headers);
1446 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1448 if (fwd->forward_host)
1450 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1451 fwd->forward_host, fwd->forward_port, http->hostport);
1455 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1458 /* here we connect to the server, gateway, or the forwarder */
1460 while ( (csp->sfd = forwarded_connect(fwd, http, csp))
1461 && (errno == EINVAL) && (forwarded_connect_retries++ < max_forwarded_connect_retries))
1463 log_error(LOG_LEVEL_ERROR, "failed request #%u to connect to %s. Trying again.",
1464 forwarded_connect_retries, http->hostport);
1467 if (csp->sfd == JB_INVALID_SOCKET)
1469 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1472 if (errno == EINVAL)
1474 rsp = error_response(csp, "no-such-domain", errno);
1476 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1477 csp->ip_addr_str, http->ocmd);
1481 rsp = error_response(csp, "connect-failed", errno);
1483 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1484 csp->ip_addr_str, http->ocmd);
1488 /* Write the answer to the client */
1491 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1492 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1494 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1498 free_http_response(rsp);
1503 log_error(LOG_LEVEL_CONNECT, "OK");
1505 if (fwd->forward_host || (http->ssl == 0))
1507 /* write the client's (modified) header to the server
1508 * (along with anything else that may be in the buffer)
1511 if (write_socket(csp->sfd, hdr, strlen(hdr))
1512 || (flush_socket(csp->sfd, csp) < 0))
1514 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1517 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1518 csp->ip_addr_str, http->ocmd);
1520 rsp = error_response(csp, "connect-failed", errno);
1524 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1525 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1527 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1531 free_http_response(rsp);
1539 * We're running an SSL tunnel and we're not forwarding,
1540 * so just send the "connect succeeded" message to the
1541 * client, flush the rest, and get out of the way.
1543 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1544 csp->ip_addr_str, http->ocmd);
1546 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1554 /* we're finished with the client's header */
1557 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1559 /* pass data between the client and server
1560 * until one or the other shuts down the connection.
1569 * FD_ZERO here seems to point to an errant macro which crashes.
1570 * So do this by hand for now...
1572 memset(&rfds,0x00,sizeof(fd_set));
1576 FD_SET(csp->cfd, &rfds);
1577 FD_SET(csp->sfd, &rfds);
1579 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1583 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1587 /* this is the body of the browser's request
1588 * just read it and write it.
1591 if (FD_ISSET(csp->cfd, &rfds))
1593 len = read_socket(csp->cfd, buf, sizeof(buf));
1597 break; /* "game over, man" */
1600 if (write_socket(csp->sfd, buf, (size_t)len))
1602 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1609 * The server wants to talk. It could be the header or the body.
1610 * If `hdr' is null, then it's the header otherwise it's the body.
1611 * FIXME: Does `hdr' really mean `host'? No.
1615 if (FD_ISSET(csp->sfd, &rfds))
1618 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1622 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1624 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1625 csp->ip_addr_str, http->ocmd);
1627 rsp = error_response(csp, "connect-failed", errno);
1631 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1632 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1634 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1638 free_http_response(rsp);
1642 /* Add a trailing zero. This lets filter_popups
1643 * use string operations.
1647 #ifdef FEATURE_KILL_POPUPS
1648 /* Filter the popups on this read. */
1649 if (block_popups_now)
1651 filter_popups(buf, csp);
1653 #endif /* def FEATURE_KILL_POPUPS */
1655 /* Normally, this would indicate that we've read
1656 * as much as the server has sent us and we can
1657 * close the client connection. However, Microsoft
1658 * in its wisdom has released IIS/5 with a bug that
1659 * prevents it from sending the trailing \r\n in
1660 * a 302 redirect header (and possibly other headers).
1661 * To work around this if we've haven't parsed
1662 * a full header we'll append a trailing \r\n
1663 * and see if this now generates a valid one.
1665 * This hack shouldn't have any impacts. If we've
1666 * already transmitted the header or if this is a
1667 * SSL connection, then we won't bother with this
1668 * hack. So we only work on partially received
1669 * headers. If we append a \r\n and this still
1670 * doesn't generate a valid header, then we won't
1671 * transmit anything to the client.
1676 if (server_body || http->ssl)
1679 * If we have been buffering up the document,
1680 * now is the time to apply content modification
1681 * and send the result to the client.
1686 * If the content filter fails, use the original
1687 * buffer and length.
1688 * (see p != NULL ? p : csp->iob->cur below)
1690 if (NULL == (p = (*content_filter)(csp)))
1692 csp->content_length = csp->iob->eod - csp->iob->cur;
1695 hdr = sed(server_patterns_light, NULL, csp);
1699 /* FIXME Should handle error properly */
1700 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1703 if (write_socket(csp->cfd, hdr, strlen(hdr))
1704 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1706 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1716 break; /* "game over, man" */
1720 * This is NOT the body, so
1721 * Let's pretend the server just sent us a blank line.
1723 len = sprintf(buf, "\r\n");
1726 * Now, let the normal header parsing algorithm below do its
1727 * job. If it fails, we'll exit instead of continuing.
1734 * If this is an SSL connection or we're in the body
1735 * of the server document, just write it to the client,
1736 * unless we need to buffer the body for later content-filtering
1739 if (server_body || http->ssl)
1744 * If there is no memory left for buffering the content, or the buffer limit
1745 * has been reached, switch to non-filtering mode, i.e. make & write the
1746 * header, flush the iob and buf, and get out of the way.
1748 if (add_to_iob(csp, buf, len))
1753 log_error(LOG_LEVEL_ERROR, "Flushing header and buffers. Stepping back from filtering.");
1755 hdr = sed(server_patterns, add_server_headers, csp);
1759 * Memory is too tight to even generate the header.
1760 * Send our static "Out-of-memory" page.
1762 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
1763 rsp = cgi_error_memory();
1765 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1766 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1768 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1773 hdrlen = strlen(hdr);
1775 if (write_socket(csp->cfd, hdr, hdrlen)
1776 || ((flushed = flush_socket(csp->cfd, csp)) < 0)
1777 || (write_socket(csp->cfd, buf, (size_t) len)))
1779 log_error(LOG_LEVEL_CONNECT, "Flush header and buffers to client failed: %E");
1785 byte_count += hdrlen + flushed + len;
1787 content_filter = NULL;
1794 if (write_socket(csp->cfd, buf, (size_t)len))
1796 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1805 /* we're still looking for the end of the
1806 * server's header ... (does that make header
1807 * parsing an "out of body experience" ?
1811 * buffer up the data we just read. If that fails,
1812 * there's little we can do but send our static
1813 * out-of-memory page.
1815 if (add_to_iob(csp, buf, len))
1817 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
1818 rsp = cgi_error_memory();
1820 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1821 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1823 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1828 /* get header lines from the iob */
1830 while ((p = get_header(csp)) != NULL)
1834 /* see following note */
1837 enlist(csp->headers, p);
1841 /* NOTE: there are no "empty" headers so
1842 * if the pointer `p' is not NULL we must
1843 * assume that we reached the end of the
1844 * buffer before we hit the end of the header.
1851 /* Well, we tried our MS IIS/5
1852 * hack and it didn't work.
1853 * The header is incomplete
1854 * and there isn't anything
1855 * we can do about it.
1861 /* Since we have to wait for
1862 * more from the server before
1863 * we can parse the headers
1864 * we just continue here.
1870 /* we have now received the entire header.
1871 * filter it and send the result to the client
1874 hdr = sed(server_patterns, add_server_headers, csp);
1877 /* FIXME Should handle error properly */
1878 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1881 #ifdef FEATURE_KILL_POPUPS
1882 /* Start blocking popups if appropriate. */
1884 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1885 !http->ssl && /* We talk plaintext */
1886 block_popups) /* Policy allows */
1888 block_popups_now = 1;
1890 * Filter the part of the body that came in the same read
1891 * as the last headers:
1893 filter_popups(csp->iob->cur, csp);
1896 #endif /* def FEATURE_KILL_POPUPS */
1898 /* Buffer and pcrs filter this if appropriate. */
1900 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1901 !http->ssl && /* We talk plaintext */
1902 pcrs_filter) /* Policy allows */
1904 content_filter = pcrs_filter_response;
1907 /* Buffer and gif_deanimate this if appropriate. */
1909 if ((csp->content_type & CT_GIF) && /* It's an image/gif MIME-Type */
1910 !http->ssl && /* We talk plaintext */
1911 gif_deanimate) /* Policy allows */
1913 content_filter = gif_deanimate_response;
1916 /* Buffer and jpg_inspect this if appropriate. */
1918 if ((csp->content_type & CT_JPEG) && /* It's an image/jpeg MIME-Type */
1919 !http->ssl && /* We talk plaintext */
1920 jpeg_inspect) /* Policy allows */
1922 content_filter = jpeg_inspect_response;
1926 * Only write if we're not buffering for content modification
1928 if (!content_filter)
1930 /* write the server's (modified) header to
1931 * the client (along with anything else that
1932 * may be in the buffer)
1935 if (write_socket(csp->cfd, hdr, strlen(hdr))
1936 || ((len = flush_socket(csp->cfd, csp)) < 0))
1938 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1940 /* the write failed, so don't bother
1941 * mentioning it to the client...
1942 * it probably can't hear us anyway.
1951 /* we're finished with the server's header */
1956 /* If this was a MS IIS/5 hack then it means
1957 * the server has already closed the
1958 * connection. Nothing more to read. Time
1969 return; /* huh? we should never get here */
1972 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1973 csp->ip_addr_str, http->ocmd, byte_count);
1977 /*********************************************************************
1981 * Description : This is little more than chat. We only "serve" to
1982 * to close any socket that chat may have opened.
1985 * 1 : csp = Current client state (buffers, headers, etc...)
1989 *********************************************************************/
1991 void serve(struct client_state *csp)
1992 #else /* ifndef AMIGA */
1993 static void serve(struct client_state *csp)
1994 #endif /* def AMIGA */
1997 close_socket(csp->cfd);
1999 if (csp->sfd != JB_INVALID_SOCKET)
2001 close_socket(csp->sfd);
2004 csp->flags &= ~CSP_FLAG_ACTIVE;
2010 /*********************************************************************
2012 * Function : server_thread
2014 * Description : We only exist to call `serve' in a threaded environment.
2017 * 1 : data = Current client state (buffers, headers, etc...)
2019 * Returns : Always 0.
2021 *********************************************************************/
2022 static int32 server_thread(void *data)
2024 serve((struct client_state *) data);
2031 /*********************************************************************
2035 * Description : Print usage info & exit.
2037 * Parameters : Pointer to argv[0] for identifying ourselves
2041 *********************************************************************/
2042 void usage(const char *myname)
2044 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
2046 "Usage: %s [--help] [--version] [configfile]\n"
2048 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
2050 "Aborting.\n", myname);
2057 /*********************************************************************
2061 * Description : Load the config file and start the listen loop.
2062 * This function is a lot more *sane* with the `load_config'
2063 * and `listen_loop' functions; although it stills does
2064 * a *little* too much for my taste.
2067 * 1 : argc = Number of parameters (including $0).
2068 * 2 : argv = Array of (char *)'s to the parameters.
2070 * Returns : 1 if : can't open config file, unrecognized directive,
2071 * stats requested in multi-thread mode, can't open the
2072 * log file, can't open the jar file, listen port is invalid,
2073 * any load fails, and can't bind port.
2075 * Else main never returns, the process must be signaled
2076 * to terminate execution. Or, on Windows, use the
2077 * "File", "Exit" menu option.
2079 *********************************************************************/
2081 int real_main(int argc, const char *argv[])
2083 int main(int argc, const char *argv[])
2087 unsigned int random_seed;
2089 struct passwd *pw = NULL;
2090 struct group *grp = NULL;
2099 #if !defined(_WIN32)
2107 * Parse the command line arguments
2109 while (++argc_pos < argc)
2112 /* Check to see if the service must be installed or uninstalled */
2113 if (strncmp(argv[argc_pos], "--install", 9) == 0)
2115 const char *pName = argv[argc_pos] + 9;
2118 exit( (install_service(pName)) ? 0 : 1 );
2120 else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
2122 const char *pName = argv[argc_pos] + 11;
2125 exit((uninstall_service(pName)) ? 0 : 1);
2127 else if (strcmp(argv[argc_pos], "--service" ) == 0)
2129 bRunAsService = TRUE;
2130 w32_set_service_cwd();
2131 atexit(w32_service_exit_notify);
2134 #endif /* defined(_WIN32) */
2137 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2139 if (strcmp(argv[argc_pos], "--help") == 0)
2144 else if(strcmp(argv[argc_pos], "--version") == 0)
2146 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2152 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
2157 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
2159 if (++argc_pos == argc) usage(argv[0]);
2160 pidfile = strdup(argv[argc_pos]);
2163 else if (strcmp(argv[argc_pos], "--user" ) == 0)
2165 if (++argc_pos == argc) usage(argv[argc_pos]);
2167 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
2170 if (NULL == (grp = getgrnam(p)))
2172 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
2176 if (NULL == (pw = getpwnam(argv[argc_pos])))
2178 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
2181 if (p != NULL) *--p = '\0';
2184 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
2189 #endif /* defined(unix) */
2190 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
2192 configfile = argv[argc_pos];
2195 } /* -END- while (more arguments) */
2198 if ( *configfile != '/' )
2200 char *abs_file, cwd[1024];
2202 /* make config-filename absolute here */
2203 if ( !(getcwd(cwd, sizeof(cwd))))
2205 perror("get working dir failed");
2209 if (!(basedir = strdup(cwd))
2210 || (!(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 ))))
2212 perror("malloc failed");
2215 strcpy( abs_file, basedir );
2216 strcat( abs_file, "/" );
2217 strcat( abs_file, configfile );
2218 configfile = abs_file;
2220 #endif /* defined unix */
2224 clients->next = NULL;
2228 #elif defined(_WIN32)
2232 #ifdef FEATURE_PTHREAD
2234 * Prepare global mutex semaphores
2236 pthread_mutex_init(&log_mutex,0);
2237 pthread_mutex_init(&log_init_mutex,0);
2239 #ifndef HAVE_GMTIME_R
2240 pthread_mutex_init(&gmtime_mutex,0);
2241 #endif /* ndef HAVE_GMTIME_R */
2243 #ifndef HAVE_LOCALTIME_R
2244 pthread_mutex_init(&localtime_mutex,0);
2245 #endif /* ndef HAVE_GMTIME_R */
2247 #ifndef HAVE_GETHOSTBYADDR_R
2248 pthread_mutex_init(&gethostbyaddr_mutex,0);
2249 #endif /* ndef HAVE_GETHOSTBYADDR_R */
2251 #ifndef HAVE_GETHOSTBYNAME_R
2252 pthread_mutex_init(&gethostbyname_mutex,0);
2253 #endif /* ndef HAVE_GETHOSTBYNAME_R */
2256 pthread_mutex_init(&rand_mutex,0);
2257 #endif /* ndef HAVE_RANDOM */
2259 #endif /* FEATURE_PTHREAD */
2261 random_seed = (int)time(NULL);
2263 srandom(random_seed);
2266 #endif /* ifdef HAVE_RANDOM */
2269 * Unix signal handling
2271 * Catch the abort, interrupt and terminate signals for a graceful exit
2272 * Catch the hangup signal so the errlog can be reopened.
2273 * Ignore the broken pipe signals (FIXME: Why?)
2275 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
2278 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP, 0 };
2279 const int ignored_signals[] = { SIGPIPE, 0 };
2281 for (idx = 0; catched_signals[idx] != 0; idx++)
2283 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
2284 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
2286 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
2287 #endif /* ifdef sun */
2289 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
2293 for (idx = 0; ignored_signals[idx] != 0; idx++)
2295 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
2297 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
2302 #else /* ifdef _WIN32 */
2303 # ifdef _WIN_CONSOLE
2305 * We *are* in a windows console app.
2306 * Print a verbose messages about FAQ's and such
2308 printf(win32_blurb);
2309 # endif /* def _WIN_CONSOLE */
2310 #endif /* def _WIN32 */
2313 /* Initialize the CGI subsystem */
2314 cgi_init_error_messages();
2317 * If runnig on unix and without the --nodaemon
2318 * option, become a daemon. I.e. fork, detach
2319 * from tty and get process group leadership
2332 if ( pid < 0 ) /* error */
2337 else if ( pid != 0 ) /* parent */
2342 * must check for errors
2343 * child died due to missing files aso
2346 wpid = waitpid( pid, &status, WNOHANG );
2355 /* Should be more portable, but not as well tested */
2360 #else /* ndef __FreeBSD__ */
2362 #endif /* ndef __FreeBSD__ */
2363 fd = open("/dev/tty", O_RDONLY);
2366 /* no error check here */
2367 ioctl( fd, TIOCNOTTY,0 );
2371 /* FIXME: should close stderr (fd 2) here too, but the test
2373 * and load config file is done in listen_loop() and puts
2374 * some messages on stderr there.
2381 } /* -END- if (!no_daemon) */
2384 * As soon as we have written the PID file, we can switch
2385 * to the user and group ID indicated by the --user option
2391 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
2393 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
2399 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
2401 if (chroot(pw->pw_dir) < 0)
2403 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
2407 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
2410 if (setuid(pw->pw_uid))
2412 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
2416 char putenv_dummy[64];
2418 strcpy(putenv_dummy, "HOME=/");
2419 if (putenv(putenv_dummy) != 0)
2421 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
2424 snprintf(putenv_dummy, 64, "USER=%s", pw->pw_name);
2425 if (putenv(putenv_dummy) != 0)
2427 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
2433 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
2436 #endif /* defined unix */
2439 /* This will be FALSE unless the command line specified --service
2443 /* Yup, so now we must attempt to establish a connection
2444 * with the service dispatcher. This will only work if this
2445 * process was launched by the service control manager to
2446 * actually run as a service. If this isn't the case, i've
2447 * known it take around 30 seconds or so for the call to return.
2450 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
2451 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
2453 /* Service has run, and at this point is now being stopped, so just return */
2458 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
2460 /* An error occurred. Usually it's because --service was wrongly specified
2461 * and we were unable to connect to the Service Control Dispatcher because
2462 * it wasn't expecting us and is therefore not listening.
2464 * For now, just continue below to call the listen_loop function.
2467 #endif /* def _WIN32 */
2477 /*********************************************************************
2479 * Function : bind_port_helper
2481 * Description : Bind the listen port. Handles logging, and aborts
2485 * 1 : config = Privoxy configuration. Specifies port
2488 * Returns : Port that was opened.
2490 *********************************************************************/
2491 static jb_socket bind_port_helper(struct configuration_spec * config)
2496 if ( (config->haddr != NULL)
2497 && (config->haddr[0] == '1')
2498 && (config->haddr[1] == '2')
2499 && (config->haddr[2] == '7')
2500 && (config->haddr[3] == '.') )
2502 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
2505 else if (config->haddr == NULL)
2507 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
2512 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
2513 config->hport, config->haddr);
2516 result = bind_port(config->haddr, config->hport, &bfd);
2523 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2524 "There may be another Privoxy or some other "
2525 "proxy running on port %d",
2526 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
2527 config->hport, config->hport);
2530 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2531 "The hostname is not resolvable",
2532 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2535 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
2536 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2539 /* shouldn't get here */
2540 return JB_INVALID_SOCKET;
2543 config->need_bind = 0;
2550 /* Without this simple workaround we get this compiler warning from _beginthread
2551 * warning C4028: formal parameter 1 different from declaration
2553 void w32_service_listen_loop(void *p)
2557 #endif /* def _WIN32 */
2560 /*********************************************************************
2562 * Function : listen_loop
2564 * Description : bind the listen port and enter a "FOREVER" listening loop.
2570 *********************************************************************/
2571 static void listen_loop(void)
2573 struct client_state *csp = NULL;
2575 struct configuration_spec * config;
2577 config = load_config();
2579 bfd = bind_port_helper(config);
2581 #ifdef FEATURE_GRACEFUL_TERMINATION
2582 while (!g_terminate)
2587 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
2588 while (waitpid(-1, NULL, WNOHANG) > 0)
2590 /* zombie children */
2592 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2595 * Free data that was used by died threads
2601 * Re-open the errlog after HUP signal
2603 if (received_hup_signal)
2605 init_error_log(Argv[0], config->logfile, config->debug);
2606 received_hup_signal = 0;
2611 #ifdef FEATURE_COOKIE_JAR
2613 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
2614 * already open. I think unload_configfile() is not being run, which should do
2615 * this work. Until that can get resolved, we'll use this workaround.
2619 if (csp->config->jar)
2621 fclose(csp->config->jar);
2622 csp->config->jar = NULL;
2624 #endif /* FEATURE_COOKIE_JAR */
2625 #endif /* __OS2__ */
2627 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2629 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2633 csp->flags |= CSP_FLAG_ACTIVE;
2634 csp->sfd = JB_INVALID_SOCKET;
2636 csp->config = config = load_config();
2638 if ( config->need_bind )
2641 * Since we were listening to the "old port", we will not see
2642 * a "listen" param change until the next IJB request. So, at
2643 * least 1 more request must be made for us to find the new
2644 * setting. I am simply closing the old socket and binding the
2647 * Which-ever is correct, we will serve 1 more page via the
2648 * old settings. This should probably be a "show-proxy-args"
2649 * request. This should not be a so common of an operation
2650 * that this will hurt people's feelings.
2655 bfd = bind_port_helper(config);
2658 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2660 if (!accept_connection(csp, bfd))
2662 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2675 log_error(LOG_LEVEL_CONNECT, "OK");
2678 #ifdef FEATURE_TOGGLE
2679 if (global_toggle_state)
2681 csp->flags |= CSP_FLAG_TOGGLED_ON;
2683 #endif /* def FEATURE_TOGGLE */
2685 if (run_loader(csp))
2687 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2688 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2692 if (block_acl(NULL,csp))
2694 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2695 close_socket(csp->cfd);
2699 #endif /* def FEATURE_ACL */
2701 /* add it to the list of clients */
2702 csp->next = clients->next;
2703 clients->next = csp;
2705 if (config->multi_threaded)
2709 /* this is a switch () statment in the C preprocessor - ugh */
2710 #undef SELECTED_ONE_OPTION
2712 /* Use Pthreads in preference to native code */
2713 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2714 #define SELECTED_ONE_OPTION
2716 pthread_t the_thread;
2717 pthread_attr_t attrs;
2719 pthread_attr_init(&attrs);
2720 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2721 errno = pthread_create(&the_thread, &attrs,
2723 child_id = errno ? -1 : 0;
2724 pthread_attr_destroy(&attrs);
2728 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2729 #define SELECTED_ONE_OPTION
2730 child_id = _beginthread(
2731 (void (*)(void *))serve,
2736 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2737 #define SELECTED_ONE_OPTION
2738 child_id = _beginthread(
2739 (void(* _Optlink)(void*))serve,
2745 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2746 #define SELECTED_ONE_OPTION
2748 thread_id tid = spawn_thread
2749 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2751 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2753 child_id = (int) tid;
2762 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2763 #define SELECTED_ONE_OPTION
2764 csp->cfd = ReleaseSocket(csp->cfd, -1);
2766 if((child_id = (int)CreateNewProcTags(
2767 NP_Entry, (ULONG)server_thread,
2768 NP_Output, Output(),
2769 NP_CloseOutput, FALSE,
2770 NP_Name, (ULONG)"privoxy child",
2771 NP_StackSize, 200*1024,
2775 ((struct Task *)child_id)->tc_UserData = csp;
2776 Signal((struct Task *)child_id, SIGF_SINGLE);
2781 #if !defined(SELECTED_ONE_OPTION)
2784 /* This block is only needed when using fork().
2785 * When using threads, the server thread was
2786 * created and run by the call to _beginthread().
2788 if (child_id == 0) /* child */
2791 #ifdef FEATURE_TOGGLE
2792 int inherited_toggle_state = global_toggle_state;
2793 #endif /* def FEATURE_TOGGLE */
2798 * If we've been toggled or we've blocked the request, tell Mom
2801 #ifdef FEATURE_TOGGLE
2802 if (inherited_toggle_state != global_toggle_state)
2804 rc |= RC_FLAG_TOGGLED;
2806 #endif /* def FEATURE_TOGGLE */
2808 #ifdef FEATURE_STATISTICS
2809 if (csp->flags & CSP_FLAG_REJECTED)
2811 rc |= RC_FLAG_BLOCKED;
2813 #endif /* ndef FEATURE_STATISTICS */
2817 else if (child_id > 0) /* parent */
2819 /* in a fork()'d environment, the parent's
2820 * copy of the client socket and the CSP
2824 #if !defined(_WIN32) && !defined(__CYGWIN__)
2826 wait( &child_status );
2829 * Evaluate child's return code: If the child has
2830 * - been toggled, toggle ourselves
2831 * - blocked its request, bump up the stats counter
2834 #ifdef FEATURE_TOGGLE
2835 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
2837 global_toggle_state = !global_toggle_state;
2839 #endif /* def FEATURE_TOGGLE */
2841 #ifdef FEATURE_STATISTICS
2843 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
2847 #endif /* def FEATURE_STATISTICS */
2849 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2850 close_socket(csp->cfd);
2851 csp->flags &= ~CSP_FLAG_ACTIVE;
2855 #undef SELECTED_ONE_OPTION
2856 /* end of cpp switch () */
2858 if (child_id < 0) /* failed */
2860 char buf[BUFFER_SIZE];
2862 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2864 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
2866 write_socket(csp->cfd, buf, strlen(buf));
2867 close_socket(csp->cfd);
2868 csp->flags &= ~CSP_FLAG_ACTIVE;
2879 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2881 /* Clean up. Aim: free all memory (no leaks) */
2882 #ifdef FEATURE_GRACEFUL_TERMINATION
2884 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2886 unload_current_config_file();
2887 unload_current_actions_file();
2888 unload_current_re_filterfile();
2889 #ifdef FEATURE_TRUST
2890 unload_current_trust_file();
2893 if (config->multi_threaded)
2900 } while ((clients->next != NULL) && (--i > 0));
2904 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2915 #ifdef FEATURE_COOKIE_JAR
2916 if (NULL != config->jar)
2918 fclose(config->jar);
2922 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2923 /* Cleanup - remove taskbar icon etc. */
2928 #endif /* FEATURE_GRACEFUL_TERMINATION */