1 const char jcc_rcs[] = "$Id: jcc.c,v 1.67 2002/03/04 18:18:57 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.67 2002/03/04 18:18:57 oes
37 * - Removed _DEBUG mode
38 * - Cleand up cmdline parsing
39 * - Introduced --no-daemon, --pidfile options
40 * - Cleaned up signal handling:
41 * - Terminate cleanly on INT, TERM and ABRT
42 * - Schedule logfile for re-opening on HUP
43 * - Ignore CHLD and PIPE
44 * - Leave the rest with their default handlers
45 * - Uniform handler registration
46 * - Added usage() function
47 * - Played styleguide police
49 * Revision 1.66 2002/03/03 15:06:55 oes
50 * Re-enabled automatic config reloading
52 * Revision 1.65 2002/03/03 14:49:11 oes
53 * Fixed CLF logging: Now uses client's original HTTP request
55 * Revision 1.64 2002/03/03 09:18:03 joergs
56 * Made jumbjuster work on AmigaOS again.
58 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
59 * Clean up a little CRLF unpleasantness that suddenly appeared
61 * Revision 1.62 2002/02/20 23:17:23 jongfoster
62 * Detecting some out-of memory conditions and exiting with a log message.
64 * Revision 1.61 2002/01/17 21:01:52 jongfoster
65 * Moving all our URL and URL pattern parsing code to urlmatch.c.
67 * Revision 1.60 2001/12/30 14:07:32 steudten
68 * - Add signal handling (unix)
69 * - Add SIGHUP handler (unix)
70 * - Add creation of pidfile (unix)
71 * - Add action 'top' in rc file (RH)
72 * - Add entry 'SIGNALS' to manpage
73 * - Add exit message to logfile (unix)
75 * Revision 1.59 2001/12/13 14:07:18 oes
76 * Fixed Bug: 503 error page now sent OK
78 * Revision 1.58 2001/11/30 23:37:24 jongfoster
79 * Renaming the Win32 config file to config.txt - this is almost the
80 * same as the corresponding UNIX name "config"
82 * Revision 1.57 2001/11/16 00:47:43 jongfoster
83 * Changing the tty-disconnection code to use setsid().
85 * Revision 1.56 2001/11/13 20:20:54 jongfoster
86 * Tabs->spaces, fixing a bug with missing {} around an if()
88 * Revision 1.55 2001/11/13 20:14:53 jongfoster
89 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
91 * Revision 1.54 2001/11/07 00:03:14 steudten
92 * Give reliable return value if an error
93 * occurs not just 0 with new daemon mode.
95 * Revision 1.53 2001/11/05 21:41:43 steudten
96 * Add changes to be a real daemon just for unix os.
97 * (change cwd to /, detach from controlling tty, set
98 * process group and session leader to the own process.
100 * Add some fatal-error log message for failed malloc().
101 * Add '-d' if compiled with 'configure --with-debug' to
102 * enable debug output.
104 * Revision 1.52 2001/10/26 20:11:20 jongfoster
105 * Fixing type mismatch
107 * Revision 1.51 2001/10/26 17:38:28 oes
110 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
111 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
112 * threads to call select() simultaneously. So, it's time to do a real, live,
113 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
114 * (native). Both versions will work, but using __OS2__ offers multi-threading.
116 * Revision 1.49 2001/10/23 21:41:35 jongfoster
117 * Added call to initialize the (statically-allocated of course)
118 * "out of memory" CGI response.
120 * Revision 1.48 2001/10/10 19:56:46 jongfoster
121 * Moving some code that wasn't cookie-related out of an #ifdef
124 * Revision 1.47 2001/10/10 16:44:36 oes
125 * Added CONNECT destination port limitation check
127 * Revision 1.46 2001/10/08 15:17:41 oes
128 * Re-enabled SSL forwarding
130 * Revision 1.45 2001/10/07 15:42:11 oes
131 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
133 * Moved downgrading of the HTTP version from parse_http_request to
134 * chat(), since we can't decide if it is necessary before we have
135 * determined the actions for the URL. The HTTP command is now
136 * *always* re-built so the repairs need no longer be special-cased.
138 * filter_popups now gets a csp pointer so it can raise the new
139 * CSP_FLAG_MODIFIED flag.
143 * Added configurable size limit for the IOB. If the IOB grows so
144 * large that the next read would exceed the limit, the header
145 * is generated, and the header & unfiltered buffer are flushed
146 * to the client. Chat then continues in non-buffering,
147 * non-filtering body mode.
149 * Revision 1.44 2001/10/02 18:13:57 oes
152 * Revision 1.43 2001/10/02 15:32:13 oes
153 * Moved generation of hdr
155 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
156 * Cleaning up 2 compiler warnings on OS/2.
158 * Revision 1.41 2001/09/16 17:05:14 jongfoster
159 * Removing unused #include showarg.h
161 * Revision 1.40 2001/09/16 15:41:45 jongfoster
162 * Fixing signed/unsigned comparison warning.
164 * Revision 1.39 2001/09/16 13:21:27 jongfoster
165 * Changes to use new list functions.
167 * Revision 1.38 2001/09/16 13:01:46 jongfoster
168 * Removing redundant function call that zeroed zalloc()'d memory.
170 * Revision 1.37 2001/09/10 11:12:24 oes
171 * Deleted unused variable
173 * Revision 1.36 2001/09/10 10:56:15 oes
174 * Silenced compiler warnings
176 * Revision 1.35 2001/07/31 14:44:22 oes
177 * Deleted unused size parameter from filter_popups()
179 * Revision 1.34 2001/07/30 22:08:36 jongfoster
180 * Tidying up #defines:
181 * - All feature #defines are now of the form FEATURE_xxx
182 * - Permanently turned off WIN_GUI_EDIT
183 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
185 * Revision 1.33 2001/07/29 19:32:00 jongfoster
186 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
188 * Revision 1.32 2001/07/29 18:47:05 jongfoster
189 * Adding missing #include "loadcfg.h"
191 * Revision 1.31 2001/07/29 12:17:48 oes
192 * Applied pthread fix by Paul Lieverse
194 * Revision 1.30 2001/07/25 22:57:13 jongfoster
195 * __BEOS__ no longer overrides FEATURE_PTHREAD.
196 * This is because FEATURE_PTHREAD will soon be widely used, so I
197 * want to keep it simple.
199 * Revision 1.29 2001/07/24 12:47:06 oes
200 * Applied BeOS support update by Eugenia
202 * Revision 1.28 2001/07/23 13:26:12 oes
203 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
205 * Revision 1.27 2001/07/19 19:09:47 haroon
206 * - Added code to take care of the situation where while processing the first
207 * server response (which includes the server header), after finding the end
208 * of the headers we were not looking past the end of the headers for
209 * content modification. I enabled it for filter_popups.
210 * Someone else should look to see if other similar operations should be
211 * done to the discarded portion of the buffer.
213 * Note 2001/07/20: No, the other content modification mechanisms will process
214 * the whole iob later anyway. --oes
216 * Revision 1.26 2001/07/18 12:31:36 oes
219 * Revision 1.25 2001/07/15 19:43:49 jongfoster
220 * Supports POSIX threads.
221 * Also removed some unused #includes.
223 * Revision 1.24 2001/07/13 14:00:40 oes
224 * - Generic content modification scheme:
225 * Each feature has its own applicability flag that is set
226 * from csp->action->flags.
227 * Replaced the "filtering" int flag , by a function pointer
228 * "content_filter" to the function that will do the content
229 * modification. If it is != NULL, the document will be buffered
230 * and processed through *content_filter, which must set
231 * csp->content_length and return a modified copy of the body
232 * or return NULL (on failiure).
233 * - Changed csp->is_text to the more generic bitmap csp->content_type
234 * which can currently take the valued CT_TEXT or CT_GIF
236 * - Removed all #ifdef PCRS
238 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
239 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
240 * the `block_acl' call. This prevents a compilation error when the user
241 * does not wish to use the "ACL" feature.
243 * Revision 1.22 2001/06/29 21:45:41 oes
244 * Indentation, CRLF->LF, Tab-> Space
246 * Revision 1.21 2001/06/29 13:29:36 oes
247 * - Cleaned up, improved comments
248 * - Unified all possible interceptors (CGI,
249 * block, trust, fast_redirect) in one
250 * place, with one (CGI) answer generation
251 * mechansim. Much clearer now.
252 * - Removed the GIF image generation, which
253 * is now done in filters.c:block_url()
254 * - Made error conditions like domain lookup
255 * failiure or (various) problems while talking
256 * to the server use cgi.c:error_response()
257 * instead of generating HTML/HTTP in chat() (yuck!)
258 * - Removed logentry from cancelled commit
260 * Revision 1.20 2001/06/09 10:55:28 jongfoster
261 * Changing BUFSIZ ==> BUFFER_SIZE
263 * Revision 1.19 2001/06/07 23:12:52 jongfoster
264 * Replacing function pointer in struct gateway with a directly
265 * called function forwarded_connect().
266 * Replacing struct gateway with struct forward_spec
268 * Revision 1.18 2001/06/03 19:12:16 oes
269 * introduced new cgi handling
271 * Revision 1.17 2001/06/01 20:07:23 jongfoster
272 * Now uses action +image-blocker{} rather than config->tinygif
274 * Revision 1.16 2001/06/01 18:49:17 jongfoster
275 * Replaced "list_share" with "list" - the tiny memory gain was not
276 * worth the extra complexity.
278 * Revision 1.15 2001/05/31 21:24:47 jongfoster
279 * Changed "permission" to "action" throughout.
280 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
281 * Moved vanilla wafer check into chat(), since we must now
282 * decide whether or not to add it based on the URL.
284 * Revision 1.14 2001/05/29 20:14:01 joergs
285 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
288 * Revision 1.13 2001/05/29 09:50:24 jongfoster
289 * Unified blocklist/imagelist/permissionslist.
290 * File format is still under discussion, but the internal changes
293 * Also modified interceptor behaviour:
294 * - We now intercept all URLs beginning with one of the following
295 * prefixes (and *only* these prefixes):
297 * * http://ijbswa.sf.net/config/
298 * * http://ijbswa.sourceforge.net/config/
299 * - New interceptors "home page" - go to http://i.j.b/ to see it.
300 * - Internal changes so that intercepted and fast redirect pages
301 * are not replaced with an image.
302 * - Interceptors now have the option to send a binary page direct
303 * to the client. (i.e. ijb-send-banner uses this)
304 * - Implemented show-url-info interceptor. (Which is why I needed
305 * the above interceptors changes - a typical URL is
306 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
307 * The previous mechanism would not have intercepted that, and
308 * if it had been intercepted then it then it would have replaced
311 * Revision 1.12 2001/05/27 22:17:04 oes
313 * - re_process_buffer no longer writes the modified buffer
314 * to the client, which was very ugly. It now returns the
315 * buffer, which it is then written by chat.
317 * - content_length now adjusts the Content-Length: header
318 * for modified documents rather than crunch()ing it.
319 * (Length info in csp->content_length, which is 0 for
320 * unmodified documents)
322 * - For this to work, sed() is called twice when filtering.
324 * Revision 1.11 2001/05/26 17:27:53 jongfoster
325 * Added support for CLF and fixed LOG_LEVEL_LOG.
326 * Also did CRLF->LF fix of my previous patch.
328 * Revision 1.10 2001/05/26 15:26:15 jongfoster
329 * ACL feature now provides more security by immediately dropping
330 * connections from untrusted hosts.
332 * Revision 1.9 2001/05/26 00:28:36 jongfoster
333 * Automatic reloading of config file.
334 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
335 * Most of the global variables have been moved to a new
336 * struct configuration_spec, accessed through csp->config->globalname
337 * Most of the globals remaining are used by the Win32 GUI.
339 * Revision 1.8 2001/05/25 22:43:18 jongfoster
340 * Fixing minor memory leak and buffer overflow.
342 * Revision 1.7 2001/05/25 22:34:30 jongfoster
345 * Revision 1.6 2001/05/23 00:13:58 joergs
346 * AmigaOS support fixed.
348 * Revision 1.5 2001/05/22 18:46:04 oes
350 * - Enabled filtering banners by size rather than URL
351 * by adding patterns that replace all standard banner
352 * sizes with the "Junkbuster" gif to the re_filterfile
354 * - Enabled filtering WebBugs by providing a pattern
355 * which kills all 1x1 images
357 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
358 * which is selected by the (nonstandard and therefore
359 * capital) letter 'U' in the option string.
360 * It causes the quantifiers to be ungreedy by default.
361 * Appending a ? turns back to greedy (!).
363 * - Added a new interceptor ijb-send-banner, which
364 * sends back the "Junkbuster" gif. Without imagelist or
365 * MSIE detection support, or if tinygif = 1, or the
366 * URL isn't recognized as an imageurl, a lame HTML
367 * explanation is sent instead.
369 * - Added new feature, which permits blocking remote
370 * script redirects and firing back a local redirect
372 * The feature is conditionally compiled, i.e. it
373 * can be disabled with --disable-fast-redirects,
374 * plus it must be activated by a "fast-redirects"
375 * line in the config file, has its own log level
376 * and of course wants to be displayed by show-proxy-args
377 * Note: Boy, all the #ifdefs in 1001 locations and
378 * all the fumbling with configure.in and acconfig.h
379 * were *way* more work than the feature itself :-(
381 * - Because a generic redirect template was needed for
382 * this, tinygif = 3 now uses the same.
384 * - Moved GIFs, and other static HTTP response templates
389 * - Removed some >400 CRs again (Jon, you really worked
392 * Revision 1.4 2001/05/21 19:34:01 jongfoster
393 * Made failure to bind() a fatal error.
395 * Revision 1.3 2001/05/20 01:21:20 jongfoster
396 * Version 2.9.4 checkin.
397 * - Merged popupfile and cookiefile, and added control over PCRS
398 * filtering, in new "permissionsfile".
399 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
400 * file error you now get a message box (in the Win32 GUI) rather
401 * than the program exiting with no explanation.
402 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
404 * - Removed tabs from "config"
405 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
406 * - Bumped up version number.
408 * Revision 1.2 2001/05/17 22:34:44 oes
409 * - Added hint on GIF char array generation to jcc.c
410 * - Cleaned CRLF's from the sources and related files
411 * - Repaired logging for REF and FRC
413 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
414 * Initial import of version 2.9.3 source tree
417 *********************************************************************/
423 #include <sys/types.h>
430 #ifdef FEATURE_PTHREAD
432 #endif /* def FEATURE_PTHREAD */
435 # ifndef FEATURE_PTHREAD
436 # include <windows.h>
437 # include <process.h>
438 # endif /* ndef FEATURE_PTHREAD */
441 # ifndef _WIN_CONSOLE
443 # endif /* ndef _WIN_CONSOLE */
445 #else /* ifndef _WIN32 */
447 # if !defined (__OS2__)
449 # include <sys/wait.h>
450 # endif /* ndef __OS2__ */
451 # include <sys/time.h>
452 # include <sys/stat.h>
453 # include <sys/ioctl.h>
456 #include <sys/termios.h>
462 # include <socket.h> /* BeOS has select() for sockets only. */
463 # include <OS.h> /* declarations for threads and stuff. */
466 # if defined(__EMX__) || defined(__OS2__)
467 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
472 #define bzero(B,N) memset(B,0x00,n)
487 #include "killpopup.h"
488 #include "miscutil.h"
490 #include "jbsockets.h"
495 #include "urlmatch.h"
497 const char jcc_h_rcs[] = JCC_H_VERSION;
498 const char project_h_rcs[] = PROJECT_H_VERSION;
501 struct client_state clients[1];
502 struct file_list files[1];
504 #ifdef FEATURE_STATISTICS
505 int urls_read = 0; /* total nr of urls read inc rejected */
506 int urls_rejected = 0; /* total nr of urls rejected */
507 #endif /* def FEATURE_STATISTICS */
510 static void listen_loop(void);
511 static void chat(struct client_state *csp);
513 void serve(struct client_state *csp);
514 #else /* ifndef AMIGA */
515 static void serve(struct client_state *csp);
516 #endif /* def AMIGA */
519 static int32 server_thread(void *data);
520 #endif /* def __BEOS__ */
523 #define sleep(N) Sleep(((N) * 1000))
527 #define sleep(N) DosSleep(((N) * 100))
532 const char *pidfile = NULL;
533 int received_hup_signal = 0;
534 #endif /* defined unix */
536 /* The vanilla wafer. */
537 static const char VANILLA_WAFER[] =
538 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
539 "Do_not_send_me_any_copyrighted_information_other_than_the_"
540 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
541 "In_particular_do_not_send_me_any_cookies_that_"
542 "are_subject_to_a_claim_of_copyright_by_anybody._"
543 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
544 "(copyright_or_otherwise)_applying_to_any_cookie._";
547 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
548 /*********************************************************************
550 * Function : sig_handler
552 * Description : Signal handler for different signals.
553 * Exit gracefully on ABRT, TERM and INT
554 * or set a flag that will cause the errlog
555 * to be reopened by the main thread on HUP.
558 * 1 : the_signal - the signal cause this function to call
562 *********************************************************************/
563 static void sig_handler(int the_signal)
570 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
578 received_hup_signal = 1;
583 * We shouldn't be here, unless we catch signals
584 * in main() that we can't handle here!
586 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
594 /*********************************************************************
598 * Description : Once a connection to the client has been accepted,
599 * this function is called (via serve()) to handle the
600 * main business of the communication. When this
601 * function returns, the caller must close the client
605 * 1 : csp = Current client state (buffers, headers, etc...)
607 * Returns : On success, the number of bytes written are returned (zero
608 * indicates nothing was written). On error, -1 is returned,
609 * and errno is set appropriately. If count is zero and the
610 * file descriptor refers to a regular file, 0 will be
611 * returned without causing any other effect. For a special
612 * file, the results are not portable.
614 *********************************************************************/
615 static void chat(struct client_state *csp)
618 * This next lines are a little ugly, but they simplifies the if statements
619 * below. Basically if TOGGLE, then we want the if to test if the
620 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
621 * then we want the if to test for CSP_FLAG_FORCED , else we don't
623 #ifdef FEATURE_TOGGLE
624 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
625 #else /* ifndef FEATURE_TOGGLE */
626 # define IS_TOGGLED_ON_AND
627 #endif /* ndef FEATURE_TOGGLE */
628 #ifdef FEATURE_FORCE_LOAD
629 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
630 #else /* ifndef FEATURE_FORCE_LOAD */
631 # define IS_NOT_FORCED_AND
632 #endif /* def FEATURE_FORCE_LOAD */
634 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
636 char buf[BUFFER_SIZE];
639 int n, maxfd, server_body;
640 int ms_iis5_hack = 0;
642 const struct forward_spec * fwd;
643 struct http_request *http;
644 #ifdef FEATURE_KILL_POPUPS
645 int block_popups; /* bool, 1==will block popups */
646 int block_popups_now = 0; /* bool, 1==currently blocking popups */
647 #endif /* def FEATURE_KILL_POPUPS */
649 int pcrs_filter; /* bool, 1==will filter through pcrs */
650 int gif_deanimate; /* bool, 1==will deanimate gifs */
652 /* Function that does the content filtering for the current request */
653 char *(*content_filter)() = NULL;
655 /* Skeleton for HTTP response, if we should intercept the request */
656 struct http_response *rsp;
661 * Read the client's request. Note that since we're not using select() we
662 * could get blocked here if a client connected, then didn't say anything!
667 n = read_socket(csp->cfd, buf, sizeof(buf));
669 if (n <= 0) break; /* error! */
671 add_to_iob(csp, buf, n);
673 req = get_header(csp);
677 break; /* no HTTP request! */
682 continue; /* more to come! */
685 #ifdef FEATURE_FORCE_LOAD
686 /* If this request contains the FORCE_PREFIX,
687 * better get rid of it now and set the force flag --oes
690 if (strstr(req, FORCE_PREFIX))
692 strclean(req, FORCE_PREFIX);
693 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
694 csp->flags |= CSP_FLAG_FORCED;
697 #endif /* def FEATURE_FORCE_LOAD */
699 parse_http_request(req, http, csp);
704 if (http->cmd == NULL)
706 strcpy(buf, CHEADER);
707 write_socket(csp->cfd, buf, strlen(buf));
709 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
714 /* decide how to route the HTTP request */
716 if ((fwd = forward_url(http, csp)) == NULL)
718 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
719 /* Never get here - LOG_LEVEL_FATAL causes program exit */
722 /* build the http request to send to the server
723 * we have to do one of the following:
725 * create = use the original HTTP request to create a new
726 * HTTP request that has either the path component
727 * without the http://domainspec (w/path) or the
728 * full orininal URL (w/url)
729 * Note that the path and/or the HTTP version may
730 * have been altered by now.
732 * connect = Open a socket to the host:port of the server
733 * and short-circuit server and client socket.
735 * pass = Pass the request unchanged if forwarding a CONNECT
736 * request to a parent proxy. Note that we'll be sending
737 * the CFAIL message ourselves if connecting to the parent
738 * fails, but we won't send a CSUCCEED message if it works,
739 * since that would result in a double message (ours and the
740 * parent's). After sending the request to the parent, we simply
746 * +--------+--------+
748 * 0 | create | connect|
750 * Forwarding +--------+--------+
752 * 1 | create | pass |
754 * +--------+--------+
759 * Determine the actions for this URL
761 #ifdef FEATURE_TOGGLE
762 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
764 /* Most compatible set of actions (i.e. none) */
765 init_current_action(csp->action);
768 #endif /* ndef FEATURE_TOGGLE */
770 url_actions(http, csp);
775 * Check if a CONNECT request is allowable:
776 * In the absence of a +limit-connect action, allow only port 443.
777 * If there is an action, allow whatever matches the specificaton.
781 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
782 || (csp->action->flags & ACTION_LIMIT_CONNECT
783 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
785 strcpy(buf, CFORBIDDEN);
786 write_socket(csp->cfd, buf, strlen(buf));
788 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
789 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
797 * Downgrade http version from 1.1 to 1.0 if +downgrade
800 if ( (http->ssl == 0)
801 && (!strcmpic(http->ver, "HTTP/1.1"))
802 && (csp->action->flags & ACTION_DOWNGRADE))
805 http->ver = strdup("HTTP/1.0");
807 if (http->ver == NULL)
809 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
814 * Save a copy of the original request for logging
816 http->ocmd = strdup(http->cmd);
818 if (http->ocmd == NULL)
820 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
824 * (Re)build the HTTP request for non-SSL requests.
825 * If forwarding, use the whole URL, else, use only the path.
831 http->cmd = strdup(http->gpc);
832 string_append(&http->cmd, " ");
834 if (fwd->forward_host)
836 string_append(&http->cmd, http->url);
840 string_append(&http->cmd, http->path);
843 string_append(&http->cmd, " ");
844 string_append(&http->cmd, http->ver);
846 if (http->cmd == NULL)
848 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
851 enlist(csp->headers, http->cmd);
854 #ifdef FEATURE_COOKIE_JAR
856 * If we're logging cookies in a cookie jar, and the user has not
857 * supplied any wafers, and the user has not told us to suppress the
858 * vanilla wafer, then send the vanilla wafer.
860 if ((csp->config->jarfile != NULL)
861 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
862 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
864 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
866 #endif /* def FEATURE_COOKIE_JAR */
869 #ifdef FEATURE_KILL_POPUPS
870 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
871 #endif /* def FEATURE_KILL_POPUPS */
873 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
874 ((csp->action->flags & ACTION_FILTER) != 0);
876 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
878 /* grab the rest of the client's headers */
882 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
884 n = read_socket(csp->cfd, buf, sizeof(buf));
887 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
890 add_to_iob(csp, buf, n);
894 if (p == NULL) break;
896 enlist(csp->headers, p);
900 * We have a request. Now, check to see if we need to
901 * intercept it, i.e. If ..
905 /* a CGI call was detected and answered */
906 (NULL != (rsp = dispatch_cgi(csp)))
908 /* or we are enabled and... */
911 /* ..the request was blocked */
912 ( NULL != (rsp = block_url(csp)))
916 || ( NULL != (rsp = trust_url(csp)))
917 #endif /* def FEATURE_TRUST */
919 /* ..or a fast redirect kicked in */
920 #ifdef FEATURE_FAST_REDIRECTS
921 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
922 (NULL != (rsp = redirect_url(csp))))
923 #endif /* def FEATURE_FAST_REDIRECTS */
927 /* Write the answer to the client */
928 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
929 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
931 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
934 #ifdef FEATURE_STATISTICS
935 /* Count as a rejected request */
936 csp->flags |= CSP_FLAG_REJECTED;
937 #endif /* def FEATURE_STATISTICS */
939 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
940 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
941 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
943 /* Clean up and return */
944 free_http_response(rsp);
948 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
950 if (fwd->forward_host)
952 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
953 fwd->forward_host, fwd->forward_port, http->hostport);
957 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
960 /* here we connect to the server, gateway, or the forwarder */
962 csp->sfd = forwarded_connect(fwd, http, csp);
966 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
971 rsp = error_response(csp, "no-such-domain", errno);
973 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
974 csp->ip_addr_str, http->ocmd);
978 rsp = error_response(csp, "connect-failed", errno);
980 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
981 csp->ip_addr_str, http->ocmd);
985 /* Write the answer to the client */
988 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
989 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
991 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
995 free_http_response(rsp);
999 log_error(LOG_LEVEL_CONNECT, "OK");
1001 hdr = sed(client_patterns, add_client_headers, csp);
1004 /* FIXME Should handle error properly */
1005 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1008 list_remove_all(csp->headers);
1010 if (fwd->forward_host || (http->ssl == 0))
1012 /* write the client's (modified) header to the server
1013 * (along with anything else that may be in the buffer)
1018 if ((write_socket(csp->sfd, hdr, n) != n)
1019 || (flush_socket(csp->sfd, csp ) < 0))
1021 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1024 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1025 csp->ip_addr_str, http->ocmd);
1027 rsp = error_response(csp, "connect-failed", errno);
1031 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1032 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1034 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1038 free_http_response(rsp);
1046 * We're running an SSL tunnel and we're not forwarding,
1047 * so just send the "connect succeeded" message to the
1048 * client, flush the rest, and get out of the way.
1050 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1051 csp->ip_addr_str, http->ocmd);
1053 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
1061 /* we're finished with the client's header */
1064 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1066 /* pass data between the client and server
1067 * until one or the other shuts down the connection.
1076 FD_SET(csp->cfd, &rfds);
1077 FD_SET(csp->sfd, &rfds);
1079 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1083 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1087 /* this is the body of the browser's request
1088 * just read it and write it.
1091 if (FD_ISSET(csp->cfd, &rfds))
1093 n = read_socket(csp->cfd, buf, sizeof(buf));
1097 break; /* "game over, man" */
1100 if (write_socket(csp->sfd, buf, n) != n)
1102 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1109 * The server wants to talk. It could be the header or the body.
1110 * If `hdr' is null, then it's the header otherwise it's the body.
1111 * FIXME: Does `hdr' really mean `host'? No.
1115 if (FD_ISSET(csp->sfd, &rfds))
1118 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1122 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1124 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1125 csp->ip_addr_str, http->ocmd);
1127 rsp = error_response(csp, "connect-failed", errno);
1131 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1132 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1134 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1138 free_http_response(rsp);
1142 /* Add a trailing zero. This lets filter_popups
1143 * use string operations.
1147 #ifdef FEATURE_KILL_POPUPS
1148 /* Filter the popups on this read. */
1149 if (block_popups_now)
1151 filter_popups(buf, csp);
1153 #endif /* def FEATURE_KILL_POPUPS */
1155 /* Normally, this would indicate that we've read
1156 * as much as the server has sent us and we can
1157 * close the client connection. However, Microsoft
1158 * in its wisdom has released IIS/5 with a bug that
1159 * prevents it from sending the trailing \r\n in
1160 * a 302 redirect header (and possibly other headers).
1161 * To work around this if we've haven't parsed
1162 * a full header we'll append a trailing \r\n
1163 * and see if this now generates a valid one.
1165 * This hack shouldn't have any impacts. If we've
1166 * already transmitted the header or if this is a
1167 * SSL connection, then we won't bother with this
1168 * hack. So we only work on partially received
1169 * headers. If we append a \r\n and this still
1170 * doesn't generate a valid header, then we won't
1171 * transmit anything to the client.
1176 if (server_body || http->ssl)
1179 * If we have been buffering up the document,
1180 * now is the time to apply content modification
1181 * and send the result to the client.
1186 * If the content filter fails, use the original
1187 * buffer and length.
1188 * (see p != NULL ? p : csp->iob->cur below)
1190 if (NULL == (p = (*content_filter)(csp)))
1192 csp->content_length = csp->iob->eod - csp->iob->cur;
1195 hdr = sed(server_patterns, add_server_headers, csp);
1198 /* FIXME Should handle error properly */
1199 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1204 if ((write_socket(csp->cfd, hdr, n) != n)
1205 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1207 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1217 break; /* "game over, man" */
1221 * This is NOT the body, so
1222 * Let's pretend the server just sent us a blank line.
1224 n = sprintf(buf, "\r\n");
1227 * Now, let the normal header parsing algorithm below do its
1228 * job. If it fails, we'll exit instead of continuing.
1235 * If this is an SSL connection or we're in the body
1236 * of the server document, just write it to the client,
1237 * unless we need to buffer the body for later content-filtering
1240 if (server_body || http->ssl)
1244 add_to_iob(csp, buf, n);
1247 * If the buffer limit will be reached on the next read,
1248 * switch to non-filtering mode, i.e. make & write the
1249 * header, flush the socket and get out of the way.
1251 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1253 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1255 hdr = sed(server_patterns, add_server_headers, csp);
1258 /* FIXME Should handle error properly */
1259 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1265 if (((write_socket(csp->cfd, hdr, n) != n)
1266 || (n = flush_socket(csp->cfd, csp) < 0)))
1268 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1277 content_filter = NULL;
1284 if (write_socket(csp->cfd, buf, n) != n)
1286 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1295 /* we're still looking for the end of the
1296 * server's header ... (does that make header
1297 * parsing an "out of body experience" ?
1300 /* buffer up the data we just read */
1301 add_to_iob(csp, buf, n);
1303 /* get header lines from the iob */
1305 while ((p = get_header(csp)))
1309 /* see following note */
1312 enlist(csp->headers, p);
1316 /* NOTE: there are no "empty" headers so
1317 * if the pointer `p' is not NULL we must
1318 * assume that we reached the end of the
1319 * buffer before we hit the end of the header.
1326 /* Well, we tried our MS IIS/5
1327 * hack and it didn't work.
1328 * The header is incomplete
1329 * and there isn't anything
1330 * we can do about it.
1336 /* Since we have to wait for
1337 * more from the server before
1338 * we can parse the headers
1339 * we just continue here.
1345 /* we have now received the entire header.
1346 * filter it and send the result to the client
1349 hdr = sed(server_patterns, add_server_headers, csp);
1352 /* FIXME Should handle error properly */
1353 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1358 /* write the server's (modified) header to
1359 * the client (along with anything else that
1360 * may be in the buffer)
1363 #ifdef FEATURE_KILL_POPUPS
1364 /* Start blocking popups if appropriate. */
1366 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1367 !http->ssl && /* We talk plaintext */
1368 block_popups) /* Policy allows */
1370 block_popups_now = 1;
1372 * Filter the part of the body that came in the same read
1373 * as the last headers:
1375 filter_popups(csp->iob->cur, csp);
1378 #endif /* def FEATURE_KILL_POPUPS */
1380 /* Buffer and pcrs filter this if appropriate. */
1382 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1383 !http->ssl && /* We talk plaintext */
1384 pcrs_filter) /* Policy allows */
1386 content_filter = pcrs_filter_response;
1389 /* Buffer and gif_deanimate this if appropriate. */
1391 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1392 !http->ssl && /* We talk plaintext */
1393 gif_deanimate) /* Policy allows */
1395 content_filter = gif_deanimate_response;
1400 * Only write if we're not buffering for content modification
1402 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1403 || (n = flush_socket(csp->cfd, csp) < 0)))
1405 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1407 /* the write failed, so don't bother
1408 * mentioning it to the client...
1409 * it probably can't hear us anyway.
1415 if(!content_filter) byte_count += n;
1417 /* we're finished with the server's header */
1422 /* If this was a MS IIS/5 hack then it means
1423 * the server has already closed the
1424 * connection. Nothing more to read. Time
1435 return; /* huh? we should never get here */
1438 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1439 csp->ip_addr_str, http->ocmd, byte_count);
1443 /*********************************************************************
1447 * Description : This is little more than chat. We only "serve" to
1448 * to close any socket that chat may have opened.
1451 * 1 : csp = Current client state (buffers, headers, etc...)
1455 *********************************************************************/
1457 void serve(struct client_state *csp)
1458 #else /* ifndef AMIGA */
1459 static void serve(struct client_state *csp)
1460 #endif /* def AMIGA */
1463 close_socket(csp->cfd);
1467 close_socket(csp->sfd);
1470 csp->flags &= ~CSP_FLAG_ACTIVE;
1476 /*********************************************************************
1478 * Function : server_thread
1480 * Description : We only exist to call `serve' in a threaded environment.
1483 * 1 : data = Current client state (buffers, headers, etc...)
1485 * Returns : Always 0.
1487 *********************************************************************/
1488 static int32 server_thread(void *data)
1490 serve((struct client_state *) data);
1497 /*********************************************************************
1501 * Description : Print usage info & exit.
1503 * Parameters : Pointer to argv[0] for identifying ourselves
1507 *********************************************************************/
1508 void usage(const char *myname)
1510 printf("JunkBuster proxy version " VERSION " (" HOME_PAGE_URL ")\n"
1511 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [configfile]\n"
1512 "Aborting.\n", myname);
1519 /*********************************************************************
1523 * Description : Load the config file and start the listen loop.
1524 * This function is a lot more *sane* with the `load_config'
1525 * and `listen_loop' functions; although it stills does
1526 * a *little* too much for my taste.
1529 * 1 : argc = Number of parameters (including $0).
1530 * 2 : argv = Array of (char *)'s to the parameters.
1532 * Returns : 1 if : can't open config file, unrecognized directive,
1533 * stats requested in multi-thread mode, can't open the
1534 * log file, can't open the jar file, listen port is invalid,
1535 * any load fails, and can't bind port.
1537 * Else main never returns, the process must be signaled
1538 * to terminate execution. Or, on Windows, use the
1539 * "File", "Exit" menu option.
1541 *********************************************************************/
1543 int real_main(int argc, const char *argv[])
1545 int main(int argc, const char *argv[])
1554 #if !defined(_WIN32)
1562 * Parse the command line arguments
1564 while (++argc_pos < argc)
1566 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1568 if (strcmp(argv[argc_pos], "--help") == 0)
1573 else if(strcmp(argv[argc_pos], "--version") == 0)
1575 printf("Junkbuster version " VERSION " (" HOME_PAGE_URL ")\n");
1579 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1584 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1586 if (++argc_pos == argc) usage(argv[0]);
1587 pidfile = strdup(argv[argc_pos]);
1590 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1594 configfile = argv[argc_pos];
1597 } /* -END- while (more arguments) */
1600 if ( *configfile != '/' )
1604 DBG(1, ("configfile before '%s'\n",configfile) );
1606 /* make config-filename absolute here */
1607 if ( !(basedir = getcwd( NULL, 1024 )))
1609 perror("get working dir failed");
1612 DBG(1, ("working dir '%s'\n",basedir) );
1613 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1615 perror("malloc failed");
1618 strcpy( abs_file, basedir );
1619 strcat( abs_file, "/" );
1620 strcat( abs_file, configfile );
1621 configfile = abs_file;
1622 DBG(1, ("configfile after '%s'\n",configfile) );
1624 #endif /* defined unix */
1631 #elif defined(_WIN32)
1636 * Unix signal handling
1638 * Catch the abort, interrupt and terminate signals for a graceful exit
1639 * Catch the hangup signal so the errlog can be reopened.
1640 * Ignore the broken pipe and child signals
1641 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1643 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1646 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1647 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1649 for (idx = 0; catched_signals[idx] != 0; idx++)
1651 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1653 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1657 for (idx = 0; ignored_signals[idx] != 0; idx++)
1659 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1661 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1666 #else /* ifdef _WIN32 */
1667 # ifdef _WIN_CONSOLE
1669 * We *are* in a windows console app.
1670 * Print a verbose messages about FAQ's and such
1672 printf(win32_blurb);
1673 # endif /* def _WIN_CONSOLE */
1674 #endif /* def _WIN32 */
1677 /* Initialize the CGI subsystem */
1678 cgi_init_error_messages();
1681 * If runnig on unix and without the --nodaemon
1682 * option, become a daemon. I.e. fork, detach
1683 * from tty and get process group leadership
1696 if ( pid < 0 ) /* error */
1701 else if ( pid != 0 ) /* parent */
1706 * must check for errors
1707 * child died due to missing files aso
1710 wpid = waitpid( pid, &status, WNOHANG );
1719 /* Should be more portable, but not as well tested */
1724 #else /* ndef __FreeBSD__ */
1726 #endif /* ndef __FreeBSD__ */
1727 fd = open("/dev/tty", O_RDONLY);
1730 /* no error check here */
1731 ioctl( fd, TIOCNOTTY,0 );
1735 /* FIXME: should close stderr (fd 2) here too, but the test
1737 * and load config file is done in listen_loop() and puts
1738 * some messages on stderr there.
1747 } /* -END- if (!no_daemon) */
1749 #endif /* defined unix */
1751 DBG(1, ("call listen_loop() \n") );
1760 /*********************************************************************
1762 * Function : listen_loop
1764 * Description : bind the listen port and enter a "FOREVER" listening loop.
1770 *********************************************************************/
1771 static void listen_loop(void)
1773 struct client_state *csp = NULL;
1775 struct configuration_spec * config;
1777 config = load_config();
1779 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1780 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1782 bfd = bind_port(config->haddr, config->hport);
1786 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1787 "- There may be another junkbuster or some other "
1788 "proxy running on port %d",
1789 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1790 config->hport, config->hport
1792 /* shouldn't get here */
1796 config->need_bind = 0;
1800 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1801 while (waitpid(-1, NULL, WNOHANG) > 0)
1803 /* zombie children */
1805 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1808 * Free data that was used by died threads
1813 * Re-open the errlog after HUP signal
1815 if (received_hup_signal)
1817 init_error_log(Argv[0], config->logfile, config->debug);
1818 received_hup_signal = 0;
1821 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1823 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1827 csp->flags |= CSP_FLAG_ACTIVE;
1830 csp->config = config = load_config();
1832 if ( config->need_bind )
1835 * Since we were listening to the "old port", we will not see
1836 * a "listen" param change until the next IJB request. So, at
1837 * least 1 more request must be made for us to find the new
1838 * setting. I am simply closing the old socket and binding the
1841 * Which-ever is correct, we will serve 1 more page via the
1842 * old settings. This should probably be a "show-proxy-args"
1843 * request. This should not be a so common of an operation
1844 * that this will hurt people's feelings.
1849 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1850 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1851 bfd = bind_port(config->haddr, config->hport);
1855 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1856 "- There may be another junkbuster or some other "
1857 "proxy running on port %d",
1858 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1859 config->hport, config->hport
1861 /* shouldn't get here */
1865 config->need_bind = 0;
1868 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1870 if (!accept_connection(csp, bfd))
1872 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1885 log_error(LOG_LEVEL_CONNECT, "OK");
1888 #ifdef FEATURE_TOGGLE
1891 csp->flags |= CSP_FLAG_TOGGLED_ON;
1893 #endif /* def FEATURE_TOGGLE */
1895 if (run_loader(csp))
1897 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1898 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1902 if (block_acl(NULL,csp))
1904 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1905 close_socket(csp->cfd);
1909 #endif /* def FEATURE_ACL */
1911 /* add it to the list of clients */
1912 csp->next = clients->next;
1913 clients->next = csp;
1915 if (config->multi_threaded)
1919 /* this is a switch () statment in the C preprocessor - ugh */
1920 #undef SELECTED_ONE_OPTION
1922 /* Use Pthreads in preference to native code */
1923 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1924 #define SELECTED_ONE_OPTION
1926 pthread_t the_thread;
1927 pthread_attr_t attrs;
1929 pthread_attr_init(&attrs);
1930 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1931 child_id = (pthread_create(&the_thread, &attrs,
1932 (void*)serve, csp) ? -1 : 0);
1933 pthread_attr_destroy(&attrs);
1937 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1938 #define SELECTED_ONE_OPTION
1939 child_id = _beginthread(
1945 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1946 #define SELECTED_ONE_OPTION
1947 child_id = _beginthread(
1954 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1955 #define SELECTED_ONE_OPTION
1957 thread_id tid = spawn_thread
1958 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1960 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1962 child_id = (int) tid;
1971 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1972 #define SELECTED_ONE_OPTION
1973 csp->cfd = ReleaseSocket(csp->cfd, -1);
1974 if((child_id = (int)CreateNewProcTags(
1975 NP_Entry, (ULONG)server_thread,
1976 NP_Output, Output(),
1977 NP_CloseOutput, FALSE,
1978 NP_Name, (ULONG)"junkbuster child",
1979 NP_StackSize, 200*1024,
1983 ((struct Task *)child_id)->tc_UserData = csp;
1984 Signal((struct Task *)child_id, SIGF_SINGLE);
1989 #if !defined(SELECTED_ONE_OPTION)
1992 /* This block is only needed when using fork().
1993 * When using threads, the server thread was
1994 * created and run by the call to _beginthread().
1996 if (child_id == 0) /* child */
2002 else if (child_id > 0) /* parent */
2004 /* in a fork()'d environment, the parent's
2005 * copy of the client socket and the CSP
2009 #if !defined(_WIN32) && defined(__CYGWIN__)
2011 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2012 close_socket(csp->cfd);
2013 csp->flags &= ~CSP_FLAG_ACTIVE;
2017 #undef SELECTED_ONE_OPTION
2018 /* end of cpp switch () */
2020 if (child_id < 0) /* failed */
2022 char buf[BUFFER_SIZE];
2024 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2026 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
2028 write_socket(csp->cfd, buf, strlen(buf));
2029 close_socket(csp->cfd);
2030 csp->flags &= ~CSP_FLAG_ACTIVE;