1 const char jcc_rcs[] = "$Id: jcc.c,v 1.76 2002/03/06 22:54:35 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.76 2002/03/06 22:54:35 jongfoster
37 * Automated function-comment nitpicking.
39 * Revision 1.75 2002/03/06 10:02:19 oes
40 * Fixed stupid bug when --user was not given
42 * Revision 1.74 2002/03/06 00:49:31 jongfoster
43 * Fixing warning on Windows
44 * Making #ifdefs that refer to the same variable consistently
45 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
47 * Revision 1.73 2002/03/05 23:57:30 hal9
48 * Stray character 's' on line 1618 was breaking build.
50 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
51 * - Re-enable OS/2 building after new parms were added
52 * - Fix false out of memory report when resolving CGI templates when no IP
53 * address is available of failed attempt (a la no such domain)
55 * Revision 1.71 2002/03/05 18:13:56 oes
58 * Revision 1.70 2002/03/05 04:52:42 oes
59 * Deleted non-errlog debugging code
61 * Revision 1.69 2002/03/04 23:50:00 jongfoster
62 * Splitting off bind_port() call into bind_port_helper(), with
65 * Revision 1.68 2002/03/04 20:17:32 oes
68 * Revision 1.67 2002/03/04 18:18:57 oes
69 * - Removed _DEBUG mode
70 * - Cleand up cmdline parsing
71 * - Introduced --no-daemon, --pidfile options
72 * - Cleaned up signal handling:
73 * - Terminate cleanly on INT, TERM and ABRT
74 * - Schedule logfile for re-opening on HUP
75 * - Ignore CHLD and PIPE
76 * - Leave the rest with their default handlers
77 * - Uniform handler registration
78 * - Added usage() function
79 * - Played styleguide police
81 * Revision 1.66 2002/03/03 15:06:55 oes
82 * Re-enabled automatic config reloading
84 * Revision 1.65 2002/03/03 14:49:11 oes
85 * Fixed CLF logging: Now uses client's original HTTP request
87 * Revision 1.64 2002/03/03 09:18:03 joergs
88 * Made jumbjuster work on AmigaOS again.
90 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
91 * Clean up a little CRLF unpleasantness that suddenly appeared
93 * Revision 1.62 2002/02/20 23:17:23 jongfoster
94 * Detecting some out-of memory conditions and exiting with a log message.
96 * Revision 1.61 2002/01/17 21:01:52 jongfoster
97 * Moving all our URL and URL pattern parsing code to urlmatch.c.
99 * Revision 1.60 2001/12/30 14:07:32 steudten
100 * - Add signal handling (unix)
101 * - Add SIGHUP handler (unix)
102 * - Add creation of pidfile (unix)
103 * - Add action 'top' in rc file (RH)
104 * - Add entry 'SIGNALS' to manpage
105 * - Add exit message to logfile (unix)
107 * Revision 1.59 2001/12/13 14:07:18 oes
108 * Fixed Bug: 503 error page now sent OK
110 * Revision 1.58 2001/11/30 23:37:24 jongfoster
111 * Renaming the Win32 config file to config.txt - this is almost the
112 * same as the corresponding UNIX name "config"
114 * Revision 1.57 2001/11/16 00:47:43 jongfoster
115 * Changing the tty-disconnection code to use setsid().
117 * Revision 1.56 2001/11/13 20:20:54 jongfoster
118 * Tabs->spaces, fixing a bug with missing {} around an if()
120 * Revision 1.55 2001/11/13 20:14:53 jongfoster
121 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
123 * Revision 1.54 2001/11/07 00:03:14 steudten
124 * Give reliable return value if an error
125 * occurs not just 0 with new daemon mode.
127 * Revision 1.53 2001/11/05 21:41:43 steudten
128 * Add changes to be a real daemon just for unix os.
129 * (change cwd to /, detach from controlling tty, set
130 * process group and session leader to the own process.
132 * Add some fatal-error log message for failed malloc().
133 * Add '-d' if compiled with 'configure --with-debug' to
134 * enable debug output.
136 * Revision 1.52 2001/10/26 20:11:20 jongfoster
137 * Fixing type mismatch
139 * Revision 1.51 2001/10/26 17:38:28 oes
142 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
143 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
144 * threads to call select() simultaneously. So, it's time to do a real, live,
145 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
146 * (native). Both versions will work, but using __OS2__ offers multi-threading.
148 * Revision 1.49 2001/10/23 21:41:35 jongfoster
149 * Added call to initialize the (statically-allocated of course)
150 * "out of memory" CGI response.
152 * Revision 1.48 2001/10/10 19:56:46 jongfoster
153 * Moving some code that wasn't cookie-related out of an #ifdef
156 * Revision 1.47 2001/10/10 16:44:36 oes
157 * Added CONNECT destination port limitation check
159 * Revision 1.46 2001/10/08 15:17:41 oes
160 * Re-enabled SSL forwarding
162 * Revision 1.45 2001/10/07 15:42:11 oes
163 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
165 * Moved downgrading of the HTTP version from parse_http_request to
166 * chat(), since we can't decide if it is necessary before we have
167 * determined the actions for the URL. The HTTP command is now
168 * *always* re-built so the repairs need no longer be special-cased.
170 * filter_popups now gets a csp pointer so it can raise the new
171 * CSP_FLAG_MODIFIED flag.
175 * Added configurable size limit for the IOB. If the IOB grows so
176 * large that the next read would exceed the limit, the header
177 * is generated, and the header & unfiltered buffer are flushed
178 * to the client. Chat then continues in non-buffering,
179 * non-filtering body mode.
181 * Revision 1.44 2001/10/02 18:13:57 oes
184 * Revision 1.43 2001/10/02 15:32:13 oes
185 * Moved generation of hdr
187 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
188 * Cleaning up 2 compiler warnings on OS/2.
190 * Revision 1.41 2001/09/16 17:05:14 jongfoster
191 * Removing unused #include showarg.h
193 * Revision 1.40 2001/09/16 15:41:45 jongfoster
194 * Fixing signed/unsigned comparison warning.
196 * Revision 1.39 2001/09/16 13:21:27 jongfoster
197 * Changes to use new list functions.
199 * Revision 1.38 2001/09/16 13:01:46 jongfoster
200 * Removing redundant function call that zeroed zalloc()'d memory.
202 * Revision 1.37 2001/09/10 11:12:24 oes
203 * Deleted unused variable
205 * Revision 1.36 2001/09/10 10:56:15 oes
206 * Silenced compiler warnings
208 * Revision 1.35 2001/07/31 14:44:22 oes
209 * Deleted unused size parameter from filter_popups()
211 * Revision 1.34 2001/07/30 22:08:36 jongfoster
212 * Tidying up #defines:
213 * - All feature #defines are now of the form FEATURE_xxx
214 * - Permanently turned off WIN_GUI_EDIT
215 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
217 * Revision 1.33 2001/07/29 19:32:00 jongfoster
218 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
220 * Revision 1.32 2001/07/29 18:47:05 jongfoster
221 * Adding missing #include "loadcfg.h"
223 * Revision 1.31 2001/07/29 12:17:48 oes
224 * Applied pthread fix by Paul Lieverse
226 * Revision 1.30 2001/07/25 22:57:13 jongfoster
227 * __BEOS__ no longer overrides FEATURE_PTHREAD.
228 * This is because FEATURE_PTHREAD will soon be widely used, so I
229 * want to keep it simple.
231 * Revision 1.29 2001/07/24 12:47:06 oes
232 * Applied BeOS support update by Eugenia
234 * Revision 1.28 2001/07/23 13:26:12 oes
235 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
237 * Revision 1.27 2001/07/19 19:09:47 haroon
238 * - Added code to take care of the situation where while processing the first
239 * server response (which includes the server header), after finding the end
240 * of the headers we were not looking past the end of the headers for
241 * content modification. I enabled it for filter_popups.
242 * Someone else should look to see if other similar operations should be
243 * done to the discarded portion of the buffer.
245 * Note 2001/07/20: No, the other content modification mechanisms will process
246 * the whole iob later anyway. --oes
248 * Revision 1.26 2001/07/18 12:31:36 oes
251 * Revision 1.25 2001/07/15 19:43:49 jongfoster
252 * Supports POSIX threads.
253 * Also removed some unused #includes.
255 * Revision 1.24 2001/07/13 14:00:40 oes
256 * - Generic content modification scheme:
257 * Each feature has its own applicability flag that is set
258 * from csp->action->flags.
259 * Replaced the "filtering" int flag , by a function pointer
260 * "content_filter" to the function that will do the content
261 * modification. If it is != NULL, the document will be buffered
262 * and processed through *content_filter, which must set
263 * csp->content_length and return a modified copy of the body
264 * or return NULL (on failiure).
265 * - Changed csp->is_text to the more generic bitmap csp->content_type
266 * which can currently take the valued CT_TEXT or CT_GIF
268 * - Removed all #ifdef PCRS
270 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
271 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
272 * the `block_acl' call. This prevents a compilation error when the user
273 * does not wish to use the "ACL" feature.
275 * Revision 1.22 2001/06/29 21:45:41 oes
276 * Indentation, CRLF->LF, Tab-> Space
278 * Revision 1.21 2001/06/29 13:29:36 oes
279 * - Cleaned up, improved comments
280 * - Unified all possible interceptors (CGI,
281 * block, trust, fast_redirect) in one
282 * place, with one (CGI) answer generation
283 * mechansim. Much clearer now.
284 * - Removed the GIF image generation, which
285 * is now done in filters.c:block_url()
286 * - Made error conditions like domain lookup
287 * failiure or (various) problems while talking
288 * to the server use cgi.c:error_response()
289 * instead of generating HTML/HTTP in chat() (yuck!)
290 * - Removed logentry from cancelled commit
292 * Revision 1.20 2001/06/09 10:55:28 jongfoster
293 * Changing BUFSIZ ==> BUFFER_SIZE
295 * Revision 1.19 2001/06/07 23:12:52 jongfoster
296 * Replacing function pointer in struct gateway with a directly
297 * called function forwarded_connect().
298 * Replacing struct gateway with struct forward_spec
300 * Revision 1.18 2001/06/03 19:12:16 oes
301 * introduced new cgi handling
303 * Revision 1.17 2001/06/01 20:07:23 jongfoster
304 * Now uses action +image-blocker{} rather than config->tinygif
306 * Revision 1.16 2001/06/01 18:49:17 jongfoster
307 * Replaced "list_share" with "list" - the tiny memory gain was not
308 * worth the extra complexity.
310 * Revision 1.15 2001/05/31 21:24:47 jongfoster
311 * Changed "permission" to "action" throughout.
312 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
313 * Moved vanilla wafer check into chat(), since we must now
314 * decide whether or not to add it based on the URL.
316 * Revision 1.14 2001/05/29 20:14:01 joergs
317 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
320 * Revision 1.13 2001/05/29 09:50:24 jongfoster
321 * Unified blocklist/imagelist/permissionslist.
322 * File format is still under discussion, but the internal changes
325 * Also modified interceptor behaviour:
326 * - We now intercept all URLs beginning with one of the following
327 * prefixes (and *only* these prefixes):
329 * * http://ijbswa.sf.net/config/
330 * * http://ijbswa.sourceforge.net/config/
331 * - New interceptors "home page" - go to http://i.j.b/ to see it.
332 * - Internal changes so that intercepted and fast redirect pages
333 * are not replaced with an image.
334 * - Interceptors now have the option to send a binary page direct
335 * to the client. (i.e. ijb-send-banner uses this)
336 * - Implemented show-url-info interceptor. (Which is why I needed
337 * the above interceptors changes - a typical URL is
338 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
339 * The previous mechanism would not have intercepted that, and
340 * if it had been intercepted then it then it would have replaced
343 * Revision 1.12 2001/05/27 22:17:04 oes
345 * - re_process_buffer no longer writes the modified buffer
346 * to the client, which was very ugly. It now returns the
347 * buffer, which it is then written by chat.
349 * - content_length now adjusts the Content-Length: header
350 * for modified documents rather than crunch()ing it.
351 * (Length info in csp->content_length, which is 0 for
352 * unmodified documents)
354 * - For this to work, sed() is called twice when filtering.
356 * Revision 1.11 2001/05/26 17:27:53 jongfoster
357 * Added support for CLF and fixed LOG_LEVEL_LOG.
358 * Also did CRLF->LF fix of my previous patch.
360 * Revision 1.10 2001/05/26 15:26:15 jongfoster
361 * ACL feature now provides more security by immediately dropping
362 * connections from untrusted hosts.
364 * Revision 1.9 2001/05/26 00:28:36 jongfoster
365 * Automatic reloading of config file.
366 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
367 * Most of the global variables have been moved to a new
368 * struct configuration_spec, accessed through csp->config->globalname
369 * Most of the globals remaining are used by the Win32 GUI.
371 * Revision 1.8 2001/05/25 22:43:18 jongfoster
372 * Fixing minor memory leak and buffer overflow.
374 * Revision 1.7 2001/05/25 22:34:30 jongfoster
377 * Revision 1.6 2001/05/23 00:13:58 joergs
378 * AmigaOS support fixed.
380 * Revision 1.5 2001/05/22 18:46:04 oes
382 * - Enabled filtering banners by size rather than URL
383 * by adding patterns that replace all standard banner
384 * sizes with the "Junkbuster" gif to the re_filterfile
386 * - Enabled filtering WebBugs by providing a pattern
387 * which kills all 1x1 images
389 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
390 * which is selected by the (nonstandard and therefore
391 * capital) letter 'U' in the option string.
392 * It causes the quantifiers to be ungreedy by default.
393 * Appending a ? turns back to greedy (!).
395 * - Added a new interceptor ijb-send-banner, which
396 * sends back the "Junkbuster" gif. Without imagelist or
397 * MSIE detection support, or if tinygif = 1, or the
398 * URL isn't recognized as an imageurl, a lame HTML
399 * explanation is sent instead.
401 * - Added new feature, which permits blocking remote
402 * script redirects and firing back a local redirect
404 * The feature is conditionally compiled, i.e. it
405 * can be disabled with --disable-fast-redirects,
406 * plus it must be activated by a "fast-redirects"
407 * line in the config file, has its own log level
408 * and of course wants to be displayed by show-proxy-args
409 * Note: Boy, all the #ifdefs in 1001 locations and
410 * all the fumbling with configure.in and acconfig.h
411 * were *way* more work than the feature itself :-(
413 * - Because a generic redirect template was needed for
414 * this, tinygif = 3 now uses the same.
416 * - Moved GIFs, and other static HTTP response templates
421 * - Removed some >400 CRs again (Jon, you really worked
424 * Revision 1.4 2001/05/21 19:34:01 jongfoster
425 * Made failure to bind() a fatal error.
427 * Revision 1.3 2001/05/20 01:21:20 jongfoster
428 * Version 2.9.4 checkin.
429 * - Merged popupfile and cookiefile, and added control over PCRS
430 * filtering, in new "permissionsfile".
431 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
432 * file error you now get a message box (in the Win32 GUI) rather
433 * than the program exiting with no explanation.
434 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
436 * - Removed tabs from "config"
437 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
438 * - Bumped up version number.
440 * Revision 1.2 2001/05/17 22:34:44 oes
441 * - Added hint on GIF char array generation to jcc.c
442 * - Cleaned CRLF's from the sources and related files
443 * - Repaired logging for REF and FRC
445 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
446 * Initial import of version 2.9.3 source tree
449 *********************************************************************/
455 #include <sys/types.h>
462 #ifdef FEATURE_PTHREAD
464 #endif /* def FEATURE_PTHREAD */
467 # ifndef FEATURE_PTHREAD
468 # include <windows.h>
469 # include <process.h>
470 # endif /* ndef FEATURE_PTHREAD */
473 # ifndef _WIN_CONSOLE
475 # endif /* ndef _WIN_CONSOLE */
477 #else /* ifndef _WIN32 */
479 # if !defined (__OS2__)
481 # include <sys/wait.h>
482 # endif /* ndef __OS2__ */
483 # include <sys/time.h>
484 # include <sys/stat.h>
485 # include <sys/ioctl.h>
488 #include <sys/termios.h>
498 # include <socket.h> /* BeOS has select() for sockets only. */
499 # include <OS.h> /* declarations for threads and stuff. */
502 # if defined(__EMX__) || defined(__OS2__)
503 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
508 #define bzero(B,N) memset(B,0x00,n)
523 #include "killpopup.h"
524 #include "miscutil.h"
526 #include "jbsockets.h"
531 #include "urlmatch.h"
533 const char jcc_h_rcs[] = JCC_H_VERSION;
534 const char project_h_rcs[] = PROJECT_H_VERSION;
537 struct client_state clients[1];
538 struct file_list files[1];
540 #ifdef FEATURE_STATISTICS
541 int urls_read = 0; /* total nr of urls read inc rejected */
542 int urls_rejected = 0; /* total nr of urls rejected */
543 #endif /* def FEATURE_STATISTICS */
546 static void listen_loop(void);
547 static void chat(struct client_state *csp);
549 void serve(struct client_state *csp);
550 #else /* ifndef AMIGA */
551 static void serve(struct client_state *csp);
552 #endif /* def AMIGA */
555 static int32 server_thread(void *data);
556 #endif /* def __BEOS__ */
559 #define sleep(N) Sleep(((N) * 1000))
563 #define sleep(N) DosSleep(((N) * 100))
568 const char *pidfile = NULL;
569 int received_hup_signal = 0;
570 #endif /* defined unix */
572 /* The vanilla wafer. */
573 static const char VANILLA_WAFER[] =
574 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
575 "Do_not_send_me_any_copyrighted_information_other_than_the_"
576 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
577 "In_particular_do_not_send_me_any_cookies_that_"
578 "are_subject_to_a_claim_of_copyright_by_anybody._"
579 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
580 "(copyright_or_otherwise)_applying_to_any_cookie._";
583 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
584 /*********************************************************************
586 * Function : sig_handler
588 * Description : Signal handler for different signals.
589 * Exit gracefully on ABRT, TERM and INT
590 * or set a flag that will cause the errlog
591 * to be reopened by the main thread on HUP.
594 * 1 : the_signal = the signal cause this function to call
598 *********************************************************************/
599 static void sig_handler(int the_signal)
606 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
614 received_hup_signal = 1;
619 * We shouldn't be here, unless we catch signals
620 * in main() that we can't handle here!
622 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
630 /*********************************************************************
634 * Description : Once a connection to the client has been accepted,
635 * this function is called (via serve()) to handle the
636 * main business of the communication. When this
637 * function returns, the caller must close the client
641 * 1 : csp = Current client state (buffers, headers, etc...)
643 * Returns : On success, the number of bytes written are returned (zero
644 * indicates nothing was written). On error, -1 is returned,
645 * and errno is set appropriately. If count is zero and the
646 * file descriptor refers to a regular file, 0 will be
647 * returned without causing any other effect. For a special
648 * file, the results are not portable.
650 *********************************************************************/
651 static void chat(struct client_state *csp)
654 * This next lines are a little ugly, but they simplifies the if statements
655 * below. Basically if TOGGLE, then we want the if to test if the
656 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
657 * then we want the if to test for CSP_FLAG_FORCED , else we don't
659 #ifdef FEATURE_TOGGLE
660 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
661 #else /* ifndef FEATURE_TOGGLE */
662 # define IS_TOGGLED_ON_AND
663 #endif /* ndef FEATURE_TOGGLE */
664 #ifdef FEATURE_FORCE_LOAD
665 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
666 #else /* ifndef FEATURE_FORCE_LOAD */
667 # define IS_NOT_FORCED_AND
668 #endif /* def FEATURE_FORCE_LOAD */
670 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
672 char buf[BUFFER_SIZE];
675 int n, maxfd, server_body;
676 int ms_iis5_hack = 0;
678 const struct forward_spec * fwd;
679 struct http_request *http;
680 size_t len; /* for buffer sizes */
681 #ifdef FEATURE_KILL_POPUPS
682 int block_popups; /* bool, 1==will block popups */
683 int block_popups_now = 0; /* bool, 1==currently blocking popups */
684 #endif /* def FEATURE_KILL_POPUPS */
686 int pcrs_filter; /* bool, 1==will filter through pcrs */
687 int gif_deanimate; /* bool, 1==will deanimate gifs */
689 /* Function that does the content filtering for the current request */
690 char *(*content_filter)() = NULL;
692 /* Skeleton for HTTP response, if we should intercept the request */
693 struct http_response *rsp;
698 * Read the client's request. Note that since we're not using select() we
699 * could get blocked here if a client connected, then didn't say anything!
704 len = read_socket(csp->cfd, buf, sizeof(buf));
706 if (len <= 0) break; /* error! */
708 add_to_iob(csp, buf, len);
710 req = get_header(csp);
714 break; /* no HTTP request! */
719 continue; /* more to come! */
722 #ifdef FEATURE_FORCE_LOAD
723 /* If this request contains the FORCE_PREFIX,
724 * better get rid of it now and set the force flag --oes
727 if (strstr(req, FORCE_PREFIX))
729 strclean(req, FORCE_PREFIX);
730 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
731 csp->flags |= CSP_FLAG_FORCED;
734 #endif /* def FEATURE_FORCE_LOAD */
736 parse_http_request(req, http, csp);
741 if (http->cmd == NULL)
743 strcpy(buf, CHEADER);
744 write_socket(csp->cfd, buf, strlen(buf));
746 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
751 /* decide how to route the HTTP request */
753 if ((fwd = forward_url(http, csp)) == NULL)
755 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
756 /* Never get here - LOG_LEVEL_FATAL causes program exit */
759 /* build the http request to send to the server
760 * we have to do one of the following:
762 * create = use the original HTTP request to create a new
763 * HTTP request that has either the path component
764 * without the http://domainspec (w/path) or the
765 * full orininal URL (w/url)
766 * Note that the path and/or the HTTP version may
767 * have been altered by now.
769 * connect = Open a socket to the host:port of the server
770 * and short-circuit server and client socket.
772 * pass = Pass the request unchanged if forwarding a CONNECT
773 * request to a parent proxy. Note that we'll be sending
774 * the CFAIL message ourselves if connecting to the parent
775 * fails, but we won't send a CSUCCEED message if it works,
776 * since that would result in a double message (ours and the
777 * parent's). After sending the request to the parent, we simply
783 * +--------+--------+
785 * 0 | create | connect|
787 * Forwarding +--------+--------+
789 * 1 | create | pass |
791 * +--------+--------+
796 * Determine the actions for this URL
798 #ifdef FEATURE_TOGGLE
799 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
801 /* Most compatible set of actions (i.e. none) */
802 init_current_action(csp->action);
805 #endif /* ndef FEATURE_TOGGLE */
807 url_actions(http, csp);
812 * Check if a CONNECT request is allowable:
813 * In the absence of a +limit-connect action, allow only port 443.
814 * If there is an action, allow whatever matches the specificaton.
818 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
819 || (csp->action->flags & ACTION_LIMIT_CONNECT
820 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
822 strcpy(buf, CFORBIDDEN);
823 write_socket(csp->cfd, buf, strlen(buf));
825 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
826 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
834 * Downgrade http version from 1.1 to 1.0 if +downgrade
837 if ( (http->ssl == 0)
838 && (!strcmpic(http->ver, "HTTP/1.1"))
839 && (csp->action->flags & ACTION_DOWNGRADE))
842 http->ver = strdup("HTTP/1.0");
844 if (http->ver == NULL)
846 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
851 * Save a copy of the original request for logging
853 http->ocmd = strdup(http->cmd);
855 if (http->ocmd == NULL)
857 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
861 * (Re)build the HTTP request for non-SSL requests.
862 * If forwarding, use the whole URL, else, use only the path.
868 http->cmd = strdup(http->gpc);
869 string_append(&http->cmd, " ");
871 if (fwd->forward_host)
873 string_append(&http->cmd, http->url);
877 string_append(&http->cmd, http->path);
880 string_append(&http->cmd, " ");
881 string_append(&http->cmd, http->ver);
883 if (http->cmd == NULL)
885 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
888 enlist(csp->headers, http->cmd);
891 #ifdef FEATURE_COOKIE_JAR
893 * If we're logging cookies in a cookie jar, and the user has not
894 * supplied any wafers, and the user has not told us to suppress the
895 * vanilla wafer, then send the vanilla wafer.
897 if ((csp->config->jarfile != NULL)
898 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
899 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
901 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
903 #endif /* def FEATURE_COOKIE_JAR */
906 #ifdef FEATURE_KILL_POPUPS
907 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
908 #endif /* def FEATURE_KILL_POPUPS */
910 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
911 ((csp->action->flags & ACTION_FILTER) != 0);
913 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
915 /* grab the rest of the client's headers */
919 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
921 len = read_socket(csp->cfd, buf, sizeof(buf));
924 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
927 add_to_iob(csp, buf, len);
931 if (p == NULL) break;
933 enlist(csp->headers, p);
937 * We have a request. Now, check to see if we need to
938 * intercept it, i.e. If ..
942 /* a CGI call was detected and answered */
943 (NULL != (rsp = dispatch_cgi(csp)))
945 /* or we are enabled and... */
948 /* ..the request was blocked */
949 ( NULL != (rsp = block_url(csp)))
953 || ( NULL != (rsp = trust_url(csp)))
954 #endif /* def FEATURE_TRUST */
956 /* ..or a fast redirect kicked in */
957 #ifdef FEATURE_FAST_REDIRECTS
958 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
959 (NULL != (rsp = redirect_url(csp))))
960 #endif /* def FEATURE_FAST_REDIRECTS */
964 /* Write the answer to the client */
965 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
966 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
968 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
971 #ifdef FEATURE_STATISTICS
972 /* Count as a rejected request */
973 csp->flags |= CSP_FLAG_REJECTED;
974 #endif /* def FEATURE_STATISTICS */
976 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
977 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
978 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
980 /* Clean up and return */
981 free_http_response(rsp);
985 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
987 if (fwd->forward_host)
989 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
990 fwd->forward_host, fwd->forward_port, http->hostport);
994 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
997 /* here we connect to the server, gateway, or the forwarder */
999 csp->sfd = forwarded_connect(fwd, http, csp);
1003 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1006 if (errno == EINVAL)
1008 rsp = error_response(csp, "no-such-domain", errno);
1010 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1011 csp->ip_addr_str, http->ocmd);
1015 rsp = error_response(csp, "connect-failed", errno);
1017 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1018 csp->ip_addr_str, http->ocmd);
1022 /* Write the answer to the client */
1025 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1026 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1028 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1032 free_http_response(rsp);
1036 log_error(LOG_LEVEL_CONNECT, "OK");
1038 hdr = sed(client_patterns, add_client_headers, csp);
1041 /* FIXME Should handle error properly */
1042 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1045 list_remove_all(csp->headers);
1047 if (fwd->forward_host || (http->ssl == 0))
1049 /* write the client's (modified) header to the server
1050 * (along with anything else that may be in the buffer)
1055 if ((write_socket(csp->sfd, hdr, len) != len)
1056 || (flush_socket(csp->sfd, csp ) < 0))
1058 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1061 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1062 csp->ip_addr_str, http->ocmd);
1064 rsp = error_response(csp, "connect-failed", errno);
1068 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1069 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1071 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1075 free_http_response(rsp);
1083 * We're running an SSL tunnel and we're not forwarding,
1084 * so just send the "connect succeeded" message to the
1085 * client, flush the rest, and get out of the way.
1087 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1088 csp->ip_addr_str, http->ocmd);
1090 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
1098 /* we're finished with the client's header */
1101 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1103 /* pass data between the client and server
1104 * until one or the other shuts down the connection.
1113 FD_SET(csp->cfd, &rfds);
1114 FD_SET(csp->sfd, &rfds);
1116 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1120 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1124 /* this is the body of the browser's request
1125 * just read it and write it.
1128 if (FD_ISSET(csp->cfd, &rfds))
1130 len = read_socket(csp->cfd, buf, sizeof(buf));
1134 break; /* "game over, man" */
1137 if (write_socket(csp->sfd, buf, len) != len)
1139 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1146 * The server wants to talk. It could be the header or the body.
1147 * If `hdr' is null, then it's the header otherwise it's the body.
1148 * FIXME: Does `hdr' really mean `host'? No.
1152 if (FD_ISSET(csp->sfd, &rfds))
1155 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1159 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1161 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1162 csp->ip_addr_str, http->ocmd);
1164 rsp = error_response(csp, "connect-failed", errno);
1168 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1169 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1171 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1175 free_http_response(rsp);
1179 /* Add a trailing zero. This lets filter_popups
1180 * use string operations.
1184 #ifdef FEATURE_KILL_POPUPS
1185 /* Filter the popups on this read. */
1186 if (block_popups_now)
1188 filter_popups(buf, csp);
1190 #endif /* def FEATURE_KILL_POPUPS */
1192 /* Normally, this would indicate that we've read
1193 * as much as the server has sent us and we can
1194 * close the client connection. However, Microsoft
1195 * in its wisdom has released IIS/5 with a bug that
1196 * prevents it from sending the trailing \r\n in
1197 * a 302 redirect header (and possibly other headers).
1198 * To work around this if we've haven't parsed
1199 * a full header we'll append a trailing \r\n
1200 * and see if this now generates a valid one.
1202 * This hack shouldn't have any impacts. If we've
1203 * already transmitted the header or if this is a
1204 * SSL connection, then we won't bother with this
1205 * hack. So we only work on partially received
1206 * headers. If we append a \r\n and this still
1207 * doesn't generate a valid header, then we won't
1208 * transmit anything to the client.
1213 if (server_body || http->ssl)
1216 * If we have been buffering up the document,
1217 * now is the time to apply content modification
1218 * and send the result to the client.
1223 * If the content filter fails, use the original
1224 * buffer and length.
1225 * (see p != NULL ? p : csp->iob->cur below)
1227 if (NULL == (p = (*content_filter)(csp)))
1229 csp->content_length = csp->iob->eod - csp->iob->cur;
1232 hdr = sed(server_patterns, add_server_headers, csp);
1235 /* FIXME Should handle error properly */
1236 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1241 if ((write_socket(csp->cfd, hdr, len) != len)
1242 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1244 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1254 break; /* "game over, man" */
1258 * This is NOT the body, so
1259 * Let's pretend the server just sent us a blank line.
1261 len = sprintf(buf, "\r\n");
1264 * Now, let the normal header parsing algorithm below do its
1265 * job. If it fails, we'll exit instead of continuing.
1272 * If this is an SSL connection or we're in the body
1273 * of the server document, just write it to the client,
1274 * unless we need to buffer the body for later content-filtering
1277 if (server_body || http->ssl)
1281 add_to_iob(csp, buf, len);
1284 * If the buffer limit will be reached on the next read,
1285 * switch to non-filtering mode, i.e. make & write the
1286 * header, flush the socket and get out of the way.
1288 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1290 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1292 hdr = sed(server_patterns, add_server_headers, csp);
1295 /* FIXME Should handle error properly */
1296 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1302 if (((write_socket(csp->cfd, hdr, len) != len)
1303 || (len = flush_socket(csp->cfd, csp) < 0)))
1305 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1314 content_filter = NULL;
1321 if (write_socket(csp->cfd, buf, len) != len)
1323 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1332 /* we're still looking for the end of the
1333 * server's header ... (does that make header
1334 * parsing an "out of body experience" ?
1337 /* buffer up the data we just read */
1338 add_to_iob(csp, buf, len);
1340 /* get header lines from the iob */
1342 while ((p = get_header(csp)))
1346 /* see following note */
1349 enlist(csp->headers, p);
1353 /* NOTE: there are no "empty" headers so
1354 * if the pointer `p' is not NULL we must
1355 * assume that we reached the end of the
1356 * buffer before we hit the end of the header.
1363 /* Well, we tried our MS IIS/5
1364 * hack and it didn't work.
1365 * The header is incomplete
1366 * and there isn't anything
1367 * we can do about it.
1373 /* Since we have to wait for
1374 * more from the server before
1375 * we can parse the headers
1376 * we just continue here.
1382 /* we have now received the entire header.
1383 * filter it and send the result to the client
1386 hdr = sed(server_patterns, add_server_headers, csp);
1389 /* FIXME Should handle error properly */
1390 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1395 /* write the server's (modified) header to
1396 * the client (along with anything else that
1397 * may be in the buffer)
1400 #ifdef FEATURE_KILL_POPUPS
1401 /* Start blocking popups if appropriate. */
1403 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1404 !http->ssl && /* We talk plaintext */
1405 block_popups) /* Policy allows */
1407 block_popups_now = 1;
1409 * Filter the part of the body that came in the same read
1410 * as the last headers:
1412 filter_popups(csp->iob->cur, csp);
1415 #endif /* def FEATURE_KILL_POPUPS */
1417 /* Buffer and pcrs filter this if appropriate. */
1419 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1420 !http->ssl && /* We talk plaintext */
1421 pcrs_filter) /* Policy allows */
1423 content_filter = pcrs_filter_response;
1426 /* Buffer and gif_deanimate this if appropriate. */
1428 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1429 !http->ssl && /* We talk plaintext */
1430 gif_deanimate) /* Policy allows */
1432 content_filter = gif_deanimate_response;
1437 * Only write if we're not buffering for content modification
1439 if (!content_filter && ((write_socket(csp->cfd, hdr, len) != len)
1440 || (len = flush_socket(csp->cfd, csp) < 0)))
1442 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1444 /* the write failed, so don't bother
1445 * mentioning it to the client...
1446 * it probably can't hear us anyway.
1452 if(!content_filter) byte_count += len;
1454 /* we're finished with the server's header */
1459 /* If this was a MS IIS/5 hack then it means
1460 * the server has already closed the
1461 * connection. Nothing more to read. Time
1472 return; /* huh? we should never get here */
1475 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1476 csp->ip_addr_str, http->ocmd, byte_count);
1480 /*********************************************************************
1484 * Description : This is little more than chat. We only "serve" to
1485 * to close any socket that chat may have opened.
1488 * 1 : csp = Current client state (buffers, headers, etc...)
1492 *********************************************************************/
1494 void serve(struct client_state *csp)
1495 #else /* ifndef AMIGA */
1496 static void serve(struct client_state *csp)
1497 #endif /* def AMIGA */
1500 close_socket(csp->cfd);
1504 close_socket(csp->sfd);
1507 csp->flags &= ~CSP_FLAG_ACTIVE;
1513 /*********************************************************************
1515 * Function : server_thread
1517 * Description : We only exist to call `serve' in a threaded environment.
1520 * 1 : data = Current client state (buffers, headers, etc...)
1522 * Returns : Always 0.
1524 *********************************************************************/
1525 static int32 server_thread(void *data)
1527 serve((struct client_state *) data);
1534 /*********************************************************************
1538 * Description : Print usage info & exit.
1540 * Parameters : Pointer to argv[0] for identifying ourselves
1544 *********************************************************************/
1545 void usage(const char *myname)
1547 printf("JunkBuster proxy version " VERSION " (" HOME_PAGE_URL ")\n"
1548 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user] [configfile]\n"
1549 "Aborting.\n", myname);
1556 /*********************************************************************
1560 * Description : Load the config file and start the listen loop.
1561 * This function is a lot more *sane* with the `load_config'
1562 * and `listen_loop' functions; although it stills does
1563 * a *little* too much for my taste.
1566 * 1 : argc = Number of parameters (including $0).
1567 * 2 : argv = Array of (char *)'s to the parameters.
1569 * Returns : 1 if : can't open config file, unrecognized directive,
1570 * stats requested in multi-thread mode, can't open the
1571 * log file, can't open the jar file, listen port is invalid,
1572 * any load fails, and can't bind port.
1574 * Else main never returns, the process must be signaled
1575 * to terminate execution. Or, on Windows, use the
1576 * "File", "Exit" menu option.
1578 *********************************************************************/
1580 int real_main(int argc, const char *argv[])
1582 int main(int argc, const char *argv[])
1587 struct passwd *pw = NULL;
1594 #if !defined(_WIN32)
1602 * Parse the command line arguments
1604 while (++argc_pos < argc)
1606 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1608 if (strcmp(argv[argc_pos], "--help") == 0)
1613 else if(strcmp(argv[argc_pos], "--version") == 0)
1615 printf("Junkbuster version " VERSION " (" HOME_PAGE_URL ")\n");
1619 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1624 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1626 if (++argc_pos == argc) usage(argv[0]);
1627 pidfile = strdup(argv[argc_pos]);
1630 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1632 if (++argc_pos == argc) usage(argv[0]);
1633 pw = getpwnam(argv[argc_pos]);
1637 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1640 #endif /* defined(unix) */
1642 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1644 configfile = argv[argc_pos];
1647 } /* -END- while (more arguments) */
1650 if ( *configfile != '/' )
1654 /* make config-filename absolute here */
1655 if ( !(basedir = getcwd( NULL, 1024 )))
1657 perror("get working dir failed");
1661 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1663 perror("malloc failed");
1666 strcpy( abs_file, basedir );
1667 strcat( abs_file, "/" );
1668 strcat( abs_file, configfile );
1669 configfile = abs_file;
1671 #endif /* defined unix */
1678 #elif defined(_WIN32)
1683 * Unix signal handling
1685 * Catch the abort, interrupt and terminate signals for a graceful exit
1686 * Catch the hangup signal so the errlog can be reopened.
1687 * Ignore the broken pipe and child signals
1688 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1690 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1693 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1694 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1696 for (idx = 0; catched_signals[idx] != 0; idx++)
1698 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1700 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1704 for (idx = 0; ignored_signals[idx] != 0; idx++)
1706 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1708 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1713 #else /* ifdef _WIN32 */
1714 # ifdef _WIN_CONSOLE
1716 * We *are* in a windows console app.
1717 * Print a verbose messages about FAQ's and such
1719 printf(win32_blurb);
1720 # endif /* def _WIN_CONSOLE */
1721 #endif /* def _WIN32 */
1724 /* Initialize the CGI subsystem */
1725 cgi_init_error_messages();
1728 * If runnig on unix and without the --nodaemon
1729 * option, become a daemon. I.e. fork, detach
1730 * from tty and get process group leadership
1743 if ( pid < 0 ) /* error */
1748 else if ( pid != 0 ) /* parent */
1753 * must check for errors
1754 * child died due to missing files aso
1757 wpid = waitpid( pid, &status, WNOHANG );
1766 /* Should be more portable, but not as well tested */
1771 #else /* ndef __FreeBSD__ */
1773 #endif /* ndef __FreeBSD__ */
1774 fd = open("/dev/tty", O_RDONLY);
1777 /* no error check here */
1778 ioctl( fd, TIOCNOTTY,0 );
1782 /* FIXME: should close stderr (fd 2) here too, but the test
1784 * and load config file is done in listen_loop() and puts
1785 * some messages on stderr there.
1792 } /* -END- if (!no_daemon) */
1795 * As soon as we have written the PID file, we can switch
1796 * to the user ID indicated by the --user option
1800 if ((NULL != pw) && setuid(pw->pw_uid))
1802 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1806 #endif /* defined unix */
1816 /*********************************************************************
1818 * Function : bind_port_helper
1820 * Description : Bind the listen port. Handles logging, and aborts
1824 * 1 : config = Junkbuster configuration. Specifies port
1827 * Returns : Port that was opened.
1829 *********************************************************************/
1830 static int bind_port_helper(struct configuration_spec * config)
1834 if ( (config->haddr != NULL)
1835 && (config->haddr[0] == '1')
1836 && (config->haddr[1] == '2')
1837 && (config->haddr[2] == '7')
1838 && (config->haddr[3] == '.') )
1840 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1843 else if (config->haddr == NULL)
1845 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1850 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1851 config->hport, config->haddr);
1854 bfd = bind_port(config->haddr, config->hport);
1861 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1862 "There may be another junkbuster or some other "
1863 "proxy running on port %d",
1864 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1865 config->hport, config->hport);
1868 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1869 "The hostname is not resolvable",
1870 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1873 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
1874 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1877 /* shouldn't get here */
1881 config->need_bind = 0;
1887 /*********************************************************************
1889 * Function : listen_loop
1891 * Description : bind the listen port and enter a "FOREVER" listening loop.
1897 *********************************************************************/
1898 static void listen_loop(void)
1900 struct client_state *csp = NULL;
1902 struct configuration_spec * config;
1904 config = load_config();
1906 bfd = bind_port_helper(config);
1910 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1911 while (waitpid(-1, NULL, WNOHANG) > 0)
1913 /* zombie children */
1915 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1918 * Free data that was used by died threads
1924 * Re-open the errlog after HUP signal
1926 if (received_hup_signal)
1928 init_error_log(Argv[0], config->logfile, config->debug);
1929 received_hup_signal = 0;
1933 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1935 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1939 csp->flags |= CSP_FLAG_ACTIVE;
1942 csp->config = config = load_config();
1944 if ( config->need_bind )
1947 * Since we were listening to the "old port", we will not see
1948 * a "listen" param change until the next IJB request. So, at
1949 * least 1 more request must be made for us to find the new
1950 * setting. I am simply closing the old socket and binding the
1953 * Which-ever is correct, we will serve 1 more page via the
1954 * old settings. This should probably be a "show-proxy-args"
1955 * request. This should not be a so common of an operation
1956 * that this will hurt people's feelings.
1961 bfd = bind_port_helper(config);
1964 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1966 if (!accept_connection(csp, bfd))
1968 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1981 log_error(LOG_LEVEL_CONNECT, "OK");
1984 #ifdef FEATURE_TOGGLE
1987 csp->flags |= CSP_FLAG_TOGGLED_ON;
1989 #endif /* def FEATURE_TOGGLE */
1991 if (run_loader(csp))
1993 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1994 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1998 if (block_acl(NULL,csp))
2000 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2001 close_socket(csp->cfd);
2005 #endif /* def FEATURE_ACL */
2007 /* add it to the list of clients */
2008 csp->next = clients->next;
2009 clients->next = csp;
2011 if (config->multi_threaded)
2015 /* this is a switch () statment in the C preprocessor - ugh */
2016 #undef SELECTED_ONE_OPTION
2018 /* Use Pthreads in preference to native code */
2019 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2020 #define SELECTED_ONE_OPTION
2022 pthread_t the_thread;
2023 pthread_attr_t attrs;
2025 pthread_attr_init(&attrs);
2026 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2027 child_id = (pthread_create(&the_thread, &attrs,
2028 (void*)serve, csp) ? -1 : 0);
2029 pthread_attr_destroy(&attrs);
2033 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2034 #define SELECTED_ONE_OPTION
2035 child_id = _beginthread(
2041 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2042 #define SELECTED_ONE_OPTION
2043 child_id = _beginthread(
2050 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2051 #define SELECTED_ONE_OPTION
2053 thread_id tid = spawn_thread
2054 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2056 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2058 child_id = (int) tid;
2067 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2068 #define SELECTED_ONE_OPTION
2069 csp->cfd = ReleaseSocket(csp->cfd, -1);
2070 if((child_id = (int)CreateNewProcTags(
2071 NP_Entry, (ULONG)server_thread,
2072 NP_Output, Output(),
2073 NP_CloseOutput, FALSE,
2074 NP_Name, (ULONG)"junkbuster child",
2075 NP_StackSize, 200*1024,
2079 ((struct Task *)child_id)->tc_UserData = csp;
2080 Signal((struct Task *)child_id, SIGF_SINGLE);
2085 #if !defined(SELECTED_ONE_OPTION)
2088 /* This block is only needed when using fork().
2089 * When using threads, the server thread was
2090 * created and run by the call to _beginthread().
2092 if (child_id == 0) /* child */
2098 else if (child_id > 0) /* parent */
2100 /* in a fork()'d environment, the parent's
2101 * copy of the client socket and the CSP
2105 #if !defined(_WIN32) && defined(__CYGWIN__)
2107 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2108 close_socket(csp->cfd);
2109 csp->flags &= ~CSP_FLAG_ACTIVE;
2113 #undef SELECTED_ONE_OPTION
2114 /* end of cpp switch () */
2116 if (child_id < 0) /* failed */
2118 char buf[BUFFER_SIZE];
2120 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2122 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
2124 write_socket(csp->cfd, buf, strlen(buf));
2125 close_socket(csp->cfd);
2126 csp->flags &= ~CSP_FLAG_ACTIVE;