1 const char jcc_rcs[] = "$Id: jcc.c,v 1.72 2002/03/05 21:33:45 david__schmidt Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001 the SourceForge
10 * 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.72 2002/03/05 21:33:45 david__schmidt
37 * - Re-enable OS/2 building after new parms were added
38 * - Fix false out of memory report when resolving CGI templates when no IP
39 * address is available of failed attempt (a la no such domain)
41 * Revision 1.71 2002/03/05 18:13:56 oes
44 * Revision 1.70 2002/03/05 04:52:42 oes
45 * Deleted non-errlog debugging code
47 * Revision 1.69 2002/03/04 23:50:00 jongfoster
48 * Splitting off bind_port() call into bind_port_helper(), with
51 * Revision 1.68 2002/03/04 20:17:32 oes
54 * Revision 1.67 2002/03/04 18:18:57 oes
55 * - Removed _DEBUG mode
56 * - Cleand up cmdline parsing
57 * - Introduced --no-daemon, --pidfile options
58 * - Cleaned up signal handling:
59 * - Terminate cleanly on INT, TERM and ABRT
60 * - Schedule logfile for re-opening on HUP
61 * - Ignore CHLD and PIPE
62 * - Leave the rest with their default handlers
63 * - Uniform handler registration
64 * - Added usage() function
65 * - Played styleguide police
67 * Revision 1.66 2002/03/03 15:06:55 oes
68 * Re-enabled automatic config reloading
70 * Revision 1.65 2002/03/03 14:49:11 oes
71 * Fixed CLF logging: Now uses client's original HTTP request
73 * Revision 1.64 2002/03/03 09:18:03 joergs
74 * Made jumbjuster work on AmigaOS again.
76 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
77 * Clean up a little CRLF unpleasantness that suddenly appeared
79 * Revision 1.62 2002/02/20 23:17:23 jongfoster
80 * Detecting some out-of memory conditions and exiting with a log message.
82 * Revision 1.61 2002/01/17 21:01:52 jongfoster
83 * Moving all our URL and URL pattern parsing code to urlmatch.c.
85 * Revision 1.60 2001/12/30 14:07:32 steudten
86 * - Add signal handling (unix)
87 * - Add SIGHUP handler (unix)
88 * - Add creation of pidfile (unix)
89 * - Add action 'top' in rc file (RH)
90 * - Add entry 'SIGNALS' to manpage
91 * - Add exit message to logfile (unix)
93 * Revision 1.59 2001/12/13 14:07:18 oes
94 * Fixed Bug: 503 error page now sent OK
96 * Revision 1.58 2001/11/30 23:37:24 jongfoster
97 * Renaming the Win32 config file to config.txt - this is almost the
98 * same as the corresponding UNIX name "config"
100 * Revision 1.57 2001/11/16 00:47:43 jongfoster
101 * Changing the tty-disconnection code to use setsid().
103 * Revision 1.56 2001/11/13 20:20:54 jongfoster
104 * Tabs->spaces, fixing a bug with missing {} around an if()
106 * Revision 1.55 2001/11/13 20:14:53 jongfoster
107 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
109 * Revision 1.54 2001/11/07 00:03:14 steudten
110 * Give reliable return value if an error
111 * occurs not just 0 with new daemon mode.
113 * Revision 1.53 2001/11/05 21:41:43 steudten
114 * Add changes to be a real daemon just for unix os.
115 * (change cwd to /, detach from controlling tty, set
116 * process group and session leader to the own process.
118 * Add some fatal-error log message for failed malloc().
119 * Add '-d' if compiled with 'configure --with-debug' to
120 * enable debug output.
122 * Revision 1.52 2001/10/26 20:11:20 jongfoster
123 * Fixing type mismatch
125 * Revision 1.51 2001/10/26 17:38:28 oes
128 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
129 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
130 * threads to call select() simultaneously. So, it's time to do a real, live,
131 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
132 * (native). Both versions will work, but using __OS2__ offers multi-threading.
134 * Revision 1.49 2001/10/23 21:41:35 jongfoster
135 * Added call to initialize the (statically-allocated of course)
136 * "out of memory" CGI response.
138 * Revision 1.48 2001/10/10 19:56:46 jongfoster
139 * Moving some code that wasn't cookie-related out of an #ifdef
142 * Revision 1.47 2001/10/10 16:44:36 oes
143 * Added CONNECT destination port limitation check
145 * Revision 1.46 2001/10/08 15:17:41 oes
146 * Re-enabled SSL forwarding
148 * Revision 1.45 2001/10/07 15:42:11 oes
149 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
151 * Moved downgrading of the HTTP version from parse_http_request to
152 * chat(), since we can't decide if it is necessary before we have
153 * determined the actions for the URL. The HTTP command is now
154 * *always* re-built so the repairs need no longer be special-cased.
156 * filter_popups now gets a csp pointer so it can raise the new
157 * CSP_FLAG_MODIFIED flag.
161 * Added configurable size limit for the IOB. If the IOB grows so
162 * large that the next read would exceed the limit, the header
163 * is generated, and the header & unfiltered buffer are flushed
164 * to the client. Chat then continues in non-buffering,
165 * non-filtering body mode.
167 * Revision 1.44 2001/10/02 18:13:57 oes
170 * Revision 1.43 2001/10/02 15:32:13 oes
171 * Moved generation of hdr
173 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
174 * Cleaning up 2 compiler warnings on OS/2.
176 * Revision 1.41 2001/09/16 17:05:14 jongfoster
177 * Removing unused #include showarg.h
179 * Revision 1.40 2001/09/16 15:41:45 jongfoster
180 * Fixing signed/unsigned comparison warning.
182 * Revision 1.39 2001/09/16 13:21:27 jongfoster
183 * Changes to use new list functions.
185 * Revision 1.38 2001/09/16 13:01:46 jongfoster
186 * Removing redundant function call that zeroed zalloc()'d memory.
188 * Revision 1.37 2001/09/10 11:12:24 oes
189 * Deleted unused variable
191 * Revision 1.36 2001/09/10 10:56:15 oes
192 * Silenced compiler warnings
194 * Revision 1.35 2001/07/31 14:44:22 oes
195 * Deleted unused size parameter from filter_popups()
197 * Revision 1.34 2001/07/30 22:08:36 jongfoster
198 * Tidying up #defines:
199 * - All feature #defines are now of the form FEATURE_xxx
200 * - Permanently turned off WIN_GUI_EDIT
201 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
203 * Revision 1.33 2001/07/29 19:32:00 jongfoster
204 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
206 * Revision 1.32 2001/07/29 18:47:05 jongfoster
207 * Adding missing #include "loadcfg.h"
209 * Revision 1.31 2001/07/29 12:17:48 oes
210 * Applied pthread fix by Paul Lieverse
212 * Revision 1.30 2001/07/25 22:57:13 jongfoster
213 * __BEOS__ no longer overrides FEATURE_PTHREAD.
214 * This is because FEATURE_PTHREAD will soon be widely used, so I
215 * want to keep it simple.
217 * Revision 1.29 2001/07/24 12:47:06 oes
218 * Applied BeOS support update by Eugenia
220 * Revision 1.28 2001/07/23 13:26:12 oes
221 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
223 * Revision 1.27 2001/07/19 19:09:47 haroon
224 * - Added code to take care of the situation where while processing the first
225 * server response (which includes the server header), after finding the end
226 * of the headers we were not looking past the end of the headers for
227 * content modification. I enabled it for filter_popups.
228 * Someone else should look to see if other similar operations should be
229 * done to the discarded portion of the buffer.
231 * Note 2001/07/20: No, the other content modification mechanisms will process
232 * the whole iob later anyway. --oes
234 * Revision 1.26 2001/07/18 12:31:36 oes
237 * Revision 1.25 2001/07/15 19:43:49 jongfoster
238 * Supports POSIX threads.
239 * Also removed some unused #includes.
241 * Revision 1.24 2001/07/13 14:00:40 oes
242 * - Generic content modification scheme:
243 * Each feature has its own applicability flag that is set
244 * from csp->action->flags.
245 * Replaced the "filtering" int flag , by a function pointer
246 * "content_filter" to the function that will do the content
247 * modification. If it is != NULL, the document will be buffered
248 * and processed through *content_filter, which must set
249 * csp->content_length and return a modified copy of the body
250 * or return NULL (on failiure).
251 * - Changed csp->is_text to the more generic bitmap csp->content_type
252 * which can currently take the valued CT_TEXT or CT_GIF
254 * - Removed all #ifdef PCRS
256 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
257 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
258 * the `block_acl' call. This prevents a compilation error when the user
259 * does not wish to use the "ACL" feature.
261 * Revision 1.22 2001/06/29 21:45:41 oes
262 * Indentation, CRLF->LF, Tab-> Space
264 * Revision 1.21 2001/06/29 13:29:36 oes
265 * - Cleaned up, improved comments
266 * - Unified all possible interceptors (CGI,
267 * block, trust, fast_redirect) in one
268 * place, with one (CGI) answer generation
269 * mechansim. Much clearer now.
270 * - Removed the GIF image generation, which
271 * is now done in filters.c:block_url()
272 * - Made error conditions like domain lookup
273 * failiure or (various) problems while talking
274 * to the server use cgi.c:error_response()
275 * instead of generating HTML/HTTP in chat() (yuck!)
276 * - Removed logentry from cancelled commit
278 * Revision 1.20 2001/06/09 10:55:28 jongfoster
279 * Changing BUFSIZ ==> BUFFER_SIZE
281 * Revision 1.19 2001/06/07 23:12:52 jongfoster
282 * Replacing function pointer in struct gateway with a directly
283 * called function forwarded_connect().
284 * Replacing struct gateway with struct forward_spec
286 * Revision 1.18 2001/06/03 19:12:16 oes
287 * introduced new cgi handling
289 * Revision 1.17 2001/06/01 20:07:23 jongfoster
290 * Now uses action +image-blocker{} rather than config->tinygif
292 * Revision 1.16 2001/06/01 18:49:17 jongfoster
293 * Replaced "list_share" with "list" - the tiny memory gain was not
294 * worth the extra complexity.
296 * Revision 1.15 2001/05/31 21:24:47 jongfoster
297 * Changed "permission" to "action" throughout.
298 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
299 * Moved vanilla wafer check into chat(), since we must now
300 * decide whether or not to add it based on the URL.
302 * Revision 1.14 2001/05/29 20:14:01 joergs
303 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
306 * Revision 1.13 2001/05/29 09:50:24 jongfoster
307 * Unified blocklist/imagelist/permissionslist.
308 * File format is still under discussion, but the internal changes
311 * Also modified interceptor behaviour:
312 * - We now intercept all URLs beginning with one of the following
313 * prefixes (and *only* these prefixes):
315 * * http://ijbswa.sf.net/config/
316 * * http://ijbswa.sourceforge.net/config/
317 * - New interceptors "home page" - go to http://i.j.b/ to see it.
318 * - Internal changes so that intercepted and fast redirect pages
319 * are not replaced with an image.
320 * - Interceptors now have the option to send a binary page direct
321 * to the client. (i.e. ijb-send-banner uses this)
322 * - Implemented show-url-info interceptor. (Which is why I needed
323 * the above interceptors changes - a typical URL is
324 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
325 * The previous mechanism would not have intercepted that, and
326 * if it had been intercepted then it then it would have replaced
329 * Revision 1.12 2001/05/27 22:17:04 oes
331 * - re_process_buffer no longer writes the modified buffer
332 * to the client, which was very ugly. It now returns the
333 * buffer, which it is then written by chat.
335 * - content_length now adjusts the Content-Length: header
336 * for modified documents rather than crunch()ing it.
337 * (Length info in csp->content_length, which is 0 for
338 * unmodified documents)
340 * - For this to work, sed() is called twice when filtering.
342 * Revision 1.11 2001/05/26 17:27:53 jongfoster
343 * Added support for CLF and fixed LOG_LEVEL_LOG.
344 * Also did CRLF->LF fix of my previous patch.
346 * Revision 1.10 2001/05/26 15:26:15 jongfoster
347 * ACL feature now provides more security by immediately dropping
348 * connections from untrusted hosts.
350 * Revision 1.9 2001/05/26 00:28:36 jongfoster
351 * Automatic reloading of config file.
352 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
353 * Most of the global variables have been moved to a new
354 * struct configuration_spec, accessed through csp->config->globalname
355 * Most of the globals remaining are used by the Win32 GUI.
357 * Revision 1.8 2001/05/25 22:43:18 jongfoster
358 * Fixing minor memory leak and buffer overflow.
360 * Revision 1.7 2001/05/25 22:34:30 jongfoster
363 * Revision 1.6 2001/05/23 00:13:58 joergs
364 * AmigaOS support fixed.
366 * Revision 1.5 2001/05/22 18:46:04 oes
368 * - Enabled filtering banners by size rather than URL
369 * by adding patterns that replace all standard banner
370 * sizes with the "Junkbuster" gif to the re_filterfile
372 * - Enabled filtering WebBugs by providing a pattern
373 * which kills all 1x1 images
375 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
376 * which is selected by the (nonstandard and therefore
377 * capital) letter 'U' in the option string.
378 * It causes the quantifiers to be ungreedy by default.
379 * Appending a ? turns back to greedy (!).
381 * - Added a new interceptor ijb-send-banner, which
382 * sends back the "Junkbuster" gif. Without imagelist or
383 * MSIE detection support, or if tinygif = 1, or the
384 * URL isn't recognized as an imageurl, a lame HTML
385 * explanation is sent instead.
387 * - Added new feature, which permits blocking remote
388 * script redirects and firing back a local redirect
390 * The feature is conditionally compiled, i.e. it
391 * can be disabled with --disable-fast-redirects,
392 * plus it must be activated by a "fast-redirects"
393 * line in the config file, has its own log level
394 * and of course wants to be displayed by show-proxy-args
395 * Note: Boy, all the #ifdefs in 1001 locations and
396 * all the fumbling with configure.in and acconfig.h
397 * were *way* more work than the feature itself :-(
399 * - Because a generic redirect template was needed for
400 * this, tinygif = 3 now uses the same.
402 * - Moved GIFs, and other static HTTP response templates
407 * - Removed some >400 CRs again (Jon, you really worked
410 * Revision 1.4 2001/05/21 19:34:01 jongfoster
411 * Made failure to bind() a fatal error.
413 * Revision 1.3 2001/05/20 01:21:20 jongfoster
414 * Version 2.9.4 checkin.
415 * - Merged popupfile and cookiefile, and added control over PCRS
416 * filtering, in new "permissionsfile".
417 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
418 * file error you now get a message box (in the Win32 GUI) rather
419 * than the program exiting with no explanation.
420 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
422 * - Removed tabs from "config"
423 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
424 * - Bumped up version number.
426 * Revision 1.2 2001/05/17 22:34:44 oes
427 * - Added hint on GIF char array generation to jcc.c
428 * - Cleaned CRLF's from the sources and related files
429 * - Repaired logging for REF and FRC
431 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
432 * Initial import of version 2.9.3 source tree
435 *********************************************************************/
441 #include <sys/types.h>
448 #ifdef FEATURE_PTHREAD
450 #endif /* def FEATURE_PTHREAD */
453 # ifndef FEATURE_PTHREAD
454 # include <windows.h>
455 # include <process.h>
456 # endif /* ndef FEATURE_PTHREAD */
459 # ifndef _WIN_CONSOLE
461 # endif /* ndef _WIN_CONSOLE */
463 #else /* ifndef _WIN32 */
465 # if !defined (__OS2__)
467 # include <sys/wait.h>
468 # endif /* ndef __OS2__ */
469 # include <sys/time.h>
470 # include <sys/stat.h>
471 # include <sys/ioctl.h>
474 #include <sys/termios.h>
484 # include <socket.h> /* BeOS has select() for sockets only. */
485 # include <OS.h> /* declarations for threads and stuff. */
488 # if defined(__EMX__) || defined(__OS2__)
489 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
494 #define bzero(B,N) memset(B,0x00,n)
509 #include "killpopup.h"
510 #include "miscutil.h"
512 #include "jbsockets.h"
517 #include "urlmatch.h"
519 const char jcc_h_rcs[] = JCC_H_VERSION;
520 const char project_h_rcs[] = PROJECT_H_VERSION;
523 struct client_state clients[1];
524 struct file_list files[1];
526 #ifdef FEATURE_STATISTICS
527 int urls_read = 0; /* total nr of urls read inc rejected */
528 int urls_rejected = 0; /* total nr of urls rejected */
529 #endif /* def FEATURE_STATISTICS */
532 static void listen_loop(void);
533 static void chat(struct client_state *csp);
535 void serve(struct client_state *csp);
536 #else /* ifndef AMIGA */
537 static void serve(struct client_state *csp);
538 #endif /* def AMIGA */
541 static int32 server_thread(void *data);
542 #endif /* def __BEOS__ */
545 #define sleep(N) Sleep(((N) * 1000))
549 #define sleep(N) DosSleep(((N) * 100))
554 const char *pidfile = NULL;
555 int received_hup_signal = 0;
556 #endif /* defined unix */
558 /* The vanilla wafer. */
559 static const char VANILLA_WAFER[] =
560 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
561 "Do_not_send_me_any_copyrighted_information_other_than_the_"
562 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
563 "In_particular_do_not_send_me_any_cookies_that_"
564 "are_subject_to_a_claim_of_copyright_by_anybody._"
565 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
566 "(copyright_or_otherwise)_applying_to_any_cookie._";
569 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
570 /*********************************************************************
572 * Function : sig_handler
574 * Description : Signal handler for different signals.
575 * Exit gracefully on ABRT, TERM and INT
576 * or set a flag that will cause the errlog
577 * to be reopened by the main thread on HUP.
580 * 1 : the_signal - the signal cause this function to call
584 *********************************************************************/
585 static void sig_handler(int the_signal)
592 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
600 received_hup_signal = 1;
605 * We shouldn't be here, unless we catch signals
606 * in main() that we can't handle here!
608 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
616 /*********************************************************************
620 * Description : Once a connection to the client has been accepted,
621 * this function is called (via serve()) to handle the
622 * main business of the communication. When this
623 * function returns, the caller must close the client
627 * 1 : csp = Current client state (buffers, headers, etc...)
629 * Returns : On success, the number of bytes written are returned (zero
630 * indicates nothing was written). On error, -1 is returned,
631 * and errno is set appropriately. If count is zero and the
632 * file descriptor refers to a regular file, 0 will be
633 * returned without causing any other effect. For a special
634 * file, the results are not portable.
636 *********************************************************************/
637 static void chat(struct client_state *csp)
640 * This next lines are a little ugly, but they simplifies the if statements
641 * below. Basically if TOGGLE, then we want the if to test if the
642 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
643 * then we want the if to test for CSP_FLAG_FORCED , else we don't
645 #ifdef FEATURE_TOGGLE
646 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
647 #else /* ifndef FEATURE_TOGGLE */
648 # define IS_TOGGLED_ON_AND
649 #endif /* ndef FEATURE_TOGGLE */
650 #ifdef FEATURE_FORCE_LOAD
651 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
652 #else /* ifndef FEATURE_FORCE_LOAD */
653 # define IS_NOT_FORCED_AND
654 #endif /* def FEATURE_FORCE_LOAD */
656 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
658 char buf[BUFFER_SIZE];
661 int n, maxfd, server_body;
662 int ms_iis5_hack = 0;
664 const struct forward_spec * fwd;
665 struct http_request *http;
666 #ifdef FEATURE_KILL_POPUPS
667 int block_popups; /* bool, 1==will block popups */
668 int block_popups_now = 0; /* bool, 1==currently blocking popups */
669 #endif /* def FEATURE_KILL_POPUPS */
671 int pcrs_filter; /* bool, 1==will filter through pcrs */
672 int gif_deanimate; /* bool, 1==will deanimate gifs */
674 /* Function that does the content filtering for the current request */
675 char *(*content_filter)() = NULL;
677 /* Skeleton for HTTP response, if we should intercept the request */
678 struct http_response *rsp;
683 * Read the client's request. Note that since we're not using select() we
684 * could get blocked here if a client connected, then didn't say anything!
689 n = read_socket(csp->cfd, buf, sizeof(buf));
691 if (n <= 0) break; /* error! */
693 add_to_iob(csp, buf, n);
695 req = get_header(csp);
699 break; /* no HTTP request! */
704 continue; /* more to come! */
707 #ifdef FEATURE_FORCE_LOAD
708 /* If this request contains the FORCE_PREFIX,
709 * better get rid of it now and set the force flag --oes
712 if (strstr(req, FORCE_PREFIX))
714 strclean(req, FORCE_PREFIX);
715 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
716 csp->flags |= CSP_FLAG_FORCED;
719 #endif /* def FEATURE_FORCE_LOAD */
721 parse_http_request(req, http, csp);
726 if (http->cmd == NULL)
728 strcpy(buf, CHEADER);
729 write_socket(csp->cfd, buf, strlen(buf));
731 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
736 /* decide how to route the HTTP request */
738 if ((fwd = forward_url(http, csp)) == NULL)
740 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
741 /* Never get here - LOG_LEVEL_FATAL causes program exit */
744 /* build the http request to send to the server
745 * we have to do one of the following:
747 * create = use the original HTTP request to create a new
748 * HTTP request that has either the path component
749 * without the http://domainspec (w/path) or the
750 * full orininal URL (w/url)
751 * Note that the path and/or the HTTP version may
752 * have been altered by now.
754 * connect = Open a socket to the host:port of the server
755 * and short-circuit server and client socket.
757 * pass = Pass the request unchanged if forwarding a CONNECT
758 * request to a parent proxy. Note that we'll be sending
759 * the CFAIL message ourselves if connecting to the parent
760 * fails, but we won't send a CSUCCEED message if it works,
761 * since that would result in a double message (ours and the
762 * parent's). After sending the request to the parent, we simply
768 * +--------+--------+
770 * 0 | create | connect|
772 * Forwarding +--------+--------+
774 * 1 | create | pass |
776 * +--------+--------+
781 * Determine the actions for this URL
783 #ifdef FEATURE_TOGGLE
784 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
786 /* Most compatible set of actions (i.e. none) */
787 init_current_action(csp->action);
790 #endif /* ndef FEATURE_TOGGLE */
792 url_actions(http, csp);
797 * Check if a CONNECT request is allowable:
798 * In the absence of a +limit-connect action, allow only port 443.
799 * If there is an action, allow whatever matches the specificaton.
803 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
804 || (csp->action->flags & ACTION_LIMIT_CONNECT
805 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
807 strcpy(buf, CFORBIDDEN);
808 write_socket(csp->cfd, buf, strlen(buf));
810 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
811 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
819 * Downgrade http version from 1.1 to 1.0 if +downgrade
822 if ( (http->ssl == 0)
823 && (!strcmpic(http->ver, "HTTP/1.1"))
824 && (csp->action->flags & ACTION_DOWNGRADE))
827 http->ver = strdup("HTTP/1.0");
829 if (http->ver == NULL)
831 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
836 * Save a copy of the original request for logging
838 http->ocmd = strdup(http->cmd);
840 if (http->ocmd == NULL)
842 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
846 * (Re)build the HTTP request for non-SSL requests.
847 * If forwarding, use the whole URL, else, use only the path.
853 http->cmd = strdup(http->gpc);
854 string_append(&http->cmd, " ");
856 if (fwd->forward_host)
858 string_append(&http->cmd, http->url);
862 string_append(&http->cmd, http->path);
865 string_append(&http->cmd, " ");
866 string_append(&http->cmd, http->ver);
868 if (http->cmd == NULL)
870 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
873 enlist(csp->headers, http->cmd);
876 #ifdef FEATURE_COOKIE_JAR
878 * If we're logging cookies in a cookie jar, and the user has not
879 * supplied any wafers, and the user has not told us to suppress the
880 * vanilla wafer, then send the vanilla wafer.
882 if ((csp->config->jarfile != NULL)
883 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
884 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
886 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
888 #endif /* def FEATURE_COOKIE_JAR */
891 #ifdef FEATURE_KILL_POPUPS
892 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
893 #endif /* def FEATURE_KILL_POPUPS */
895 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
896 ((csp->action->flags & ACTION_FILTER) != 0);
898 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
900 /* grab the rest of the client's headers */
904 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
906 n = read_socket(csp->cfd, buf, sizeof(buf));
909 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
912 add_to_iob(csp, buf, n);
916 if (p == NULL) break;
918 enlist(csp->headers, p);
922 * We have a request. Now, check to see if we need to
923 * intercept it, i.e. If ..
927 /* a CGI call was detected and answered */
928 (NULL != (rsp = dispatch_cgi(csp)))
930 /* or we are enabled and... */
933 /* ..the request was blocked */
934 ( NULL != (rsp = block_url(csp)))
938 || ( NULL != (rsp = trust_url(csp)))
939 #endif /* def FEATURE_TRUST */
941 /* ..or a fast redirect kicked in */
942 #ifdef FEATURE_FAST_REDIRECTS
943 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
944 (NULL != (rsp = redirect_url(csp))))
945 #endif /* def FEATURE_FAST_REDIRECTS */
949 /* Write the answer to the client */
950 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
951 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
953 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
956 #ifdef FEATURE_STATISTICS
957 /* Count as a rejected request */
958 csp->flags |= CSP_FLAG_REJECTED;
959 #endif /* def FEATURE_STATISTICS */
961 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
962 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
963 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
965 /* Clean up and return */
966 free_http_response(rsp);
970 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
972 if (fwd->forward_host)
974 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
975 fwd->forward_host, fwd->forward_port, http->hostport);
979 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
982 /* here we connect to the server, gateway, or the forwarder */
984 csp->sfd = forwarded_connect(fwd, http, csp);
988 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
993 rsp = error_response(csp, "no-such-domain", errno);
995 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
996 csp->ip_addr_str, http->ocmd);
1000 rsp = error_response(csp, "connect-failed", errno);
1002 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1003 csp->ip_addr_str, http->ocmd);
1007 /* Write the answer to the client */
1010 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1011 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1013 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1017 free_http_response(rsp);
1021 log_error(LOG_LEVEL_CONNECT, "OK");
1023 hdr = sed(client_patterns, add_client_headers, csp);
1026 /* FIXME Should handle error properly */
1027 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1030 list_remove_all(csp->headers);
1032 if (fwd->forward_host || (http->ssl == 0))
1034 /* write the client's (modified) header to the server
1035 * (along with anything else that may be in the buffer)
1040 if ((write_socket(csp->sfd, hdr, n) != n)
1041 || (flush_socket(csp->sfd, csp ) < 0))
1043 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1046 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1047 csp->ip_addr_str, http->ocmd);
1049 rsp = error_response(csp, "connect-failed", errno);
1053 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1054 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1056 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1060 free_http_response(rsp);
1068 * We're running an SSL tunnel and we're not forwarding,
1069 * so just send the "connect succeeded" message to the
1070 * client, flush the rest, and get out of the way.
1072 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1073 csp->ip_addr_str, http->ocmd);
1075 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
1083 /* we're finished with the client's header */
1086 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1088 /* pass data between the client and server
1089 * until one or the other shuts down the connection.
1098 FD_SET(csp->cfd, &rfds);
1099 FD_SET(csp->sfd, &rfds);
1101 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1105 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1109 /* this is the body of the browser's request
1110 * just read it and write it.
1113 if (FD_ISSET(csp->cfd, &rfds))
1115 n = read_socket(csp->cfd, buf, sizeof(buf));
1119 break; /* "game over, man" */
1122 if (write_socket(csp->sfd, buf, n) != n)
1124 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1131 * The server wants to talk. It could be the header or the body.
1132 * If `hdr' is null, then it's the header otherwise it's the body.
1133 * FIXME: Does `hdr' really mean `host'? No.
1137 if (FD_ISSET(csp->sfd, &rfds))
1140 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1144 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1146 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1147 csp->ip_addr_str, http->ocmd);
1149 rsp = error_response(csp, "connect-failed", errno);
1153 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1154 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1156 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1160 free_http_response(rsp);
1164 /* Add a trailing zero. This lets filter_popups
1165 * use string operations.
1169 #ifdef FEATURE_KILL_POPUPS
1170 /* Filter the popups on this read. */
1171 if (block_popups_now)
1173 filter_popups(buf, csp);
1175 #endif /* def FEATURE_KILL_POPUPS */
1177 /* Normally, this would indicate that we've read
1178 * as much as the server has sent us and we can
1179 * close the client connection. However, Microsoft
1180 * in its wisdom has released IIS/5 with a bug that
1181 * prevents it from sending the trailing \r\n in
1182 * a 302 redirect header (and possibly other headers).
1183 * To work around this if we've haven't parsed
1184 * a full header we'll append a trailing \r\n
1185 * and see if this now generates a valid one.
1187 * This hack shouldn't have any impacts. If we've
1188 * already transmitted the header or if this is a
1189 * SSL connection, then we won't bother with this
1190 * hack. So we only work on partially received
1191 * headers. If we append a \r\n and this still
1192 * doesn't generate a valid header, then we won't
1193 * transmit anything to the client.
1198 if (server_body || http->ssl)
1201 * If we have been buffering up the document,
1202 * now is the time to apply content modification
1203 * and send the result to the client.
1208 * If the content filter fails, use the original
1209 * buffer and length.
1210 * (see p != NULL ? p : csp->iob->cur below)
1212 if (NULL == (p = (*content_filter)(csp)))
1214 csp->content_length = csp->iob->eod - csp->iob->cur;
1217 hdr = sed(server_patterns, add_server_headers, csp);
1220 /* FIXME Should handle error properly */
1221 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1226 if ((write_socket(csp->cfd, hdr, n) != n)
1227 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1229 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1239 break; /* "game over, man" */
1243 * This is NOT the body, so
1244 * Let's pretend the server just sent us a blank line.
1246 n = sprintf(buf, "\r\n");
1249 * Now, let the normal header parsing algorithm below do its
1250 * job. If it fails, we'll exit instead of continuing.
1257 * If this is an SSL connection or we're in the body
1258 * of the server document, just write it to the client,
1259 * unless we need to buffer the body for later content-filtering
1262 if (server_body || http->ssl)
1266 add_to_iob(csp, buf, n);
1269 * If the buffer limit will be reached on the next read,
1270 * switch to non-filtering mode, i.e. make & write the
1271 * header, flush the socket and get out of the way.
1273 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1275 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1277 hdr = sed(server_patterns, add_server_headers, csp);
1280 /* FIXME Should handle error properly */
1281 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1287 if (((write_socket(csp->cfd, hdr, n) != n)
1288 || (n = flush_socket(csp->cfd, csp) < 0)))
1290 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1299 content_filter = NULL;
1306 if (write_socket(csp->cfd, buf, n) != n)
1308 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1317 /* we're still looking for the end of the
1318 * server's header ... (does that make header
1319 * parsing an "out of body experience" ?
1322 /* buffer up the data we just read */
1323 add_to_iob(csp, buf, n);
1325 /* get header lines from the iob */
1327 while ((p = get_header(csp)))
1331 /* see following note */
1334 enlist(csp->headers, p);
1338 /* NOTE: there are no "empty" headers so
1339 * if the pointer `p' is not NULL we must
1340 * assume that we reached the end of the
1341 * buffer before we hit the end of the header.
1348 /* Well, we tried our MS IIS/5
1349 * hack and it didn't work.
1350 * The header is incomplete
1351 * and there isn't anything
1352 * we can do about it.
1358 /* Since we have to wait for
1359 * more from the server before
1360 * we can parse the headers
1361 * we just continue here.
1367 /* we have now received the entire header.
1368 * filter it and send the result to the client
1371 hdr = sed(server_patterns, add_server_headers, csp);
1374 /* FIXME Should handle error properly */
1375 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1380 /* write the server's (modified) header to
1381 * the client (along with anything else that
1382 * may be in the buffer)
1385 #ifdef FEATURE_KILL_POPUPS
1386 /* Start blocking popups if appropriate. */
1388 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1389 !http->ssl && /* We talk plaintext */
1390 block_popups) /* Policy allows */
1392 block_popups_now = 1;
1394 * Filter the part of the body that came in the same read
1395 * as the last headers:
1397 filter_popups(csp->iob->cur, csp);
1400 #endif /* def FEATURE_KILL_POPUPS */
1402 /* Buffer and pcrs filter this if appropriate. */
1404 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1405 !http->ssl && /* We talk plaintext */
1406 pcrs_filter) /* Policy allows */
1408 content_filter = pcrs_filter_response;
1411 /* Buffer and gif_deanimate this if appropriate. */
1413 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1414 !http->ssl && /* We talk plaintext */
1415 gif_deanimate) /* Policy allows */
1417 content_filter = gif_deanimate_response;
1422 * Only write if we're not buffering for content modification
1424 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1425 || (n = flush_socket(csp->cfd, csp) < 0)))
1427 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1429 /* the write failed, so don't bother
1430 * mentioning it to the client...
1431 * it probably can't hear us anyway.
1437 if(!content_filter) byte_count += n;
1439 /* we're finished with the server's header */
1444 /* If this was a MS IIS/5 hack then it means
1445 * the server has already closed the
1446 * connection. Nothing more to read. Time
1457 return; /* huh? we should never get here */
1460 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1461 csp->ip_addr_str, http->ocmd, byte_count);
1465 /*********************************************************************
1469 * Description : This is little more than chat. We only "serve" to
1470 * to close any socket that chat may have opened.
1473 * 1 : csp = Current client state (buffers, headers, etc...)
1477 *********************************************************************/
1479 void serve(struct client_state *csp)
1480 #else /* ifndef AMIGA */
1481 static void serve(struct client_state *csp)
1482 #endif /* def AMIGA */
1485 close_socket(csp->cfd);
1489 close_socket(csp->sfd);
1492 csp->flags &= ~CSP_FLAG_ACTIVE;
1498 /*********************************************************************
1500 * Function : server_thread
1502 * Description : We only exist to call `serve' in a threaded environment.
1505 * 1 : data = Current client state (buffers, headers, etc...)
1507 * Returns : Always 0.
1509 *********************************************************************/
1510 static int32 server_thread(void *data)
1512 serve((struct client_state *) data);
1519 /*********************************************************************
1523 * Description : Print usage info & exit.
1525 * Parameters : Pointer to argv[0] for identifying ourselves
1529 *********************************************************************/
1530 void usage(const char *myname)
1532 printf("JunkBuster proxy version " VERSION " (" HOME_PAGE_URL ")\n"
1533 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user] [configfile]\n"
1534 "Aborting.\n", myname);
1541 /*********************************************************************
1545 * Description : Load the config file and start the listen loop.
1546 * This function is a lot more *sane* with the `load_config'
1547 * and `listen_loop' functions; although it stills does
1548 * a *little* too much for my taste.
1551 * 1 : argc = Number of parameters (including $0).
1552 * 2 : argv = Array of (char *)'s to the parameters.
1554 * Returns : 1 if : can't open config file, unrecognized directive,
1555 * stats requested in multi-thread mode, can't open the
1556 * log file, can't open the jar file, listen port is invalid,
1557 * any load fails, and can't bind port.
1559 * Else main never returns, the process must be signaled
1560 * to terminate execution. Or, on Windows, use the
1561 * "File", "Exit" menu option.
1563 *********************************************************************/
1565 int real_main(int argc, const char *argv[])
1567 int main(int argc, const char *argv[])
1577 #if !defined(_WIN32)
1585 * Parse the command line arguments
1587 while (++argc_pos < argc)
1589 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1591 if (strcmp(argv[argc_pos], "--help") == 0)
1596 else if(strcmp(argv[argc_pos], "--version") == 0)
1598 printf("Junkbuster version " VERSION " (" HOME_PAGE_URL ")\n");
1602 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1606 #if !defined(__OS2__)
1607 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1609 if (++argc_pos == argc) usage(argv[0]);
1610 pidfile = strdup(argv[argc_pos]);
1613 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1615 if (++argc_pos == argc) usage(argv[0]);
1616 pw = getpwnam(argv[argc_pos]);
1620 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1623 #endif /* !defined(__OS2__) */
1625 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1627 configfile = argv[argc_pos];
1630 } /* -END- while (more arguments) */
1633 if ( *configfile != '/' )
1637 /* make config-filename absolute here */
1638 if ( !(basedir = getcwd( NULL, 1024 )))
1640 perror("get working dir failed");
1644 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1646 perror("malloc failed");
1649 strcpy( abs_file, basedir );
1650 strcat( abs_file, "/" );
1651 strcat( abs_file, configfile );
1652 configfile = abs_file;
1654 #endif /* defined unix */
1661 #elif defined(_WIN32)
1666 * Unix signal handling
1668 * Catch the abort, interrupt and terminate signals for a graceful exit
1669 * Catch the hangup signal so the errlog can be reopened.
1670 * Ignore the broken pipe and child signals
1671 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1673 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1676 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1677 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1679 for (idx = 0; catched_signals[idx] != 0; idx++)
1681 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1683 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1687 for (idx = 0; ignored_signals[idx] != 0; idx++)
1689 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1691 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1696 #else /* ifdef _WIN32 */
1697 # ifdef _WIN_CONSOLE
1699 * We *are* in a windows console app.
1700 * Print a verbose messages about FAQ's and such
1702 printf(win32_blurb);
1703 # endif /* def _WIN_CONSOLE */
1704 #endif /* def _WIN32 */
1707 /* Initialize the CGI subsystem */
1708 cgi_init_error_messages();
1711 * If runnig on unix and without the --nodaemon
1712 * option, become a daemon. I.e. fork, detach
1713 * from tty and get process group leadership
1726 if ( pid < 0 ) /* error */
1731 else if ( pid != 0 ) /* parent */
1736 * must check for errors
1737 * child died due to missing files aso
1740 wpid = waitpid( pid, &status, WNOHANG );
1749 /* Should be more portable, but not as well tested */
1754 #else /* ndef __FreeBSD__ */
1756 #endif /* ndef __FreeBSD__ */
1757 fd = open("/dev/tty", O_RDONLY);
1760 /* no error check here */
1761 ioctl( fd, TIOCNOTTY,0 );
1765 /* FIXME: should close stderr (fd 2) here too, but the test
1767 * and load config file is done in listen_loop() and puts
1768 * some messages on stderr there.
1775 } /* -END- if (!no_daemon) */
1778 * As soon as we have written the PID file, we can switch
1779 * to the user ID indicated by the --user option
1783 if (setuid(pw->pw_uid))
1785 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1789 #endif /* defined unix */
1799 /*********************************************************************
1801 * Function : bind_port_helper
1803 * Description : Bind the listen port. Handles logging, and aborts
1807 * 1 : config = Junkbuster configuration. Specifies port
1810 * Returns : Port that was opened.
1812 *********************************************************************/
1813 static int bind_port_helper(struct configuration_spec * config)
1817 if ( (config->haddr != NULL)
1818 && (config->haddr[0] == '1')
1819 && (config->haddr[1] == '2')
1820 && (config->haddr[2] == '7')
1821 && (config->haddr[3] == '.') )
1823 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1826 else if (config->haddr == NULL)
1828 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1833 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1834 config->hport, config->haddr);
1837 bfd = bind_port(config->haddr, config->hport);
1841 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1842 "- There may be another junkbuster or some other "
1843 "proxy running on port %d",
1844 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1845 config->hport, config->hport
1847 /* shouldn't get here */
1851 config->need_bind = 0;
1857 /*********************************************************************
1859 * Function : listen_loop
1861 * Description : bind the listen port and enter a "FOREVER" listening loop.
1867 *********************************************************************/
1868 static void listen_loop(void)
1870 struct client_state *csp = NULL;
1872 struct configuration_spec * config;
1874 config = load_config();
1876 bfd = bind_port_helper(config);
1880 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1881 while (waitpid(-1, NULL, WNOHANG) > 0)
1883 /* zombie children */
1885 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1888 * Free data that was used by died threads
1894 * Re-open the errlog after HUP signal
1896 if (received_hup_signal)
1898 init_error_log(Argv[0], config->logfile, config->debug);
1899 received_hup_signal = 0;
1903 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1905 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1909 csp->flags |= CSP_FLAG_ACTIVE;
1912 csp->config = config = load_config();
1914 if ( config->need_bind )
1917 * Since we were listening to the "old port", we will not see
1918 * a "listen" param change until the next IJB request. So, at
1919 * least 1 more request must be made for us to find the new
1920 * setting. I am simply closing the old socket and binding the
1923 * Which-ever is correct, we will serve 1 more page via the
1924 * old settings. This should probably be a "show-proxy-args"
1925 * request. This should not be a so common of an operation
1926 * that this will hurt people's feelings.
1931 bfd = bind_port_helper(config);
1934 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1936 if (!accept_connection(csp, bfd))
1938 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1951 log_error(LOG_LEVEL_CONNECT, "OK");
1954 #ifdef FEATURE_TOGGLE
1957 csp->flags |= CSP_FLAG_TOGGLED_ON;
1959 #endif /* def FEATURE_TOGGLE */
1961 if (run_loader(csp))
1963 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1964 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1968 if (block_acl(NULL,csp))
1970 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1971 close_socket(csp->cfd);
1975 #endif /* def FEATURE_ACL */
1977 /* add it to the list of clients */
1978 csp->next = clients->next;
1979 clients->next = csp;
1981 if (config->multi_threaded)
1985 /* this is a switch () statment in the C preprocessor - ugh */
1986 #undef SELECTED_ONE_OPTION
1988 /* Use Pthreads in preference to native code */
1989 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1990 #define SELECTED_ONE_OPTION
1992 pthread_t the_thread;
1993 pthread_attr_t attrs;
1995 pthread_attr_init(&attrs);
1996 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1997 child_id = (pthread_create(&the_thread, &attrs,
1998 (void*)serve, csp) ? -1 : 0);
1999 pthread_attr_destroy(&attrs);
2003 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2004 #define SELECTED_ONE_OPTION
2005 child_id = _beginthread(
2011 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2012 #define SELECTED_ONE_OPTION
2013 child_id = _beginthread(
2020 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2021 #define SELECTED_ONE_OPTION
2023 thread_id tid = spawn_thread
2024 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2026 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2028 child_id = (int) tid;
2037 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2038 #define SELECTED_ONE_OPTION
2039 csp->cfd = ReleaseSocket(csp->cfd, -1);
2040 if((child_id = (int)CreateNewProcTags(
2041 NP_Entry, (ULONG)server_thread,
2042 NP_Output, Output(),
2043 NP_CloseOutput, FALSE,
2044 NP_Name, (ULONG)"junkbuster child",
2045 NP_StackSize, 200*1024,
2049 ((struct Task *)child_id)->tc_UserData = csp;
2050 Signal((struct Task *)child_id, SIGF_SINGLE);
2055 #if !defined(SELECTED_ONE_OPTION)
2058 /* This block is only needed when using fork().
2059 * When using threads, the server thread was
2060 * created and run by the call to _beginthread().
2062 if (child_id == 0) /* child */
2068 else if (child_id > 0) /* parent */
2070 /* in a fork()'d environment, the parent's
2071 * copy of the client socket and the CSP
2075 #if !defined(_WIN32) && defined(__CYGWIN__)
2077 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2078 close_socket(csp->cfd);
2079 csp->flags &= ~CSP_FLAG_ACTIVE;
2083 #undef SELECTED_ONE_OPTION
2084 /* end of cpp switch () */
2086 if (child_id < 0) /* failed */
2088 char buf[BUFFER_SIZE];
2090 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2092 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
2094 write_socket(csp->cfd, buf, strlen(buf));
2095 close_socket(csp->cfd);
2096 csp->flags &= ~CSP_FLAG_ACTIVE;