1 const char jcc_rcs[] = "$Id: jcc.c,v 1.66 2002/03/03 15:06:55 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.66 2002/03/03 15:06:55 oes
37 * Re-enabled automatic config reloading
39 * Revision 1.65 2002/03/03 14:49:11 oes
40 * Fixed CLF logging: Now uses client's original HTTP request
42 * Revision 1.64 2002/03/03 09:18:03 joergs
43 * Made jumbjuster work on AmigaOS again.
45 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
46 * Clean up a little CRLF unpleasantness that suddenly appeared
48 * Revision 1.62 2002/02/20 23:17:23 jongfoster
49 * Detecting some out-of memory conditions and exiting with a log message.
51 * Revision 1.61 2002/01/17 21:01:52 jongfoster
52 * Moving all our URL and URL pattern parsing code to urlmatch.c.
54 * Revision 1.60 2001/12/30 14:07:32 steudten
55 * - Add signal handling (unix)
56 * - Add SIGHUP handler (unix)
57 * - Add creation of pidfile (unix)
58 * - Add action 'top' in rc file (RH)
59 * - Add entry 'SIGNALS' to manpage
60 * - Add exit message to logfile (unix)
62 * Revision 1.59 2001/12/13 14:07:18 oes
63 * Fixed Bug: 503 error page now sent OK
65 * Revision 1.58 2001/11/30 23:37:24 jongfoster
66 * Renaming the Win32 config file to config.txt - this is almost the
67 * same as the corresponding UNIX name "config"
69 * Revision 1.57 2001/11/16 00:47:43 jongfoster
70 * Changing the tty-disconnection code to use setsid().
72 * Revision 1.56 2001/11/13 20:20:54 jongfoster
73 * Tabs->spaces, fixing a bug with missing {} around an if()
75 * Revision 1.55 2001/11/13 20:14:53 jongfoster
76 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
78 * Revision 1.54 2001/11/07 00:03:14 steudten
79 * Give reliable return value if an error
80 * occurs not just 0 with new daemon mode.
82 * Revision 1.53 2001/11/05 21:41:43 steudten
83 * Add changes to be a real daemon just for unix os.
84 * (change cwd to /, detach from controlling tty, set
85 * process group and session leader to the own process.
87 * Add some fatal-error log message for failed malloc().
88 * Add '-d' if compiled with 'configure --with-debug' to
89 * enable debug output.
91 * Revision 1.52 2001/10/26 20:11:20 jongfoster
92 * Fixing type mismatch
94 * Revision 1.51 2001/10/26 17:38:28 oes
97 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
98 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
99 * threads to call select() simultaneously. So, it's time to do a real, live,
100 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
101 * (native). Both versions will work, but using __OS2__ offers multi-threading.
103 * Revision 1.49 2001/10/23 21:41:35 jongfoster
104 * Added call to initialize the (statically-allocated of course)
105 * "out of memory" CGI response.
107 * Revision 1.48 2001/10/10 19:56:46 jongfoster
108 * Moving some code that wasn't cookie-related out of an #ifdef
111 * Revision 1.47 2001/10/10 16:44:36 oes
112 * Added CONNECT destination port limitation check
114 * Revision 1.46 2001/10/08 15:17:41 oes
115 * Re-enabled SSL forwarding
117 * Revision 1.45 2001/10/07 15:42:11 oes
118 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
120 * Moved downgrading of the HTTP version from parse_http_request to
121 * chat(), since we can't decide if it is necessary before we have
122 * determined the actions for the URL. The HTTP command is now
123 * *always* re-built so the repairs need no longer be special-cased.
125 * filter_popups now gets a csp pointer so it can raise the new
126 * CSP_FLAG_MODIFIED flag.
130 * Added configurable size limit for the IOB. If the IOB grows so
131 * large that the next read would exceed the limit, the header
132 * is generated, and the header & unfiltered buffer are flushed
133 * to the client. Chat then continues in non-buffering,
134 * non-filtering body mode.
136 * Revision 1.44 2001/10/02 18:13:57 oes
139 * Revision 1.43 2001/10/02 15:32:13 oes
140 * Moved generation of hdr
142 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
143 * Cleaning up 2 compiler warnings on OS/2.
145 * Revision 1.41 2001/09/16 17:05:14 jongfoster
146 * Removing unused #include showarg.h
148 * Revision 1.40 2001/09/16 15:41:45 jongfoster
149 * Fixing signed/unsigned comparison warning.
151 * Revision 1.39 2001/09/16 13:21:27 jongfoster
152 * Changes to use new list functions.
154 * Revision 1.38 2001/09/16 13:01:46 jongfoster
155 * Removing redundant function call that zeroed zalloc()'d memory.
157 * Revision 1.37 2001/09/10 11:12:24 oes
158 * Deleted unused variable
160 * Revision 1.36 2001/09/10 10:56:15 oes
161 * Silenced compiler warnings
163 * Revision 1.35 2001/07/31 14:44:22 oes
164 * Deleted unused size parameter from filter_popups()
166 * Revision 1.34 2001/07/30 22:08:36 jongfoster
167 * Tidying up #defines:
168 * - All feature #defines are now of the form FEATURE_xxx
169 * - Permanently turned off WIN_GUI_EDIT
170 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
172 * Revision 1.33 2001/07/29 19:32:00 jongfoster
173 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
175 * Revision 1.32 2001/07/29 18:47:05 jongfoster
176 * Adding missing #include "loadcfg.h"
178 * Revision 1.31 2001/07/29 12:17:48 oes
179 * Applied pthread fix by Paul Lieverse
181 * Revision 1.30 2001/07/25 22:57:13 jongfoster
182 * __BEOS__ no longer overrides FEATURE_PTHREAD.
183 * This is because FEATURE_PTHREAD will soon be widely used, so I
184 * want to keep it simple.
186 * Revision 1.29 2001/07/24 12:47:06 oes
187 * Applied BeOS support update by Eugenia
189 * Revision 1.28 2001/07/23 13:26:12 oes
190 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
192 * Revision 1.27 2001/07/19 19:09:47 haroon
193 * - Added code to take care of the situation where while processing the first
194 * server response (which includes the server header), after finding the end
195 * of the headers we were not looking past the end of the headers for
196 * content modification. I enabled it for filter_popups.
197 * Someone else should look to see if other similar operations should be
198 * done to the discarded portion of the buffer.
200 * Note 2001/07/20: No, the other content modification mechanisms will process
201 * the whole iob later anyway. --oes
203 * Revision 1.26 2001/07/18 12:31:36 oes
206 * Revision 1.25 2001/07/15 19:43:49 jongfoster
207 * Supports POSIX threads.
208 * Also removed some unused #includes.
210 * Revision 1.24 2001/07/13 14:00:40 oes
211 * - Generic content modification scheme:
212 * Each feature has its own applicability flag that is set
213 * from csp->action->flags.
214 * Replaced the "filtering" int flag , by a function pointer
215 * "content_filter" to the function that will do the content
216 * modification. If it is != NULL, the document will be buffered
217 * and processed through *content_filter, which must set
218 * csp->content_length and return a modified copy of the body
219 * or return NULL (on failiure).
220 * - Changed csp->is_text to the more generic bitmap csp->content_type
221 * which can currently take the valued CT_TEXT or CT_GIF
223 * - Removed all #ifdef PCRS
225 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
226 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
227 * the `block_acl' call. This prevents a compilation error when the user
228 * does not wish to use the "ACL" feature.
230 * Revision 1.22 2001/06/29 21:45:41 oes
231 * Indentation, CRLF->LF, Tab-> Space
233 * Revision 1.21 2001/06/29 13:29:36 oes
234 * - Cleaned up, improved comments
235 * - Unified all possible interceptors (CGI,
236 * block, trust, fast_redirect) in one
237 * place, with one (CGI) answer generation
238 * mechansim. Much clearer now.
239 * - Removed the GIF image generation, which
240 * is now done in filters.c:block_url()
241 * - Made error conditions like domain lookup
242 * failiure or (various) problems while talking
243 * to the server use cgi.c:error_response()
244 * instead of generating HTML/HTTP in chat() (yuck!)
245 * - Removed logentry from cancelled commit
247 * Revision 1.20 2001/06/09 10:55:28 jongfoster
248 * Changing BUFSIZ ==> BUFFER_SIZE
250 * Revision 1.19 2001/06/07 23:12:52 jongfoster
251 * Replacing function pointer in struct gateway with a directly
252 * called function forwarded_connect().
253 * Replacing struct gateway with struct forward_spec
255 * Revision 1.18 2001/06/03 19:12:16 oes
256 * introduced new cgi handling
258 * Revision 1.17 2001/06/01 20:07:23 jongfoster
259 * Now uses action +image-blocker{} rather than config->tinygif
261 * Revision 1.16 2001/06/01 18:49:17 jongfoster
262 * Replaced "list_share" with "list" - the tiny memory gain was not
263 * worth the extra complexity.
265 * Revision 1.15 2001/05/31 21:24:47 jongfoster
266 * Changed "permission" to "action" throughout.
267 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
268 * Moved vanilla wafer check into chat(), since we must now
269 * decide whether or not to add it based on the URL.
271 * Revision 1.14 2001/05/29 20:14:01 joergs
272 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
275 * Revision 1.13 2001/05/29 09:50:24 jongfoster
276 * Unified blocklist/imagelist/permissionslist.
277 * File format is still under discussion, but the internal changes
280 * Also modified interceptor behaviour:
281 * - We now intercept all URLs beginning with one of the following
282 * prefixes (and *only* these prefixes):
284 * * http://ijbswa.sf.net/config/
285 * * http://ijbswa.sourceforge.net/config/
286 * - New interceptors "home page" - go to http://i.j.b/ to see it.
287 * - Internal changes so that intercepted and fast redirect pages
288 * are not replaced with an image.
289 * - Interceptors now have the option to send a binary page direct
290 * to the client. (i.e. ijb-send-banner uses this)
291 * - Implemented show-url-info interceptor. (Which is why I needed
292 * the above interceptors changes - a typical URL is
293 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
294 * The previous mechanism would not have intercepted that, and
295 * if it had been intercepted then it then it would have replaced
298 * Revision 1.12 2001/05/27 22:17:04 oes
300 * - re_process_buffer no longer writes the modified buffer
301 * to the client, which was very ugly. It now returns the
302 * buffer, which it is then written by chat.
304 * - content_length now adjusts the Content-Length: header
305 * for modified documents rather than crunch()ing it.
306 * (Length info in csp->content_length, which is 0 for
307 * unmodified documents)
309 * - For this to work, sed() is called twice when filtering.
311 * Revision 1.11 2001/05/26 17:27:53 jongfoster
312 * Added support for CLF and fixed LOG_LEVEL_LOG.
313 * Also did CRLF->LF fix of my previous patch.
315 * Revision 1.10 2001/05/26 15:26:15 jongfoster
316 * ACL feature now provides more security by immediately dropping
317 * connections from untrusted hosts.
319 * Revision 1.9 2001/05/26 00:28:36 jongfoster
320 * Automatic reloading of config file.
321 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
322 * Most of the global variables have been moved to a new
323 * struct configuration_spec, accessed through csp->config->globalname
324 * Most of the globals remaining are used by the Win32 GUI.
326 * Revision 1.8 2001/05/25 22:43:18 jongfoster
327 * Fixing minor memory leak and buffer overflow.
329 * Revision 1.7 2001/05/25 22:34:30 jongfoster
332 * Revision 1.6 2001/05/23 00:13:58 joergs
333 * AmigaOS support fixed.
335 * Revision 1.5 2001/05/22 18:46:04 oes
337 * - Enabled filtering banners by size rather than URL
338 * by adding patterns that replace all standard banner
339 * sizes with the "Junkbuster" gif to the re_filterfile
341 * - Enabled filtering WebBugs by providing a pattern
342 * which kills all 1x1 images
344 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
345 * which is selected by the (nonstandard and therefore
346 * capital) letter 'U' in the option string.
347 * It causes the quantifiers to be ungreedy by default.
348 * Appending a ? turns back to greedy (!).
350 * - Added a new interceptor ijb-send-banner, which
351 * sends back the "Junkbuster" gif. Without imagelist or
352 * MSIE detection support, or if tinygif = 1, or the
353 * URL isn't recognized as an imageurl, a lame HTML
354 * explanation is sent instead.
356 * - Added new feature, which permits blocking remote
357 * script redirects and firing back a local redirect
359 * The feature is conditionally compiled, i.e. it
360 * can be disabled with --disable-fast-redirects,
361 * plus it must be activated by a "fast-redirects"
362 * line in the config file, has its own log level
363 * and of course wants to be displayed by show-proxy-args
364 * Note: Boy, all the #ifdefs in 1001 locations and
365 * all the fumbling with configure.in and acconfig.h
366 * were *way* more work than the feature itself :-(
368 * - Because a generic redirect template was needed for
369 * this, tinygif = 3 now uses the same.
371 * - Moved GIFs, and other static HTTP response templates
376 * - Removed some >400 CRs again (Jon, you really worked
379 * Revision 1.4 2001/05/21 19:34:01 jongfoster
380 * Made failure to bind() a fatal error.
382 * Revision 1.3 2001/05/20 01:21:20 jongfoster
383 * Version 2.9.4 checkin.
384 * - Merged popupfile and cookiefile, and added control over PCRS
385 * filtering, in new "permissionsfile".
386 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
387 * file error you now get a message box (in the Win32 GUI) rather
388 * than the program exiting with no explanation.
389 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
391 * - Removed tabs from "config"
392 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
393 * - Bumped up version number.
395 * Revision 1.2 2001/05/17 22:34:44 oes
396 * - Added hint on GIF char array generation to jcc.c
397 * - Cleaned CRLF's from the sources and related files
398 * - Repaired logging for REF and FRC
400 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
401 * Initial import of version 2.9.3 source tree
404 *********************************************************************/
410 #include <sys/types.h>
417 #ifdef FEATURE_PTHREAD
419 #endif /* def FEATURE_PTHREAD */
422 # ifndef FEATURE_PTHREAD
423 # include <windows.h>
424 # include <process.h>
425 # endif /* ndef FEATURE_PTHREAD */
428 # ifndef _WIN_CONSOLE
430 # endif /* ndef _WIN_CONSOLE */
432 #else /* ifndef _WIN32 */
434 # if !defined (__OS2__)
436 # include <sys/wait.h>
437 # endif /* ndef __OS2__ */
438 # include <sys/time.h>
439 # include <sys/stat.h>
440 # include <sys/ioctl.h>
443 #include <sys/termios.h>
449 # include <socket.h> /* BeOS has select() for sockets only. */
450 # include <OS.h> /* declarations for threads and stuff. */
453 # if defined(__EMX__) || defined(__OS2__)
454 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
459 #define bzero(B,N) memset(B,0x00,n)
474 #include "killpopup.h"
475 #include "miscutil.h"
477 #include "jbsockets.h"
482 #include "urlmatch.h"
484 const char jcc_h_rcs[] = JCC_H_VERSION;
485 const char project_h_rcs[] = PROJECT_H_VERSION;
488 struct client_state clients[1];
489 struct file_list files[1];
491 #ifdef FEATURE_STATISTICS
492 int urls_read = 0; /* total nr of urls read inc rejected */
493 int urls_rejected = 0; /* total nr of urls rejected */
494 #endif /* def FEATURE_STATISTICS */
497 static void listen_loop(void);
498 static void chat(struct client_state *csp);
500 void serve(struct client_state *csp);
501 #else /* ifndef AMIGA */
502 static void serve(struct client_state *csp);
503 #endif /* def AMIGA */
506 static int32 server_thread(void *data);
507 #endif /* def __BEOS__ */
510 #define sleep(N) Sleep(((N) * 1000))
514 #define sleep(N) DosSleep(((N) * 100))
519 const char *pidfile = NULL;
520 int received_hup_signal = 0;
521 #endif /* defined unix */
523 /* The vanilla wafer. */
524 static const char VANILLA_WAFER[] =
525 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
526 "Do_not_send_me_any_copyrighted_information_other_than_the_"
527 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
528 "In_particular_do_not_send_me_any_cookies_that_"
529 "are_subject_to_a_claim_of_copyright_by_anybody._"
530 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
531 "(copyright_or_otherwise)_applying_to_any_cookie._";
534 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
535 /*********************************************************************
537 * Function : sig_handler
539 * Description : Signal handler for different signals.
540 * Exit gracefully on ABRT, TERM and INT
541 * or set a flag that will cause the errlog
542 * to be reopened by the main thread on HUP.
545 * 1 : the_signal - the signal cause this function to call
549 *********************************************************************/
550 static void sig_handler(int the_signal)
557 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
565 received_hup_signal = 1;
570 * We shouldn't be here, unless we catch signals
571 * in main() that we can't handle here!
573 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
581 /*********************************************************************
585 * Description : Once a connection to the client has been accepted,
586 * this function is called (via serve()) to handle the
587 * main business of the communication. When this
588 * function returns, the caller must close the client
592 * 1 : csp = Current client state (buffers, headers, etc...)
594 * Returns : On success, the number of bytes written are returned (zero
595 * indicates nothing was written). On error, -1 is returned,
596 * and errno is set appropriately. If count is zero and the
597 * file descriptor refers to a regular file, 0 will be
598 * returned without causing any other effect. For a special
599 * file, the results are not portable.
601 *********************************************************************/
602 static void chat(struct client_state *csp)
605 * This next lines are a little ugly, but they simplifies the if statements
606 * below. Basically if TOGGLE, then we want the if to test if the
607 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
608 * then we want the if to test for CSP_FLAG_FORCED , else we don't
610 #ifdef FEATURE_TOGGLE
611 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
612 #else /* ifndef FEATURE_TOGGLE */
613 # define IS_TOGGLED_ON_AND
614 #endif /* ndef FEATURE_TOGGLE */
615 #ifdef FEATURE_FORCE_LOAD
616 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
617 #else /* ifndef FEATURE_FORCE_LOAD */
618 # define IS_NOT_FORCED_AND
619 #endif /* def FEATURE_FORCE_LOAD */
621 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
623 char buf[BUFFER_SIZE];
626 int n, maxfd, server_body;
627 int ms_iis5_hack = 0;
629 const struct forward_spec * fwd;
630 struct http_request *http;
631 #ifdef FEATURE_KILL_POPUPS
632 int block_popups; /* bool, 1==will block popups */
633 int block_popups_now = 0; /* bool, 1==currently blocking popups */
634 #endif /* def FEATURE_KILL_POPUPS */
636 int pcrs_filter; /* bool, 1==will filter through pcrs */
637 int gif_deanimate; /* bool, 1==will deanimate gifs */
639 /* Function that does the content filtering for the current request */
640 char *(*content_filter)() = NULL;
642 /* Skeleton for HTTP response, if we should intercept the request */
643 struct http_response *rsp;
648 * Read the client's request. Note that since we're not using select() we
649 * could get blocked here if a client connected, then didn't say anything!
654 n = read_socket(csp->cfd, buf, sizeof(buf));
656 if (n <= 0) break; /* error! */
658 add_to_iob(csp, buf, n);
660 req = get_header(csp);
664 break; /* no HTTP request! */
669 continue; /* more to come! */
672 #ifdef FEATURE_FORCE_LOAD
673 /* If this request contains the FORCE_PREFIX,
674 * better get rid of it now and set the force flag --oes
677 if (strstr(req, FORCE_PREFIX))
679 strclean(req, FORCE_PREFIX);
680 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
681 csp->flags |= CSP_FLAG_FORCED;
684 #endif /* def FEATURE_FORCE_LOAD */
686 parse_http_request(req, http, csp);
691 if (http->cmd == NULL)
693 strcpy(buf, CHEADER);
694 write_socket(csp->cfd, buf, strlen(buf));
696 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
701 /* decide how to route the HTTP request */
703 if ((fwd = forward_url(http, csp)) == NULL)
705 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
706 /* Never get here - LOG_LEVEL_FATAL causes program exit */
709 /* build the http request to send to the server
710 * we have to do one of the following:
712 * create = use the original HTTP request to create a new
713 * HTTP request that has either the path component
714 * without the http://domainspec (w/path) or the
715 * full orininal URL (w/url)
716 * Note that the path and/or the HTTP version may
717 * have been altered by now.
719 * connect = Open a socket to the host:port of the server
720 * and short-circuit server and client socket.
722 * pass = Pass the request unchanged if forwarding a CONNECT
723 * request to a parent proxy. Note that we'll be sending
724 * the CFAIL message ourselves if connecting to the parent
725 * fails, but we won't send a CSUCCEED message if it works,
726 * since that would result in a double message (ours and the
727 * parent's). After sending the request to the parent, we simply
733 * +--------+--------+
735 * 0 | create | connect|
737 * Forwarding +--------+--------+
739 * 1 | create | pass |
741 * +--------+--------+
746 * Determine the actions for this URL
748 #ifdef FEATURE_TOGGLE
749 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
751 /* Most compatible set of actions (i.e. none) */
752 init_current_action(csp->action);
755 #endif /* ndef FEATURE_TOGGLE */
757 url_actions(http, csp);
762 * Check if a CONNECT request is allowable:
763 * In the absence of a +limit-connect action, allow only port 443.
764 * If there is an action, allow whatever matches the specificaton.
768 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
769 || (csp->action->flags & ACTION_LIMIT_CONNECT
770 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
772 strcpy(buf, CFORBIDDEN);
773 write_socket(csp->cfd, buf, strlen(buf));
775 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
776 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
784 * Downgrade http version from 1.1 to 1.0 if +downgrade
787 if ( (http->ssl == 0)
788 && (!strcmpic(http->ver, "HTTP/1.1"))
789 && (csp->action->flags & ACTION_DOWNGRADE))
792 http->ver = strdup("HTTP/1.0");
794 if (http->ver == NULL)
796 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
801 * Save a copy of the original request for logging
803 http->ocmd = strdup(http->cmd);
805 if (http->ocmd == NULL)
807 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
811 * (Re)build the HTTP request for non-SSL requests.
812 * If forwarding, use the whole URL, else, use only the path.
818 http->cmd = strdup(http->gpc);
819 string_append(&http->cmd, " ");
821 if (fwd->forward_host)
823 string_append(&http->cmd, http->url);
827 string_append(&http->cmd, http->path);
830 string_append(&http->cmd, " ");
831 string_append(&http->cmd, http->ver);
833 if (http->cmd == NULL)
835 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
838 enlist(csp->headers, http->cmd);
841 #ifdef FEATURE_COOKIE_JAR
843 * If we're logging cookies in a cookie jar, and the user has not
844 * supplied any wafers, and the user has not told us to suppress the
845 * vanilla wafer, then send the vanilla wafer.
847 if ((csp->config->jarfile != NULL)
848 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
849 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
851 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
853 #endif /* def FEATURE_COOKIE_JAR */
856 #ifdef FEATURE_KILL_POPUPS
857 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
858 #endif /* def FEATURE_KILL_POPUPS */
860 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
861 ((csp->action->flags & ACTION_FILTER) != 0);
863 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
865 /* grab the rest of the client's headers */
869 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
871 n = read_socket(csp->cfd, buf, sizeof(buf));
874 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
877 add_to_iob(csp, buf, n);
881 if (p == NULL) break;
883 enlist(csp->headers, p);
887 * We have a request. Now, check to see if we need to
888 * intercept it, i.e. If ..
892 /* a CGI call was detected and answered */
893 (NULL != (rsp = dispatch_cgi(csp)))
895 /* or we are enabled and... */
898 /* ..the request was blocked */
899 ( NULL != (rsp = block_url(csp)))
903 || ( NULL != (rsp = trust_url(csp)))
904 #endif /* def FEATURE_TRUST */
906 /* ..or a fast redirect kicked in */
907 #ifdef FEATURE_FAST_REDIRECTS
908 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
909 (NULL != (rsp = redirect_url(csp))))
910 #endif /* def FEATURE_FAST_REDIRECTS */
914 /* Write the answer to the client */
915 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
916 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
918 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
921 #ifdef FEATURE_STATISTICS
922 /* Count as a rejected request */
923 csp->flags |= CSP_FLAG_REJECTED;
924 #endif /* def FEATURE_STATISTICS */
926 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
927 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
928 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
930 /* Clean up and return */
931 free_http_response(rsp);
935 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
937 if (fwd->forward_host)
939 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
940 fwd->forward_host, fwd->forward_port, http->hostport);
944 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
947 /* here we connect to the server, gateway, or the forwarder */
949 csp->sfd = forwarded_connect(fwd, http, csp);
953 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
958 rsp = error_response(csp, "no-such-domain", errno);
960 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
961 csp->ip_addr_str, http->ocmd);
965 rsp = error_response(csp, "connect-failed", errno);
967 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
968 csp->ip_addr_str, http->ocmd);
972 /* Write the answer to the client */
975 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
976 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
978 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
982 free_http_response(rsp);
986 log_error(LOG_LEVEL_CONNECT, "OK");
988 hdr = sed(client_patterns, add_client_headers, csp);
991 /* FIXME Should handle error properly */
992 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
995 list_remove_all(csp->headers);
997 if (fwd->forward_host || (http->ssl == 0))
999 /* write the client's (modified) header to the server
1000 * (along with anything else that may be in the buffer)
1005 if ((write_socket(csp->sfd, hdr, n) != n)
1006 || (flush_socket(csp->sfd, csp ) < 0))
1008 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1011 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1012 csp->ip_addr_str, http->ocmd);
1014 rsp = error_response(csp, "connect-failed", errno);
1018 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1019 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1021 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1025 free_http_response(rsp);
1033 * We're running an SSL tunnel and we're not forwarding,
1034 * so just send the "connect succeeded" message to the
1035 * client, flush the rest, and get out of the way.
1037 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1038 csp->ip_addr_str, http->ocmd);
1040 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
1048 /* we're finished with the client's header */
1051 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1053 /* pass data between the client and server
1054 * until one or the other shuts down the connection.
1063 FD_SET(csp->cfd, &rfds);
1064 FD_SET(csp->sfd, &rfds);
1066 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1070 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1074 /* this is the body of the browser's request
1075 * just read it and write it.
1078 if (FD_ISSET(csp->cfd, &rfds))
1080 n = read_socket(csp->cfd, buf, sizeof(buf));
1084 break; /* "game over, man" */
1087 if (write_socket(csp->sfd, buf, n) != n)
1089 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1096 * The server wants to talk. It could be the header or the body.
1097 * If `hdr' is null, then it's the header otherwise it's the body.
1098 * FIXME: Does `hdr' really mean `host'? No.
1102 if (FD_ISSET(csp->sfd, &rfds))
1105 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1109 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1111 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1112 csp->ip_addr_str, http->ocmd);
1114 rsp = error_response(csp, "connect-failed", errno);
1118 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1119 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1121 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1125 free_http_response(rsp);
1129 /* Add a trailing zero. This lets filter_popups
1130 * use string operations.
1134 #ifdef FEATURE_KILL_POPUPS
1135 /* Filter the popups on this read. */
1136 if (block_popups_now)
1138 filter_popups(buf, csp);
1140 #endif /* def FEATURE_KILL_POPUPS */
1142 /* Normally, this would indicate that we've read
1143 * as much as the server has sent us and we can
1144 * close the client connection. However, Microsoft
1145 * in its wisdom has released IIS/5 with a bug that
1146 * prevents it from sending the trailing \r\n in
1147 * a 302 redirect header (and possibly other headers).
1148 * To work around this if we've haven't parsed
1149 * a full header we'll append a trailing \r\n
1150 * and see if this now generates a valid one.
1152 * This hack shouldn't have any impacts. If we've
1153 * already transmitted the header or if this is a
1154 * SSL connection, then we won't bother with this
1155 * hack. So we only work on partially received
1156 * headers. If we append a \r\n and this still
1157 * doesn't generate a valid header, then we won't
1158 * transmit anything to the client.
1163 if (server_body || http->ssl)
1166 * If we have been buffering up the document,
1167 * now is the time to apply content modification
1168 * and send the result to the client.
1173 * If the content filter fails, use the original
1174 * buffer and length.
1175 * (see p != NULL ? p : csp->iob->cur below)
1177 if (NULL == (p = (*content_filter)(csp)))
1179 csp->content_length = csp->iob->eod - csp->iob->cur;
1182 hdr = sed(server_patterns, add_server_headers, csp);
1185 /* FIXME Should handle error properly */
1186 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1191 if ((write_socket(csp->cfd, hdr, n) != n)
1192 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1194 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1204 break; /* "game over, man" */
1208 * This is NOT the body, so
1209 * Let's pretend the server just sent us a blank line.
1211 n = sprintf(buf, "\r\n");
1214 * Now, let the normal header parsing algorithm below do its
1215 * job. If it fails, we'll exit instead of continuing.
1222 * If this is an SSL connection or we're in the body
1223 * of the server document, just write it to the client,
1224 * unless we need to buffer the body for later content-filtering
1227 if (server_body || http->ssl)
1231 add_to_iob(csp, buf, n);
1234 * If the buffer limit will be reached on the next read,
1235 * switch to non-filtering mode, i.e. make & write the
1236 * header, flush the socket and get out of the way.
1238 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1240 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1242 hdr = sed(server_patterns, add_server_headers, csp);
1245 /* FIXME Should handle error properly */
1246 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1252 if (((write_socket(csp->cfd, hdr, n) != n)
1253 || (n = flush_socket(csp->cfd, csp) < 0)))
1255 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1264 content_filter = NULL;
1271 if (write_socket(csp->cfd, buf, n) != n)
1273 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1282 /* we're still looking for the end of the
1283 * server's header ... (does that make header
1284 * parsing an "out of body experience" ?
1287 /* buffer up the data we just read */
1288 add_to_iob(csp, buf, n);
1290 /* get header lines from the iob */
1292 while ((p = get_header(csp)))
1296 /* see following note */
1299 enlist(csp->headers, p);
1303 /* NOTE: there are no "empty" headers so
1304 * if the pointer `p' is not NULL we must
1305 * assume that we reached the end of the
1306 * buffer before we hit the end of the header.
1313 /* Well, we tried our MS IIS/5
1314 * hack and it didn't work.
1315 * The header is incomplete
1316 * and there isn't anything
1317 * we can do about it.
1323 /* Since we have to wait for
1324 * more from the server before
1325 * we can parse the headers
1326 * we just continue here.
1332 /* we have now received the entire header.
1333 * filter it and send the result to the client
1336 hdr = sed(server_patterns, add_server_headers, csp);
1339 /* FIXME Should handle error properly */
1340 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1345 /* write the server's (modified) header to
1346 * the client (along with anything else that
1347 * may be in the buffer)
1350 #ifdef FEATURE_KILL_POPUPS
1351 /* Start blocking popups if appropriate. */
1353 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1354 !http->ssl && /* We talk plaintext */
1355 block_popups) /* Policy allows */
1357 block_popups_now = 1;
1359 * Filter the part of the body that came in the same read
1360 * as the last headers:
1362 filter_popups(csp->iob->cur, csp);
1365 #endif /* def FEATURE_KILL_POPUPS */
1367 /* Buffer and pcrs filter this if appropriate. */
1369 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1370 !http->ssl && /* We talk plaintext */
1371 pcrs_filter) /* Policy allows */
1373 content_filter = pcrs_filter_response;
1376 /* Buffer and gif_deanimate this if appropriate. */
1378 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1379 !http->ssl && /* We talk plaintext */
1380 gif_deanimate) /* Policy allows */
1382 content_filter = gif_deanimate_response;
1387 * Only write if we're not buffering for content modification
1389 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1390 || (n = flush_socket(csp->cfd, csp) < 0)))
1392 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1394 /* the write failed, so don't bother
1395 * mentioning it to the client...
1396 * it probably can't hear us anyway.
1402 if(!content_filter) byte_count += n;
1404 /* we're finished with the server's header */
1409 /* If this was a MS IIS/5 hack then it means
1410 * the server has already closed the
1411 * connection. Nothing more to read. Time
1422 return; /* huh? we should never get here */
1425 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1426 csp->ip_addr_str, http->ocmd, byte_count);
1430 /*********************************************************************
1434 * Description : This is little more than chat. We only "serve" to
1435 * to close any socket that chat may have opened.
1438 * 1 : csp = Current client state (buffers, headers, etc...)
1442 *********************************************************************/
1444 void serve(struct client_state *csp)
1445 #else /* ifndef AMIGA */
1446 static void serve(struct client_state *csp)
1447 #endif /* def AMIGA */
1450 close_socket(csp->cfd);
1454 close_socket(csp->sfd);
1457 csp->flags &= ~CSP_FLAG_ACTIVE;
1463 /*********************************************************************
1465 * Function : server_thread
1467 * Description : We only exist to call `serve' in a threaded environment.
1470 * 1 : data = Current client state (buffers, headers, etc...)
1472 * Returns : Always 0.
1474 *********************************************************************/
1475 static int32 server_thread(void *data)
1477 serve((struct client_state *) data);
1484 /*********************************************************************
1488 * Description : Print usage info & exit.
1490 * Parameters : Pointer to argv[0] for identifying ourselves
1494 *********************************************************************/
1495 void usage(const char *myname)
1497 printf("JunkBuster proxy version " VERSION " (" HOME_PAGE_URL ")\n"
1498 "Usage: %s [--no-daemon] [--pidfile pidfile] [--help] [configfile]\n"
1499 "Aborting.\n", myname);
1506 /*********************************************************************
1510 * Description : Load the config file and start the listen loop.
1511 * This function is a lot more *sane* with the `load_config'
1512 * and `listen_loop' functions; although it stills does
1513 * a *little* too much for my taste.
1516 * 1 : argc = Number of parameters (including $0).
1517 * 2 : argv = Array of (char *)'s to the parameters.
1519 * Returns : 1 if : can't open config file, unrecognized directive,
1520 * stats requested in multi-thread mode, can't open the
1521 * log file, can't open the jar file, listen port is invalid,
1522 * any load fails, and can't bind port.
1524 * Else main never returns, the process must be signaled
1525 * to terminate execution. Or, on Windows, use the
1526 * "File", "Exit" menu option.
1528 *********************************************************************/
1530 int real_main(int argc, const char *argv[])
1532 int main(int argc, const char *argv[])
1541 #if !defined(_WIN32)
1549 * Parse the command line arguments
1551 while (++argc_pos < argc)
1553 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1555 if (strcmp(argv[argc_pos], "--help") == 0)
1560 else if(strcmp(argv[argc_pos], "--version") == 0)
1562 printf("Junkbuster version " VERSION " (" HOME_PAGE_URL ")\n");
1566 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1571 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1573 if (++argc_pos == argc) usage(argv[0]);
1574 pidfile = strdup(argv[argc_pos]);
1577 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1581 configfile = argv[argc_pos];
1584 } /* -END- while (more arguments) */
1587 if ( *configfile != '/' )
1591 DBG(1, ("configfile before '%s'\n",configfile) );
1593 /* make config-filename absolute here */
1594 if ( !(basedir = getcwd( NULL, 1024 )))
1596 perror("get working dir failed");
1599 DBG(1, ("working dir '%s'\n",basedir) );
1600 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1602 perror("malloc failed");
1605 strcpy( abs_file, basedir );
1606 strcat( abs_file, "/" );
1607 strcat( abs_file, configfile );
1608 configfile = abs_file;
1609 DBG(1, ("configfile after '%s'\n",configfile) );
1611 #endif /* defined unix */
1618 #elif defined(_WIN32)
1623 * Unix signal handling
1625 * Catch the abort, interrupt and terminate signals for a graceful exit
1626 * Catch the hangup signal so the errlog can be reopened.
1627 * Ignore the broken pipe and child signals
1628 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1630 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1633 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1634 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1636 for (idx = 0; catched_signals[idx] != 0; idx++)
1638 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1640 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1644 for (idx = 0; ignored_signals[idx] != 0; idx++)
1646 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1648 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1653 #else /* ifdef _WIN32 */
1654 # ifdef _WIN_CONSOLE
1656 * We *are* in a windows console app.
1657 * Print a verbose messages about FAQ's and such
1659 printf(win32_blurb);
1660 # endif /* def _WIN_CONSOLE */
1661 #endif /* def _WIN32 */
1664 /* Initialize the CGI subsystem */
1665 cgi_init_error_messages();
1668 * If runnig on unix and without the --nodaemon
1669 * option, become a daemon. I.e. fork, detach
1670 * from tty and get process group leadership
1683 if ( pid < 0 ) /* error */
1688 else if ( pid != 0 ) /* parent */
1693 * must check for errors
1694 * child died due to missing files aso
1697 wpid = waitpid( pid, &status, WNOHANG );
1706 /* Should be more portable, but not as well tested */
1711 #else /* ndef __FreeBSD__ */
1713 #endif /* ndef __FreeBSD__ */
1714 fd = open("/dev/tty", O_RDONLY);
1717 /* no error check here */
1718 ioctl( fd, TIOCNOTTY,0 );
1722 /* FIXME: should close stderr (fd 2) here too, but the test
1724 * and load config file is done in listen_loop() and puts
1725 * some messages on stderr there.
1734 } /* -END- if (!no_daemon) */
1736 #endif /* defined unix */
1738 DBG(1, ("call listen_loop() \n") );
1747 /*********************************************************************
1749 * Function : listen_loop
1751 * Description : bind the listen port and enter a "FOREVER" listening loop.
1757 *********************************************************************/
1758 static void listen_loop(void)
1760 struct client_state *csp = NULL;
1762 struct configuration_spec * config;
1764 config = load_config();
1766 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1767 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1769 bfd = bind_port(config->haddr, config->hport);
1773 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1774 "- There may be another junkbuster or some other "
1775 "proxy running on port %d",
1776 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1777 config->hport, config->hport
1779 /* shouldn't get here */
1783 config->need_bind = 0;
1787 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1788 while (waitpid(-1, NULL, WNOHANG) > 0)
1790 /* zombie children */
1792 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1795 * Free data that was used by died threads
1800 * Re-open the errlog after HUP signal
1802 if (received_hup_signal)
1804 init_error_log(Argv[0], config->logfile, config->debug);
1805 received_hup_signal = 0;
1808 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1810 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1814 csp->flags |= CSP_FLAG_ACTIVE;
1817 csp->config = config = load_config();
1819 if ( config->need_bind )
1822 * Since we were listening to the "old port", we will not see
1823 * a "listen" param change until the next IJB request. So, at
1824 * least 1 more request must be made for us to find the new
1825 * setting. I am simply closing the old socket and binding the
1828 * Which-ever is correct, we will serve 1 more page via the
1829 * old settings. This should probably be a "show-proxy-args"
1830 * request. This should not be a so common of an operation
1831 * that this will hurt people's feelings.
1836 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1837 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1838 bfd = bind_port(config->haddr, config->hport);
1842 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1843 "- There may be another junkbuster or some other "
1844 "proxy running on port %d",
1845 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1846 config->hport, config->hport
1848 /* shouldn't get here */
1852 config->need_bind = 0;
1855 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1857 if (!accept_connection(csp, bfd))
1859 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1872 log_error(LOG_LEVEL_CONNECT, "OK");
1875 #ifdef FEATURE_TOGGLE
1878 csp->flags |= CSP_FLAG_TOGGLED_ON;
1880 #endif /* def FEATURE_TOGGLE */
1882 if (run_loader(csp))
1884 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1885 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1889 if (block_acl(NULL,csp))
1891 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1892 close_socket(csp->cfd);
1896 #endif /* def FEATURE_ACL */
1898 /* add it to the list of clients */
1899 csp->next = clients->next;
1900 clients->next = csp;
1902 if (config->multi_threaded)
1906 /* this is a switch () statment in the C preprocessor - ugh */
1907 #undef SELECTED_ONE_OPTION
1909 /* Use Pthreads in preference to native code */
1910 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1911 #define SELECTED_ONE_OPTION
1913 pthread_t the_thread;
1914 pthread_attr_t attrs;
1916 pthread_attr_init(&attrs);
1917 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1918 child_id = (pthread_create(&the_thread, &attrs,
1919 (void*)serve, csp) ? -1 : 0);
1920 pthread_attr_destroy(&attrs);
1924 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1925 #define SELECTED_ONE_OPTION
1926 child_id = _beginthread(
1932 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1933 #define SELECTED_ONE_OPTION
1934 child_id = _beginthread(
1941 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1942 #define SELECTED_ONE_OPTION
1944 thread_id tid = spawn_thread
1945 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1947 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1949 child_id = (int) tid;
1958 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1959 #define SELECTED_ONE_OPTION
1960 csp->cfd = ReleaseSocket(csp->cfd, -1);
1961 if((child_id = (int)CreateNewProcTags(
1962 NP_Entry, (ULONG)server_thread,
1963 NP_Output, Output(),
1964 NP_CloseOutput, FALSE,
1965 NP_Name, (ULONG)"junkbuster child",
1966 NP_StackSize, 200*1024,
1970 ((struct Task *)child_id)->tc_UserData = csp;
1971 Signal((struct Task *)child_id, SIGF_SINGLE);
1976 #if !defined(SELECTED_ONE_OPTION)
1979 /* This block is only needed when using fork().
1980 * When using threads, the server thread was
1981 * created and run by the call to _beginthread().
1983 if (child_id == 0) /* child */
1989 else if (child_id > 0) /* parent */
1991 /* in a fork()'d environment, the parent's
1992 * copy of the client socket and the CSP
1996 #if !defined(_WIN32) && defined(__CYGWIN__)
1998 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1999 close_socket(csp->cfd);
2000 csp->flags &= ~CSP_FLAG_ACTIVE;
2004 #undef SELECTED_ONE_OPTION
2005 /* end of cpp switch () */
2007 if (child_id < 0) /* failed */
2009 char buf[BUFFER_SIZE];
2011 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2013 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
2015 write_socket(csp->cfd, buf, strlen(buf));
2016 close_socket(csp->cfd);
2017 csp->flags &= ~CSP_FLAG_ACTIVE;