1 const char jcc_rcs[] = "$Id: jcc.c,v 1.60 2001/12/30 14:07:32 steudten 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.60 2001/12/30 14:07:32 steudten
37 * - Add signal handling (unix)
38 * - Add SIGHUP handler (unix)
39 * - Add creation of pidfile (unix)
40 * - Add action 'top' in rc file (RH)
41 * - Add entry 'SIGNALS' to manpage
42 * - Add exit message to logfile (unix)
44 * Revision 1.59 2001/12/13 14:07:18 oes
45 * Fixed Bug: 503 error page now sent OK
47 * Revision 1.58 2001/11/30 23:37:24 jongfoster
48 * Renaming the Win32 config file to config.txt - this is almost the
49 * same as the corresponding UNIX name "config"
51 * Revision 1.57 2001/11/16 00:47:43 jongfoster
52 * Changing the tty-disconnection code to use setsid().
54 * Revision 1.56 2001/11/13 20:20:54 jongfoster
55 * Tabs->spaces, fixing a bug with missing {} around an if()
57 * Revision 1.55 2001/11/13 20:14:53 jongfoster
58 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
60 * Revision 1.54 2001/11/07 00:03:14 steudten
61 * Give reliable return value if an error
62 * occurs not just 0 with new daemon mode.
64 * Revision 1.53 2001/11/05 21:41:43 steudten
65 * Add changes to be a real daemon just for unix os.
66 * (change cwd to /, detach from controlling tty, set
67 * process group and session leader to the own process.
69 * Add some fatal-error log message for failed malloc().
70 * Add '-d' if compiled with 'configure --with-debug' to
71 * enable debug output.
73 * Revision 1.52 2001/10/26 20:11:20 jongfoster
74 * Fixing type mismatch
76 * Revision 1.51 2001/10/26 17:38:28 oes
79 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
80 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
81 * threads to call select() simultaneously. So, it's time to do a real, live,
82 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
83 * (native). Both versions will work, but using __OS2__ offers multi-threading.
85 * Revision 1.49 2001/10/23 21:41:35 jongfoster
86 * Added call to initialize the (statically-allocated of course)
87 * "out of memory" CGI response.
89 * Revision 1.48 2001/10/10 19:56:46 jongfoster
90 * Moving some code that wasn't cookie-related out of an #ifdef
93 * Revision 1.47 2001/10/10 16:44:36 oes
94 * Added CONNECT destination port limitation check
96 * Revision 1.46 2001/10/08 15:17:41 oes
97 * Re-enabled SSL forwarding
99 * Revision 1.45 2001/10/07 15:42:11 oes
100 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
102 * Moved downgrading of the HTTP version from parse_http_request to
103 * chat(), since we can't decide if it is necessary before we have
104 * determined the actions for the URL. The HTTP command is now
105 * *always* re-built so the repairs need no longer be special-cased.
107 * filter_popups now gets a csp pointer so it can raise the new
108 * CSP_FLAG_MODIFIED flag.
112 * Added configurable size limit for the IOB. If the IOB grows so
113 * large that the next read would exceed the limit, the header
114 * is generated, and the header & unfiltered buffer are flushed
115 * to the client. Chat then continues in non-buffering,
116 * non-filtering body mode.
118 * Revision 1.44 2001/10/02 18:13:57 oes
121 * Revision 1.43 2001/10/02 15:32:13 oes
122 * Moved generation of hdr
124 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
125 * Cleaning up 2 compiler warnings on OS/2.
127 * Revision 1.41 2001/09/16 17:05:14 jongfoster
128 * Removing unused #include showarg.h
130 * Revision 1.40 2001/09/16 15:41:45 jongfoster
131 * Fixing signed/unsigned comparison warning.
133 * Revision 1.39 2001/09/16 13:21:27 jongfoster
134 * Changes to use new list functions.
136 * Revision 1.38 2001/09/16 13:01:46 jongfoster
137 * Removing redundant function call that zeroed zalloc()'d memory.
139 * Revision 1.37 2001/09/10 11:12:24 oes
140 * Deleted unused variable
142 * Revision 1.36 2001/09/10 10:56:15 oes
143 * Silenced compiler warnings
145 * Revision 1.35 2001/07/31 14:44:22 oes
146 * Deleted unused size parameter from filter_popups()
148 * Revision 1.34 2001/07/30 22:08:36 jongfoster
149 * Tidying up #defines:
150 * - All feature #defines are now of the form FEATURE_xxx
151 * - Permanently turned off WIN_GUI_EDIT
152 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
154 * Revision 1.33 2001/07/29 19:32:00 jongfoster
155 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
157 * Revision 1.32 2001/07/29 18:47:05 jongfoster
158 * Adding missing #include "loadcfg.h"
160 * Revision 1.31 2001/07/29 12:17:48 oes
161 * Applied pthread fix by Paul Lieverse
163 * Revision 1.30 2001/07/25 22:57:13 jongfoster
164 * __BEOS__ no longer overrides FEATURE_PTHREAD.
165 * This is because FEATURE_PTHREAD will soon be widely used, so I
166 * want to keep it simple.
168 * Revision 1.29 2001/07/24 12:47:06 oes
169 * Applied BeOS support update by Eugenia
171 * Revision 1.28 2001/07/23 13:26:12 oes
172 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
174 * Revision 1.27 2001/07/19 19:09:47 haroon
175 * - Added code to take care of the situation where while processing the first
176 * server response (which includes the server header), after finding the end
177 * of the headers we were not looking past the end of the headers for
178 * content modification. I enabled it for filter_popups.
179 * Someone else should look to see if other similar operations should be
180 * done to the discarded portion of the buffer.
182 * Note 2001/07/20: No, the other content modification mechanisms will process
183 * the whole iob later anyway. --oes
185 * Revision 1.26 2001/07/18 12:31:36 oes
188 * Revision 1.25 2001/07/15 19:43:49 jongfoster
189 * Supports POSIX threads.
190 * Also removed some unused #includes.
192 * Revision 1.24 2001/07/13 14:00:40 oes
193 * - Generic content modification scheme:
194 * Each feature has its own applicability flag that is set
195 * from csp->action->flags.
196 * Replaced the "filtering" int flag , by a function pointer
197 * "content_filter" to the function that will do the content
198 * modification. If it is != NULL, the document will be buffered
199 * and processed through *content_filter, which must set
200 * csp->content_length and return a modified copy of the body
201 * or return NULL (on failiure).
202 * - Changed csp->is_text to the more generic bitmap csp->content_type
203 * which can currently take the valued CT_TEXT or CT_GIF
205 * - Removed all #ifdef PCRS
207 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
208 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
209 * the `block_acl' call. This prevents a compilation error when the user
210 * does not wish to use the "ACL" feature.
212 * Revision 1.22 2001/06/29 21:45:41 oes
213 * Indentation, CRLF->LF, Tab-> Space
215 * Revision 1.21 2001/06/29 13:29:36 oes
216 * - Cleaned up, improved comments
217 * - Unified all possible interceptors (CGI,
218 * block, trust, fast_redirect) in one
219 * place, with one (CGI) answer generation
220 * mechansim. Much clearer now.
221 * - Removed the GIF image generation, which
222 * is now done in filters.c:block_url()
223 * - Made error conditions like domain lookup
224 * failiure or (various) problems while talking
225 * to the server use cgi.c:error_response()
226 * instead of generating HTML/HTTP in chat() (yuck!)
227 * - Removed logentry from cancelled commit
229 * Revision 1.20 2001/06/09 10:55:28 jongfoster
230 * Changing BUFSIZ ==> BUFFER_SIZE
232 * Revision 1.19 2001/06/07 23:12:52 jongfoster
233 * Replacing function pointer in struct gateway with a directly
234 * called function forwarded_connect().
235 * Replacing struct gateway with struct forward_spec
237 * Revision 1.18 2001/06/03 19:12:16 oes
238 * introduced new cgi handling
240 * Revision 1.17 2001/06/01 20:07:23 jongfoster
241 * Now uses action +image-blocker{} rather than config->tinygif
243 * Revision 1.16 2001/06/01 18:49:17 jongfoster
244 * Replaced "list_share" with "list" - the tiny memory gain was not
245 * worth the extra complexity.
247 * Revision 1.15 2001/05/31 21:24:47 jongfoster
248 * Changed "permission" to "action" throughout.
249 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
250 * Moved vanilla wafer check into chat(), since we must now
251 * decide whether or not to add it based on the URL.
253 * Revision 1.14 2001/05/29 20:14:01 joergs
254 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
257 * Revision 1.13 2001/05/29 09:50:24 jongfoster
258 * Unified blocklist/imagelist/permissionslist.
259 * File format is still under discussion, but the internal changes
262 * Also modified interceptor behaviour:
263 * - We now intercept all URLs beginning with one of the following
264 * prefixes (and *only* these prefixes):
266 * * http://ijbswa.sf.net/config/
267 * * http://ijbswa.sourceforge.net/config/
268 * - New interceptors "home page" - go to http://i.j.b/ to see it.
269 * - Internal changes so that intercepted and fast redirect pages
270 * are not replaced with an image.
271 * - Interceptors now have the option to send a binary page direct
272 * to the client. (i.e. ijb-send-banner uses this)
273 * - Implemented show-url-info interceptor. (Which is why I needed
274 * the above interceptors changes - a typical URL is
275 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
276 * The previous mechanism would not have intercepted that, and
277 * if it had been intercepted then it then it would have replaced
280 * Revision 1.12 2001/05/27 22:17:04 oes
282 * - re_process_buffer no longer writes the modified buffer
283 * to the client, which was very ugly. It now returns the
284 * buffer, which it is then written by chat.
286 * - content_length now adjusts the Content-Length: header
287 * for modified documents rather than crunch()ing it.
288 * (Length info in csp->content_length, which is 0 for
289 * unmodified documents)
291 * - For this to work, sed() is called twice when filtering.
293 * Revision 1.11 2001/05/26 17:27:53 jongfoster
294 * Added support for CLF and fixed LOG_LEVEL_LOG.
295 * Also did CRLF->LF fix of my previous patch.
297 * Revision 1.10 2001/05/26 15:26:15 jongfoster
298 * ACL feature now provides more security by immediately dropping
299 * connections from untrusted hosts.
301 * Revision 1.9 2001/05/26 00:28:36 jongfoster
302 * Automatic reloading of config file.
303 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
304 * Most of the global variables have been moved to a new
305 * struct configuration_spec, accessed through csp->config->globalname
306 * Most of the globals remaining are used by the Win32 GUI.
308 * Revision 1.8 2001/05/25 22:43:18 jongfoster
309 * Fixing minor memory leak and buffer overflow.
311 * Revision 1.7 2001/05/25 22:34:30 jongfoster
314 * Revision 1.6 2001/05/23 00:13:58 joergs
315 * AmigaOS support fixed.
317 * Revision 1.5 2001/05/22 18:46:04 oes
319 * - Enabled filtering banners by size rather than URL
320 * by adding patterns that replace all standard banner
321 * sizes with the "Junkbuster" gif to the re_filterfile
323 * - Enabled filtering WebBugs by providing a pattern
324 * which kills all 1x1 images
326 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
327 * which is selected by the (nonstandard and therefore
328 * capital) letter 'U' in the option string.
329 * It causes the quantifiers to be ungreedy by default.
330 * Appending a ? turns back to greedy (!).
332 * - Added a new interceptor ijb-send-banner, which
333 * sends back the "Junkbuster" gif. Without imagelist or
334 * MSIE detection support, or if tinygif = 1, or the
335 * URL isn't recognized as an imageurl, a lame HTML
336 * explanation is sent instead.
338 * - Added new feature, which permits blocking remote
339 * script redirects and firing back a local redirect
341 * The feature is conditionally compiled, i.e. it
342 * can be disabled with --disable-fast-redirects,
343 * plus it must be activated by a "fast-redirects"
344 * line in the config file, has its own log level
345 * and of course wants to be displayed by show-proxy-args
346 * Note: Boy, all the #ifdefs in 1001 locations and
347 * all the fumbling with configure.in and acconfig.h
348 * were *way* more work than the feature itself :-(
350 * - Because a generic redirect template was needed for
351 * this, tinygif = 3 now uses the same.
353 * - Moved GIFs, and other static HTTP response templates
358 * - Removed some >400 CRs again (Jon, you really worked
361 * Revision 1.4 2001/05/21 19:34:01 jongfoster
362 * Made failure to bind() a fatal error.
364 * Revision 1.3 2001/05/20 01:21:20 jongfoster
365 * Version 2.9.4 checkin.
366 * - Merged popupfile and cookiefile, and added control over PCRS
367 * filtering, in new "permissionsfile".
368 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
369 * file error you now get a message box (in the Win32 GUI) rather
370 * than the program exiting with no explanation.
371 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
373 * - Removed tabs from "config"
374 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
375 * - Bumped up version number.
377 * Revision 1.2 2001/05/17 22:34:44 oes
378 * - Added hint on GIF char array generation to jcc.c
379 * - Cleaned CRLF's from the sources and related files
380 * - Repaired logging for REF and FRC
382 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
383 * Initial import of version 2.9.3 source tree
386 *********************************************************************/
392 #include <sys/types.h>
399 #ifdef FEATURE_PTHREAD
401 #endif /* def FEATURE_PTHREAD */
404 # ifndef FEATURE_PTHREAD
405 # include <windows.h>
406 # include <process.h>
407 # endif /* ndef FEATURE_PTHREAD */
410 # ifndef _WIN_CONSOLE
412 # endif /* ndef _WIN_CONSOLE */
414 #else /* ifndef _WIN32 */
416 # if !defined (__OS2__)
418 # include <sys/wait.h>
419 # endif /* ndef __OS2__ */
420 # include <sys/time.h>
421 # include <sys/stat.h>
422 # include <sys/ioctl.h>
425 #include <sys/termios.h>
431 # include <socket.h> /* BeOS has select() for sockets only. */
432 # include <OS.h> /* declarations for threads and stuff. */
435 # if defined(__EMX__) || defined(__OS2__)
436 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
441 #define bzero(B,N) memset(B,0x00,n)
460 #include "killpopup.h"
461 #include "miscutil.h"
463 #include "jbsockets.h"
468 #include "urlmatch.h"
470 const char jcc_h_rcs[] = JCC_H_VERSION;
471 const char project_h_rcs[] = PROJECT_H_VERSION;
473 struct client_state clients[1];
474 struct file_list files[1];
476 short int MustReload = 0;
478 #ifdef FEATURE_STATISTICS
479 int urls_read = 0; /* total nr of urls read inc rejected */
480 int urls_rejected = 0; /* total nr of urls rejected */
481 #endif /* def FEATURE_STATISTICS */
484 static void listen_loop(void);
485 static void chat(struct client_state *csp);
487 void serve(struct client_state *csp);
488 #else /* ifndef AMIGA */
489 static void serve(struct client_state *csp);
490 #endif /* def AMIGA */
493 static int32 server_thread(void *data);
494 #endif /* def __BEOS__ */
497 #define sleep(N) Sleep(((N) * 1000))
501 #define sleep(N) DosSleep(((N) * 100))
506 #endif /* defined unix */
508 /* The vanilla wafer. */
509 static const char VANILLA_WAFER[] =
510 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
511 "Do_not_send_me_any_copyrighted_information_other_than_the_"
512 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
513 "In_particular_do_not_send_me_any_cookies_that_"
514 "are_subject_to_a_claim_of_copyright_by_anybody._"
515 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
516 "(copyright_or_otherwise)_applying_to_any_cookie._";
519 #if !defined(_WIN32) && !defined(__OS2__)
520 /*********************************************************************
522 * Function : SIG_handler
524 * Description : Signal handler for different signals.
525 * see man kill, signal ..
528 * 1 : signal - the signal cause this function to call
532 *********************************************************************/
533 static void SIG_handler( int signal )
541 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", signal);
551 /* want to exit jb so use FATAL */
552 log_error(LOG_LEVEL_FATAL, "SIG_handler: receive signal %d without handler.", signal);
557 /*********************************************************************
561 * Description : Once a connection to the client has been accepted,
562 * this function is called (via serve()) to handle the
563 * main business of the communication. When this
564 * function returns, the caller must close the client
568 * 1 : csp = Current client state (buffers, headers, etc...)
570 * Returns : On success, the number of bytes written are returned (zero
571 * indicates nothing was written). On error, -1 is returned,
572 * and errno is set appropriately. If count is zero and the
573 * file descriptor refers to a regular file, 0 will be
574 * returned without causing any other effect. For a special
575 * file, the results are not portable.
577 *********************************************************************/
578 static void chat(struct client_state *csp)
581 * This next lines are a little ugly, but they simplifies the if statements
582 * below. Basically if TOGGLE, then we want the if to test if the
583 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
584 * then we want the if to test for CSP_FLAG_FORCED , else we don't
586 #ifdef FEATURE_TOGGLE
587 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
588 #else /* ifndef FEATURE_TOGGLE */
589 # define IS_TOGGLED_ON_AND
590 #endif /* ndef FEATURE_TOGGLE */
591 #ifdef FEATURE_FORCE_LOAD
592 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
593 #else /* ifndef FEATURE_FORCE_LOAD */
594 # define IS_NOT_FORCED_AND
595 #endif /* def FEATURE_FORCE_LOAD */
597 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
599 char buf[BUFFER_SIZE];
602 int n, maxfd, server_body;
603 int ms_iis5_hack = 0;
605 const struct forward_spec * fwd;
606 struct http_request *http;
607 #ifdef FEATURE_KILL_POPUPS
608 int block_popups; /* bool, 1==will block popups */
609 int block_popups_now = 0; /* bool, 1==currently blocking popups */
610 #endif /* def FEATURE_KILL_POPUPS */
612 int pcrs_filter; /* bool, 1==will filter through pcrs */
613 int gif_deanimate; /* bool, 1==will deanimate gifs */
615 /* Function that does the content filtering for the current request */
616 char *(*content_filter)() = NULL;
618 /* Skeleton for HTTP response, if we should intercept the request */
619 struct http_response *rsp;
624 * Read the client's request. Note that since we're not using select() we
625 * could get blocked here if a client connected, then didn't say anything!
630 n = read_socket(csp->cfd, buf, sizeof(buf));
632 if (n <= 0) break; /* error! */
634 add_to_iob(csp, buf, n);
636 req = get_header(csp);
640 break; /* no HTTP request! */
645 continue; /* more to come! */
648 #ifdef FEATURE_FORCE_LOAD
649 /* If this request contains the FORCE_PREFIX,
650 * better get rid of it now and set the force flag --oes
653 if (strstr(req, FORCE_PREFIX))
655 strclean(req, FORCE_PREFIX);
656 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
657 csp->flags |= CSP_FLAG_FORCED;
660 #endif /* def FEATURE_FORCE_LOAD */
662 parse_http_request(req, http, csp);
667 if (http->cmd == NULL)
669 strcpy(buf, CHEADER);
670 write_socket(csp->cfd, buf, strlen(buf));
672 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
677 /* decide how to route the HTTP request */
679 if ((fwd = forward_url(http, csp)) == NULL)
681 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
682 /* Never get here - LOG_LEVEL_FATAL causes program exit */
685 /* build the http request to send to the server
686 * we have to do one of the following:
688 * create = use the original HTTP request to create a new
689 * HTTP request that has either the path component
690 * without the http://domainspec (w/path) or the
691 * full orininal URL (w/url)
692 * Note that the path and/or the HTTP version may
693 * have been altered by now.
695 * connect = Open a socket to the host:port of the server
696 * and short-circuit server and client socket.
698 * pass = Pass the request unchanged if forwarding a CONNECT
699 * request to a parent proxy. Note that we'll be sending
700 * the CFAIL message ourselves if connecting to the parent
701 * fails, but we won't send a CSUCCEED message if it works,
702 * since that would result in a double message (ours and the
703 * parent's). After sending the request to the parent, we simply
709 * +--------+--------+
711 * 0 | create | connect|
713 * Forwarding +--------+--------+
715 * 1 | create | pass |
717 * +--------+--------+
722 * Determine the actions for this URL
724 #ifdef FEATURE_TOGGLE
725 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
727 /* Most compatible set of actions (i.e. none) */
728 init_current_action(csp->action);
731 #endif /* ndef FEATURE_TOGGLE */
733 url_actions(http, csp);
738 * Check if a CONNECT request is allowable:
739 * In the absence of a +limit-connect action, allow only port 443.
740 * If there is an action, allow whatever matches the specificaton.
744 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
745 || (csp->action->flags & ACTION_LIMIT_CONNECT
746 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
748 strcpy(buf, CFORBIDDEN);
749 write_socket(csp->cfd, buf, strlen(buf));
751 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
752 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
760 * Downgrade http version from 1.1 to 1.0 if +downgrade
763 if (!strcmpic(http->ver, "HTTP/1.1") && csp->action->flags & ACTION_DOWNGRADE)
766 http->ver = strdup("HTTP/1.0");
770 * (Re)build the HTTP request for non-SSL requests.
771 * If forwarding, use the whole URL, else, use only the path.
777 http->cmd = strsav(http->cmd, http->gpc);
778 http->cmd = strsav(http->cmd, " ");
780 if (fwd->forward_host)
782 http->cmd = strsav(http->cmd, http->url);
786 http->cmd = strsav(http->cmd, http->path);
789 http->cmd = strsav(http->cmd, " ");
790 http->cmd = strsav(http->cmd, http->ver);
793 enlist(csp->headers, http->cmd);
796 #ifdef FEATURE_COOKIE_JAR
798 * If we're logging cookies in a cookie jar, and the user has not
799 * supplied any wafers, and the user has not told us to suppress the
800 * vanilla wafer, then send the vanilla wafer.
802 if ((csp->config->jarfile != NULL)
803 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
804 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
806 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
808 #endif /* def FEATURE_COOKIE_JAR */
811 #ifdef FEATURE_KILL_POPUPS
812 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
813 #endif /* def FEATURE_KILL_POPUPS */
815 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
816 ((csp->action->flags & ACTION_FILTER) != 0);
818 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
820 /* grab the rest of the client's headers */
824 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
826 n = read_socket(csp->cfd, buf, sizeof(buf));
829 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
832 add_to_iob(csp, buf, n);
836 if (p == NULL) break;
838 enlist(csp->headers, p);
842 * We have a request. Now, check to see if we need to
843 * intercept it, i.e. If ..
847 /* a CGI call was detected and answered */
848 (NULL != (rsp = dispatch_cgi(csp)))
850 /* or we are enabled and... */
853 /* ..the request was blocked */
854 ( NULL != (rsp = block_url(csp)))
858 || ( NULL != (rsp = trust_url(csp)))
859 #endif /* def FEATURE_TRUST */
861 /* ..or a fast redirect kicked in */
862 #ifdef FEATURE_FAST_REDIRECTS
863 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
864 (NULL != (rsp = redirect_url(csp))))
865 #endif /* def FEATURE_FAST_REDIRECTS */
869 /* Write the answer to the client */
870 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
871 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
873 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
876 #ifdef FEATURE_STATISTICS
877 /* Count as a rejected request */
878 csp->flags |= CSP_FLAG_REJECTED;
879 #endif /* def FEATURE_STATISTICS */
881 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
882 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
883 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
885 /* Clean up and return */
886 free_http_response(rsp);
890 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
892 if (fwd->forward_host)
894 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
895 fwd->forward_host, fwd->forward_port, http->hostport);
899 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
902 /* here we connect to the server, gateway, or the forwarder */
904 csp->sfd = forwarded_connect(fwd, http, csp);
908 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
913 rsp = error_response(csp, "no-such-domain", errno);
915 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
916 csp->ip_addr_str, http->cmd);
920 rsp = error_response(csp, "connect-failed", errno);
922 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
923 csp->ip_addr_str, http->cmd);
927 /* Write the answer to the client */
930 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
931 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
933 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
937 free_http_response(rsp);
941 log_error(LOG_LEVEL_CONNECT, "OK");
943 hdr = sed(client_patterns, add_client_headers, csp);
944 list_remove_all(csp->headers);
946 if (fwd->forward_host || (http->ssl == 0))
948 /* write the client's (modified) header to the server
949 * (along with anything else that may be in the buffer)
954 if ((write_socket(csp->sfd, hdr, n) != n)
955 || (flush_socket(csp->sfd, csp ) < 0))
957 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
960 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
961 csp->ip_addr_str, http->cmd);
963 rsp = error_response(csp, "connect-failed", errno);
967 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
968 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
970 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
974 free_http_response(rsp);
982 * We're running an SSL tunnel and we're not forwarding,
983 * so just send the "connect succeeded" message to the
984 * client, flush the rest, and get out of the way.
986 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
987 csp->ip_addr_str, http->cmd);
989 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
997 /* we're finished with the client's header */
1000 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1002 /* pass data between the client and server
1003 * until one or the other shuts down the connection.
1012 FD_SET(csp->cfd, &rfds);
1013 FD_SET(csp->sfd, &rfds);
1015 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1019 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1023 /* this is the body of the browser's request
1024 * just read it and write it.
1027 if (FD_ISSET(csp->cfd, &rfds))
1029 n = read_socket(csp->cfd, buf, sizeof(buf));
1033 break; /* "game over, man" */
1036 if (write_socket(csp->sfd, buf, n) != n)
1038 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1045 * The server wants to talk. It could be the header or the body.
1046 * If `hdr' is null, then it's the header otherwise it's the body.
1047 * FIXME: Does `hdr' really mean `host'? No.
1051 if (FD_ISSET(csp->sfd, &rfds))
1054 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1058 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1060 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1061 csp->ip_addr_str, http->cmd);
1063 rsp = error_response(csp, "connect-failed", errno);
1067 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1068 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1070 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1074 free_http_response(rsp);
1078 /* Add a trailing zero. This lets filter_popups
1079 * use string operations.
1083 #ifdef FEATURE_KILL_POPUPS
1084 /* Filter the popups on this read. */
1085 if (block_popups_now)
1087 filter_popups(buf, csp);
1089 #endif /* def FEATURE_KILL_POPUPS */
1091 /* Normally, this would indicate that we've read
1092 * as much as the server has sent us and we can
1093 * close the client connection. However, Microsoft
1094 * in its wisdom has released IIS/5 with a bug that
1095 * prevents it from sending the trailing \r\n in
1096 * a 302 redirect header (and possibly other headers).
1097 * To work around this if we've haven't parsed
1098 * a full header we'll append a trailing \r\n
1099 * and see if this now generates a valid one.
1101 * This hack shouldn't have any impacts. If we've
1102 * already transmitted the header or if this is a
1103 * SSL connection, then we won't bother with this
1104 * hack. So we only work on partially received
1105 * headers. If we append a \r\n and this still
1106 * doesn't generate a valid header, then we won't
1107 * transmit anything to the client.
1112 if (server_body || http->ssl)
1115 * If we have been buffering up the document,
1116 * now is the time to apply content modification
1117 * and send the result to the client.
1122 * If the content filter fails, use the original
1123 * buffer and length.
1124 * (see p != NULL ? p : csp->iob->cur below)
1126 if (NULL == (p = (*content_filter)(csp)))
1128 csp->content_length = csp->iob->eod - csp->iob->cur;
1131 hdr = sed(server_patterns, add_server_headers, csp);
1134 if ((write_socket(csp->cfd, hdr, n) != n)
1135 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1137 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1147 break; /* "game over, man" */
1151 * This is NOT the body, so
1152 * Let's pretend the server just sent us a blank line.
1154 n = sprintf(buf, "\r\n");
1157 * Now, let the normal header parsing algorithm below do its
1158 * job. If it fails, we'll exit instead of continuing.
1165 * If this is an SSL connection or we're in the body
1166 * of the server document, just write it to the client,
1167 * unless we need to buffer the body for later content-filtering
1170 if (server_body || http->ssl)
1174 add_to_iob(csp, buf, n);
1177 * If the buffer limit will be reached on the next read,
1178 * switch to non-filtering mode, i.e. make & write the
1179 * header, flush the socket and get out of the way.
1181 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1183 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1185 hdr = sed(server_patterns, add_server_headers, csp);
1189 if (((write_socket(csp->cfd, hdr, n) != n)
1190 || (n = flush_socket(csp->cfd, csp) < 0)))
1192 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1201 content_filter = NULL;
1208 if (write_socket(csp->cfd, buf, n) != n)
1210 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1219 /* we're still looking for the end of the
1220 * server's header ... (does that make header
1221 * parsing an "out of body experience" ?
1224 /* buffer up the data we just read */
1225 add_to_iob(csp, buf, n);
1227 /* get header lines from the iob */
1229 while ((p = get_header(csp)))
1233 /* see following note */
1236 enlist(csp->headers, p);
1240 /* NOTE: there are no "empty" headers so
1241 * if the pointer `p' is not NULL we must
1242 * assume that we reached the end of the
1243 * buffer before we hit the end of the header.
1250 /* Well, we tried our MS IIS/5
1251 * hack and it didn't work.
1252 * The header is incomplete
1253 * and there isn't anything
1254 * we can do about it.
1260 /* Since we have to wait for
1261 * more from the server before
1262 * we can parse the headers
1263 * we just continue here.
1269 /* we have now received the entire header.
1270 * filter it and send the result to the client
1273 hdr = sed(server_patterns, add_server_headers, csp);
1276 /* write the server's (modified) header to
1277 * the client (along with anything else that
1278 * may be in the buffer)
1281 #ifdef FEATURE_KILL_POPUPS
1282 /* Start blocking popups if appropriate. */
1284 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1285 !http->ssl && /* We talk plaintext */
1286 block_popups) /* Policy allows */
1288 block_popups_now = 1;
1290 * Filter the part of the body that came in the same read
1291 * as the last headers:
1293 filter_popups(csp->iob->cur, csp);
1296 #endif /* def FEATURE_KILL_POPUPS */
1298 /* Buffer and pcrs filter this if appropriate. */
1300 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1301 !http->ssl && /* We talk plaintext */
1302 pcrs_filter) /* Policy allows */
1304 content_filter = pcrs_filter_response;
1307 /* Buffer and gif_deanimate this if appropriate. */
1309 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1310 !http->ssl && /* We talk plaintext */
1311 gif_deanimate) /* Policy allows */
1313 content_filter = gif_deanimate_response;
1318 * Only write if we're not buffering for content modification
1320 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1321 || (n = flush_socket(csp->cfd, csp) < 0)))
1323 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1325 /* the write failed, so don't bother
1326 * mentioning it to the client...
1327 * it probably can't hear us anyway.
1333 if(!content_filter) byte_count += n;
1335 /* we're finished with the server's header */
1340 /* If this was a MS IIS/5 hack then it means
1341 * the server has already closed the
1342 * connection. Nothing more to read. Time
1353 return; /* huh? we should never get here */
1356 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1357 csp->ip_addr_str, http->cmd, byte_count);
1361 /*********************************************************************
1365 * Description : This is little more than chat. We only "serve" to
1366 * to close any socket that chat may have opened.
1369 * 1 : csp = Current client state (buffers, headers, etc...)
1373 *********************************************************************/
1375 void serve(struct client_state *csp)
1376 #else /* ifndef AMIGA */
1377 static void serve(struct client_state *csp)
1378 #endif /* def AMIGA */
1381 close_socket(csp->cfd);
1385 close_socket(csp->sfd);
1388 csp->flags &= ~CSP_FLAG_ACTIVE;
1394 /*********************************************************************
1396 * Function : server_thread
1398 * Description : We only exist to call `serve' in a threaded environment.
1401 * 1 : data = Current client state (buffers, headers, etc...)
1403 * Returns : Always 0.
1405 *********************************************************************/
1406 static int32 server_thread(void *data)
1408 serve((struct client_state *) data);
1415 /*********************************************************************
1419 * Description : Load the config file and start the listen loop.
1420 * This function is a lot more *sane* with the `load_config'
1421 * and `listen_loop' functions; although it stills does
1422 * a *little* too much for my taste.
1425 * 1 : argc = Number of parameters (including $0).
1426 * 2 : argv = Array of (char *)'s to the parameters.
1428 * Returns : 1 if : can't open config file, unrecognized directive,
1429 * stats requested in multi-thread mode, can't open the
1430 * log file, can't open the jar file, listen port is invalid,
1431 * any load fails, and can't bind port.
1433 * Else main never returns, the process must be signaled
1434 * to terminate execution. Or, on Windows, use the
1435 * "File", "Exit" menu option.
1437 *********************************************************************/
1439 int real_main(int argc, const char *argv[])
1441 int main(int argc, const char *argv[])
1448 "AmiTCP:db/junkbuster/config"
1449 #elif !defined(_WIN32)
1456 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1457 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1459 printf("JunkBuster proxy version " VERSION ".\n\n"
1460 "Usage: %s [configfile]\n\n"
1461 "See " HOME_PAGE_URL " for details.\n"
1462 "This program is distributed under the GNU GPL, version 2 or later.\n",
1466 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1468 printf(VERSION "\n");
1472 if ((argc >= 2) && (strcmp(argv[1], "-d")==0))
1476 fprintf(stderr,"debugging enabled..\n");
1479 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1484 if (argc > argc_pos )
1486 configfile = argv[argc_pos];
1490 if ( *configfile != '/' )
1494 DBG(1, ("configfile before '%s'\n",configfile) );
1496 /* make config-filename absolute here */
1497 if ( !(basedir = getcwd( NULL, 1024 )))
1499 perror("get working dir failed");
1502 DBG(1, ("working dir '%s'\n",basedir) );
1503 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1505 perror("malloc failed");
1508 strcpy( abs_file, basedir );
1509 strcat( abs_file, "/" );
1510 strcat( abs_file, configfile );
1511 configfile = abs_file;
1512 DBG(1, ("configfile after '%s'\n",configfile) );
1514 #endif /* defined unix */
1521 #elif defined(_WIN32)
1526 #if !defined(_WIN32) && !defined(__OS2__)
1529 struct sigaction action;
1531 for ( sig = 1; sig < 16; sig++ )
1541 if ( signal(sig, SIG_handler) == SIG_ERR )
1542 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", sig);
1545 if ( signal(SIGPIPE, SIG_IGN) == SIG_ERR )
1546 log_error(LOG_LEVEL_FATAL, "Can't set SIG_IGN to SIGPIPE: %E");
1547 if ( signal(SIGCHLD, SIG_IGN) == SIG_ERR )
1548 log_error(LOG_LEVEL_FATAL, "Can't set SIG_IGN to SIGCHLD: %E");
1549 /* log file reload */
1550 if (!sigaction(SIGHUP,NULL,&action))
1552 action.sa_handler = &SIG_handler;
1553 action.sa_flags = SA_RESTART;
1555 if ( sigaction(SIGHUP,&action,NULL))
1556 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal SIGHUP: %E");
1560 perror("sigaction");
1561 log_error(LOG_LEVEL_FATAL, "Can't get sigaction data for signal SIGHUP");
1566 #else /* ifdef _WIN32 */
1567 # ifdef _WIN_CONSOLE
1569 * We *are* in a windows console app.
1570 * Print a verbose messages about FAQ's and such
1572 printf(win32_blurb);
1573 # endif /* def _WIN_CONSOLE */
1574 #endif /* def _WIN32 */
1577 /* Initialize the CGI subsystem */
1578 cgi_init_error_messages();
1588 * we make us a real daemon
1594 if ( pid < 0 ) /* error */
1599 else if ( pid != 0 ) /* parent */
1604 * must check for errors
1605 * child died due to missing files aso
1608 wpid = waitpid( pid, &status, WNOHANG );
1617 /* Should be more portable, but not as well tested */
1622 #else /* ndef __FreeBSD__ */
1624 #endif /* ndef __FreeBSD__ */
1625 fd = open("/dev/tty", O_RDONLY);
1628 /* no error check here */
1629 ioctl( fd, TIOCNOTTY,0 );
1633 /* should close stderr (fd 2) here too, but the test for existence
1634 ** and load config file is done in listen_loop() and puts
1635 ** some messages on stderr there.
1651 #endif /* defined unix */
1653 DBG(1, ("call listen_loop() \n") );
1662 /*********************************************************************
1664 * Function : listen_loop
1666 * Description : bind the listen port and enter a "FOREVER" listening loop.
1672 *********************************************************************/
1673 static void listen_loop(void)
1675 struct client_state *csp = NULL;
1677 struct configuration_spec * config;
1679 config = load_config();
1681 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1682 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1684 bfd = bind_port(config->haddr, config->hport);
1688 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1689 "- There may be another junkbuster or some other "
1690 "proxy running on port %d",
1691 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1692 config->hport, config->hport
1694 /* shouldn't get here */
1698 config->need_bind = 0;
1702 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1703 while (waitpid(-1, NULL, WNOHANG) > 0)
1705 /* zombie children */
1707 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1710 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1712 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1716 csp->flags |= CSP_FLAG_ACTIVE;
1719 csp->config = config = load_config();
1721 if ( config->need_bind )
1724 * Since we were listening to the "old port", we will not see
1725 * a "listen" param change until the next IJB request. So, at
1726 * least 1 more request must be made for us to find the new
1727 * setting. I am simply closing the old socket and binding the
1730 * Which-ever is correct, we will serve 1 more page via the
1731 * old settings. This should probably be a "show-proxy-args"
1732 * request. This should not be a so common of an operation
1733 * that this will hurt people's feelings.
1738 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1739 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1740 bfd = bind_port(config->haddr, config->hport);
1744 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1745 "- There may be another junkbuster or some other "
1746 "proxy running on port %d",
1747 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1748 config->hport, config->hport
1750 /* shouldn't get here */
1754 config->need_bind = 0;
1757 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1759 if (!accept_connection(csp, bfd))
1761 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1774 log_error(LOG_LEVEL_CONNECT, "OK");
1777 #ifdef FEATURE_TOGGLE
1780 csp->flags |= CSP_FLAG_TOGGLED_ON;
1782 #endif /* def FEATURE_TOGGLE */
1784 if (run_loader(csp))
1786 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1787 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1791 if (block_acl(NULL,csp))
1793 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1794 close_socket(csp->cfd);
1798 #endif /* def FEATURE_ACL */
1800 /* add it to the list of clients */
1801 csp->next = clients->next;
1802 clients->next = csp;
1804 if (config->multi_threaded)
1808 /* this is a switch () statment in the C preprocessor - ugh */
1809 #undef SELECTED_ONE_OPTION
1811 /* Use Pthreads in preference to native code */
1812 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1813 #define SELECTED_ONE_OPTION
1815 pthread_t the_thread;
1816 pthread_attr_t attrs;
1818 pthread_attr_init(&attrs);
1819 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1820 child_id = (pthread_create(&the_thread, &attrs,
1821 (void*)serve, csp) ? -1 : 0);
1822 pthread_attr_destroy(&attrs);
1826 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1827 #define SELECTED_ONE_OPTION
1828 child_id = _beginthread(
1834 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1835 #define SELECTED_ONE_OPTION
1836 child_id = _beginthread(
1843 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1844 #define SELECTED_ONE_OPTION
1846 thread_id tid = spawn_thread
1847 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1849 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1851 child_id = (int) tid;
1860 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1861 #define SELECTED_ONE_OPTION
1862 csp->cfd = ReleaseSocket(csp->cfd, -1);
1863 if((child_id = (int)CreateNewProcTags(
1864 NP_Entry, (ULONG)server_thread,
1865 NP_Output, Output(),
1866 NP_CloseOutput, FALSE,
1867 NP_Name, (ULONG)"junkbuster child",
1868 NP_StackSize, 200*1024,
1872 ((struct Task *)child_id)->tc_UserData = csp;
1873 Signal((struct Task *)child_id, SIGF_SINGLE);
1878 #if !defined(SELECTED_ONE_OPTION)
1881 /* This block is only needed when using fork().
1882 * When using threads, the server thread was
1883 * created and run by the call to _beginthread().
1885 if (child_id == 0) /* child */
1891 else if (child_id > 0) /* parent */
1893 /* in a fork()'d environment, the parent's
1894 * copy of the client socket and the CSP
1898 #if !defined(_WIN32) && defined(__CYGWIN__)
1900 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1901 close_socket(csp->cfd);
1902 csp->flags &= ~CSP_FLAG_ACTIVE;
1906 #undef SELECTED_ONE_OPTION
1907 /* end of cpp switch () */
1909 if (child_id < 0) /* failed */
1911 char buf[BUFFER_SIZE];
1913 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1915 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1917 write_socket(csp->cfd, buf, strlen(buf));
1918 close_socket(csp->cfd);
1919 csp->flags &= ~CSP_FLAG_ACTIVE;