1 const char jcc_rcs[] = "$Id: jcc.c,v 1.71 2002/03/05 18:13:56 oes Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001 the SourceForge
10 * IJBSWA team. http://ijbswa.sourceforge.net
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
36 * Revision 1.71 2002/03/05 18:13:56 oes
39 * Revision 1.70 2002/03/05 04:52:42 oes
40 * Deleted non-errlog debugging code
42 * Revision 1.69 2002/03/04 23:50:00 jongfoster
43 * Splitting off bind_port() call into bind_port_helper(), with
46 * Revision 1.68 2002/03/04 20:17:32 oes
49 * Revision 1.67 2002/03/04 18:18:57 oes
50 * - Removed _DEBUG mode
51 * - Cleand up cmdline parsing
52 * - Introduced --no-daemon, --pidfile options
53 * - Cleaned up signal handling:
54 * - Terminate cleanly on INT, TERM and ABRT
55 * - Schedule logfile for re-opening on HUP
56 * - Ignore CHLD and PIPE
57 * - Leave the rest with their default handlers
58 * - Uniform handler registration
59 * - Added usage() function
60 * - Played styleguide police
62 * Revision 1.66 2002/03/03 15:06:55 oes
63 * Re-enabled automatic config reloading
65 * Revision 1.65 2002/03/03 14:49:11 oes
66 * Fixed CLF logging: Now uses client's original HTTP request
68 * Revision 1.64 2002/03/03 09:18:03 joergs
69 * Made jumbjuster work on AmigaOS again.
71 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
72 * Clean up a little CRLF unpleasantness that suddenly appeared
74 * Revision 1.62 2002/02/20 23:17:23 jongfoster
75 * Detecting some out-of memory conditions and exiting with a log message.
77 * Revision 1.61 2002/01/17 21:01:52 jongfoster
78 * Moving all our URL and URL pattern parsing code to urlmatch.c.
80 * Revision 1.60 2001/12/30 14:07:32 steudten
81 * - Add signal handling (unix)
82 * - Add SIGHUP handler (unix)
83 * - Add creation of pidfile (unix)
84 * - Add action 'top' in rc file (RH)
85 * - Add entry 'SIGNALS' to manpage
86 * - Add exit message to logfile (unix)
88 * Revision 1.59 2001/12/13 14:07:18 oes
89 * Fixed Bug: 503 error page now sent OK
91 * Revision 1.58 2001/11/30 23:37:24 jongfoster
92 * Renaming the Win32 config file to config.txt - this is almost the
93 * same as the corresponding UNIX name "config"
95 * Revision 1.57 2001/11/16 00:47:43 jongfoster
96 * Changing the tty-disconnection code to use setsid().
98 * Revision 1.56 2001/11/13 20:20:54 jongfoster
99 * Tabs->spaces, fixing a bug with missing {} around an if()
101 * Revision 1.55 2001/11/13 20:14:53 jongfoster
102 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
104 * Revision 1.54 2001/11/07 00:03:14 steudten
105 * Give reliable return value if an error
106 * occurs not just 0 with new daemon mode.
108 * Revision 1.53 2001/11/05 21:41:43 steudten
109 * Add changes to be a real daemon just for unix os.
110 * (change cwd to /, detach from controlling tty, set
111 * process group and session leader to the own process.
113 * Add some fatal-error log message for failed malloc().
114 * Add '-d' if compiled with 'configure --with-debug' to
115 * enable debug output.
117 * Revision 1.52 2001/10/26 20:11:20 jongfoster
118 * Fixing type mismatch
120 * Revision 1.51 2001/10/26 17:38:28 oes
123 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
124 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
125 * threads to call select() simultaneously. So, it's time to do a real, live,
126 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
127 * (native). Both versions will work, but using __OS2__ offers multi-threading.
129 * Revision 1.49 2001/10/23 21:41:35 jongfoster
130 * Added call to initialize the (statically-allocated of course)
131 * "out of memory" CGI response.
133 * Revision 1.48 2001/10/10 19:56:46 jongfoster
134 * Moving some code that wasn't cookie-related out of an #ifdef
137 * Revision 1.47 2001/10/10 16:44:36 oes
138 * Added CONNECT destination port limitation check
140 * Revision 1.46 2001/10/08 15:17:41 oes
141 * Re-enabled SSL forwarding
143 * Revision 1.45 2001/10/07 15:42:11 oes
144 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
146 * Moved downgrading of the HTTP version from parse_http_request to
147 * chat(), since we can't decide if it is necessary before we have
148 * determined the actions for the URL. The HTTP command is now
149 * *always* re-built so the repairs need no longer be special-cased.
151 * filter_popups now gets a csp pointer so it can raise the new
152 * CSP_FLAG_MODIFIED flag.
156 * Added configurable size limit for the IOB. If the IOB grows so
157 * large that the next read would exceed the limit, the header
158 * is generated, and the header & unfiltered buffer are flushed
159 * to the client. Chat then continues in non-buffering,
160 * non-filtering body mode.
162 * Revision 1.44 2001/10/02 18:13:57 oes
165 * Revision 1.43 2001/10/02 15:32:13 oes
166 * Moved generation of hdr
168 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
169 * Cleaning up 2 compiler warnings on OS/2.
171 * Revision 1.41 2001/09/16 17:05:14 jongfoster
172 * Removing unused #include showarg.h
174 * Revision 1.40 2001/09/16 15:41:45 jongfoster
175 * Fixing signed/unsigned comparison warning.
177 * Revision 1.39 2001/09/16 13:21:27 jongfoster
178 * Changes to use new list functions.
180 * Revision 1.38 2001/09/16 13:01:46 jongfoster
181 * Removing redundant function call that zeroed zalloc()'d memory.
183 * Revision 1.37 2001/09/10 11:12:24 oes
184 * Deleted unused variable
186 * Revision 1.36 2001/09/10 10:56:15 oes
187 * Silenced compiler warnings
189 * Revision 1.35 2001/07/31 14:44:22 oes
190 * Deleted unused size parameter from filter_popups()
192 * Revision 1.34 2001/07/30 22:08:36 jongfoster
193 * Tidying up #defines:
194 * - All feature #defines are now of the form FEATURE_xxx
195 * - Permanently turned off WIN_GUI_EDIT
196 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
198 * Revision 1.33 2001/07/29 19:32:00 jongfoster
199 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
201 * Revision 1.32 2001/07/29 18:47:05 jongfoster
202 * Adding missing #include "loadcfg.h"
204 * Revision 1.31 2001/07/29 12:17:48 oes
205 * Applied pthread fix by Paul Lieverse
207 * Revision 1.30 2001/07/25 22:57:13 jongfoster
208 * __BEOS__ no longer overrides FEATURE_PTHREAD.
209 * This is because FEATURE_PTHREAD will soon be widely used, so I
210 * want to keep it simple.
212 * Revision 1.29 2001/07/24 12:47:06 oes
213 * Applied BeOS support update by Eugenia
215 * Revision 1.28 2001/07/23 13:26:12 oes
216 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
218 * Revision 1.27 2001/07/19 19:09:47 haroon
219 * - Added code to take care of the situation where while processing the first
220 * server response (which includes the server header), after finding the end
221 * of the headers we were not looking past the end of the headers for
222 * content modification. I enabled it for filter_popups.
223 * Someone else should look to see if other similar operations should be
224 * done to the discarded portion of the buffer.
226 * Note 2001/07/20: No, the other content modification mechanisms will process
227 * the whole iob later anyway. --oes
229 * Revision 1.26 2001/07/18 12:31:36 oes
232 * Revision 1.25 2001/07/15 19:43:49 jongfoster
233 * Supports POSIX threads.
234 * Also removed some unused #includes.
236 * Revision 1.24 2001/07/13 14:00:40 oes
237 * - Generic content modification scheme:
238 * Each feature has its own applicability flag that is set
239 * from csp->action->flags.
240 * Replaced the "filtering" int flag , by a function pointer
241 * "content_filter" to the function that will do the content
242 * modification. If it is != NULL, the document will be buffered
243 * and processed through *content_filter, which must set
244 * csp->content_length and return a modified copy of the body
245 * or return NULL (on failiure).
246 * - Changed csp->is_text to the more generic bitmap csp->content_type
247 * which can currently take the valued CT_TEXT or CT_GIF
249 * - Removed all #ifdef PCRS
251 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
252 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
253 * the `block_acl' call. This prevents a compilation error when the user
254 * does not wish to use the "ACL" feature.
256 * Revision 1.22 2001/06/29 21:45:41 oes
257 * Indentation, CRLF->LF, Tab-> Space
259 * Revision 1.21 2001/06/29 13:29:36 oes
260 * - Cleaned up, improved comments
261 * - Unified all possible interceptors (CGI,
262 * block, trust, fast_redirect) in one
263 * place, with one (CGI) answer generation
264 * mechansim. Much clearer now.
265 * - Removed the GIF image generation, which
266 * is now done in filters.c:block_url()
267 * - Made error conditions like domain lookup
268 * failiure or (various) problems while talking
269 * to the server use cgi.c:error_response()
270 * instead of generating HTML/HTTP in chat() (yuck!)
271 * - Removed logentry from cancelled commit
273 * Revision 1.20 2001/06/09 10:55:28 jongfoster
274 * Changing BUFSIZ ==> BUFFER_SIZE
276 * Revision 1.19 2001/06/07 23:12:52 jongfoster
277 * Replacing function pointer in struct gateway with a directly
278 * called function forwarded_connect().
279 * Replacing struct gateway with struct forward_spec
281 * Revision 1.18 2001/06/03 19:12:16 oes
282 * introduced new cgi handling
284 * Revision 1.17 2001/06/01 20:07:23 jongfoster
285 * Now uses action +image-blocker{} rather than config->tinygif
287 * Revision 1.16 2001/06/01 18:49:17 jongfoster
288 * Replaced "list_share" with "list" - the tiny memory gain was not
289 * worth the extra complexity.
291 * Revision 1.15 2001/05/31 21:24:47 jongfoster
292 * Changed "permission" to "action" throughout.
293 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
294 * Moved vanilla wafer check into chat(), since we must now
295 * decide whether or not to add it based on the URL.
297 * Revision 1.14 2001/05/29 20:14:01 joergs
298 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
301 * Revision 1.13 2001/05/29 09:50:24 jongfoster
302 * Unified blocklist/imagelist/permissionslist.
303 * File format is still under discussion, but the internal changes
306 * Also modified interceptor behaviour:
307 * - We now intercept all URLs beginning with one of the following
308 * prefixes (and *only* these prefixes):
310 * * http://ijbswa.sf.net/config/
311 * * http://ijbswa.sourceforge.net/config/
312 * - New interceptors "home page" - go to http://i.j.b/ to see it.
313 * - Internal changes so that intercepted and fast redirect pages
314 * are not replaced with an image.
315 * - Interceptors now have the option to send a binary page direct
316 * to the client. (i.e. ijb-send-banner uses this)
317 * - Implemented show-url-info interceptor. (Which is why I needed
318 * the above interceptors changes - a typical URL is
319 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
320 * The previous mechanism would not have intercepted that, and
321 * if it had been intercepted then it then it would have replaced
324 * Revision 1.12 2001/05/27 22:17:04 oes
326 * - re_process_buffer no longer writes the modified buffer
327 * to the client, which was very ugly. It now returns the
328 * buffer, which it is then written by chat.
330 * - content_length now adjusts the Content-Length: header
331 * for modified documents rather than crunch()ing it.
332 * (Length info in csp->content_length, which is 0 for
333 * unmodified documents)
335 * - For this to work, sed() is called twice when filtering.
337 * Revision 1.11 2001/05/26 17:27:53 jongfoster
338 * Added support for CLF and fixed LOG_LEVEL_LOG.
339 * Also did CRLF->LF fix of my previous patch.
341 * Revision 1.10 2001/05/26 15:26:15 jongfoster
342 * ACL feature now provides more security by immediately dropping
343 * connections from untrusted hosts.
345 * Revision 1.9 2001/05/26 00:28:36 jongfoster
346 * Automatic reloading of config file.
347 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
348 * Most of the global variables have been moved to a new
349 * struct configuration_spec, accessed through csp->config->globalname
350 * Most of the globals remaining are used by the Win32 GUI.
352 * Revision 1.8 2001/05/25 22:43:18 jongfoster
353 * Fixing minor memory leak and buffer overflow.
355 * Revision 1.7 2001/05/25 22:34:30 jongfoster
358 * Revision 1.6 2001/05/23 00:13:58 joergs
359 * AmigaOS support fixed.
361 * Revision 1.5 2001/05/22 18:46:04 oes
363 * - Enabled filtering banners by size rather than URL
364 * by adding patterns that replace all standard banner
365 * sizes with the "Junkbuster" gif to the re_filterfile
367 * - Enabled filtering WebBugs by providing a pattern
368 * which kills all 1x1 images
370 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
371 * which is selected by the (nonstandard and therefore
372 * capital) letter 'U' in the option string.
373 * It causes the quantifiers to be ungreedy by default.
374 * Appending a ? turns back to greedy (!).
376 * - Added a new interceptor ijb-send-banner, which
377 * sends back the "Junkbuster" gif. Without imagelist or
378 * MSIE detection support, or if tinygif = 1, or the
379 * URL isn't recognized as an imageurl, a lame HTML
380 * explanation is sent instead.
382 * - Added new feature, which permits blocking remote
383 * script redirects and firing back a local redirect
385 * The feature is conditionally compiled, i.e. it
386 * can be disabled with --disable-fast-redirects,
387 * plus it must be activated by a "fast-redirects"
388 * line in the config file, has its own log level
389 * and of course wants to be displayed by show-proxy-args
390 * Note: Boy, all the #ifdefs in 1001 locations and
391 * all the fumbling with configure.in and acconfig.h
392 * were *way* more work than the feature itself :-(
394 * - Because a generic redirect template was needed for
395 * this, tinygif = 3 now uses the same.
397 * - Moved GIFs, and other static HTTP response templates
402 * - Removed some >400 CRs again (Jon, you really worked
405 * Revision 1.4 2001/05/21 19:34:01 jongfoster
406 * Made failure to bind() a fatal error.
408 * Revision 1.3 2001/05/20 01:21:20 jongfoster
409 * Version 2.9.4 checkin.
410 * - Merged popupfile and cookiefile, and added control over PCRS
411 * filtering, in new "permissionsfile".
412 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
413 * file error you now get a message box (in the Win32 GUI) rather
414 * than the program exiting with no explanation.
415 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
417 * - Removed tabs from "config"
418 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
419 * - Bumped up version number.
421 * Revision 1.2 2001/05/17 22:34:44 oes
422 * - Added hint on GIF char array generation to jcc.c
423 * - Cleaned CRLF's from the sources and related files
424 * - Repaired logging for REF and FRC
426 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
427 * Initial import of version 2.9.3 source tree
430 *********************************************************************/
436 #include <sys/types.h>
443 #ifdef FEATURE_PTHREAD
445 #endif /* def FEATURE_PTHREAD */
448 # ifndef FEATURE_PTHREAD
449 # include <windows.h>
450 # include <process.h>
451 # endif /* ndef FEATURE_PTHREAD */
454 # ifndef _WIN_CONSOLE
456 # endif /* ndef _WIN_CONSOLE */
458 #else /* ifndef _WIN32 */
460 # if !defined (__OS2__)
462 # include <sys/wait.h>
463 # endif /* ndef __OS2__ */
464 # include <sys/time.h>
465 # include <sys/stat.h>
466 # include <sys/ioctl.h>
469 #include <sys/termios.h>
479 # include <socket.h> /* BeOS has select() for sockets only. */
480 # include <OS.h> /* declarations for threads and stuff. */
483 # if defined(__EMX__) || defined(__OS2__)
484 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
489 #define bzero(B,N) memset(B,0x00,n)
504 #include "killpopup.h"
505 #include "miscutil.h"
507 #include "jbsockets.h"
512 #include "urlmatch.h"
514 const char jcc_h_rcs[] = JCC_H_VERSION;
515 const char project_h_rcs[] = PROJECT_H_VERSION;
518 struct client_state clients[1];
519 struct file_list files[1];
521 #ifdef FEATURE_STATISTICS
522 int urls_read = 0; /* total nr of urls read inc rejected */
523 int urls_rejected = 0; /* total nr of urls rejected */
524 #endif /* def FEATURE_STATISTICS */
527 static void listen_loop(void);
528 static void chat(struct client_state *csp);
530 void serve(struct client_state *csp);
531 #else /* ifndef AMIGA */
532 static void serve(struct client_state *csp);
533 #endif /* def AMIGA */
536 static int32 server_thread(void *data);
537 #endif /* def __BEOS__ */
540 #define sleep(N) Sleep(((N) * 1000))
544 #define sleep(N) DosSleep(((N) * 100))
549 const char *pidfile = NULL;
550 int received_hup_signal = 0;
551 #endif /* defined unix */
553 /* The vanilla wafer. */
554 static const char VANILLA_WAFER[] =
555 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
556 "Do_not_send_me_any_copyrighted_information_other_than_the_"
557 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
558 "In_particular_do_not_send_me_any_cookies_that_"
559 "are_subject_to_a_claim_of_copyright_by_anybody._"
560 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
561 "(copyright_or_otherwise)_applying_to_any_cookie._";
564 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
565 /*********************************************************************
567 * Function : sig_handler
569 * Description : Signal handler for different signals.
570 * Exit gracefully on ABRT, TERM and INT
571 * or set a flag that will cause the errlog
572 * to be reopened by the main thread on HUP.
575 * 1 : the_signal - the signal cause this function to call
579 *********************************************************************/
580 static void sig_handler(int the_signal)
587 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
595 received_hup_signal = 1;
600 * We shouldn't be here, unless we catch signals
601 * in main() that we can't handle here!
603 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
611 /*********************************************************************
615 * Description : Once a connection to the client has been accepted,
616 * this function is called (via serve()) to handle the
617 * main business of the communication. When this
618 * function returns, the caller must close the client
622 * 1 : csp = Current client state (buffers, headers, etc...)
624 * Returns : On success, the number of bytes written are returned (zero
625 * indicates nothing was written). On error, -1 is returned,
626 * and errno is set appropriately. If count is zero and the
627 * file descriptor refers to a regular file, 0 will be
628 * returned without causing any other effect. For a special
629 * file, the results are not portable.
631 *********************************************************************/
632 static void chat(struct client_state *csp)
635 * This next lines are a little ugly, but they simplifies the if statements
636 * below. Basically if TOGGLE, then we want the if to test if the
637 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
638 * then we want the if to test for CSP_FLAG_FORCED , else we don't
640 #ifdef FEATURE_TOGGLE
641 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
642 #else /* ifndef FEATURE_TOGGLE */
643 # define IS_TOGGLED_ON_AND
644 #endif /* ndef FEATURE_TOGGLE */
645 #ifdef FEATURE_FORCE_LOAD
646 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
647 #else /* ifndef FEATURE_FORCE_LOAD */
648 # define IS_NOT_FORCED_AND
649 #endif /* def FEATURE_FORCE_LOAD */
651 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
653 char buf[BUFFER_SIZE];
656 int n, maxfd, server_body;
657 int ms_iis5_hack = 0;
659 const struct forward_spec * fwd;
660 struct http_request *http;
661 #ifdef FEATURE_KILL_POPUPS
662 int block_popups; /* bool, 1==will block popups */
663 int block_popups_now = 0; /* bool, 1==currently blocking popups */
664 #endif /* def FEATURE_KILL_POPUPS */
666 int pcrs_filter; /* bool, 1==will filter through pcrs */
667 int gif_deanimate; /* bool, 1==will deanimate gifs */
669 /* Function that does the content filtering for the current request */
670 char *(*content_filter)() = NULL;
672 /* Skeleton for HTTP response, if we should intercept the request */
673 struct http_response *rsp;
678 * Read the client's request. Note that since we're not using select() we
679 * could get blocked here if a client connected, then didn't say anything!
684 n = read_socket(csp->cfd, buf, sizeof(buf));
686 if (n <= 0) break; /* error! */
688 add_to_iob(csp, buf, n);
690 req = get_header(csp);
694 break; /* no HTTP request! */
699 continue; /* more to come! */
702 #ifdef FEATURE_FORCE_LOAD
703 /* If this request contains the FORCE_PREFIX,
704 * better get rid of it now and set the force flag --oes
707 if (strstr(req, FORCE_PREFIX))
709 strclean(req, FORCE_PREFIX);
710 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
711 csp->flags |= CSP_FLAG_FORCED;
714 #endif /* def FEATURE_FORCE_LOAD */
716 parse_http_request(req, http, csp);
721 if (http->cmd == NULL)
723 strcpy(buf, CHEADER);
724 write_socket(csp->cfd, buf, strlen(buf));
726 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
731 /* decide how to route the HTTP request */
733 if ((fwd = forward_url(http, csp)) == NULL)
735 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
736 /* Never get here - LOG_LEVEL_FATAL causes program exit */
739 /* build the http request to send to the server
740 * we have to do one of the following:
742 * create = use the original HTTP request to create a new
743 * HTTP request that has either the path component
744 * without the http://domainspec (w/path) or the
745 * full orininal URL (w/url)
746 * Note that the path and/or the HTTP version may
747 * have been altered by now.
749 * connect = Open a socket to the host:port of the server
750 * and short-circuit server and client socket.
752 * pass = Pass the request unchanged if forwarding a CONNECT
753 * request to a parent proxy. Note that we'll be sending
754 * the CFAIL message ourselves if connecting to the parent
755 * fails, but we won't send a CSUCCEED message if it works,
756 * since that would result in a double message (ours and the
757 * parent's). After sending the request to the parent, we simply
763 * +--------+--------+
765 * 0 | create | connect|
767 * Forwarding +--------+--------+
769 * 1 | create | pass |
771 * +--------+--------+
776 * Determine the actions for this URL
778 #ifdef FEATURE_TOGGLE
779 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
781 /* Most compatible set of actions (i.e. none) */
782 init_current_action(csp->action);
785 #endif /* ndef FEATURE_TOGGLE */
787 url_actions(http, csp);
792 * Check if a CONNECT request is allowable:
793 * In the absence of a +limit-connect action, allow only port 443.
794 * If there is an action, allow whatever matches the specificaton.
798 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
799 || (csp->action->flags & ACTION_LIMIT_CONNECT
800 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
802 strcpy(buf, CFORBIDDEN);
803 write_socket(csp->cfd, buf, strlen(buf));
805 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
806 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
814 * Downgrade http version from 1.1 to 1.0 if +downgrade
817 if ( (http->ssl == 0)
818 && (!strcmpic(http->ver, "HTTP/1.1"))
819 && (csp->action->flags & ACTION_DOWNGRADE))
822 http->ver = strdup("HTTP/1.0");
824 if (http->ver == NULL)
826 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
831 * Save a copy of the original request for logging
833 http->ocmd = strdup(http->cmd);
835 if (http->ocmd == NULL)
837 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
841 * (Re)build the HTTP request for non-SSL requests.
842 * If forwarding, use the whole URL, else, use only the path.
848 http->cmd = strdup(http->gpc);
849 string_append(&http->cmd, " ");
851 if (fwd->forward_host)
853 string_append(&http->cmd, http->url);
857 string_append(&http->cmd, http->path);
860 string_append(&http->cmd, " ");
861 string_append(&http->cmd, http->ver);
863 if (http->cmd == NULL)
865 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
868 enlist(csp->headers, http->cmd);
871 #ifdef FEATURE_COOKIE_JAR
873 * If we're logging cookies in a cookie jar, and the user has not
874 * supplied any wafers, and the user has not told us to suppress the
875 * vanilla wafer, then send the vanilla wafer.
877 if ((csp->config->jarfile != NULL)
878 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
879 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
881 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
883 #endif /* def FEATURE_COOKIE_JAR */
886 #ifdef FEATURE_KILL_POPUPS
887 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
888 #endif /* def FEATURE_KILL_POPUPS */
890 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
891 ((csp->action->flags & ACTION_FILTER) != 0);
893 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
895 /* grab the rest of the client's headers */
899 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
901 n = read_socket(csp->cfd, buf, sizeof(buf));
904 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
907 add_to_iob(csp, buf, n);
911 if (p == NULL) break;
913 enlist(csp->headers, p);
917 * We have a request. Now, check to see if we need to
918 * intercept it, i.e. If ..
922 /* a CGI call was detected and answered */
923 (NULL != (rsp = dispatch_cgi(csp)))
925 /* or we are enabled and... */
928 /* ..the request was blocked */
929 ( NULL != (rsp = block_url(csp)))
933 || ( NULL != (rsp = trust_url(csp)))
934 #endif /* def FEATURE_TRUST */
936 /* ..or a fast redirect kicked in */
937 #ifdef FEATURE_FAST_REDIRECTS
938 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
939 (NULL != (rsp = redirect_url(csp))))
940 #endif /* def FEATURE_FAST_REDIRECTS */
944 /* Write the answer to the client */
945 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
946 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
948 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
951 #ifdef FEATURE_STATISTICS
952 /* Count as a rejected request */
953 csp->flags |= CSP_FLAG_REJECTED;
954 #endif /* def FEATURE_STATISTICS */
956 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
957 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
958 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
960 /* Clean up and return */
961 free_http_response(rsp);
965 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
967 if (fwd->forward_host)
969 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
970 fwd->forward_host, fwd->forward_port, http->hostport);
974 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
977 /* here we connect to the server, gateway, or the forwarder */
979 csp->sfd = forwarded_connect(fwd, http, csp);
983 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
988 rsp = error_response(csp, "no-such-domain", errno);
990 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
991 csp->ip_addr_str, http->ocmd);
995 rsp = error_response(csp, "connect-failed", errno);
997 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
998 csp->ip_addr_str, http->ocmd);
1002 /* Write the answer to the client */
1005 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1006 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1008 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1012 free_http_response(rsp);
1016 log_error(LOG_LEVEL_CONNECT, "OK");
1018 hdr = sed(client_patterns, add_client_headers, csp);
1021 /* FIXME Should handle error properly */
1022 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1025 list_remove_all(csp->headers);
1027 if (fwd->forward_host || (http->ssl == 0))
1029 /* write the client's (modified) header to the server
1030 * (along with anything else that may be in the buffer)
1035 if ((write_socket(csp->sfd, hdr, n) != n)
1036 || (flush_socket(csp->sfd, csp ) < 0))
1038 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1041 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1042 csp->ip_addr_str, http->ocmd);
1044 rsp = error_response(csp, "connect-failed", errno);
1048 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1049 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1051 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1055 free_http_response(rsp);
1063 * We're running an SSL tunnel and we're not forwarding,
1064 * so just send the "connect succeeded" message to the
1065 * client, flush the rest, and get out of the way.
1067 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1068 csp->ip_addr_str, http->ocmd);
1070 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
1078 /* we're finished with the client's header */
1081 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1083 /* pass data between the client and server
1084 * until one or the other shuts down the connection.
1093 FD_SET(csp->cfd, &rfds);
1094 FD_SET(csp->sfd, &rfds);
1096 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1100 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1104 /* this is the body of the browser's request
1105 * just read it and write it.
1108 if (FD_ISSET(csp->cfd, &rfds))
1110 n = read_socket(csp->cfd, buf, sizeof(buf));
1114 break; /* "game over, man" */
1117 if (write_socket(csp->sfd, buf, n) != n)
1119 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1126 * The server wants to talk. It could be the header or the body.
1127 * If `hdr' is null, then it's the header otherwise it's the body.
1128 * FIXME: Does `hdr' really mean `host'? No.
1132 if (FD_ISSET(csp->sfd, &rfds))
1135 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1139 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1141 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1142 csp->ip_addr_str, http->ocmd);
1144 rsp = error_response(csp, "connect-failed", errno);
1148 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1149 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1151 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1155 free_http_response(rsp);
1159 /* Add a trailing zero. This lets filter_popups
1160 * use string operations.
1164 #ifdef FEATURE_KILL_POPUPS
1165 /* Filter the popups on this read. */
1166 if (block_popups_now)
1168 filter_popups(buf, csp);
1170 #endif /* def FEATURE_KILL_POPUPS */
1172 /* Normally, this would indicate that we've read
1173 * as much as the server has sent us and we can
1174 * close the client connection. However, Microsoft
1175 * in its wisdom has released IIS/5 with a bug that
1176 * prevents it from sending the trailing \r\n in
1177 * a 302 redirect header (and possibly other headers).
1178 * To work around this if we've haven't parsed
1179 * a full header we'll append a trailing \r\n
1180 * and see if this now generates a valid one.
1182 * This hack shouldn't have any impacts. If we've
1183 * already transmitted the header or if this is a
1184 * SSL connection, then we won't bother with this
1185 * hack. So we only work on partially received
1186 * headers. If we append a \r\n and this still
1187 * doesn't generate a valid header, then we won't
1188 * transmit anything to the client.
1193 if (server_body || http->ssl)
1196 * If we have been buffering up the document,
1197 * now is the time to apply content modification
1198 * and send the result to the client.
1203 * If the content filter fails, use the original
1204 * buffer and length.
1205 * (see p != NULL ? p : csp->iob->cur below)
1207 if (NULL == (p = (*content_filter)(csp)))
1209 csp->content_length = csp->iob->eod - csp->iob->cur;
1212 hdr = sed(server_patterns, add_server_headers, csp);
1215 /* FIXME Should handle error properly */
1216 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1221 if ((write_socket(csp->cfd, hdr, n) != n)
1222 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1224 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1234 break; /* "game over, man" */
1238 * This is NOT the body, so
1239 * Let's pretend the server just sent us a blank line.
1241 n = sprintf(buf, "\r\n");
1244 * Now, let the normal header parsing algorithm below do its
1245 * job. If it fails, we'll exit instead of continuing.
1252 * If this is an SSL connection or we're in the body
1253 * of the server document, just write it to the client,
1254 * unless we need to buffer the body for later content-filtering
1257 if (server_body || http->ssl)
1261 add_to_iob(csp, buf, n);
1264 * If the buffer limit will be reached on the next read,
1265 * switch to non-filtering mode, i.e. make & write the
1266 * header, flush the socket and get out of the way.
1268 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1270 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1272 hdr = sed(server_patterns, add_server_headers, csp);
1275 /* FIXME Should handle error properly */
1276 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1282 if (((write_socket(csp->cfd, hdr, n) != n)
1283 || (n = flush_socket(csp->cfd, csp) < 0)))
1285 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1294 content_filter = NULL;
1301 if (write_socket(csp->cfd, buf, n) != n)
1303 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1312 /* we're still looking for the end of the
1313 * server's header ... (does that make header
1314 * parsing an "out of body experience" ?
1317 /* buffer up the data we just read */
1318 add_to_iob(csp, buf, n);
1320 /* get header lines from the iob */
1322 while ((p = get_header(csp)))
1326 /* see following note */
1329 enlist(csp->headers, p);
1333 /* NOTE: there are no "empty" headers so
1334 * if the pointer `p' is not NULL we must
1335 * assume that we reached the end of the
1336 * buffer before we hit the end of the header.
1343 /* Well, we tried our MS IIS/5
1344 * hack and it didn't work.
1345 * The header is incomplete
1346 * and there isn't anything
1347 * we can do about it.
1353 /* Since we have to wait for
1354 * more from the server before
1355 * we can parse the headers
1356 * we just continue here.
1362 /* we have now received the entire header.
1363 * filter it and send the result to the client
1366 hdr = sed(server_patterns, add_server_headers, csp);
1369 /* FIXME Should handle error properly */
1370 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1375 /* write the server's (modified) header to
1376 * the client (along with anything else that
1377 * may be in the buffer)
1380 #ifdef FEATURE_KILL_POPUPS
1381 /* Start blocking popups if appropriate. */
1383 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1384 !http->ssl && /* We talk plaintext */
1385 block_popups) /* Policy allows */
1387 block_popups_now = 1;
1389 * Filter the part of the body that came in the same read
1390 * as the last headers:
1392 filter_popups(csp->iob->cur, csp);
1395 #endif /* def FEATURE_KILL_POPUPS */
1397 /* Buffer and pcrs filter this if appropriate. */
1399 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1400 !http->ssl && /* We talk plaintext */
1401 pcrs_filter) /* Policy allows */
1403 content_filter = pcrs_filter_response;
1406 /* Buffer and gif_deanimate this if appropriate. */
1408 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1409 !http->ssl && /* We talk plaintext */
1410 gif_deanimate) /* Policy allows */
1412 content_filter = gif_deanimate_response;
1417 * Only write if we're not buffering for content modification
1419 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1420 || (n = flush_socket(csp->cfd, csp) < 0)))
1422 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1424 /* the write failed, so don't bother
1425 * mentioning it to the client...
1426 * it probably can't hear us anyway.
1432 if(!content_filter) byte_count += n;
1434 /* we're finished with the server's header */
1439 /* If this was a MS IIS/5 hack then it means
1440 * the server has already closed the
1441 * connection. Nothing more to read. Time
1452 return; /* huh? we should never get here */
1455 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1456 csp->ip_addr_str, http->ocmd, byte_count);
1460 /*********************************************************************
1464 * Description : This is little more than chat. We only "serve" to
1465 * to close any socket that chat may have opened.
1468 * 1 : csp = Current client state (buffers, headers, etc...)
1472 *********************************************************************/
1474 void serve(struct client_state *csp)
1475 #else /* ifndef AMIGA */
1476 static void serve(struct client_state *csp)
1477 #endif /* def AMIGA */
1480 close_socket(csp->cfd);
1484 close_socket(csp->sfd);
1487 csp->flags &= ~CSP_FLAG_ACTIVE;
1493 /*********************************************************************
1495 * Function : server_thread
1497 * Description : We only exist to call `serve' in a threaded environment.
1500 * 1 : data = Current client state (buffers, headers, etc...)
1502 * Returns : Always 0.
1504 *********************************************************************/
1505 static int32 server_thread(void *data)
1507 serve((struct client_state *) data);
1514 /*********************************************************************
1518 * Description : Print usage info & exit.
1520 * Parameters : Pointer to argv[0] for identifying ourselves
1524 *********************************************************************/
1525 void usage(const char *myname)
1527 printf("JunkBuster proxy version " VERSION " (" HOME_PAGE_URL ")\n"
1528 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user] [configfile]\n"
1529 "Aborting.\n", myname);
1536 /*********************************************************************
1540 * Description : Load the config file and start the listen loop.
1541 * This function is a lot more *sane* with the `load_config'
1542 * and `listen_loop' functions; although it stills does
1543 * a *little* too much for my taste.
1546 * 1 : argc = Number of parameters (including $0).
1547 * 2 : argv = Array of (char *)'s to the parameters.
1549 * Returns : 1 if : can't open config file, unrecognized directive,
1550 * stats requested in multi-thread mode, can't open the
1551 * log file, can't open the jar file, listen port is invalid,
1552 * any load fails, and can't bind port.
1554 * Else main never returns, the process must be signaled
1555 * to terminate execution. Or, on Windows, use the
1556 * "File", "Exit" menu option.
1558 *********************************************************************/
1560 int real_main(int argc, const char *argv[])
1562 int main(int argc, const char *argv[])
1572 #if !defined(_WIN32)
1580 * Parse the command line arguments
1582 while (++argc_pos < argc)
1584 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1586 if (strcmp(argv[argc_pos], "--help") == 0)
1591 else if(strcmp(argv[argc_pos], "--version") == 0)
1593 printf("Junkbuster version " VERSION " (" HOME_PAGE_URL ")\n");
1597 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1601 #if !defined(__OS2__)
1602 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1604 if (++argc_pos == argc) usage(argv[0]);
1605 pidfile = strdup(argv[argc_pos]);
1608 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1610 if (++argc_pos == argc) usage(argv[0]);
1611 pw = getpwnam(argv[argc_pos]);
1615 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1618 #endif /* !defined(__OS2__) */
1620 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1622 configfile = argv[argc_pos];
1625 } /* -END- while (more arguments) */
1628 if ( *configfile != '/' )
1632 /* make config-filename absolute here */
1633 if ( !(basedir = getcwd( NULL, 1024 )))
1635 perror("get working dir failed");
1639 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1641 perror("malloc failed");
1644 strcpy( abs_file, basedir );
1645 strcat( abs_file, "/" );
1646 strcat( abs_file, configfile );
1647 configfile = abs_file;
1649 #endif /* defined unix */
1656 #elif defined(_WIN32)
1661 * Unix signal handling
1663 * Catch the abort, interrupt and terminate signals for a graceful exit
1664 * Catch the hangup signal so the errlog can be reopened.
1665 * Ignore the broken pipe and child signals
1666 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1668 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1671 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1672 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1674 for (idx = 0; catched_signals[idx] != 0; idx++)
1676 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1678 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1682 for (idx = 0; ignored_signals[idx] != 0; idx++)
1684 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1686 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1691 #else /* ifdef _WIN32 */
1692 # ifdef _WIN_CONSOLE
1694 * We *are* in a windows console app.
1695 * Print a verbose messages about FAQ's and such
1697 printf(win32_blurb);
1698 # endif /* def _WIN_CONSOLE */
1699 #endif /* def _WIN32 */
1702 /* Initialize the CGI subsystem */
1703 cgi_init_error_messages();
1706 * If runnig on unix and without the --nodaemon
1707 * option, become a daemon. I.e. fork, detach
1708 * from tty and get process group leadership
1721 if ( pid < 0 ) /* error */
1726 else if ( pid != 0 ) /* parent */
1731 * must check for errors
1732 * child died due to missing files aso
1735 wpid = waitpid( pid, &status, WNOHANG );
1744 /* Should be more portable, but not as well tested */
1749 #else /* ndef __FreeBSD__ */
1751 #endif /* ndef __FreeBSD__ */
1752 fd = open("/dev/tty", O_RDONLY);
1755 /* no error check here */
1756 ioctl( fd, TIOCNOTTY,0 );
1760 /* FIXME: should close stderr (fd 2) here too, but the test
1762 * and load config file is done in listen_loop() and puts
1763 * some messages on stderr there.
1770 } /* -END- if (!no_daemon) */
1773 * As soon as we have written the PID file, we can switch
1774 * to the user ID indicated by the --user option
1778 if (setuid(pw->pw_uid))
1780 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1784 #endif /* defined unix */
1794 /*********************************************************************
1796 * Function : bind_port_helper
1798 * Description : Bind the listen port. Handles logging, and aborts
1802 * 1 : config = Junkbuster configuration. Specifies port
1805 * Returns : Port that was opened.
1807 *********************************************************************/
1808 static int bind_port_helper(struct configuration_spec * config)
1812 if ( (config->haddr != NULL)
1813 && (config->haddr[0] == '1')
1814 && (config->haddr[1] == '2')
1815 && (config->haddr[2] == '7')
1816 && (config->haddr[3] == '.') )
1818 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1821 else if (config->haddr == NULL)
1823 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1828 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1829 config->hport, config->haddr);
1832 bfd = bind_port(config->haddr, config->hport);
1836 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1837 "- There may be another junkbuster or some other "
1838 "proxy running on port %d",
1839 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1840 config->hport, config->hport
1842 /* shouldn't get here */
1846 config->need_bind = 0;
1852 /*********************************************************************
1854 * Function : listen_loop
1856 * Description : bind the listen port and enter a "FOREVER" listening loop.
1862 *********************************************************************/
1863 static void listen_loop(void)
1865 struct client_state *csp = NULL;
1867 struct configuration_spec * config;
1869 config = load_config();
1871 bfd = bind_port_helper(config);
1875 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1876 while (waitpid(-1, NULL, WNOHANG) > 0)
1878 /* zombie children */
1880 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1883 * Free data that was used by died threads
1889 * Re-open the errlog after HUP signal
1891 if (received_hup_signal)
1893 init_error_log(Argv[0], config->logfile, config->debug);
1894 received_hup_signal = 0;
1898 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1900 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1904 csp->flags |= CSP_FLAG_ACTIVE;
1907 csp->config = config = load_config();
1909 if ( config->need_bind )
1912 * Since we were listening to the "old port", we will not see
1913 * a "listen" param change until the next IJB request. So, at
1914 * least 1 more request must be made for us to find the new
1915 * setting. I am simply closing the old socket and binding the
1918 * Which-ever is correct, we will serve 1 more page via the
1919 * old settings. This should probably be a "show-proxy-args"
1920 * request. This should not be a so common of an operation
1921 * that this will hurt people's feelings.
1926 bfd = bind_port_helper(config);
1929 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1931 if (!accept_connection(csp, bfd))
1933 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1946 log_error(LOG_LEVEL_CONNECT, "OK");
1949 #ifdef FEATURE_TOGGLE
1952 csp->flags |= CSP_FLAG_TOGGLED_ON;
1954 #endif /* def FEATURE_TOGGLE */
1956 if (run_loader(csp))
1958 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1959 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1963 if (block_acl(NULL,csp))
1965 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1966 close_socket(csp->cfd);
1970 #endif /* def FEATURE_ACL */
1972 /* add it to the list of clients */
1973 csp->next = clients->next;
1974 clients->next = csp;
1976 if (config->multi_threaded)
1980 /* this is a switch () statment in the C preprocessor - ugh */
1981 #undef SELECTED_ONE_OPTION
1983 /* Use Pthreads in preference to native code */
1984 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1985 #define SELECTED_ONE_OPTION
1987 pthread_t the_thread;
1988 pthread_attr_t attrs;
1990 pthread_attr_init(&attrs);
1991 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1992 child_id = (pthread_create(&the_thread, &attrs,
1993 (void*)serve, csp) ? -1 : 0);
1994 pthread_attr_destroy(&attrs);
1998 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1999 #define SELECTED_ONE_OPTION
2000 child_id = _beginthread(
2006 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2007 #define SELECTED_ONE_OPTION
2008 child_id = _beginthread(
2015 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2016 #define SELECTED_ONE_OPTION
2018 thread_id tid = spawn_thread
2019 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2021 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2023 child_id = (int) tid;
2032 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2033 #define SELECTED_ONE_OPTION
2034 csp->cfd = ReleaseSocket(csp->cfd, -1);
2035 if((child_id = (int)CreateNewProcTags(
2036 NP_Entry, (ULONG)server_thread,
2037 NP_Output, Output(),
2038 NP_CloseOutput, FALSE,
2039 NP_Name, (ULONG)"junkbuster child",
2040 NP_StackSize, 200*1024,
2044 ((struct Task *)child_id)->tc_UserData = csp;
2045 Signal((struct Task *)child_id, SIGF_SINGLE);
2050 #if !defined(SELECTED_ONE_OPTION)
2053 /* This block is only needed when using fork().
2054 * When using threads, the server thread was
2055 * created and run by the call to _beginthread().
2057 if (child_id == 0) /* child */
2063 else if (child_id > 0) /* parent */
2065 /* in a fork()'d environment, the parent's
2066 * copy of the client socket and the CSP
2070 #if !defined(_WIN32) && defined(__CYGWIN__)
2072 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2073 close_socket(csp->cfd);
2074 csp->flags &= ~CSP_FLAG_ACTIVE;
2078 #undef SELECTED_ONE_OPTION
2079 /* end of cpp switch () */
2081 if (child_id < 0) /* failed */
2083 char buf[BUFFER_SIZE];
2085 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2087 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
2089 write_socket(csp->cfd, buf, strlen(buf));
2090 close_socket(csp->cfd);
2091 csp->flags &= ~CSP_FLAG_ACTIVE;