1 const char jcc_rcs[] = "$Id: jcc.c,v 1.78 2002/03/08 21:35:04 oes Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001 the SourceForge
10 * IJBSWA 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.78 2002/03/08 21:35:04 oes
37 * Added optional group supplement to --user option. Will now use default group of user if no group given
39 * Revision 1.77 2002/03/07 03:52:06 oes
40 * - Fixed compiler warnings etc
41 * - Improved handling of failed DNS lookups
43 * Revision 1.76 2002/03/06 22:54:35 jongfoster
44 * Automated function-comment nitpicking.
46 * Revision 1.75 2002/03/06 10:02:19 oes
47 * Fixed stupid bug when --user was not given
49 * Revision 1.74 2002/03/06 00:49:31 jongfoster
50 * Fixing warning on Windows
51 * Making #ifdefs that refer to the same variable consistently
52 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
54 * Revision 1.73 2002/03/05 23:57:30 hal9
55 * Stray character 's' on line 1618 was breaking build.
57 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
58 * - Re-enable OS/2 building after new parms were added
59 * - Fix false out of memory report when resolving CGI templates when no IP
60 * address is available of failed attempt (a la no such domain)
62 * Revision 1.71 2002/03/05 18:13:56 oes
65 * Revision 1.70 2002/03/05 04:52:42 oes
66 * Deleted non-errlog debugging code
68 * Revision 1.69 2002/03/04 23:50:00 jongfoster
69 * Splitting off bind_port() call into bind_port_helper(), with
72 * Revision 1.68 2002/03/04 20:17:32 oes
75 * Revision 1.67 2002/03/04 18:18:57 oes
76 * - Removed _DEBUG mode
77 * - Cleand up cmdline parsing
78 * - Introduced --no-daemon, --pidfile options
79 * - Cleaned up signal handling:
80 * - Terminate cleanly on INT, TERM and ABRT
81 * - Schedule logfile for re-opening on HUP
82 * - Ignore CHLD and PIPE
83 * - Leave the rest with their default handlers
84 * - Uniform handler registration
85 * - Added usage() function
86 * - Played styleguide police
88 * Revision 1.66 2002/03/03 15:06:55 oes
89 * Re-enabled automatic config reloading
91 * Revision 1.65 2002/03/03 14:49:11 oes
92 * Fixed CLF logging: Now uses client's original HTTP request
94 * Revision 1.64 2002/03/03 09:18:03 joergs
95 * Made jumbjuster work on AmigaOS again.
97 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
98 * Clean up a little CRLF unpleasantness that suddenly appeared
100 * Revision 1.62 2002/02/20 23:17:23 jongfoster
101 * Detecting some out-of memory conditions and exiting with a log message.
103 * Revision 1.61 2002/01/17 21:01:52 jongfoster
104 * Moving all our URL and URL pattern parsing code to urlmatch.c.
106 * Revision 1.60 2001/12/30 14:07:32 steudten
107 * - Add signal handling (unix)
108 * - Add SIGHUP handler (unix)
109 * - Add creation of pidfile (unix)
110 * - Add action 'top' in rc file (RH)
111 * - Add entry 'SIGNALS' to manpage
112 * - Add exit message to logfile (unix)
114 * Revision 1.59 2001/12/13 14:07:18 oes
115 * Fixed Bug: 503 error page now sent OK
117 * Revision 1.58 2001/11/30 23:37:24 jongfoster
118 * Renaming the Win32 config file to config.txt - this is almost the
119 * same as the corresponding UNIX name "config"
121 * Revision 1.57 2001/11/16 00:47:43 jongfoster
122 * Changing the tty-disconnection code to use setsid().
124 * Revision 1.56 2001/11/13 20:20:54 jongfoster
125 * Tabs->spaces, fixing a bug with missing {} around an if()
127 * Revision 1.55 2001/11/13 20:14:53 jongfoster
128 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
130 * Revision 1.54 2001/11/07 00:03:14 steudten
131 * Give reliable return value if an error
132 * occurs not just 0 with new daemon mode.
134 * Revision 1.53 2001/11/05 21:41:43 steudten
135 * Add changes to be a real daemon just for unix os.
136 * (change cwd to /, detach from controlling tty, set
137 * process group and session leader to the own process.
139 * Add some fatal-error log message for failed malloc().
140 * Add '-d' if compiled with 'configure --with-debug' to
141 * enable debug output.
143 * Revision 1.52 2001/10/26 20:11:20 jongfoster
144 * Fixing type mismatch
146 * Revision 1.51 2001/10/26 17:38:28 oes
149 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
150 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
151 * threads to call select() simultaneously. So, it's time to do a real, live,
152 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
153 * (native). Both versions will work, but using __OS2__ offers multi-threading.
155 * Revision 1.49 2001/10/23 21:41:35 jongfoster
156 * Added call to initialize the (statically-allocated of course)
157 * "out of memory" CGI response.
159 * Revision 1.48 2001/10/10 19:56:46 jongfoster
160 * Moving some code that wasn't cookie-related out of an #ifdef
163 * Revision 1.47 2001/10/10 16:44:36 oes
164 * Added CONNECT destination port limitation check
166 * Revision 1.46 2001/10/08 15:17:41 oes
167 * Re-enabled SSL forwarding
169 * Revision 1.45 2001/10/07 15:42:11 oes
170 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
172 * Moved downgrading of the HTTP version from parse_http_request to
173 * chat(), since we can't decide if it is necessary before we have
174 * determined the actions for the URL. The HTTP command is now
175 * *always* re-built so the repairs need no longer be special-cased.
177 * filter_popups now gets a csp pointer so it can raise the new
178 * CSP_FLAG_MODIFIED flag.
182 * Added configurable size limit for the IOB. If the IOB grows so
183 * large that the next read would exceed the limit, the header
184 * is generated, and the header & unfiltered buffer are flushed
185 * to the client. Chat then continues in non-buffering,
186 * non-filtering body mode.
188 * Revision 1.44 2001/10/02 18:13:57 oes
191 * Revision 1.43 2001/10/02 15:32:13 oes
192 * Moved generation of hdr
194 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
195 * Cleaning up 2 compiler warnings on OS/2.
197 * Revision 1.41 2001/09/16 17:05:14 jongfoster
198 * Removing unused #include showarg.h
200 * Revision 1.40 2001/09/16 15:41:45 jongfoster
201 * Fixing signed/unsigned comparison warning.
203 * Revision 1.39 2001/09/16 13:21:27 jongfoster
204 * Changes to use new list functions.
206 * Revision 1.38 2001/09/16 13:01:46 jongfoster
207 * Removing redundant function call that zeroed zalloc()'d memory.
209 * Revision 1.37 2001/09/10 11:12:24 oes
210 * Deleted unused variable
212 * Revision 1.36 2001/09/10 10:56:15 oes
213 * Silenced compiler warnings
215 * Revision 1.35 2001/07/31 14:44:22 oes
216 * Deleted unused size parameter from filter_popups()
218 * Revision 1.34 2001/07/30 22:08:36 jongfoster
219 * Tidying up #defines:
220 * - All feature #defines are now of the form FEATURE_xxx
221 * - Permanently turned off WIN_GUI_EDIT
222 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
224 * Revision 1.33 2001/07/29 19:32:00 jongfoster
225 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
227 * Revision 1.32 2001/07/29 18:47:05 jongfoster
228 * Adding missing #include "loadcfg.h"
230 * Revision 1.31 2001/07/29 12:17:48 oes
231 * Applied pthread fix by Paul Lieverse
233 * Revision 1.30 2001/07/25 22:57:13 jongfoster
234 * __BEOS__ no longer overrides FEATURE_PTHREAD.
235 * This is because FEATURE_PTHREAD will soon be widely used, so I
236 * want to keep it simple.
238 * Revision 1.29 2001/07/24 12:47:06 oes
239 * Applied BeOS support update by Eugenia
241 * Revision 1.28 2001/07/23 13:26:12 oes
242 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
244 * Revision 1.27 2001/07/19 19:09:47 haroon
245 * - Added code to take care of the situation where while processing the first
246 * server response (which includes the server header), after finding the end
247 * of the headers we were not looking past the end of the headers for
248 * content modification. I enabled it for filter_popups.
249 * Someone else should look to see if other similar operations should be
250 * done to the discarded portion of the buffer.
252 * Note 2001/07/20: No, the other content modification mechanisms will process
253 * the whole iob later anyway. --oes
255 * Revision 1.26 2001/07/18 12:31:36 oes
258 * Revision 1.25 2001/07/15 19:43:49 jongfoster
259 * Supports POSIX threads.
260 * Also removed some unused #includes.
262 * Revision 1.24 2001/07/13 14:00:40 oes
263 * - Generic content modification scheme:
264 * Each feature has its own applicability flag that is set
265 * from csp->action->flags.
266 * Replaced the "filtering" int flag , by a function pointer
267 * "content_filter" to the function that will do the content
268 * modification. If it is != NULL, the document will be buffered
269 * and processed through *content_filter, which must set
270 * csp->content_length and return a modified copy of the body
271 * or return NULL (on failiure).
272 * - Changed csp->is_text to the more generic bitmap csp->content_type
273 * which can currently take the valued CT_TEXT or CT_GIF
275 * - Removed all #ifdef PCRS
277 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
278 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
279 * the `block_acl' call. This prevents a compilation error when the user
280 * does not wish to use the "ACL" feature.
282 * Revision 1.22 2001/06/29 21:45:41 oes
283 * Indentation, CRLF->LF, Tab-> Space
285 * Revision 1.21 2001/06/29 13:29:36 oes
286 * - Cleaned up, improved comments
287 * - Unified all possible interceptors (CGI,
288 * block, trust, fast_redirect) in one
289 * place, with one (CGI) answer generation
290 * mechansim. Much clearer now.
291 * - Removed the GIF image generation, which
292 * is now done in filters.c:block_url()
293 * - Made error conditions like domain lookup
294 * failiure or (various) problems while talking
295 * to the server use cgi.c:error_response()
296 * instead of generating HTML/HTTP in chat() (yuck!)
297 * - Removed logentry from cancelled commit
299 * Revision 1.20 2001/06/09 10:55:28 jongfoster
300 * Changing BUFSIZ ==> BUFFER_SIZE
302 * Revision 1.19 2001/06/07 23:12:52 jongfoster
303 * Replacing function pointer in struct gateway with a directly
304 * called function forwarded_connect().
305 * Replacing struct gateway with struct forward_spec
307 * Revision 1.18 2001/06/03 19:12:16 oes
308 * introduced new cgi handling
310 * Revision 1.17 2001/06/01 20:07:23 jongfoster
311 * Now uses action +image-blocker{} rather than config->tinygif
313 * Revision 1.16 2001/06/01 18:49:17 jongfoster
314 * Replaced "list_share" with "list" - the tiny memory gain was not
315 * worth the extra complexity.
317 * Revision 1.15 2001/05/31 21:24:47 jongfoster
318 * Changed "permission" to "action" throughout.
319 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
320 * Moved vanilla wafer check into chat(), since we must now
321 * decide whether or not to add it based on the URL.
323 * Revision 1.14 2001/05/29 20:14:01 joergs
324 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
327 * Revision 1.13 2001/05/29 09:50:24 jongfoster
328 * Unified blocklist/imagelist/permissionslist.
329 * File format is still under discussion, but the internal changes
332 * Also modified interceptor behaviour:
333 * - We now intercept all URLs beginning with one of the following
334 * prefixes (and *only* these prefixes):
336 * * http://ijbswa.sf.net/config/
337 * * http://ijbswa.sourceforge.net/config/
338 * - New interceptors "home page" - go to http://i.j.b/ to see it.
339 * - Internal changes so that intercepted and fast redirect pages
340 * are not replaced with an image.
341 * - Interceptors now have the option to send a binary page direct
342 * to the client. (i.e. ijb-send-banner uses this)
343 * - Implemented show-url-info interceptor. (Which is why I needed
344 * the above interceptors changes - a typical URL is
345 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
346 * The previous mechanism would not have intercepted that, and
347 * if it had been intercepted then it then it would have replaced
350 * Revision 1.12 2001/05/27 22:17:04 oes
352 * - re_process_buffer no longer writes the modified buffer
353 * to the client, which was very ugly. It now returns the
354 * buffer, which it is then written by chat.
356 * - content_length now adjusts the Content-Length: header
357 * for modified documents rather than crunch()ing it.
358 * (Length info in csp->content_length, which is 0 for
359 * unmodified documents)
361 * - For this to work, sed() is called twice when filtering.
363 * Revision 1.11 2001/05/26 17:27:53 jongfoster
364 * Added support for CLF and fixed LOG_LEVEL_LOG.
365 * Also did CRLF->LF fix of my previous patch.
367 * Revision 1.10 2001/05/26 15:26:15 jongfoster
368 * ACL feature now provides more security by immediately dropping
369 * connections from untrusted hosts.
371 * Revision 1.9 2001/05/26 00:28:36 jongfoster
372 * Automatic reloading of config file.
373 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
374 * Most of the global variables have been moved to a new
375 * struct configuration_spec, accessed through csp->config->globalname
376 * Most of the globals remaining are used by the Win32 GUI.
378 * Revision 1.8 2001/05/25 22:43:18 jongfoster
379 * Fixing minor memory leak and buffer overflow.
381 * Revision 1.7 2001/05/25 22:34:30 jongfoster
384 * Revision 1.6 2001/05/23 00:13:58 joergs
385 * AmigaOS support fixed.
387 * Revision 1.5 2001/05/22 18:46:04 oes
389 * - Enabled filtering banners by size rather than URL
390 * by adding patterns that replace all standard banner
391 * sizes with the "Junkbuster" gif to the re_filterfile
393 * - Enabled filtering WebBugs by providing a pattern
394 * which kills all 1x1 images
396 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
397 * which is selected by the (nonstandard and therefore
398 * capital) letter 'U' in the option string.
399 * It causes the quantifiers to be ungreedy by default.
400 * Appending a ? turns back to greedy (!).
402 * - Added a new interceptor ijb-send-banner, which
403 * sends back the "Junkbuster" gif. Without imagelist or
404 * MSIE detection support, or if tinygif = 1, or the
405 * URL isn't recognized as an imageurl, a lame HTML
406 * explanation is sent instead.
408 * - Added new feature, which permits blocking remote
409 * script redirects and firing back a local redirect
411 * The feature is conditionally compiled, i.e. it
412 * can be disabled with --disable-fast-redirects,
413 * plus it must be activated by a "fast-redirects"
414 * line in the config file, has its own log level
415 * and of course wants to be displayed by show-proxy-args
416 * Note: Boy, all the #ifdefs in 1001 locations and
417 * all the fumbling with configure.in and acconfig.h
418 * were *way* more work than the feature itself :-(
420 * - Because a generic redirect template was needed for
421 * this, tinygif = 3 now uses the same.
423 * - Moved GIFs, and other static HTTP response templates
428 * - Removed some >400 CRs again (Jon, you really worked
431 * Revision 1.4 2001/05/21 19:34:01 jongfoster
432 * Made failure to bind() a fatal error.
434 * Revision 1.3 2001/05/20 01:21:20 jongfoster
435 * Version 2.9.4 checkin.
436 * - Merged popupfile and cookiefile, and added control over PCRS
437 * filtering, in new "permissionsfile".
438 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
439 * file error you now get a message box (in the Win32 GUI) rather
440 * than the program exiting with no explanation.
441 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
443 * - Removed tabs from "config"
444 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
445 * - Bumped up version number.
447 * Revision 1.2 2001/05/17 22:34:44 oes
448 * - Added hint on GIF char array generation to jcc.c
449 * - Cleaned CRLF's from the sources and related files
450 * - Repaired logging for REF and FRC
452 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
453 * Initial import of version 2.9.3 source tree
456 *********************************************************************/
462 #include <sys/types.h>
469 #ifdef FEATURE_PTHREAD
471 #endif /* def FEATURE_PTHREAD */
474 # ifndef FEATURE_PTHREAD
475 # include <windows.h>
476 # include <process.h>
477 # endif /* ndef FEATURE_PTHREAD */
480 # ifndef _WIN_CONSOLE
482 # endif /* ndef _WIN_CONSOLE */
484 #else /* ifndef _WIN32 */
486 # if !defined (__OS2__)
488 # include <sys/wait.h>
489 # endif /* ndef __OS2__ */
490 # include <sys/time.h>
491 # include <sys/stat.h>
492 # include <sys/ioctl.h>
495 #include <sys/termios.h>
506 # include <socket.h> /* BeOS has select() for sockets only. */
507 # include <OS.h> /* declarations for threads and stuff. */
510 # if defined(__EMX__) || defined(__OS2__)
511 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
516 #define bzero(B,N) memset(B,0x00,n)
531 #include "killpopup.h"
532 #include "miscutil.h"
534 #include "jbsockets.h"
539 #include "urlmatch.h"
541 const char jcc_h_rcs[] = JCC_H_VERSION;
542 const char project_h_rcs[] = PROJECT_H_VERSION;
545 struct client_state clients[1];
546 struct file_list files[1];
548 #ifdef FEATURE_STATISTICS
549 int urls_read = 0; /* total nr of urls read inc rejected */
550 int urls_rejected = 0; /* total nr of urls rejected */
551 #endif /* def FEATURE_STATISTICS */
554 static void listen_loop(void);
555 static void chat(struct client_state *csp);
557 void serve(struct client_state *csp);
558 #else /* ifndef AMIGA */
559 static void serve(struct client_state *csp);
560 #endif /* def AMIGA */
563 static int32 server_thread(void *data);
564 #endif /* def __BEOS__ */
567 #define sleep(N) Sleep(((N) * 1000))
571 #define sleep(N) DosSleep(((N) * 100))
576 const char *pidfile = NULL;
577 int received_hup_signal = 0;
578 #endif /* defined unix */
580 /* The vanilla wafer. */
581 static const char VANILLA_WAFER[] =
582 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
583 "Do_not_send_me_any_copyrighted_information_other_than_the_"
584 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
585 "In_particular_do_not_send_me_any_cookies_that_"
586 "are_subject_to_a_claim_of_copyright_by_anybody._"
587 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
588 "(copyright_or_otherwise)_applying_to_any_cookie._";
591 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
592 /*********************************************************************
594 * Function : sig_handler
596 * Description : Signal handler for different signals.
597 * Exit gracefully on ABRT, TERM and INT
598 * or set a flag that will cause the errlog
599 * to be reopened by the main thread on HUP.
602 * 1 : the_signal = the signal cause this function to call
606 *********************************************************************/
607 static void sig_handler(int the_signal)
614 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
622 received_hup_signal = 1;
627 * We shouldn't be here, unless we catch signals
628 * in main() that we can't handle here!
630 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
638 /*********************************************************************
642 * Description : Once a connection to the client has been accepted,
643 * this function is called (via serve()) to handle the
644 * main business of the communication. When this
645 * function returns, the caller must close the client
649 * 1 : csp = Current client state (buffers, headers, etc...)
651 * Returns : On success, the number of bytes written are returned (zero
652 * indicates nothing was written). On error, -1 is returned,
653 * and errno is set appropriately. If count is zero and the
654 * file descriptor refers to a regular file, 0 will be
655 * returned without causing any other effect. For a special
656 * file, the results are not portable.
658 *********************************************************************/
659 static void chat(struct client_state *csp)
662 * This next lines are a little ugly, but they simplifies the if statements
663 * below. Basically if TOGGLE, then we want the if to test if the
664 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
665 * then we want the if to test for CSP_FLAG_FORCED , else we don't
667 #ifdef FEATURE_TOGGLE
668 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
669 #else /* ifndef FEATURE_TOGGLE */
670 # define IS_TOGGLED_ON_AND
671 #endif /* ndef FEATURE_TOGGLE */
672 #ifdef FEATURE_FORCE_LOAD
673 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
674 #else /* ifndef FEATURE_FORCE_LOAD */
675 # define IS_NOT_FORCED_AND
676 #endif /* def FEATURE_FORCE_LOAD */
678 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
680 char buf[BUFFER_SIZE];
688 int ms_iis5_hack = 0;
690 const struct forward_spec * fwd;
691 struct http_request *http;
692 int len; /* for buffer sizes */
693 #ifdef FEATURE_KILL_POPUPS
694 int block_popups; /* bool, 1==will block popups */
695 int block_popups_now = 0; /* bool, 1==currently blocking popups */
696 #endif /* def FEATURE_KILL_POPUPS */
698 int pcrs_filter; /* bool, 1==will filter through pcrs */
699 int gif_deanimate; /* bool, 1==will deanimate gifs */
701 /* Function that does the content filtering for the current request */
702 char *(*content_filter)() = NULL;
704 /* Skeleton for HTTP response, if we should intercept the request */
705 struct http_response *rsp;
710 * Read the client's request. Note that since we're not using select() we
711 * could get blocked here if a client connected, then didn't say anything!
716 len = read_socket(csp->cfd, buf, sizeof(buf));
718 if (len <= 0) break; /* error! */
720 add_to_iob(csp, buf, len);
722 req = get_header(csp);
726 break; /* no HTTP request! */
731 continue; /* more to come! */
734 #ifdef FEATURE_FORCE_LOAD
735 /* If this request contains the FORCE_PREFIX,
736 * better get rid of it now and set the force flag --oes
739 if (strstr(req, FORCE_PREFIX))
741 strclean(req, FORCE_PREFIX);
742 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
743 csp->flags |= CSP_FLAG_FORCED;
746 #endif /* def FEATURE_FORCE_LOAD */
748 parse_http_request(req, http, csp);
753 if (http->cmd == NULL)
755 strcpy(buf, CHEADER);
756 write_socket(csp->cfd, buf, strlen(buf));
758 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
763 /* decide how to route the HTTP request */
765 if ((fwd = forward_url(http, csp)) == NULL)
767 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
768 /* Never get here - LOG_LEVEL_FATAL causes program exit */
771 /* build the http request to send to the server
772 * we have to do one of the following:
774 * create = use the original HTTP request to create a new
775 * HTTP request that has either the path component
776 * without the http://domainspec (w/path) or the
777 * full orininal URL (w/url)
778 * Note that the path and/or the HTTP version may
779 * have been altered by now.
781 * connect = Open a socket to the host:port of the server
782 * and short-circuit server and client socket.
784 * pass = Pass the request unchanged if forwarding a CONNECT
785 * request to a parent proxy. Note that we'll be sending
786 * the CFAIL message ourselves if connecting to the parent
787 * fails, but we won't send a CSUCCEED message if it works,
788 * since that would result in a double message (ours and the
789 * parent's). After sending the request to the parent, we simply
795 * +--------+--------+
797 * 0 | create | connect|
799 * Forwarding +--------+--------+
801 * 1 | create | pass |
803 * +--------+--------+
808 * Determine the actions for this URL
810 #ifdef FEATURE_TOGGLE
811 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
813 /* Most compatible set of actions (i.e. none) */
814 init_current_action(csp->action);
817 #endif /* ndef FEATURE_TOGGLE */
819 url_actions(http, csp);
824 * Check if a CONNECT request is allowable:
825 * In the absence of a +limit-connect action, allow only port 443.
826 * If there is an action, allow whatever matches the specificaton.
830 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
831 || (csp->action->flags & ACTION_LIMIT_CONNECT
832 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
834 strcpy(buf, CFORBIDDEN);
835 write_socket(csp->cfd, buf, strlen(buf));
837 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
838 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
846 * Downgrade http version from 1.1 to 1.0 if +downgrade
849 if ( (http->ssl == 0)
850 && (!strcmpic(http->ver, "HTTP/1.1"))
851 && (csp->action->flags & ACTION_DOWNGRADE))
854 http->ver = strdup("HTTP/1.0");
856 if (http->ver == NULL)
858 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
863 * Save a copy of the original request for logging
865 http->ocmd = strdup(http->cmd);
867 if (http->ocmd == NULL)
869 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
873 * (Re)build the HTTP request for non-SSL requests.
874 * If forwarding, use the whole URL, else, use only the path.
880 http->cmd = strdup(http->gpc);
881 string_append(&http->cmd, " ");
883 if (fwd->forward_host)
885 string_append(&http->cmd, http->url);
889 string_append(&http->cmd, http->path);
892 string_append(&http->cmd, " ");
893 string_append(&http->cmd, http->ver);
895 if (http->cmd == NULL)
897 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
900 enlist(csp->headers, http->cmd);
903 #ifdef FEATURE_COOKIE_JAR
905 * If we're logging cookies in a cookie jar, and the user has not
906 * supplied any wafers, and the user has not told us to suppress the
907 * vanilla wafer, then send the vanilla wafer.
909 if ((csp->config->jarfile != NULL)
910 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
911 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
913 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
915 #endif /* def FEATURE_COOKIE_JAR */
918 #ifdef FEATURE_KILL_POPUPS
919 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
920 #endif /* def FEATURE_KILL_POPUPS */
922 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
923 ((csp->action->flags & ACTION_FILTER) != 0);
925 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
927 /* grab the rest of the client's headers */
931 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
933 len = read_socket(csp->cfd, buf, sizeof(buf));
936 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
939 add_to_iob(csp, buf, len);
943 if (p == NULL) break;
945 enlist(csp->headers, p);
949 * We have a request. Now, check to see if we need to
950 * intercept it, i.e. If ..
954 /* a CGI call was detected and answered */
955 (NULL != (rsp = dispatch_cgi(csp)))
957 /* or we are enabled and... */
960 /* ..the request was blocked */
961 ( NULL != (rsp = block_url(csp)))
965 || ( NULL != (rsp = trust_url(csp)))
966 #endif /* def FEATURE_TRUST */
968 /* ..or a fast redirect kicked in */
969 #ifdef FEATURE_FAST_REDIRECTS
970 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
971 (NULL != (rsp = redirect_url(csp))))
972 #endif /* def FEATURE_FAST_REDIRECTS */
976 /* Write the answer to the client */
977 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
978 || write_socket(csp->cfd, rsp->body, rsp->content_length))
980 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
983 #ifdef FEATURE_STATISTICS
984 /* Count as a rejected request */
985 csp->flags |= CSP_FLAG_REJECTED;
986 #endif /* def FEATURE_STATISTICS */
988 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
989 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
990 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
992 /* Clean up and return */
993 free_http_response(rsp);
997 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
999 if (fwd->forward_host)
1001 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1002 fwd->forward_host, fwd->forward_port, http->hostport);
1006 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1009 /* here we connect to the server, gateway, or the forwarder */
1011 csp->sfd = forwarded_connect(fwd, http, csp);
1013 if (csp->sfd == JB_INVALID_SOCKET)
1015 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1018 if (errno == EINVAL)
1020 rsp = error_response(csp, "no-such-domain", errno);
1022 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1023 csp->ip_addr_str, http->ocmd);
1027 rsp = error_response(csp, "connect-failed", errno);
1029 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1030 csp->ip_addr_str, http->ocmd);
1034 /* Write the answer to the client */
1037 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1038 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1040 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1044 free_http_response(rsp);
1048 log_error(LOG_LEVEL_CONNECT, "OK");
1050 hdr = sed(client_patterns, add_client_headers, csp);
1053 /* FIXME Should handle error properly */
1054 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1057 list_remove_all(csp->headers);
1059 if (fwd->forward_host || (http->ssl == 0))
1061 /* write the client's (modified) header to the server
1062 * (along with anything else that may be in the buffer)
1065 if (write_socket(csp->sfd, hdr, strlen(hdr))
1066 || (flush_socket(csp->sfd, csp) < 0))
1068 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1071 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1072 csp->ip_addr_str, http->ocmd);
1074 rsp = error_response(csp, "connect-failed", errno);
1078 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1079 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1081 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1085 free_http_response(rsp);
1093 * We're running an SSL tunnel and we're not forwarding,
1094 * so just send the "connect succeeded" message to the
1095 * client, flush the rest, and get out of the way.
1097 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1098 csp->ip_addr_str, http->ocmd);
1100 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1108 /* we're finished with the client's header */
1111 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1113 /* pass data between the client and server
1114 * until one or the other shuts down the connection.
1123 FD_SET(csp->cfd, &rfds);
1124 FD_SET(csp->sfd, &rfds);
1126 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1130 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1134 /* this is the body of the browser's request
1135 * just read it and write it.
1138 if (FD_ISSET(csp->cfd, &rfds))
1140 len = read_socket(csp->cfd, buf, sizeof(buf));
1144 break; /* "game over, man" */
1147 if (write_socket(csp->sfd, buf, len))
1149 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1156 * The server wants to talk. It could be the header or the body.
1157 * If `hdr' is null, then it's the header otherwise it's the body.
1158 * FIXME: Does `hdr' really mean `host'? No.
1162 if (FD_ISSET(csp->sfd, &rfds))
1165 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1169 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1171 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1172 csp->ip_addr_str, http->ocmd);
1174 rsp = error_response(csp, "connect-failed", errno);
1178 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1179 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1181 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1185 free_http_response(rsp);
1189 /* Add a trailing zero. This lets filter_popups
1190 * use string operations.
1194 #ifdef FEATURE_KILL_POPUPS
1195 /* Filter the popups on this read. */
1196 if (block_popups_now)
1198 filter_popups(buf, csp);
1200 #endif /* def FEATURE_KILL_POPUPS */
1202 /* Normally, this would indicate that we've read
1203 * as much as the server has sent us and we can
1204 * close the client connection. However, Microsoft
1205 * in its wisdom has released IIS/5 with a bug that
1206 * prevents it from sending the trailing \r\n in
1207 * a 302 redirect header (and possibly other headers).
1208 * To work around this if we've haven't parsed
1209 * a full header we'll append a trailing \r\n
1210 * and see if this now generates a valid one.
1212 * This hack shouldn't have any impacts. If we've
1213 * already transmitted the header or if this is a
1214 * SSL connection, then we won't bother with this
1215 * hack. So we only work on partially received
1216 * headers. If we append a \r\n and this still
1217 * doesn't generate a valid header, then we won't
1218 * transmit anything to the client.
1223 if (server_body || http->ssl)
1226 * If we have been buffering up the document,
1227 * now is the time to apply content modification
1228 * and send the result to the client.
1233 * If the content filter fails, use the original
1234 * buffer and length.
1235 * (see p != NULL ? p : csp->iob->cur below)
1237 if (NULL == (p = (*content_filter)(csp)))
1239 csp->content_length = csp->iob->eod - csp->iob->cur;
1242 hdr = sed(server_patterns, add_server_headers, csp);
1245 /* FIXME Should handle error properly */
1246 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1249 if (write_socket(csp->cfd, hdr, strlen(hdr))
1250 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1252 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1262 break; /* "game over, man" */
1266 * This is NOT the body, so
1267 * Let's pretend the server just sent us a blank line.
1269 len = sprintf(buf, "\r\n");
1272 * Now, let the normal header parsing algorithm below do its
1273 * job. If it fails, we'll exit instead of continuing.
1280 * If this is an SSL connection or we're in the body
1281 * of the server document, just write it to the client,
1282 * unless we need to buffer the body for later content-filtering
1285 if (server_body || http->ssl)
1289 add_to_iob(csp, buf, len);
1292 * If the buffer limit will be reached on the next read,
1293 * switch to non-filtering mode, i.e. make & write the
1294 * header, flush the socket and get out of the way.
1296 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1298 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1300 hdr = sed(server_patterns, add_server_headers, csp);
1303 /* FIXME Should handle error properly */
1304 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1310 if (write_socket(csp->cfd, hdr, len)
1311 || (len = flush_socket(csp->cfd, csp) < 0))
1313 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1322 content_filter = NULL;
1329 if (write_socket(csp->cfd, buf, len))
1331 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1340 /* we're still looking for the end of the
1341 * server's header ... (does that make header
1342 * parsing an "out of body experience" ?
1345 /* buffer up the data we just read */
1346 add_to_iob(csp, buf, len);
1348 /* get header lines from the iob */
1350 while ((p = get_header(csp)))
1354 /* see following note */
1357 enlist(csp->headers, p);
1361 /* NOTE: there are no "empty" headers so
1362 * if the pointer `p' is not NULL we must
1363 * assume that we reached the end of the
1364 * buffer before we hit the end of the header.
1371 /* Well, we tried our MS IIS/5
1372 * hack and it didn't work.
1373 * The header is incomplete
1374 * and there isn't anything
1375 * we can do about it.
1381 /* Since we have to wait for
1382 * more from the server before
1383 * we can parse the headers
1384 * we just continue here.
1390 /* we have now received the entire header.
1391 * filter it and send the result to the client
1394 hdr = sed(server_patterns, add_server_headers, csp);
1397 /* FIXME Should handle error properly */
1398 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1401 #ifdef FEATURE_KILL_POPUPS
1402 /* Start blocking popups if appropriate. */
1404 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1405 !http->ssl && /* We talk plaintext */
1406 block_popups) /* Policy allows */
1408 block_popups_now = 1;
1410 * Filter the part of the body that came in the same read
1411 * as the last headers:
1413 filter_popups(csp->iob->cur, csp);
1416 #endif /* def FEATURE_KILL_POPUPS */
1418 /* Buffer and pcrs filter this if appropriate. */
1420 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1421 !http->ssl && /* We talk plaintext */
1422 pcrs_filter) /* Policy allows */
1424 content_filter = pcrs_filter_response;
1427 /* Buffer and gif_deanimate this if appropriate. */
1429 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1430 !http->ssl && /* We talk plaintext */
1431 gif_deanimate) /* Policy allows */
1433 content_filter = gif_deanimate_response;
1437 * Only write if we're not buffering for content modification
1439 if (!content_filter)
1441 /* write the server's (modified) header to
1442 * the client (along with anything else that
1443 * may be in the buffer)
1448 if (write_socket(csp->cfd, hdr, len)
1449 || (len = flush_socket(csp->cfd, csp) < 0))
1451 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1453 /* the write failed, so don't bother
1454 * mentioning it to the client...
1455 * it probably can't hear us anyway.
1464 /* we're finished with the server's header */
1469 /* If this was a MS IIS/5 hack then it means
1470 * the server has already closed the
1471 * connection. Nothing more to read. Time
1482 return; /* huh? we should never get here */
1485 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1486 csp->ip_addr_str, http->ocmd, byte_count);
1490 /*********************************************************************
1494 * Description : This is little more than chat. We only "serve" to
1495 * to close any socket that chat may have opened.
1498 * 1 : csp = Current client state (buffers, headers, etc...)
1502 *********************************************************************/
1504 void serve(struct client_state *csp)
1505 #else /* ifndef AMIGA */
1506 static void serve(struct client_state *csp)
1507 #endif /* def AMIGA */
1510 close_socket(csp->cfd);
1512 if (csp->sfd != JB_INVALID_SOCKET)
1514 close_socket(csp->sfd);
1517 csp->flags &= ~CSP_FLAG_ACTIVE;
1523 /*********************************************************************
1525 * Function : server_thread
1527 * Description : We only exist to call `serve' in a threaded environment.
1530 * 1 : data = Current client state (buffers, headers, etc...)
1532 * Returns : Always 0.
1534 *********************************************************************/
1535 static int32 server_thread(void *data)
1537 serve((struct client_state *) data);
1544 /*********************************************************************
1548 * Description : Print usage info & exit.
1550 * Parameters : Pointer to argv[0] for identifying ourselves
1554 *********************************************************************/
1555 void usage(const char *myname)
1557 printf("JunkBuster proxy version " VERSION " (" HOME_PAGE_URL ")\n"
1558 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1559 "Aborting.\n", myname);
1566 /*********************************************************************
1570 * Description : Load the config file and start the listen loop.
1571 * This function is a lot more *sane* with the `load_config'
1572 * and `listen_loop' functions; although it stills does
1573 * a *little* too much for my taste.
1576 * 1 : argc = Number of parameters (including $0).
1577 * 2 : argv = Array of (char *)'s to the parameters.
1579 * Returns : 1 if : can't open config file, unrecognized directive,
1580 * stats requested in multi-thread mode, can't open the
1581 * log file, can't open the jar file, listen port is invalid,
1582 * any load fails, and can't bind port.
1584 * Else main never returns, the process must be signaled
1585 * to terminate execution. Or, on Windows, use the
1586 * "File", "Exit" menu option.
1588 *********************************************************************/
1590 int real_main(int argc, const char *argv[])
1592 int main(int argc, const char *argv[])
1597 struct passwd *pw = NULL;
1598 struct group *grp = NULL;
1606 #if !defined(_WIN32)
1614 * Parse the command line arguments
1616 while (++argc_pos < argc)
1618 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1620 if (strcmp(argv[argc_pos], "--help") == 0)
1625 else if(strcmp(argv[argc_pos], "--version") == 0)
1627 printf("Junkbuster version " VERSION " (" HOME_PAGE_URL ")\n");
1631 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1636 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1638 if (++argc_pos == argc) usage(argv[0]);
1639 pidfile = strdup(argv[argc_pos]);
1642 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1644 if (++argc_pos == argc) usage(argv[argc_pos]);
1646 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1649 if (NULL == (grp = getgrnam(p)))
1651 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1655 if (NULL == (pw = getpwnam(argv[argc_pos])))
1657 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1660 if (p != NULL) *--p = '\0';
1662 #endif /* defined(unix) */
1664 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1666 configfile = argv[argc_pos];
1669 } /* -END- while (more arguments) */
1672 if ( *configfile != '/' )
1676 /* make config-filename absolute here */
1677 if ( !(basedir = getcwd( NULL, 1024 )))
1679 perror("get working dir failed");
1683 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1685 perror("malloc failed");
1688 strcpy( abs_file, basedir );
1689 strcat( abs_file, "/" );
1690 strcat( abs_file, configfile );
1691 configfile = abs_file;
1693 #endif /* defined unix */
1700 #elif defined(_WIN32)
1705 * Unix signal handling
1707 * Catch the abort, interrupt and terminate signals for a graceful exit
1708 * Catch the hangup signal so the errlog can be reopened.
1709 * Ignore the broken pipe and child signals
1710 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1712 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1715 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1716 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1718 for (idx = 0; catched_signals[idx] != 0; idx++)
1720 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1722 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1726 for (idx = 0; ignored_signals[idx] != 0; idx++)
1728 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1730 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1735 #else /* ifdef _WIN32 */
1736 # ifdef _WIN_CONSOLE
1738 * We *are* in a windows console app.
1739 * Print a verbose messages about FAQ's and such
1741 printf(win32_blurb);
1742 # endif /* def _WIN_CONSOLE */
1743 #endif /* def _WIN32 */
1746 /* Initialize the CGI subsystem */
1747 cgi_init_error_messages();
1750 * If runnig on unix and without the --nodaemon
1751 * option, become a daemon. I.e. fork, detach
1752 * from tty and get process group leadership
1765 if ( pid < 0 ) /* error */
1770 else if ( pid != 0 ) /* parent */
1775 * must check for errors
1776 * child died due to missing files aso
1779 wpid = waitpid( pid, &status, WNOHANG );
1788 /* Should be more portable, but not as well tested */
1793 #else /* ndef __FreeBSD__ */
1795 #endif /* ndef __FreeBSD__ */
1796 fd = open("/dev/tty", O_RDONLY);
1799 /* no error check here */
1800 ioctl( fd, TIOCNOTTY,0 );
1804 /* FIXME: should close stderr (fd 2) here too, but the test
1806 * and load config file is done in listen_loop() and puts
1807 * some messages on stderr there.
1814 } /* -END- if (!no_daemon) */
1817 * As soon as we have written the PID file, we can switch
1818 * to the user and group ID indicated by the --user option
1824 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1826 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1828 if (setuid(pw->pw_uid))
1830 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1834 #endif /* defined unix */
1844 /*********************************************************************
1846 * Function : bind_port_helper
1848 * Description : Bind the listen port. Handles logging, and aborts
1852 * 1 : config = Junkbuster configuration. Specifies port
1855 * Returns : Port that was opened.
1857 *********************************************************************/
1858 static jb_socket bind_port_helper(struct configuration_spec * config)
1863 if ( (config->haddr != NULL)
1864 && (config->haddr[0] == '1')
1865 && (config->haddr[1] == '2')
1866 && (config->haddr[2] == '7')
1867 && (config->haddr[3] == '.') )
1869 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1872 else if (config->haddr == NULL)
1874 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1879 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1880 config->hport, config->haddr);
1883 result = bind_port(config->haddr, config->hport, &bfd);
1890 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1891 "There may be another junkbuster or some other "
1892 "proxy running on port %d",
1893 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1894 config->hport, config->hport);
1897 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1898 "The hostname is not resolvable",
1899 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1902 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
1903 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1906 /* shouldn't get here */
1907 return JB_INVALID_SOCKET;
1910 config->need_bind = 0;
1916 /*********************************************************************
1918 * Function : listen_loop
1920 * Description : bind the listen port and enter a "FOREVER" listening loop.
1926 *********************************************************************/
1927 static void listen_loop(void)
1929 struct client_state *csp = NULL;
1931 struct configuration_spec * config;
1933 config = load_config();
1935 bfd = bind_port_helper(config);
1939 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1940 while (waitpid(-1, NULL, WNOHANG) > 0)
1942 /* zombie children */
1944 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1947 * Free data that was used by died threads
1953 * Re-open the errlog after HUP signal
1955 if (received_hup_signal)
1957 init_error_log(Argv[0], config->logfile, config->debug);
1958 received_hup_signal = 0;
1962 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1964 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1968 csp->flags |= CSP_FLAG_ACTIVE;
1969 csp->sfd = JB_INVALID_SOCKET;
1971 csp->config = config = load_config();
1973 if ( config->need_bind )
1976 * Since we were listening to the "old port", we will not see
1977 * a "listen" param change until the next IJB request. So, at
1978 * least 1 more request must be made for us to find the new
1979 * setting. I am simply closing the old socket and binding the
1982 * Which-ever is correct, we will serve 1 more page via the
1983 * old settings. This should probably be a "show-proxy-args"
1984 * request. This should not be a so common of an operation
1985 * that this will hurt people's feelings.
1990 bfd = bind_port_helper(config);
1993 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1995 if (!accept_connection(csp, bfd))
1997 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2010 log_error(LOG_LEVEL_CONNECT, "OK");
2013 #ifdef FEATURE_TOGGLE
2016 csp->flags |= CSP_FLAG_TOGGLED_ON;
2018 #endif /* def FEATURE_TOGGLE */
2020 if (run_loader(csp))
2022 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2023 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2027 if (block_acl(NULL,csp))
2029 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2030 close_socket(csp->cfd);
2034 #endif /* def FEATURE_ACL */
2036 /* add it to the list of clients */
2037 csp->next = clients->next;
2038 clients->next = csp;
2040 if (config->multi_threaded)
2044 /* this is a switch () statment in the C preprocessor - ugh */
2045 #undef SELECTED_ONE_OPTION
2047 /* Use Pthreads in preference to native code */
2048 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2049 #define SELECTED_ONE_OPTION
2051 pthread_t the_thread;
2052 pthread_attr_t attrs;
2054 pthread_attr_init(&attrs);
2055 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2056 child_id = (pthread_create(&the_thread, &attrs,
2057 (void*)serve, csp) ? -1 : 0);
2058 pthread_attr_destroy(&attrs);
2062 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2063 #define SELECTED_ONE_OPTION
2064 child_id = _beginthread(
2070 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2071 #define SELECTED_ONE_OPTION
2072 child_id = _beginthread(
2079 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2080 #define SELECTED_ONE_OPTION
2082 thread_id tid = spawn_thread
2083 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2085 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2087 child_id = (int) tid;
2096 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2097 #define SELECTED_ONE_OPTION
2098 csp->cfd = ReleaseSocket(csp->cfd, -1);
2099 if((child_id = (int)CreateNewProcTags(
2100 NP_Entry, (ULONG)server_thread,
2101 NP_Output, Output(),
2102 NP_CloseOutput, FALSE,
2103 NP_Name, (ULONG)"junkbuster child",
2104 NP_StackSize, 200*1024,
2108 ((struct Task *)child_id)->tc_UserData = csp;
2109 Signal((struct Task *)child_id, SIGF_SINGLE);
2114 #if !defined(SELECTED_ONE_OPTION)
2117 /* This block is only needed when using fork().
2118 * When using threads, the server thread was
2119 * created and run by the call to _beginthread().
2121 if (child_id == 0) /* child */
2127 else if (child_id > 0) /* parent */
2129 /* in a fork()'d environment, the parent's
2130 * copy of the client socket and the CSP
2134 #if !defined(_WIN32) && defined(__CYGWIN__)
2136 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2137 close_socket(csp->cfd);
2138 csp->flags &= ~CSP_FLAG_ACTIVE;
2142 #undef SELECTED_ONE_OPTION
2143 /* end of cpp switch () */
2145 if (child_id < 0) /* failed */
2147 char buf[BUFFER_SIZE];
2149 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2151 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
2153 write_socket(csp->cfd, buf, strlen(buf));
2154 close_socket(csp->cfd);
2155 csp->flags &= ~CSP_FLAG_ACTIVE;