1 const char jcc_rcs[] = "$Id: jcc.c,v 1.86 2002/03/25 17:04:55 david__schmidt 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.86 2002/03/25 17:04:55 david__schmidt
37 * Workaround for closing the jarfile before load_config() comes around again
39 * Revision 1.85 2002/03/24 15:23:33 jongfoster
42 * Revision 1.84 2002/03/24 13:25:43 swa
43 * name change related issues
45 * Revision 1.83 2002/03/16 23:54:06 jongfoster
46 * Adding graceful termination feature, to help look for memory leaks.
47 * If you enable this (which, by design, has to be done by hand
48 * editing config.h) and then go to http://i.j.b/die, then the program
49 * will exit cleanly after the *next* request. It should free all the
50 * memory that was used.
52 * Revision 1.82 2002/03/13 00:27:05 jongfoster
55 * Revision 1.81 2002/03/12 01:42:50 oes
56 * Introduced modular filters
58 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
59 * OS/2 port maintenance:
60 * - Fixed EMX build - it had decayed a little
61 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
62 * substituted a memset for now.
64 * Revision 1.79 2002/03/09 20:03:52 jongfoster
65 * - Making various functions return int rather than size_t.
66 * (Undoing a recent change). Since size_t is unsigned on
67 * Windows, functions like read_socket that return -1 on
68 * error cannot return a size_t.
70 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
71 * crashes, and also frequently caused JB to jump to 100%
72 * CPU and stay there. (Because it thought it had just
73 * read ((unsigned)-1) == 4Gb of data...)
75 * - The signature of write_socket has changed, it now simply
76 * returns success=0/failure=nonzero.
78 * - Trying to get rid of a few warnings --with-debug on
79 * Windows, I've introduced a new type "jb_socket". This is
80 * used for the socket file descriptors. On Windows, this
81 * is SOCKET (a typedef for unsigned). Everywhere else, it's
82 * an int. The error value can't be -1 any more, so it's
83 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
84 * Windows it maps to the #define INVALID_SOCKET.)
86 * - The signature of bind_port has changed.
88 * Revision 1.78 2002/03/08 21:35:04 oes
89 * Added optional group supplement to --user option. Will now use default group of user if no group given
91 * Revision 1.77 2002/03/07 03:52:06 oes
92 * - Fixed compiler warnings etc
93 * - Improved handling of failed DNS lookups
95 * Revision 1.76 2002/03/06 22:54:35 jongfoster
96 * Automated function-comment nitpicking.
98 * Revision 1.75 2002/03/06 10:02:19 oes
99 * Fixed stupid bug when --user was not given
101 * Revision 1.74 2002/03/06 00:49:31 jongfoster
102 * Fixing warning on Windows
103 * Making #ifdefs that refer to the same variable consistently
104 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
106 * Revision 1.73 2002/03/05 23:57:30 hal9
107 * Stray character 's' on line 1618 was breaking build.
109 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
110 * - Re-enable OS/2 building after new parms were added
111 * - Fix false out of memory report when resolving CGI templates when no IP
112 * address is available of failed attempt (a la no such domain)
114 * Revision 1.71 2002/03/05 18:13:56 oes
115 * Added --user option
117 * Revision 1.70 2002/03/05 04:52:42 oes
118 * Deleted non-errlog debugging code
120 * Revision 1.69 2002/03/04 23:50:00 jongfoster
121 * Splitting off bind_port() call into bind_port_helper(), with
124 * Revision 1.68 2002/03/04 20:17:32 oes
127 * Revision 1.67 2002/03/04 18:18:57 oes
128 * - Removed _DEBUG mode
129 * - Cleand up cmdline parsing
130 * - Introduced --no-daemon, --pidfile options
131 * - Cleaned up signal handling:
132 * - Terminate cleanly on INT, TERM and ABRT
133 * - Schedule logfile for re-opening on HUP
134 * - Ignore CHLD and PIPE
135 * - Leave the rest with their default handlers
136 * - Uniform handler registration
137 * - Added usage() function
138 * - Played styleguide police
140 * Revision 1.66 2002/03/03 15:06:55 oes
141 * Re-enabled automatic config reloading
143 * Revision 1.65 2002/03/03 14:49:11 oes
144 * Fixed CLF logging: Now uses client's original HTTP request
146 * Revision 1.64 2002/03/03 09:18:03 joergs
147 * Made jumbjuster work on AmigaOS again.
149 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
150 * Clean up a little CRLF unpleasantness that suddenly appeared
152 * Revision 1.62 2002/02/20 23:17:23 jongfoster
153 * Detecting some out-of memory conditions and exiting with a log message.
155 * Revision 1.61 2002/01/17 21:01:52 jongfoster
156 * Moving all our URL and URL pattern parsing code to urlmatch.c.
158 * Revision 1.60 2001/12/30 14:07:32 steudten
159 * - Add signal handling (unix)
160 * - Add SIGHUP handler (unix)
161 * - Add creation of pidfile (unix)
162 * - Add action 'top' in rc file (RH)
163 * - Add entry 'SIGNALS' to manpage
164 * - Add exit message to logfile (unix)
166 * Revision 1.59 2001/12/13 14:07:18 oes
167 * Fixed Bug: 503 error page now sent OK
169 * Revision 1.58 2001/11/30 23:37:24 jongfoster
170 * Renaming the Win32 config file to config.txt - this is almost the
171 * same as the corresponding UNIX name "config"
173 * Revision 1.57 2001/11/16 00:47:43 jongfoster
174 * Changing the tty-disconnection code to use setsid().
176 * Revision 1.56 2001/11/13 20:20:54 jongfoster
177 * Tabs->spaces, fixing a bug with missing {} around an if()
179 * Revision 1.55 2001/11/13 20:14:53 jongfoster
180 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
182 * Revision 1.54 2001/11/07 00:03:14 steudten
183 * Give reliable return value if an error
184 * occurs not just 0 with new daemon mode.
186 * Revision 1.53 2001/11/05 21:41:43 steudten
187 * Add changes to be a real daemon just for unix os.
188 * (change cwd to /, detach from controlling tty, set
189 * process group and session leader to the own process.
191 * Add some fatal-error log message for failed malloc().
192 * Add '-d' if compiled with 'configure --with-debug' to
193 * enable debug output.
195 * Revision 1.52 2001/10/26 20:11:20 jongfoster
196 * Fixing type mismatch
198 * Revision 1.51 2001/10/26 17:38:28 oes
201 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
202 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
203 * threads to call select() simultaneously. So, it's time to do a real, live,
204 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
205 * (native). Both versions will work, but using __OS2__ offers multi-threading.
207 * Revision 1.49 2001/10/23 21:41:35 jongfoster
208 * Added call to initialize the (statically-allocated of course)
209 * "out of memory" CGI response.
211 * Revision 1.48 2001/10/10 19:56:46 jongfoster
212 * Moving some code that wasn't cookie-related out of an #ifdef
215 * Revision 1.47 2001/10/10 16:44:36 oes
216 * Added CONNECT destination port limitation check
218 * Revision 1.46 2001/10/08 15:17:41 oes
219 * Re-enabled SSL forwarding
221 * Revision 1.45 2001/10/07 15:42:11 oes
222 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
224 * Moved downgrading of the HTTP version from parse_http_request to
225 * chat(), since we can't decide if it is necessary before we have
226 * determined the actions for the URL. The HTTP command is now
227 * *always* re-built so the repairs need no longer be special-cased.
229 * filter_popups now gets a csp pointer so it can raise the new
230 * CSP_FLAG_MODIFIED flag.
234 * Added configurable size limit for the IOB. If the IOB grows so
235 * large that the next read would exceed the limit, the header
236 * is generated, and the header & unfiltered buffer are flushed
237 * to the client. Chat then continues in non-buffering,
238 * non-filtering body mode.
240 * Revision 1.44 2001/10/02 18:13:57 oes
243 * Revision 1.43 2001/10/02 15:32:13 oes
244 * Moved generation of hdr
246 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
247 * Cleaning up 2 compiler warnings on OS/2.
249 * Revision 1.41 2001/09/16 17:05:14 jongfoster
250 * Removing unused #include showarg.h
252 * Revision 1.40 2001/09/16 15:41:45 jongfoster
253 * Fixing signed/unsigned comparison warning.
255 * Revision 1.39 2001/09/16 13:21:27 jongfoster
256 * Changes to use new list functions.
258 * Revision 1.38 2001/09/16 13:01:46 jongfoster
259 * Removing redundant function call that zeroed zalloc()'d memory.
261 * Revision 1.37 2001/09/10 11:12:24 oes
262 * Deleted unused variable
264 * Revision 1.36 2001/09/10 10:56:15 oes
265 * Silenced compiler warnings
267 * Revision 1.35 2001/07/31 14:44:22 oes
268 * Deleted unused size parameter from filter_popups()
270 * Revision 1.34 2001/07/30 22:08:36 jongfoster
271 * Tidying up #defines:
272 * - All feature #defines are now of the form FEATURE_xxx
273 * - Permanently turned off WIN_GUI_EDIT
274 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
276 * Revision 1.33 2001/07/29 19:32:00 jongfoster
277 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
279 * Revision 1.32 2001/07/29 18:47:05 jongfoster
280 * Adding missing #include "loadcfg.h"
282 * Revision 1.31 2001/07/29 12:17:48 oes
283 * Applied pthread fix by Paul Lieverse
285 * Revision 1.30 2001/07/25 22:57:13 jongfoster
286 * __BEOS__ no longer overrides FEATURE_PTHREAD.
287 * This is because FEATURE_PTHREAD will soon be widely used, so I
288 * want to keep it simple.
290 * Revision 1.29 2001/07/24 12:47:06 oes
291 * Applied BeOS support update by Eugenia
293 * Revision 1.28 2001/07/23 13:26:12 oes
294 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
296 * Revision 1.27 2001/07/19 19:09:47 haroon
297 * - Added code to take care of the situation where while processing the first
298 * server response (which includes the server header), after finding the end
299 * of the headers we were not looking past the end of the headers for
300 * content modification. I enabled it for filter_popups.
301 * Someone else should look to see if other similar operations should be
302 * done to the discarded portion of the buffer.
304 * Note 2001/07/20: No, the other content modification mechanisms will process
305 * the whole iob later anyway. --oes
307 * Revision 1.26 2001/07/18 12:31:36 oes
310 * Revision 1.25 2001/07/15 19:43:49 jongfoster
311 * Supports POSIX threads.
312 * Also removed some unused #includes.
314 * Revision 1.24 2001/07/13 14:00:40 oes
315 * - Generic content modification scheme:
316 * Each feature has its own applicability flag that is set
317 * from csp->action->flags.
318 * Replaced the "filtering" int flag , by a function pointer
319 * "content_filter" to the function that will do the content
320 * modification. If it is != NULL, the document will be buffered
321 * and processed through *content_filter, which must set
322 * csp->content_length and return a modified copy of the body
323 * or return NULL (on failiure).
324 * - Changed csp->is_text to the more generic bitmap csp->content_type
325 * which can currently take the valued CT_TEXT or CT_GIF
327 * - Removed all #ifdef PCRS
329 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
330 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
331 * the `block_acl' call. This prevents a compilation error when the user
332 * does not wish to use the "ACL" feature.
334 * Revision 1.22 2001/06/29 21:45:41 oes
335 * Indentation, CRLF->LF, Tab-> Space
337 * Revision 1.21 2001/06/29 13:29:36 oes
338 * - Cleaned up, improved comments
339 * - Unified all possible interceptors (CGI,
340 * block, trust, fast_redirect) in one
341 * place, with one (CGI) answer generation
342 * mechansim. Much clearer now.
343 * - Removed the GIF image generation, which
344 * is now done in filters.c:block_url()
345 * - Made error conditions like domain lookup
346 * failiure or (various) problems while talking
347 * to the server use cgi.c:error_response()
348 * instead of generating HTML/HTTP in chat() (yuck!)
349 * - Removed logentry from cancelled commit
351 * Revision 1.20 2001/06/09 10:55:28 jongfoster
352 * Changing BUFSIZ ==> BUFFER_SIZE
354 * Revision 1.19 2001/06/07 23:12:52 jongfoster
355 * Replacing function pointer in struct gateway with a directly
356 * called function forwarded_connect().
357 * Replacing struct gateway with struct forward_spec
359 * Revision 1.18 2001/06/03 19:12:16 oes
360 * introduced new cgi handling
362 * Revision 1.17 2001/06/01 20:07:23 jongfoster
363 * Now uses action +image-blocker{} rather than config->tinygif
365 * Revision 1.16 2001/06/01 18:49:17 jongfoster
366 * Replaced "list_share" with "list" - the tiny memory gain was not
367 * worth the extra complexity.
369 * Revision 1.15 2001/05/31 21:24:47 jongfoster
370 * Changed "permission" to "action" throughout.
371 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
372 * Moved vanilla wafer check into chat(), since we must now
373 * decide whether or not to add it based on the URL.
375 * Revision 1.14 2001/05/29 20:14:01 joergs
376 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
379 * Revision 1.13 2001/05/29 09:50:24 jongfoster
380 * Unified blocklist/imagelist/permissionslist.
381 * File format is still under discussion, but the internal changes
384 * Also modified interceptor behaviour:
385 * - We now intercept all URLs beginning with one of the following
386 * prefixes (and *only* these prefixes):
388 * * http://ijbswa.sf.net/config/
389 * * http://ijbswa.sourceforge.net/config/
390 * - New interceptors "home page" - go to http://i.j.b/ to see it.
391 * - Internal changes so that intercepted and fast redirect pages
392 * are not replaced with an image.
393 * - Interceptors now have the option to send a binary page direct
394 * to the client. (i.e. ijb-send-banner uses this)
395 * - Implemented show-url-info interceptor. (Which is why I needed
396 * the above interceptors changes - a typical URL is
397 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
398 * The previous mechanism would not have intercepted that, and
399 * if it had been intercepted then it then it would have replaced
402 * Revision 1.12 2001/05/27 22:17:04 oes
404 * - re_process_buffer no longer writes the modified buffer
405 * to the client, which was very ugly. It now returns the
406 * buffer, which it is then written by chat.
408 * - content_length now adjusts the Content-Length: header
409 * for modified documents rather than crunch()ing it.
410 * (Length info in csp->content_length, which is 0 for
411 * unmodified documents)
413 * - For this to work, sed() is called twice when filtering.
415 * Revision 1.11 2001/05/26 17:27:53 jongfoster
416 * Added support for CLF and fixed LOG_LEVEL_LOG.
417 * Also did CRLF->LF fix of my previous patch.
419 * Revision 1.10 2001/05/26 15:26:15 jongfoster
420 * ACL feature now provides more security by immediately dropping
421 * connections from untrusted hosts.
423 * Revision 1.9 2001/05/26 00:28:36 jongfoster
424 * Automatic reloading of config file.
425 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
426 * Most of the global variables have been moved to a new
427 * struct configuration_spec, accessed through csp->config->globalname
428 * Most of the globals remaining are used by the Win32 GUI.
430 * Revision 1.8 2001/05/25 22:43:18 jongfoster
431 * Fixing minor memory leak and buffer overflow.
433 * Revision 1.7 2001/05/25 22:34:30 jongfoster
436 * Revision 1.6 2001/05/23 00:13:58 joergs
437 * AmigaOS support fixed.
439 * Revision 1.5 2001/05/22 18:46:04 oes
441 * - Enabled filtering banners by size rather than URL
442 * by adding patterns that replace all standard banner
443 * sizes with the "Junkbuster" gif to the re_filterfile
445 * - Enabled filtering WebBugs by providing a pattern
446 * which kills all 1x1 images
448 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
449 * which is selected by the (nonstandard and therefore
450 * capital) letter 'U' in the option string.
451 * It causes the quantifiers to be ungreedy by default.
452 * Appending a ? turns back to greedy (!).
454 * - Added a new interceptor ijb-send-banner, which
455 * sends back the "Junkbuster" gif. Without imagelist or
456 * MSIE detection support, or if tinygif = 1, or the
457 * URL isn't recognized as an imageurl, a lame HTML
458 * explanation is sent instead.
460 * - Added new feature, which permits blocking remote
461 * script redirects and firing back a local redirect
463 * The feature is conditionally compiled, i.e. it
464 * can be disabled with --disable-fast-redirects,
465 * plus it must be activated by a "fast-redirects"
466 * line in the config file, has its own log level
467 * and of course wants to be displayed by show-proxy-args
468 * Note: Boy, all the #ifdefs in 1001 locations and
469 * all the fumbling with configure.in and acconfig.h
470 * were *way* more work than the feature itself :-(
472 * - Because a generic redirect template was needed for
473 * this, tinygif = 3 now uses the same.
475 * - Moved GIFs, and other static HTTP response templates
480 * - Removed some >400 CRs again (Jon, you really worked
483 * Revision 1.4 2001/05/21 19:34:01 jongfoster
484 * Made failure to bind() a fatal error.
486 * Revision 1.3 2001/05/20 01:21:20 jongfoster
487 * Version 2.9.4 checkin.
488 * - Merged popupfile and cookiefile, and added control over PCRS
489 * filtering, in new "permissionsfile".
490 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
491 * file error you now get a message box (in the Win32 GUI) rather
492 * than the program exiting with no explanation.
493 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
495 * - Removed tabs from "config"
496 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
497 * - Bumped up version number.
499 * Revision 1.2 2001/05/17 22:34:44 oes
500 * - Added hint on GIF char array generation to jcc.c
501 * - Cleaned CRLF's from the sources and related files
502 * - Repaired logging for REF and FRC
504 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
505 * Initial import of version 2.9.3 source tree
508 *********************************************************************/
514 #include <sys/types.h>
521 #ifdef FEATURE_PTHREAD
523 #endif /* def FEATURE_PTHREAD */
526 # ifndef FEATURE_PTHREAD
527 # include <windows.h>
528 # include <process.h>
529 # endif /* ndef FEATURE_PTHREAD */
532 # ifndef _WIN_CONSOLE
534 # endif /* ndef _WIN_CONSOLE */
536 #else /* ifndef _WIN32 */
538 # if !defined (__OS2__)
540 # include <sys/wait.h>
541 # endif /* ndef __OS2__ */
542 # include <sys/time.h>
543 # include <sys/stat.h>
544 # include <sys/ioctl.h>
547 #include <sys/termios.h>
558 # include <socket.h> /* BeOS has select() for sockets only. */
559 # include <OS.h> /* declarations for threads and stuff. */
562 # if defined(__EMX__) || defined(__OS2__)
563 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
568 #define bzero(B,N) memset(B,0x00,n)
583 #include "killpopup.h"
584 #include "miscutil.h"
586 #include "jbsockets.h"
591 #include "urlmatch.h"
593 const char jcc_h_rcs[] = JCC_H_VERSION;
594 const char project_h_rcs[] = PROJECT_H_VERSION;
597 struct client_state clients[1];
598 struct file_list files[1];
600 #ifdef FEATURE_STATISTICS
601 int urls_read = 0; /* total nr of urls read inc rejected */
602 int urls_rejected = 0; /* total nr of urls rejected */
603 #endif /* def FEATURE_STATISTICS */
605 #ifdef FEATURE_GRACEFUL_TERMINATION
609 static void listen_loop(void);
610 static void chat(struct client_state *csp);
612 void serve(struct client_state *csp);
613 #else /* ifndef AMIGA */
614 static void serve(struct client_state *csp);
615 #endif /* def AMIGA */
618 static int32 server_thread(void *data);
619 #endif /* def __BEOS__ */
622 #define sleep(N) Sleep(((N) * 1000))
626 #define sleep(N) DosSleep(((N) * 100))
629 #if defined(unix) || defined(__EMX__)
631 const char *pidfile = NULL;
632 int received_hup_signal = 0;
633 #endif /* defined unix */
635 /* The vanilla wafer. */
636 static const char VANILLA_WAFER[] =
637 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
638 "Do_not_send_me_any_copyrighted_information_other_than_the_"
639 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
640 "In_particular_do_not_send_me_any_cookies_that_"
641 "are_subject_to_a_claim_of_copyright_by_anybody._"
642 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
643 "(copyright_or_otherwise)_applying_to_any_cookie._";
646 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
647 /*********************************************************************
649 * Function : sig_handler
651 * Description : Signal handler for different signals.
652 * Exit gracefully on ABRT, TERM and INT
653 * or set a flag that will cause the errlog
654 * to be reopened by the main thread on HUP.
657 * 1 : the_signal = the signal cause this function to call
661 *********************************************************************/
662 static void sig_handler(int the_signal)
669 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
677 received_hup_signal = 1;
682 * We shouldn't be here, unless we catch signals
683 * in main() that we can't handle here!
685 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
693 /*********************************************************************
697 * Description : Once a connection to the client has been accepted,
698 * this function is called (via serve()) to handle the
699 * main business of the communication. When this
700 * function returns, the caller must close the client
704 * 1 : csp = Current client state (buffers, headers, etc...)
706 * Returns : On success, the number of bytes written are returned (zero
707 * indicates nothing was written). On error, -1 is returned,
708 * and errno is set appropriately. If count is zero and the
709 * file descriptor refers to a regular file, 0 will be
710 * returned without causing any other effect. For a special
711 * file, the results are not portable.
713 *********************************************************************/
714 static void chat(struct client_state *csp)
717 * This next lines are a little ugly, but they simplifies the if statements
718 * below. Basically if TOGGLE, then we want the if to test if the
719 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
720 * then we want the if to test for CSP_FLAG_FORCED , else we don't
722 #ifdef FEATURE_TOGGLE
723 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
724 #else /* ifndef FEATURE_TOGGLE */
725 # define IS_TOGGLED_ON_AND
726 #endif /* ndef FEATURE_TOGGLE */
727 #ifdef FEATURE_FORCE_LOAD
728 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
729 #else /* ifndef FEATURE_FORCE_LOAD */
730 # define IS_NOT_FORCED_AND
731 #endif /* def FEATURE_FORCE_LOAD */
733 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
735 char buf[BUFFER_SIZE];
743 int ms_iis5_hack = 0;
745 const struct forward_spec * fwd;
746 struct http_request *http;
747 int len; /* for buffer sizes */
748 #ifdef FEATURE_KILL_POPUPS
749 int block_popups; /* bool, 1==will block popups */
750 int block_popups_now = 0; /* bool, 1==currently blocking popups */
751 #endif /* def FEATURE_KILL_POPUPS */
753 int pcrs_filter; /* bool, 1==will filter through pcrs */
754 int gif_deanimate; /* bool, 1==will deanimate gifs */
756 /* Function that does the content filtering for the current request */
757 char *(*content_filter)() = NULL;
759 /* Skeleton for HTTP response, if we should intercept the request */
760 struct http_response *rsp;
765 * Read the client's request. Note that since we're not using select() we
766 * could get blocked here if a client connected, then didn't say anything!
771 len = read_socket(csp->cfd, buf, sizeof(buf));
773 if (len <= 0) break; /* error! */
775 add_to_iob(csp, buf, len);
777 req = get_header(csp);
781 break; /* no HTTP request! */
786 continue; /* more to come! */
789 #ifdef FEATURE_FORCE_LOAD
790 /* If this request contains the FORCE_PREFIX,
791 * better get rid of it now and set the force flag --oes
794 if (strstr(req, FORCE_PREFIX))
796 strclean(req, FORCE_PREFIX);
797 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
798 csp->flags |= CSP_FLAG_FORCED;
801 #endif /* def FEATURE_FORCE_LOAD */
803 parse_http_request(req, http, csp);
808 if (http->cmd == NULL)
810 strcpy(buf, CHEADER);
811 write_socket(csp->cfd, buf, strlen(buf));
813 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
818 /* decide how to route the HTTP request */
820 if ((fwd = forward_url(http, csp)) == NULL)
822 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
823 /* Never get here - LOG_LEVEL_FATAL causes program exit */
826 /* build the http request to send to the server
827 * we have to do one of the following:
829 * create = use the original HTTP request to create a new
830 * HTTP request that has either the path component
831 * without the http://domainspec (w/path) or the
832 * full orininal URL (w/url)
833 * Note that the path and/or the HTTP version may
834 * have been altered by now.
836 * connect = Open a socket to the host:port of the server
837 * and short-circuit server and client socket.
839 * pass = Pass the request unchanged if forwarding a CONNECT
840 * request to a parent proxy. Note that we'll be sending
841 * the CFAIL message ourselves if connecting to the parent
842 * fails, but we won't send a CSUCCEED message if it works,
843 * since that would result in a double message (ours and the
844 * parent's). After sending the request to the parent, we simply
850 * +--------+--------+
852 * 0 | create | connect|
854 * Forwarding +--------+--------+
856 * 1 | create | pass |
858 * +--------+--------+
863 * Determine the actions for this URL
865 #ifdef FEATURE_TOGGLE
866 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
868 /* Most compatible set of actions (i.e. none) */
869 init_current_action(csp->action);
872 #endif /* ndef FEATURE_TOGGLE */
874 url_actions(http, csp);
879 * Check if a CONNECT request is allowable:
880 * In the absence of a +limit-connect action, allow only port 443.
881 * If there is an action, allow whatever matches the specificaton.
885 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
886 || (csp->action->flags & ACTION_LIMIT_CONNECT
887 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
889 strcpy(buf, CFORBIDDEN);
890 write_socket(csp->cfd, buf, strlen(buf));
892 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
893 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
901 * Downgrade http version from 1.1 to 1.0 if +downgrade
904 if ( (http->ssl == 0)
905 && (!strcmpic(http->ver, "HTTP/1.1"))
906 && (csp->action->flags & ACTION_DOWNGRADE))
909 http->ver = strdup("HTTP/1.0");
911 if (http->ver == NULL)
913 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
918 * Save a copy of the original request for logging
920 http->ocmd = strdup(http->cmd);
922 if (http->ocmd == NULL)
924 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
928 * (Re)build the HTTP request for non-SSL requests.
929 * If forwarding, use the whole URL, else, use only the path.
935 http->cmd = strdup(http->gpc);
936 string_append(&http->cmd, " ");
938 if (fwd->forward_host)
940 string_append(&http->cmd, http->url);
944 string_append(&http->cmd, http->path);
947 string_append(&http->cmd, " ");
948 string_append(&http->cmd, http->ver);
950 if (http->cmd == NULL)
952 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
955 enlist(csp->headers, http->cmd);
958 #ifdef FEATURE_COOKIE_JAR
960 * If we're logging cookies in a cookie jar, and the user has not
961 * supplied any wafers, and the user has not told us to suppress the
962 * vanilla wafer, then send the vanilla wafer.
964 if ((csp->config->jarfile != NULL)
965 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
966 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
968 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
970 #endif /* def FEATURE_COOKIE_JAR */
973 #ifdef FEATURE_KILL_POPUPS
974 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
975 #endif /* def FEATURE_KILL_POPUPS */
977 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
978 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
980 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
982 /* grab the rest of the client's headers */
986 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
988 len = read_socket(csp->cfd, buf, sizeof(buf));
991 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
994 add_to_iob(csp, buf, len);
998 if (p == NULL) break;
1000 enlist(csp->headers, p);
1004 * We have a request. Now, check to see if we need to
1005 * intercept it, i.e. If ..
1009 /* a CGI call was detected and answered */
1010 (NULL != (rsp = dispatch_cgi(csp)))
1012 /* or we are enabled and... */
1013 || (IS_ENABLED_AND (
1015 /* ..the request was blocked */
1016 ( NULL != (rsp = block_url(csp)))
1018 /* ..or untrusted */
1019 #ifdef FEATURE_TRUST
1020 || ( NULL != (rsp = trust_url(csp)))
1021 #endif /* def FEATURE_TRUST */
1023 /* ..or a fast redirect kicked in */
1024 #ifdef FEATURE_FAST_REDIRECTS
1025 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
1026 (NULL != (rsp = redirect_url(csp))))
1027 #endif /* def FEATURE_FAST_REDIRECTS */
1031 /* Write the answer to the client */
1032 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1033 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1035 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1038 #ifdef FEATURE_STATISTICS
1039 /* Count as a rejected request */
1040 csp->flags |= CSP_FLAG_REJECTED;
1041 #endif /* def FEATURE_STATISTICS */
1043 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
1044 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1045 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1047 /* Clean up and return */
1048 free_http_response(rsp);
1052 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1054 if (fwd->forward_host)
1056 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1057 fwd->forward_host, fwd->forward_port, http->hostport);
1061 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1064 /* here we connect to the server, gateway, or the forwarder */
1066 csp->sfd = forwarded_connect(fwd, http, csp);
1068 if (csp->sfd == JB_INVALID_SOCKET)
1070 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1073 if (errno == EINVAL)
1075 rsp = error_response(csp, "no-such-domain", errno);
1077 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1078 csp->ip_addr_str, http->ocmd);
1082 rsp = error_response(csp, "connect-failed", errno);
1084 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1085 csp->ip_addr_str, http->ocmd);
1089 /* Write the answer to the client */
1092 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1093 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1095 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1099 free_http_response(rsp);
1103 log_error(LOG_LEVEL_CONNECT, "OK");
1105 hdr = sed(client_patterns, add_client_headers, csp);
1108 /* FIXME Should handle error properly */
1109 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1112 list_remove_all(csp->headers);
1114 if (fwd->forward_host || (http->ssl == 0))
1116 /* write the client's (modified) header to the server
1117 * (along with anything else that may be in the buffer)
1120 if (write_socket(csp->sfd, hdr, strlen(hdr))
1121 || (flush_socket(csp->sfd, csp) < 0))
1123 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1126 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1127 csp->ip_addr_str, http->ocmd);
1129 rsp = error_response(csp, "connect-failed", errno);
1133 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1134 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1136 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1140 free_http_response(rsp);
1148 * We're running an SSL tunnel and we're not forwarding,
1149 * so just send the "connect succeeded" message to the
1150 * client, flush the rest, and get out of the way.
1152 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1153 csp->ip_addr_str, http->ocmd);
1155 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1163 /* we're finished with the client's header */
1166 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1168 /* pass data between the client and server
1169 * until one or the other shuts down the connection.
1178 * FD_ZERO here seems to point to an errant macro which crashes.
1179 * So do this by hand for now...
1181 memset(&rfds,0x00,sizeof(fd_set));
1185 FD_SET(csp->cfd, &rfds);
1186 FD_SET(csp->sfd, &rfds);
1188 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1192 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1196 /* this is the body of the browser's request
1197 * just read it and write it.
1200 if (FD_ISSET(csp->cfd, &rfds))
1202 len = read_socket(csp->cfd, buf, sizeof(buf));
1206 break; /* "game over, man" */
1209 if (write_socket(csp->sfd, buf, (size_t)len))
1211 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1218 * The server wants to talk. It could be the header or the body.
1219 * If `hdr' is null, then it's the header otherwise it's the body.
1220 * FIXME: Does `hdr' really mean `host'? No.
1224 if (FD_ISSET(csp->sfd, &rfds))
1227 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1231 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1233 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1234 csp->ip_addr_str, http->ocmd);
1236 rsp = error_response(csp, "connect-failed", errno);
1240 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1241 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1243 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1247 free_http_response(rsp);
1251 /* Add a trailing zero. This lets filter_popups
1252 * use string operations.
1256 #ifdef FEATURE_KILL_POPUPS
1257 /* Filter the popups on this read. */
1258 if (block_popups_now)
1260 filter_popups(buf, csp);
1262 #endif /* def FEATURE_KILL_POPUPS */
1264 /* Normally, this would indicate that we've read
1265 * as much as the server has sent us and we can
1266 * close the client connection. However, Microsoft
1267 * in its wisdom has released IIS/5 with a bug that
1268 * prevents it from sending the trailing \r\n in
1269 * a 302 redirect header (and possibly other headers).
1270 * To work around this if we've haven't parsed
1271 * a full header we'll append a trailing \r\n
1272 * and see if this now generates a valid one.
1274 * This hack shouldn't have any impacts. If we've
1275 * already transmitted the header or if this is a
1276 * SSL connection, then we won't bother with this
1277 * hack. So we only work on partially received
1278 * headers. If we append a \r\n and this still
1279 * doesn't generate a valid header, then we won't
1280 * transmit anything to the client.
1285 if (server_body || http->ssl)
1288 * If we have been buffering up the document,
1289 * now is the time to apply content modification
1290 * and send the result to the client.
1295 * If the content filter fails, use the original
1296 * buffer and length.
1297 * (see p != NULL ? p : csp->iob->cur below)
1299 if (NULL == (p = (*content_filter)(csp)))
1301 csp->content_length = csp->iob->eod - csp->iob->cur;
1304 hdr = sed(server_patterns, add_server_headers, csp);
1307 /* FIXME Should handle error properly */
1308 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1311 if (write_socket(csp->cfd, hdr, strlen(hdr))
1312 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1314 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1324 break; /* "game over, man" */
1328 * This is NOT the body, so
1329 * Let's pretend the server just sent us a blank line.
1331 len = sprintf(buf, "\r\n");
1334 * Now, let the normal header parsing algorithm below do its
1335 * job. If it fails, we'll exit instead of continuing.
1342 * If this is an SSL connection or we're in the body
1343 * of the server document, just write it to the client,
1344 * unless we need to buffer the body for later content-filtering
1347 if (server_body || http->ssl)
1351 add_to_iob(csp, buf, len);
1354 * If the buffer limit will be reached on the next read,
1355 * switch to non-filtering mode, i.e. make & write the
1356 * header, flush the socket and get out of the way.
1358 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1362 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1364 hdr = sed(server_patterns, add_server_headers, csp);
1367 /* FIXME Should handle error properly */
1368 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1371 hdrlen = strlen(hdr);
1372 byte_count += hdrlen;
1374 if (write_socket(csp->cfd, hdr, hdrlen)
1375 || ((len = flush_socket(csp->cfd, csp)) < 0))
1377 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1386 content_filter = NULL;
1393 if (write_socket(csp->cfd, buf, (size_t)len))
1395 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1404 /* we're still looking for the end of the
1405 * server's header ... (does that make header
1406 * parsing an "out of body experience" ?
1409 /* buffer up the data we just read */
1410 add_to_iob(csp, buf, len);
1412 /* get header lines from the iob */
1414 while ((p = get_header(csp)) != NULL)
1418 /* see following note */
1421 enlist(csp->headers, p);
1425 /* NOTE: there are no "empty" headers so
1426 * if the pointer `p' is not NULL we must
1427 * assume that we reached the end of the
1428 * buffer before we hit the end of the header.
1435 /* Well, we tried our MS IIS/5
1436 * hack and it didn't work.
1437 * The header is incomplete
1438 * and there isn't anything
1439 * we can do about it.
1445 /* Since we have to wait for
1446 * more from the server before
1447 * we can parse the headers
1448 * we just continue here.
1454 /* we have now received the entire header.
1455 * filter it and send the result to the client
1458 hdr = sed(server_patterns, add_server_headers, csp);
1461 /* FIXME Should handle error properly */
1462 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1465 #ifdef FEATURE_KILL_POPUPS
1466 /* Start blocking popups if appropriate. */
1468 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1469 !http->ssl && /* We talk plaintext */
1470 block_popups) /* Policy allows */
1472 block_popups_now = 1;
1474 * Filter the part of the body that came in the same read
1475 * as the last headers:
1477 filter_popups(csp->iob->cur, csp);
1480 #endif /* def FEATURE_KILL_POPUPS */
1482 /* Buffer and pcrs filter this if appropriate. */
1484 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1485 !http->ssl && /* We talk plaintext */
1486 pcrs_filter) /* Policy allows */
1488 content_filter = pcrs_filter_response;
1491 /* Buffer and gif_deanimate this if appropriate. */
1493 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1494 !http->ssl && /* We talk plaintext */
1495 gif_deanimate) /* Policy allows */
1497 content_filter = gif_deanimate_response;
1501 * Only write if we're not buffering for content modification
1503 if (!content_filter)
1505 /* write the server's (modified) header to
1506 * the client (along with anything else that
1507 * may be in the buffer)
1510 if (write_socket(csp->cfd, hdr, strlen(hdr))
1511 || ((len = flush_socket(csp->cfd, csp)) < 0))
1513 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1515 /* the write failed, so don't bother
1516 * mentioning it to the client...
1517 * it probably can't hear us anyway.
1526 /* we're finished with the server's header */
1531 /* If this was a MS IIS/5 hack then it means
1532 * the server has already closed the
1533 * connection. Nothing more to read. Time
1544 return; /* huh? we should never get here */
1547 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1548 csp->ip_addr_str, http->ocmd, byte_count);
1552 /*********************************************************************
1556 * Description : This is little more than chat. We only "serve" to
1557 * to close any socket that chat may have opened.
1560 * 1 : csp = Current client state (buffers, headers, etc...)
1564 *********************************************************************/
1566 void serve(struct client_state *csp)
1567 #else /* ifndef AMIGA */
1568 static void serve(struct client_state *csp)
1569 #endif /* def AMIGA */
1572 close_socket(csp->cfd);
1574 if (csp->sfd != JB_INVALID_SOCKET)
1576 close_socket(csp->sfd);
1579 csp->flags &= ~CSP_FLAG_ACTIVE;
1585 /*********************************************************************
1587 * Function : server_thread
1589 * Description : We only exist to call `serve' in a threaded environment.
1592 * 1 : data = Current client state (buffers, headers, etc...)
1594 * Returns : Always 0.
1596 *********************************************************************/
1597 static int32 server_thread(void *data)
1599 serve((struct client_state *) data);
1606 /*********************************************************************
1610 * Description : Print usage info & exit.
1612 * Parameters : Pointer to argv[0] for identifying ourselves
1616 *********************************************************************/
1617 void usage(const char *myname)
1619 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
1620 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1621 "Aborting.\n", myname);
1628 /*********************************************************************
1632 * Description : Load the config file and start the listen loop.
1633 * This function is a lot more *sane* with the `load_config'
1634 * and `listen_loop' functions; although it stills does
1635 * a *little* too much for my taste.
1638 * 1 : argc = Number of parameters (including $0).
1639 * 2 : argv = Array of (char *)'s to the parameters.
1641 * Returns : 1 if : can't open config file, unrecognized directive,
1642 * stats requested in multi-thread mode, can't open the
1643 * log file, can't open the jar file, listen port is invalid,
1644 * any load fails, and can't bind port.
1646 * Else main never returns, the process must be signaled
1647 * to terminate execution. Or, on Windows, use the
1648 * "File", "Exit" menu option.
1650 *********************************************************************/
1652 int real_main(int argc, const char *argv[])
1654 int main(int argc, const char *argv[])
1659 struct passwd *pw = NULL;
1660 struct group *grp = NULL;
1668 #if !defined(_WIN32)
1676 * Parse the command line arguments
1678 while (++argc_pos < argc)
1680 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1682 if (strcmp(argv[argc_pos], "--help") == 0)
1687 else if(strcmp(argv[argc_pos], "--version") == 0)
1689 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1693 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1698 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1700 if (++argc_pos == argc) usage(argv[0]);
1701 pidfile = strdup(argv[argc_pos]);
1704 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1706 if (++argc_pos == argc) usage(argv[argc_pos]);
1708 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1711 if (NULL == (grp = getgrnam(p)))
1713 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1717 if (NULL == (pw = getpwnam(argv[argc_pos])))
1719 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1722 if (p != NULL) *--p = '\0';
1724 #endif /* defined(unix) */
1726 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1728 configfile = argv[argc_pos];
1731 } /* -END- while (more arguments) */
1734 if ( *configfile != '/' )
1738 /* make config-filename absolute here */
1739 if ( !(basedir = getcwd( NULL, 1024 )))
1741 perror("get working dir failed");
1745 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1747 perror("malloc failed");
1750 strcpy( abs_file, basedir );
1751 strcat( abs_file, "/" );
1752 strcat( abs_file, configfile );
1753 configfile = abs_file;
1755 #endif /* defined unix */
1762 #elif defined(_WIN32)
1767 * Unix signal handling
1769 * Catch the abort, interrupt and terminate signals for a graceful exit
1770 * Catch the hangup signal so the errlog can be reopened.
1771 * Ignore the broken pipe and child signals
1772 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1774 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1777 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1778 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1780 for (idx = 0; catched_signals[idx] != 0; idx++)
1782 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1784 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1788 for (idx = 0; ignored_signals[idx] != 0; idx++)
1790 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1792 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1797 #else /* ifdef _WIN32 */
1798 # ifdef _WIN_CONSOLE
1800 * We *are* in a windows console app.
1801 * Print a verbose messages about FAQ's and such
1803 printf(win32_blurb);
1804 # endif /* def _WIN_CONSOLE */
1805 #endif /* def _WIN32 */
1808 /* Initialize the CGI subsystem */
1809 cgi_init_error_messages();
1812 * If runnig on unix and without the --nodaemon
1813 * option, become a daemon. I.e. fork, detach
1814 * from tty and get process group leadership
1827 if ( pid < 0 ) /* error */
1832 else if ( pid != 0 ) /* parent */
1837 * must check for errors
1838 * child died due to missing files aso
1841 wpid = waitpid( pid, &status, WNOHANG );
1850 /* Should be more portable, but not as well tested */
1855 #else /* ndef __FreeBSD__ */
1857 #endif /* ndef __FreeBSD__ */
1858 fd = open("/dev/tty", O_RDONLY);
1861 /* no error check here */
1862 ioctl( fd, TIOCNOTTY,0 );
1866 /* FIXME: should close stderr (fd 2) here too, but the test
1868 * and load config file is done in listen_loop() and puts
1869 * some messages on stderr there.
1876 } /* -END- if (!no_daemon) */
1879 * As soon as we have written the PID file, we can switch
1880 * to the user and group ID indicated by the --user option
1886 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1888 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1890 if (setuid(pw->pw_uid))
1892 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1896 #endif /* defined unix */
1906 /*********************************************************************
1908 * Function : bind_port_helper
1910 * Description : Bind the listen port. Handles logging, and aborts
1914 * 1 : config = Privoxy configuration. Specifies port
1917 * Returns : Port that was opened.
1919 *********************************************************************/
1920 static jb_socket bind_port_helper(struct configuration_spec * config)
1925 if ( (config->haddr != NULL)
1926 && (config->haddr[0] == '1')
1927 && (config->haddr[1] == '2')
1928 && (config->haddr[2] == '7')
1929 && (config->haddr[3] == '.') )
1931 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1934 else if (config->haddr == NULL)
1936 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1941 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1942 config->hport, config->haddr);
1945 result = bind_port(config->haddr, config->hport, &bfd);
1952 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1953 "There may be another Privoxy or some other "
1954 "proxy running on port %d",
1955 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1956 config->hport, config->hport);
1959 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1960 "The hostname is not resolvable",
1961 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1964 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
1965 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1968 /* shouldn't get here */
1969 return JB_INVALID_SOCKET;
1972 config->need_bind = 0;
1978 /*********************************************************************
1980 * Function : listen_loop
1982 * Description : bind the listen port and enter a "FOREVER" listening loop.
1988 *********************************************************************/
1989 static void listen_loop(void)
1991 struct client_state *csp = NULL;
1993 struct configuration_spec * config;
1995 config = load_config();
1997 bfd = bind_port_helper(config);
1999 #ifdef FEATURE_GRACEFUL_TERMINATION
2000 while (!g_terminate)
2005 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
2006 while (waitpid(-1, NULL, WNOHANG) > 0)
2008 /* zombie children */
2010 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2013 * Free data that was used by died threads
2019 * Re-open the errlog after HUP signal
2021 if (received_hup_signal)
2023 init_error_log(Argv[0], config->logfile, config->debug);
2024 received_hup_signal = 0;
2029 #ifdef FEATURE_COOKIE_JAR
2031 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
2032 * already open. I think unload_configfile() is not being run, which should do
2033 * this work. Until that can get resolved, we'll use this workaround.
2037 if (csp->config->jar)
2039 fclose(csp->config->jar);
2040 csp->config->jar = NULL;
2042 #endif /* FEATURE_COOKIE_JAR */
2043 #endif /* __OS2__ */
2045 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2047 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2051 csp->flags |= CSP_FLAG_ACTIVE;
2052 csp->sfd = JB_INVALID_SOCKET;
2054 csp->config = config = load_config();
2056 if ( config->need_bind )
2059 * Since we were listening to the "old port", we will not see
2060 * a "listen" param change until the next IJB request. So, at
2061 * least 1 more request must be made for us to find the new
2062 * setting. I am simply closing the old socket and binding the
2065 * Which-ever is correct, we will serve 1 more page via the
2066 * old settings. This should probably be a "show-proxy-args"
2067 * request. This should not be a so common of an operation
2068 * that this will hurt people's feelings.
2073 bfd = bind_port_helper(config);
2076 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2078 if (!accept_connection(csp, bfd))
2080 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2093 log_error(LOG_LEVEL_CONNECT, "OK");
2096 #ifdef FEATURE_TOGGLE
2099 csp->flags |= CSP_FLAG_TOGGLED_ON;
2101 #endif /* def FEATURE_TOGGLE */
2103 if (run_loader(csp))
2105 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2106 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2110 if (block_acl(NULL,csp))
2112 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2113 close_socket(csp->cfd);
2117 #endif /* def FEATURE_ACL */
2119 /* add it to the list of clients */
2120 csp->next = clients->next;
2121 clients->next = csp;
2123 if (config->multi_threaded)
2127 /* this is a switch () statment in the C preprocessor - ugh */
2128 #undef SELECTED_ONE_OPTION
2130 /* Use Pthreads in preference to native code */
2131 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2132 #define SELECTED_ONE_OPTION
2134 pthread_t the_thread;
2135 pthread_attr_t attrs;
2137 pthread_attr_init(&attrs);
2138 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2139 child_id = (pthread_create(&the_thread, &attrs,
2140 (void*)serve, csp) ? -1 : 0);
2141 pthread_attr_destroy(&attrs);
2145 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2146 #define SELECTED_ONE_OPTION
2147 child_id = _beginthread(
2148 (void (*)(void *))serve,
2153 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2154 #define SELECTED_ONE_OPTION
2155 child_id = _beginthread(
2162 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2163 #define SELECTED_ONE_OPTION
2165 thread_id tid = spawn_thread
2166 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2168 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2170 child_id = (int) tid;
2179 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2180 #define SELECTED_ONE_OPTION
2181 csp->cfd = ReleaseSocket(csp->cfd, -1);
2182 if((child_id = (int)CreateNewProcTags(
2183 NP_Entry, (ULONG)server_thread,
2184 NP_Output, Output(),
2185 NP_CloseOutput, FALSE,
2186 NP_Name, (ULONG)"privoxy child",
2187 NP_StackSize, 200*1024,
2191 ((struct Task *)child_id)->tc_UserData = csp;
2192 Signal((struct Task *)child_id, SIGF_SINGLE);
2197 #if !defined(SELECTED_ONE_OPTION)
2200 /* This block is only needed when using fork().
2201 * When using threads, the server thread was
2202 * created and run by the call to _beginthread().
2204 if (child_id == 0) /* child */
2210 else if (child_id > 0) /* parent */
2212 /* in a fork()'d environment, the parent's
2213 * copy of the client socket and the CSP
2217 #if !defined(_WIN32) && defined(__CYGWIN__)
2219 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2220 close_socket(csp->cfd);
2221 csp->flags &= ~CSP_FLAG_ACTIVE;
2225 #undef SELECTED_ONE_OPTION
2226 /* end of cpp switch () */
2228 if (child_id < 0) /* failed */
2230 char buf[BUFFER_SIZE];
2232 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2234 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
2236 write_socket(csp->cfd, buf, strlen(buf));
2237 close_socket(csp->cfd);
2238 csp->flags &= ~CSP_FLAG_ACTIVE;
2249 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2251 /* Clean up. Aim: free all memory (no leaks) */
2252 #ifdef FEATURE_GRACEFUL_TERMINATION
2254 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2256 unload_current_config_file();
2257 unload_current_actions_file();
2258 unload_current_re_filterfile();
2259 #ifdef FEATURE_TRUST
2260 unload_current_trust_file();
2263 if (config->multi_threaded)
2270 } while ((clients->next != NULL) && (--i > 0));
2274 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2283 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2284 /* Cleanup - remove taskbar icon etc. */
2289 #endif /* FEATURE_GRACEFUL_TERMINATION */