1 const char jcc_rcs[] = "$Id: jcc.c,v 1.63 2002/03/02 04:14:50 david__schmidt 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.63 2002/03/02 04:14:50 david__schmidt
37 * Clean up a little CRLF unpleasantness that suddenly appeared
39 * Revision 1.62 2002/02/20 23:17:23 jongfoster
40 * Detecting some out-of memory conditions and exiting with a log message.
42 * Revision 1.61 2002/01/17 21:01:52 jongfoster
43 * Moving all our URL and URL pattern parsing code to urlmatch.c.
45 * Revision 1.60 2001/12/30 14:07:32 steudten
46 * - Add signal handling (unix)
47 * - Add SIGHUP handler (unix)
48 * - Add creation of pidfile (unix)
49 * - Add action 'top' in rc file (RH)
50 * - Add entry 'SIGNALS' to manpage
51 * - Add exit message to logfile (unix)
53 * Revision 1.59 2001/12/13 14:07:18 oes
54 * Fixed Bug: 503 error page now sent OK
56 * Revision 1.58 2001/11/30 23:37:24 jongfoster
57 * Renaming the Win32 config file to config.txt - this is almost the
58 * same as the corresponding UNIX name "config"
60 * Revision 1.57 2001/11/16 00:47:43 jongfoster
61 * Changing the tty-disconnection code to use setsid().
63 * Revision 1.56 2001/11/13 20:20:54 jongfoster
64 * Tabs->spaces, fixing a bug with missing {} around an if()
66 * Revision 1.55 2001/11/13 20:14:53 jongfoster
67 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
69 * Revision 1.54 2001/11/07 00:03:14 steudten
70 * Give reliable return value if an error
71 * occurs not just 0 with new daemon mode.
73 * Revision 1.53 2001/11/05 21:41:43 steudten
74 * Add changes to be a real daemon just for unix os.
75 * (change cwd to /, detach from controlling tty, set
76 * process group and session leader to the own process.
78 * Add some fatal-error log message for failed malloc().
79 * Add '-d' if compiled with 'configure --with-debug' to
80 * enable debug output.
82 * Revision 1.52 2001/10/26 20:11:20 jongfoster
83 * Fixing type mismatch
85 * Revision 1.51 2001/10/26 17:38:28 oes
88 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
89 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
90 * threads to call select() simultaneously. So, it's time to do a real, live,
91 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
92 * (native). Both versions will work, but using __OS2__ offers multi-threading.
94 * Revision 1.49 2001/10/23 21:41:35 jongfoster
95 * Added call to initialize the (statically-allocated of course)
96 * "out of memory" CGI response.
98 * Revision 1.48 2001/10/10 19:56:46 jongfoster
99 * Moving some code that wasn't cookie-related out of an #ifdef
102 * Revision 1.47 2001/10/10 16:44:36 oes
103 * Added CONNECT destination port limitation check
105 * Revision 1.46 2001/10/08 15:17:41 oes
106 * Re-enabled SSL forwarding
108 * Revision 1.45 2001/10/07 15:42:11 oes
109 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
111 * Moved downgrading of the HTTP version from parse_http_request to
112 * chat(), since we can't decide if it is necessary before we have
113 * determined the actions for the URL. The HTTP command is now
114 * *always* re-built so the repairs need no longer be special-cased.
116 * filter_popups now gets a csp pointer so it can raise the new
117 * CSP_FLAG_MODIFIED flag.
121 * Added configurable size limit for the IOB. If the IOB grows so
122 * large that the next read would exceed the limit, the header
123 * is generated, and the header & unfiltered buffer are flushed
124 * to the client. Chat then continues in non-buffering,
125 * non-filtering body mode.
127 * Revision 1.44 2001/10/02 18:13:57 oes
130 * Revision 1.43 2001/10/02 15:32:13 oes
131 * Moved generation of hdr
133 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
134 * Cleaning up 2 compiler warnings on OS/2.
136 * Revision 1.41 2001/09/16 17:05:14 jongfoster
137 * Removing unused #include showarg.h
139 * Revision 1.40 2001/09/16 15:41:45 jongfoster
140 * Fixing signed/unsigned comparison warning.
142 * Revision 1.39 2001/09/16 13:21:27 jongfoster
143 * Changes to use new list functions.
145 * Revision 1.38 2001/09/16 13:01:46 jongfoster
146 * Removing redundant function call that zeroed zalloc()'d memory.
148 * Revision 1.37 2001/09/10 11:12:24 oes
149 * Deleted unused variable
151 * Revision 1.36 2001/09/10 10:56:15 oes
152 * Silenced compiler warnings
154 * Revision 1.35 2001/07/31 14:44:22 oes
155 * Deleted unused size parameter from filter_popups()
157 * Revision 1.34 2001/07/30 22:08:36 jongfoster
158 * Tidying up #defines:
159 * - All feature #defines are now of the form FEATURE_xxx
160 * - Permanently turned off WIN_GUI_EDIT
161 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
163 * Revision 1.33 2001/07/29 19:32:00 jongfoster
164 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
166 * Revision 1.32 2001/07/29 18:47:05 jongfoster
167 * Adding missing #include "loadcfg.h"
169 * Revision 1.31 2001/07/29 12:17:48 oes
170 * Applied pthread fix by Paul Lieverse
172 * Revision 1.30 2001/07/25 22:57:13 jongfoster
173 * __BEOS__ no longer overrides FEATURE_PTHREAD.
174 * This is because FEATURE_PTHREAD will soon be widely used, so I
175 * want to keep it simple.
177 * Revision 1.29 2001/07/24 12:47:06 oes
178 * Applied BeOS support update by Eugenia
180 * Revision 1.28 2001/07/23 13:26:12 oes
181 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
183 * Revision 1.27 2001/07/19 19:09:47 haroon
184 * - Added code to take care of the situation where while processing the first
185 * server response (which includes the server header), after finding the end
186 * of the headers we were not looking past the end of the headers for
187 * content modification. I enabled it for filter_popups.
188 * Someone else should look to see if other similar operations should be
189 * done to the discarded portion of the buffer.
191 * Note 2001/07/20: No, the other content modification mechanisms will process
192 * the whole iob later anyway. --oes
194 * Revision 1.26 2001/07/18 12:31:36 oes
197 * Revision 1.25 2001/07/15 19:43:49 jongfoster
198 * Supports POSIX threads.
199 * Also removed some unused #includes.
201 * Revision 1.24 2001/07/13 14:00:40 oes
202 * - Generic content modification scheme:
203 * Each feature has its own applicability flag that is set
204 * from csp->action->flags.
205 * Replaced the "filtering" int flag , by a function pointer
206 * "content_filter" to the function that will do the content
207 * modification. If it is != NULL, the document will be buffered
208 * and processed through *content_filter, which must set
209 * csp->content_length and return a modified copy of the body
210 * or return NULL (on failiure).
211 * - Changed csp->is_text to the more generic bitmap csp->content_type
212 * which can currently take the valued CT_TEXT or CT_GIF
214 * - Removed all #ifdef PCRS
216 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
217 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
218 * the `block_acl' call. This prevents a compilation error when the user
219 * does not wish to use the "ACL" feature.
221 * Revision 1.22 2001/06/29 21:45:41 oes
222 * Indentation, CRLF->LF, Tab-> Space
224 * Revision 1.21 2001/06/29 13:29:36 oes
225 * - Cleaned up, improved comments
226 * - Unified all possible interceptors (CGI,
227 * block, trust, fast_redirect) in one
228 * place, with one (CGI) answer generation
229 * mechansim. Much clearer now.
230 * - Removed the GIF image generation, which
231 * is now done in filters.c:block_url()
232 * - Made error conditions like domain lookup
233 * failiure or (various) problems while talking
234 * to the server use cgi.c:error_response()
235 * instead of generating HTML/HTTP in chat() (yuck!)
236 * - Removed logentry from cancelled commit
238 * Revision 1.20 2001/06/09 10:55:28 jongfoster
239 * Changing BUFSIZ ==> BUFFER_SIZE
241 * Revision 1.19 2001/06/07 23:12:52 jongfoster
242 * Replacing function pointer in struct gateway with a directly
243 * called function forwarded_connect().
244 * Replacing struct gateway with struct forward_spec
246 * Revision 1.18 2001/06/03 19:12:16 oes
247 * introduced new cgi handling
249 * Revision 1.17 2001/06/01 20:07:23 jongfoster
250 * Now uses action +image-blocker{} rather than config->tinygif
252 * Revision 1.16 2001/06/01 18:49:17 jongfoster
253 * Replaced "list_share" with "list" - the tiny memory gain was not
254 * worth the extra complexity.
256 * Revision 1.15 2001/05/31 21:24:47 jongfoster
257 * Changed "permission" to "action" throughout.
258 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
259 * Moved vanilla wafer check into chat(), since we must now
260 * decide whether or not to add it based on the URL.
262 * Revision 1.14 2001/05/29 20:14:01 joergs
263 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
266 * Revision 1.13 2001/05/29 09:50:24 jongfoster
267 * Unified blocklist/imagelist/permissionslist.
268 * File format is still under discussion, but the internal changes
271 * Also modified interceptor behaviour:
272 * - We now intercept all URLs beginning with one of the following
273 * prefixes (and *only* these prefixes):
275 * * http://ijbswa.sf.net/config/
276 * * http://ijbswa.sourceforge.net/config/
277 * - New interceptors "home page" - go to http://i.j.b/ to see it.
278 * - Internal changes so that intercepted and fast redirect pages
279 * are not replaced with an image.
280 * - Interceptors now have the option to send a binary page direct
281 * to the client. (i.e. ijb-send-banner uses this)
282 * - Implemented show-url-info interceptor. (Which is why I needed
283 * the above interceptors changes - a typical URL is
284 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
285 * The previous mechanism would not have intercepted that, and
286 * if it had been intercepted then it then it would have replaced
289 * Revision 1.12 2001/05/27 22:17:04 oes
291 * - re_process_buffer no longer writes the modified buffer
292 * to the client, which was very ugly. It now returns the
293 * buffer, which it is then written by chat.
295 * - content_length now adjusts the Content-Length: header
296 * for modified documents rather than crunch()ing it.
297 * (Length info in csp->content_length, which is 0 for
298 * unmodified documents)
300 * - For this to work, sed() is called twice when filtering.
302 * Revision 1.11 2001/05/26 17:27:53 jongfoster
303 * Added support for CLF and fixed LOG_LEVEL_LOG.
304 * Also did CRLF->LF fix of my previous patch.
306 * Revision 1.10 2001/05/26 15:26:15 jongfoster
307 * ACL feature now provides more security by immediately dropping
308 * connections from untrusted hosts.
310 * Revision 1.9 2001/05/26 00:28:36 jongfoster
311 * Automatic reloading of config file.
312 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
313 * Most of the global variables have been moved to a new
314 * struct configuration_spec, accessed through csp->config->globalname
315 * Most of the globals remaining are used by the Win32 GUI.
317 * Revision 1.8 2001/05/25 22:43:18 jongfoster
318 * Fixing minor memory leak and buffer overflow.
320 * Revision 1.7 2001/05/25 22:34:30 jongfoster
323 * Revision 1.6 2001/05/23 00:13:58 joergs
324 * AmigaOS support fixed.
326 * Revision 1.5 2001/05/22 18:46:04 oes
328 * - Enabled filtering banners by size rather than URL
329 * by adding patterns that replace all standard banner
330 * sizes with the "Junkbuster" gif to the re_filterfile
332 * - Enabled filtering WebBugs by providing a pattern
333 * which kills all 1x1 images
335 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
336 * which is selected by the (nonstandard and therefore
337 * capital) letter 'U' in the option string.
338 * It causes the quantifiers to be ungreedy by default.
339 * Appending a ? turns back to greedy (!).
341 * - Added a new interceptor ijb-send-banner, which
342 * sends back the "Junkbuster" gif. Without imagelist or
343 * MSIE detection support, or if tinygif = 1, or the
344 * URL isn't recognized as an imageurl, a lame HTML
345 * explanation is sent instead.
347 * - Added new feature, which permits blocking remote
348 * script redirects and firing back a local redirect
350 * The feature is conditionally compiled, i.e. it
351 * can be disabled with --disable-fast-redirects,
352 * plus it must be activated by a "fast-redirects"
353 * line in the config file, has its own log level
354 * and of course wants to be displayed by show-proxy-args
355 * Note: Boy, all the #ifdefs in 1001 locations and
356 * all the fumbling with configure.in and acconfig.h
357 * were *way* more work than the feature itself :-(
359 * - Because a generic redirect template was needed for
360 * this, tinygif = 3 now uses the same.
362 * - Moved GIFs, and other static HTTP response templates
367 * - Removed some >400 CRs again (Jon, you really worked
370 * Revision 1.4 2001/05/21 19:34:01 jongfoster
371 * Made failure to bind() a fatal error.
373 * Revision 1.3 2001/05/20 01:21:20 jongfoster
374 * Version 2.9.4 checkin.
375 * - Merged popupfile and cookiefile, and added control over PCRS
376 * filtering, in new "permissionsfile".
377 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
378 * file error you now get a message box (in the Win32 GUI) rather
379 * than the program exiting with no explanation.
380 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
382 * - Removed tabs from "config"
383 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
384 * - Bumped up version number.
386 * Revision 1.2 2001/05/17 22:34:44 oes
387 * - Added hint on GIF char array generation to jcc.c
388 * - Cleaned CRLF's from the sources and related files
389 * - Repaired logging for REF and FRC
391 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
392 * Initial import of version 2.9.3 source tree
395 *********************************************************************/
401 #include <sys/types.h>
408 #ifdef FEATURE_PTHREAD
410 #endif /* def FEATURE_PTHREAD */
413 # ifndef FEATURE_PTHREAD
414 # include <windows.h>
415 # include <process.h>
416 # endif /* ndef FEATURE_PTHREAD */
419 # ifndef _WIN_CONSOLE
421 # endif /* ndef _WIN_CONSOLE */
423 #else /* ifndef _WIN32 */
425 # if !defined (__OS2__)
427 # include <sys/wait.h>
428 # endif /* ndef __OS2__ */
429 # include <sys/time.h>
430 # include <sys/stat.h>
431 # include <sys/ioctl.h>
434 #include <sys/termios.h>
440 # include <socket.h> /* BeOS has select() for sockets only. */
441 # include <OS.h> /* declarations for threads and stuff. */
444 # if defined(__EMX__) || defined(__OS2__)
445 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
450 #define bzero(B,N) memset(B,0x00,n)
469 #include "killpopup.h"
470 #include "miscutil.h"
472 #include "jbsockets.h"
477 #include "urlmatch.h"
479 const char jcc_h_rcs[] = JCC_H_VERSION;
480 const char project_h_rcs[] = PROJECT_H_VERSION;
482 struct client_state clients[1];
483 struct file_list files[1];
485 short int MustReload = 0;
487 #ifdef FEATURE_STATISTICS
488 int urls_read = 0; /* total nr of urls read inc rejected */
489 int urls_rejected = 0; /* total nr of urls rejected */
490 #endif /* def FEATURE_STATISTICS */
493 static void listen_loop(void);
494 static void chat(struct client_state *csp);
496 void serve(struct client_state *csp);
497 #else /* ifndef AMIGA */
498 static void serve(struct client_state *csp);
499 #endif /* def AMIGA */
502 static int32 server_thread(void *data);
503 #endif /* def __BEOS__ */
506 #define sleep(N) Sleep(((N) * 1000))
510 #define sleep(N) DosSleep(((N) * 100))
515 #endif /* defined unix */
517 /* The vanilla wafer. */
518 static const char VANILLA_WAFER[] =
519 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
520 "Do_not_send_me_any_copyrighted_information_other_than_the_"
521 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
522 "In_particular_do_not_send_me_any_cookies_that_"
523 "are_subject_to_a_claim_of_copyright_by_anybody._"
524 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
525 "(copyright_or_otherwise)_applying_to_any_cookie._";
528 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
529 /*********************************************************************
531 * Function : SIG_handler
533 * Description : Signal handler for different signals.
534 * see man kill, signal ..
537 * 1 : signal - the signal cause this function to call
541 *********************************************************************/
542 static void SIG_handler( int signal )
550 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", signal);
560 /* want to exit jb so use FATAL */
561 log_error(LOG_LEVEL_FATAL, "SIG_handler: receive signal %d without handler.", signal);
566 /*********************************************************************
570 * Description : Once a connection to the client has been accepted,
571 * this function is called (via serve()) to handle the
572 * main business of the communication. When this
573 * function returns, the caller must close the client
577 * 1 : csp = Current client state (buffers, headers, etc...)
579 * Returns : On success, the number of bytes written are returned (zero
580 * indicates nothing was written). On error, -1 is returned,
581 * and errno is set appropriately. If count is zero and the
582 * file descriptor refers to a regular file, 0 will be
583 * returned without causing any other effect. For a special
584 * file, the results are not portable.
586 *********************************************************************/
587 static void chat(struct client_state *csp)
590 * This next lines are a little ugly, but they simplifies the if statements
591 * below. Basically if TOGGLE, then we want the if to test if the
592 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
593 * then we want the if to test for CSP_FLAG_FORCED , else we don't
595 #ifdef FEATURE_TOGGLE
596 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
597 #else /* ifndef FEATURE_TOGGLE */
598 # define IS_TOGGLED_ON_AND
599 #endif /* ndef FEATURE_TOGGLE */
600 #ifdef FEATURE_FORCE_LOAD
601 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
602 #else /* ifndef FEATURE_FORCE_LOAD */
603 # define IS_NOT_FORCED_AND
604 #endif /* def FEATURE_FORCE_LOAD */
606 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
608 char buf[BUFFER_SIZE];
611 int n, maxfd, server_body;
612 int ms_iis5_hack = 0;
614 const struct forward_spec * fwd;
615 struct http_request *http;
616 #ifdef FEATURE_KILL_POPUPS
617 int block_popups; /* bool, 1==will block popups */
618 int block_popups_now = 0; /* bool, 1==currently blocking popups */
619 #endif /* def FEATURE_KILL_POPUPS */
621 int pcrs_filter; /* bool, 1==will filter through pcrs */
622 int gif_deanimate; /* bool, 1==will deanimate gifs */
624 /* Function that does the content filtering for the current request */
625 char *(*content_filter)() = NULL;
627 /* Skeleton for HTTP response, if we should intercept the request */
628 struct http_response *rsp;
633 * Read the client's request. Note that since we're not using select() we
634 * could get blocked here if a client connected, then didn't say anything!
639 n = read_socket(csp->cfd, buf, sizeof(buf));
641 if (n <= 0) break; /* error! */
643 add_to_iob(csp, buf, n);
645 req = get_header(csp);
649 break; /* no HTTP request! */
654 continue; /* more to come! */
657 #ifdef FEATURE_FORCE_LOAD
658 /* If this request contains the FORCE_PREFIX,
659 * better get rid of it now and set the force flag --oes
662 if (strstr(req, FORCE_PREFIX))
664 strclean(req, FORCE_PREFIX);
665 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
666 csp->flags |= CSP_FLAG_FORCED;
669 #endif /* def FEATURE_FORCE_LOAD */
671 parse_http_request(req, http, csp);
676 if (http->cmd == NULL)
678 strcpy(buf, CHEADER);
679 write_socket(csp->cfd, buf, strlen(buf));
681 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
686 /* decide how to route the HTTP request */
688 if ((fwd = forward_url(http, csp)) == NULL)
690 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
691 /* Never get here - LOG_LEVEL_FATAL causes program exit */
694 /* build the http request to send to the server
695 * we have to do one of the following:
697 * create = use the original HTTP request to create a new
698 * HTTP request that has either the path component
699 * without the http://domainspec (w/path) or the
700 * full orininal URL (w/url)
701 * Note that the path and/or the HTTP version may
702 * have been altered by now.
704 * connect = Open a socket to the host:port of the server
705 * and short-circuit server and client socket.
707 * pass = Pass the request unchanged if forwarding a CONNECT
708 * request to a parent proxy. Note that we'll be sending
709 * the CFAIL message ourselves if connecting to the parent
710 * fails, but we won't send a CSUCCEED message if it works,
711 * since that would result in a double message (ours and the
712 * parent's). After sending the request to the parent, we simply
718 * +--------+--------+
720 * 0 | create | connect|
722 * Forwarding +--------+--------+
724 * 1 | create | pass |
726 * +--------+--------+
731 * Determine the actions for this URL
733 #ifdef FEATURE_TOGGLE
734 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
736 /* Most compatible set of actions (i.e. none) */
737 init_current_action(csp->action);
740 #endif /* ndef FEATURE_TOGGLE */
742 url_actions(http, csp);
747 * Check if a CONNECT request is allowable:
748 * In the absence of a +limit-connect action, allow only port 443.
749 * If there is an action, allow whatever matches the specificaton.
753 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
754 || (csp->action->flags & ACTION_LIMIT_CONNECT
755 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
757 strcpy(buf, CFORBIDDEN);
758 write_socket(csp->cfd, buf, strlen(buf));
760 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
761 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
769 * Downgrade http version from 1.1 to 1.0 if +downgrade
772 if ( (http->ssl == 0)
773 && (!strcmpic(http->ver, "HTTP/1.1"))
774 && (csp->action->flags & ACTION_DOWNGRADE))
777 http->ver = strdup("HTTP/1.0");
779 if (http->ver == NULL)
781 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
786 * (Re)build the HTTP request for non-SSL requests.
787 * If forwarding, use the whole URL, else, use only the path.
793 http->cmd = strdup(http->gpc);
794 string_append(&http->cmd, " ");
796 if (fwd->forward_host)
798 string_append(&http->cmd, http->url);
802 string_append(&http->cmd, http->path);
805 string_append(&http->cmd, " ");
806 string_append(&http->cmd, http->ver);
808 if (http->cmd == NULL)
810 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
813 enlist(csp->headers, http->cmd);
816 #ifdef FEATURE_COOKIE_JAR
818 * If we're logging cookies in a cookie jar, and the user has not
819 * supplied any wafers, and the user has not told us to suppress the
820 * vanilla wafer, then send the vanilla wafer.
822 if ((csp->config->jarfile != NULL)
823 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
824 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
826 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
828 #endif /* def FEATURE_COOKIE_JAR */
831 #ifdef FEATURE_KILL_POPUPS
832 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
833 #endif /* def FEATURE_KILL_POPUPS */
835 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
836 ((csp->action->flags & ACTION_FILTER) != 0);
838 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
840 /* grab the rest of the client's headers */
844 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
846 n = read_socket(csp->cfd, buf, sizeof(buf));
849 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
852 add_to_iob(csp, buf, n);
856 if (p == NULL) break;
858 enlist(csp->headers, p);
862 * We have a request. Now, check to see if we need to
863 * intercept it, i.e. If ..
867 /* a CGI call was detected and answered */
868 (NULL != (rsp = dispatch_cgi(csp)))
870 /* or we are enabled and... */
873 /* ..the request was blocked */
874 ( NULL != (rsp = block_url(csp)))
878 || ( NULL != (rsp = trust_url(csp)))
879 #endif /* def FEATURE_TRUST */
881 /* ..or a fast redirect kicked in */
882 #ifdef FEATURE_FAST_REDIRECTS
883 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
884 (NULL != (rsp = redirect_url(csp))))
885 #endif /* def FEATURE_FAST_REDIRECTS */
889 /* Write the answer to the client */
890 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
891 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
893 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
896 #ifdef FEATURE_STATISTICS
897 /* Count as a rejected request */
898 csp->flags |= CSP_FLAG_REJECTED;
899 #endif /* def FEATURE_STATISTICS */
901 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
902 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
903 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
905 /* Clean up and return */
906 free_http_response(rsp);
910 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
912 if (fwd->forward_host)
914 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
915 fwd->forward_host, fwd->forward_port, http->hostport);
919 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
922 /* here we connect to the server, gateway, or the forwarder */
924 csp->sfd = forwarded_connect(fwd, http, csp);
928 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
933 rsp = error_response(csp, "no-such-domain", errno);
935 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
936 csp->ip_addr_str, http->cmd);
940 rsp = error_response(csp, "connect-failed", errno);
942 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
943 csp->ip_addr_str, http->cmd);
947 /* Write the answer to the client */
950 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
951 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
953 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
957 free_http_response(rsp);
961 log_error(LOG_LEVEL_CONNECT, "OK");
963 hdr = sed(client_patterns, add_client_headers, csp);
966 /* FIXME Should handle error properly */
967 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
970 list_remove_all(csp->headers);
972 if (fwd->forward_host || (http->ssl == 0))
974 /* write the client's (modified) header to the server
975 * (along with anything else that may be in the buffer)
980 if ((write_socket(csp->sfd, hdr, n) != n)
981 || (flush_socket(csp->sfd, csp ) < 0))
983 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
986 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
987 csp->ip_addr_str, http->cmd);
989 rsp = error_response(csp, "connect-failed", errno);
993 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
994 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
996 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1000 free_http_response(rsp);
1008 * We're running an SSL tunnel and we're not forwarding,
1009 * so just send the "connect succeeded" message to the
1010 * client, flush the rest, and get out of the way.
1012 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1013 csp->ip_addr_str, http->cmd);
1015 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
1023 /* we're finished with the client's header */
1026 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1028 /* pass data between the client and server
1029 * until one or the other shuts down the connection.
1038 FD_SET(csp->cfd, &rfds);
1039 FD_SET(csp->sfd, &rfds);
1041 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1045 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1049 /* this is the body of the browser's request
1050 * just read it and write it.
1053 if (FD_ISSET(csp->cfd, &rfds))
1055 n = read_socket(csp->cfd, buf, sizeof(buf));
1059 break; /* "game over, man" */
1062 if (write_socket(csp->sfd, buf, n) != n)
1064 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1071 * The server wants to talk. It could be the header or the body.
1072 * If `hdr' is null, then it's the header otherwise it's the body.
1073 * FIXME: Does `hdr' really mean `host'? No.
1077 if (FD_ISSET(csp->sfd, &rfds))
1080 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1084 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1086 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1087 csp->ip_addr_str, http->cmd);
1089 rsp = error_response(csp, "connect-failed", errno);
1093 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1094 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1096 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1100 free_http_response(rsp);
1104 /* Add a trailing zero. This lets filter_popups
1105 * use string operations.
1109 #ifdef FEATURE_KILL_POPUPS
1110 /* Filter the popups on this read. */
1111 if (block_popups_now)
1113 filter_popups(buf, csp);
1115 #endif /* def FEATURE_KILL_POPUPS */
1117 /* Normally, this would indicate that we've read
1118 * as much as the server has sent us and we can
1119 * close the client connection. However, Microsoft
1120 * in its wisdom has released IIS/5 with a bug that
1121 * prevents it from sending the trailing \r\n in
1122 * a 302 redirect header (and possibly other headers).
1123 * To work around this if we've haven't parsed
1124 * a full header we'll append a trailing \r\n
1125 * and see if this now generates a valid one.
1127 * This hack shouldn't have any impacts. If we've
1128 * already transmitted the header or if this is a
1129 * SSL connection, then we won't bother with this
1130 * hack. So we only work on partially received
1131 * headers. If we append a \r\n and this still
1132 * doesn't generate a valid header, then we won't
1133 * transmit anything to the client.
1138 if (server_body || http->ssl)
1141 * If we have been buffering up the document,
1142 * now is the time to apply content modification
1143 * and send the result to the client.
1148 * If the content filter fails, use the original
1149 * buffer and length.
1150 * (see p != NULL ? p : csp->iob->cur below)
1152 if (NULL == (p = (*content_filter)(csp)))
1154 csp->content_length = csp->iob->eod - csp->iob->cur;
1157 hdr = sed(server_patterns, add_server_headers, csp);
1160 /* FIXME Should handle error properly */
1161 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1166 if ((write_socket(csp->cfd, hdr, n) != n)
1167 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1169 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1179 break; /* "game over, man" */
1183 * This is NOT the body, so
1184 * Let's pretend the server just sent us a blank line.
1186 n = sprintf(buf, "\r\n");
1189 * Now, let the normal header parsing algorithm below do its
1190 * job. If it fails, we'll exit instead of continuing.
1197 * If this is an SSL connection or we're in the body
1198 * of the server document, just write it to the client,
1199 * unless we need to buffer the body for later content-filtering
1202 if (server_body || http->ssl)
1206 add_to_iob(csp, buf, n);
1209 * If the buffer limit will be reached on the next read,
1210 * switch to non-filtering mode, i.e. make & write the
1211 * header, flush the socket and get out of the way.
1213 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1215 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1217 hdr = sed(server_patterns, add_server_headers, csp);
1220 /* FIXME Should handle error properly */
1221 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1227 if (((write_socket(csp->cfd, hdr, n) != n)
1228 || (n = flush_socket(csp->cfd, csp) < 0)))
1230 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1239 content_filter = NULL;
1246 if (write_socket(csp->cfd, buf, n) != n)
1248 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1257 /* we're still looking for the end of the
1258 * server's header ... (does that make header
1259 * parsing an "out of body experience" ?
1262 /* buffer up the data we just read */
1263 add_to_iob(csp, buf, n);
1265 /* get header lines from the iob */
1267 while ((p = get_header(csp)))
1271 /* see following note */
1274 enlist(csp->headers, p);
1278 /* NOTE: there are no "empty" headers so
1279 * if the pointer `p' is not NULL we must
1280 * assume that we reached the end of the
1281 * buffer before we hit the end of the header.
1288 /* Well, we tried our MS IIS/5
1289 * hack and it didn't work.
1290 * The header is incomplete
1291 * and there isn't anything
1292 * we can do about it.
1298 /* Since we have to wait for
1299 * more from the server before
1300 * we can parse the headers
1301 * we just continue here.
1307 /* we have now received the entire header.
1308 * filter it and send the result to the client
1311 hdr = sed(server_patterns, add_server_headers, csp);
1314 /* FIXME Should handle error properly */
1315 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1320 /* write the server's (modified) header to
1321 * the client (along with anything else that
1322 * may be in the buffer)
1325 #ifdef FEATURE_KILL_POPUPS
1326 /* Start blocking popups if appropriate. */
1328 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1329 !http->ssl && /* We talk plaintext */
1330 block_popups) /* Policy allows */
1332 block_popups_now = 1;
1334 * Filter the part of the body that came in the same read
1335 * as the last headers:
1337 filter_popups(csp->iob->cur, csp);
1340 #endif /* def FEATURE_KILL_POPUPS */
1342 /* Buffer and pcrs filter this if appropriate. */
1344 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1345 !http->ssl && /* We talk plaintext */
1346 pcrs_filter) /* Policy allows */
1348 content_filter = pcrs_filter_response;
1351 /* Buffer and gif_deanimate this if appropriate. */
1353 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1354 !http->ssl && /* We talk plaintext */
1355 gif_deanimate) /* Policy allows */
1357 content_filter = gif_deanimate_response;
1362 * Only write if we're not buffering for content modification
1364 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1365 || (n = flush_socket(csp->cfd, csp) < 0)))
1367 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1369 /* the write failed, so don't bother
1370 * mentioning it to the client...
1371 * it probably can't hear us anyway.
1377 if(!content_filter) byte_count += n;
1379 /* we're finished with the server's header */
1384 /* If this was a MS IIS/5 hack then it means
1385 * the server has already closed the
1386 * connection. Nothing more to read. Time
1397 return; /* huh? we should never get here */
1400 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1401 csp->ip_addr_str, http->cmd, byte_count);
1405 /*********************************************************************
1409 * Description : This is little more than chat. We only "serve" to
1410 * to close any socket that chat may have opened.
1413 * 1 : csp = Current client state (buffers, headers, etc...)
1417 *********************************************************************/
1419 void serve(struct client_state *csp)
1420 #else /* ifndef AMIGA */
1421 static void serve(struct client_state *csp)
1422 #endif /* def AMIGA */
1425 close_socket(csp->cfd);
1429 close_socket(csp->sfd);
1432 csp->flags &= ~CSP_FLAG_ACTIVE;
1438 /*********************************************************************
1440 * Function : server_thread
1442 * Description : We only exist to call `serve' in a threaded environment.
1445 * 1 : data = Current client state (buffers, headers, etc...)
1447 * Returns : Always 0.
1449 *********************************************************************/
1450 static int32 server_thread(void *data)
1452 serve((struct client_state *) data);
1459 /*********************************************************************
1463 * Description : Load the config file and start the listen loop.
1464 * This function is a lot more *sane* with the `load_config'
1465 * and `listen_loop' functions; although it stills does
1466 * a *little* too much for my taste.
1469 * 1 : argc = Number of parameters (including $0).
1470 * 2 : argv = Array of (char *)'s to the parameters.
1472 * Returns : 1 if : can't open config file, unrecognized directive,
1473 * stats requested in multi-thread mode, can't open the
1474 * log file, can't open the jar file, listen port is invalid,
1475 * any load fails, and can't bind port.
1477 * Else main never returns, the process must be signaled
1478 * to terminate execution. Or, on Windows, use the
1479 * "File", "Exit" menu option.
1481 *********************************************************************/
1483 int real_main(int argc, const char *argv[])
1485 int main(int argc, const char *argv[])
1491 #if !defined(_WIN32)
1498 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1499 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1501 printf("JunkBuster proxy version " VERSION ".\n\n"
1502 "Usage: %s [configfile]\n\n"
1503 "See " HOME_PAGE_URL " for details.\n"
1504 "This program is distributed under the GNU GPL, version 2 or later.\n",
1508 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1510 printf(VERSION "\n");
1514 if ((argc >= 2) && (strcmp(argv[1], "-d")==0))
1518 fprintf(stderr,"debugging enabled..\n");
1521 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1526 if (argc > argc_pos )
1528 configfile = argv[argc_pos];
1532 if ( *configfile != '/' )
1536 DBG(1, ("configfile before '%s'\n",configfile) );
1538 /* make config-filename absolute here */
1539 if ( !(basedir = getcwd( NULL, 1024 )))
1541 perror("get working dir failed");
1544 DBG(1, ("working dir '%s'\n",basedir) );
1545 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1547 perror("malloc failed");
1550 strcpy( abs_file, basedir );
1551 strcat( abs_file, "/" );
1552 strcat( abs_file, configfile );
1553 configfile = abs_file;
1554 DBG(1, ("configfile after '%s'\n",configfile) );
1556 #endif /* defined unix */
1563 #elif defined(_WIN32)
1568 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1571 struct sigaction action;
1573 for ( sig = 1; sig < 16; sig++ )
1583 if ( signal(sig, SIG_handler) == SIG_ERR )
1584 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", sig);
1587 if ( signal(SIGPIPE, SIG_IGN) == SIG_ERR )
1588 log_error(LOG_LEVEL_FATAL, "Can't set SIG_IGN to SIGPIPE: %E");
1589 if ( signal(SIGCHLD, SIG_IGN) == SIG_ERR )
1590 log_error(LOG_LEVEL_FATAL, "Can't set SIG_IGN to SIGCHLD: %E");
1591 /* log file reload */
1592 if (!sigaction(SIGHUP,NULL,&action))
1594 action.sa_handler = &SIG_handler;
1595 action.sa_flags = SA_RESTART;
1597 if ( sigaction(SIGHUP,&action,NULL))
1598 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal SIGHUP: %E");
1602 perror("sigaction");
1603 log_error(LOG_LEVEL_FATAL, "Can't get sigaction data for signal SIGHUP");
1608 #else /* ifdef _WIN32 */
1609 # ifdef _WIN_CONSOLE
1611 * We *are* in a windows console app.
1612 * Print a verbose messages about FAQ's and such
1614 printf(win32_blurb);
1615 # endif /* def _WIN_CONSOLE */
1616 #endif /* def _WIN32 */
1619 /* Initialize the CGI subsystem */
1620 cgi_init_error_messages();
1630 * we make us a real daemon
1636 if ( pid < 0 ) /* error */
1641 else if ( pid != 0 ) /* parent */
1646 * must check for errors
1647 * child died due to missing files aso
1650 wpid = waitpid( pid, &status, WNOHANG );
1659 /* Should be more portable, but not as well tested */
1664 #else /* ndef __FreeBSD__ */
1666 #endif /* ndef __FreeBSD__ */
1667 fd = open("/dev/tty", O_RDONLY);
1670 /* no error check here */
1671 ioctl( fd, TIOCNOTTY,0 );
1675 /* should close stderr (fd 2) here too, but the test for existence
1676 ** and load config file is done in listen_loop() and puts
1677 ** some messages on stderr there.
1693 #endif /* defined unix */
1695 DBG(1, ("call listen_loop() \n") );
1704 /*********************************************************************
1706 * Function : listen_loop
1708 * Description : bind the listen port and enter a "FOREVER" listening loop.
1714 *********************************************************************/
1715 static void listen_loop(void)
1717 struct client_state *csp = NULL;
1719 struct configuration_spec * config;
1721 config = load_config();
1723 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1724 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1726 bfd = bind_port(config->haddr, config->hport);
1730 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1731 "- There may be another junkbuster or some other "
1732 "proxy running on port %d",
1733 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1734 config->hport, config->hport
1736 /* shouldn't get here */
1740 config->need_bind = 0;
1744 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1745 while (waitpid(-1, NULL, WNOHANG) > 0)
1747 /* zombie children */
1749 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1752 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1754 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1758 csp->flags |= CSP_FLAG_ACTIVE;
1761 csp->config = config = load_config();
1763 if ( config->need_bind )
1766 * Since we were listening to the "old port", we will not see
1767 * a "listen" param change until the next IJB request. So, at
1768 * least 1 more request must be made for us to find the new
1769 * setting. I am simply closing the old socket and binding the
1772 * Which-ever is correct, we will serve 1 more page via the
1773 * old settings. This should probably be a "show-proxy-args"
1774 * request. This should not be a so common of an operation
1775 * that this will hurt people's feelings.
1780 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1781 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1782 bfd = bind_port(config->haddr, config->hport);
1786 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1787 "- There may be another junkbuster or some other "
1788 "proxy running on port %d",
1789 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1790 config->hport, config->hport
1792 /* shouldn't get here */
1796 config->need_bind = 0;
1799 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1801 if (!accept_connection(csp, bfd))
1803 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1816 log_error(LOG_LEVEL_CONNECT, "OK");
1819 #ifdef FEATURE_TOGGLE
1822 csp->flags |= CSP_FLAG_TOGGLED_ON;
1824 #endif /* def FEATURE_TOGGLE */
1826 if (run_loader(csp))
1828 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1829 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1833 if (block_acl(NULL,csp))
1835 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1836 close_socket(csp->cfd);
1840 #endif /* def FEATURE_ACL */
1842 /* add it to the list of clients */
1843 csp->next = clients->next;
1844 clients->next = csp;
1846 if (config->multi_threaded)
1850 /* this is a switch () statment in the C preprocessor - ugh */
1851 #undef SELECTED_ONE_OPTION
1853 /* Use Pthreads in preference to native code */
1854 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1855 #define SELECTED_ONE_OPTION
1857 pthread_t the_thread;
1858 pthread_attr_t attrs;
1860 pthread_attr_init(&attrs);
1861 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1862 child_id = (pthread_create(&the_thread, &attrs,
1863 (void*)serve, csp) ? -1 : 0);
1864 pthread_attr_destroy(&attrs);
1868 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1869 #define SELECTED_ONE_OPTION
1870 child_id = _beginthread(
1876 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1877 #define SELECTED_ONE_OPTION
1878 child_id = _beginthread(
1885 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1886 #define SELECTED_ONE_OPTION
1888 thread_id tid = spawn_thread
1889 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1891 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1893 child_id = (int) tid;
1902 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1903 #define SELECTED_ONE_OPTION
1904 csp->cfd = ReleaseSocket(csp->cfd, -1);
1905 if((child_id = (int)CreateNewProcTags(
1906 NP_Entry, (ULONG)server_thread,
1907 NP_Output, Output(),
1908 NP_CloseOutput, FALSE,
1909 NP_Name, (ULONG)"junkbuster child",
1910 NP_StackSize, 200*1024,
1914 ((struct Task *)child_id)->tc_UserData = csp;
1915 Signal((struct Task *)child_id, SIGF_SINGLE);
1920 #if !defined(SELECTED_ONE_OPTION)
1923 /* This block is only needed when using fork().
1924 * When using threads, the server thread was
1925 * created and run by the call to _beginthread().
1927 if (child_id == 0) /* child */
1933 else if (child_id > 0) /* parent */
1935 /* in a fork()'d environment, the parent's
1936 * copy of the client socket and the CSP
1940 #if !defined(_WIN32) && defined(__CYGWIN__)
1942 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1943 close_socket(csp->cfd);
1944 csp->flags &= ~CSP_FLAG_ACTIVE;
1948 #undef SELECTED_ONE_OPTION
1949 /* end of cpp switch () */
1951 if (child_id < 0) /* failed */
1953 char buf[BUFFER_SIZE];
1955 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1957 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1959 write_socket(csp->cfd, buf, strlen(buf));
1960 close_socket(csp->cfd);
1961 csp->flags &= ~CSP_FLAG_ACTIVE;