1 const char jcc_rcs[] = "$Id: jcc.c,v 1.65 2002/03/03 14:49:11 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.65 2002/03/03 14:49:11 oes
37 * Fixed CLF logging: Now uses client's original HTTP request
39 * Revision 1.64 2002/03/03 09:18:03 joergs
40 * Made jumbjuster work on AmigaOS again.
42 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
43 * Clean up a little CRLF unpleasantness that suddenly appeared
45 * Revision 1.62 2002/02/20 23:17:23 jongfoster
46 * Detecting some out-of memory conditions and exiting with a log message.
48 * Revision 1.61 2002/01/17 21:01:52 jongfoster
49 * Moving all our URL and URL pattern parsing code to urlmatch.c.
51 * Revision 1.60 2001/12/30 14:07:32 steudten
52 * - Add signal handling (unix)
53 * - Add SIGHUP handler (unix)
54 * - Add creation of pidfile (unix)
55 * - Add action 'top' in rc file (RH)
56 * - Add entry 'SIGNALS' to manpage
57 * - Add exit message to logfile (unix)
59 * Revision 1.59 2001/12/13 14:07:18 oes
60 * Fixed Bug: 503 error page now sent OK
62 * Revision 1.58 2001/11/30 23:37:24 jongfoster
63 * Renaming the Win32 config file to config.txt - this is almost the
64 * same as the corresponding UNIX name "config"
66 * Revision 1.57 2001/11/16 00:47:43 jongfoster
67 * Changing the tty-disconnection code to use setsid().
69 * Revision 1.56 2001/11/13 20:20:54 jongfoster
70 * Tabs->spaces, fixing a bug with missing {} around an if()
72 * Revision 1.55 2001/11/13 20:14:53 jongfoster
73 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
75 * Revision 1.54 2001/11/07 00:03:14 steudten
76 * Give reliable return value if an error
77 * occurs not just 0 with new daemon mode.
79 * Revision 1.53 2001/11/05 21:41:43 steudten
80 * Add changes to be a real daemon just for unix os.
81 * (change cwd to /, detach from controlling tty, set
82 * process group and session leader to the own process.
84 * Add some fatal-error log message for failed malloc().
85 * Add '-d' if compiled with 'configure --with-debug' to
86 * enable debug output.
88 * Revision 1.52 2001/10/26 20:11:20 jongfoster
89 * Fixing type mismatch
91 * Revision 1.51 2001/10/26 17:38:28 oes
94 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
95 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
96 * threads to call select() simultaneously. So, it's time to do a real, live,
97 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
98 * (native). Both versions will work, but using __OS2__ offers multi-threading.
100 * Revision 1.49 2001/10/23 21:41:35 jongfoster
101 * Added call to initialize the (statically-allocated of course)
102 * "out of memory" CGI response.
104 * Revision 1.48 2001/10/10 19:56:46 jongfoster
105 * Moving some code that wasn't cookie-related out of an #ifdef
108 * Revision 1.47 2001/10/10 16:44:36 oes
109 * Added CONNECT destination port limitation check
111 * Revision 1.46 2001/10/08 15:17:41 oes
112 * Re-enabled SSL forwarding
114 * Revision 1.45 2001/10/07 15:42:11 oes
115 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
117 * Moved downgrading of the HTTP version from parse_http_request to
118 * chat(), since we can't decide if it is necessary before we have
119 * determined the actions for the URL. The HTTP command is now
120 * *always* re-built so the repairs need no longer be special-cased.
122 * filter_popups now gets a csp pointer so it can raise the new
123 * CSP_FLAG_MODIFIED flag.
127 * Added configurable size limit for the IOB. If the IOB grows so
128 * large that the next read would exceed the limit, the header
129 * is generated, and the header & unfiltered buffer are flushed
130 * to the client. Chat then continues in non-buffering,
131 * non-filtering body mode.
133 * Revision 1.44 2001/10/02 18:13:57 oes
136 * Revision 1.43 2001/10/02 15:32:13 oes
137 * Moved generation of hdr
139 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
140 * Cleaning up 2 compiler warnings on OS/2.
142 * Revision 1.41 2001/09/16 17:05:14 jongfoster
143 * Removing unused #include showarg.h
145 * Revision 1.40 2001/09/16 15:41:45 jongfoster
146 * Fixing signed/unsigned comparison warning.
148 * Revision 1.39 2001/09/16 13:21:27 jongfoster
149 * Changes to use new list functions.
151 * Revision 1.38 2001/09/16 13:01:46 jongfoster
152 * Removing redundant function call that zeroed zalloc()'d memory.
154 * Revision 1.37 2001/09/10 11:12:24 oes
155 * Deleted unused variable
157 * Revision 1.36 2001/09/10 10:56:15 oes
158 * Silenced compiler warnings
160 * Revision 1.35 2001/07/31 14:44:22 oes
161 * Deleted unused size parameter from filter_popups()
163 * Revision 1.34 2001/07/30 22:08:36 jongfoster
164 * Tidying up #defines:
165 * - All feature #defines are now of the form FEATURE_xxx
166 * - Permanently turned off WIN_GUI_EDIT
167 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
169 * Revision 1.33 2001/07/29 19:32:00 jongfoster
170 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
172 * Revision 1.32 2001/07/29 18:47:05 jongfoster
173 * Adding missing #include "loadcfg.h"
175 * Revision 1.31 2001/07/29 12:17:48 oes
176 * Applied pthread fix by Paul Lieverse
178 * Revision 1.30 2001/07/25 22:57:13 jongfoster
179 * __BEOS__ no longer overrides FEATURE_PTHREAD.
180 * This is because FEATURE_PTHREAD will soon be widely used, so I
181 * want to keep it simple.
183 * Revision 1.29 2001/07/24 12:47:06 oes
184 * Applied BeOS support update by Eugenia
186 * Revision 1.28 2001/07/23 13:26:12 oes
187 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
189 * Revision 1.27 2001/07/19 19:09:47 haroon
190 * - Added code to take care of the situation where while processing the first
191 * server response (which includes the server header), after finding the end
192 * of the headers we were not looking past the end of the headers for
193 * content modification. I enabled it for filter_popups.
194 * Someone else should look to see if other similar operations should be
195 * done to the discarded portion of the buffer.
197 * Note 2001/07/20: No, the other content modification mechanisms will process
198 * the whole iob later anyway. --oes
200 * Revision 1.26 2001/07/18 12:31:36 oes
203 * Revision 1.25 2001/07/15 19:43:49 jongfoster
204 * Supports POSIX threads.
205 * Also removed some unused #includes.
207 * Revision 1.24 2001/07/13 14:00:40 oes
208 * - Generic content modification scheme:
209 * Each feature has its own applicability flag that is set
210 * from csp->action->flags.
211 * Replaced the "filtering" int flag , by a function pointer
212 * "content_filter" to the function that will do the content
213 * modification. If it is != NULL, the document will be buffered
214 * and processed through *content_filter, which must set
215 * csp->content_length and return a modified copy of the body
216 * or return NULL (on failiure).
217 * - Changed csp->is_text to the more generic bitmap csp->content_type
218 * which can currently take the valued CT_TEXT or CT_GIF
220 * - Removed all #ifdef PCRS
222 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
223 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
224 * the `block_acl' call. This prevents a compilation error when the user
225 * does not wish to use the "ACL" feature.
227 * Revision 1.22 2001/06/29 21:45:41 oes
228 * Indentation, CRLF->LF, Tab-> Space
230 * Revision 1.21 2001/06/29 13:29:36 oes
231 * - Cleaned up, improved comments
232 * - Unified all possible interceptors (CGI,
233 * block, trust, fast_redirect) in one
234 * place, with one (CGI) answer generation
235 * mechansim. Much clearer now.
236 * - Removed the GIF image generation, which
237 * is now done in filters.c:block_url()
238 * - Made error conditions like domain lookup
239 * failiure or (various) problems while talking
240 * to the server use cgi.c:error_response()
241 * instead of generating HTML/HTTP in chat() (yuck!)
242 * - Removed logentry from cancelled commit
244 * Revision 1.20 2001/06/09 10:55:28 jongfoster
245 * Changing BUFSIZ ==> BUFFER_SIZE
247 * Revision 1.19 2001/06/07 23:12:52 jongfoster
248 * Replacing function pointer in struct gateway with a directly
249 * called function forwarded_connect().
250 * Replacing struct gateway with struct forward_spec
252 * Revision 1.18 2001/06/03 19:12:16 oes
253 * introduced new cgi handling
255 * Revision 1.17 2001/06/01 20:07:23 jongfoster
256 * Now uses action +image-blocker{} rather than config->tinygif
258 * Revision 1.16 2001/06/01 18:49:17 jongfoster
259 * Replaced "list_share" with "list" - the tiny memory gain was not
260 * worth the extra complexity.
262 * Revision 1.15 2001/05/31 21:24:47 jongfoster
263 * Changed "permission" to "action" throughout.
264 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
265 * Moved vanilla wafer check into chat(), since we must now
266 * decide whether or not to add it based on the URL.
268 * Revision 1.14 2001/05/29 20:14:01 joergs
269 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
272 * Revision 1.13 2001/05/29 09:50:24 jongfoster
273 * Unified blocklist/imagelist/permissionslist.
274 * File format is still under discussion, but the internal changes
277 * Also modified interceptor behaviour:
278 * - We now intercept all URLs beginning with one of the following
279 * prefixes (and *only* these prefixes):
281 * * http://ijbswa.sf.net/config/
282 * * http://ijbswa.sourceforge.net/config/
283 * - New interceptors "home page" - go to http://i.j.b/ to see it.
284 * - Internal changes so that intercepted and fast redirect pages
285 * are not replaced with an image.
286 * - Interceptors now have the option to send a binary page direct
287 * to the client. (i.e. ijb-send-banner uses this)
288 * - Implemented show-url-info interceptor. (Which is why I needed
289 * the above interceptors changes - a typical URL is
290 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
291 * The previous mechanism would not have intercepted that, and
292 * if it had been intercepted then it then it would have replaced
295 * Revision 1.12 2001/05/27 22:17:04 oes
297 * - re_process_buffer no longer writes the modified buffer
298 * to the client, which was very ugly. It now returns the
299 * buffer, which it is then written by chat.
301 * - content_length now adjusts the Content-Length: header
302 * for modified documents rather than crunch()ing it.
303 * (Length info in csp->content_length, which is 0 for
304 * unmodified documents)
306 * - For this to work, sed() is called twice when filtering.
308 * Revision 1.11 2001/05/26 17:27:53 jongfoster
309 * Added support for CLF and fixed LOG_LEVEL_LOG.
310 * Also did CRLF->LF fix of my previous patch.
312 * Revision 1.10 2001/05/26 15:26:15 jongfoster
313 * ACL feature now provides more security by immediately dropping
314 * connections from untrusted hosts.
316 * Revision 1.9 2001/05/26 00:28:36 jongfoster
317 * Automatic reloading of config file.
318 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
319 * Most of the global variables have been moved to a new
320 * struct configuration_spec, accessed through csp->config->globalname
321 * Most of the globals remaining are used by the Win32 GUI.
323 * Revision 1.8 2001/05/25 22:43:18 jongfoster
324 * Fixing minor memory leak and buffer overflow.
326 * Revision 1.7 2001/05/25 22:34:30 jongfoster
329 * Revision 1.6 2001/05/23 00:13:58 joergs
330 * AmigaOS support fixed.
332 * Revision 1.5 2001/05/22 18:46:04 oes
334 * - Enabled filtering banners by size rather than URL
335 * by adding patterns that replace all standard banner
336 * sizes with the "Junkbuster" gif to the re_filterfile
338 * - Enabled filtering WebBugs by providing a pattern
339 * which kills all 1x1 images
341 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
342 * which is selected by the (nonstandard and therefore
343 * capital) letter 'U' in the option string.
344 * It causes the quantifiers to be ungreedy by default.
345 * Appending a ? turns back to greedy (!).
347 * - Added a new interceptor ijb-send-banner, which
348 * sends back the "Junkbuster" gif. Without imagelist or
349 * MSIE detection support, or if tinygif = 1, or the
350 * URL isn't recognized as an imageurl, a lame HTML
351 * explanation is sent instead.
353 * - Added new feature, which permits blocking remote
354 * script redirects and firing back a local redirect
356 * The feature is conditionally compiled, i.e. it
357 * can be disabled with --disable-fast-redirects,
358 * plus it must be activated by a "fast-redirects"
359 * line in the config file, has its own log level
360 * and of course wants to be displayed by show-proxy-args
361 * Note: Boy, all the #ifdefs in 1001 locations and
362 * all the fumbling with configure.in and acconfig.h
363 * were *way* more work than the feature itself :-(
365 * - Because a generic redirect template was needed for
366 * this, tinygif = 3 now uses the same.
368 * - Moved GIFs, and other static HTTP response templates
373 * - Removed some >400 CRs again (Jon, you really worked
376 * Revision 1.4 2001/05/21 19:34:01 jongfoster
377 * Made failure to bind() a fatal error.
379 * Revision 1.3 2001/05/20 01:21:20 jongfoster
380 * Version 2.9.4 checkin.
381 * - Merged popupfile and cookiefile, and added control over PCRS
382 * filtering, in new "permissionsfile".
383 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
384 * file error you now get a message box (in the Win32 GUI) rather
385 * than the program exiting with no explanation.
386 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
388 * - Removed tabs from "config"
389 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
390 * - Bumped up version number.
392 * Revision 1.2 2001/05/17 22:34:44 oes
393 * - Added hint on GIF char array generation to jcc.c
394 * - Cleaned CRLF's from the sources and related files
395 * - Repaired logging for REF and FRC
397 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
398 * Initial import of version 2.9.3 source tree
401 *********************************************************************/
407 #include <sys/types.h>
414 #ifdef FEATURE_PTHREAD
416 #endif /* def FEATURE_PTHREAD */
419 # ifndef FEATURE_PTHREAD
420 # include <windows.h>
421 # include <process.h>
422 # endif /* ndef FEATURE_PTHREAD */
425 # ifndef _WIN_CONSOLE
427 # endif /* ndef _WIN_CONSOLE */
429 #else /* ifndef _WIN32 */
431 # if !defined (__OS2__)
433 # include <sys/wait.h>
434 # endif /* ndef __OS2__ */
435 # include <sys/time.h>
436 # include <sys/stat.h>
437 # include <sys/ioctl.h>
440 #include <sys/termios.h>
446 # include <socket.h> /* BeOS has select() for sockets only. */
447 # include <OS.h> /* declarations for threads and stuff. */
450 # if defined(__EMX__) || defined(__OS2__)
451 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
456 #define bzero(B,N) memset(B,0x00,n)
475 #include "killpopup.h"
476 #include "miscutil.h"
478 #include "jbsockets.h"
483 #include "urlmatch.h"
485 const char jcc_h_rcs[] = JCC_H_VERSION;
486 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 #endif /* defined unix */
521 /* The vanilla wafer. */
522 static const char VANILLA_WAFER[] =
523 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
524 "Do_not_send_me_any_copyrighted_information_other_than_the_"
525 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
526 "In_particular_do_not_send_me_any_cookies_that_"
527 "are_subject_to_a_claim_of_copyright_by_anybody._"
528 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
529 "(copyright_or_otherwise)_applying_to_any_cookie._";
532 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
533 /*********************************************************************
535 * Function : SIG_handler
537 * Description : Signal handler for different signals.
538 * see man kill, signal ..
541 * 1 : signal - the signal cause this function to call
545 *********************************************************************/
546 static void SIG_handler( int signal )
551 log_error(LOG_LEVEL_INFO, "ignoring HUP signal (%d)", signal);
554 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", signal);
564 /* want to exit jb so use FATAL */
565 log_error(LOG_LEVEL_FATAL, "SIG_handler: receive signal %d without handler.", signal);
570 /*********************************************************************
574 * Description : Once a connection to the client has been accepted,
575 * this function is called (via serve()) to handle the
576 * main business of the communication. When this
577 * function returns, the caller must close the client
581 * 1 : csp = Current client state (buffers, headers, etc...)
583 * Returns : On success, the number of bytes written are returned (zero
584 * indicates nothing was written). On error, -1 is returned,
585 * and errno is set appropriately. If count is zero and the
586 * file descriptor refers to a regular file, 0 will be
587 * returned without causing any other effect. For a special
588 * file, the results are not portable.
590 *********************************************************************/
591 static void chat(struct client_state *csp)
594 * This next lines are a little ugly, but they simplifies the if statements
595 * below. Basically if TOGGLE, then we want the if to test if the
596 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
597 * then we want the if to test for CSP_FLAG_FORCED , else we don't
599 #ifdef FEATURE_TOGGLE
600 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
601 #else /* ifndef FEATURE_TOGGLE */
602 # define IS_TOGGLED_ON_AND
603 #endif /* ndef FEATURE_TOGGLE */
604 #ifdef FEATURE_FORCE_LOAD
605 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
606 #else /* ifndef FEATURE_FORCE_LOAD */
607 # define IS_NOT_FORCED_AND
608 #endif /* def FEATURE_FORCE_LOAD */
610 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
612 char buf[BUFFER_SIZE];
615 int n, maxfd, server_body;
616 int ms_iis5_hack = 0;
618 const struct forward_spec * fwd;
619 struct http_request *http;
620 #ifdef FEATURE_KILL_POPUPS
621 int block_popups; /* bool, 1==will block popups */
622 int block_popups_now = 0; /* bool, 1==currently blocking popups */
623 #endif /* def FEATURE_KILL_POPUPS */
625 int pcrs_filter; /* bool, 1==will filter through pcrs */
626 int gif_deanimate; /* bool, 1==will deanimate gifs */
628 /* Function that does the content filtering for the current request */
629 char *(*content_filter)() = NULL;
631 /* Skeleton for HTTP response, if we should intercept the request */
632 struct http_response *rsp;
637 * Read the client's request. Note that since we're not using select() we
638 * could get blocked here if a client connected, then didn't say anything!
643 n = read_socket(csp->cfd, buf, sizeof(buf));
645 if (n <= 0) break; /* error! */
647 add_to_iob(csp, buf, n);
649 req = get_header(csp);
653 break; /* no HTTP request! */
658 continue; /* more to come! */
661 #ifdef FEATURE_FORCE_LOAD
662 /* If this request contains the FORCE_PREFIX,
663 * better get rid of it now and set the force flag --oes
666 if (strstr(req, FORCE_PREFIX))
668 strclean(req, FORCE_PREFIX);
669 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
670 csp->flags |= CSP_FLAG_FORCED;
673 #endif /* def FEATURE_FORCE_LOAD */
675 parse_http_request(req, http, csp);
680 if (http->cmd == NULL)
682 strcpy(buf, CHEADER);
683 write_socket(csp->cfd, buf, strlen(buf));
685 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
690 /* decide how to route the HTTP request */
692 if ((fwd = forward_url(http, csp)) == NULL)
694 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
695 /* Never get here - LOG_LEVEL_FATAL causes program exit */
698 /* build the http request to send to the server
699 * we have to do one of the following:
701 * create = use the original HTTP request to create a new
702 * HTTP request that has either the path component
703 * without the http://domainspec (w/path) or the
704 * full orininal URL (w/url)
705 * Note that the path and/or the HTTP version may
706 * have been altered by now.
708 * connect = Open a socket to the host:port of the server
709 * and short-circuit server and client socket.
711 * pass = Pass the request unchanged if forwarding a CONNECT
712 * request to a parent proxy. Note that we'll be sending
713 * the CFAIL message ourselves if connecting to the parent
714 * fails, but we won't send a CSUCCEED message if it works,
715 * since that would result in a double message (ours and the
716 * parent's). After sending the request to the parent, we simply
722 * +--------+--------+
724 * 0 | create | connect|
726 * Forwarding +--------+--------+
728 * 1 | create | pass |
730 * +--------+--------+
735 * Determine the actions for this URL
737 #ifdef FEATURE_TOGGLE
738 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
740 /* Most compatible set of actions (i.e. none) */
741 init_current_action(csp->action);
744 #endif /* ndef FEATURE_TOGGLE */
746 url_actions(http, csp);
751 * Check if a CONNECT request is allowable:
752 * In the absence of a +limit-connect action, allow only port 443.
753 * If there is an action, allow whatever matches the specificaton.
757 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
758 || (csp->action->flags & ACTION_LIMIT_CONNECT
759 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
761 strcpy(buf, CFORBIDDEN);
762 write_socket(csp->cfd, buf, strlen(buf));
764 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
765 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
773 * Downgrade http version from 1.1 to 1.0 if +downgrade
776 if ( (http->ssl == 0)
777 && (!strcmpic(http->ver, "HTTP/1.1"))
778 && (csp->action->flags & ACTION_DOWNGRADE))
781 http->ver = strdup("HTTP/1.0");
783 if (http->ver == NULL)
785 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
790 * Save a copy of the original request for logging
792 http->ocmd = strdup(http->cmd);
794 if (http->ocmd == NULL)
796 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
800 * (Re)build the HTTP request for non-SSL requests.
801 * If forwarding, use the whole URL, else, use only the path.
807 http->cmd = strdup(http->gpc);
808 string_append(&http->cmd, " ");
810 if (fwd->forward_host)
812 string_append(&http->cmd, http->url);
816 string_append(&http->cmd, http->path);
819 string_append(&http->cmd, " ");
820 string_append(&http->cmd, http->ver);
822 if (http->cmd == NULL)
824 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
827 enlist(csp->headers, http->cmd);
830 #ifdef FEATURE_COOKIE_JAR
832 * If we're logging cookies in a cookie jar, and the user has not
833 * supplied any wafers, and the user has not told us to suppress the
834 * vanilla wafer, then send the vanilla wafer.
836 if ((csp->config->jarfile != NULL)
837 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
838 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
840 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
842 #endif /* def FEATURE_COOKIE_JAR */
845 #ifdef FEATURE_KILL_POPUPS
846 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
847 #endif /* def FEATURE_KILL_POPUPS */
849 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
850 ((csp->action->flags & ACTION_FILTER) != 0);
852 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
854 /* grab the rest of the client's headers */
858 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
860 n = read_socket(csp->cfd, buf, sizeof(buf));
863 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
866 add_to_iob(csp, buf, n);
870 if (p == NULL) break;
872 enlist(csp->headers, p);
876 * We have a request. Now, check to see if we need to
877 * intercept it, i.e. If ..
881 /* a CGI call was detected and answered */
882 (NULL != (rsp = dispatch_cgi(csp)))
884 /* or we are enabled and... */
887 /* ..the request was blocked */
888 ( NULL != (rsp = block_url(csp)))
892 || ( NULL != (rsp = trust_url(csp)))
893 #endif /* def FEATURE_TRUST */
895 /* ..or a fast redirect kicked in */
896 #ifdef FEATURE_FAST_REDIRECTS
897 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
898 (NULL != (rsp = redirect_url(csp))))
899 #endif /* def FEATURE_FAST_REDIRECTS */
903 /* Write the answer to the client */
904 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
905 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
907 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
910 #ifdef FEATURE_STATISTICS
911 /* Count as a rejected request */
912 csp->flags |= CSP_FLAG_REJECTED;
913 #endif /* def FEATURE_STATISTICS */
915 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
916 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
917 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
919 /* Clean up and return */
920 free_http_response(rsp);
924 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
926 if (fwd->forward_host)
928 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
929 fwd->forward_host, fwd->forward_port, http->hostport);
933 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
936 /* here we connect to the server, gateway, or the forwarder */
938 csp->sfd = forwarded_connect(fwd, http, csp);
942 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
947 rsp = error_response(csp, "no-such-domain", errno);
949 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
950 csp->ip_addr_str, http->ocmd);
954 rsp = error_response(csp, "connect-failed", errno);
956 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
957 csp->ip_addr_str, http->ocmd);
961 /* Write the answer to the client */
964 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
965 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
967 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
971 free_http_response(rsp);
975 log_error(LOG_LEVEL_CONNECT, "OK");
977 hdr = sed(client_patterns, add_client_headers, csp);
980 /* FIXME Should handle error properly */
981 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
984 list_remove_all(csp->headers);
986 if (fwd->forward_host || (http->ssl == 0))
988 /* write the client's (modified) header to the server
989 * (along with anything else that may be in the buffer)
994 if ((write_socket(csp->sfd, hdr, n) != n)
995 || (flush_socket(csp->sfd, csp ) < 0))
997 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1000 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1001 csp->ip_addr_str, http->ocmd);
1003 rsp = error_response(csp, "connect-failed", errno);
1007 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1008 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1010 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1014 free_http_response(rsp);
1022 * We're running an SSL tunnel and we're not forwarding,
1023 * so just send the "connect succeeded" message to the
1024 * client, flush the rest, and get out of the way.
1026 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1027 csp->ip_addr_str, http->ocmd);
1029 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
1037 /* we're finished with the client's header */
1040 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1042 /* pass data between the client and server
1043 * until one or the other shuts down the connection.
1052 FD_SET(csp->cfd, &rfds);
1053 FD_SET(csp->sfd, &rfds);
1055 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1059 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1063 /* this is the body of the browser's request
1064 * just read it and write it.
1067 if (FD_ISSET(csp->cfd, &rfds))
1069 n = read_socket(csp->cfd, buf, sizeof(buf));
1073 break; /* "game over, man" */
1076 if (write_socket(csp->sfd, buf, n) != n)
1078 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1085 * The server wants to talk. It could be the header or the body.
1086 * If `hdr' is null, then it's the header otherwise it's the body.
1087 * FIXME: Does `hdr' really mean `host'? No.
1091 if (FD_ISSET(csp->sfd, &rfds))
1094 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1098 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1100 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1101 csp->ip_addr_str, http->ocmd);
1103 rsp = error_response(csp, "connect-failed", errno);
1107 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1108 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1110 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1114 free_http_response(rsp);
1118 /* Add a trailing zero. This lets filter_popups
1119 * use string operations.
1123 #ifdef FEATURE_KILL_POPUPS
1124 /* Filter the popups on this read. */
1125 if (block_popups_now)
1127 filter_popups(buf, csp);
1129 #endif /* def FEATURE_KILL_POPUPS */
1131 /* Normally, this would indicate that we've read
1132 * as much as the server has sent us and we can
1133 * close the client connection. However, Microsoft
1134 * in its wisdom has released IIS/5 with a bug that
1135 * prevents it from sending the trailing \r\n in
1136 * a 302 redirect header (and possibly other headers).
1137 * To work around this if we've haven't parsed
1138 * a full header we'll append a trailing \r\n
1139 * and see if this now generates a valid one.
1141 * This hack shouldn't have any impacts. If we've
1142 * already transmitted the header or if this is a
1143 * SSL connection, then we won't bother with this
1144 * hack. So we only work on partially received
1145 * headers. If we append a \r\n and this still
1146 * doesn't generate a valid header, then we won't
1147 * transmit anything to the client.
1152 if (server_body || http->ssl)
1155 * If we have been buffering up the document,
1156 * now is the time to apply content modification
1157 * and send the result to the client.
1162 * If the content filter fails, use the original
1163 * buffer and length.
1164 * (see p != NULL ? p : csp->iob->cur below)
1166 if (NULL == (p = (*content_filter)(csp)))
1168 csp->content_length = csp->iob->eod - csp->iob->cur;
1171 hdr = sed(server_patterns, add_server_headers, csp);
1174 /* FIXME Should handle error properly */
1175 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1180 if ((write_socket(csp->cfd, hdr, n) != n)
1181 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1183 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1193 break; /* "game over, man" */
1197 * This is NOT the body, so
1198 * Let's pretend the server just sent us a blank line.
1200 n = sprintf(buf, "\r\n");
1203 * Now, let the normal header parsing algorithm below do its
1204 * job. If it fails, we'll exit instead of continuing.
1211 * If this is an SSL connection or we're in the body
1212 * of the server document, just write it to the client,
1213 * unless we need to buffer the body for later content-filtering
1216 if (server_body || http->ssl)
1220 add_to_iob(csp, buf, n);
1223 * If the buffer limit will be reached on the next read,
1224 * switch to non-filtering mode, i.e. make & write the
1225 * header, flush the socket and get out of the way.
1227 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1229 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1231 hdr = sed(server_patterns, add_server_headers, csp);
1234 /* FIXME Should handle error properly */
1235 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1241 if (((write_socket(csp->cfd, hdr, n) != n)
1242 || (n = flush_socket(csp->cfd, csp) < 0)))
1244 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1253 content_filter = NULL;
1260 if (write_socket(csp->cfd, buf, n) != n)
1262 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1271 /* we're still looking for the end of the
1272 * server's header ... (does that make header
1273 * parsing an "out of body experience" ?
1276 /* buffer up the data we just read */
1277 add_to_iob(csp, buf, n);
1279 /* get header lines from the iob */
1281 while ((p = get_header(csp)))
1285 /* see following note */
1288 enlist(csp->headers, p);
1292 /* NOTE: there are no "empty" headers so
1293 * if the pointer `p' is not NULL we must
1294 * assume that we reached the end of the
1295 * buffer before we hit the end of the header.
1302 /* Well, we tried our MS IIS/5
1303 * hack and it didn't work.
1304 * The header is incomplete
1305 * and there isn't anything
1306 * we can do about it.
1312 /* Since we have to wait for
1313 * more from the server before
1314 * we can parse the headers
1315 * we just continue here.
1321 /* we have now received the entire header.
1322 * filter it and send the result to the client
1325 hdr = sed(server_patterns, add_server_headers, csp);
1328 /* FIXME Should handle error properly */
1329 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1334 /* write the server's (modified) header to
1335 * the client (along with anything else that
1336 * may be in the buffer)
1339 #ifdef FEATURE_KILL_POPUPS
1340 /* Start blocking popups if appropriate. */
1342 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1343 !http->ssl && /* We talk plaintext */
1344 block_popups) /* Policy allows */
1346 block_popups_now = 1;
1348 * Filter the part of the body that came in the same read
1349 * as the last headers:
1351 filter_popups(csp->iob->cur, csp);
1354 #endif /* def FEATURE_KILL_POPUPS */
1356 /* Buffer and pcrs filter this if appropriate. */
1358 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1359 !http->ssl && /* We talk plaintext */
1360 pcrs_filter) /* Policy allows */
1362 content_filter = pcrs_filter_response;
1365 /* Buffer and gif_deanimate this if appropriate. */
1367 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1368 !http->ssl && /* We talk plaintext */
1369 gif_deanimate) /* Policy allows */
1371 content_filter = gif_deanimate_response;
1376 * Only write if we're not buffering for content modification
1378 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1379 || (n = flush_socket(csp->cfd, csp) < 0)))
1381 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1383 /* the write failed, so don't bother
1384 * mentioning it to the client...
1385 * it probably can't hear us anyway.
1391 if(!content_filter) byte_count += n;
1393 /* we're finished with the server's header */
1398 /* If this was a MS IIS/5 hack then it means
1399 * the server has already closed the
1400 * connection. Nothing more to read. Time
1411 return; /* huh? we should never get here */
1414 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1415 csp->ip_addr_str, http->ocmd, byte_count);
1419 /*********************************************************************
1423 * Description : This is little more than chat. We only "serve" to
1424 * to close any socket that chat may have opened.
1427 * 1 : csp = Current client state (buffers, headers, etc...)
1431 *********************************************************************/
1433 void serve(struct client_state *csp)
1434 #else /* ifndef AMIGA */
1435 static void serve(struct client_state *csp)
1436 #endif /* def AMIGA */
1439 close_socket(csp->cfd);
1443 close_socket(csp->sfd);
1446 csp->flags &= ~CSP_FLAG_ACTIVE;
1452 /*********************************************************************
1454 * Function : server_thread
1456 * Description : We only exist to call `serve' in a threaded environment.
1459 * 1 : data = Current client state (buffers, headers, etc...)
1461 * Returns : Always 0.
1463 *********************************************************************/
1464 static int32 server_thread(void *data)
1466 serve((struct client_state *) data);
1473 /*********************************************************************
1477 * Description : Load the config file and start the listen loop.
1478 * This function is a lot more *sane* with the `load_config'
1479 * and `listen_loop' functions; although it stills does
1480 * a *little* too much for my taste.
1483 * 1 : argc = Number of parameters (including $0).
1484 * 2 : argv = Array of (char *)'s to the parameters.
1486 * Returns : 1 if : can't open config file, unrecognized directive,
1487 * stats requested in multi-thread mode, can't open the
1488 * log file, can't open the jar file, listen port is invalid,
1489 * any load fails, and can't bind port.
1491 * Else main never returns, the process must be signaled
1492 * to terminate execution. Or, on Windows, use the
1493 * "File", "Exit" menu option.
1495 *********************************************************************/
1497 int real_main(int argc, const char *argv[])
1499 int main(int argc, const char *argv[])
1505 #if !defined(_WIN32)
1512 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1513 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1515 printf("JunkBuster proxy version " VERSION ".\n\n"
1516 "Usage: %s [configfile]\n\n"
1517 "See " HOME_PAGE_URL " for details.\n"
1518 "This program is distributed under the GNU GPL, version 2 or later.\n",
1522 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1524 printf(VERSION "\n");
1528 if ((argc >= 2) && (strcmp(argv[1], "-d")==0))
1532 fprintf(stderr,"debugging enabled..\n");
1535 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1540 if (argc > argc_pos )
1542 configfile = argv[argc_pos];
1546 if ( *configfile != '/' )
1550 DBG(1, ("configfile before '%s'\n",configfile) );
1552 /* make config-filename absolute here */
1553 if ( !(basedir = getcwd( NULL, 1024 )))
1555 perror("get working dir failed");
1558 DBG(1, ("working dir '%s'\n",basedir) );
1559 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1561 perror("malloc failed");
1564 strcpy( abs_file, basedir );
1565 strcat( abs_file, "/" );
1566 strcat( abs_file, configfile );
1567 configfile = abs_file;
1568 DBG(1, ("configfile after '%s'\n",configfile) );
1570 #endif /* defined unix */
1577 #elif defined(_WIN32)
1582 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1585 struct sigaction action;
1587 for ( sig = 1; sig < 16; sig++ )
1597 if ( signal(sig, SIG_handler) == SIG_ERR )
1598 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", sig);
1601 if ( signal(SIGPIPE, SIG_IGN) == SIG_ERR )
1602 log_error(LOG_LEVEL_FATAL, "Can't set SIG_IGN to SIGPIPE: %E");
1603 if ( signal(SIGCHLD, SIG_IGN) == SIG_ERR )
1604 log_error(LOG_LEVEL_FATAL, "Can't set SIG_IGN to SIGCHLD: %E");
1605 /* log file reload */
1606 if (!sigaction(SIGHUP,NULL,&action))
1608 action.sa_handler = &SIG_handler;
1609 action.sa_flags = SA_RESTART;
1611 if ( sigaction(SIGHUP,&action,NULL))
1612 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal SIGHUP: %E");
1616 perror("sigaction");
1617 log_error(LOG_LEVEL_FATAL, "Can't get sigaction data for signal SIGHUP");
1622 #else /* ifdef _WIN32 */
1623 # ifdef _WIN_CONSOLE
1625 * We *are* in a windows console app.
1626 * Print a verbose messages about FAQ's and such
1628 printf(win32_blurb);
1629 # endif /* def _WIN_CONSOLE */
1630 #endif /* def _WIN32 */
1633 /* Initialize the CGI subsystem */
1634 cgi_init_error_messages();
1644 * we make us a real daemon
1650 if ( pid < 0 ) /* error */
1655 else if ( pid != 0 ) /* parent */
1660 * must check for errors
1661 * child died due to missing files aso
1664 wpid = waitpid( pid, &status, WNOHANG );
1673 /* Should be more portable, but not as well tested */
1678 #else /* ndef __FreeBSD__ */
1680 #endif /* ndef __FreeBSD__ */
1681 fd = open("/dev/tty", O_RDONLY);
1684 /* no error check here */
1685 ioctl( fd, TIOCNOTTY,0 );
1689 /* should close stderr (fd 2) here too, but the test for existence
1690 ** and load config file is done in listen_loop() and puts
1691 ** some messages on stderr there.
1707 #endif /* defined unix */
1709 DBG(1, ("call listen_loop() \n") );
1718 /*********************************************************************
1720 * Function : listen_loop
1722 * Description : bind the listen port and enter a "FOREVER" listening loop.
1728 *********************************************************************/
1729 static void listen_loop(void)
1731 struct client_state *csp = NULL;
1733 struct configuration_spec * config;
1735 config = load_config();
1737 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1738 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1740 bfd = bind_port(config->haddr, config->hport);
1744 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1745 "- There may be another junkbuster or some other "
1746 "proxy running on port %d",
1747 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1748 config->hport, config->hport
1750 /* shouldn't get here */
1754 config->need_bind = 0;
1758 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1759 while (waitpid(-1, NULL, WNOHANG) > 0)
1761 /* zombie children */
1763 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1766 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1768 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1772 csp->flags |= CSP_FLAG_ACTIVE;
1775 csp->config = config = load_config();
1777 if ( config->need_bind )
1780 * Since we were listening to the "old port", we will not see
1781 * a "listen" param change until the next IJB request. So, at
1782 * least 1 more request must be made for us to find the new
1783 * setting. I am simply closing the old socket and binding the
1786 * Which-ever is correct, we will serve 1 more page via the
1787 * old settings. This should probably be a "show-proxy-args"
1788 * request. This should not be a so common of an operation
1789 * that this will hurt people's feelings.
1794 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1795 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1796 bfd = bind_port(config->haddr, config->hport);
1800 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1801 "- There may be another junkbuster or some other "
1802 "proxy running on port %d",
1803 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1804 config->hport, config->hport
1806 /* shouldn't get here */
1810 config->need_bind = 0;
1813 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1815 if (!accept_connection(csp, bfd))
1817 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1830 log_error(LOG_LEVEL_CONNECT, "OK");
1833 #ifdef FEATURE_TOGGLE
1836 csp->flags |= CSP_FLAG_TOGGLED_ON;
1838 #endif /* def FEATURE_TOGGLE */
1840 if (run_loader(csp))
1842 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1843 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1847 if (block_acl(NULL,csp))
1849 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1850 close_socket(csp->cfd);
1854 #endif /* def FEATURE_ACL */
1856 /* add it to the list of clients */
1857 csp->next = clients->next;
1858 clients->next = csp;
1860 if (config->multi_threaded)
1864 /* this is a switch () statment in the C preprocessor - ugh */
1865 #undef SELECTED_ONE_OPTION
1867 /* Use Pthreads in preference to native code */
1868 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1869 #define SELECTED_ONE_OPTION
1871 pthread_t the_thread;
1872 pthread_attr_t attrs;
1874 pthread_attr_init(&attrs);
1875 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1876 child_id = (pthread_create(&the_thread, &attrs,
1877 (void*)serve, csp) ? -1 : 0);
1878 pthread_attr_destroy(&attrs);
1882 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1883 #define SELECTED_ONE_OPTION
1884 child_id = _beginthread(
1890 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1891 #define SELECTED_ONE_OPTION
1892 child_id = _beginthread(
1899 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1900 #define SELECTED_ONE_OPTION
1902 thread_id tid = spawn_thread
1903 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1905 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1907 child_id = (int) tid;
1916 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1917 #define SELECTED_ONE_OPTION
1918 csp->cfd = ReleaseSocket(csp->cfd, -1);
1919 if((child_id = (int)CreateNewProcTags(
1920 NP_Entry, (ULONG)server_thread,
1921 NP_Output, Output(),
1922 NP_CloseOutput, FALSE,
1923 NP_Name, (ULONG)"junkbuster child",
1924 NP_StackSize, 200*1024,
1928 ((struct Task *)child_id)->tc_UserData = csp;
1929 Signal((struct Task *)child_id, SIGF_SINGLE);
1934 #if !defined(SELECTED_ONE_OPTION)
1937 /* This block is only needed when using fork().
1938 * When using threads, the server thread was
1939 * created and run by the call to _beginthread().
1941 if (child_id == 0) /* child */
1947 else if (child_id > 0) /* parent */
1949 /* in a fork()'d environment, the parent's
1950 * copy of the client socket and the CSP
1954 #if !defined(_WIN32) && defined(__CYGWIN__)
1956 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1957 close_socket(csp->cfd);
1958 csp->flags &= ~CSP_FLAG_ACTIVE;
1962 #undef SELECTED_ONE_OPTION
1963 /* end of cpp switch () */
1965 if (child_id < 0) /* failed */
1967 char buf[BUFFER_SIZE];
1969 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1971 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1973 write_socket(csp->cfd, buf, strlen(buf));
1974 close_socket(csp->cfd);
1975 csp->flags &= ~CSP_FLAG_ACTIVE;