1 const char jcc_rcs[] = "$Id: jcc.c,v 1.90 2002/04/02 14:57:28 oes 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.90 2002/04/02 14:57:28 oes
37 * Made sending wafers independent of FEATURE_COOKIE_JAR
39 * Revision 1.89 2002/03/31 17:18:59 jongfoster
40 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
42 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
43 * More compiler warning message maintenance
45 * Revision 1.87 2002/03/26 22:29:54 swa
46 * we have a new homepage!
48 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
49 * Workaround for closing the jarfile before load_config() comes around again
51 * Revision 1.85 2002/03/24 15:23:33 jongfoster
54 * Revision 1.84 2002/03/24 13:25:43 swa
55 * name change related issues
57 * Revision 1.83 2002/03/16 23:54:06 jongfoster
58 * Adding graceful termination feature, to help look for memory leaks.
59 * If you enable this (which, by design, has to be done by hand
60 * editing config.h) and then go to http://i.j.b/die, then the program
61 * will exit cleanly after the *next* request. It should free all the
62 * memory that was used.
64 * Revision 1.82 2002/03/13 00:27:05 jongfoster
67 * Revision 1.81 2002/03/12 01:42:50 oes
68 * Introduced modular filters
70 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
71 * OS/2 port maintenance:
72 * - Fixed EMX build - it had decayed a little
73 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
74 * substituted a memset for now.
76 * Revision 1.79 2002/03/09 20:03:52 jongfoster
77 * - Making various functions return int rather than size_t.
78 * (Undoing a recent change). Since size_t is unsigned on
79 * Windows, functions like read_socket that return -1 on
80 * error cannot return a size_t.
82 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
83 * crashes, and also frequently caused JB to jump to 100%
84 * CPU and stay there. (Because it thought it had just
85 * read ((unsigned)-1) == 4Gb of data...)
87 * - The signature of write_socket has changed, it now simply
88 * returns success=0/failure=nonzero.
90 * - Trying to get rid of a few warnings --with-debug on
91 * Windows, I've introduced a new type "jb_socket". This is
92 * used for the socket file descriptors. On Windows, this
93 * is SOCKET (a typedef for unsigned). Everywhere else, it's
94 * an int. The error value can't be -1 any more, so it's
95 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
96 * Windows it maps to the #define INVALID_SOCKET.)
98 * - The signature of bind_port has changed.
100 * Revision 1.78 2002/03/08 21:35:04 oes
101 * Added optional group supplement to --user option. Will now use default group of user if no group given
103 * Revision 1.77 2002/03/07 03:52:06 oes
104 * - Fixed compiler warnings etc
105 * - Improved handling of failed DNS lookups
107 * Revision 1.76 2002/03/06 22:54:35 jongfoster
108 * Automated function-comment nitpicking.
110 * Revision 1.75 2002/03/06 10:02:19 oes
111 * Fixed stupid bug when --user was not given
113 * Revision 1.74 2002/03/06 00:49:31 jongfoster
114 * Fixing warning on Windows
115 * Making #ifdefs that refer to the same variable consistently
116 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
118 * Revision 1.73 2002/03/05 23:57:30 hal9
119 * Stray character 's' on line 1618 was breaking build.
121 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
122 * - Re-enable OS/2 building after new parms were added
123 * - Fix false out of memory report when resolving CGI templates when no IP
124 * address is available of failed attempt (a la no such domain)
126 * Revision 1.71 2002/03/05 18:13:56 oes
127 * Added --user option
129 * Revision 1.70 2002/03/05 04:52:42 oes
130 * Deleted non-errlog debugging code
132 * Revision 1.69 2002/03/04 23:50:00 jongfoster
133 * Splitting off bind_port() call into bind_port_helper(), with
136 * Revision 1.68 2002/03/04 20:17:32 oes
139 * Revision 1.67 2002/03/04 18:18:57 oes
140 * - Removed _DEBUG mode
141 * - Cleand up cmdline parsing
142 * - Introduced --no-daemon, --pidfile options
143 * - Cleaned up signal handling:
144 * - Terminate cleanly on INT, TERM and ABRT
145 * - Schedule logfile for re-opening on HUP
146 * - Ignore CHLD and PIPE
147 * - Leave the rest with their default handlers
148 * - Uniform handler registration
149 * - Added usage() function
150 * - Played styleguide police
152 * Revision 1.66 2002/03/03 15:06:55 oes
153 * Re-enabled automatic config reloading
155 * Revision 1.65 2002/03/03 14:49:11 oes
156 * Fixed CLF logging: Now uses client's original HTTP request
158 * Revision 1.64 2002/03/03 09:18:03 joergs
159 * Made jumbjuster work on AmigaOS again.
161 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
162 * Clean up a little CRLF unpleasantness that suddenly appeared
164 * Revision 1.62 2002/02/20 23:17:23 jongfoster
165 * Detecting some out-of memory conditions and exiting with a log message.
167 * Revision 1.61 2002/01/17 21:01:52 jongfoster
168 * Moving all our URL and URL pattern parsing code to urlmatch.c.
170 * Revision 1.60 2001/12/30 14:07:32 steudten
171 * - Add signal handling (unix)
172 * - Add SIGHUP handler (unix)
173 * - Add creation of pidfile (unix)
174 * - Add action 'top' in rc file (RH)
175 * - Add entry 'SIGNALS' to manpage
176 * - Add exit message to logfile (unix)
178 * Revision 1.59 2001/12/13 14:07:18 oes
179 * Fixed Bug: 503 error page now sent OK
181 * Revision 1.58 2001/11/30 23:37:24 jongfoster
182 * Renaming the Win32 config file to config.txt - this is almost the
183 * same as the corresponding UNIX name "config"
185 * Revision 1.57 2001/11/16 00:47:43 jongfoster
186 * Changing the tty-disconnection code to use setsid().
188 * Revision 1.56 2001/11/13 20:20:54 jongfoster
189 * Tabs->spaces, fixing a bug with missing {} around an if()
191 * Revision 1.55 2001/11/13 20:14:53 jongfoster
192 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
194 * Revision 1.54 2001/11/07 00:03:14 steudten
195 * Give reliable return value if an error
196 * occurs not just 0 with new daemon mode.
198 * Revision 1.53 2001/11/05 21:41:43 steudten
199 * Add changes to be a real daemon just for unix os.
200 * (change cwd to /, detach from controlling tty, set
201 * process group and session leader to the own process.
203 * Add some fatal-error log message for failed malloc().
204 * Add '-d' if compiled with 'configure --with-debug' to
205 * enable debug output.
207 * Revision 1.52 2001/10/26 20:11:20 jongfoster
208 * Fixing type mismatch
210 * Revision 1.51 2001/10/26 17:38:28 oes
213 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
214 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
215 * threads to call select() simultaneously. So, it's time to do a real, live,
216 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
217 * (native). Both versions will work, but using __OS2__ offers multi-threading.
219 * Revision 1.49 2001/10/23 21:41:35 jongfoster
220 * Added call to initialize the (statically-allocated of course)
221 * "out of memory" CGI response.
223 * Revision 1.48 2001/10/10 19:56:46 jongfoster
224 * Moving some code that wasn't cookie-related out of an #ifdef
227 * Revision 1.47 2001/10/10 16:44:36 oes
228 * Added CONNECT destination port limitation check
230 * Revision 1.46 2001/10/08 15:17:41 oes
231 * Re-enabled SSL forwarding
233 * Revision 1.45 2001/10/07 15:42:11 oes
234 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
236 * Moved downgrading of the HTTP version from parse_http_request to
237 * chat(), since we can't decide if it is necessary before we have
238 * determined the actions for the URL. The HTTP command is now
239 * *always* re-built so the repairs need no longer be special-cased.
241 * filter_popups now gets a csp pointer so it can raise the new
242 * CSP_FLAG_MODIFIED flag.
246 * Added configurable size limit for the IOB. If the IOB grows so
247 * large that the next read would exceed the limit, the header
248 * is generated, and the header & unfiltered buffer are flushed
249 * to the client. Chat then continues in non-buffering,
250 * non-filtering body mode.
252 * Revision 1.44 2001/10/02 18:13:57 oes
255 * Revision 1.43 2001/10/02 15:32:13 oes
256 * Moved generation of hdr
258 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
259 * Cleaning up 2 compiler warnings on OS/2.
261 * Revision 1.41 2001/09/16 17:05:14 jongfoster
262 * Removing unused #include showarg.h
264 * Revision 1.40 2001/09/16 15:41:45 jongfoster
265 * Fixing signed/unsigned comparison warning.
267 * Revision 1.39 2001/09/16 13:21:27 jongfoster
268 * Changes to use new list functions.
270 * Revision 1.38 2001/09/16 13:01:46 jongfoster
271 * Removing redundant function call that zeroed zalloc()'d memory.
273 * Revision 1.37 2001/09/10 11:12:24 oes
274 * Deleted unused variable
276 * Revision 1.36 2001/09/10 10:56:15 oes
277 * Silenced compiler warnings
279 * Revision 1.35 2001/07/31 14:44:22 oes
280 * Deleted unused size parameter from filter_popups()
282 * Revision 1.34 2001/07/30 22:08:36 jongfoster
283 * Tidying up #defines:
284 * - All feature #defines are now of the form FEATURE_xxx
285 * - Permanently turned off WIN_GUI_EDIT
286 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
288 * Revision 1.33 2001/07/29 19:32:00 jongfoster
289 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
291 * Revision 1.32 2001/07/29 18:47:05 jongfoster
292 * Adding missing #include "loadcfg.h"
294 * Revision 1.31 2001/07/29 12:17:48 oes
295 * Applied pthread fix by Paul Lieverse
297 * Revision 1.30 2001/07/25 22:57:13 jongfoster
298 * __BEOS__ no longer overrides FEATURE_PTHREAD.
299 * This is because FEATURE_PTHREAD will soon be widely used, so I
300 * want to keep it simple.
302 * Revision 1.29 2001/07/24 12:47:06 oes
303 * Applied BeOS support update by Eugenia
305 * Revision 1.28 2001/07/23 13:26:12 oes
306 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
308 * Revision 1.27 2001/07/19 19:09:47 haroon
309 * - Added code to take care of the situation where while processing the first
310 * server response (which includes the server header), after finding the end
311 * of the headers we were not looking past the end of the headers for
312 * content modification. I enabled it for filter_popups.
313 * Someone else should look to see if other similar operations should be
314 * done to the discarded portion of the buffer.
316 * Note 2001/07/20: No, the other content modification mechanisms will process
317 * the whole iob later anyway. --oes
319 * Revision 1.26 2001/07/18 12:31:36 oes
322 * Revision 1.25 2001/07/15 19:43:49 jongfoster
323 * Supports POSIX threads.
324 * Also removed some unused #includes.
326 * Revision 1.24 2001/07/13 14:00:40 oes
327 * - Generic content modification scheme:
328 * Each feature has its own applicability flag that is set
329 * from csp->action->flags.
330 * Replaced the "filtering" int flag , by a function pointer
331 * "content_filter" to the function that will do the content
332 * modification. If it is != NULL, the document will be buffered
333 * and processed through *content_filter, which must set
334 * csp->content_length and return a modified copy of the body
335 * or return NULL (on failiure).
336 * - Changed csp->is_text to the more generic bitmap csp->content_type
337 * which can currently take the valued CT_TEXT or CT_GIF
339 * - Removed all #ifdef PCRS
341 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
342 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
343 * the `block_acl' call. This prevents a compilation error when the user
344 * does not wish to use the "ACL" feature.
346 * Revision 1.22 2001/06/29 21:45:41 oes
347 * Indentation, CRLF->LF, Tab-> Space
349 * Revision 1.21 2001/06/29 13:29:36 oes
350 * - Cleaned up, improved comments
351 * - Unified all possible interceptors (CGI,
352 * block, trust, fast_redirect) in one
353 * place, with one (CGI) answer generation
354 * mechansim. Much clearer now.
355 * - Removed the GIF image generation, which
356 * is now done in filters.c:block_url()
357 * - Made error conditions like domain lookup
358 * failiure or (various) problems while talking
359 * to the server use cgi.c:error_response()
360 * instead of generating HTML/HTTP in chat() (yuck!)
361 * - Removed logentry from cancelled commit
363 * Revision 1.20 2001/06/09 10:55:28 jongfoster
364 * Changing BUFSIZ ==> BUFFER_SIZE
366 * Revision 1.19 2001/06/07 23:12:52 jongfoster
367 * Replacing function pointer in struct gateway with a directly
368 * called function forwarded_connect().
369 * Replacing struct gateway with struct forward_spec
371 * Revision 1.18 2001/06/03 19:12:16 oes
372 * introduced new cgi handling
374 * Revision 1.17 2001/06/01 20:07:23 jongfoster
375 * Now uses action +image-blocker{} rather than config->tinygif
377 * Revision 1.16 2001/06/01 18:49:17 jongfoster
378 * Replaced "list_share" with "list" - the tiny memory gain was not
379 * worth the extra complexity.
381 * Revision 1.15 2001/05/31 21:24:47 jongfoster
382 * Changed "permission" to "action" throughout.
383 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
384 * Moved vanilla wafer check into chat(), since we must now
385 * decide whether or not to add it based on the URL.
387 * Revision 1.14 2001/05/29 20:14:01 joergs
388 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
391 * Revision 1.13 2001/05/29 09:50:24 jongfoster
392 * Unified blocklist/imagelist/permissionslist.
393 * File format is still under discussion, but the internal changes
396 * Also modified interceptor behaviour:
397 * - We now intercept all URLs beginning with one of the following
398 * prefixes (and *only* these prefixes):
400 * * http://ijbswa.sf.net/config/
401 * * http://ijbswa.sourceforge.net/config/
402 * - New interceptors "home page" - go to http://i.j.b/ to see it.
403 * - Internal changes so that intercepted and fast redirect pages
404 * are not replaced with an image.
405 * - Interceptors now have the option to send a binary page direct
406 * to the client. (i.e. ijb-send-banner uses this)
407 * - Implemented show-url-info interceptor. (Which is why I needed
408 * the above interceptors changes - a typical URL is
409 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
410 * The previous mechanism would not have intercepted that, and
411 * if it had been intercepted then it then it would have replaced
414 * Revision 1.12 2001/05/27 22:17:04 oes
416 * - re_process_buffer no longer writes the modified buffer
417 * to the client, which was very ugly. It now returns the
418 * buffer, which it is then written by chat.
420 * - content_length now adjusts the Content-Length: header
421 * for modified documents rather than crunch()ing it.
422 * (Length info in csp->content_length, which is 0 for
423 * unmodified documents)
425 * - For this to work, sed() is called twice when filtering.
427 * Revision 1.11 2001/05/26 17:27:53 jongfoster
428 * Added support for CLF and fixed LOG_LEVEL_LOG.
429 * Also did CRLF->LF fix of my previous patch.
431 * Revision 1.10 2001/05/26 15:26:15 jongfoster
432 * ACL feature now provides more security by immediately dropping
433 * connections from untrusted hosts.
435 * Revision 1.9 2001/05/26 00:28:36 jongfoster
436 * Automatic reloading of config file.
437 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
438 * Most of the global variables have been moved to a new
439 * struct configuration_spec, accessed through csp->config->globalname
440 * Most of the globals remaining are used by the Win32 GUI.
442 * Revision 1.8 2001/05/25 22:43:18 jongfoster
443 * Fixing minor memory leak and buffer overflow.
445 * Revision 1.7 2001/05/25 22:34:30 jongfoster
448 * Revision 1.6 2001/05/23 00:13:58 joergs
449 * AmigaOS support fixed.
451 * Revision 1.5 2001/05/22 18:46:04 oes
453 * - Enabled filtering banners by size rather than URL
454 * by adding patterns that replace all standard banner
455 * sizes with the "Junkbuster" gif to the re_filterfile
457 * - Enabled filtering WebBugs by providing a pattern
458 * which kills all 1x1 images
460 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
461 * which is selected by the (nonstandard and therefore
462 * capital) letter 'U' in the option string.
463 * It causes the quantifiers to be ungreedy by default.
464 * Appending a ? turns back to greedy (!).
466 * - Added a new interceptor ijb-send-banner, which
467 * sends back the "Junkbuster" gif. Without imagelist or
468 * MSIE detection support, or if tinygif = 1, or the
469 * URL isn't recognized as an imageurl, a lame HTML
470 * explanation is sent instead.
472 * - Added new feature, which permits blocking remote
473 * script redirects and firing back a local redirect
475 * The feature is conditionally compiled, i.e. it
476 * can be disabled with --disable-fast-redirects,
477 * plus it must be activated by a "fast-redirects"
478 * line in the config file, has its own log level
479 * and of course wants to be displayed by show-proxy-args
480 * Note: Boy, all the #ifdefs in 1001 locations and
481 * all the fumbling with configure.in and acconfig.h
482 * were *way* more work than the feature itself :-(
484 * - Because a generic redirect template was needed for
485 * this, tinygif = 3 now uses the same.
487 * - Moved GIFs, and other static HTTP response templates
492 * - Removed some >400 CRs again (Jon, you really worked
495 * Revision 1.4 2001/05/21 19:34:01 jongfoster
496 * Made failure to bind() a fatal error.
498 * Revision 1.3 2001/05/20 01:21:20 jongfoster
499 * Version 2.9.4 checkin.
500 * - Merged popupfile and cookiefile, and added control over PCRS
501 * filtering, in new "permissionsfile".
502 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
503 * file error you now get a message box (in the Win32 GUI) rather
504 * than the program exiting with no explanation.
505 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
507 * - Removed tabs from "config"
508 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
509 * - Bumped up version number.
511 * Revision 1.2 2001/05/17 22:34:44 oes
512 * - Added hint on GIF char array generation to jcc.c
513 * - Cleaned CRLF's from the sources and related files
514 * - Repaired logging for REF and FRC
516 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
517 * Initial import of version 2.9.3 source tree
520 *********************************************************************/
526 #include <sys/types.h>
533 #ifdef FEATURE_PTHREAD
535 #endif /* def FEATURE_PTHREAD */
538 # ifndef FEATURE_PTHREAD
542 # include <windows.h>
543 # include <process.h>
544 # endif /* ndef FEATURE_PTHREAD */
547 # ifndef _WIN_CONSOLE
549 # endif /* ndef _WIN_CONSOLE */
551 #else /* ifndef _WIN32 */
553 # if !defined (__OS2__)
555 # include <sys/wait.h>
556 # endif /* ndef __OS2__ */
557 # include <sys/time.h>
558 # include <sys/stat.h>
559 # include <sys/ioctl.h>
562 #include <sys/termios.h>
573 # include <socket.h> /* BeOS has select() for sockets only. */
574 # include <OS.h> /* declarations for threads and stuff. */
577 # if defined(__EMX__) || defined(__OS2__)
578 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
583 #define bzero(B,N) memset(B,0x00,n)
598 #include "killpopup.h"
599 #include "miscutil.h"
601 #include "jbsockets.h"
606 #include "urlmatch.h"
608 const char jcc_h_rcs[] = JCC_H_VERSION;
609 const char project_h_rcs[] = PROJECT_H_VERSION;
612 struct client_state clients[1];
613 struct file_list files[1];
615 #ifdef FEATURE_STATISTICS
616 int urls_read = 0; /* total nr of urls read inc rejected */
617 int urls_rejected = 0; /* total nr of urls rejected */
618 #endif /* def FEATURE_STATISTICS */
620 #ifdef FEATURE_GRACEFUL_TERMINATION
624 static void listen_loop(void);
625 static void chat(struct client_state *csp);
627 void serve(struct client_state *csp);
628 #else /* ifndef AMIGA */
629 static void serve(struct client_state *csp);
630 #endif /* def AMIGA */
633 static int32 server_thread(void *data);
634 #endif /* def __BEOS__ */
637 #define sleep(N) Sleep(((N) * 1000))
641 #define sleep(N) DosSleep(((N) * 100))
644 #if defined(unix) || defined(__EMX__)
646 const char *pidfile = NULL;
647 int received_hup_signal = 0;
648 #endif /* defined unix */
650 /* The vanilla wafer. */
651 static const char VANILLA_WAFER[] =
652 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
653 "Do_not_send_me_any_copyrighted_information_other_than_the_"
654 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
655 "In_particular_do_not_send_me_any_cookies_that_"
656 "are_subject_to_a_claim_of_copyright_by_anybody._"
657 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
658 "(copyright_or_otherwise)_applying_to_any_cookie._";
661 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
662 /*********************************************************************
664 * Function : sig_handler
666 * Description : Signal handler for different signals.
667 * Exit gracefully on ABRT, TERM and INT
668 * or set a flag that will cause the errlog
669 * to be reopened by the main thread on HUP.
672 * 1 : the_signal = the signal cause this function to call
676 *********************************************************************/
677 static void sig_handler(int the_signal)
684 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
692 received_hup_signal = 1;
697 * We shouldn't be here, unless we catch signals
698 * in main() that we can't handle here!
700 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
708 /*********************************************************************
712 * Description : Once a connection to the client has been accepted,
713 * this function is called (via serve()) to handle the
714 * main business of the communication. When this
715 * function returns, the caller must close the client
719 * 1 : csp = Current client state (buffers, headers, etc...)
721 * Returns : On success, the number of bytes written are returned (zero
722 * indicates nothing was written). On error, -1 is returned,
723 * and errno is set appropriately. If count is zero and the
724 * file descriptor refers to a regular file, 0 will be
725 * returned without causing any other effect. For a special
726 * file, the results are not portable.
728 *********************************************************************/
729 static void chat(struct client_state *csp)
732 * This next lines are a little ugly, but they simplifies the if statements
733 * below. Basically if TOGGLE, then we want the if to test if the
734 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
735 * then we want the if to test for CSP_FLAG_FORCED , else we don't
737 #ifdef FEATURE_TOGGLE
738 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
739 #else /* ifndef FEATURE_TOGGLE */
740 # define IS_TOGGLED_ON_AND
741 #endif /* ndef FEATURE_TOGGLE */
742 #ifdef FEATURE_FORCE_LOAD
743 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
744 #else /* ifndef FEATURE_FORCE_LOAD */
745 # define IS_NOT_FORCED_AND
746 #endif /* def FEATURE_FORCE_LOAD */
748 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
750 char buf[BUFFER_SIZE];
758 int ms_iis5_hack = 0;
760 const struct forward_spec * fwd;
761 struct http_request *http;
762 int len; /* for buffer sizes */
763 #ifdef FEATURE_KILL_POPUPS
764 int block_popups; /* bool, 1==will block popups */
765 int block_popups_now = 0; /* bool, 1==currently blocking popups */
766 #endif /* def FEATURE_KILL_POPUPS */
768 int pcrs_filter; /* bool, 1==will filter through pcrs */
769 int gif_deanimate; /* bool, 1==will deanimate gifs */
771 /* Function that does the content filtering for the current request */
772 char *(*content_filter)() = NULL;
774 /* Skeleton for HTTP response, if we should intercept the request */
775 struct http_response *rsp;
780 * Read the client's request. Note that since we're not using select() we
781 * could get blocked here if a client connected, then didn't say anything!
786 len = read_socket(csp->cfd, buf, sizeof(buf));
788 if (len <= 0) break; /* error! */
790 add_to_iob(csp, buf, len);
792 req = get_header(csp);
796 break; /* no HTTP request! */
801 continue; /* more to come! */
804 #ifdef FEATURE_FORCE_LOAD
805 /* If this request contains the FORCE_PREFIX,
806 * better get rid of it now and set the force flag --oes
809 if (strstr(req, FORCE_PREFIX))
811 strclean(req, FORCE_PREFIX);
812 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
813 csp->flags |= CSP_FLAG_FORCED;
816 #endif /* def FEATURE_FORCE_LOAD */
818 parse_http_request(req, http, csp);
823 if (http->cmd == NULL)
825 strcpy(buf, CHEADER);
826 write_socket(csp->cfd, buf, strlen(buf));
828 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
833 /* decide how to route the HTTP request */
835 if ((fwd = forward_url(http, csp)) == NULL)
837 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
838 /* Never get here - LOG_LEVEL_FATAL causes program exit */
841 /* build the http request to send to the server
842 * we have to do one of the following:
844 * create = use the original HTTP request to create a new
845 * HTTP request that has either the path component
846 * without the http://domainspec (w/path) or the
847 * full orininal URL (w/url)
848 * Note that the path and/or the HTTP version may
849 * have been altered by now.
851 * connect = Open a socket to the host:port of the server
852 * and short-circuit server and client socket.
854 * pass = Pass the request unchanged if forwarding a CONNECT
855 * request to a parent proxy. Note that we'll be sending
856 * the CFAIL message ourselves if connecting to the parent
857 * fails, but we won't send a CSUCCEED message if it works,
858 * since that would result in a double message (ours and the
859 * parent's). After sending the request to the parent, we simply
865 * +--------+--------+
867 * 0 | create | connect|
869 * Forwarding +--------+--------+
871 * 1 | create | pass |
873 * +--------+--------+
878 * Determine the actions for this URL
880 #ifdef FEATURE_TOGGLE
881 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
883 /* Most compatible set of actions (i.e. none) */
884 init_current_action(csp->action);
887 #endif /* ndef FEATURE_TOGGLE */
889 url_actions(http, csp);
894 * Check if a CONNECT request is allowable:
895 * In the absence of a +limit-connect action, allow only port 443.
896 * If there is an action, allow whatever matches the specificaton.
900 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
901 || (csp->action->flags & ACTION_LIMIT_CONNECT
902 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
904 strcpy(buf, CFORBIDDEN);
905 write_socket(csp->cfd, buf, strlen(buf));
907 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
908 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
916 * Downgrade http version from 1.1 to 1.0 if +downgrade
919 if ( (http->ssl == 0)
920 && (!strcmpic(http->ver, "HTTP/1.1"))
921 && (csp->action->flags & ACTION_DOWNGRADE))
924 http->ver = strdup("HTTP/1.0");
926 if (http->ver == NULL)
928 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
933 * Save a copy of the original request for logging
935 http->ocmd = strdup(http->cmd);
937 if (http->ocmd == NULL)
939 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
943 * (Re)build the HTTP request for non-SSL requests.
944 * If forwarding, use the whole URL, else, use only the path.
950 http->cmd = strdup(http->gpc);
951 string_append(&http->cmd, " ");
953 if (fwd->forward_host)
955 string_append(&http->cmd, http->url);
959 string_append(&http->cmd, http->path);
962 string_append(&http->cmd, " ");
963 string_append(&http->cmd, http->ver);
965 if (http->cmd == NULL)
967 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
970 enlist(csp->headers, http->cmd);
974 * If the user has not supplied any wafers, and the user has not
975 * told us to suppress the vanilla wafer, then send the vanilla wafer.
977 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
978 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
980 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
984 #ifdef FEATURE_KILL_POPUPS
985 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
986 #endif /* def FEATURE_KILL_POPUPS */
988 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
989 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
991 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
993 /* grab the rest of the client's headers */
997 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
999 len = read_socket(csp->cfd, buf, sizeof(buf));
1002 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1005 add_to_iob(csp, buf, len);
1009 if (p == NULL) break;
1011 enlist(csp->headers, p);
1015 * We have a request. Now, check to see if we need to
1016 * intercept it, i.e. If ..
1020 /* a CGI call was detected and answered */
1021 (NULL != (rsp = dispatch_cgi(csp)))
1023 /* or we are enabled and... */
1024 || (IS_ENABLED_AND (
1026 /* ..the request was blocked */
1027 ( NULL != (rsp = block_url(csp)))
1029 /* ..or untrusted */
1030 #ifdef FEATURE_TRUST
1031 || ( NULL != (rsp = trust_url(csp)))
1032 #endif /* def FEATURE_TRUST */
1034 /* ..or a fast redirect kicked in */
1035 #ifdef FEATURE_FAST_REDIRECTS
1036 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
1037 (NULL != (rsp = redirect_url(csp))))
1038 #endif /* def FEATURE_FAST_REDIRECTS */
1042 /* Write the answer to the client */
1043 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1044 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1046 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1049 #ifdef FEATURE_STATISTICS
1050 /* Count as a rejected request */
1051 csp->flags |= CSP_FLAG_REJECTED;
1052 #endif /* def FEATURE_STATISTICS */
1054 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
1055 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1056 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1058 /* Clean up and return */
1059 free_http_response(rsp);
1063 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1065 if (fwd->forward_host)
1067 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1068 fwd->forward_host, fwd->forward_port, http->hostport);
1072 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1075 /* here we connect to the server, gateway, or the forwarder */
1077 csp->sfd = forwarded_connect(fwd, http, csp);
1079 if (csp->sfd == JB_INVALID_SOCKET)
1081 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1084 if (errno == EINVAL)
1086 rsp = error_response(csp, "no-such-domain", errno);
1088 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1089 csp->ip_addr_str, http->ocmd);
1093 rsp = error_response(csp, "connect-failed", errno);
1095 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1096 csp->ip_addr_str, http->ocmd);
1100 /* Write the answer to the client */
1103 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1104 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1106 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1110 free_http_response(rsp);
1114 log_error(LOG_LEVEL_CONNECT, "OK");
1116 hdr = sed(client_patterns, add_client_headers, csp);
1119 /* FIXME Should handle error properly */
1120 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1123 list_remove_all(csp->headers);
1125 if (fwd->forward_host || (http->ssl == 0))
1127 /* write the client's (modified) header to the server
1128 * (along with anything else that may be in the buffer)
1131 if (write_socket(csp->sfd, hdr, strlen(hdr))
1132 || (flush_socket(csp->sfd, csp) < 0))
1134 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1137 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1138 csp->ip_addr_str, http->ocmd);
1140 rsp = error_response(csp, "connect-failed", errno);
1144 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1145 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1147 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1151 free_http_response(rsp);
1159 * We're running an SSL tunnel and we're not forwarding,
1160 * so just send the "connect succeeded" message to the
1161 * client, flush the rest, and get out of the way.
1163 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1164 csp->ip_addr_str, http->ocmd);
1166 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1174 /* we're finished with the client's header */
1177 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1179 /* pass data between the client and server
1180 * until one or the other shuts down the connection.
1189 * FD_ZERO here seems to point to an errant macro which crashes.
1190 * So do this by hand for now...
1192 memset(&rfds,0x00,sizeof(fd_set));
1196 FD_SET(csp->cfd, &rfds);
1197 FD_SET(csp->sfd, &rfds);
1199 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1203 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1207 /* this is the body of the browser's request
1208 * just read it and write it.
1211 if (FD_ISSET(csp->cfd, &rfds))
1213 len = read_socket(csp->cfd, buf, sizeof(buf));
1217 break; /* "game over, man" */
1220 if (write_socket(csp->sfd, buf, (size_t)len))
1222 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1229 * The server wants to talk. It could be the header or the body.
1230 * If `hdr' is null, then it's the header otherwise it's the body.
1231 * FIXME: Does `hdr' really mean `host'? No.
1235 if (FD_ISSET(csp->sfd, &rfds))
1238 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1242 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1244 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1245 csp->ip_addr_str, http->ocmd);
1247 rsp = error_response(csp, "connect-failed", errno);
1251 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1252 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1254 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1258 free_http_response(rsp);
1262 /* Add a trailing zero. This lets filter_popups
1263 * use string operations.
1267 #ifdef FEATURE_KILL_POPUPS
1268 /* Filter the popups on this read. */
1269 if (block_popups_now)
1271 filter_popups(buf, csp);
1273 #endif /* def FEATURE_KILL_POPUPS */
1275 /* Normally, this would indicate that we've read
1276 * as much as the server has sent us and we can
1277 * close the client connection. However, Microsoft
1278 * in its wisdom has released IIS/5 with a bug that
1279 * prevents it from sending the trailing \r\n in
1280 * a 302 redirect header (and possibly other headers).
1281 * To work around this if we've haven't parsed
1282 * a full header we'll append a trailing \r\n
1283 * and see if this now generates a valid one.
1285 * This hack shouldn't have any impacts. If we've
1286 * already transmitted the header or if this is a
1287 * SSL connection, then we won't bother with this
1288 * hack. So we only work on partially received
1289 * headers. If we append a \r\n and this still
1290 * doesn't generate a valid header, then we won't
1291 * transmit anything to the client.
1296 if (server_body || http->ssl)
1299 * If we have been buffering up the document,
1300 * now is the time to apply content modification
1301 * and send the result to the client.
1306 * If the content filter fails, use the original
1307 * buffer and length.
1308 * (see p != NULL ? p : csp->iob->cur below)
1310 if (NULL == (p = (*content_filter)(csp)))
1312 csp->content_length = csp->iob->eod - csp->iob->cur;
1315 hdr = sed(server_patterns, add_server_headers, csp);
1318 /* FIXME Should handle error properly */
1319 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1322 if (write_socket(csp->cfd, hdr, strlen(hdr))
1323 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1325 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1335 break; /* "game over, man" */
1339 * This is NOT the body, so
1340 * Let's pretend the server just sent us a blank line.
1342 len = sprintf(buf, "\r\n");
1345 * Now, let the normal header parsing algorithm below do its
1346 * job. If it fails, we'll exit instead of continuing.
1353 * If this is an SSL connection or we're in the body
1354 * of the server document, just write it to the client,
1355 * unless we need to buffer the body for later content-filtering
1358 if (server_body || http->ssl)
1362 add_to_iob(csp, buf, len);
1365 * If the buffer limit will be reached on the next read,
1366 * switch to non-filtering mode, i.e. make & write the
1367 * header, flush the socket and get out of the way.
1369 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1373 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1375 hdr = sed(server_patterns, add_server_headers, csp);
1378 /* FIXME Should handle error properly */
1379 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1382 hdrlen = strlen(hdr);
1383 byte_count += hdrlen;
1385 if (write_socket(csp->cfd, hdr, hdrlen)
1386 || ((len = flush_socket(csp->cfd, csp)) < 0))
1388 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1397 content_filter = NULL;
1404 if (write_socket(csp->cfd, buf, (size_t)len))
1406 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1415 /* we're still looking for the end of the
1416 * server's header ... (does that make header
1417 * parsing an "out of body experience" ?
1420 /* buffer up the data we just read */
1421 add_to_iob(csp, buf, len);
1423 /* get header lines from the iob */
1425 while ((p = get_header(csp)) != NULL)
1429 /* see following note */
1432 enlist(csp->headers, p);
1436 /* NOTE: there are no "empty" headers so
1437 * if the pointer `p' is not NULL we must
1438 * assume that we reached the end of the
1439 * buffer before we hit the end of the header.
1446 /* Well, we tried our MS IIS/5
1447 * hack and it didn't work.
1448 * The header is incomplete
1449 * and there isn't anything
1450 * we can do about it.
1456 /* Since we have to wait for
1457 * more from the server before
1458 * we can parse the headers
1459 * we just continue here.
1465 /* we have now received the entire header.
1466 * filter it and send the result to the client
1469 hdr = sed(server_patterns, add_server_headers, csp);
1472 /* FIXME Should handle error properly */
1473 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1476 #ifdef FEATURE_KILL_POPUPS
1477 /* Start blocking popups if appropriate. */
1479 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1480 !http->ssl && /* We talk plaintext */
1481 block_popups) /* Policy allows */
1483 block_popups_now = 1;
1485 * Filter the part of the body that came in the same read
1486 * as the last headers:
1488 filter_popups(csp->iob->cur, csp);
1491 #endif /* def FEATURE_KILL_POPUPS */
1493 /* Buffer and pcrs filter this if appropriate. */
1495 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1496 !http->ssl && /* We talk plaintext */
1497 pcrs_filter) /* Policy allows */
1499 content_filter = pcrs_filter_response;
1502 /* Buffer and gif_deanimate this if appropriate. */
1504 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1505 !http->ssl && /* We talk plaintext */
1506 gif_deanimate) /* Policy allows */
1508 content_filter = gif_deanimate_response;
1512 * Only write if we're not buffering for content modification
1514 if (!content_filter)
1516 /* write the server's (modified) header to
1517 * the client (along with anything else that
1518 * may be in the buffer)
1521 if (write_socket(csp->cfd, hdr, strlen(hdr))
1522 || ((len = flush_socket(csp->cfd, csp)) < 0))
1524 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1526 /* the write failed, so don't bother
1527 * mentioning it to the client...
1528 * it probably can't hear us anyway.
1537 /* we're finished with the server's header */
1542 /* If this was a MS IIS/5 hack then it means
1543 * the server has already closed the
1544 * connection. Nothing more to read. Time
1555 return; /* huh? we should never get here */
1558 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1559 csp->ip_addr_str, http->ocmd, byte_count);
1563 /*********************************************************************
1567 * Description : This is little more than chat. We only "serve" to
1568 * to close any socket that chat may have opened.
1571 * 1 : csp = Current client state (buffers, headers, etc...)
1575 *********************************************************************/
1577 void serve(struct client_state *csp)
1578 #else /* ifndef AMIGA */
1579 static void serve(struct client_state *csp)
1580 #endif /* def AMIGA */
1583 close_socket(csp->cfd);
1585 if (csp->sfd != JB_INVALID_SOCKET)
1587 close_socket(csp->sfd);
1590 csp->flags &= ~CSP_FLAG_ACTIVE;
1596 /*********************************************************************
1598 * Function : server_thread
1600 * Description : We only exist to call `serve' in a threaded environment.
1603 * 1 : data = Current client state (buffers, headers, etc...)
1605 * Returns : Always 0.
1607 *********************************************************************/
1608 static int32 server_thread(void *data)
1610 serve((struct client_state *) data);
1617 /*********************************************************************
1621 * Description : Print usage info & exit.
1623 * Parameters : Pointer to argv[0] for identifying ourselves
1627 *********************************************************************/
1628 void usage(const char *myname)
1630 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
1631 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1632 "Aborting.\n", myname);
1639 /*********************************************************************
1643 * Description : Load the config file and start the listen loop.
1644 * This function is a lot more *sane* with the `load_config'
1645 * and `listen_loop' functions; although it stills does
1646 * a *little* too much for my taste.
1649 * 1 : argc = Number of parameters (including $0).
1650 * 2 : argv = Array of (char *)'s to the parameters.
1652 * Returns : 1 if : can't open config file, unrecognized directive,
1653 * stats requested in multi-thread mode, can't open the
1654 * log file, can't open the jar file, listen port is invalid,
1655 * any load fails, and can't bind port.
1657 * Else main never returns, the process must be signaled
1658 * to terminate execution. Or, on Windows, use the
1659 * "File", "Exit" menu option.
1661 *********************************************************************/
1663 int real_main(int argc, const char *argv[])
1665 int main(int argc, const char *argv[])
1670 struct passwd *pw = NULL;
1671 struct group *grp = NULL;
1679 #if !defined(_WIN32)
1687 * Parse the command line arguments
1689 while (++argc_pos < argc)
1691 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1693 if (strcmp(argv[argc_pos], "--help") == 0)
1698 else if(strcmp(argv[argc_pos], "--version") == 0)
1700 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1704 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1709 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1711 if (++argc_pos == argc) usage(argv[0]);
1712 pidfile = strdup(argv[argc_pos]);
1715 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1717 if (++argc_pos == argc) usage(argv[argc_pos]);
1719 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1722 if (NULL == (grp = getgrnam(p)))
1724 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1728 if (NULL == (pw = getpwnam(argv[argc_pos])))
1730 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1733 if (p != NULL) *--p = '\0';
1735 #endif /* defined(unix) */
1737 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1739 configfile = argv[argc_pos];
1742 } /* -END- while (more arguments) */
1745 if ( *configfile != '/' )
1749 /* make config-filename absolute here */
1750 if ( !(basedir = getcwd( NULL, 1024 )))
1752 perror("get working dir failed");
1756 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1758 perror("malloc failed");
1761 strcpy( abs_file, basedir );
1762 strcat( abs_file, "/" );
1763 strcat( abs_file, configfile );
1764 configfile = abs_file;
1766 #endif /* defined unix */
1773 #elif defined(_WIN32)
1778 * Unix signal handling
1780 * Catch the abort, interrupt and terminate signals for a graceful exit
1781 * Catch the hangup signal so the errlog can be reopened.
1782 * Ignore the broken pipe and child signals
1783 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1785 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1788 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1789 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1791 for (idx = 0; catched_signals[idx] != 0; idx++)
1793 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1795 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1799 for (idx = 0; ignored_signals[idx] != 0; idx++)
1801 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1803 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1808 #else /* ifdef _WIN32 */
1809 # ifdef _WIN_CONSOLE
1811 * We *are* in a windows console app.
1812 * Print a verbose messages about FAQ's and such
1814 printf(win32_blurb);
1815 # endif /* def _WIN_CONSOLE */
1816 #endif /* def _WIN32 */
1819 /* Initialize the CGI subsystem */
1820 cgi_init_error_messages();
1823 * If runnig on unix and without the --nodaemon
1824 * option, become a daemon. I.e. fork, detach
1825 * from tty and get process group leadership
1838 if ( pid < 0 ) /* error */
1843 else if ( pid != 0 ) /* parent */
1848 * must check for errors
1849 * child died due to missing files aso
1852 wpid = waitpid( pid, &status, WNOHANG );
1861 /* Should be more portable, but not as well tested */
1866 #else /* ndef __FreeBSD__ */
1868 #endif /* ndef __FreeBSD__ */
1869 fd = open("/dev/tty", O_RDONLY);
1872 /* no error check here */
1873 ioctl( fd, TIOCNOTTY,0 );
1877 /* FIXME: should close stderr (fd 2) here too, but the test
1879 * and load config file is done in listen_loop() and puts
1880 * some messages on stderr there.
1887 } /* -END- if (!no_daemon) */
1890 * As soon as we have written the PID file, we can switch
1891 * to the user and group ID indicated by the --user option
1897 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1899 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1901 if (setuid(pw->pw_uid))
1903 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1907 #endif /* defined unix */
1917 /*********************************************************************
1919 * Function : bind_port_helper
1921 * Description : Bind the listen port. Handles logging, and aborts
1925 * 1 : config = Privoxy configuration. Specifies port
1928 * Returns : Port that was opened.
1930 *********************************************************************/
1931 static jb_socket bind_port_helper(struct configuration_spec * config)
1936 if ( (config->haddr != NULL)
1937 && (config->haddr[0] == '1')
1938 && (config->haddr[1] == '2')
1939 && (config->haddr[2] == '7')
1940 && (config->haddr[3] == '.') )
1942 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1945 else if (config->haddr == NULL)
1947 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1952 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1953 config->hport, config->haddr);
1956 result = bind_port(config->haddr, config->hport, &bfd);
1963 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1964 "There may be another Privoxy or some other "
1965 "proxy running on port %d",
1966 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1967 config->hport, config->hport);
1970 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1971 "The hostname is not resolvable",
1972 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1975 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
1976 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1979 /* shouldn't get here */
1980 return JB_INVALID_SOCKET;
1983 config->need_bind = 0;
1989 /*********************************************************************
1991 * Function : listen_loop
1993 * Description : bind the listen port and enter a "FOREVER" listening loop.
1999 *********************************************************************/
2000 static void listen_loop(void)
2002 struct client_state *csp = NULL;
2004 struct configuration_spec * config;
2006 config = load_config();
2008 bfd = bind_port_helper(config);
2010 #ifdef FEATURE_GRACEFUL_TERMINATION
2011 while (!g_terminate)
2016 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
2017 while (waitpid(-1, NULL, WNOHANG) > 0)
2019 /* zombie children */
2021 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2024 * Free data that was used by died threads
2030 * Re-open the errlog after HUP signal
2032 if (received_hup_signal)
2034 init_error_log(Argv[0], config->logfile, config->debug);
2035 received_hup_signal = 0;
2040 #ifdef FEATURE_COOKIE_JAR
2042 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
2043 * already open. I think unload_configfile() is not being run, which should do
2044 * this work. Until that can get resolved, we'll use this workaround.
2048 if (csp->config->jar)
2050 fclose(csp->config->jar);
2051 csp->config->jar = NULL;
2053 #endif /* FEATURE_COOKIE_JAR */
2054 #endif /* __OS2__ */
2056 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2058 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2062 csp->flags |= CSP_FLAG_ACTIVE;
2063 csp->sfd = JB_INVALID_SOCKET;
2065 csp->config = config = load_config();
2067 if ( config->need_bind )
2070 * Since we were listening to the "old port", we will not see
2071 * a "listen" param change until the next IJB request. So, at
2072 * least 1 more request must be made for us to find the new
2073 * setting. I am simply closing the old socket and binding the
2076 * Which-ever is correct, we will serve 1 more page via the
2077 * old settings. This should probably be a "show-proxy-args"
2078 * request. This should not be a so common of an operation
2079 * that this will hurt people's feelings.
2084 bfd = bind_port_helper(config);
2087 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2089 if (!accept_connection(csp, bfd))
2091 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2104 log_error(LOG_LEVEL_CONNECT, "OK");
2107 #ifdef FEATURE_TOGGLE
2110 csp->flags |= CSP_FLAG_TOGGLED_ON;
2112 #endif /* def FEATURE_TOGGLE */
2114 if (run_loader(csp))
2116 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2117 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2121 if (block_acl(NULL,csp))
2123 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2124 close_socket(csp->cfd);
2128 #endif /* def FEATURE_ACL */
2130 /* add it to the list of clients */
2131 csp->next = clients->next;
2132 clients->next = csp;
2134 if (config->multi_threaded)
2138 /* this is a switch () statment in the C preprocessor - ugh */
2139 #undef SELECTED_ONE_OPTION
2141 /* Use Pthreads in preference to native code */
2142 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2143 #define SELECTED_ONE_OPTION
2145 pthread_t the_thread;
2146 pthread_attr_t attrs;
2148 pthread_attr_init(&attrs);
2149 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2150 child_id = (pthread_create(&the_thread, &attrs,
2151 (void*)serve, csp) ? -1 : 0);
2152 pthread_attr_destroy(&attrs);
2156 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2157 #define SELECTED_ONE_OPTION
2158 child_id = _beginthread(
2159 (void (*)(void *))serve,
2164 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2165 #define SELECTED_ONE_OPTION
2166 child_id = _beginthread(
2167 (void(* _Optlink)(void*))serve,
2173 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2174 #define SELECTED_ONE_OPTION
2176 thread_id tid = spawn_thread
2177 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2179 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2181 child_id = (int) tid;
2190 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2191 #define SELECTED_ONE_OPTION
2192 csp->cfd = ReleaseSocket(csp->cfd, -1);
2193 if((child_id = (int)CreateNewProcTags(
2194 NP_Entry, (ULONG)server_thread,
2195 NP_Output, Output(),
2196 NP_CloseOutput, FALSE,
2197 NP_Name, (ULONG)"privoxy child",
2198 NP_StackSize, 200*1024,
2202 ((struct Task *)child_id)->tc_UserData = csp;
2203 Signal((struct Task *)child_id, SIGF_SINGLE);
2208 #if !defined(SELECTED_ONE_OPTION)
2211 /* This block is only needed when using fork().
2212 * When using threads, the server thread was
2213 * created and run by the call to _beginthread().
2215 if (child_id == 0) /* child */
2221 else if (child_id > 0) /* parent */
2223 /* in a fork()'d environment, the parent's
2224 * copy of the client socket and the CSP
2228 #if !defined(_WIN32) && defined(__CYGWIN__)
2230 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2231 close_socket(csp->cfd);
2232 csp->flags &= ~CSP_FLAG_ACTIVE;
2236 #undef SELECTED_ONE_OPTION
2237 /* end of cpp switch () */
2239 if (child_id < 0) /* failed */
2241 char buf[BUFFER_SIZE];
2243 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2245 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
2247 write_socket(csp->cfd, buf, strlen(buf));
2248 close_socket(csp->cfd);
2249 csp->flags &= ~CSP_FLAG_ACTIVE;
2260 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2262 /* Clean up. Aim: free all memory (no leaks) */
2263 #ifdef FEATURE_GRACEFUL_TERMINATION
2265 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2267 unload_current_config_file();
2268 unload_current_actions_file();
2269 unload_current_re_filterfile();
2270 #ifdef FEATURE_TRUST
2271 unload_current_trust_file();
2274 if (config->multi_threaded)
2281 } while ((clients->next != NULL) && (--i > 0));
2285 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2294 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2295 /* Cleanup - remove taskbar icon etc. */
2300 #endif /* FEATURE_GRACEFUL_TERMINATION */