1 const char jcc_rcs[] = "$Id: jcc.c,v 1.59 2001/12/13 14:07:18 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.59 2001/12/13 14:07:18 oes
37 * Fixed Bug: 503 error page now sent OK
39 * Revision 1.58 2001/11/30 23:37:24 jongfoster
40 * Renaming the Win32 config file to config.txt - this is almost the
41 * same as the corresponding UNIX name "config"
43 * Revision 1.57 2001/11/16 00:47:43 jongfoster
44 * Changing the tty-disconnection code to use setsid().
46 * Revision 1.56 2001/11/13 20:20:54 jongfoster
47 * Tabs->spaces, fixing a bug with missing {} around an if()
49 * Revision 1.55 2001/11/13 20:14:53 jongfoster
50 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
52 * Revision 1.54 2001/11/07 00:03:14 steudten
53 * Give reliable return value if an error
54 * occurs not just 0 with new daemon mode.
56 * Revision 1.53 2001/11/05 21:41:43 steudten
57 * Add changes to be a real daemon just for unix os.
58 * (change cwd to /, detach from controlling tty, set
59 * process group and session leader to the own process.
61 * Add some fatal-error log message for failed malloc().
62 * Add '-d' if compiled with 'configure --with-debug' to
63 * enable debug output.
65 * Revision 1.52 2001/10/26 20:11:20 jongfoster
66 * Fixing type mismatch
68 * Revision 1.51 2001/10/26 17:38:28 oes
71 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
72 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
73 * threads to call select() simultaneously. So, it's time to do a real, live,
74 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
75 * (native). Both versions will work, but using __OS2__ offers multi-threading.
77 * Revision 1.49 2001/10/23 21:41:35 jongfoster
78 * Added call to initialize the (statically-allocated of course)
79 * "out of memory" CGI response.
81 * Revision 1.48 2001/10/10 19:56:46 jongfoster
82 * Moving some code that wasn't cookie-related out of an #ifdef
85 * Revision 1.47 2001/10/10 16:44:36 oes
86 * Added CONNECT destination port limitation check
88 * Revision 1.46 2001/10/08 15:17:41 oes
89 * Re-enabled SSL forwarding
91 * Revision 1.45 2001/10/07 15:42:11 oes
92 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
94 * Moved downgrading of the HTTP version from parse_http_request to
95 * chat(), since we can't decide if it is necessary before we have
96 * determined the actions for the URL. The HTTP command is now
97 * *always* re-built so the repairs need no longer be special-cased.
99 * filter_popups now gets a csp pointer so it can raise the new
100 * CSP_FLAG_MODIFIED flag.
104 * Added configurable size limit for the IOB. If the IOB grows so
105 * large that the next read would exceed the limit, the header
106 * is generated, and the header & unfiltered buffer are flushed
107 * to the client. Chat then continues in non-buffering,
108 * non-filtering body mode.
110 * Revision 1.44 2001/10/02 18:13:57 oes
113 * Revision 1.43 2001/10/02 15:32:13 oes
114 * Moved generation of hdr
116 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
117 * Cleaning up 2 compiler warnings on OS/2.
119 * Revision 1.41 2001/09/16 17:05:14 jongfoster
120 * Removing unused #include showarg.h
122 * Revision 1.40 2001/09/16 15:41:45 jongfoster
123 * Fixing signed/unsigned comparison warning.
125 * Revision 1.39 2001/09/16 13:21:27 jongfoster
126 * Changes to use new list functions.
128 * Revision 1.38 2001/09/16 13:01:46 jongfoster
129 * Removing redundant function call that zeroed zalloc()'d memory.
131 * Revision 1.37 2001/09/10 11:12:24 oes
132 * Deleted unused variable
134 * Revision 1.36 2001/09/10 10:56:15 oes
135 * Silenced compiler warnings
137 * Revision 1.35 2001/07/31 14:44:22 oes
138 * Deleted unused size parameter from filter_popups()
140 * Revision 1.34 2001/07/30 22:08:36 jongfoster
141 * Tidying up #defines:
142 * - All feature #defines are now of the form FEATURE_xxx
143 * - Permanently turned off WIN_GUI_EDIT
144 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
146 * Revision 1.33 2001/07/29 19:32:00 jongfoster
147 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
149 * Revision 1.32 2001/07/29 18:47:05 jongfoster
150 * Adding missing #include "loadcfg.h"
152 * Revision 1.31 2001/07/29 12:17:48 oes
153 * Applied pthread fix by Paul Lieverse
155 * Revision 1.30 2001/07/25 22:57:13 jongfoster
156 * __BEOS__ no longer overrides FEATURE_PTHREAD.
157 * This is because FEATURE_PTHREAD will soon be widely used, so I
158 * want to keep it simple.
160 * Revision 1.29 2001/07/24 12:47:06 oes
161 * Applied BeOS support update by Eugenia
163 * Revision 1.28 2001/07/23 13:26:12 oes
164 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
166 * Revision 1.27 2001/07/19 19:09:47 haroon
167 * - Added code to take care of the situation where while processing the first
168 * server response (which includes the server header), after finding the end
169 * of the headers we were not looking past the end of the headers for
170 * content modification. I enabled it for filter_popups.
171 * Someone else should look to see if other similar operations should be
172 * done to the discarded portion of the buffer.
174 * Note 2001/07/20: No, the other content modification mechanisms will process
175 * the whole iob later anyway. --oes
177 * Revision 1.26 2001/07/18 12:31:36 oes
180 * Revision 1.25 2001/07/15 19:43:49 jongfoster
181 * Supports POSIX threads.
182 * Also removed some unused #includes.
184 * Revision 1.24 2001/07/13 14:00:40 oes
185 * - Generic content modification scheme:
186 * Each feature has its own applicability flag that is set
187 * from csp->action->flags.
188 * Replaced the "filtering" int flag , by a function pointer
189 * "content_filter" to the function that will do the content
190 * modification. If it is != NULL, the document will be buffered
191 * and processed through *content_filter, which must set
192 * csp->content_length and return a modified copy of the body
193 * or return NULL (on failiure).
194 * - Changed csp->is_text to the more generic bitmap csp->content_type
195 * which can currently take the valued CT_TEXT or CT_GIF
197 * - Removed all #ifdef PCRS
199 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
200 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
201 * the `block_acl' call. This prevents a compilation error when the user
202 * does not wish to use the "ACL" feature.
204 * Revision 1.22 2001/06/29 21:45:41 oes
205 * Indentation, CRLF->LF, Tab-> Space
207 * Revision 1.21 2001/06/29 13:29:36 oes
208 * - Cleaned up, improved comments
209 * - Unified all possible interceptors (CGI,
210 * block, trust, fast_redirect) in one
211 * place, with one (CGI) answer generation
212 * mechansim. Much clearer now.
213 * - Removed the GIF image generation, which
214 * is now done in filters.c:block_url()
215 * - Made error conditions like domain lookup
216 * failiure or (various) problems while talking
217 * to the server use cgi.c:error_response()
218 * instead of generating HTML/HTTP in chat() (yuck!)
219 * - Removed logentry from cancelled commit
221 * Revision 1.20 2001/06/09 10:55:28 jongfoster
222 * Changing BUFSIZ ==> BUFFER_SIZE
224 * Revision 1.19 2001/06/07 23:12:52 jongfoster
225 * Replacing function pointer in struct gateway with a directly
226 * called function forwarded_connect().
227 * Replacing struct gateway with struct forward_spec
229 * Revision 1.18 2001/06/03 19:12:16 oes
230 * introduced new cgi handling
232 * Revision 1.17 2001/06/01 20:07:23 jongfoster
233 * Now uses action +image-blocker{} rather than config->tinygif
235 * Revision 1.16 2001/06/01 18:49:17 jongfoster
236 * Replaced "list_share" with "list" - the tiny memory gain was not
237 * worth the extra complexity.
239 * Revision 1.15 2001/05/31 21:24:47 jongfoster
240 * Changed "permission" to "action" throughout.
241 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
242 * Moved vanilla wafer check into chat(), since we must now
243 * decide whether or not to add it based on the URL.
245 * Revision 1.14 2001/05/29 20:14:01 joergs
246 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
249 * Revision 1.13 2001/05/29 09:50:24 jongfoster
250 * Unified blocklist/imagelist/permissionslist.
251 * File format is still under discussion, but the internal changes
254 * Also modified interceptor behaviour:
255 * - We now intercept all URLs beginning with one of the following
256 * prefixes (and *only* these prefixes):
258 * * http://ijbswa.sf.net/config/
259 * * http://ijbswa.sourceforge.net/config/
260 * - New interceptors "home page" - go to http://i.j.b/ to see it.
261 * - Internal changes so that intercepted and fast redirect pages
262 * are not replaced with an image.
263 * - Interceptors now have the option to send a binary page direct
264 * to the client. (i.e. ijb-send-banner uses this)
265 * - Implemented show-url-info interceptor. (Which is why I needed
266 * the above interceptors changes - a typical URL is
267 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
268 * The previous mechanism would not have intercepted that, and
269 * if it had been intercepted then it then it would have replaced
272 * Revision 1.12 2001/05/27 22:17:04 oes
274 * - re_process_buffer no longer writes the modified buffer
275 * to the client, which was very ugly. It now returns the
276 * buffer, which it is then written by chat.
278 * - content_length now adjusts the Content-Length: header
279 * for modified documents rather than crunch()ing it.
280 * (Length info in csp->content_length, which is 0 for
281 * unmodified documents)
283 * - For this to work, sed() is called twice when filtering.
285 * Revision 1.11 2001/05/26 17:27:53 jongfoster
286 * Added support for CLF and fixed LOG_LEVEL_LOG.
287 * Also did CRLF->LF fix of my previous patch.
289 * Revision 1.10 2001/05/26 15:26:15 jongfoster
290 * ACL feature now provides more security by immediately dropping
291 * connections from untrusted hosts.
293 * Revision 1.9 2001/05/26 00:28:36 jongfoster
294 * Automatic reloading of config file.
295 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
296 * Most of the global variables have been moved to a new
297 * struct configuration_spec, accessed through csp->config->globalname
298 * Most of the globals remaining are used by the Win32 GUI.
300 * Revision 1.8 2001/05/25 22:43:18 jongfoster
301 * Fixing minor memory leak and buffer overflow.
303 * Revision 1.7 2001/05/25 22:34:30 jongfoster
306 * Revision 1.6 2001/05/23 00:13:58 joergs
307 * AmigaOS support fixed.
309 * Revision 1.5 2001/05/22 18:46:04 oes
311 * - Enabled filtering banners by size rather than URL
312 * by adding patterns that replace all standard banner
313 * sizes with the "Junkbuster" gif to the re_filterfile
315 * - Enabled filtering WebBugs by providing a pattern
316 * which kills all 1x1 images
318 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
319 * which is selected by the (nonstandard and therefore
320 * capital) letter 'U' in the option string.
321 * It causes the quantifiers to be ungreedy by default.
322 * Appending a ? turns back to greedy (!).
324 * - Added a new interceptor ijb-send-banner, which
325 * sends back the "Junkbuster" gif. Without imagelist or
326 * MSIE detection support, or if tinygif = 1, or the
327 * URL isn't recognized as an imageurl, a lame HTML
328 * explanation is sent instead.
330 * - Added new feature, which permits blocking remote
331 * script redirects and firing back a local redirect
333 * The feature is conditionally compiled, i.e. it
334 * can be disabled with --disable-fast-redirects,
335 * plus it must be activated by a "fast-redirects"
336 * line in the config file, has its own log level
337 * and of course wants to be displayed by show-proxy-args
338 * Note: Boy, all the #ifdefs in 1001 locations and
339 * all the fumbling with configure.in and acconfig.h
340 * were *way* more work than the feature itself :-(
342 * - Because a generic redirect template was needed for
343 * this, tinygif = 3 now uses the same.
345 * - Moved GIFs, and other static HTTP response templates
350 * - Removed some >400 CRs again (Jon, you really worked
353 * Revision 1.4 2001/05/21 19:34:01 jongfoster
354 * Made failure to bind() a fatal error.
356 * Revision 1.3 2001/05/20 01:21:20 jongfoster
357 * Version 2.9.4 checkin.
358 * - Merged popupfile and cookiefile, and added control over PCRS
359 * filtering, in new "permissionsfile".
360 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
361 * file error you now get a message box (in the Win32 GUI) rather
362 * than the program exiting with no explanation.
363 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
365 * - Removed tabs from "config"
366 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
367 * - Bumped up version number.
369 * Revision 1.2 2001/05/17 22:34:44 oes
370 * - Added hint on GIF char array generation to jcc.c
371 * - Cleaned CRLF's from the sources and related files
372 * - Repaired logging for REF and FRC
374 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
375 * Initial import of version 2.9.3 source tree
378 *********************************************************************/
384 #include <sys/types.h>
391 #ifdef FEATURE_PTHREAD
393 #endif /* def FEATURE_PTHREAD */
396 # ifndef FEATURE_PTHREAD
397 # include <windows.h>
398 # include <process.h>
399 # endif /* ndef FEATURE_PTHREAD */
402 # ifndef _WIN_CONSOLE
404 # endif /* ndef _WIN_CONSOLE */
406 #else /* ifndef _WIN32 */
408 # if !defined (__OS2__)
410 # include <sys/wait.h>
411 # endif /* ndef __OS2__ */
412 # include <sys/time.h>
413 # include <sys/stat.h>
414 # include <sys/ioctl.h>
417 #include <sys/termios.h>
423 # include <socket.h> /* BeOS has select() for sockets only. */
424 # include <OS.h> /* declarations for threads and stuff. */
427 # if defined(__EMX__) || defined(__OS2__)
428 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
433 #define bzero(B,N) memset(B,0x00,n)
452 #include "killpopup.h"
453 #include "miscutil.h"
455 #include "jbsockets.h"
461 const char jcc_h_rcs[] = JCC_H_VERSION;
462 const char project_h_rcs[] = PROJECT_H_VERSION;
464 struct client_state clients[1];
465 struct file_list files[1];
467 short int MustReload = 0;
469 #ifdef FEATURE_STATISTICS
470 int urls_read = 0; /* total nr of urls read inc rejected */
471 int urls_rejected = 0; /* total nr of urls rejected */
472 #endif /* def FEATURE_STATISTICS */
475 static void listen_loop(void);
476 static void chat(struct client_state *csp);
478 void serve(struct client_state *csp);
479 #else /* ifndef AMIGA */
480 static void serve(struct client_state *csp);
481 #endif /* def AMIGA */
484 static int32 server_thread(void *data);
485 #endif /* def __BEOS__ */
488 #define sleep(N) Sleep(((N) * 1000))
492 #define sleep(N) DosSleep(((N) * 100))
497 #endif /* defined unix */
499 /* The vanilla wafer. */
500 static const char VANILLA_WAFER[] =
501 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
502 "Do_not_send_me_any_copyrighted_information_other_than_the_"
503 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
504 "In_particular_do_not_send_me_any_cookies_that_"
505 "are_subject_to_a_claim_of_copyright_by_anybody._"
506 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
507 "(copyright_or_otherwise)_applying_to_any_cookie._";
510 #if !defined(_WIN32) && !defined(__OS2__)
511 /*********************************************************************
513 * Function : SIG_handler
515 * Description : Signal handler for different signals.
516 * see man kill, signal ..
519 * 1 : signal - the signal cause this function to call
523 *********************************************************************/
524 static void SIG_handler( int signal )
532 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", signal);
542 /* want to exit jb so use FATAL */
543 log_error(LOG_LEVEL_FATAL, "SIG_handler: receive signal %d without handler.", signal);
548 /*********************************************************************
552 * Description : Once a connection to the client has been accepted,
553 * this function is called (via serve()) to handle the
554 * main business of the communication. When this
555 * function returns, the caller must close the client
559 * 1 : csp = Current client state (buffers, headers, etc...)
561 * Returns : On success, the number of bytes written are returned (zero
562 * indicates nothing was written). On error, -1 is returned,
563 * and errno is set appropriately. If count is zero and the
564 * file descriptor refers to a regular file, 0 will be
565 * returned without causing any other effect. For a special
566 * file, the results are not portable.
568 *********************************************************************/
569 static void chat(struct client_state *csp)
572 * This next lines are a little ugly, but they simplifies the if statements
573 * below. Basically if TOGGLE, then we want the if to test if the
574 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
575 * then we want the if to test for CSP_FLAG_FORCED , else we don't
577 #ifdef FEATURE_TOGGLE
578 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
579 #else /* ifndef FEATURE_TOGGLE */
580 # define IS_TOGGLED_ON_AND
581 #endif /* ndef FEATURE_TOGGLE */
582 #ifdef FEATURE_FORCE_LOAD
583 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
584 #else /* ifndef FEATURE_FORCE_LOAD */
585 # define IS_NOT_FORCED_AND
586 #endif /* def FEATURE_FORCE_LOAD */
588 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
590 char buf[BUFFER_SIZE];
593 int n, maxfd, server_body;
594 int ms_iis5_hack = 0;
596 const struct forward_spec * fwd;
597 struct http_request *http;
598 #ifdef FEATURE_KILL_POPUPS
599 int block_popups; /* bool, 1==will block popups */
600 int block_popups_now = 0; /* bool, 1==currently blocking popups */
601 #endif /* def FEATURE_KILL_POPUPS */
603 int pcrs_filter; /* bool, 1==will filter through pcrs */
604 int gif_deanimate; /* bool, 1==will deanimate gifs */
606 /* Function that does the content filtering for the current request */
607 char *(*content_filter)() = NULL;
609 /* Skeleton for HTTP response, if we should intercept the request */
610 struct http_response *rsp;
615 * Read the client's request. Note that since we're not using select() we
616 * could get blocked here if a client connected, then didn't say anything!
621 n = read_socket(csp->cfd, buf, sizeof(buf));
623 if (n <= 0) break; /* error! */
625 add_to_iob(csp, buf, n);
627 req = get_header(csp);
631 break; /* no HTTP request! */
636 continue; /* more to come! */
639 #ifdef FEATURE_FORCE_LOAD
640 /* If this request contains the FORCE_PREFIX,
641 * better get rid of it now and set the force flag --oes
644 if (strstr(req, FORCE_PREFIX))
646 strclean(req, FORCE_PREFIX);
647 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
648 csp->flags |= CSP_FLAG_FORCED;
651 #endif /* def FEATURE_FORCE_LOAD */
653 parse_http_request(req, http, csp);
658 if (http->cmd == NULL)
660 strcpy(buf, CHEADER);
661 write_socket(csp->cfd, buf, strlen(buf));
663 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
668 /* decide how to route the HTTP request */
670 if ((fwd = forward_url(http, csp)) == NULL)
672 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
673 /* Never get here - LOG_LEVEL_FATAL causes program exit */
676 /* build the http request to send to the server
677 * we have to do one of the following:
679 * create = use the original HTTP request to create a new
680 * HTTP request that has either the path component
681 * without the http://domainspec (w/path) or the
682 * full orininal URL (w/url)
683 * Note that the path and/or the HTTP version may
684 * have been altered by now.
686 * connect = Open a socket to the host:port of the server
687 * and short-circuit server and client socket.
689 * pass = Pass the request unchanged if forwarding a CONNECT
690 * request to a parent proxy. Note that we'll be sending
691 * the CFAIL message ourselves if connecting to the parent
692 * fails, but we won't send a CSUCCEED message if it works,
693 * since that would result in a double message (ours and the
694 * parent's). After sending the request to the parent, we simply
700 * +--------+--------+
702 * 0 | create | connect|
704 * Forwarding +--------+--------+
706 * 1 | create | pass |
708 * +--------+--------+
713 * Determine the actions for this URL
715 #ifdef FEATURE_TOGGLE
716 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
718 /* Most compatible set of actions (i.e. none) */
719 init_current_action(csp->action);
722 #endif /* ndef FEATURE_TOGGLE */
724 url_actions(http, csp);
729 * Check if a CONNECT request is allowable:
730 * In the absence of a +limit-connect action, allow only port 443.
731 * If there is an action, allow whatever matches the specificaton.
735 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
736 || (csp->action->flags & ACTION_LIMIT_CONNECT
737 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
739 strcpy(buf, CFORBIDDEN);
740 write_socket(csp->cfd, buf, strlen(buf));
742 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
743 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
751 * Downgrade http version from 1.1 to 1.0 if +downgrade
754 if (!strcmpic(http->ver, "HTTP/1.1") && csp->action->flags & ACTION_DOWNGRADE)
757 http->ver = strdup("HTTP/1.0");
761 * (Re)build the HTTP request for non-SSL requests.
762 * If forwarding, use the whole URL, else, use only the path.
768 http->cmd = strsav(http->cmd, http->gpc);
769 http->cmd = strsav(http->cmd, " ");
771 if (fwd->forward_host)
773 http->cmd = strsav(http->cmd, http->url);
777 http->cmd = strsav(http->cmd, http->path);
780 http->cmd = strsav(http->cmd, " ");
781 http->cmd = strsav(http->cmd, http->ver);
784 enlist(csp->headers, http->cmd);
787 #ifdef FEATURE_COOKIE_JAR
789 * If we're logging cookies in a cookie jar, and the user has not
790 * supplied any wafers, and the user has not told us to suppress the
791 * vanilla wafer, then send the vanilla wafer.
793 if ((csp->config->jarfile != NULL)
794 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
795 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
797 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
799 #endif /* def FEATURE_COOKIE_JAR */
802 #ifdef FEATURE_KILL_POPUPS
803 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
804 #endif /* def FEATURE_KILL_POPUPS */
806 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
807 ((csp->action->flags & ACTION_FILTER) != 0);
809 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
811 /* grab the rest of the client's headers */
815 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
817 n = read_socket(csp->cfd, buf, sizeof(buf));
820 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
823 add_to_iob(csp, buf, n);
827 if (p == NULL) break;
829 enlist(csp->headers, p);
833 * We have a request. Now, check to see if we need to
834 * intercept it, i.e. If ..
838 /* a CGI call was detected and answered */
839 (NULL != (rsp = dispatch_cgi(csp)))
841 /* or we are enabled and... */
844 /* ..the request was blocked */
845 ( NULL != (rsp = block_url(csp)))
849 || ( NULL != (rsp = trust_url(csp)))
850 #endif /* def FEATURE_TRUST */
852 /* ..or a fast redirect kicked in */
853 #ifdef FEATURE_FAST_REDIRECTS
854 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
855 (NULL != (rsp = redirect_url(csp))))
856 #endif /* def FEATURE_FAST_REDIRECTS */
860 /* Write the answer to the client */
861 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
862 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
864 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
867 #ifdef FEATURE_STATISTICS
868 /* Count as a rejected request */
869 csp->flags |= CSP_FLAG_REJECTED;
870 #endif /* def FEATURE_STATISTICS */
872 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
873 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
874 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
876 /* Clean up and return */
877 free_http_response(rsp);
881 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
883 if (fwd->forward_host)
885 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
886 fwd->forward_host, fwd->forward_port, http->hostport);
890 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
893 /* here we connect to the server, gateway, or the forwarder */
895 csp->sfd = forwarded_connect(fwd, http, csp);
899 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
904 rsp = error_response(csp, "no-such-domain", errno);
906 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
907 csp->ip_addr_str, http->cmd);
911 rsp = error_response(csp, "connect-failed", errno);
913 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
914 csp->ip_addr_str, http->cmd);
918 /* Write the answer to the client */
921 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
922 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
924 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
928 free_http_response(rsp);
932 log_error(LOG_LEVEL_CONNECT, "OK");
934 hdr = sed(client_patterns, add_client_headers, csp);
935 list_remove_all(csp->headers);
937 if (fwd->forward_host || (http->ssl == 0))
939 /* write the client's (modified) header to the server
940 * (along with anything else that may be in the buffer)
945 if ((write_socket(csp->sfd, hdr, n) != n)
946 || (flush_socket(csp->sfd, csp ) < 0))
948 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
951 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
952 csp->ip_addr_str, http->cmd);
954 rsp = error_response(csp, "connect-failed", errno);
958 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
959 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
961 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
965 free_http_response(rsp);
973 * We're running an SSL tunnel and we're not forwarding,
974 * so just send the "connect succeeded" message to the
975 * client, flush the rest, and get out of the way.
977 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
978 csp->ip_addr_str, http->cmd);
980 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
988 /* we're finished with the client's header */
991 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
993 /* pass data between the client and server
994 * until one or the other shuts down the connection.
1003 FD_SET(csp->cfd, &rfds);
1004 FD_SET(csp->sfd, &rfds);
1006 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1010 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1014 /* this is the body of the browser's request
1015 * just read it and write it.
1018 if (FD_ISSET(csp->cfd, &rfds))
1020 n = read_socket(csp->cfd, buf, sizeof(buf));
1024 break; /* "game over, man" */
1027 if (write_socket(csp->sfd, buf, n) != n)
1029 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1036 * The server wants to talk. It could be the header or the body.
1037 * If `hdr' is null, then it's the header otherwise it's the body.
1038 * FIXME: Does `hdr' really mean `host'? No.
1042 if (FD_ISSET(csp->sfd, &rfds))
1045 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1049 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1051 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1052 csp->ip_addr_str, http->cmd);
1054 rsp = error_response(csp, "connect-failed", errno);
1058 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1059 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1061 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1065 free_http_response(rsp);
1069 /* Add a trailing zero. This lets filter_popups
1070 * use string operations.
1074 #ifdef FEATURE_KILL_POPUPS
1075 /* Filter the popups on this read. */
1076 if (block_popups_now)
1078 filter_popups(buf, csp);
1080 #endif /* def FEATURE_KILL_POPUPS */
1082 /* Normally, this would indicate that we've read
1083 * as much as the server has sent us and we can
1084 * close the client connection. However, Microsoft
1085 * in its wisdom has released IIS/5 with a bug that
1086 * prevents it from sending the trailing \r\n in
1087 * a 302 redirect header (and possibly other headers).
1088 * To work around this if we've haven't parsed
1089 * a full header we'll append a trailing \r\n
1090 * and see if this now generates a valid one.
1092 * This hack shouldn't have any impacts. If we've
1093 * already transmitted the header or if this is a
1094 * SSL connection, then we won't bother with this
1095 * hack. So we only work on partially received
1096 * headers. If we append a \r\n and this still
1097 * doesn't generate a valid header, then we won't
1098 * transmit anything to the client.
1103 if (server_body || http->ssl)
1106 * If we have been buffering up the document,
1107 * now is the time to apply content modification
1108 * and send the result to the client.
1113 * If the content filter fails, use the original
1114 * buffer and length.
1115 * (see p != NULL ? p : csp->iob->cur below)
1117 if (NULL == (p = (*content_filter)(csp)))
1119 csp->content_length = csp->iob->eod - csp->iob->cur;
1122 hdr = sed(server_patterns, add_server_headers, csp);
1125 if ((write_socket(csp->cfd, hdr, n) != n)
1126 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1128 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1138 break; /* "game over, man" */
1142 * This is NOT the body, so
1143 * Let's pretend the server just sent us a blank line.
1145 n = sprintf(buf, "\r\n");
1148 * Now, let the normal header parsing algorithm below do its
1149 * job. If it fails, we'll exit instead of continuing.
1156 * If this is an SSL connection or we're in the body
1157 * of the server document, just write it to the client,
1158 * unless we need to buffer the body for later content-filtering
1161 if (server_body || http->ssl)
1165 add_to_iob(csp, buf, n);
1168 * If the buffer limit will be reached on the next read,
1169 * switch to non-filtering mode, i.e. make & write the
1170 * header, flush the socket and get out of the way.
1172 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1174 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1176 hdr = sed(server_patterns, add_server_headers, csp);
1180 if (((write_socket(csp->cfd, hdr, n) != n)
1181 || (n = flush_socket(csp->cfd, csp) < 0)))
1183 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1192 content_filter = NULL;
1199 if (write_socket(csp->cfd, buf, n) != n)
1201 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1210 /* we're still looking for the end of the
1211 * server's header ... (does that make header
1212 * parsing an "out of body experience" ?
1215 /* buffer up the data we just read */
1216 add_to_iob(csp, buf, n);
1218 /* get header lines from the iob */
1220 while ((p = get_header(csp)))
1224 /* see following note */
1227 enlist(csp->headers, p);
1231 /* NOTE: there are no "empty" headers so
1232 * if the pointer `p' is not NULL we must
1233 * assume that we reached the end of the
1234 * buffer before we hit the end of the header.
1241 /* Well, we tried our MS IIS/5
1242 * hack and it didn't work.
1243 * The header is incomplete
1244 * and there isn't anything
1245 * we can do about it.
1251 /* Since we have to wait for
1252 * more from the server before
1253 * we can parse the headers
1254 * we just continue here.
1260 /* we have now received the entire header.
1261 * filter it and send the result to the client
1264 hdr = sed(server_patterns, add_server_headers, csp);
1267 /* write the server's (modified) header to
1268 * the client (along with anything else that
1269 * may be in the buffer)
1272 #ifdef FEATURE_KILL_POPUPS
1273 /* Start blocking popups if appropriate. */
1275 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1276 !http->ssl && /* We talk plaintext */
1277 block_popups) /* Policy allows */
1279 block_popups_now = 1;
1281 * Filter the part of the body that came in the same read
1282 * as the last headers:
1284 filter_popups(csp->iob->cur, csp);
1287 #endif /* def FEATURE_KILL_POPUPS */
1289 /* Buffer and pcrs filter this if appropriate. */
1291 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1292 !http->ssl && /* We talk plaintext */
1293 pcrs_filter) /* Policy allows */
1295 content_filter = pcrs_filter_response;
1298 /* Buffer and gif_deanimate this if appropriate. */
1300 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1301 !http->ssl && /* We talk plaintext */
1302 gif_deanimate) /* Policy allows */
1304 content_filter = gif_deanimate_response;
1309 * Only write if we're not buffering for content modification
1311 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1312 || (n = flush_socket(csp->cfd, csp) < 0)))
1314 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1316 /* the write failed, so don't bother
1317 * mentioning it to the client...
1318 * it probably can't hear us anyway.
1324 if(!content_filter) byte_count += n;
1326 /* we're finished with the server's header */
1331 /* If this was a MS IIS/5 hack then it means
1332 * the server has already closed the
1333 * connection. Nothing more to read. Time
1344 return; /* huh? we should never get here */
1347 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1348 csp->ip_addr_str, http->cmd, byte_count);
1352 /*********************************************************************
1356 * Description : This is little more than chat. We only "serve" to
1357 * to close any socket that chat may have opened.
1360 * 1 : csp = Current client state (buffers, headers, etc...)
1364 *********************************************************************/
1366 void serve(struct client_state *csp)
1367 #else /* ifndef AMIGA */
1368 static void serve(struct client_state *csp)
1369 #endif /* def AMIGA */
1372 close_socket(csp->cfd);
1376 close_socket(csp->sfd);
1379 csp->flags &= ~CSP_FLAG_ACTIVE;
1385 /*********************************************************************
1387 * Function : server_thread
1389 * Description : We only exist to call `serve' in a threaded environment.
1392 * 1 : data = Current client state (buffers, headers, etc...)
1394 * Returns : Always 0.
1396 *********************************************************************/
1397 static int32 server_thread(void *data)
1399 serve((struct client_state *) data);
1406 /*********************************************************************
1410 * Description : Load the config file and start the listen loop.
1411 * This function is a lot more *sane* with the `load_config'
1412 * and `listen_loop' functions; although it stills does
1413 * a *little* too much for my taste.
1416 * 1 : argc = Number of parameters (including $0).
1417 * 2 : argv = Array of (char *)'s to the parameters.
1419 * Returns : 1 if : can't open config file, unrecognized directive,
1420 * stats requested in multi-thread mode, can't open the
1421 * log file, can't open the jar file, listen port is invalid,
1422 * any load fails, and can't bind port.
1424 * Else main never returns, the process must be signaled
1425 * to terminate execution. Or, on Windows, use the
1426 * "File", "Exit" menu option.
1428 *********************************************************************/
1430 int real_main(int argc, const char *argv[])
1432 int main(int argc, const char *argv[])
1439 "AmiTCP:db/junkbuster/config"
1440 #elif !defined(_WIN32)
1447 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1448 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1450 printf("JunkBuster proxy version " VERSION ".\n\n"
1451 "Usage: %s [configfile]\n\n"
1452 "See " HOME_PAGE_URL " for details.\n"
1453 "This program is distributed under the GNU GPL, version 2 or later.\n",
1457 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1459 printf(VERSION "\n");
1463 if ((argc >= 2) && (strcmp(argv[1], "-d")==0))
1467 fprintf(stderr,"debugging enabled..\n");
1470 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1475 if (argc > argc_pos )
1477 configfile = argv[argc_pos];
1481 if ( *configfile != '/' )
1485 DBG(1, ("configfile before '%s'\n",configfile) );
1487 /* make config-filename absolute here */
1488 if ( !(basedir = getcwd( NULL, 1024 )))
1490 perror("get working dir failed");
1493 DBG(1, ("working dir '%s'\n",basedir) );
1494 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1496 perror("malloc failed");
1499 strcpy( abs_file, basedir );
1500 strcat( abs_file, "/" );
1501 strcat( abs_file, configfile );
1502 configfile = abs_file;
1503 DBG(1, ("configfile after '%s'\n",configfile) );
1505 #endif /* defined unix */
1512 #elif defined(_WIN32)
1517 #if !defined(_WIN32) && !defined(__OS2__)
1520 struct sigaction action;
1522 for ( sig = 1; sig < 16; sig++ )
1532 if ( signal(sig, SIG_handler) == SIG_ERR )
1533 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", sig);
1536 if ( signal(SIGPIPE, SIG_IGN) == SIG_ERR )
1537 log_error(LOG_LEVEL_FATAL, "Can't set SIG_IGN to SIGPIPE: %E");
1538 if ( signal(SIGCHLD, SIG_IGN) == SIG_ERR )
1539 log_error(LOG_LEVEL_FATAL, "Can't set SIG_IGN to SIGCHLD: %E");
1540 /* log file reload */
1541 if (!sigaction(SIGHUP,NULL,&action))
1543 action.sa_handler = &SIG_handler;
1544 action.sa_flags = SA_RESTART;
1546 if ( sigaction(SIGHUP,&action,NULL))
1547 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal SIGHUP: %E");
1551 perror("sigaction");
1552 log_error(LOG_LEVEL_FATAL, "Can't get sigaction data for signal SIGHUP");
1557 #else /* ifdef _WIN32 */
1558 # ifdef _WIN_CONSOLE
1560 * We *are* in a windows console app.
1561 * Print a verbose messages about FAQ's and such
1563 printf(win32_blurb);
1564 # endif /* def _WIN_CONSOLE */
1565 #endif /* def _WIN32 */
1568 /* Initialize the CGI subsystem */
1569 cgi_init_error_messages();
1579 * we make us a real daemon
1585 if ( pid < 0 ) /* error */
1590 else if ( pid != 0 ) /* parent */
1595 * must check for errors
1596 * child died due to missing files aso
1599 wpid = waitpid( pid, &status, WNOHANG );
1608 /* Should be more portable, but not as well tested */
1613 #else /* ndef __FreeBSD__ */
1615 #endif /* ndef __FreeBSD__ */
1616 fd = open("/dev/tty", O_RDONLY);
1619 /* no error check here */
1620 ioctl( fd, TIOCNOTTY,0 );
1624 /* should close stderr (fd 2) here too, but the test for existence
1625 ** and load config file is done in listen_loop() and puts
1626 ** some messages on stderr there.
1642 #endif /* defined unix */
1644 DBG(1, ("call listen_loop() \n") );
1653 /*********************************************************************
1655 * Function : listen_loop
1657 * Description : bind the listen port and enter a "FOREVER" listening loop.
1663 *********************************************************************/
1664 static void listen_loop(void)
1666 struct client_state *csp = NULL;
1668 struct configuration_spec * config;
1670 config = load_config();
1672 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1673 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1675 bfd = bind_port(config->haddr, config->hport);
1679 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1680 "- There may be another junkbuster or some other "
1681 "proxy running on port %d",
1682 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1683 config->hport, config->hport
1685 /* shouldn't get here */
1689 config->need_bind = 0;
1693 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1694 while (waitpid(-1, NULL, WNOHANG) > 0)
1696 /* zombie children */
1698 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1701 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1703 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1707 csp->flags |= CSP_FLAG_ACTIVE;
1710 csp->config = config = load_config();
1712 if ( config->need_bind )
1715 * Since we were listening to the "old port", we will not see
1716 * a "listen" param change until the next IJB request. So, at
1717 * least 1 more request must be made for us to find the new
1718 * setting. I am simply closing the old socket and binding the
1721 * Which-ever is correct, we will serve 1 more page via the
1722 * old settings. This should probably be a "show-proxy-args"
1723 * request. This should not be a so common of an operation
1724 * that this will hurt people's feelings.
1729 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1730 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1731 bfd = bind_port(config->haddr, config->hport);
1735 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1736 "- There may be another junkbuster or some other "
1737 "proxy running on port %d",
1738 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1739 config->hport, config->hport
1741 /* shouldn't get here */
1745 config->need_bind = 0;
1748 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1750 if (!accept_connection(csp, bfd))
1752 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1765 log_error(LOG_LEVEL_CONNECT, "OK");
1768 #ifdef FEATURE_TOGGLE
1771 csp->flags |= CSP_FLAG_TOGGLED_ON;
1773 #endif /* def FEATURE_TOGGLE */
1775 if (run_loader(csp))
1777 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1778 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1782 if (block_acl(NULL,csp))
1784 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1785 close_socket(csp->cfd);
1789 #endif /* def FEATURE_ACL */
1791 /* add it to the list of clients */
1792 csp->next = clients->next;
1793 clients->next = csp;
1795 if (config->multi_threaded)
1799 /* this is a switch () statment in the C preprocessor - ugh */
1800 #undef SELECTED_ONE_OPTION
1802 /* Use Pthreads in preference to native code */
1803 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1804 #define SELECTED_ONE_OPTION
1806 pthread_t the_thread;
1807 pthread_attr_t attrs;
1809 pthread_attr_init(&attrs);
1810 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1811 child_id = (pthread_create(&the_thread, &attrs,
1812 (void*)serve, csp) ? -1 : 0);
1813 pthread_attr_destroy(&attrs);
1817 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1818 #define SELECTED_ONE_OPTION
1819 child_id = _beginthread(
1825 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1826 #define SELECTED_ONE_OPTION
1827 child_id = _beginthread(
1834 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1835 #define SELECTED_ONE_OPTION
1837 thread_id tid = spawn_thread
1838 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1840 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1842 child_id = (int) tid;
1851 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1852 #define SELECTED_ONE_OPTION
1853 csp->cfd = ReleaseSocket(csp->cfd, -1);
1854 if((child_id = (int)CreateNewProcTags(
1855 NP_Entry, (ULONG)server_thread,
1856 NP_Output, Output(),
1857 NP_CloseOutput, FALSE,
1858 NP_Name, (ULONG)"junkbuster child",
1859 NP_StackSize, 200*1024,
1863 ((struct Task *)child_id)->tc_UserData = csp;
1864 Signal((struct Task *)child_id, SIGF_SINGLE);
1869 #if !defined(SELECTED_ONE_OPTION)
1872 /* This block is only needed when using fork().
1873 * When using threads, the server thread was
1874 * created and run by the call to _beginthread().
1876 if (child_id == 0) /* child */
1882 else if (child_id > 0) /* parent */
1884 /* in a fork()'d environment, the parent's
1885 * copy of the client socket and the CSP
1889 #if !defined(_WIN32) && defined(__CYGWIN__)
1891 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1892 close_socket(csp->cfd);
1893 csp->flags &= ~CSP_FLAG_ACTIVE;
1897 #undef SELECTED_ONE_OPTION
1898 /* end of cpp switch () */
1900 if (child_id < 0) /* failed */
1902 char buf[BUFFER_SIZE];
1904 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1906 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1908 write_socket(csp->cfd, buf, strlen(buf));
1909 close_socket(csp->cfd);
1910 csp->flags &= ~CSP_FLAG_ACTIVE;