1 const char jcc_rcs[] = "$Id: jcc.c,v 1.77 2002/03/07 03:52:06 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.77 2002/03/07 03:52:06 oes
37 * - Fixed compiler warnings etc
38 * - Improved handling of failed DNS lookups
40 * Revision 1.76 2002/03/06 22:54:35 jongfoster
41 * Automated function-comment nitpicking.
43 * Revision 1.75 2002/03/06 10:02:19 oes
44 * Fixed stupid bug when --user was not given
46 * Revision 1.74 2002/03/06 00:49:31 jongfoster
47 * Fixing warning on Windows
48 * Making #ifdefs that refer to the same variable consistently
49 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
51 * Revision 1.73 2002/03/05 23:57:30 hal9
52 * Stray character 's' on line 1618 was breaking build.
54 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
55 * - Re-enable OS/2 building after new parms were added
56 * - Fix false out of memory report when resolving CGI templates when no IP
57 * address is available of failed attempt (a la no such domain)
59 * Revision 1.71 2002/03/05 18:13:56 oes
62 * Revision 1.70 2002/03/05 04:52:42 oes
63 * Deleted non-errlog debugging code
65 * Revision 1.69 2002/03/04 23:50:00 jongfoster
66 * Splitting off bind_port() call into bind_port_helper(), with
69 * Revision 1.68 2002/03/04 20:17:32 oes
72 * Revision 1.67 2002/03/04 18:18:57 oes
73 * - Removed _DEBUG mode
74 * - Cleand up cmdline parsing
75 * - Introduced --no-daemon, --pidfile options
76 * - Cleaned up signal handling:
77 * - Terminate cleanly on INT, TERM and ABRT
78 * - Schedule logfile for re-opening on HUP
79 * - Ignore CHLD and PIPE
80 * - Leave the rest with their default handlers
81 * - Uniform handler registration
82 * - Added usage() function
83 * - Played styleguide police
85 * Revision 1.66 2002/03/03 15:06:55 oes
86 * Re-enabled automatic config reloading
88 * Revision 1.65 2002/03/03 14:49:11 oes
89 * Fixed CLF logging: Now uses client's original HTTP request
91 * Revision 1.64 2002/03/03 09:18:03 joergs
92 * Made jumbjuster work on AmigaOS again.
94 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
95 * Clean up a little CRLF unpleasantness that suddenly appeared
97 * Revision 1.62 2002/02/20 23:17:23 jongfoster
98 * Detecting some out-of memory conditions and exiting with a log message.
100 * Revision 1.61 2002/01/17 21:01:52 jongfoster
101 * Moving all our URL and URL pattern parsing code to urlmatch.c.
103 * Revision 1.60 2001/12/30 14:07:32 steudten
104 * - Add signal handling (unix)
105 * - Add SIGHUP handler (unix)
106 * - Add creation of pidfile (unix)
107 * - Add action 'top' in rc file (RH)
108 * - Add entry 'SIGNALS' to manpage
109 * - Add exit message to logfile (unix)
111 * Revision 1.59 2001/12/13 14:07:18 oes
112 * Fixed Bug: 503 error page now sent OK
114 * Revision 1.58 2001/11/30 23:37:24 jongfoster
115 * Renaming the Win32 config file to config.txt - this is almost the
116 * same as the corresponding UNIX name "config"
118 * Revision 1.57 2001/11/16 00:47:43 jongfoster
119 * Changing the tty-disconnection code to use setsid().
121 * Revision 1.56 2001/11/13 20:20:54 jongfoster
122 * Tabs->spaces, fixing a bug with missing {} around an if()
124 * Revision 1.55 2001/11/13 20:14:53 jongfoster
125 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
127 * Revision 1.54 2001/11/07 00:03:14 steudten
128 * Give reliable return value if an error
129 * occurs not just 0 with new daemon mode.
131 * Revision 1.53 2001/11/05 21:41:43 steudten
132 * Add changes to be a real daemon just for unix os.
133 * (change cwd to /, detach from controlling tty, set
134 * process group and session leader to the own process.
136 * Add some fatal-error log message for failed malloc().
137 * Add '-d' if compiled with 'configure --with-debug' to
138 * enable debug output.
140 * Revision 1.52 2001/10/26 20:11:20 jongfoster
141 * Fixing type mismatch
143 * Revision 1.51 2001/10/26 17:38:28 oes
146 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
147 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
148 * threads to call select() simultaneously. So, it's time to do a real, live,
149 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
150 * (native). Both versions will work, but using __OS2__ offers multi-threading.
152 * Revision 1.49 2001/10/23 21:41:35 jongfoster
153 * Added call to initialize the (statically-allocated of course)
154 * "out of memory" CGI response.
156 * Revision 1.48 2001/10/10 19:56:46 jongfoster
157 * Moving some code that wasn't cookie-related out of an #ifdef
160 * Revision 1.47 2001/10/10 16:44:36 oes
161 * Added CONNECT destination port limitation check
163 * Revision 1.46 2001/10/08 15:17:41 oes
164 * Re-enabled SSL forwarding
166 * Revision 1.45 2001/10/07 15:42:11 oes
167 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
169 * Moved downgrading of the HTTP version from parse_http_request to
170 * chat(), since we can't decide if it is necessary before we have
171 * determined the actions for the URL. The HTTP command is now
172 * *always* re-built so the repairs need no longer be special-cased.
174 * filter_popups now gets a csp pointer so it can raise the new
175 * CSP_FLAG_MODIFIED flag.
179 * Added configurable size limit for the IOB. If the IOB grows so
180 * large that the next read would exceed the limit, the header
181 * is generated, and the header & unfiltered buffer are flushed
182 * to the client. Chat then continues in non-buffering,
183 * non-filtering body mode.
185 * Revision 1.44 2001/10/02 18:13:57 oes
188 * Revision 1.43 2001/10/02 15:32:13 oes
189 * Moved generation of hdr
191 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
192 * Cleaning up 2 compiler warnings on OS/2.
194 * Revision 1.41 2001/09/16 17:05:14 jongfoster
195 * Removing unused #include showarg.h
197 * Revision 1.40 2001/09/16 15:41:45 jongfoster
198 * Fixing signed/unsigned comparison warning.
200 * Revision 1.39 2001/09/16 13:21:27 jongfoster
201 * Changes to use new list functions.
203 * Revision 1.38 2001/09/16 13:01:46 jongfoster
204 * Removing redundant function call that zeroed zalloc()'d memory.
206 * Revision 1.37 2001/09/10 11:12:24 oes
207 * Deleted unused variable
209 * Revision 1.36 2001/09/10 10:56:15 oes
210 * Silenced compiler warnings
212 * Revision 1.35 2001/07/31 14:44:22 oes
213 * Deleted unused size parameter from filter_popups()
215 * Revision 1.34 2001/07/30 22:08:36 jongfoster
216 * Tidying up #defines:
217 * - All feature #defines are now of the form FEATURE_xxx
218 * - Permanently turned off WIN_GUI_EDIT
219 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
221 * Revision 1.33 2001/07/29 19:32:00 jongfoster
222 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
224 * Revision 1.32 2001/07/29 18:47:05 jongfoster
225 * Adding missing #include "loadcfg.h"
227 * Revision 1.31 2001/07/29 12:17:48 oes
228 * Applied pthread fix by Paul Lieverse
230 * Revision 1.30 2001/07/25 22:57:13 jongfoster
231 * __BEOS__ no longer overrides FEATURE_PTHREAD.
232 * This is because FEATURE_PTHREAD will soon be widely used, so I
233 * want to keep it simple.
235 * Revision 1.29 2001/07/24 12:47:06 oes
236 * Applied BeOS support update by Eugenia
238 * Revision 1.28 2001/07/23 13:26:12 oes
239 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
241 * Revision 1.27 2001/07/19 19:09:47 haroon
242 * - Added code to take care of the situation where while processing the first
243 * server response (which includes the server header), after finding the end
244 * of the headers we were not looking past the end of the headers for
245 * content modification. I enabled it for filter_popups.
246 * Someone else should look to see if other similar operations should be
247 * done to the discarded portion of the buffer.
249 * Note 2001/07/20: No, the other content modification mechanisms will process
250 * the whole iob later anyway. --oes
252 * Revision 1.26 2001/07/18 12:31:36 oes
255 * Revision 1.25 2001/07/15 19:43:49 jongfoster
256 * Supports POSIX threads.
257 * Also removed some unused #includes.
259 * Revision 1.24 2001/07/13 14:00:40 oes
260 * - Generic content modification scheme:
261 * Each feature has its own applicability flag that is set
262 * from csp->action->flags.
263 * Replaced the "filtering" int flag , by a function pointer
264 * "content_filter" to the function that will do the content
265 * modification. If it is != NULL, the document will be buffered
266 * and processed through *content_filter, which must set
267 * csp->content_length and return a modified copy of the body
268 * or return NULL (on failiure).
269 * - Changed csp->is_text to the more generic bitmap csp->content_type
270 * which can currently take the valued CT_TEXT or CT_GIF
272 * - Removed all #ifdef PCRS
274 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
275 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
276 * the `block_acl' call. This prevents a compilation error when the user
277 * does not wish to use the "ACL" feature.
279 * Revision 1.22 2001/06/29 21:45:41 oes
280 * Indentation, CRLF->LF, Tab-> Space
282 * Revision 1.21 2001/06/29 13:29:36 oes
283 * - Cleaned up, improved comments
284 * - Unified all possible interceptors (CGI,
285 * block, trust, fast_redirect) in one
286 * place, with one (CGI) answer generation
287 * mechansim. Much clearer now.
288 * - Removed the GIF image generation, which
289 * is now done in filters.c:block_url()
290 * - Made error conditions like domain lookup
291 * failiure or (various) problems while talking
292 * to the server use cgi.c:error_response()
293 * instead of generating HTML/HTTP in chat() (yuck!)
294 * - Removed logentry from cancelled commit
296 * Revision 1.20 2001/06/09 10:55:28 jongfoster
297 * Changing BUFSIZ ==> BUFFER_SIZE
299 * Revision 1.19 2001/06/07 23:12:52 jongfoster
300 * Replacing function pointer in struct gateway with a directly
301 * called function forwarded_connect().
302 * Replacing struct gateway with struct forward_spec
304 * Revision 1.18 2001/06/03 19:12:16 oes
305 * introduced new cgi handling
307 * Revision 1.17 2001/06/01 20:07:23 jongfoster
308 * Now uses action +image-blocker{} rather than config->tinygif
310 * Revision 1.16 2001/06/01 18:49:17 jongfoster
311 * Replaced "list_share" with "list" - the tiny memory gain was not
312 * worth the extra complexity.
314 * Revision 1.15 2001/05/31 21:24:47 jongfoster
315 * Changed "permission" to "action" throughout.
316 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
317 * Moved vanilla wafer check into chat(), since we must now
318 * decide whether or not to add it based on the URL.
320 * Revision 1.14 2001/05/29 20:14:01 joergs
321 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
324 * Revision 1.13 2001/05/29 09:50:24 jongfoster
325 * Unified blocklist/imagelist/permissionslist.
326 * File format is still under discussion, but the internal changes
329 * Also modified interceptor behaviour:
330 * - We now intercept all URLs beginning with one of the following
331 * prefixes (and *only* these prefixes):
333 * * http://ijbswa.sf.net/config/
334 * * http://ijbswa.sourceforge.net/config/
335 * - New interceptors "home page" - go to http://i.j.b/ to see it.
336 * - Internal changes so that intercepted and fast redirect pages
337 * are not replaced with an image.
338 * - Interceptors now have the option to send a binary page direct
339 * to the client. (i.e. ijb-send-banner uses this)
340 * - Implemented show-url-info interceptor. (Which is why I needed
341 * the above interceptors changes - a typical URL is
342 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
343 * The previous mechanism would not have intercepted that, and
344 * if it had been intercepted then it then it would have replaced
347 * Revision 1.12 2001/05/27 22:17:04 oes
349 * - re_process_buffer no longer writes the modified buffer
350 * to the client, which was very ugly. It now returns the
351 * buffer, which it is then written by chat.
353 * - content_length now adjusts the Content-Length: header
354 * for modified documents rather than crunch()ing it.
355 * (Length info in csp->content_length, which is 0 for
356 * unmodified documents)
358 * - For this to work, sed() is called twice when filtering.
360 * Revision 1.11 2001/05/26 17:27:53 jongfoster
361 * Added support for CLF and fixed LOG_LEVEL_LOG.
362 * Also did CRLF->LF fix of my previous patch.
364 * Revision 1.10 2001/05/26 15:26:15 jongfoster
365 * ACL feature now provides more security by immediately dropping
366 * connections from untrusted hosts.
368 * Revision 1.9 2001/05/26 00:28:36 jongfoster
369 * Automatic reloading of config file.
370 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
371 * Most of the global variables have been moved to a new
372 * struct configuration_spec, accessed through csp->config->globalname
373 * Most of the globals remaining are used by the Win32 GUI.
375 * Revision 1.8 2001/05/25 22:43:18 jongfoster
376 * Fixing minor memory leak and buffer overflow.
378 * Revision 1.7 2001/05/25 22:34:30 jongfoster
381 * Revision 1.6 2001/05/23 00:13:58 joergs
382 * AmigaOS support fixed.
384 * Revision 1.5 2001/05/22 18:46:04 oes
386 * - Enabled filtering banners by size rather than URL
387 * by adding patterns that replace all standard banner
388 * sizes with the "Junkbuster" gif to the re_filterfile
390 * - Enabled filtering WebBugs by providing a pattern
391 * which kills all 1x1 images
393 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
394 * which is selected by the (nonstandard and therefore
395 * capital) letter 'U' in the option string.
396 * It causes the quantifiers to be ungreedy by default.
397 * Appending a ? turns back to greedy (!).
399 * - Added a new interceptor ijb-send-banner, which
400 * sends back the "Junkbuster" gif. Without imagelist or
401 * MSIE detection support, or if tinygif = 1, or the
402 * URL isn't recognized as an imageurl, a lame HTML
403 * explanation is sent instead.
405 * - Added new feature, which permits blocking remote
406 * script redirects and firing back a local redirect
408 * The feature is conditionally compiled, i.e. it
409 * can be disabled with --disable-fast-redirects,
410 * plus it must be activated by a "fast-redirects"
411 * line in the config file, has its own log level
412 * and of course wants to be displayed by show-proxy-args
413 * Note: Boy, all the #ifdefs in 1001 locations and
414 * all the fumbling with configure.in and acconfig.h
415 * were *way* more work than the feature itself :-(
417 * - Because a generic redirect template was needed for
418 * this, tinygif = 3 now uses the same.
420 * - Moved GIFs, and other static HTTP response templates
425 * - Removed some >400 CRs again (Jon, you really worked
428 * Revision 1.4 2001/05/21 19:34:01 jongfoster
429 * Made failure to bind() a fatal error.
431 * Revision 1.3 2001/05/20 01:21:20 jongfoster
432 * Version 2.9.4 checkin.
433 * - Merged popupfile and cookiefile, and added control over PCRS
434 * filtering, in new "permissionsfile".
435 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
436 * file error you now get a message box (in the Win32 GUI) rather
437 * than the program exiting with no explanation.
438 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
440 * - Removed tabs from "config"
441 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
442 * - Bumped up version number.
444 * Revision 1.2 2001/05/17 22:34:44 oes
445 * - Added hint on GIF char array generation to jcc.c
446 * - Cleaned CRLF's from the sources and related files
447 * - Repaired logging for REF and FRC
449 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
450 * Initial import of version 2.9.3 source tree
453 *********************************************************************/
459 #include <sys/types.h>
466 #ifdef FEATURE_PTHREAD
468 #endif /* def FEATURE_PTHREAD */
471 # ifndef FEATURE_PTHREAD
472 # include <windows.h>
473 # include <process.h>
474 # endif /* ndef FEATURE_PTHREAD */
477 # ifndef _WIN_CONSOLE
479 # endif /* ndef _WIN_CONSOLE */
481 #else /* ifndef _WIN32 */
483 # if !defined (__OS2__)
485 # include <sys/wait.h>
486 # endif /* ndef __OS2__ */
487 # include <sys/time.h>
488 # include <sys/stat.h>
489 # include <sys/ioctl.h>
492 #include <sys/termios.h>
503 # include <socket.h> /* BeOS has select() for sockets only. */
504 # include <OS.h> /* declarations for threads and stuff. */
507 # if defined(__EMX__) || defined(__OS2__)
508 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
513 #define bzero(B,N) memset(B,0x00,n)
528 #include "killpopup.h"
529 #include "miscutil.h"
531 #include "jbsockets.h"
536 #include "urlmatch.h"
538 const char jcc_h_rcs[] = JCC_H_VERSION;
539 const char project_h_rcs[] = PROJECT_H_VERSION;
542 struct client_state clients[1];
543 struct file_list files[1];
545 #ifdef FEATURE_STATISTICS
546 int urls_read = 0; /* total nr of urls read inc rejected */
547 int urls_rejected = 0; /* total nr of urls rejected */
548 #endif /* def FEATURE_STATISTICS */
551 static void listen_loop(void);
552 static void chat(struct client_state *csp);
554 void serve(struct client_state *csp);
555 #else /* ifndef AMIGA */
556 static void serve(struct client_state *csp);
557 #endif /* def AMIGA */
560 static int32 server_thread(void *data);
561 #endif /* def __BEOS__ */
564 #define sleep(N) Sleep(((N) * 1000))
568 #define sleep(N) DosSleep(((N) * 100))
573 const char *pidfile = NULL;
574 int received_hup_signal = 0;
575 #endif /* defined unix */
577 /* The vanilla wafer. */
578 static const char VANILLA_WAFER[] =
579 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
580 "Do_not_send_me_any_copyrighted_information_other_than_the_"
581 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
582 "In_particular_do_not_send_me_any_cookies_that_"
583 "are_subject_to_a_claim_of_copyright_by_anybody._"
584 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
585 "(copyright_or_otherwise)_applying_to_any_cookie._";
588 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
589 /*********************************************************************
591 * Function : sig_handler
593 * Description : Signal handler for different signals.
594 * Exit gracefully on ABRT, TERM and INT
595 * or set a flag that will cause the errlog
596 * to be reopened by the main thread on HUP.
599 * 1 : the_signal = the signal cause this function to call
603 *********************************************************************/
604 static void sig_handler(int the_signal)
611 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
619 received_hup_signal = 1;
624 * We shouldn't be here, unless we catch signals
625 * in main() that we can't handle here!
627 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
635 /*********************************************************************
639 * Description : Once a connection to the client has been accepted,
640 * this function is called (via serve()) to handle the
641 * main business of the communication. When this
642 * function returns, the caller must close the client
646 * 1 : csp = Current client state (buffers, headers, etc...)
648 * Returns : On success, the number of bytes written are returned (zero
649 * indicates nothing was written). On error, -1 is returned,
650 * and errno is set appropriately. If count is zero and the
651 * file descriptor refers to a regular file, 0 will be
652 * returned without causing any other effect. For a special
653 * file, the results are not portable.
655 *********************************************************************/
656 static void chat(struct client_state *csp)
659 * This next lines are a little ugly, but they simplifies the if statements
660 * below. Basically if TOGGLE, then we want the if to test if the
661 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
662 * then we want the if to test for CSP_FLAG_FORCED , else we don't
664 #ifdef FEATURE_TOGGLE
665 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
666 #else /* ifndef FEATURE_TOGGLE */
667 # define IS_TOGGLED_ON_AND
668 #endif /* ndef FEATURE_TOGGLE */
669 #ifdef FEATURE_FORCE_LOAD
670 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
671 #else /* ifndef FEATURE_FORCE_LOAD */
672 # define IS_NOT_FORCED_AND
673 #endif /* def FEATURE_FORCE_LOAD */
675 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
677 char buf[BUFFER_SIZE];
680 int n, maxfd, server_body;
681 int ms_iis5_hack = 0;
683 const struct forward_spec * fwd;
684 struct http_request *http;
685 size_t len; /* for buffer sizes */
686 #ifdef FEATURE_KILL_POPUPS
687 int block_popups; /* bool, 1==will block popups */
688 int block_popups_now = 0; /* bool, 1==currently blocking popups */
689 #endif /* def FEATURE_KILL_POPUPS */
691 int pcrs_filter; /* bool, 1==will filter through pcrs */
692 int gif_deanimate; /* bool, 1==will deanimate gifs */
694 /* Function that does the content filtering for the current request */
695 char *(*content_filter)() = NULL;
697 /* Skeleton for HTTP response, if we should intercept the request */
698 struct http_response *rsp;
703 * Read the client's request. Note that since we're not using select() we
704 * could get blocked here if a client connected, then didn't say anything!
709 len = read_socket(csp->cfd, buf, sizeof(buf));
711 if (len <= 0) break; /* error! */
713 add_to_iob(csp, buf, len);
715 req = get_header(csp);
719 break; /* no HTTP request! */
724 continue; /* more to come! */
727 #ifdef FEATURE_FORCE_LOAD
728 /* If this request contains the FORCE_PREFIX,
729 * better get rid of it now and set the force flag --oes
732 if (strstr(req, FORCE_PREFIX))
734 strclean(req, FORCE_PREFIX);
735 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
736 csp->flags |= CSP_FLAG_FORCED;
739 #endif /* def FEATURE_FORCE_LOAD */
741 parse_http_request(req, http, csp);
746 if (http->cmd == NULL)
748 strcpy(buf, CHEADER);
749 write_socket(csp->cfd, buf, strlen(buf));
751 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
756 /* decide how to route the HTTP request */
758 if ((fwd = forward_url(http, csp)) == NULL)
760 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
761 /* Never get here - LOG_LEVEL_FATAL causes program exit */
764 /* build the http request to send to the server
765 * we have to do one of the following:
767 * create = use the original HTTP request to create a new
768 * HTTP request that has either the path component
769 * without the http://domainspec (w/path) or the
770 * full orininal URL (w/url)
771 * Note that the path and/or the HTTP version may
772 * have been altered by now.
774 * connect = Open a socket to the host:port of the server
775 * and short-circuit server and client socket.
777 * pass = Pass the request unchanged if forwarding a CONNECT
778 * request to a parent proxy. Note that we'll be sending
779 * the CFAIL message ourselves if connecting to the parent
780 * fails, but we won't send a CSUCCEED message if it works,
781 * since that would result in a double message (ours and the
782 * parent's). After sending the request to the parent, we simply
788 * +--------+--------+
790 * 0 | create | connect|
792 * Forwarding +--------+--------+
794 * 1 | create | pass |
796 * +--------+--------+
801 * Determine the actions for this URL
803 #ifdef FEATURE_TOGGLE
804 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
806 /* Most compatible set of actions (i.e. none) */
807 init_current_action(csp->action);
810 #endif /* ndef FEATURE_TOGGLE */
812 url_actions(http, csp);
817 * Check if a CONNECT request is allowable:
818 * In the absence of a +limit-connect action, allow only port 443.
819 * If there is an action, allow whatever matches the specificaton.
823 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
824 || (csp->action->flags & ACTION_LIMIT_CONNECT
825 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
827 strcpy(buf, CFORBIDDEN);
828 write_socket(csp->cfd, buf, strlen(buf));
830 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
831 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
839 * Downgrade http version from 1.1 to 1.0 if +downgrade
842 if ( (http->ssl == 0)
843 && (!strcmpic(http->ver, "HTTP/1.1"))
844 && (csp->action->flags & ACTION_DOWNGRADE))
847 http->ver = strdup("HTTP/1.0");
849 if (http->ver == NULL)
851 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
856 * Save a copy of the original request for logging
858 http->ocmd = strdup(http->cmd);
860 if (http->ocmd == NULL)
862 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
866 * (Re)build the HTTP request for non-SSL requests.
867 * If forwarding, use the whole URL, else, use only the path.
873 http->cmd = strdup(http->gpc);
874 string_append(&http->cmd, " ");
876 if (fwd->forward_host)
878 string_append(&http->cmd, http->url);
882 string_append(&http->cmd, http->path);
885 string_append(&http->cmd, " ");
886 string_append(&http->cmd, http->ver);
888 if (http->cmd == NULL)
890 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
893 enlist(csp->headers, http->cmd);
896 #ifdef FEATURE_COOKIE_JAR
898 * If we're logging cookies in a cookie jar, and the user has not
899 * supplied any wafers, and the user has not told us to suppress the
900 * vanilla wafer, then send the vanilla wafer.
902 if ((csp->config->jarfile != NULL)
903 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
904 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
906 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
908 #endif /* def FEATURE_COOKIE_JAR */
911 #ifdef FEATURE_KILL_POPUPS
912 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
913 #endif /* def FEATURE_KILL_POPUPS */
915 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
916 ((csp->action->flags & ACTION_FILTER) != 0);
918 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
920 /* grab the rest of the client's headers */
924 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
926 len = read_socket(csp->cfd, buf, sizeof(buf));
929 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
932 add_to_iob(csp, buf, len);
936 if (p == NULL) break;
938 enlist(csp->headers, p);
942 * We have a request. Now, check to see if we need to
943 * intercept it, i.e. If ..
947 /* a CGI call was detected and answered */
948 (NULL != (rsp = dispatch_cgi(csp)))
950 /* or we are enabled and... */
953 /* ..the request was blocked */
954 ( NULL != (rsp = block_url(csp)))
958 || ( NULL != (rsp = trust_url(csp)))
959 #endif /* def FEATURE_TRUST */
961 /* ..or a fast redirect kicked in */
962 #ifdef FEATURE_FAST_REDIRECTS
963 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
964 (NULL != (rsp = redirect_url(csp))))
965 #endif /* def FEATURE_FAST_REDIRECTS */
969 /* Write the answer to the client */
970 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
971 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
973 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
976 #ifdef FEATURE_STATISTICS
977 /* Count as a rejected request */
978 csp->flags |= CSP_FLAG_REJECTED;
979 #endif /* def FEATURE_STATISTICS */
981 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
982 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
983 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
985 /* Clean up and return */
986 free_http_response(rsp);
990 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
992 if (fwd->forward_host)
994 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
995 fwd->forward_host, fwd->forward_port, http->hostport);
999 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1002 /* here we connect to the server, gateway, or the forwarder */
1004 csp->sfd = forwarded_connect(fwd, http, csp);
1008 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1011 if (errno == EINVAL)
1013 rsp = error_response(csp, "no-such-domain", errno);
1015 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1016 csp->ip_addr_str, http->ocmd);
1020 rsp = error_response(csp, "connect-failed", errno);
1022 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1023 csp->ip_addr_str, http->ocmd);
1027 /* Write the answer to the client */
1030 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1031 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1033 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1037 free_http_response(rsp);
1041 log_error(LOG_LEVEL_CONNECT, "OK");
1043 hdr = sed(client_patterns, add_client_headers, csp);
1046 /* FIXME Should handle error properly */
1047 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1050 list_remove_all(csp->headers);
1052 if (fwd->forward_host || (http->ssl == 0))
1054 /* write the client's (modified) header to the server
1055 * (along with anything else that may be in the buffer)
1060 if ((write_socket(csp->sfd, hdr, len) != len)
1061 || (flush_socket(csp->sfd, csp ) < 0))
1063 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1066 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1067 csp->ip_addr_str, http->ocmd);
1069 rsp = error_response(csp, "connect-failed", errno);
1073 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1074 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1076 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1080 free_http_response(rsp);
1088 * We're running an SSL tunnel and we're not forwarding,
1089 * so just send the "connect succeeded" message to the
1090 * client, flush the rest, and get out of the way.
1092 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1093 csp->ip_addr_str, http->ocmd);
1095 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
1103 /* we're finished with the client's header */
1106 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1108 /* pass data between the client and server
1109 * until one or the other shuts down the connection.
1118 FD_SET(csp->cfd, &rfds);
1119 FD_SET(csp->sfd, &rfds);
1121 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1125 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1129 /* this is the body of the browser's request
1130 * just read it and write it.
1133 if (FD_ISSET(csp->cfd, &rfds))
1135 len = read_socket(csp->cfd, buf, sizeof(buf));
1139 break; /* "game over, man" */
1142 if (write_socket(csp->sfd, buf, len) != len)
1144 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1151 * The server wants to talk. It could be the header or the body.
1152 * If `hdr' is null, then it's the header otherwise it's the body.
1153 * FIXME: Does `hdr' really mean `host'? No.
1157 if (FD_ISSET(csp->sfd, &rfds))
1160 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1164 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1166 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1167 csp->ip_addr_str, http->ocmd);
1169 rsp = error_response(csp, "connect-failed", errno);
1173 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1174 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1176 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1180 free_http_response(rsp);
1184 /* Add a trailing zero. This lets filter_popups
1185 * use string operations.
1189 #ifdef FEATURE_KILL_POPUPS
1190 /* Filter the popups on this read. */
1191 if (block_popups_now)
1193 filter_popups(buf, csp);
1195 #endif /* def FEATURE_KILL_POPUPS */
1197 /* Normally, this would indicate that we've read
1198 * as much as the server has sent us and we can
1199 * close the client connection. However, Microsoft
1200 * in its wisdom has released IIS/5 with a bug that
1201 * prevents it from sending the trailing \r\n in
1202 * a 302 redirect header (and possibly other headers).
1203 * To work around this if we've haven't parsed
1204 * a full header we'll append a trailing \r\n
1205 * and see if this now generates a valid one.
1207 * This hack shouldn't have any impacts. If we've
1208 * already transmitted the header or if this is a
1209 * SSL connection, then we won't bother with this
1210 * hack. So we only work on partially received
1211 * headers. If we append a \r\n and this still
1212 * doesn't generate a valid header, then we won't
1213 * transmit anything to the client.
1218 if (server_body || http->ssl)
1221 * If we have been buffering up the document,
1222 * now is the time to apply content modification
1223 * and send the result to the client.
1228 * If the content filter fails, use the original
1229 * buffer and length.
1230 * (see p != NULL ? p : csp->iob->cur below)
1232 if (NULL == (p = (*content_filter)(csp)))
1234 csp->content_length = csp->iob->eod - csp->iob->cur;
1237 hdr = sed(server_patterns, add_server_headers, csp);
1240 /* FIXME Should handle error properly */
1241 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1246 if ((write_socket(csp->cfd, hdr, len) != len)
1247 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1249 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1259 break; /* "game over, man" */
1263 * This is NOT the body, so
1264 * Let's pretend the server just sent us a blank line.
1266 len = sprintf(buf, "\r\n");
1269 * Now, let the normal header parsing algorithm below do its
1270 * job. If it fails, we'll exit instead of continuing.
1277 * If this is an SSL connection or we're in the body
1278 * of the server document, just write it to the client,
1279 * unless we need to buffer the body for later content-filtering
1282 if (server_body || http->ssl)
1286 add_to_iob(csp, buf, len);
1289 * If the buffer limit will be reached on the next read,
1290 * switch to non-filtering mode, i.e. make & write the
1291 * header, flush the socket and get out of the way.
1293 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1295 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1297 hdr = sed(server_patterns, add_server_headers, csp);
1300 /* FIXME Should handle error properly */
1301 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1307 if (((write_socket(csp->cfd, hdr, len) != len)
1308 || (len = flush_socket(csp->cfd, csp) < 0)))
1310 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1319 content_filter = NULL;
1326 if (write_socket(csp->cfd, buf, len) != len)
1328 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1337 /* we're still looking for the end of the
1338 * server's header ... (does that make header
1339 * parsing an "out of body experience" ?
1342 /* buffer up the data we just read */
1343 add_to_iob(csp, buf, len);
1345 /* get header lines from the iob */
1347 while ((p = get_header(csp)))
1351 /* see following note */
1354 enlist(csp->headers, p);
1358 /* NOTE: there are no "empty" headers so
1359 * if the pointer `p' is not NULL we must
1360 * assume that we reached the end of the
1361 * buffer before we hit the end of the header.
1368 /* Well, we tried our MS IIS/5
1369 * hack and it didn't work.
1370 * The header is incomplete
1371 * and there isn't anything
1372 * we can do about it.
1378 /* Since we have to wait for
1379 * more from the server before
1380 * we can parse the headers
1381 * we just continue here.
1387 /* we have now received the entire header.
1388 * filter it and send the result to the client
1391 hdr = sed(server_patterns, add_server_headers, csp);
1394 /* FIXME Should handle error properly */
1395 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1400 /* write the server's (modified) header to
1401 * the client (along with anything else that
1402 * may be in the buffer)
1405 #ifdef FEATURE_KILL_POPUPS
1406 /* Start blocking popups if appropriate. */
1408 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1409 !http->ssl && /* We talk plaintext */
1410 block_popups) /* Policy allows */
1412 block_popups_now = 1;
1414 * Filter the part of the body that came in the same read
1415 * as the last headers:
1417 filter_popups(csp->iob->cur, csp);
1420 #endif /* def FEATURE_KILL_POPUPS */
1422 /* Buffer and pcrs filter this if appropriate. */
1424 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1425 !http->ssl && /* We talk plaintext */
1426 pcrs_filter) /* Policy allows */
1428 content_filter = pcrs_filter_response;
1431 /* Buffer and gif_deanimate this if appropriate. */
1433 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1434 !http->ssl && /* We talk plaintext */
1435 gif_deanimate) /* Policy allows */
1437 content_filter = gif_deanimate_response;
1442 * Only write if we're not buffering for content modification
1444 if (!content_filter && ((write_socket(csp->cfd, hdr, len) != len)
1445 || (len = flush_socket(csp->cfd, csp) < 0)))
1447 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1449 /* the write failed, so don't bother
1450 * mentioning it to the client...
1451 * it probably can't hear us anyway.
1457 if(!content_filter) byte_count += len;
1459 /* we're finished with the server's header */
1464 /* If this was a MS IIS/5 hack then it means
1465 * the server has already closed the
1466 * connection. Nothing more to read. Time
1477 return; /* huh? we should never get here */
1480 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1481 csp->ip_addr_str, http->ocmd, byte_count);
1485 /*********************************************************************
1489 * Description : This is little more than chat. We only "serve" to
1490 * to close any socket that chat may have opened.
1493 * 1 : csp = Current client state (buffers, headers, etc...)
1497 *********************************************************************/
1499 void serve(struct client_state *csp)
1500 #else /* ifndef AMIGA */
1501 static void serve(struct client_state *csp)
1502 #endif /* def AMIGA */
1505 close_socket(csp->cfd);
1509 close_socket(csp->sfd);
1512 csp->flags &= ~CSP_FLAG_ACTIVE;
1518 /*********************************************************************
1520 * Function : server_thread
1522 * Description : We only exist to call `serve' in a threaded environment.
1525 * 1 : data = Current client state (buffers, headers, etc...)
1527 * Returns : Always 0.
1529 *********************************************************************/
1530 static int32 server_thread(void *data)
1532 serve((struct client_state *) data);
1539 /*********************************************************************
1543 * Description : Print usage info & exit.
1545 * Parameters : Pointer to argv[0] for identifying ourselves
1549 *********************************************************************/
1550 void usage(const char *myname)
1552 printf("JunkBuster proxy version " VERSION " (" HOME_PAGE_URL ")\n"
1553 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1554 "Aborting.\n", myname);
1561 /*********************************************************************
1565 * Description : Load the config file and start the listen loop.
1566 * This function is a lot more *sane* with the `load_config'
1567 * and `listen_loop' functions; although it stills does
1568 * a *little* too much for my taste.
1571 * 1 : argc = Number of parameters (including $0).
1572 * 2 : argv = Array of (char *)'s to the parameters.
1574 * Returns : 1 if : can't open config file, unrecognized directive,
1575 * stats requested in multi-thread mode, can't open the
1576 * log file, can't open the jar file, listen port is invalid,
1577 * any load fails, and can't bind port.
1579 * Else main never returns, the process must be signaled
1580 * to terminate execution. Or, on Windows, use the
1581 * "File", "Exit" menu option.
1583 *********************************************************************/
1585 int real_main(int argc, const char *argv[])
1587 int main(int argc, const char *argv[])
1592 struct passwd *pw = NULL;
1593 struct group *grp = NULL;
1601 #if !defined(_WIN32)
1609 * Parse the command line arguments
1611 while (++argc_pos < argc)
1613 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1615 if (strcmp(argv[argc_pos], "--help") == 0)
1620 else if(strcmp(argv[argc_pos], "--version") == 0)
1622 printf("Junkbuster version " VERSION " (" HOME_PAGE_URL ")\n");
1626 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1631 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1633 if (++argc_pos == argc) usage(argv[0]);
1634 pidfile = strdup(argv[argc_pos]);
1637 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1639 if (++argc_pos == argc) usage(argv[argc_pos]);
1641 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1644 if (NULL == (grp = getgrnam(p)))
1646 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1650 if (NULL == (pw = getpwnam(argv[argc_pos])))
1652 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1655 if (p != NULL) *--p = '\0';
1657 #endif /* defined(unix) */
1659 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1661 configfile = argv[argc_pos];
1664 } /* -END- while (more arguments) */
1667 if ( *configfile != '/' )
1671 /* make config-filename absolute here */
1672 if ( !(basedir = getcwd( NULL, 1024 )))
1674 perror("get working dir failed");
1678 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1680 perror("malloc failed");
1683 strcpy( abs_file, basedir );
1684 strcat( abs_file, "/" );
1685 strcat( abs_file, configfile );
1686 configfile = abs_file;
1688 #endif /* defined unix */
1695 #elif defined(_WIN32)
1700 * Unix signal handling
1702 * Catch the abort, interrupt and terminate signals for a graceful exit
1703 * Catch the hangup signal so the errlog can be reopened.
1704 * Ignore the broken pipe and child signals
1705 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1707 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1710 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1711 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1713 for (idx = 0; catched_signals[idx] != 0; idx++)
1715 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1717 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1721 for (idx = 0; ignored_signals[idx] != 0; idx++)
1723 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1725 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1730 #else /* ifdef _WIN32 */
1731 # ifdef _WIN_CONSOLE
1733 * We *are* in a windows console app.
1734 * Print a verbose messages about FAQ's and such
1736 printf(win32_blurb);
1737 # endif /* def _WIN_CONSOLE */
1738 #endif /* def _WIN32 */
1741 /* Initialize the CGI subsystem */
1742 cgi_init_error_messages();
1745 * If runnig on unix and without the --nodaemon
1746 * option, become a daemon. I.e. fork, detach
1747 * from tty and get process group leadership
1760 if ( pid < 0 ) /* error */
1765 else if ( pid != 0 ) /* parent */
1770 * must check for errors
1771 * child died due to missing files aso
1774 wpid = waitpid( pid, &status, WNOHANG );
1783 /* Should be more portable, but not as well tested */
1788 #else /* ndef __FreeBSD__ */
1790 #endif /* ndef __FreeBSD__ */
1791 fd = open("/dev/tty", O_RDONLY);
1794 /* no error check here */
1795 ioctl( fd, TIOCNOTTY,0 );
1799 /* FIXME: should close stderr (fd 2) here too, but the test
1801 * and load config file is done in listen_loop() and puts
1802 * some messages on stderr there.
1809 } /* -END- if (!no_daemon) */
1812 * As soon as we have written the PID file, we can switch
1813 * to the user and group ID indicated by the --user option
1819 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1821 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1823 if (setuid(pw->pw_uid))
1825 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1829 #endif /* defined unix */
1839 /*********************************************************************
1841 * Function : bind_port_helper
1843 * Description : Bind the listen port. Handles logging, and aborts
1847 * 1 : config = Junkbuster configuration. Specifies port
1850 * Returns : Port that was opened.
1852 *********************************************************************/
1853 static int bind_port_helper(struct configuration_spec * config)
1857 if ( (config->haddr != NULL)
1858 && (config->haddr[0] == '1')
1859 && (config->haddr[1] == '2')
1860 && (config->haddr[2] == '7')
1861 && (config->haddr[3] == '.') )
1863 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1866 else if (config->haddr == NULL)
1868 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1873 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1874 config->hport, config->haddr);
1877 bfd = bind_port(config->haddr, config->hport);
1884 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1885 "There may be another junkbuster or some other "
1886 "proxy running on port %d",
1887 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1888 config->hport, config->hport);
1891 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1892 "The hostname is not resolvable",
1893 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1896 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
1897 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1900 /* shouldn't get here */
1904 config->need_bind = 0;
1910 /*********************************************************************
1912 * Function : listen_loop
1914 * Description : bind the listen port and enter a "FOREVER" listening loop.
1920 *********************************************************************/
1921 static void listen_loop(void)
1923 struct client_state *csp = NULL;
1925 struct configuration_spec * config;
1927 config = load_config();
1929 bfd = bind_port_helper(config);
1933 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1934 while (waitpid(-1, NULL, WNOHANG) > 0)
1936 /* zombie children */
1938 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1941 * Free data that was used by died threads
1947 * Re-open the errlog after HUP signal
1949 if (received_hup_signal)
1951 init_error_log(Argv[0], config->logfile, config->debug);
1952 received_hup_signal = 0;
1956 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1958 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1962 csp->flags |= CSP_FLAG_ACTIVE;
1965 csp->config = config = load_config();
1967 if ( config->need_bind )
1970 * Since we were listening to the "old port", we will not see
1971 * a "listen" param change until the next IJB request. So, at
1972 * least 1 more request must be made for us to find the new
1973 * setting. I am simply closing the old socket and binding the
1976 * Which-ever is correct, we will serve 1 more page via the
1977 * old settings. This should probably be a "show-proxy-args"
1978 * request. This should not be a so common of an operation
1979 * that this will hurt people's feelings.
1984 bfd = bind_port_helper(config);
1987 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1989 if (!accept_connection(csp, bfd))
1991 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2004 log_error(LOG_LEVEL_CONNECT, "OK");
2007 #ifdef FEATURE_TOGGLE
2010 csp->flags |= CSP_FLAG_TOGGLED_ON;
2012 #endif /* def FEATURE_TOGGLE */
2014 if (run_loader(csp))
2016 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2017 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2021 if (block_acl(NULL,csp))
2023 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2024 close_socket(csp->cfd);
2028 #endif /* def FEATURE_ACL */
2030 /* add it to the list of clients */
2031 csp->next = clients->next;
2032 clients->next = csp;
2034 if (config->multi_threaded)
2038 /* this is a switch () statment in the C preprocessor - ugh */
2039 #undef SELECTED_ONE_OPTION
2041 /* Use Pthreads in preference to native code */
2042 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2043 #define SELECTED_ONE_OPTION
2045 pthread_t the_thread;
2046 pthread_attr_t attrs;
2048 pthread_attr_init(&attrs);
2049 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2050 child_id = (pthread_create(&the_thread, &attrs,
2051 (void*)serve, csp) ? -1 : 0);
2052 pthread_attr_destroy(&attrs);
2056 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2057 #define SELECTED_ONE_OPTION
2058 child_id = _beginthread(
2064 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2065 #define SELECTED_ONE_OPTION
2066 child_id = _beginthread(
2073 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2074 #define SELECTED_ONE_OPTION
2076 thread_id tid = spawn_thread
2077 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2079 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2081 child_id = (int) tid;
2090 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2091 #define SELECTED_ONE_OPTION
2092 csp->cfd = ReleaseSocket(csp->cfd, -1);
2093 if((child_id = (int)CreateNewProcTags(
2094 NP_Entry, (ULONG)server_thread,
2095 NP_Output, Output(),
2096 NP_CloseOutput, FALSE,
2097 NP_Name, (ULONG)"junkbuster child",
2098 NP_StackSize, 200*1024,
2102 ((struct Task *)child_id)->tc_UserData = csp;
2103 Signal((struct Task *)child_id, SIGF_SINGLE);
2108 #if !defined(SELECTED_ONE_OPTION)
2111 /* This block is only needed when using fork().
2112 * When using threads, the server thread was
2113 * created and run by the call to _beginthread().
2115 if (child_id == 0) /* child */
2121 else if (child_id > 0) /* parent */
2123 /* in a fork()'d environment, the parent's
2124 * copy of the client socket and the CSP
2128 #if !defined(_WIN32) && defined(__CYGWIN__)
2130 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2131 close_socket(csp->cfd);
2132 csp->flags &= ~CSP_FLAG_ACTIVE;
2136 #undef SELECTED_ONE_OPTION
2137 /* end of cpp switch () */
2139 if (child_id < 0) /* failed */
2141 char buf[BUFFER_SIZE];
2143 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2145 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
2147 write_socket(csp->cfd, buf, strlen(buf));
2148 close_socket(csp->cfd);
2149 csp->flags &= ~CSP_FLAG_ACTIVE;