1 const char jcc_rcs[] = "$Id: jcc.c,v 1.70 2002/03/05 04:52:42 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.70 2002/03/05 04:52:42 oes
37 * Deleted non-errlog debugging code
39 * Revision 1.69 2002/03/04 23:50:00 jongfoster
40 * Splitting off bind_port() call into bind_port_helper(), with
43 * Revision 1.68 2002/03/04 20:17:32 oes
46 * Revision 1.67 2002/03/04 18:18:57 oes
47 * - Removed _DEBUG mode
48 * - Cleand up cmdline parsing
49 * - Introduced --no-daemon, --pidfile options
50 * - Cleaned up signal handling:
51 * - Terminate cleanly on INT, TERM and ABRT
52 * - Schedule logfile for re-opening on HUP
53 * - Ignore CHLD and PIPE
54 * - Leave the rest with their default handlers
55 * - Uniform handler registration
56 * - Added usage() function
57 * - Played styleguide police
59 * Revision 1.66 2002/03/03 15:06:55 oes
60 * Re-enabled automatic config reloading
62 * Revision 1.65 2002/03/03 14:49:11 oes
63 * Fixed CLF logging: Now uses client's original HTTP request
65 * Revision 1.64 2002/03/03 09:18:03 joergs
66 * Made jumbjuster work on AmigaOS again.
68 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
69 * Clean up a little CRLF unpleasantness that suddenly appeared
71 * Revision 1.62 2002/02/20 23:17:23 jongfoster
72 * Detecting some out-of memory conditions and exiting with a log message.
74 * Revision 1.61 2002/01/17 21:01:52 jongfoster
75 * Moving all our URL and URL pattern parsing code to urlmatch.c.
77 * Revision 1.60 2001/12/30 14:07:32 steudten
78 * - Add signal handling (unix)
79 * - Add SIGHUP handler (unix)
80 * - Add creation of pidfile (unix)
81 * - Add action 'top' in rc file (RH)
82 * - Add entry 'SIGNALS' to manpage
83 * - Add exit message to logfile (unix)
85 * Revision 1.59 2001/12/13 14:07:18 oes
86 * Fixed Bug: 503 error page now sent OK
88 * Revision 1.58 2001/11/30 23:37:24 jongfoster
89 * Renaming the Win32 config file to config.txt - this is almost the
90 * same as the corresponding UNIX name "config"
92 * Revision 1.57 2001/11/16 00:47:43 jongfoster
93 * Changing the tty-disconnection code to use setsid().
95 * Revision 1.56 2001/11/13 20:20:54 jongfoster
96 * Tabs->spaces, fixing a bug with missing {} around an if()
98 * Revision 1.55 2001/11/13 20:14:53 jongfoster
99 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
101 * Revision 1.54 2001/11/07 00:03:14 steudten
102 * Give reliable return value if an error
103 * occurs not just 0 with new daemon mode.
105 * Revision 1.53 2001/11/05 21:41:43 steudten
106 * Add changes to be a real daemon just for unix os.
107 * (change cwd to /, detach from controlling tty, set
108 * process group and session leader to the own process.
110 * Add some fatal-error log message for failed malloc().
111 * Add '-d' if compiled with 'configure --with-debug' to
112 * enable debug output.
114 * Revision 1.52 2001/10/26 20:11:20 jongfoster
115 * Fixing type mismatch
117 * Revision 1.51 2001/10/26 17:38:28 oes
120 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
121 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
122 * threads to call select() simultaneously. So, it's time to do a real, live,
123 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
124 * (native). Both versions will work, but using __OS2__ offers multi-threading.
126 * Revision 1.49 2001/10/23 21:41:35 jongfoster
127 * Added call to initialize the (statically-allocated of course)
128 * "out of memory" CGI response.
130 * Revision 1.48 2001/10/10 19:56:46 jongfoster
131 * Moving some code that wasn't cookie-related out of an #ifdef
134 * Revision 1.47 2001/10/10 16:44:36 oes
135 * Added CONNECT destination port limitation check
137 * Revision 1.46 2001/10/08 15:17:41 oes
138 * Re-enabled SSL forwarding
140 * Revision 1.45 2001/10/07 15:42:11 oes
141 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
143 * Moved downgrading of the HTTP version from parse_http_request to
144 * chat(), since we can't decide if it is necessary before we have
145 * determined the actions for the URL. The HTTP command is now
146 * *always* re-built so the repairs need no longer be special-cased.
148 * filter_popups now gets a csp pointer so it can raise the new
149 * CSP_FLAG_MODIFIED flag.
153 * Added configurable size limit for the IOB. If the IOB grows so
154 * large that the next read would exceed the limit, the header
155 * is generated, and the header & unfiltered buffer are flushed
156 * to the client. Chat then continues in non-buffering,
157 * non-filtering body mode.
159 * Revision 1.44 2001/10/02 18:13:57 oes
162 * Revision 1.43 2001/10/02 15:32:13 oes
163 * Moved generation of hdr
165 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
166 * Cleaning up 2 compiler warnings on OS/2.
168 * Revision 1.41 2001/09/16 17:05:14 jongfoster
169 * Removing unused #include showarg.h
171 * Revision 1.40 2001/09/16 15:41:45 jongfoster
172 * Fixing signed/unsigned comparison warning.
174 * Revision 1.39 2001/09/16 13:21:27 jongfoster
175 * Changes to use new list functions.
177 * Revision 1.38 2001/09/16 13:01:46 jongfoster
178 * Removing redundant function call that zeroed zalloc()'d memory.
180 * Revision 1.37 2001/09/10 11:12:24 oes
181 * Deleted unused variable
183 * Revision 1.36 2001/09/10 10:56:15 oes
184 * Silenced compiler warnings
186 * Revision 1.35 2001/07/31 14:44:22 oes
187 * Deleted unused size parameter from filter_popups()
189 * Revision 1.34 2001/07/30 22:08:36 jongfoster
190 * Tidying up #defines:
191 * - All feature #defines are now of the form FEATURE_xxx
192 * - Permanently turned off WIN_GUI_EDIT
193 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
195 * Revision 1.33 2001/07/29 19:32:00 jongfoster
196 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
198 * Revision 1.32 2001/07/29 18:47:05 jongfoster
199 * Adding missing #include "loadcfg.h"
201 * Revision 1.31 2001/07/29 12:17:48 oes
202 * Applied pthread fix by Paul Lieverse
204 * Revision 1.30 2001/07/25 22:57:13 jongfoster
205 * __BEOS__ no longer overrides FEATURE_PTHREAD.
206 * This is because FEATURE_PTHREAD will soon be widely used, so I
207 * want to keep it simple.
209 * Revision 1.29 2001/07/24 12:47:06 oes
210 * Applied BeOS support update by Eugenia
212 * Revision 1.28 2001/07/23 13:26:12 oes
213 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
215 * Revision 1.27 2001/07/19 19:09:47 haroon
216 * - Added code to take care of the situation where while processing the first
217 * server response (which includes the server header), after finding the end
218 * of the headers we were not looking past the end of the headers for
219 * content modification. I enabled it for filter_popups.
220 * Someone else should look to see if other similar operations should be
221 * done to the discarded portion of the buffer.
223 * Note 2001/07/20: No, the other content modification mechanisms will process
224 * the whole iob later anyway. --oes
226 * Revision 1.26 2001/07/18 12:31:36 oes
229 * Revision 1.25 2001/07/15 19:43:49 jongfoster
230 * Supports POSIX threads.
231 * Also removed some unused #includes.
233 * Revision 1.24 2001/07/13 14:00:40 oes
234 * - Generic content modification scheme:
235 * Each feature has its own applicability flag that is set
236 * from csp->action->flags.
237 * Replaced the "filtering" int flag , by a function pointer
238 * "content_filter" to the function that will do the content
239 * modification. If it is != NULL, the document will be buffered
240 * and processed through *content_filter, which must set
241 * csp->content_length and return a modified copy of the body
242 * or return NULL (on failiure).
243 * - Changed csp->is_text to the more generic bitmap csp->content_type
244 * which can currently take the valued CT_TEXT or CT_GIF
246 * - Removed all #ifdef PCRS
248 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
249 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
250 * the `block_acl' call. This prevents a compilation error when the user
251 * does not wish to use the "ACL" feature.
253 * Revision 1.22 2001/06/29 21:45:41 oes
254 * Indentation, CRLF->LF, Tab-> Space
256 * Revision 1.21 2001/06/29 13:29:36 oes
257 * - Cleaned up, improved comments
258 * - Unified all possible interceptors (CGI,
259 * block, trust, fast_redirect) in one
260 * place, with one (CGI) answer generation
261 * mechansim. Much clearer now.
262 * - Removed the GIF image generation, which
263 * is now done in filters.c:block_url()
264 * - Made error conditions like domain lookup
265 * failiure or (various) problems while talking
266 * to the server use cgi.c:error_response()
267 * instead of generating HTML/HTTP in chat() (yuck!)
268 * - Removed logentry from cancelled commit
270 * Revision 1.20 2001/06/09 10:55:28 jongfoster
271 * Changing BUFSIZ ==> BUFFER_SIZE
273 * Revision 1.19 2001/06/07 23:12:52 jongfoster
274 * Replacing function pointer in struct gateway with a directly
275 * called function forwarded_connect().
276 * Replacing struct gateway with struct forward_spec
278 * Revision 1.18 2001/06/03 19:12:16 oes
279 * introduced new cgi handling
281 * Revision 1.17 2001/06/01 20:07:23 jongfoster
282 * Now uses action +image-blocker{} rather than config->tinygif
284 * Revision 1.16 2001/06/01 18:49:17 jongfoster
285 * Replaced "list_share" with "list" - the tiny memory gain was not
286 * worth the extra complexity.
288 * Revision 1.15 2001/05/31 21:24:47 jongfoster
289 * Changed "permission" to "action" throughout.
290 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
291 * Moved vanilla wafer check into chat(), since we must now
292 * decide whether or not to add it based on the URL.
294 * Revision 1.14 2001/05/29 20:14:01 joergs
295 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
298 * Revision 1.13 2001/05/29 09:50:24 jongfoster
299 * Unified blocklist/imagelist/permissionslist.
300 * File format is still under discussion, but the internal changes
303 * Also modified interceptor behaviour:
304 * - We now intercept all URLs beginning with one of the following
305 * prefixes (and *only* these prefixes):
307 * * http://ijbswa.sf.net/config/
308 * * http://ijbswa.sourceforge.net/config/
309 * - New interceptors "home page" - go to http://i.j.b/ to see it.
310 * - Internal changes so that intercepted and fast redirect pages
311 * are not replaced with an image.
312 * - Interceptors now have the option to send a binary page direct
313 * to the client. (i.e. ijb-send-banner uses this)
314 * - Implemented show-url-info interceptor. (Which is why I needed
315 * the above interceptors changes - a typical URL is
316 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
317 * The previous mechanism would not have intercepted that, and
318 * if it had been intercepted then it then it would have replaced
321 * Revision 1.12 2001/05/27 22:17:04 oes
323 * - re_process_buffer no longer writes the modified buffer
324 * to the client, which was very ugly. It now returns the
325 * buffer, which it is then written by chat.
327 * - content_length now adjusts the Content-Length: header
328 * for modified documents rather than crunch()ing it.
329 * (Length info in csp->content_length, which is 0 for
330 * unmodified documents)
332 * - For this to work, sed() is called twice when filtering.
334 * Revision 1.11 2001/05/26 17:27:53 jongfoster
335 * Added support for CLF and fixed LOG_LEVEL_LOG.
336 * Also did CRLF->LF fix of my previous patch.
338 * Revision 1.10 2001/05/26 15:26:15 jongfoster
339 * ACL feature now provides more security by immediately dropping
340 * connections from untrusted hosts.
342 * Revision 1.9 2001/05/26 00:28:36 jongfoster
343 * Automatic reloading of config file.
344 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
345 * Most of the global variables have been moved to a new
346 * struct configuration_spec, accessed through csp->config->globalname
347 * Most of the globals remaining are used by the Win32 GUI.
349 * Revision 1.8 2001/05/25 22:43:18 jongfoster
350 * Fixing minor memory leak and buffer overflow.
352 * Revision 1.7 2001/05/25 22:34:30 jongfoster
355 * Revision 1.6 2001/05/23 00:13:58 joergs
356 * AmigaOS support fixed.
358 * Revision 1.5 2001/05/22 18:46:04 oes
360 * - Enabled filtering banners by size rather than URL
361 * by adding patterns that replace all standard banner
362 * sizes with the "Junkbuster" gif to the re_filterfile
364 * - Enabled filtering WebBugs by providing a pattern
365 * which kills all 1x1 images
367 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
368 * which is selected by the (nonstandard and therefore
369 * capital) letter 'U' in the option string.
370 * It causes the quantifiers to be ungreedy by default.
371 * Appending a ? turns back to greedy (!).
373 * - Added a new interceptor ijb-send-banner, which
374 * sends back the "Junkbuster" gif. Without imagelist or
375 * MSIE detection support, or if tinygif = 1, or the
376 * URL isn't recognized as an imageurl, a lame HTML
377 * explanation is sent instead.
379 * - Added new feature, which permits blocking remote
380 * script redirects and firing back a local redirect
382 * The feature is conditionally compiled, i.e. it
383 * can be disabled with --disable-fast-redirects,
384 * plus it must be activated by a "fast-redirects"
385 * line in the config file, has its own log level
386 * and of course wants to be displayed by show-proxy-args
387 * Note: Boy, all the #ifdefs in 1001 locations and
388 * all the fumbling with configure.in and acconfig.h
389 * were *way* more work than the feature itself :-(
391 * - Because a generic redirect template was needed for
392 * this, tinygif = 3 now uses the same.
394 * - Moved GIFs, and other static HTTP response templates
399 * - Removed some >400 CRs again (Jon, you really worked
402 * Revision 1.4 2001/05/21 19:34:01 jongfoster
403 * Made failure to bind() a fatal error.
405 * Revision 1.3 2001/05/20 01:21:20 jongfoster
406 * Version 2.9.4 checkin.
407 * - Merged popupfile and cookiefile, and added control over PCRS
408 * filtering, in new "permissionsfile".
409 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
410 * file error you now get a message box (in the Win32 GUI) rather
411 * than the program exiting with no explanation.
412 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
414 * - Removed tabs from "config"
415 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
416 * - Bumped up version number.
418 * Revision 1.2 2001/05/17 22:34:44 oes
419 * - Added hint on GIF char array generation to jcc.c
420 * - Cleaned CRLF's from the sources and related files
421 * - Repaired logging for REF and FRC
423 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
424 * Initial import of version 2.9.3 source tree
427 *********************************************************************/
433 #include <sys/types.h>
440 #ifdef FEATURE_PTHREAD
442 #endif /* def FEATURE_PTHREAD */
445 # ifndef FEATURE_PTHREAD
446 # include <windows.h>
447 # include <process.h>
448 # endif /* ndef FEATURE_PTHREAD */
451 # ifndef _WIN_CONSOLE
453 # endif /* ndef _WIN_CONSOLE */
455 #else /* ifndef _WIN32 */
457 # if !defined (__OS2__)
459 # include <sys/wait.h>
460 # endif /* ndef __OS2__ */
461 # include <sys/time.h>
462 # include <sys/stat.h>
463 # include <sys/ioctl.h>
466 #include <sys/termios.h>
476 # include <socket.h> /* BeOS has select() for sockets only. */
477 # include <OS.h> /* declarations for threads and stuff. */
480 # if defined(__EMX__) || defined(__OS2__)
481 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
486 #define bzero(B,N) memset(B,0x00,n)
501 #include "killpopup.h"
502 #include "miscutil.h"
504 #include "jbsockets.h"
509 #include "urlmatch.h"
511 const char jcc_h_rcs[] = JCC_H_VERSION;
512 const char project_h_rcs[] = PROJECT_H_VERSION;
515 struct client_state clients[1];
516 struct file_list files[1];
518 #ifdef FEATURE_STATISTICS
519 int urls_read = 0; /* total nr of urls read inc rejected */
520 int urls_rejected = 0; /* total nr of urls rejected */
521 #endif /* def FEATURE_STATISTICS */
524 static void listen_loop(void);
525 static void chat(struct client_state *csp);
527 void serve(struct client_state *csp);
528 #else /* ifndef AMIGA */
529 static void serve(struct client_state *csp);
530 #endif /* def AMIGA */
533 static int32 server_thread(void *data);
534 #endif /* def __BEOS__ */
537 #define sleep(N) Sleep(((N) * 1000))
541 #define sleep(N) DosSleep(((N) * 100))
546 const char *pidfile = NULL;
547 int received_hup_signal = 0;
548 #endif /* defined unix */
550 /* The vanilla wafer. */
551 static const char VANILLA_WAFER[] =
552 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
553 "Do_not_send_me_any_copyrighted_information_other_than_the_"
554 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
555 "In_particular_do_not_send_me_any_cookies_that_"
556 "are_subject_to_a_claim_of_copyright_by_anybody._"
557 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
558 "(copyright_or_otherwise)_applying_to_any_cookie._";
561 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
562 /*********************************************************************
564 * Function : sig_handler
566 * Description : Signal handler for different signals.
567 * Exit gracefully on ABRT, TERM and INT
568 * or set a flag that will cause the errlog
569 * to be reopened by the main thread on HUP.
572 * 1 : the_signal - the signal cause this function to call
576 *********************************************************************/
577 static void sig_handler(int the_signal)
584 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
592 received_hup_signal = 1;
597 * We shouldn't be here, unless we catch signals
598 * in main() that we can't handle here!
600 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
608 /*********************************************************************
612 * Description : Once a connection to the client has been accepted,
613 * this function is called (via serve()) to handle the
614 * main business of the communication. When this
615 * function returns, the caller must close the client
619 * 1 : csp = Current client state (buffers, headers, etc...)
621 * Returns : On success, the number of bytes written are returned (zero
622 * indicates nothing was written). On error, -1 is returned,
623 * and errno is set appropriately. If count is zero and the
624 * file descriptor refers to a regular file, 0 will be
625 * returned without causing any other effect. For a special
626 * file, the results are not portable.
628 *********************************************************************/
629 static void chat(struct client_state *csp)
632 * This next lines are a little ugly, but they simplifies the if statements
633 * below. Basically if TOGGLE, then we want the if to test if the
634 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
635 * then we want the if to test for CSP_FLAG_FORCED , else we don't
637 #ifdef FEATURE_TOGGLE
638 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
639 #else /* ifndef FEATURE_TOGGLE */
640 # define IS_TOGGLED_ON_AND
641 #endif /* ndef FEATURE_TOGGLE */
642 #ifdef FEATURE_FORCE_LOAD
643 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
644 #else /* ifndef FEATURE_FORCE_LOAD */
645 # define IS_NOT_FORCED_AND
646 #endif /* def FEATURE_FORCE_LOAD */
648 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
650 char buf[BUFFER_SIZE];
653 int n, maxfd, server_body;
654 int ms_iis5_hack = 0;
656 const struct forward_spec * fwd;
657 struct http_request *http;
658 #ifdef FEATURE_KILL_POPUPS
659 int block_popups; /* bool, 1==will block popups */
660 int block_popups_now = 0; /* bool, 1==currently blocking popups */
661 #endif /* def FEATURE_KILL_POPUPS */
663 int pcrs_filter; /* bool, 1==will filter through pcrs */
664 int gif_deanimate; /* bool, 1==will deanimate gifs */
666 /* Function that does the content filtering for the current request */
667 char *(*content_filter)() = NULL;
669 /* Skeleton for HTTP response, if we should intercept the request */
670 struct http_response *rsp;
675 * Read the client's request. Note that since we're not using select() we
676 * could get blocked here if a client connected, then didn't say anything!
681 n = read_socket(csp->cfd, buf, sizeof(buf));
683 if (n <= 0) break; /* error! */
685 add_to_iob(csp, buf, n);
687 req = get_header(csp);
691 break; /* no HTTP request! */
696 continue; /* more to come! */
699 #ifdef FEATURE_FORCE_LOAD
700 /* If this request contains the FORCE_PREFIX,
701 * better get rid of it now and set the force flag --oes
704 if (strstr(req, FORCE_PREFIX))
706 strclean(req, FORCE_PREFIX);
707 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
708 csp->flags |= CSP_FLAG_FORCED;
711 #endif /* def FEATURE_FORCE_LOAD */
713 parse_http_request(req, http, csp);
718 if (http->cmd == NULL)
720 strcpy(buf, CHEADER);
721 write_socket(csp->cfd, buf, strlen(buf));
723 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
728 /* decide how to route the HTTP request */
730 if ((fwd = forward_url(http, csp)) == NULL)
732 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
733 /* Never get here - LOG_LEVEL_FATAL causes program exit */
736 /* build the http request to send to the server
737 * we have to do one of the following:
739 * create = use the original HTTP request to create a new
740 * HTTP request that has either the path component
741 * without the http://domainspec (w/path) or the
742 * full orininal URL (w/url)
743 * Note that the path and/or the HTTP version may
744 * have been altered by now.
746 * connect = Open a socket to the host:port of the server
747 * and short-circuit server and client socket.
749 * pass = Pass the request unchanged if forwarding a CONNECT
750 * request to a parent proxy. Note that we'll be sending
751 * the CFAIL message ourselves if connecting to the parent
752 * fails, but we won't send a CSUCCEED message if it works,
753 * since that would result in a double message (ours and the
754 * parent's). After sending the request to the parent, we simply
760 * +--------+--------+
762 * 0 | create | connect|
764 * Forwarding +--------+--------+
766 * 1 | create | pass |
768 * +--------+--------+
773 * Determine the actions for this URL
775 #ifdef FEATURE_TOGGLE
776 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
778 /* Most compatible set of actions (i.e. none) */
779 init_current_action(csp->action);
782 #endif /* ndef FEATURE_TOGGLE */
784 url_actions(http, csp);
789 * Check if a CONNECT request is allowable:
790 * In the absence of a +limit-connect action, allow only port 443.
791 * If there is an action, allow whatever matches the specificaton.
795 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
796 || (csp->action->flags & ACTION_LIMIT_CONNECT
797 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
799 strcpy(buf, CFORBIDDEN);
800 write_socket(csp->cfd, buf, strlen(buf));
802 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
803 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
811 * Downgrade http version from 1.1 to 1.0 if +downgrade
814 if ( (http->ssl == 0)
815 && (!strcmpic(http->ver, "HTTP/1.1"))
816 && (csp->action->flags & ACTION_DOWNGRADE))
819 http->ver = strdup("HTTP/1.0");
821 if (http->ver == NULL)
823 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
828 * Save a copy of the original request for logging
830 http->ocmd = strdup(http->cmd);
832 if (http->ocmd == NULL)
834 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
838 * (Re)build the HTTP request for non-SSL requests.
839 * If forwarding, use the whole URL, else, use only the path.
845 http->cmd = strdup(http->gpc);
846 string_append(&http->cmd, " ");
848 if (fwd->forward_host)
850 string_append(&http->cmd, http->url);
854 string_append(&http->cmd, http->path);
857 string_append(&http->cmd, " ");
858 string_append(&http->cmd, http->ver);
860 if (http->cmd == NULL)
862 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
865 enlist(csp->headers, http->cmd);
868 #ifdef FEATURE_COOKIE_JAR
870 * If we're logging cookies in a cookie jar, and the user has not
871 * supplied any wafers, and the user has not told us to suppress the
872 * vanilla wafer, then send the vanilla wafer.
874 if ((csp->config->jarfile != NULL)
875 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
876 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
878 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
880 #endif /* def FEATURE_COOKIE_JAR */
883 #ifdef FEATURE_KILL_POPUPS
884 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
885 #endif /* def FEATURE_KILL_POPUPS */
887 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
888 ((csp->action->flags & ACTION_FILTER) != 0);
890 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
892 /* grab the rest of the client's headers */
896 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
898 n = read_socket(csp->cfd, buf, sizeof(buf));
901 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
904 add_to_iob(csp, buf, n);
908 if (p == NULL) break;
910 enlist(csp->headers, p);
914 * We have a request. Now, check to see if we need to
915 * intercept it, i.e. If ..
919 /* a CGI call was detected and answered */
920 (NULL != (rsp = dispatch_cgi(csp)))
922 /* or we are enabled and... */
925 /* ..the request was blocked */
926 ( NULL != (rsp = block_url(csp)))
930 || ( NULL != (rsp = trust_url(csp)))
931 #endif /* def FEATURE_TRUST */
933 /* ..or a fast redirect kicked in */
934 #ifdef FEATURE_FAST_REDIRECTS
935 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
936 (NULL != (rsp = redirect_url(csp))))
937 #endif /* def FEATURE_FAST_REDIRECTS */
941 /* Write the answer to the client */
942 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
943 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
945 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
948 #ifdef FEATURE_STATISTICS
949 /* Count as a rejected request */
950 csp->flags |= CSP_FLAG_REJECTED;
951 #endif /* def FEATURE_STATISTICS */
953 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
954 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
955 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
957 /* Clean up and return */
958 free_http_response(rsp);
962 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
964 if (fwd->forward_host)
966 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
967 fwd->forward_host, fwd->forward_port, http->hostport);
971 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
974 /* here we connect to the server, gateway, or the forwarder */
976 csp->sfd = forwarded_connect(fwd, http, csp);
980 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
985 rsp = error_response(csp, "no-such-domain", errno);
987 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
988 csp->ip_addr_str, http->ocmd);
992 rsp = error_response(csp, "connect-failed", errno);
994 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
995 csp->ip_addr_str, http->ocmd);
999 /* Write the answer to the client */
1002 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1003 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1005 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1009 free_http_response(rsp);
1013 log_error(LOG_LEVEL_CONNECT, "OK");
1015 hdr = sed(client_patterns, add_client_headers, csp);
1018 /* FIXME Should handle error properly */
1019 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1022 list_remove_all(csp->headers);
1024 if (fwd->forward_host || (http->ssl == 0))
1026 /* write the client's (modified) header to the server
1027 * (along with anything else that may be in the buffer)
1032 if ((write_socket(csp->sfd, hdr, n) != n)
1033 || (flush_socket(csp->sfd, csp ) < 0))
1035 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1038 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1039 csp->ip_addr_str, http->ocmd);
1041 rsp = error_response(csp, "connect-failed", errno);
1045 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1046 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1048 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1052 free_http_response(rsp);
1060 * We're running an SSL tunnel and we're not forwarding,
1061 * so just send the "connect succeeded" message to the
1062 * client, flush the rest, and get out of the way.
1064 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1065 csp->ip_addr_str, http->ocmd);
1067 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
1075 /* we're finished with the client's header */
1078 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1080 /* pass data between the client and server
1081 * until one or the other shuts down the connection.
1090 FD_SET(csp->cfd, &rfds);
1091 FD_SET(csp->sfd, &rfds);
1093 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1097 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1101 /* this is the body of the browser's request
1102 * just read it and write it.
1105 if (FD_ISSET(csp->cfd, &rfds))
1107 n = read_socket(csp->cfd, buf, sizeof(buf));
1111 break; /* "game over, man" */
1114 if (write_socket(csp->sfd, buf, n) != n)
1116 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1123 * The server wants to talk. It could be the header or the body.
1124 * If `hdr' is null, then it's the header otherwise it's the body.
1125 * FIXME: Does `hdr' really mean `host'? No.
1129 if (FD_ISSET(csp->sfd, &rfds))
1132 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1136 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1138 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1139 csp->ip_addr_str, http->ocmd);
1141 rsp = error_response(csp, "connect-failed", errno);
1145 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1146 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1148 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1152 free_http_response(rsp);
1156 /* Add a trailing zero. This lets filter_popups
1157 * use string operations.
1161 #ifdef FEATURE_KILL_POPUPS
1162 /* Filter the popups on this read. */
1163 if (block_popups_now)
1165 filter_popups(buf, csp);
1167 #endif /* def FEATURE_KILL_POPUPS */
1169 /* Normally, this would indicate that we've read
1170 * as much as the server has sent us and we can
1171 * close the client connection. However, Microsoft
1172 * in its wisdom has released IIS/5 with a bug that
1173 * prevents it from sending the trailing \r\n in
1174 * a 302 redirect header (and possibly other headers).
1175 * To work around this if we've haven't parsed
1176 * a full header we'll append a trailing \r\n
1177 * and see if this now generates a valid one.
1179 * This hack shouldn't have any impacts. If we've
1180 * already transmitted the header or if this is a
1181 * SSL connection, then we won't bother with this
1182 * hack. So we only work on partially received
1183 * headers. If we append a \r\n and this still
1184 * doesn't generate a valid header, then we won't
1185 * transmit anything to the client.
1190 if (server_body || http->ssl)
1193 * If we have been buffering up the document,
1194 * now is the time to apply content modification
1195 * and send the result to the client.
1200 * If the content filter fails, use the original
1201 * buffer and length.
1202 * (see p != NULL ? p : csp->iob->cur below)
1204 if (NULL == (p = (*content_filter)(csp)))
1206 csp->content_length = csp->iob->eod - csp->iob->cur;
1209 hdr = sed(server_patterns, add_server_headers, csp);
1212 /* FIXME Should handle error properly */
1213 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1218 if ((write_socket(csp->cfd, hdr, n) != n)
1219 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1221 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1231 break; /* "game over, man" */
1235 * This is NOT the body, so
1236 * Let's pretend the server just sent us a blank line.
1238 n = sprintf(buf, "\r\n");
1241 * Now, let the normal header parsing algorithm below do its
1242 * job. If it fails, we'll exit instead of continuing.
1249 * If this is an SSL connection or we're in the body
1250 * of the server document, just write it to the client,
1251 * unless we need to buffer the body for later content-filtering
1254 if (server_body || http->ssl)
1258 add_to_iob(csp, buf, n);
1261 * If the buffer limit will be reached on the next read,
1262 * switch to non-filtering mode, i.e. make & write the
1263 * header, flush the socket and get out of the way.
1265 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1267 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1269 hdr = sed(server_patterns, add_server_headers, csp);
1272 /* FIXME Should handle error properly */
1273 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1279 if (((write_socket(csp->cfd, hdr, n) != n)
1280 || (n = flush_socket(csp->cfd, csp) < 0)))
1282 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1291 content_filter = NULL;
1298 if (write_socket(csp->cfd, buf, n) != n)
1300 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1309 /* we're still looking for the end of the
1310 * server's header ... (does that make header
1311 * parsing an "out of body experience" ?
1314 /* buffer up the data we just read */
1315 add_to_iob(csp, buf, n);
1317 /* get header lines from the iob */
1319 while ((p = get_header(csp)))
1323 /* see following note */
1326 enlist(csp->headers, p);
1330 /* NOTE: there are no "empty" headers so
1331 * if the pointer `p' is not NULL we must
1332 * assume that we reached the end of the
1333 * buffer before we hit the end of the header.
1340 /* Well, we tried our MS IIS/5
1341 * hack and it didn't work.
1342 * The header is incomplete
1343 * and there isn't anything
1344 * we can do about it.
1350 /* Since we have to wait for
1351 * more from the server before
1352 * we can parse the headers
1353 * we just continue here.
1359 /* we have now received the entire header.
1360 * filter it and send the result to the client
1363 hdr = sed(server_patterns, add_server_headers, csp);
1366 /* FIXME Should handle error properly */
1367 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1372 /* write the server's (modified) header to
1373 * the client (along with anything else that
1374 * may be in the buffer)
1377 #ifdef FEATURE_KILL_POPUPS
1378 /* Start blocking popups if appropriate. */
1380 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1381 !http->ssl && /* We talk plaintext */
1382 block_popups) /* Policy allows */
1384 block_popups_now = 1;
1386 * Filter the part of the body that came in the same read
1387 * as the last headers:
1389 filter_popups(csp->iob->cur, csp);
1392 #endif /* def FEATURE_KILL_POPUPS */
1394 /* Buffer and pcrs filter this if appropriate. */
1396 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1397 !http->ssl && /* We talk plaintext */
1398 pcrs_filter) /* Policy allows */
1400 content_filter = pcrs_filter_response;
1403 /* Buffer and gif_deanimate this if appropriate. */
1405 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1406 !http->ssl && /* We talk plaintext */
1407 gif_deanimate) /* Policy allows */
1409 content_filter = gif_deanimate_response;
1414 * Only write if we're not buffering for content modification
1416 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1417 || (n = flush_socket(csp->cfd, csp) < 0)))
1419 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1421 /* the write failed, so don't bother
1422 * mentioning it to the client...
1423 * it probably can't hear us anyway.
1429 if(!content_filter) byte_count += n;
1431 /* we're finished with the server's header */
1436 /* If this was a MS IIS/5 hack then it means
1437 * the server has already closed the
1438 * connection. Nothing more to read. Time
1449 return; /* huh? we should never get here */
1452 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1453 csp->ip_addr_str, http->ocmd, byte_count);
1457 /*********************************************************************
1461 * Description : This is little more than chat. We only "serve" to
1462 * to close any socket that chat may have opened.
1465 * 1 : csp = Current client state (buffers, headers, etc...)
1469 *********************************************************************/
1471 void serve(struct client_state *csp)
1472 #else /* ifndef AMIGA */
1473 static void serve(struct client_state *csp)
1474 #endif /* def AMIGA */
1477 close_socket(csp->cfd);
1481 close_socket(csp->sfd);
1484 csp->flags &= ~CSP_FLAG_ACTIVE;
1490 /*********************************************************************
1492 * Function : server_thread
1494 * Description : We only exist to call `serve' in a threaded environment.
1497 * 1 : data = Current client state (buffers, headers, etc...)
1499 * Returns : Always 0.
1501 *********************************************************************/
1502 static int32 server_thread(void *data)
1504 serve((struct client_state *) data);
1511 /*********************************************************************
1515 * Description : Print usage info & exit.
1517 * Parameters : Pointer to argv[0] for identifying ourselves
1521 *********************************************************************/
1522 void usage(const char *myname)
1524 printf("JunkBuster proxy version " VERSION " (" HOME_PAGE_URL ")\n"
1525 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user] [configfile]\n"
1526 "Aborting.\n", myname);
1533 /*********************************************************************
1537 * Description : Load the config file and start the listen loop.
1538 * This function is a lot more *sane* with the `load_config'
1539 * and `listen_loop' functions; although it stills does
1540 * a *little* too much for my taste.
1543 * 1 : argc = Number of parameters (including $0).
1544 * 2 : argv = Array of (char *)'s to the parameters.
1546 * Returns : 1 if : can't open config file, unrecognized directive,
1547 * stats requested in multi-thread mode, can't open the
1548 * log file, can't open the jar file, listen port is invalid,
1549 * any load fails, and can't bind port.
1551 * Else main never returns, the process must be signaled
1552 * to terminate execution. Or, on Windows, use the
1553 * "File", "Exit" menu option.
1555 *********************************************************************/
1557 int real_main(int argc, const char *argv[])
1559 int main(int argc, const char *argv[])
1569 #if !defined(_WIN32)
1577 * Parse the command line arguments
1579 while (++argc_pos < argc)
1581 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1583 if (strcmp(argv[argc_pos], "--help") == 0)
1588 else if(strcmp(argv[argc_pos], "--version") == 0)
1590 printf("Junkbuster version " VERSION " (" HOME_PAGE_URL ")\n");
1594 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1599 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1601 if (++argc_pos == argc) usage(argv[0]);
1602 pidfile = strdup(argv[argc_pos]);
1605 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1607 if (++argc_pos == argc) usage(argv[0]);
1608 pw = getpwnam(argv[argc_pos]);
1612 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1616 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1618 configfile = argv[argc_pos];
1621 } /* -END- while (more arguments) */
1624 if ( *configfile != '/' )
1628 /* make config-filename absolute here */
1629 if ( !(basedir = getcwd( NULL, 1024 )))
1631 perror("get working dir failed");
1635 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1637 perror("malloc failed");
1640 strcpy( abs_file, basedir );
1641 strcat( abs_file, "/" );
1642 strcat( abs_file, configfile );
1643 configfile = abs_file;
1645 #endif /* defined unix */
1652 #elif defined(_WIN32)
1657 * Unix signal handling
1659 * Catch the abort, interrupt and terminate signals for a graceful exit
1660 * Catch the hangup signal so the errlog can be reopened.
1661 * Ignore the broken pipe and child signals
1662 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1664 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1667 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1668 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1670 for (idx = 0; catched_signals[idx] != 0; idx++)
1672 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1674 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1678 for (idx = 0; ignored_signals[idx] != 0; idx++)
1680 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1682 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1687 #else /* ifdef _WIN32 */
1688 # ifdef _WIN_CONSOLE
1690 * We *are* in a windows console app.
1691 * Print a verbose messages about FAQ's and such
1693 printf(win32_blurb);
1694 # endif /* def _WIN_CONSOLE */
1695 #endif /* def _WIN32 */
1698 /* Initialize the CGI subsystem */
1699 cgi_init_error_messages();
1702 * If runnig on unix and without the --nodaemon
1703 * option, become a daemon. I.e. fork, detach
1704 * from tty and get process group leadership
1717 if ( pid < 0 ) /* error */
1722 else if ( pid != 0 ) /* parent */
1727 * must check for errors
1728 * child died due to missing files aso
1731 wpid = waitpid( pid, &status, WNOHANG );
1740 /* Should be more portable, but not as well tested */
1745 #else /* ndef __FreeBSD__ */
1747 #endif /* ndef __FreeBSD__ */
1748 fd = open("/dev/tty", O_RDONLY);
1751 /* no error check here */
1752 ioctl( fd, TIOCNOTTY,0 );
1756 /* FIXME: should close stderr (fd 2) here too, but the test
1758 * and load config file is done in listen_loop() and puts
1759 * some messages on stderr there.
1766 } /* -END- if (!no_daemon) */
1769 * As soon as we have written the PID file, we can switch
1770 * to the user ID indicated by the --user option
1774 if (setuid(pw->pw_uid))
1776 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1780 #endif /* defined unix */
1790 /*********************************************************************
1792 * Function : bind_port_helper
1794 * Description : Bind the listen port. Handles logging, and aborts
1798 * 1 : config = Junkbuster configuration. Specifies port
1801 * Returns : Port that was opened.
1803 *********************************************************************/
1804 static int bind_port_helper(struct configuration_spec * config)
1808 if ( (config->haddr != NULL)
1809 && (config->haddr[0] == '1')
1810 && (config->haddr[1] == '2')
1811 && (config->haddr[2] == '7')
1812 && (config->haddr[3] == '.') )
1814 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1817 else if (config->haddr == NULL)
1819 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1824 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1825 config->hport, config->haddr);
1828 bfd = bind_port(config->haddr, config->hport);
1832 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1833 "- There may be another junkbuster or some other "
1834 "proxy running on port %d",
1835 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1836 config->hport, config->hport
1838 /* shouldn't get here */
1842 config->need_bind = 0;
1848 /*********************************************************************
1850 * Function : listen_loop
1852 * Description : bind the listen port and enter a "FOREVER" listening loop.
1858 *********************************************************************/
1859 static void listen_loop(void)
1861 struct client_state *csp = NULL;
1863 struct configuration_spec * config;
1865 config = load_config();
1867 bfd = bind_port_helper(config);
1871 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1872 while (waitpid(-1, NULL, WNOHANG) > 0)
1874 /* zombie children */
1876 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1879 * Free data that was used by died threads
1885 * Re-open the errlog after HUP signal
1887 if (received_hup_signal)
1889 init_error_log(Argv[0], config->logfile, config->debug);
1890 received_hup_signal = 0;
1894 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1896 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1900 csp->flags |= CSP_FLAG_ACTIVE;
1903 csp->config = config = load_config();
1905 if ( config->need_bind )
1908 * Since we were listening to the "old port", we will not see
1909 * a "listen" param change until the next IJB request. So, at
1910 * least 1 more request must be made for us to find the new
1911 * setting. I am simply closing the old socket and binding the
1914 * Which-ever is correct, we will serve 1 more page via the
1915 * old settings. This should probably be a "show-proxy-args"
1916 * request. This should not be a so common of an operation
1917 * that this will hurt people's feelings.
1922 bfd = bind_port_helper(config);
1925 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1927 if (!accept_connection(csp, bfd))
1929 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1942 log_error(LOG_LEVEL_CONNECT, "OK");
1945 #ifdef FEATURE_TOGGLE
1948 csp->flags |= CSP_FLAG_TOGGLED_ON;
1950 #endif /* def FEATURE_TOGGLE */
1952 if (run_loader(csp))
1954 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1955 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1959 if (block_acl(NULL,csp))
1961 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1962 close_socket(csp->cfd);
1966 #endif /* def FEATURE_ACL */
1968 /* add it to the list of clients */
1969 csp->next = clients->next;
1970 clients->next = csp;
1972 if (config->multi_threaded)
1976 /* this is a switch () statment in the C preprocessor - ugh */
1977 #undef SELECTED_ONE_OPTION
1979 /* Use Pthreads in preference to native code */
1980 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1981 #define SELECTED_ONE_OPTION
1983 pthread_t the_thread;
1984 pthread_attr_t attrs;
1986 pthread_attr_init(&attrs);
1987 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1988 child_id = (pthread_create(&the_thread, &attrs,
1989 (void*)serve, csp) ? -1 : 0);
1990 pthread_attr_destroy(&attrs);
1994 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1995 #define SELECTED_ONE_OPTION
1996 child_id = _beginthread(
2002 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2003 #define SELECTED_ONE_OPTION
2004 child_id = _beginthread(
2011 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2012 #define SELECTED_ONE_OPTION
2014 thread_id tid = spawn_thread
2015 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2017 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2019 child_id = (int) tid;
2028 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2029 #define SELECTED_ONE_OPTION
2030 csp->cfd = ReleaseSocket(csp->cfd, -1);
2031 if((child_id = (int)CreateNewProcTags(
2032 NP_Entry, (ULONG)server_thread,
2033 NP_Output, Output(),
2034 NP_CloseOutput, FALSE,
2035 NP_Name, (ULONG)"junkbuster child",
2036 NP_StackSize, 200*1024,
2040 ((struct Task *)child_id)->tc_UserData = csp;
2041 Signal((struct Task *)child_id, SIGF_SINGLE);
2046 #if !defined(SELECTED_ONE_OPTION)
2049 /* This block is only needed when using fork().
2050 * When using threads, the server thread was
2051 * created and run by the call to _beginthread().
2053 if (child_id == 0) /* child */
2059 else if (child_id > 0) /* parent */
2061 /* in a fork()'d environment, the parent's
2062 * copy of the client socket and the CSP
2066 #if !defined(_WIN32) && defined(__CYGWIN__)
2068 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2069 close_socket(csp->cfd);
2070 csp->flags &= ~CSP_FLAG_ACTIVE;
2074 #undef SELECTED_ONE_OPTION
2075 /* end of cpp switch () */
2077 if (child_id < 0) /* failed */
2079 char buf[BUFFER_SIZE];
2081 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2083 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
2085 write_socket(csp->cfd, buf, strlen(buf));
2086 close_socket(csp->cfd);
2087 csp->flags &= ~CSP_FLAG_ACTIVE;