1 const char jcc_rcs[] = "$Id: jcc.c,v 1.83 2002/03/16 23:54:06 jongfoster 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://ijbswa.sourceforge.net
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.83 2002/03/16 23:54:06 jongfoster
37 * Adding graceful termination feature, to help look for memory leaks.
38 * If you enable this (which, by design, has to be done by hand
39 * editing config.h) and then go to http://i.j.b/die, then the program
40 * will exit cleanly after the *next* request. It should free all the
41 * memory that was used.
43 * Revision 1.82 2002/03/13 00:27:05 jongfoster
46 * Revision 1.81 2002/03/12 01:42:50 oes
47 * Introduced modular filters
49 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
50 * OS/2 port maintenance:
51 * - Fixed EMX build - it had decayed a little
52 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
53 * substituted a memset for now.
55 * Revision 1.79 2002/03/09 20:03:52 jongfoster
56 * - Making various functions return int rather than size_t.
57 * (Undoing a recent change). Since size_t is unsigned on
58 * Windows, functions like read_socket that return -1 on
59 * error cannot return a size_t.
61 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
62 * crashes, and also frequently caused JB to jump to 100%
63 * CPU and stay there. (Because it thought it had just
64 * read ((unsigned)-1) == 4Gb of data...)
66 * - The signature of write_socket has changed, it now simply
67 * returns success=0/failure=nonzero.
69 * - Trying to get rid of a few warnings --with-debug on
70 * Windows, I've introduced a new type "jb_socket". This is
71 * used for the socket file descriptors. On Windows, this
72 * is SOCKET (a typedef for unsigned). Everywhere else, it's
73 * an int. The error value can't be -1 any more, so it's
74 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
75 * Windows it maps to the #define INVALID_SOCKET.)
77 * - The signature of bind_port has changed.
79 * Revision 1.78 2002/03/08 21:35:04 oes
80 * Added optional group supplement to --user option. Will now use default group of user if no group given
82 * Revision 1.77 2002/03/07 03:52:06 oes
83 * - Fixed compiler warnings etc
84 * - Improved handling of failed DNS lookups
86 * Revision 1.76 2002/03/06 22:54:35 jongfoster
87 * Automated function-comment nitpicking.
89 * Revision 1.75 2002/03/06 10:02:19 oes
90 * Fixed stupid bug when --user was not given
92 * Revision 1.74 2002/03/06 00:49:31 jongfoster
93 * Fixing warning on Windows
94 * Making #ifdefs that refer to the same variable consistently
95 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
97 * Revision 1.73 2002/03/05 23:57:30 hal9
98 * Stray character 's' on line 1618 was breaking build.
100 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
101 * - Re-enable OS/2 building after new parms were added
102 * - Fix false out of memory report when resolving CGI templates when no IP
103 * address is available of failed attempt (a la no such domain)
105 * Revision 1.71 2002/03/05 18:13:56 oes
106 * Added --user option
108 * Revision 1.70 2002/03/05 04:52:42 oes
109 * Deleted non-errlog debugging code
111 * Revision 1.69 2002/03/04 23:50:00 jongfoster
112 * Splitting off bind_port() call into bind_port_helper(), with
115 * Revision 1.68 2002/03/04 20:17:32 oes
118 * Revision 1.67 2002/03/04 18:18:57 oes
119 * - Removed _DEBUG mode
120 * - Cleand up cmdline parsing
121 * - Introduced --no-daemon, --pidfile options
122 * - Cleaned up signal handling:
123 * - Terminate cleanly on INT, TERM and ABRT
124 * - Schedule logfile for re-opening on HUP
125 * - Ignore CHLD and PIPE
126 * - Leave the rest with their default handlers
127 * - Uniform handler registration
128 * - Added usage() function
129 * - Played styleguide police
131 * Revision 1.66 2002/03/03 15:06:55 oes
132 * Re-enabled automatic config reloading
134 * Revision 1.65 2002/03/03 14:49:11 oes
135 * Fixed CLF logging: Now uses client's original HTTP request
137 * Revision 1.64 2002/03/03 09:18:03 joergs
138 * Made jumbjuster work on AmigaOS again.
140 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
141 * Clean up a little CRLF unpleasantness that suddenly appeared
143 * Revision 1.62 2002/02/20 23:17:23 jongfoster
144 * Detecting some out-of memory conditions and exiting with a log message.
146 * Revision 1.61 2002/01/17 21:01:52 jongfoster
147 * Moving all our URL and URL pattern parsing code to urlmatch.c.
149 * Revision 1.60 2001/12/30 14:07:32 steudten
150 * - Add signal handling (unix)
151 * - Add SIGHUP handler (unix)
152 * - Add creation of pidfile (unix)
153 * - Add action 'top' in rc file (RH)
154 * - Add entry 'SIGNALS' to manpage
155 * - Add exit message to logfile (unix)
157 * Revision 1.59 2001/12/13 14:07:18 oes
158 * Fixed Bug: 503 error page now sent OK
160 * Revision 1.58 2001/11/30 23:37:24 jongfoster
161 * Renaming the Win32 config file to config.txt - this is almost the
162 * same as the corresponding UNIX name "config"
164 * Revision 1.57 2001/11/16 00:47:43 jongfoster
165 * Changing the tty-disconnection code to use setsid().
167 * Revision 1.56 2001/11/13 20:20:54 jongfoster
168 * Tabs->spaces, fixing a bug with missing {} around an if()
170 * Revision 1.55 2001/11/13 20:14:53 jongfoster
171 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
173 * Revision 1.54 2001/11/07 00:03:14 steudten
174 * Give reliable return value if an error
175 * occurs not just 0 with new daemon mode.
177 * Revision 1.53 2001/11/05 21:41:43 steudten
178 * Add changes to be a real daemon just for unix os.
179 * (change cwd to /, detach from controlling tty, set
180 * process group and session leader to the own process.
182 * Add some fatal-error log message for failed malloc().
183 * Add '-d' if compiled with 'configure --with-debug' to
184 * enable debug output.
186 * Revision 1.52 2001/10/26 20:11:20 jongfoster
187 * Fixing type mismatch
189 * Revision 1.51 2001/10/26 17:38:28 oes
192 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
193 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
194 * threads to call select() simultaneously. So, it's time to do a real, live,
195 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
196 * (native). Both versions will work, but using __OS2__ offers multi-threading.
198 * Revision 1.49 2001/10/23 21:41:35 jongfoster
199 * Added call to initialize the (statically-allocated of course)
200 * "out of memory" CGI response.
202 * Revision 1.48 2001/10/10 19:56:46 jongfoster
203 * Moving some code that wasn't cookie-related out of an #ifdef
206 * Revision 1.47 2001/10/10 16:44:36 oes
207 * Added CONNECT destination port limitation check
209 * Revision 1.46 2001/10/08 15:17:41 oes
210 * Re-enabled SSL forwarding
212 * Revision 1.45 2001/10/07 15:42:11 oes
213 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
215 * Moved downgrading of the HTTP version from parse_http_request to
216 * chat(), since we can't decide if it is necessary before we have
217 * determined the actions for the URL. The HTTP command is now
218 * *always* re-built so the repairs need no longer be special-cased.
220 * filter_popups now gets a csp pointer so it can raise the new
221 * CSP_FLAG_MODIFIED flag.
225 * Added configurable size limit for the IOB. If the IOB grows so
226 * large that the next read would exceed the limit, the header
227 * is generated, and the header & unfiltered buffer are flushed
228 * to the client. Chat then continues in non-buffering,
229 * non-filtering body mode.
231 * Revision 1.44 2001/10/02 18:13:57 oes
234 * Revision 1.43 2001/10/02 15:32:13 oes
235 * Moved generation of hdr
237 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
238 * Cleaning up 2 compiler warnings on OS/2.
240 * Revision 1.41 2001/09/16 17:05:14 jongfoster
241 * Removing unused #include showarg.h
243 * Revision 1.40 2001/09/16 15:41:45 jongfoster
244 * Fixing signed/unsigned comparison warning.
246 * Revision 1.39 2001/09/16 13:21:27 jongfoster
247 * Changes to use new list functions.
249 * Revision 1.38 2001/09/16 13:01:46 jongfoster
250 * Removing redundant function call that zeroed zalloc()'d memory.
252 * Revision 1.37 2001/09/10 11:12:24 oes
253 * Deleted unused variable
255 * Revision 1.36 2001/09/10 10:56:15 oes
256 * Silenced compiler warnings
258 * Revision 1.35 2001/07/31 14:44:22 oes
259 * Deleted unused size parameter from filter_popups()
261 * Revision 1.34 2001/07/30 22:08:36 jongfoster
262 * Tidying up #defines:
263 * - All feature #defines are now of the form FEATURE_xxx
264 * - Permanently turned off WIN_GUI_EDIT
265 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
267 * Revision 1.33 2001/07/29 19:32:00 jongfoster
268 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
270 * Revision 1.32 2001/07/29 18:47:05 jongfoster
271 * Adding missing #include "loadcfg.h"
273 * Revision 1.31 2001/07/29 12:17:48 oes
274 * Applied pthread fix by Paul Lieverse
276 * Revision 1.30 2001/07/25 22:57:13 jongfoster
277 * __BEOS__ no longer overrides FEATURE_PTHREAD.
278 * This is because FEATURE_PTHREAD will soon be widely used, so I
279 * want to keep it simple.
281 * Revision 1.29 2001/07/24 12:47:06 oes
282 * Applied BeOS support update by Eugenia
284 * Revision 1.28 2001/07/23 13:26:12 oes
285 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
287 * Revision 1.27 2001/07/19 19:09:47 haroon
288 * - Added code to take care of the situation where while processing the first
289 * server response (which includes the server header), after finding the end
290 * of the headers we were not looking past the end of the headers for
291 * content modification. I enabled it for filter_popups.
292 * Someone else should look to see if other similar operations should be
293 * done to the discarded portion of the buffer.
295 * Note 2001/07/20: No, the other content modification mechanisms will process
296 * the whole iob later anyway. --oes
298 * Revision 1.26 2001/07/18 12:31:36 oes
301 * Revision 1.25 2001/07/15 19:43:49 jongfoster
302 * Supports POSIX threads.
303 * Also removed some unused #includes.
305 * Revision 1.24 2001/07/13 14:00:40 oes
306 * - Generic content modification scheme:
307 * Each feature has its own applicability flag that is set
308 * from csp->action->flags.
309 * Replaced the "filtering" int flag , by a function pointer
310 * "content_filter" to the function that will do the content
311 * modification. If it is != NULL, the document will be buffered
312 * and processed through *content_filter, which must set
313 * csp->content_length and return a modified copy of the body
314 * or return NULL (on failiure).
315 * - Changed csp->is_text to the more generic bitmap csp->content_type
316 * which can currently take the valued CT_TEXT or CT_GIF
318 * - Removed all #ifdef PCRS
320 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
321 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
322 * the `block_acl' call. This prevents a compilation error when the user
323 * does not wish to use the "ACL" feature.
325 * Revision 1.22 2001/06/29 21:45:41 oes
326 * Indentation, CRLF->LF, Tab-> Space
328 * Revision 1.21 2001/06/29 13:29:36 oes
329 * - Cleaned up, improved comments
330 * - Unified all possible interceptors (CGI,
331 * block, trust, fast_redirect) in one
332 * place, with one (CGI) answer generation
333 * mechansim. Much clearer now.
334 * - Removed the GIF image generation, which
335 * is now done in filters.c:block_url()
336 * - Made error conditions like domain lookup
337 * failiure or (various) problems while talking
338 * to the server use cgi.c:error_response()
339 * instead of generating HTML/HTTP in chat() (yuck!)
340 * - Removed logentry from cancelled commit
342 * Revision 1.20 2001/06/09 10:55:28 jongfoster
343 * Changing BUFSIZ ==> BUFFER_SIZE
345 * Revision 1.19 2001/06/07 23:12:52 jongfoster
346 * Replacing function pointer in struct gateway with a directly
347 * called function forwarded_connect().
348 * Replacing struct gateway with struct forward_spec
350 * Revision 1.18 2001/06/03 19:12:16 oes
351 * introduced new cgi handling
353 * Revision 1.17 2001/06/01 20:07:23 jongfoster
354 * Now uses action +image-blocker{} rather than config->tinygif
356 * Revision 1.16 2001/06/01 18:49:17 jongfoster
357 * Replaced "list_share" with "list" - the tiny memory gain was not
358 * worth the extra complexity.
360 * Revision 1.15 2001/05/31 21:24:47 jongfoster
361 * Changed "permission" to "action" throughout.
362 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
363 * Moved vanilla wafer check into chat(), since we must now
364 * decide whether or not to add it based on the URL.
366 * Revision 1.14 2001/05/29 20:14:01 joergs
367 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
370 * Revision 1.13 2001/05/29 09:50:24 jongfoster
371 * Unified blocklist/imagelist/permissionslist.
372 * File format is still under discussion, but the internal changes
375 * Also modified interceptor behaviour:
376 * - We now intercept all URLs beginning with one of the following
377 * prefixes (and *only* these prefixes):
379 * * http://ijbswa.sf.net/config/
380 * * http://ijbswa.sourceforge.net/config/
381 * - New interceptors "home page" - go to http://i.j.b/ to see it.
382 * - Internal changes so that intercepted and fast redirect pages
383 * are not replaced with an image.
384 * - Interceptors now have the option to send a binary page direct
385 * to the client. (i.e. ijb-send-banner uses this)
386 * - Implemented show-url-info interceptor. (Which is why I needed
387 * the above interceptors changes - a typical URL is
388 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
389 * The previous mechanism would not have intercepted that, and
390 * if it had been intercepted then it then it would have replaced
393 * Revision 1.12 2001/05/27 22:17:04 oes
395 * - re_process_buffer no longer writes the modified buffer
396 * to the client, which was very ugly. It now returns the
397 * buffer, which it is then written by chat.
399 * - content_length now adjusts the Content-Length: header
400 * for modified documents rather than crunch()ing it.
401 * (Length info in csp->content_length, which is 0 for
402 * unmodified documents)
404 * - For this to work, sed() is called twice when filtering.
406 * Revision 1.11 2001/05/26 17:27:53 jongfoster
407 * Added support for CLF and fixed LOG_LEVEL_LOG.
408 * Also did CRLF->LF fix of my previous patch.
410 * Revision 1.10 2001/05/26 15:26:15 jongfoster
411 * ACL feature now provides more security by immediately dropping
412 * connections from untrusted hosts.
414 * Revision 1.9 2001/05/26 00:28:36 jongfoster
415 * Automatic reloading of config file.
416 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
417 * Most of the global variables have been moved to a new
418 * struct configuration_spec, accessed through csp->config->globalname
419 * Most of the globals remaining are used by the Win32 GUI.
421 * Revision 1.8 2001/05/25 22:43:18 jongfoster
422 * Fixing minor memory leak and buffer overflow.
424 * Revision 1.7 2001/05/25 22:34:30 jongfoster
427 * Revision 1.6 2001/05/23 00:13:58 joergs
428 * AmigaOS support fixed.
430 * Revision 1.5 2001/05/22 18:46:04 oes
432 * - Enabled filtering banners by size rather than URL
433 * by adding patterns that replace all standard banner
434 * sizes with the "Junkbuster" gif to the re_filterfile
436 * - Enabled filtering WebBugs by providing a pattern
437 * which kills all 1x1 images
439 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
440 * which is selected by the (nonstandard and therefore
441 * capital) letter 'U' in the option string.
442 * It causes the quantifiers to be ungreedy by default.
443 * Appending a ? turns back to greedy (!).
445 * - Added a new interceptor ijb-send-banner, which
446 * sends back the "Junkbuster" gif. Without imagelist or
447 * MSIE detection support, or if tinygif = 1, or the
448 * URL isn't recognized as an imageurl, a lame HTML
449 * explanation is sent instead.
451 * - Added new feature, which permits blocking remote
452 * script redirects and firing back a local redirect
454 * The feature is conditionally compiled, i.e. it
455 * can be disabled with --disable-fast-redirects,
456 * plus it must be activated by a "fast-redirects"
457 * line in the config file, has its own log level
458 * and of course wants to be displayed by show-proxy-args
459 * Note: Boy, all the #ifdefs in 1001 locations and
460 * all the fumbling with configure.in and acconfig.h
461 * were *way* more work than the feature itself :-(
463 * - Because a generic redirect template was needed for
464 * this, tinygif = 3 now uses the same.
466 * - Moved GIFs, and other static HTTP response templates
471 * - Removed some >400 CRs again (Jon, you really worked
474 * Revision 1.4 2001/05/21 19:34:01 jongfoster
475 * Made failure to bind() a fatal error.
477 * Revision 1.3 2001/05/20 01:21:20 jongfoster
478 * Version 2.9.4 checkin.
479 * - Merged popupfile and cookiefile, and added control over PCRS
480 * filtering, in new "permissionsfile".
481 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
482 * file error you now get a message box (in the Win32 GUI) rather
483 * than the program exiting with no explanation.
484 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
486 * - Removed tabs from "config"
487 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
488 * - Bumped up version number.
490 * Revision 1.2 2001/05/17 22:34:44 oes
491 * - Added hint on GIF char array generation to jcc.c
492 * - Cleaned CRLF's from the sources and related files
493 * - Repaired logging for REF and FRC
495 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
496 * Initial import of version 2.9.3 source tree
499 *********************************************************************/
505 #include <sys/types.h>
512 #ifdef FEATURE_PTHREAD
514 #endif /* def FEATURE_PTHREAD */
517 # ifndef FEATURE_PTHREAD
518 # include <windows.h>
519 # include <process.h>
520 # endif /* ndef FEATURE_PTHREAD */
523 # ifndef _WIN_CONSOLE
525 # endif /* ndef _WIN_CONSOLE */
527 #else /* ifndef _WIN32 */
529 # if !defined (__OS2__)
531 # include <sys/wait.h>
532 # endif /* ndef __OS2__ */
533 # include <sys/time.h>
534 # include <sys/stat.h>
535 # include <sys/ioctl.h>
538 #include <sys/termios.h>
549 # include <socket.h> /* BeOS has select() for sockets only. */
550 # include <OS.h> /* declarations for threads and stuff. */
553 # if defined(__EMX__) || defined(__OS2__)
554 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
559 #define bzero(B,N) memset(B,0x00,n)
574 #include "killpopup.h"
575 #include "miscutil.h"
577 #include "jbsockets.h"
582 #include "urlmatch.h"
584 const char jcc_h_rcs[] = JCC_H_VERSION;
585 const char project_h_rcs[] = PROJECT_H_VERSION;
588 struct client_state clients[1];
589 struct file_list files[1];
591 #ifdef FEATURE_STATISTICS
592 int urls_read = 0; /* total nr of urls read inc rejected */
593 int urls_rejected = 0; /* total nr of urls rejected */
594 #endif /* def FEATURE_STATISTICS */
596 #ifdef FEATURE_GRACEFUL_TERMINATION
600 static void listen_loop(void);
601 static void chat(struct client_state *csp);
603 void serve(struct client_state *csp);
604 #else /* ifndef AMIGA */
605 static void serve(struct client_state *csp);
606 #endif /* def AMIGA */
609 static int32 server_thread(void *data);
610 #endif /* def __BEOS__ */
613 #define sleep(N) Sleep(((N) * 1000))
617 #define sleep(N) DosSleep(((N) * 100))
620 #if defined(unix) || defined(__EMX__)
622 const char *pidfile = NULL;
623 int received_hup_signal = 0;
624 #endif /* defined unix */
626 /* The vanilla wafer. */
627 static const char VANILLA_WAFER[] =
628 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
629 "Do_not_send_me_any_copyrighted_information_other_than_the_"
630 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
631 "In_particular_do_not_send_me_any_cookies_that_"
632 "are_subject_to_a_claim_of_copyright_by_anybody._"
633 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
634 "(copyright_or_otherwise)_applying_to_any_cookie._";
637 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
638 /*********************************************************************
640 * Function : sig_handler
642 * Description : Signal handler for different signals.
643 * Exit gracefully on ABRT, TERM and INT
644 * or set a flag that will cause the errlog
645 * to be reopened by the main thread on HUP.
648 * 1 : the_signal = the signal cause this function to call
652 *********************************************************************/
653 static void sig_handler(int the_signal)
660 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
668 received_hup_signal = 1;
673 * We shouldn't be here, unless we catch signals
674 * in main() that we can't handle here!
676 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
684 /*********************************************************************
688 * Description : Once a connection to the client has been accepted,
689 * this function is called (via serve()) to handle the
690 * main business of the communication. When this
691 * function returns, the caller must close the client
695 * 1 : csp = Current client state (buffers, headers, etc...)
697 * Returns : On success, the number of bytes written are returned (zero
698 * indicates nothing was written). On error, -1 is returned,
699 * and errno is set appropriately. If count is zero and the
700 * file descriptor refers to a regular file, 0 will be
701 * returned without causing any other effect. For a special
702 * file, the results are not portable.
704 *********************************************************************/
705 static void chat(struct client_state *csp)
708 * This next lines are a little ugly, but they simplifies the if statements
709 * below. Basically if TOGGLE, then we want the if to test if the
710 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
711 * then we want the if to test for CSP_FLAG_FORCED , else we don't
713 #ifdef FEATURE_TOGGLE
714 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
715 #else /* ifndef FEATURE_TOGGLE */
716 # define IS_TOGGLED_ON_AND
717 #endif /* ndef FEATURE_TOGGLE */
718 #ifdef FEATURE_FORCE_LOAD
719 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
720 #else /* ifndef FEATURE_FORCE_LOAD */
721 # define IS_NOT_FORCED_AND
722 #endif /* def FEATURE_FORCE_LOAD */
724 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
726 char buf[BUFFER_SIZE];
734 int ms_iis5_hack = 0;
736 const struct forward_spec * fwd;
737 struct http_request *http;
738 int len; /* for buffer sizes */
739 #ifdef FEATURE_KILL_POPUPS
740 int block_popups; /* bool, 1==will block popups */
741 int block_popups_now = 0; /* bool, 1==currently blocking popups */
742 #endif /* def FEATURE_KILL_POPUPS */
744 int pcrs_filter; /* bool, 1==will filter through pcrs */
745 int gif_deanimate; /* bool, 1==will deanimate gifs */
747 /* Function that does the content filtering for the current request */
748 char *(*content_filter)() = NULL;
750 /* Skeleton for HTTP response, if we should intercept the request */
751 struct http_response *rsp;
756 * Read the client's request. Note that since we're not using select() we
757 * could get blocked here if a client connected, then didn't say anything!
762 len = read_socket(csp->cfd, buf, sizeof(buf));
764 if (len <= 0) break; /* error! */
766 add_to_iob(csp, buf, len);
768 req = get_header(csp);
772 break; /* no HTTP request! */
777 continue; /* more to come! */
780 #ifdef FEATURE_FORCE_LOAD
781 /* If this request contains the FORCE_PREFIX,
782 * better get rid of it now and set the force flag --oes
785 if (strstr(req, FORCE_PREFIX))
787 strclean(req, FORCE_PREFIX);
788 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
789 csp->flags |= CSP_FLAG_FORCED;
792 #endif /* def FEATURE_FORCE_LOAD */
794 parse_http_request(req, http, csp);
799 if (http->cmd == NULL)
801 strcpy(buf, CHEADER);
802 write_socket(csp->cfd, buf, strlen(buf));
804 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
809 /* decide how to route the HTTP request */
811 if ((fwd = forward_url(http, csp)) == NULL)
813 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
814 /* Never get here - LOG_LEVEL_FATAL causes program exit */
817 /* build the http request to send to the server
818 * we have to do one of the following:
820 * create = use the original HTTP request to create a new
821 * HTTP request that has either the path component
822 * without the http://domainspec (w/path) or the
823 * full orininal URL (w/url)
824 * Note that the path and/or the HTTP version may
825 * have been altered by now.
827 * connect = Open a socket to the host:port of the server
828 * and short-circuit server and client socket.
830 * pass = Pass the request unchanged if forwarding a CONNECT
831 * request to a parent proxy. Note that we'll be sending
832 * the CFAIL message ourselves if connecting to the parent
833 * fails, but we won't send a CSUCCEED message if it works,
834 * since that would result in a double message (ours and the
835 * parent's). After sending the request to the parent, we simply
841 * +--------+--------+
843 * 0 | create | connect|
845 * Forwarding +--------+--------+
847 * 1 | create | pass |
849 * +--------+--------+
854 * Determine the actions for this URL
856 #ifdef FEATURE_TOGGLE
857 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
859 /* Most compatible set of actions (i.e. none) */
860 init_current_action(csp->action);
863 #endif /* ndef FEATURE_TOGGLE */
865 url_actions(http, csp);
870 * Check if a CONNECT request is allowable:
871 * In the absence of a +limit-connect action, allow only port 443.
872 * If there is an action, allow whatever matches the specificaton.
876 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
877 || (csp->action->flags & ACTION_LIMIT_CONNECT
878 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
880 strcpy(buf, CFORBIDDEN);
881 write_socket(csp->cfd, buf, strlen(buf));
883 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
884 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
892 * Downgrade http version from 1.1 to 1.0 if +downgrade
895 if ( (http->ssl == 0)
896 && (!strcmpic(http->ver, "HTTP/1.1"))
897 && (csp->action->flags & ACTION_DOWNGRADE))
900 http->ver = strdup("HTTP/1.0");
902 if (http->ver == NULL)
904 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
909 * Save a copy of the original request for logging
911 http->ocmd = strdup(http->cmd);
913 if (http->ocmd == NULL)
915 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
919 * (Re)build the HTTP request for non-SSL requests.
920 * If forwarding, use the whole URL, else, use only the path.
926 http->cmd = strdup(http->gpc);
927 string_append(&http->cmd, " ");
929 if (fwd->forward_host)
931 string_append(&http->cmd, http->url);
935 string_append(&http->cmd, http->path);
938 string_append(&http->cmd, " ");
939 string_append(&http->cmd, http->ver);
941 if (http->cmd == NULL)
943 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
946 enlist(csp->headers, http->cmd);
949 #ifdef FEATURE_COOKIE_JAR
951 * If we're logging cookies in a cookie jar, and the user has not
952 * supplied any wafers, and the user has not told us to suppress the
953 * vanilla wafer, then send the vanilla wafer.
955 if ((csp->config->jarfile != NULL)
956 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
957 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
959 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
961 #endif /* def FEATURE_COOKIE_JAR */
964 #ifdef FEATURE_KILL_POPUPS
965 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
966 #endif /* def FEATURE_KILL_POPUPS */
968 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
969 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
971 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
973 /* grab the rest of the client's headers */
977 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
979 len = read_socket(csp->cfd, buf, sizeof(buf));
982 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
985 add_to_iob(csp, buf, len);
989 if (p == NULL) break;
991 enlist(csp->headers, p);
995 * We have a request. Now, check to see if we need to
996 * intercept it, i.e. If ..
1000 /* a CGI call was detected and answered */
1001 (NULL != (rsp = dispatch_cgi(csp)))
1003 /* or we are enabled and... */
1004 || (IS_ENABLED_AND (
1006 /* ..the request was blocked */
1007 ( NULL != (rsp = block_url(csp)))
1009 /* ..or untrusted */
1010 #ifdef FEATURE_TRUST
1011 || ( NULL != (rsp = trust_url(csp)))
1012 #endif /* def FEATURE_TRUST */
1014 /* ..or a fast redirect kicked in */
1015 #ifdef FEATURE_FAST_REDIRECTS
1016 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
1017 (NULL != (rsp = redirect_url(csp))))
1018 #endif /* def FEATURE_FAST_REDIRECTS */
1022 /* Write the answer to the client */
1023 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1024 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1026 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1029 #ifdef FEATURE_STATISTICS
1030 /* Count as a rejected request */
1031 csp->flags |= CSP_FLAG_REJECTED;
1032 #endif /* def FEATURE_STATISTICS */
1034 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
1035 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1036 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1038 /* Clean up and return */
1039 free_http_response(rsp);
1043 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1045 if (fwd->forward_host)
1047 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1048 fwd->forward_host, fwd->forward_port, http->hostport);
1052 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1055 /* here we connect to the server, gateway, or the forwarder */
1057 csp->sfd = forwarded_connect(fwd, http, csp);
1059 if (csp->sfd == JB_INVALID_SOCKET)
1061 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1064 if (errno == EINVAL)
1066 rsp = error_response(csp, "no-such-domain", errno);
1068 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1069 csp->ip_addr_str, http->ocmd);
1073 rsp = error_response(csp, "connect-failed", errno);
1075 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1076 csp->ip_addr_str, http->ocmd);
1080 /* Write the answer to the client */
1083 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1084 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1086 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1090 free_http_response(rsp);
1094 log_error(LOG_LEVEL_CONNECT, "OK");
1096 hdr = sed(client_patterns, add_client_headers, csp);
1099 /* FIXME Should handle error properly */
1100 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1103 list_remove_all(csp->headers);
1105 if (fwd->forward_host || (http->ssl == 0))
1107 /* write the client's (modified) header to the server
1108 * (along with anything else that may be in the buffer)
1111 if (write_socket(csp->sfd, hdr, strlen(hdr))
1112 || (flush_socket(csp->sfd, csp) < 0))
1114 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1117 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1118 csp->ip_addr_str, http->ocmd);
1120 rsp = error_response(csp, "connect-failed", errno);
1124 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1125 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1127 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1131 free_http_response(rsp);
1139 * We're running an SSL tunnel and we're not forwarding,
1140 * so just send the "connect succeeded" message to the
1141 * client, flush the rest, and get out of the way.
1143 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1144 csp->ip_addr_str, http->ocmd);
1146 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1154 /* we're finished with the client's header */
1157 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1159 /* pass data between the client and server
1160 * until one or the other shuts down the connection.
1169 * FD_ZERO here seems to point to an errant macro which crashes.
1170 * So do this by hand for now...
1172 memset(&rfds,0x00,sizeof(fd_set));
1176 FD_SET(csp->cfd, &rfds);
1177 FD_SET(csp->sfd, &rfds);
1179 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1183 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1187 /* this is the body of the browser's request
1188 * just read it and write it.
1191 if (FD_ISSET(csp->cfd, &rfds))
1193 len = read_socket(csp->cfd, buf, sizeof(buf));
1197 break; /* "game over, man" */
1200 if (write_socket(csp->sfd, buf, (size_t)len))
1202 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1209 * The server wants to talk. It could be the header or the body.
1210 * If `hdr' is null, then it's the header otherwise it's the body.
1211 * FIXME: Does `hdr' really mean `host'? No.
1215 if (FD_ISSET(csp->sfd, &rfds))
1218 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1222 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1224 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1225 csp->ip_addr_str, http->ocmd);
1227 rsp = error_response(csp, "connect-failed", errno);
1231 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1232 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1234 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1238 free_http_response(rsp);
1242 /* Add a trailing zero. This lets filter_popups
1243 * use string operations.
1247 #ifdef FEATURE_KILL_POPUPS
1248 /* Filter the popups on this read. */
1249 if (block_popups_now)
1251 filter_popups(buf, csp);
1253 #endif /* def FEATURE_KILL_POPUPS */
1255 /* Normally, this would indicate that we've read
1256 * as much as the server has sent us and we can
1257 * close the client connection. However, Microsoft
1258 * in its wisdom has released IIS/5 with a bug that
1259 * prevents it from sending the trailing \r\n in
1260 * a 302 redirect header (and possibly other headers).
1261 * To work around this if we've haven't parsed
1262 * a full header we'll append a trailing \r\n
1263 * and see if this now generates a valid one.
1265 * This hack shouldn't have any impacts. If we've
1266 * already transmitted the header or if this is a
1267 * SSL connection, then we won't bother with this
1268 * hack. So we only work on partially received
1269 * headers. If we append a \r\n and this still
1270 * doesn't generate a valid header, then we won't
1271 * transmit anything to the client.
1276 if (server_body || http->ssl)
1279 * If we have been buffering up the document,
1280 * now is the time to apply content modification
1281 * and send the result to the client.
1286 * If the content filter fails, use the original
1287 * buffer and length.
1288 * (see p != NULL ? p : csp->iob->cur below)
1290 if (NULL == (p = (*content_filter)(csp)))
1292 csp->content_length = csp->iob->eod - csp->iob->cur;
1295 hdr = sed(server_patterns, add_server_headers, csp);
1298 /* FIXME Should handle error properly */
1299 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1302 if (write_socket(csp->cfd, hdr, strlen(hdr))
1303 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1305 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1315 break; /* "game over, man" */
1319 * This is NOT the body, so
1320 * Let's pretend the server just sent us a blank line.
1322 len = sprintf(buf, "\r\n");
1325 * Now, let the normal header parsing algorithm below do its
1326 * job. If it fails, we'll exit instead of continuing.
1333 * If this is an SSL connection or we're in the body
1334 * of the server document, just write it to the client,
1335 * unless we need to buffer the body for later content-filtering
1338 if (server_body || http->ssl)
1342 add_to_iob(csp, buf, len);
1345 * If the buffer limit will be reached on the next read,
1346 * switch to non-filtering mode, i.e. make & write the
1347 * header, flush the socket and get out of the way.
1349 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1353 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1355 hdr = sed(server_patterns, add_server_headers, csp);
1358 /* FIXME Should handle error properly */
1359 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1362 hdrlen = strlen(hdr);
1363 byte_count += hdrlen;
1365 if (write_socket(csp->cfd, hdr, hdrlen)
1366 || ((len = flush_socket(csp->cfd, csp)) < 0))
1368 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1377 content_filter = NULL;
1384 if (write_socket(csp->cfd, buf, (size_t)len))
1386 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1395 /* we're still looking for the end of the
1396 * server's header ... (does that make header
1397 * parsing an "out of body experience" ?
1400 /* buffer up the data we just read */
1401 add_to_iob(csp, buf, len);
1403 /* get header lines from the iob */
1405 while ((p = get_header(csp)) != NULL)
1409 /* see following note */
1412 enlist(csp->headers, p);
1416 /* NOTE: there are no "empty" headers so
1417 * if the pointer `p' is not NULL we must
1418 * assume that we reached the end of the
1419 * buffer before we hit the end of the header.
1426 /* Well, we tried our MS IIS/5
1427 * hack and it didn't work.
1428 * The header is incomplete
1429 * and there isn't anything
1430 * we can do about it.
1436 /* Since we have to wait for
1437 * more from the server before
1438 * we can parse the headers
1439 * we just continue here.
1445 /* we have now received the entire header.
1446 * filter it and send the result to the client
1449 hdr = sed(server_patterns, add_server_headers, csp);
1452 /* FIXME Should handle error properly */
1453 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1456 #ifdef FEATURE_KILL_POPUPS
1457 /* Start blocking popups if appropriate. */
1459 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1460 !http->ssl && /* We talk plaintext */
1461 block_popups) /* Policy allows */
1463 block_popups_now = 1;
1465 * Filter the part of the body that came in the same read
1466 * as the last headers:
1468 filter_popups(csp->iob->cur, csp);
1471 #endif /* def FEATURE_KILL_POPUPS */
1473 /* Buffer and pcrs filter this if appropriate. */
1475 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1476 !http->ssl && /* We talk plaintext */
1477 pcrs_filter) /* Policy allows */
1479 content_filter = pcrs_filter_response;
1482 /* Buffer and gif_deanimate this if appropriate. */
1484 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1485 !http->ssl && /* We talk plaintext */
1486 gif_deanimate) /* Policy allows */
1488 content_filter = gif_deanimate_response;
1492 * Only write if we're not buffering for content modification
1494 if (!content_filter)
1496 /* write the server's (modified) header to
1497 * the client (along with anything else that
1498 * may be in the buffer)
1501 if (write_socket(csp->cfd, hdr, strlen(hdr))
1502 || ((len = flush_socket(csp->cfd, csp)) < 0))
1504 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1506 /* the write failed, so don't bother
1507 * mentioning it to the client...
1508 * it probably can't hear us anyway.
1517 /* we're finished with the server's header */
1522 /* If this was a MS IIS/5 hack then it means
1523 * the server has already closed the
1524 * connection. Nothing more to read. Time
1535 return; /* huh? we should never get here */
1538 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1539 csp->ip_addr_str, http->ocmd, byte_count);
1543 /*********************************************************************
1547 * Description : This is little more than chat. We only "serve" to
1548 * to close any socket that chat may have opened.
1551 * 1 : csp = Current client state (buffers, headers, etc...)
1555 *********************************************************************/
1557 void serve(struct client_state *csp)
1558 #else /* ifndef AMIGA */
1559 static void serve(struct client_state *csp)
1560 #endif /* def AMIGA */
1563 close_socket(csp->cfd);
1565 if (csp->sfd != JB_INVALID_SOCKET)
1567 close_socket(csp->sfd);
1570 csp->flags &= ~CSP_FLAG_ACTIVE;
1576 /*********************************************************************
1578 * Function : server_thread
1580 * Description : We only exist to call `serve' in a threaded environment.
1583 * 1 : data = Current client state (buffers, headers, etc...)
1585 * Returns : Always 0.
1587 *********************************************************************/
1588 static int32 server_thread(void *data)
1590 serve((struct client_state *) data);
1597 /*********************************************************************
1601 * Description : Print usage info & exit.
1603 * Parameters : Pointer to argv[0] for identifying ourselves
1607 *********************************************************************/
1608 void usage(const char *myname)
1610 printf("JunkBuster proxy version " VERSION " (" HOME_PAGE_URL ")\n"
1611 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1612 "Aborting.\n", myname);
1619 /*********************************************************************
1623 * Description : Load the config file and start the listen loop.
1624 * This function is a lot more *sane* with the `load_config'
1625 * and `listen_loop' functions; although it stills does
1626 * a *little* too much for my taste.
1629 * 1 : argc = Number of parameters (including $0).
1630 * 2 : argv = Array of (char *)'s to the parameters.
1632 * Returns : 1 if : can't open config file, unrecognized directive,
1633 * stats requested in multi-thread mode, can't open the
1634 * log file, can't open the jar file, listen port is invalid,
1635 * any load fails, and can't bind port.
1637 * Else main never returns, the process must be signaled
1638 * to terminate execution. Or, on Windows, use the
1639 * "File", "Exit" menu option.
1641 *********************************************************************/
1643 int real_main(int argc, const char *argv[])
1645 int main(int argc, const char *argv[])
1650 struct passwd *pw = NULL;
1651 struct group *grp = NULL;
1659 #if !defined(_WIN32)
1667 * Parse the command line arguments
1669 while (++argc_pos < argc)
1671 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1673 if (strcmp(argv[argc_pos], "--help") == 0)
1678 else if(strcmp(argv[argc_pos], "--version") == 0)
1680 printf("Junkbuster version " VERSION " (" HOME_PAGE_URL ")\n");
1684 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1689 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1691 if (++argc_pos == argc) usage(argv[0]);
1692 pidfile = strdup(argv[argc_pos]);
1695 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1697 if (++argc_pos == argc) usage(argv[argc_pos]);
1699 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1702 if (NULL == (grp = getgrnam(p)))
1704 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1708 if (NULL == (pw = getpwnam(argv[argc_pos])))
1710 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1713 if (p != NULL) *--p = '\0';
1715 #endif /* defined(unix) */
1717 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1719 configfile = argv[argc_pos];
1722 } /* -END- while (more arguments) */
1725 if ( *configfile != '/' )
1729 /* make config-filename absolute here */
1730 if ( !(basedir = getcwd( NULL, 1024 )))
1732 perror("get working dir failed");
1736 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1738 perror("malloc failed");
1741 strcpy( abs_file, basedir );
1742 strcat( abs_file, "/" );
1743 strcat( abs_file, configfile );
1744 configfile = abs_file;
1746 #endif /* defined unix */
1753 #elif defined(_WIN32)
1758 * Unix signal handling
1760 * Catch the abort, interrupt and terminate signals for a graceful exit
1761 * Catch the hangup signal so the errlog can be reopened.
1762 * Ignore the broken pipe and child signals
1763 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1765 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1768 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1769 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1771 for (idx = 0; catched_signals[idx] != 0; idx++)
1773 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1775 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1779 for (idx = 0; ignored_signals[idx] != 0; idx++)
1781 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1783 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1788 #else /* ifdef _WIN32 */
1789 # ifdef _WIN_CONSOLE
1791 * We *are* in a windows console app.
1792 * Print a verbose messages about FAQ's and such
1794 printf(win32_blurb);
1795 # endif /* def _WIN_CONSOLE */
1796 #endif /* def _WIN32 */
1799 /* Initialize the CGI subsystem */
1800 cgi_init_error_messages();
1803 * If runnig on unix and without the --nodaemon
1804 * option, become a daemon. I.e. fork, detach
1805 * from tty and get process group leadership
1818 if ( pid < 0 ) /* error */
1823 else if ( pid != 0 ) /* parent */
1828 * must check for errors
1829 * child died due to missing files aso
1832 wpid = waitpid( pid, &status, WNOHANG );
1841 /* Should be more portable, but not as well tested */
1846 #else /* ndef __FreeBSD__ */
1848 #endif /* ndef __FreeBSD__ */
1849 fd = open("/dev/tty", O_RDONLY);
1852 /* no error check here */
1853 ioctl( fd, TIOCNOTTY,0 );
1857 /* FIXME: should close stderr (fd 2) here too, but the test
1859 * and load config file is done in listen_loop() and puts
1860 * some messages on stderr there.
1867 } /* -END- if (!no_daemon) */
1870 * As soon as we have written the PID file, we can switch
1871 * to the user and group ID indicated by the --user option
1877 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1879 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1881 if (setuid(pw->pw_uid))
1883 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1887 #endif /* defined unix */
1897 /*********************************************************************
1899 * Function : bind_port_helper
1901 * Description : Bind the listen port. Handles logging, and aborts
1905 * 1 : config = Junkbuster configuration. Specifies port
1908 * Returns : Port that was opened.
1910 *********************************************************************/
1911 static jb_socket bind_port_helper(struct configuration_spec * config)
1916 if ( (config->haddr != NULL)
1917 && (config->haddr[0] == '1')
1918 && (config->haddr[1] == '2')
1919 && (config->haddr[2] == '7')
1920 && (config->haddr[3] == '.') )
1922 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1925 else if (config->haddr == NULL)
1927 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1932 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1933 config->hport, config->haddr);
1936 result = bind_port(config->haddr, config->hport, &bfd);
1943 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1944 "There may be another junkbuster or some other "
1945 "proxy running on port %d",
1946 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1947 config->hport, config->hport);
1950 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1951 "The hostname is not resolvable",
1952 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1955 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
1956 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1959 /* shouldn't get here */
1960 return JB_INVALID_SOCKET;
1963 config->need_bind = 0;
1969 /*********************************************************************
1971 * Function : listen_loop
1973 * Description : bind the listen port and enter a "FOREVER" listening loop.
1979 *********************************************************************/
1980 static void listen_loop(void)
1982 struct client_state *csp = NULL;
1984 struct configuration_spec * config;
1986 config = load_config();
1988 bfd = bind_port_helper(config);
1990 #ifdef FEATURE_GRACEFUL_TERMINATION
1991 while (!g_terminate)
1996 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1997 while (waitpid(-1, NULL, WNOHANG) > 0)
1999 /* zombie children */
2001 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2004 * Free data that was used by died threads
2010 * Re-open the errlog after HUP signal
2012 if (received_hup_signal)
2014 init_error_log(Argv[0], config->logfile, config->debug);
2015 received_hup_signal = 0;
2019 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2021 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2025 csp->flags |= CSP_FLAG_ACTIVE;
2026 csp->sfd = JB_INVALID_SOCKET;
2028 csp->config = config = load_config();
2030 if ( config->need_bind )
2033 * Since we were listening to the "old port", we will not see
2034 * a "listen" param change until the next IJB request. So, at
2035 * least 1 more request must be made for us to find the new
2036 * setting. I am simply closing the old socket and binding the
2039 * Which-ever is correct, we will serve 1 more page via the
2040 * old settings. This should probably be a "show-proxy-args"
2041 * request. This should not be a so common of an operation
2042 * that this will hurt people's feelings.
2047 bfd = bind_port_helper(config);
2050 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2052 if (!accept_connection(csp, bfd))
2054 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2067 log_error(LOG_LEVEL_CONNECT, "OK");
2070 #ifdef FEATURE_TOGGLE
2073 csp->flags |= CSP_FLAG_TOGGLED_ON;
2075 #endif /* def FEATURE_TOGGLE */
2077 if (run_loader(csp))
2079 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2080 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2084 if (block_acl(NULL,csp))
2086 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2087 close_socket(csp->cfd);
2091 #endif /* def FEATURE_ACL */
2093 /* add it to the list of clients */
2094 csp->next = clients->next;
2095 clients->next = csp;
2097 if (config->multi_threaded)
2101 /* this is a switch () statment in the C preprocessor - ugh */
2102 #undef SELECTED_ONE_OPTION
2104 /* Use Pthreads in preference to native code */
2105 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2106 #define SELECTED_ONE_OPTION
2108 pthread_t the_thread;
2109 pthread_attr_t attrs;
2111 pthread_attr_init(&attrs);
2112 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2113 child_id = (pthread_create(&the_thread, &attrs,
2114 (void*)serve, csp) ? -1 : 0);
2115 pthread_attr_destroy(&attrs);
2119 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2120 #define SELECTED_ONE_OPTION
2121 child_id = _beginthread(
2122 (void (*)(void *))serve,
2127 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2128 #define SELECTED_ONE_OPTION
2129 child_id = _beginthread(
2136 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2137 #define SELECTED_ONE_OPTION
2139 thread_id tid = spawn_thread
2140 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2142 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2144 child_id = (int) tid;
2153 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2154 #define SELECTED_ONE_OPTION
2155 csp->cfd = ReleaseSocket(csp->cfd, -1);
2156 if((child_id = (int)CreateNewProcTags(
2157 NP_Entry, (ULONG)server_thread,
2158 NP_Output, Output(),
2159 NP_CloseOutput, FALSE,
2160 NP_Name, (ULONG)"junkbuster child",
2161 NP_StackSize, 200*1024,
2165 ((struct Task *)child_id)->tc_UserData = csp;
2166 Signal((struct Task *)child_id, SIGF_SINGLE);
2171 #if !defined(SELECTED_ONE_OPTION)
2174 /* This block is only needed when using fork().
2175 * When using threads, the server thread was
2176 * created and run by the call to _beginthread().
2178 if (child_id == 0) /* child */
2184 else if (child_id > 0) /* parent */
2186 /* in a fork()'d environment, the parent's
2187 * copy of the client socket and the CSP
2191 #if !defined(_WIN32) && defined(__CYGWIN__)
2193 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2194 close_socket(csp->cfd);
2195 csp->flags &= ~CSP_FLAG_ACTIVE;
2199 #undef SELECTED_ONE_OPTION
2200 /* end of cpp switch () */
2202 if (child_id < 0) /* failed */
2204 char buf[BUFFER_SIZE];
2206 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2208 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
2210 write_socket(csp->cfd, buf, strlen(buf));
2211 close_socket(csp->cfd);
2212 csp->flags &= ~CSP_FLAG_ACTIVE;
2223 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2225 /* Clean up. Aim: free all memory (no leaks) */
2226 #ifdef FEATURE_GRACEFUL_TERMINATION
2228 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2230 unload_current_config_file();
2231 unload_current_actions_file();
2232 unload_current_re_filterfile();
2233 #ifdef FEATURE_TRUST
2234 unload_current_trust_file();
2237 if (config->multi_threaded)
2244 } while ((clients->next != NULL) && (--i > 0));
2248 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2254 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2255 /* Cleanup - remove taskbar icon etc. */
2260 #endif /* FEATURE_GRACEFUL_TERMINATION */