1 const char jcc_rcs[] = "$Id: jcc.c,v 1.74 2002/03/06 00:49:31 jongfoster Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001 the SourceForge
10 * 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.74 2002/03/06 00:49:31 jongfoster
37 * Fixing warning on Windows
38 * Making #ifdefs that refer to the same variable consistently
39 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
41 * Revision 1.73 2002/03/05 23:57:30 hal9
42 * Stray character 's' on line 1618 was breaking build.
44 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
45 * - Re-enable OS/2 building after new parms were added
46 * - Fix false out of memory report when resolving CGI templates when no IP
47 * address is available of failed attempt (a la no such domain)
49 * Revision 1.71 2002/03/05 18:13:56 oes
52 * Revision 1.70 2002/03/05 04:52:42 oes
53 * Deleted non-errlog debugging code
55 * Revision 1.69 2002/03/04 23:50:00 jongfoster
56 * Splitting off bind_port() call into bind_port_helper(), with
59 * Revision 1.68 2002/03/04 20:17:32 oes
62 * Revision 1.67 2002/03/04 18:18:57 oes
63 * - Removed _DEBUG mode
64 * - Cleand up cmdline parsing
65 * - Introduced --no-daemon, --pidfile options
66 * - Cleaned up signal handling:
67 * - Terminate cleanly on INT, TERM and ABRT
68 * - Schedule logfile for re-opening on HUP
69 * - Ignore CHLD and PIPE
70 * - Leave the rest with their default handlers
71 * - Uniform handler registration
72 * - Added usage() function
73 * - Played styleguide police
75 * Revision 1.66 2002/03/03 15:06:55 oes
76 * Re-enabled automatic config reloading
78 * Revision 1.65 2002/03/03 14:49:11 oes
79 * Fixed CLF logging: Now uses client's original HTTP request
81 * Revision 1.64 2002/03/03 09:18:03 joergs
82 * Made jumbjuster work on AmigaOS again.
84 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
85 * Clean up a little CRLF unpleasantness that suddenly appeared
87 * Revision 1.62 2002/02/20 23:17:23 jongfoster
88 * Detecting some out-of memory conditions and exiting with a log message.
90 * Revision 1.61 2002/01/17 21:01:52 jongfoster
91 * Moving all our URL and URL pattern parsing code to urlmatch.c.
93 * Revision 1.60 2001/12/30 14:07:32 steudten
94 * - Add signal handling (unix)
95 * - Add SIGHUP handler (unix)
96 * - Add creation of pidfile (unix)
97 * - Add action 'top' in rc file (RH)
98 * - Add entry 'SIGNALS' to manpage
99 * - Add exit message to logfile (unix)
101 * Revision 1.59 2001/12/13 14:07:18 oes
102 * Fixed Bug: 503 error page now sent OK
104 * Revision 1.58 2001/11/30 23:37:24 jongfoster
105 * Renaming the Win32 config file to config.txt - this is almost the
106 * same as the corresponding UNIX name "config"
108 * Revision 1.57 2001/11/16 00:47:43 jongfoster
109 * Changing the tty-disconnection code to use setsid().
111 * Revision 1.56 2001/11/13 20:20:54 jongfoster
112 * Tabs->spaces, fixing a bug with missing {} around an if()
114 * Revision 1.55 2001/11/13 20:14:53 jongfoster
115 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
117 * Revision 1.54 2001/11/07 00:03:14 steudten
118 * Give reliable return value if an error
119 * occurs not just 0 with new daemon mode.
121 * Revision 1.53 2001/11/05 21:41:43 steudten
122 * Add changes to be a real daemon just for unix os.
123 * (change cwd to /, detach from controlling tty, set
124 * process group and session leader to the own process.
126 * Add some fatal-error log message for failed malloc().
127 * Add '-d' if compiled with 'configure --with-debug' to
128 * enable debug output.
130 * Revision 1.52 2001/10/26 20:11:20 jongfoster
131 * Fixing type mismatch
133 * Revision 1.51 2001/10/26 17:38:28 oes
136 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
137 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
138 * threads to call select() simultaneously. So, it's time to do a real, live,
139 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
140 * (native). Both versions will work, but using __OS2__ offers multi-threading.
142 * Revision 1.49 2001/10/23 21:41:35 jongfoster
143 * Added call to initialize the (statically-allocated of course)
144 * "out of memory" CGI response.
146 * Revision 1.48 2001/10/10 19:56:46 jongfoster
147 * Moving some code that wasn't cookie-related out of an #ifdef
150 * Revision 1.47 2001/10/10 16:44:36 oes
151 * Added CONNECT destination port limitation check
153 * Revision 1.46 2001/10/08 15:17:41 oes
154 * Re-enabled SSL forwarding
156 * Revision 1.45 2001/10/07 15:42:11 oes
157 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
159 * Moved downgrading of the HTTP version from parse_http_request to
160 * chat(), since we can't decide if it is necessary before we have
161 * determined the actions for the URL. The HTTP command is now
162 * *always* re-built so the repairs need no longer be special-cased.
164 * filter_popups now gets a csp pointer so it can raise the new
165 * CSP_FLAG_MODIFIED flag.
169 * Added configurable size limit for the IOB. If the IOB grows so
170 * large that the next read would exceed the limit, the header
171 * is generated, and the header & unfiltered buffer are flushed
172 * to the client. Chat then continues in non-buffering,
173 * non-filtering body mode.
175 * Revision 1.44 2001/10/02 18:13:57 oes
178 * Revision 1.43 2001/10/02 15:32:13 oes
179 * Moved generation of hdr
181 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
182 * Cleaning up 2 compiler warnings on OS/2.
184 * Revision 1.41 2001/09/16 17:05:14 jongfoster
185 * Removing unused #include showarg.h
187 * Revision 1.40 2001/09/16 15:41:45 jongfoster
188 * Fixing signed/unsigned comparison warning.
190 * Revision 1.39 2001/09/16 13:21:27 jongfoster
191 * Changes to use new list functions.
193 * Revision 1.38 2001/09/16 13:01:46 jongfoster
194 * Removing redundant function call that zeroed zalloc()'d memory.
196 * Revision 1.37 2001/09/10 11:12:24 oes
197 * Deleted unused variable
199 * Revision 1.36 2001/09/10 10:56:15 oes
200 * Silenced compiler warnings
202 * Revision 1.35 2001/07/31 14:44:22 oes
203 * Deleted unused size parameter from filter_popups()
205 * Revision 1.34 2001/07/30 22:08:36 jongfoster
206 * Tidying up #defines:
207 * - All feature #defines are now of the form FEATURE_xxx
208 * - Permanently turned off WIN_GUI_EDIT
209 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
211 * Revision 1.33 2001/07/29 19:32:00 jongfoster
212 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
214 * Revision 1.32 2001/07/29 18:47:05 jongfoster
215 * Adding missing #include "loadcfg.h"
217 * Revision 1.31 2001/07/29 12:17:48 oes
218 * Applied pthread fix by Paul Lieverse
220 * Revision 1.30 2001/07/25 22:57:13 jongfoster
221 * __BEOS__ no longer overrides FEATURE_PTHREAD.
222 * This is because FEATURE_PTHREAD will soon be widely used, so I
223 * want to keep it simple.
225 * Revision 1.29 2001/07/24 12:47:06 oes
226 * Applied BeOS support update by Eugenia
228 * Revision 1.28 2001/07/23 13:26:12 oes
229 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
231 * Revision 1.27 2001/07/19 19:09:47 haroon
232 * - Added code to take care of the situation where while processing the first
233 * server response (which includes the server header), after finding the end
234 * of the headers we were not looking past the end of the headers for
235 * content modification. I enabled it for filter_popups.
236 * Someone else should look to see if other similar operations should be
237 * done to the discarded portion of the buffer.
239 * Note 2001/07/20: No, the other content modification mechanisms will process
240 * the whole iob later anyway. --oes
242 * Revision 1.26 2001/07/18 12:31:36 oes
245 * Revision 1.25 2001/07/15 19:43:49 jongfoster
246 * Supports POSIX threads.
247 * Also removed some unused #includes.
249 * Revision 1.24 2001/07/13 14:00:40 oes
250 * - Generic content modification scheme:
251 * Each feature has its own applicability flag that is set
252 * from csp->action->flags.
253 * Replaced the "filtering" int flag , by a function pointer
254 * "content_filter" to the function that will do the content
255 * modification. If it is != NULL, the document will be buffered
256 * and processed through *content_filter, which must set
257 * csp->content_length and return a modified copy of the body
258 * or return NULL (on failiure).
259 * - Changed csp->is_text to the more generic bitmap csp->content_type
260 * which can currently take the valued CT_TEXT or CT_GIF
262 * - Removed all #ifdef PCRS
264 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
265 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
266 * the `block_acl' call. This prevents a compilation error when the user
267 * does not wish to use the "ACL" feature.
269 * Revision 1.22 2001/06/29 21:45:41 oes
270 * Indentation, CRLF->LF, Tab-> Space
272 * Revision 1.21 2001/06/29 13:29:36 oes
273 * - Cleaned up, improved comments
274 * - Unified all possible interceptors (CGI,
275 * block, trust, fast_redirect) in one
276 * place, with one (CGI) answer generation
277 * mechansim. Much clearer now.
278 * - Removed the GIF image generation, which
279 * is now done in filters.c:block_url()
280 * - Made error conditions like domain lookup
281 * failiure or (various) problems while talking
282 * to the server use cgi.c:error_response()
283 * instead of generating HTML/HTTP in chat() (yuck!)
284 * - Removed logentry from cancelled commit
286 * Revision 1.20 2001/06/09 10:55:28 jongfoster
287 * Changing BUFSIZ ==> BUFFER_SIZE
289 * Revision 1.19 2001/06/07 23:12:52 jongfoster
290 * Replacing function pointer in struct gateway with a directly
291 * called function forwarded_connect().
292 * Replacing struct gateway with struct forward_spec
294 * Revision 1.18 2001/06/03 19:12:16 oes
295 * introduced new cgi handling
297 * Revision 1.17 2001/06/01 20:07:23 jongfoster
298 * Now uses action +image-blocker{} rather than config->tinygif
300 * Revision 1.16 2001/06/01 18:49:17 jongfoster
301 * Replaced "list_share" with "list" - the tiny memory gain was not
302 * worth the extra complexity.
304 * Revision 1.15 2001/05/31 21:24:47 jongfoster
305 * Changed "permission" to "action" throughout.
306 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
307 * Moved vanilla wafer check into chat(), since we must now
308 * decide whether or not to add it based on the URL.
310 * Revision 1.14 2001/05/29 20:14:01 joergs
311 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
314 * Revision 1.13 2001/05/29 09:50:24 jongfoster
315 * Unified blocklist/imagelist/permissionslist.
316 * File format is still under discussion, but the internal changes
319 * Also modified interceptor behaviour:
320 * - We now intercept all URLs beginning with one of the following
321 * prefixes (and *only* these prefixes):
323 * * http://ijbswa.sf.net/config/
324 * * http://ijbswa.sourceforge.net/config/
325 * - New interceptors "home page" - go to http://i.j.b/ to see it.
326 * - Internal changes so that intercepted and fast redirect pages
327 * are not replaced with an image.
328 * - Interceptors now have the option to send a binary page direct
329 * to the client. (i.e. ijb-send-banner uses this)
330 * - Implemented show-url-info interceptor. (Which is why I needed
331 * the above interceptors changes - a typical URL is
332 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
333 * The previous mechanism would not have intercepted that, and
334 * if it had been intercepted then it then it would have replaced
337 * Revision 1.12 2001/05/27 22:17:04 oes
339 * - re_process_buffer no longer writes the modified buffer
340 * to the client, which was very ugly. It now returns the
341 * buffer, which it is then written by chat.
343 * - content_length now adjusts the Content-Length: header
344 * for modified documents rather than crunch()ing it.
345 * (Length info in csp->content_length, which is 0 for
346 * unmodified documents)
348 * - For this to work, sed() is called twice when filtering.
350 * Revision 1.11 2001/05/26 17:27:53 jongfoster
351 * Added support for CLF and fixed LOG_LEVEL_LOG.
352 * Also did CRLF->LF fix of my previous patch.
354 * Revision 1.10 2001/05/26 15:26:15 jongfoster
355 * ACL feature now provides more security by immediately dropping
356 * connections from untrusted hosts.
358 * Revision 1.9 2001/05/26 00:28:36 jongfoster
359 * Automatic reloading of config file.
360 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
361 * Most of the global variables have been moved to a new
362 * struct configuration_spec, accessed through csp->config->globalname
363 * Most of the globals remaining are used by the Win32 GUI.
365 * Revision 1.8 2001/05/25 22:43:18 jongfoster
366 * Fixing minor memory leak and buffer overflow.
368 * Revision 1.7 2001/05/25 22:34:30 jongfoster
371 * Revision 1.6 2001/05/23 00:13:58 joergs
372 * AmigaOS support fixed.
374 * Revision 1.5 2001/05/22 18:46:04 oes
376 * - Enabled filtering banners by size rather than URL
377 * by adding patterns that replace all standard banner
378 * sizes with the "Junkbuster" gif to the re_filterfile
380 * - Enabled filtering WebBugs by providing a pattern
381 * which kills all 1x1 images
383 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
384 * which is selected by the (nonstandard and therefore
385 * capital) letter 'U' in the option string.
386 * It causes the quantifiers to be ungreedy by default.
387 * Appending a ? turns back to greedy (!).
389 * - Added a new interceptor ijb-send-banner, which
390 * sends back the "Junkbuster" gif. Without imagelist or
391 * MSIE detection support, or if tinygif = 1, or the
392 * URL isn't recognized as an imageurl, a lame HTML
393 * explanation is sent instead.
395 * - Added new feature, which permits blocking remote
396 * script redirects and firing back a local redirect
398 * The feature is conditionally compiled, i.e. it
399 * can be disabled with --disable-fast-redirects,
400 * plus it must be activated by a "fast-redirects"
401 * line in the config file, has its own log level
402 * and of course wants to be displayed by show-proxy-args
403 * Note: Boy, all the #ifdefs in 1001 locations and
404 * all the fumbling with configure.in and acconfig.h
405 * were *way* more work than the feature itself :-(
407 * - Because a generic redirect template was needed for
408 * this, tinygif = 3 now uses the same.
410 * - Moved GIFs, and other static HTTP response templates
415 * - Removed some >400 CRs again (Jon, you really worked
418 * Revision 1.4 2001/05/21 19:34:01 jongfoster
419 * Made failure to bind() a fatal error.
421 * Revision 1.3 2001/05/20 01:21:20 jongfoster
422 * Version 2.9.4 checkin.
423 * - Merged popupfile and cookiefile, and added control over PCRS
424 * filtering, in new "permissionsfile".
425 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
426 * file error you now get a message box (in the Win32 GUI) rather
427 * than the program exiting with no explanation.
428 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
430 * - Removed tabs from "config"
431 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
432 * - Bumped up version number.
434 * Revision 1.2 2001/05/17 22:34:44 oes
435 * - Added hint on GIF char array generation to jcc.c
436 * - Cleaned CRLF's from the sources and related files
437 * - Repaired logging for REF and FRC
439 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
440 * Initial import of version 2.9.3 source tree
443 *********************************************************************/
449 #include <sys/types.h>
456 #ifdef FEATURE_PTHREAD
458 #endif /* def FEATURE_PTHREAD */
461 # ifndef FEATURE_PTHREAD
462 # include <windows.h>
463 # include <process.h>
464 # endif /* ndef FEATURE_PTHREAD */
467 # ifndef _WIN_CONSOLE
469 # endif /* ndef _WIN_CONSOLE */
471 #else /* ifndef _WIN32 */
473 # if !defined (__OS2__)
475 # include <sys/wait.h>
476 # endif /* ndef __OS2__ */
477 # include <sys/time.h>
478 # include <sys/stat.h>
479 # include <sys/ioctl.h>
482 #include <sys/termios.h>
492 # include <socket.h> /* BeOS has select() for sockets only. */
493 # include <OS.h> /* declarations for threads and stuff. */
496 # if defined(__EMX__) || defined(__OS2__)
497 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
502 #define bzero(B,N) memset(B,0x00,n)
517 #include "killpopup.h"
518 #include "miscutil.h"
520 #include "jbsockets.h"
525 #include "urlmatch.h"
527 const char jcc_h_rcs[] = JCC_H_VERSION;
528 const char project_h_rcs[] = PROJECT_H_VERSION;
531 struct client_state clients[1];
532 struct file_list files[1];
534 #ifdef FEATURE_STATISTICS
535 int urls_read = 0; /* total nr of urls read inc rejected */
536 int urls_rejected = 0; /* total nr of urls rejected */
537 #endif /* def FEATURE_STATISTICS */
540 static void listen_loop(void);
541 static void chat(struct client_state *csp);
543 void serve(struct client_state *csp);
544 #else /* ifndef AMIGA */
545 static void serve(struct client_state *csp);
546 #endif /* def AMIGA */
549 static int32 server_thread(void *data);
550 #endif /* def __BEOS__ */
553 #define sleep(N) Sleep(((N) * 1000))
557 #define sleep(N) DosSleep(((N) * 100))
562 const char *pidfile = NULL;
563 int received_hup_signal = 0;
564 #endif /* defined unix */
566 /* The vanilla wafer. */
567 static const char VANILLA_WAFER[] =
568 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
569 "Do_not_send_me_any_copyrighted_information_other_than_the_"
570 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
571 "In_particular_do_not_send_me_any_cookies_that_"
572 "are_subject_to_a_claim_of_copyright_by_anybody._"
573 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
574 "(copyright_or_otherwise)_applying_to_any_cookie._";
577 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
578 /*********************************************************************
580 * Function : sig_handler
582 * Description : Signal handler for different signals.
583 * Exit gracefully on ABRT, TERM and INT
584 * or set a flag that will cause the errlog
585 * to be reopened by the main thread on HUP.
588 * 1 : the_signal - the signal cause this function to call
592 *********************************************************************/
593 static void sig_handler(int the_signal)
600 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
608 received_hup_signal = 1;
613 * We shouldn't be here, unless we catch signals
614 * in main() that we can't handle here!
616 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
624 /*********************************************************************
628 * Description : Once a connection to the client has been accepted,
629 * this function is called (via serve()) to handle the
630 * main business of the communication. When this
631 * function returns, the caller must close the client
635 * 1 : csp = Current client state (buffers, headers, etc...)
637 * Returns : On success, the number of bytes written are returned (zero
638 * indicates nothing was written). On error, -1 is returned,
639 * and errno is set appropriately. If count is zero and the
640 * file descriptor refers to a regular file, 0 will be
641 * returned without causing any other effect. For a special
642 * file, the results are not portable.
644 *********************************************************************/
645 static void chat(struct client_state *csp)
648 * This next lines are a little ugly, but they simplifies the if statements
649 * below. Basically if TOGGLE, then we want the if to test if the
650 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
651 * then we want the if to test for CSP_FLAG_FORCED , else we don't
653 #ifdef FEATURE_TOGGLE
654 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
655 #else /* ifndef FEATURE_TOGGLE */
656 # define IS_TOGGLED_ON_AND
657 #endif /* ndef FEATURE_TOGGLE */
658 #ifdef FEATURE_FORCE_LOAD
659 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
660 #else /* ifndef FEATURE_FORCE_LOAD */
661 # define IS_NOT_FORCED_AND
662 #endif /* def FEATURE_FORCE_LOAD */
664 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
666 char buf[BUFFER_SIZE];
669 int n, maxfd, server_body;
670 int ms_iis5_hack = 0;
672 const struct forward_spec * fwd;
673 struct http_request *http;
674 #ifdef FEATURE_KILL_POPUPS
675 int block_popups; /* bool, 1==will block popups */
676 int block_popups_now = 0; /* bool, 1==currently blocking popups */
677 #endif /* def FEATURE_KILL_POPUPS */
679 int pcrs_filter; /* bool, 1==will filter through pcrs */
680 int gif_deanimate; /* bool, 1==will deanimate gifs */
682 /* Function that does the content filtering for the current request */
683 char *(*content_filter)() = NULL;
685 /* Skeleton for HTTP response, if we should intercept the request */
686 struct http_response *rsp;
691 * Read the client's request. Note that since we're not using select() we
692 * could get blocked here if a client connected, then didn't say anything!
697 n = read_socket(csp->cfd, buf, sizeof(buf));
699 if (n <= 0) break; /* error! */
701 add_to_iob(csp, buf, n);
703 req = get_header(csp);
707 break; /* no HTTP request! */
712 continue; /* more to come! */
715 #ifdef FEATURE_FORCE_LOAD
716 /* If this request contains the FORCE_PREFIX,
717 * better get rid of it now and set the force flag --oes
720 if (strstr(req, FORCE_PREFIX))
722 strclean(req, FORCE_PREFIX);
723 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
724 csp->flags |= CSP_FLAG_FORCED;
727 #endif /* def FEATURE_FORCE_LOAD */
729 parse_http_request(req, http, csp);
734 if (http->cmd == NULL)
736 strcpy(buf, CHEADER);
737 write_socket(csp->cfd, buf, strlen(buf));
739 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
744 /* decide how to route the HTTP request */
746 if ((fwd = forward_url(http, csp)) == NULL)
748 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
749 /* Never get here - LOG_LEVEL_FATAL causes program exit */
752 /* build the http request to send to the server
753 * we have to do one of the following:
755 * create = use the original HTTP request to create a new
756 * HTTP request that has either the path component
757 * without the http://domainspec (w/path) or the
758 * full orininal URL (w/url)
759 * Note that the path and/or the HTTP version may
760 * have been altered by now.
762 * connect = Open a socket to the host:port of the server
763 * and short-circuit server and client socket.
765 * pass = Pass the request unchanged if forwarding a CONNECT
766 * request to a parent proxy. Note that we'll be sending
767 * the CFAIL message ourselves if connecting to the parent
768 * fails, but we won't send a CSUCCEED message if it works,
769 * since that would result in a double message (ours and the
770 * parent's). After sending the request to the parent, we simply
776 * +--------+--------+
778 * 0 | create | connect|
780 * Forwarding +--------+--------+
782 * 1 | create | pass |
784 * +--------+--------+
789 * Determine the actions for this URL
791 #ifdef FEATURE_TOGGLE
792 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
794 /* Most compatible set of actions (i.e. none) */
795 init_current_action(csp->action);
798 #endif /* ndef FEATURE_TOGGLE */
800 url_actions(http, csp);
805 * Check if a CONNECT request is allowable:
806 * In the absence of a +limit-connect action, allow only port 443.
807 * If there is an action, allow whatever matches the specificaton.
811 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
812 || (csp->action->flags & ACTION_LIMIT_CONNECT
813 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
815 strcpy(buf, CFORBIDDEN);
816 write_socket(csp->cfd, buf, strlen(buf));
818 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
819 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
827 * Downgrade http version from 1.1 to 1.0 if +downgrade
830 if ( (http->ssl == 0)
831 && (!strcmpic(http->ver, "HTTP/1.1"))
832 && (csp->action->flags & ACTION_DOWNGRADE))
835 http->ver = strdup("HTTP/1.0");
837 if (http->ver == NULL)
839 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
844 * Save a copy of the original request for logging
846 http->ocmd = strdup(http->cmd);
848 if (http->ocmd == NULL)
850 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
854 * (Re)build the HTTP request for non-SSL requests.
855 * If forwarding, use the whole URL, else, use only the path.
861 http->cmd = strdup(http->gpc);
862 string_append(&http->cmd, " ");
864 if (fwd->forward_host)
866 string_append(&http->cmd, http->url);
870 string_append(&http->cmd, http->path);
873 string_append(&http->cmd, " ");
874 string_append(&http->cmd, http->ver);
876 if (http->cmd == NULL)
878 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
881 enlist(csp->headers, http->cmd);
884 #ifdef FEATURE_COOKIE_JAR
886 * If we're logging cookies in a cookie jar, and the user has not
887 * supplied any wafers, and the user has not told us to suppress the
888 * vanilla wafer, then send the vanilla wafer.
890 if ((csp->config->jarfile != NULL)
891 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
892 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
894 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
896 #endif /* def FEATURE_COOKIE_JAR */
899 #ifdef FEATURE_KILL_POPUPS
900 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
901 #endif /* def FEATURE_KILL_POPUPS */
903 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
904 ((csp->action->flags & ACTION_FILTER) != 0);
906 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
908 /* grab the rest of the client's headers */
912 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
914 n = read_socket(csp->cfd, buf, sizeof(buf));
917 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
920 add_to_iob(csp, buf, n);
924 if (p == NULL) break;
926 enlist(csp->headers, p);
930 * We have a request. Now, check to see if we need to
931 * intercept it, i.e. If ..
935 /* a CGI call was detected and answered */
936 (NULL != (rsp = dispatch_cgi(csp)))
938 /* or we are enabled and... */
941 /* ..the request was blocked */
942 ( NULL != (rsp = block_url(csp)))
946 || ( NULL != (rsp = trust_url(csp)))
947 #endif /* def FEATURE_TRUST */
949 /* ..or a fast redirect kicked in */
950 #ifdef FEATURE_FAST_REDIRECTS
951 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
952 (NULL != (rsp = redirect_url(csp))))
953 #endif /* def FEATURE_FAST_REDIRECTS */
957 /* Write the answer to the client */
958 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
959 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
961 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
964 #ifdef FEATURE_STATISTICS
965 /* Count as a rejected request */
966 csp->flags |= CSP_FLAG_REJECTED;
967 #endif /* def FEATURE_STATISTICS */
969 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
970 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
971 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
973 /* Clean up and return */
974 free_http_response(rsp);
978 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
980 if (fwd->forward_host)
982 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
983 fwd->forward_host, fwd->forward_port, http->hostport);
987 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
990 /* here we connect to the server, gateway, or the forwarder */
992 csp->sfd = forwarded_connect(fwd, http, csp);
996 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1001 rsp = error_response(csp, "no-such-domain", errno);
1003 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1004 csp->ip_addr_str, http->ocmd);
1008 rsp = error_response(csp, "connect-failed", errno);
1010 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1011 csp->ip_addr_str, http->ocmd);
1015 /* Write the answer to the client */
1018 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1019 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1021 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1025 free_http_response(rsp);
1029 log_error(LOG_LEVEL_CONNECT, "OK");
1031 hdr = sed(client_patterns, add_client_headers, csp);
1034 /* FIXME Should handle error properly */
1035 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1038 list_remove_all(csp->headers);
1040 if (fwd->forward_host || (http->ssl == 0))
1042 /* write the client's (modified) header to the server
1043 * (along with anything else that may be in the buffer)
1048 if ((write_socket(csp->sfd, hdr, n) != n)
1049 || (flush_socket(csp->sfd, csp ) < 0))
1051 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1054 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1055 csp->ip_addr_str, http->ocmd);
1057 rsp = error_response(csp, "connect-failed", errno);
1061 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1062 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1064 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1068 free_http_response(rsp);
1076 * We're running an SSL tunnel and we're not forwarding,
1077 * so just send the "connect succeeded" message to the
1078 * client, flush the rest, and get out of the way.
1080 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1081 csp->ip_addr_str, http->ocmd);
1083 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
1091 /* we're finished with the client's header */
1094 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1096 /* pass data between the client and server
1097 * until one or the other shuts down the connection.
1106 FD_SET(csp->cfd, &rfds);
1107 FD_SET(csp->sfd, &rfds);
1109 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1113 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1117 /* this is the body of the browser's request
1118 * just read it and write it.
1121 if (FD_ISSET(csp->cfd, &rfds))
1123 n = read_socket(csp->cfd, buf, sizeof(buf));
1127 break; /* "game over, man" */
1130 if (write_socket(csp->sfd, buf, n) != n)
1132 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1139 * The server wants to talk. It could be the header or the body.
1140 * If `hdr' is null, then it's the header otherwise it's the body.
1141 * FIXME: Does `hdr' really mean `host'? No.
1145 if (FD_ISSET(csp->sfd, &rfds))
1148 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1152 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1154 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1155 csp->ip_addr_str, http->ocmd);
1157 rsp = error_response(csp, "connect-failed", errno);
1161 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1162 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1164 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1168 free_http_response(rsp);
1172 /* Add a trailing zero. This lets filter_popups
1173 * use string operations.
1177 #ifdef FEATURE_KILL_POPUPS
1178 /* Filter the popups on this read. */
1179 if (block_popups_now)
1181 filter_popups(buf, csp);
1183 #endif /* def FEATURE_KILL_POPUPS */
1185 /* Normally, this would indicate that we've read
1186 * as much as the server has sent us and we can
1187 * close the client connection. However, Microsoft
1188 * in its wisdom has released IIS/5 with a bug that
1189 * prevents it from sending the trailing \r\n in
1190 * a 302 redirect header (and possibly other headers).
1191 * To work around this if we've haven't parsed
1192 * a full header we'll append a trailing \r\n
1193 * and see if this now generates a valid one.
1195 * This hack shouldn't have any impacts. If we've
1196 * already transmitted the header or if this is a
1197 * SSL connection, then we won't bother with this
1198 * hack. So we only work on partially received
1199 * headers. If we append a \r\n and this still
1200 * doesn't generate a valid header, then we won't
1201 * transmit anything to the client.
1206 if (server_body || http->ssl)
1209 * If we have been buffering up the document,
1210 * now is the time to apply content modification
1211 * and send the result to the client.
1216 * If the content filter fails, use the original
1217 * buffer and length.
1218 * (see p != NULL ? p : csp->iob->cur below)
1220 if (NULL == (p = (*content_filter)(csp)))
1222 csp->content_length = csp->iob->eod - csp->iob->cur;
1225 hdr = sed(server_patterns, add_server_headers, csp);
1228 /* FIXME Should handle error properly */
1229 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1234 if ((write_socket(csp->cfd, hdr, n) != n)
1235 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1237 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1247 break; /* "game over, man" */
1251 * This is NOT the body, so
1252 * Let's pretend the server just sent us a blank line.
1254 n = sprintf(buf, "\r\n");
1257 * Now, let the normal header parsing algorithm below do its
1258 * job. If it fails, we'll exit instead of continuing.
1265 * If this is an SSL connection or we're in the body
1266 * of the server document, just write it to the client,
1267 * unless we need to buffer the body for later content-filtering
1270 if (server_body || http->ssl)
1274 add_to_iob(csp, buf, n);
1277 * If the buffer limit will be reached on the next read,
1278 * switch to non-filtering mode, i.e. make & write the
1279 * header, flush the socket and get out of the way.
1281 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1283 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1285 hdr = sed(server_patterns, add_server_headers, csp);
1288 /* FIXME Should handle error properly */
1289 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1295 if (((write_socket(csp->cfd, hdr, n) != n)
1296 || (n = flush_socket(csp->cfd, csp) < 0)))
1298 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1307 content_filter = NULL;
1314 if (write_socket(csp->cfd, buf, n) != n)
1316 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1325 /* we're still looking for the end of the
1326 * server's header ... (does that make header
1327 * parsing an "out of body experience" ?
1330 /* buffer up the data we just read */
1331 add_to_iob(csp, buf, n);
1333 /* get header lines from the iob */
1335 while ((p = get_header(csp)))
1339 /* see following note */
1342 enlist(csp->headers, p);
1346 /* NOTE: there are no "empty" headers so
1347 * if the pointer `p' is not NULL we must
1348 * assume that we reached the end of the
1349 * buffer before we hit the end of the header.
1356 /* Well, we tried our MS IIS/5
1357 * hack and it didn't work.
1358 * The header is incomplete
1359 * and there isn't anything
1360 * we can do about it.
1366 /* Since we have to wait for
1367 * more from the server before
1368 * we can parse the headers
1369 * we just continue here.
1375 /* we have now received the entire header.
1376 * filter it and send the result to the client
1379 hdr = sed(server_patterns, add_server_headers, csp);
1382 /* FIXME Should handle error properly */
1383 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1388 /* write the server's (modified) header to
1389 * the client (along with anything else that
1390 * may be in the buffer)
1393 #ifdef FEATURE_KILL_POPUPS
1394 /* Start blocking popups if appropriate. */
1396 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1397 !http->ssl && /* We talk plaintext */
1398 block_popups) /* Policy allows */
1400 block_popups_now = 1;
1402 * Filter the part of the body that came in the same read
1403 * as the last headers:
1405 filter_popups(csp->iob->cur, csp);
1408 #endif /* def FEATURE_KILL_POPUPS */
1410 /* Buffer and pcrs filter this if appropriate. */
1412 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1413 !http->ssl && /* We talk plaintext */
1414 pcrs_filter) /* Policy allows */
1416 content_filter = pcrs_filter_response;
1419 /* Buffer and gif_deanimate this if appropriate. */
1421 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1422 !http->ssl && /* We talk plaintext */
1423 gif_deanimate) /* Policy allows */
1425 content_filter = gif_deanimate_response;
1430 * Only write if we're not buffering for content modification
1432 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1433 || (n = flush_socket(csp->cfd, csp) < 0)))
1435 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1437 /* the write failed, so don't bother
1438 * mentioning it to the client...
1439 * it probably can't hear us anyway.
1445 if(!content_filter) byte_count += n;
1447 /* we're finished with the server's header */
1452 /* If this was a MS IIS/5 hack then it means
1453 * the server has already closed the
1454 * connection. Nothing more to read. Time
1465 return; /* huh? we should never get here */
1468 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1469 csp->ip_addr_str, http->ocmd, byte_count);
1473 /*********************************************************************
1477 * Description : This is little more than chat. We only "serve" to
1478 * to close any socket that chat may have opened.
1481 * 1 : csp = Current client state (buffers, headers, etc...)
1485 *********************************************************************/
1487 void serve(struct client_state *csp)
1488 #else /* ifndef AMIGA */
1489 static void serve(struct client_state *csp)
1490 #endif /* def AMIGA */
1493 close_socket(csp->cfd);
1497 close_socket(csp->sfd);
1500 csp->flags &= ~CSP_FLAG_ACTIVE;
1506 /*********************************************************************
1508 * Function : server_thread
1510 * Description : We only exist to call `serve' in a threaded environment.
1513 * 1 : data = Current client state (buffers, headers, etc...)
1515 * Returns : Always 0.
1517 *********************************************************************/
1518 static int32 server_thread(void *data)
1520 serve((struct client_state *) data);
1527 /*********************************************************************
1531 * Description : Print usage info & exit.
1533 * Parameters : Pointer to argv[0] for identifying ourselves
1537 *********************************************************************/
1538 void usage(const char *myname)
1540 printf("JunkBuster proxy version " VERSION " (" HOME_PAGE_URL ")\n"
1541 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user] [configfile]\n"
1542 "Aborting.\n", myname);
1549 /*********************************************************************
1553 * Description : Load the config file and start the listen loop.
1554 * This function is a lot more *sane* with the `load_config'
1555 * and `listen_loop' functions; although it stills does
1556 * a *little* too much for my taste.
1559 * 1 : argc = Number of parameters (including $0).
1560 * 2 : argv = Array of (char *)'s to the parameters.
1562 * Returns : 1 if : can't open config file, unrecognized directive,
1563 * stats requested in multi-thread mode, can't open the
1564 * log file, can't open the jar file, listen port is invalid,
1565 * any load fails, and can't bind port.
1567 * Else main never returns, the process must be signaled
1568 * to terminate execution. Or, on Windows, use the
1569 * "File", "Exit" menu option.
1571 *********************************************************************/
1573 int real_main(int argc, const char *argv[])
1575 int main(int argc, const char *argv[])
1580 struct passwd *pw = NULL;
1587 #if !defined(_WIN32)
1595 * Parse the command line arguments
1597 while (++argc_pos < argc)
1599 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1601 if (strcmp(argv[argc_pos], "--help") == 0)
1606 else if(strcmp(argv[argc_pos], "--version") == 0)
1608 printf("Junkbuster version " VERSION " (" HOME_PAGE_URL ")\n");
1612 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1617 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1619 if (++argc_pos == argc) usage(argv[0]);
1620 pidfile = strdup(argv[argc_pos]);
1623 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1625 if (++argc_pos == argc) usage(argv[0]);
1626 pw = getpwnam(argv[argc_pos]);
1630 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1633 #endif /* defined(unix) */
1635 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1637 configfile = argv[argc_pos];
1640 } /* -END- while (more arguments) */
1643 if ( *configfile != '/' )
1647 /* make config-filename absolute here */
1648 if ( !(basedir = getcwd( NULL, 1024 )))
1650 perror("get working dir failed");
1654 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1656 perror("malloc failed");
1659 strcpy( abs_file, basedir );
1660 strcat( abs_file, "/" );
1661 strcat( abs_file, configfile );
1662 configfile = abs_file;
1664 #endif /* defined unix */
1671 #elif defined(_WIN32)
1676 * Unix signal handling
1678 * Catch the abort, interrupt and terminate signals for a graceful exit
1679 * Catch the hangup signal so the errlog can be reopened.
1680 * Ignore the broken pipe and child signals
1681 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1683 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1686 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1687 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1689 for (idx = 0; catched_signals[idx] != 0; idx++)
1691 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1693 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1697 for (idx = 0; ignored_signals[idx] != 0; idx++)
1699 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1701 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1706 #else /* ifdef _WIN32 */
1707 # ifdef _WIN_CONSOLE
1709 * We *are* in a windows console app.
1710 * Print a verbose messages about FAQ's and such
1712 printf(win32_blurb);
1713 # endif /* def _WIN_CONSOLE */
1714 #endif /* def _WIN32 */
1717 /* Initialize the CGI subsystem */
1718 cgi_init_error_messages();
1721 * If runnig on unix and without the --nodaemon
1722 * option, become a daemon. I.e. fork, detach
1723 * from tty and get process group leadership
1736 if ( pid < 0 ) /* error */
1741 else if ( pid != 0 ) /* parent */
1746 * must check for errors
1747 * child died due to missing files aso
1750 wpid = waitpid( pid, &status, WNOHANG );
1759 /* Should be more portable, but not as well tested */
1764 #else /* ndef __FreeBSD__ */
1766 #endif /* ndef __FreeBSD__ */
1767 fd = open("/dev/tty", O_RDONLY);
1770 /* no error check here */
1771 ioctl( fd, TIOCNOTTY,0 );
1775 /* FIXME: should close stderr (fd 2) here too, but the test
1777 * and load config file is done in listen_loop() and puts
1778 * some messages on stderr there.
1785 } /* -END- if (!no_daemon) */
1788 * As soon as we have written the PID file, we can switch
1789 * to the user ID indicated by the --user option
1793 if ((NULL != pw) && setuid(pw->pw_uid))
1795 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1799 #endif /* defined unix */
1809 /*********************************************************************
1811 * Function : bind_port_helper
1813 * Description : Bind the listen port. Handles logging, and aborts
1817 * 1 : config = Junkbuster configuration. Specifies port
1820 * Returns : Port that was opened.
1822 *********************************************************************/
1823 static int bind_port_helper(struct configuration_spec * config)
1827 if ( (config->haddr != NULL)
1828 && (config->haddr[0] == '1')
1829 && (config->haddr[1] == '2')
1830 && (config->haddr[2] == '7')
1831 && (config->haddr[3] == '.') )
1833 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1836 else if (config->haddr == NULL)
1838 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1843 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1844 config->hport, config->haddr);
1847 bfd = bind_port(config->haddr, config->hport);
1851 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1852 "- There may be another junkbuster or some other "
1853 "proxy running on port %d",
1854 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1855 config->hport, config->hport
1857 /* shouldn't get here */
1861 config->need_bind = 0;
1867 /*********************************************************************
1869 * Function : listen_loop
1871 * Description : bind the listen port and enter a "FOREVER" listening loop.
1877 *********************************************************************/
1878 static void listen_loop(void)
1880 struct client_state *csp = NULL;
1882 struct configuration_spec * config;
1884 config = load_config();
1886 bfd = bind_port_helper(config);
1890 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1891 while (waitpid(-1, NULL, WNOHANG) > 0)
1893 /* zombie children */
1895 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1898 * Free data that was used by died threads
1904 * Re-open the errlog after HUP signal
1906 if (received_hup_signal)
1908 init_error_log(Argv[0], config->logfile, config->debug);
1909 received_hup_signal = 0;
1913 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1915 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1919 csp->flags |= CSP_FLAG_ACTIVE;
1922 csp->config = config = load_config();
1924 if ( config->need_bind )
1927 * Since we were listening to the "old port", we will not see
1928 * a "listen" param change until the next IJB request. So, at
1929 * least 1 more request must be made for us to find the new
1930 * setting. I am simply closing the old socket and binding the
1933 * Which-ever is correct, we will serve 1 more page via the
1934 * old settings. This should probably be a "show-proxy-args"
1935 * request. This should not be a so common of an operation
1936 * that this will hurt people's feelings.
1941 bfd = bind_port_helper(config);
1944 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1946 if (!accept_connection(csp, bfd))
1948 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1961 log_error(LOG_LEVEL_CONNECT, "OK");
1964 #ifdef FEATURE_TOGGLE
1967 csp->flags |= CSP_FLAG_TOGGLED_ON;
1969 #endif /* def FEATURE_TOGGLE */
1971 if (run_loader(csp))
1973 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1974 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1978 if (block_acl(NULL,csp))
1980 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1981 close_socket(csp->cfd);
1985 #endif /* def FEATURE_ACL */
1987 /* add it to the list of clients */
1988 csp->next = clients->next;
1989 clients->next = csp;
1991 if (config->multi_threaded)
1995 /* this is a switch () statment in the C preprocessor - ugh */
1996 #undef SELECTED_ONE_OPTION
1998 /* Use Pthreads in preference to native code */
1999 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2000 #define SELECTED_ONE_OPTION
2002 pthread_t the_thread;
2003 pthread_attr_t attrs;
2005 pthread_attr_init(&attrs);
2006 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2007 child_id = (pthread_create(&the_thread, &attrs,
2008 (void*)serve, csp) ? -1 : 0);
2009 pthread_attr_destroy(&attrs);
2013 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2014 #define SELECTED_ONE_OPTION
2015 child_id = _beginthread(
2021 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2022 #define SELECTED_ONE_OPTION
2023 child_id = _beginthread(
2030 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2031 #define SELECTED_ONE_OPTION
2033 thread_id tid = spawn_thread
2034 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2036 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2038 child_id = (int) tid;
2047 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2048 #define SELECTED_ONE_OPTION
2049 csp->cfd = ReleaseSocket(csp->cfd, -1);
2050 if((child_id = (int)CreateNewProcTags(
2051 NP_Entry, (ULONG)server_thread,
2052 NP_Output, Output(),
2053 NP_CloseOutput, FALSE,
2054 NP_Name, (ULONG)"junkbuster child",
2055 NP_StackSize, 200*1024,
2059 ((struct Task *)child_id)->tc_UserData = csp;
2060 Signal((struct Task *)child_id, SIGF_SINGLE);
2065 #if !defined(SELECTED_ONE_OPTION)
2068 /* This block is only needed when using fork().
2069 * When using threads, the server thread was
2070 * created and run by the call to _beginthread().
2072 if (child_id == 0) /* child */
2078 else if (child_id > 0) /* parent */
2080 /* in a fork()'d environment, the parent's
2081 * copy of the client socket and the CSP
2085 #if !defined(_WIN32) && defined(__CYGWIN__)
2087 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2088 close_socket(csp->cfd);
2089 csp->flags &= ~CSP_FLAG_ACTIVE;
2093 #undef SELECTED_ONE_OPTION
2094 /* end of cpp switch () */
2096 if (child_id < 0) /* failed */
2098 char buf[BUFFER_SIZE];
2100 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2102 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
2104 write_socket(csp->cfd, buf, strlen(buf));
2105 close_socket(csp->cfd);
2106 csp->flags &= ~CSP_FLAG_ACTIVE;