1 const char jcc_rcs[] = "$Id: jcc.c,v 1.61 2002/01/17 21:01:52 jongfoster 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.61 2002/01/17 21:01:52 jongfoster
37 * Moving all our URL and URL pattern parsing code to urlmatch.c.
39 * Revision 1.60 2001/12/30 14:07:32 steudten
40 * - Add signal handling (unix)
41 * - Add SIGHUP handler (unix)
42 * - Add creation of pidfile (unix)
43 * - Add action 'top' in rc file (RH)
44 * - Add entry 'SIGNALS' to manpage
45 * - Add exit message to logfile (unix)
47 * Revision 1.59 2001/12/13 14:07:18 oes
48 * Fixed Bug: 503 error page now sent OK
50 * Revision 1.58 2001/11/30 23:37:24 jongfoster
51 * Renaming the Win32 config file to config.txt - this is almost the
52 * same as the corresponding UNIX name "config"
54 * Revision 1.57 2001/11/16 00:47:43 jongfoster
55 * Changing the tty-disconnection code to use setsid().
57 * Revision 1.56 2001/11/13 20:20:54 jongfoster
58 * Tabs->spaces, fixing a bug with missing {} around an if()
60 * Revision 1.55 2001/11/13 20:14:53 jongfoster
61 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
63 * Revision 1.54 2001/11/07 00:03:14 steudten
64 * Give reliable return value if an error
65 * occurs not just 0 with new daemon mode.
67 * Revision 1.53 2001/11/05 21:41:43 steudten
68 * Add changes to be a real daemon just for unix os.
69 * (change cwd to /, detach from controlling tty, set
70 * process group and session leader to the own process.
72 * Add some fatal-error log message for failed malloc().
73 * Add '-d' if compiled with 'configure --with-debug' to
74 * enable debug output.
76 * Revision 1.52 2001/10/26 20:11:20 jongfoster
77 * Fixing type mismatch
79 * Revision 1.51 2001/10/26 17:38:28 oes
82 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
83 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
84 * threads to call select() simultaneously. So, it's time to do a real, live,
85 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
86 * (native). Both versions will work, but using __OS2__ offers multi-threading.
88 * Revision 1.49 2001/10/23 21:41:35 jongfoster
89 * Added call to initialize the (statically-allocated of course)
90 * "out of memory" CGI response.
92 * Revision 1.48 2001/10/10 19:56:46 jongfoster
93 * Moving some code that wasn't cookie-related out of an #ifdef
96 * Revision 1.47 2001/10/10 16:44:36 oes
97 * Added CONNECT destination port limitation check
99 * Revision 1.46 2001/10/08 15:17:41 oes
100 * Re-enabled SSL forwarding
102 * Revision 1.45 2001/10/07 15:42:11 oes
103 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
105 * Moved downgrading of the HTTP version from parse_http_request to
106 * chat(), since we can't decide if it is necessary before we have
107 * determined the actions for the URL. The HTTP command is now
108 * *always* re-built so the repairs need no longer be special-cased.
110 * filter_popups now gets a csp pointer so it can raise the new
111 * CSP_FLAG_MODIFIED flag.
115 * Added configurable size limit for the IOB. If the IOB grows so
116 * large that the next read would exceed the limit, the header
117 * is generated, and the header & unfiltered buffer are flushed
118 * to the client. Chat then continues in non-buffering,
119 * non-filtering body mode.
121 * Revision 1.44 2001/10/02 18:13:57 oes
124 * Revision 1.43 2001/10/02 15:32:13 oes
125 * Moved generation of hdr
127 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
128 * Cleaning up 2 compiler warnings on OS/2.
130 * Revision 1.41 2001/09/16 17:05:14 jongfoster
131 * Removing unused #include showarg.h
133 * Revision 1.40 2001/09/16 15:41:45 jongfoster
134 * Fixing signed/unsigned comparison warning.
136 * Revision 1.39 2001/09/16 13:21:27 jongfoster
137 * Changes to use new list functions.
139 * Revision 1.38 2001/09/16 13:01:46 jongfoster
140 * Removing redundant function call that zeroed zalloc()'d memory.
142 * Revision 1.37 2001/09/10 11:12:24 oes
143 * Deleted unused variable
145 * Revision 1.36 2001/09/10 10:56:15 oes
146 * Silenced compiler warnings
148 * Revision 1.35 2001/07/31 14:44:22 oes
149 * Deleted unused size parameter from filter_popups()
151 * Revision 1.34 2001/07/30 22:08:36 jongfoster
152 * Tidying up #defines:
153 * - All feature #defines are now of the form FEATURE_xxx
154 * - Permanently turned off WIN_GUI_EDIT
155 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
157 * Revision 1.33 2001/07/29 19:32:00 jongfoster
158 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
160 * Revision 1.32 2001/07/29 18:47:05 jongfoster
161 * Adding missing #include "loadcfg.h"
163 * Revision 1.31 2001/07/29 12:17:48 oes
164 * Applied pthread fix by Paul Lieverse
166 * Revision 1.30 2001/07/25 22:57:13 jongfoster
167 * __BEOS__ no longer overrides FEATURE_PTHREAD.
168 * This is because FEATURE_PTHREAD will soon be widely used, so I
169 * want to keep it simple.
171 * Revision 1.29 2001/07/24 12:47:06 oes
172 * Applied BeOS support update by Eugenia
174 * Revision 1.28 2001/07/23 13:26:12 oes
175 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
177 * Revision 1.27 2001/07/19 19:09:47 haroon
178 * - Added code to take care of the situation where while processing the first
179 * server response (which includes the server header), after finding the end
180 * of the headers we were not looking past the end of the headers for
181 * content modification. I enabled it for filter_popups.
182 * Someone else should look to see if other similar operations should be
183 * done to the discarded portion of the buffer.
185 * Note 2001/07/20: No, the other content modification mechanisms will process
186 * the whole iob later anyway. --oes
188 * Revision 1.26 2001/07/18 12:31:36 oes
191 * Revision 1.25 2001/07/15 19:43:49 jongfoster
192 * Supports POSIX threads.
193 * Also removed some unused #includes.
195 * Revision 1.24 2001/07/13 14:00:40 oes
196 * - Generic content modification scheme:
197 * Each feature has its own applicability flag that is set
198 * from csp->action->flags.
199 * Replaced the "filtering" int flag , by a function pointer
200 * "content_filter" to the function that will do the content
201 * modification. If it is != NULL, the document will be buffered
202 * and processed through *content_filter, which must set
203 * csp->content_length and return a modified copy of the body
204 * or return NULL (on failiure).
205 * - Changed csp->is_text to the more generic bitmap csp->content_type
206 * which can currently take the valued CT_TEXT or CT_GIF
208 * - Removed all #ifdef PCRS
210 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
211 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
212 * the `block_acl' call. This prevents a compilation error when the user
213 * does not wish to use the "ACL" feature.
215 * Revision 1.22 2001/06/29 21:45:41 oes
216 * Indentation, CRLF->LF, Tab-> Space
218 * Revision 1.21 2001/06/29 13:29:36 oes
219 * - Cleaned up, improved comments
220 * - Unified all possible interceptors (CGI,
221 * block, trust, fast_redirect) in one
222 * place, with one (CGI) answer generation
223 * mechansim. Much clearer now.
224 * - Removed the GIF image generation, which
225 * is now done in filters.c:block_url()
226 * - Made error conditions like domain lookup
227 * failiure or (various) problems while talking
228 * to the server use cgi.c:error_response()
229 * instead of generating HTML/HTTP in chat() (yuck!)
230 * - Removed logentry from cancelled commit
232 * Revision 1.20 2001/06/09 10:55:28 jongfoster
233 * Changing BUFSIZ ==> BUFFER_SIZE
235 * Revision 1.19 2001/06/07 23:12:52 jongfoster
236 * Replacing function pointer in struct gateway with a directly
237 * called function forwarded_connect().
238 * Replacing struct gateway with struct forward_spec
240 * Revision 1.18 2001/06/03 19:12:16 oes
241 * introduced new cgi handling
243 * Revision 1.17 2001/06/01 20:07:23 jongfoster
244 * Now uses action +image-blocker{} rather than config->tinygif
246 * Revision 1.16 2001/06/01 18:49:17 jongfoster
247 * Replaced "list_share" with "list" - the tiny memory gain was not
248 * worth the extra complexity.
250 * Revision 1.15 2001/05/31 21:24:47 jongfoster
251 * Changed "permission" to "action" throughout.
252 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
253 * Moved vanilla wafer check into chat(), since we must now
254 * decide whether or not to add it based on the URL.
256 * Revision 1.14 2001/05/29 20:14:01 joergs
257 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
260 * Revision 1.13 2001/05/29 09:50:24 jongfoster
261 * Unified blocklist/imagelist/permissionslist.
262 * File format is still under discussion, but the internal changes
265 * Also modified interceptor behaviour:
266 * - We now intercept all URLs beginning with one of the following
267 * prefixes (and *only* these prefixes):
269 * * http://ijbswa.sf.net/config/
270 * * http://ijbswa.sourceforge.net/config/
271 * - New interceptors "home page" - go to http://i.j.b/ to see it.
272 * - Internal changes so that intercepted and fast redirect pages
273 * are not replaced with an image.
274 * - Interceptors now have the option to send a binary page direct
275 * to the client. (i.e. ijb-send-banner uses this)
276 * - Implemented show-url-info interceptor. (Which is why I needed
277 * the above interceptors changes - a typical URL is
278 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
279 * The previous mechanism would not have intercepted that, and
280 * if it had been intercepted then it then it would have replaced
283 * Revision 1.12 2001/05/27 22:17:04 oes
285 * - re_process_buffer no longer writes the modified buffer
286 * to the client, which was very ugly. It now returns the
287 * buffer, which it is then written by chat.
289 * - content_length now adjusts the Content-Length: header
290 * for modified documents rather than crunch()ing it.
291 * (Length info in csp->content_length, which is 0 for
292 * unmodified documents)
294 * - For this to work, sed() is called twice when filtering.
296 * Revision 1.11 2001/05/26 17:27:53 jongfoster
297 * Added support for CLF and fixed LOG_LEVEL_LOG.
298 * Also did CRLF->LF fix of my previous patch.
300 * Revision 1.10 2001/05/26 15:26:15 jongfoster
301 * ACL feature now provides more security by immediately dropping
302 * connections from untrusted hosts.
304 * Revision 1.9 2001/05/26 00:28:36 jongfoster
305 * Automatic reloading of config file.
306 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
307 * Most of the global variables have been moved to a new
308 * struct configuration_spec, accessed through csp->config->globalname
309 * Most of the globals remaining are used by the Win32 GUI.
311 * Revision 1.8 2001/05/25 22:43:18 jongfoster
312 * Fixing minor memory leak and buffer overflow.
314 * Revision 1.7 2001/05/25 22:34:30 jongfoster
317 * Revision 1.6 2001/05/23 00:13:58 joergs
318 * AmigaOS support fixed.
320 * Revision 1.5 2001/05/22 18:46:04 oes
322 * - Enabled filtering banners by size rather than URL
323 * by adding patterns that replace all standard banner
324 * sizes with the "Junkbuster" gif to the re_filterfile
326 * - Enabled filtering WebBugs by providing a pattern
327 * which kills all 1x1 images
329 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
330 * which is selected by the (nonstandard and therefore
331 * capital) letter 'U' in the option string.
332 * It causes the quantifiers to be ungreedy by default.
333 * Appending a ? turns back to greedy (!).
335 * - Added a new interceptor ijb-send-banner, which
336 * sends back the "Junkbuster" gif. Without imagelist or
337 * MSIE detection support, or if tinygif = 1, or the
338 * URL isn't recognized as an imageurl, a lame HTML
339 * explanation is sent instead.
341 * - Added new feature, which permits blocking remote
342 * script redirects and firing back a local redirect
344 * The feature is conditionally compiled, i.e. it
345 * can be disabled with --disable-fast-redirects,
346 * plus it must be activated by a "fast-redirects"
347 * line in the config file, has its own log level
348 * and of course wants to be displayed by show-proxy-args
349 * Note: Boy, all the #ifdefs in 1001 locations and
350 * all the fumbling with configure.in and acconfig.h
351 * were *way* more work than the feature itself :-(
353 * - Because a generic redirect template was needed for
354 * this, tinygif = 3 now uses the same.
356 * - Moved GIFs, and other static HTTP response templates
361 * - Removed some >400 CRs again (Jon, you really worked
364 * Revision 1.4 2001/05/21 19:34:01 jongfoster
365 * Made failure to bind() a fatal error.
367 * Revision 1.3 2001/05/20 01:21:20 jongfoster
368 * Version 2.9.4 checkin.
369 * - Merged popupfile and cookiefile, and added control over PCRS
370 * filtering, in new "permissionsfile".
371 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
372 * file error you now get a message box (in the Win32 GUI) rather
373 * than the program exiting with no explanation.
374 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
376 * - Removed tabs from "config"
377 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
378 * - Bumped up version number.
380 * Revision 1.2 2001/05/17 22:34:44 oes
381 * - Added hint on GIF char array generation to jcc.c
382 * - Cleaned CRLF's from the sources and related files
383 * - Repaired logging for REF and FRC
385 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
386 * Initial import of version 2.9.3 source tree
389 *********************************************************************/
395 #include <sys/types.h>
402 #ifdef FEATURE_PTHREAD
404 #endif /* def FEATURE_PTHREAD */
407 # ifndef FEATURE_PTHREAD
408 # include <windows.h>
409 # include <process.h>
410 # endif /* ndef FEATURE_PTHREAD */
413 # ifndef _WIN_CONSOLE
415 # endif /* ndef _WIN_CONSOLE */
417 #else /* ifndef _WIN32 */
419 # if !defined (__OS2__)
421 # include <sys/wait.h>
422 # endif /* ndef __OS2__ */
423 # include <sys/time.h>
424 # include <sys/stat.h>
425 # include <sys/ioctl.h>
428 #include <sys/termios.h>
434 # include <socket.h> /* BeOS has select() for sockets only. */
435 # include <OS.h> /* declarations for threads and stuff. */
438 # if defined(__EMX__) || defined(__OS2__)
439 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
444 #define bzero(B,N) memset(B,0x00,n)
463 #include "killpopup.h"
464 #include "miscutil.h"
466 #include "jbsockets.h"
471 #include "urlmatch.h"
473 const char jcc_h_rcs[] = JCC_H_VERSION;
474 const char project_h_rcs[] = PROJECT_H_VERSION;
476 struct client_state clients[1];
477 struct file_list files[1];
479 short int MustReload = 0;
481 #ifdef FEATURE_STATISTICS
482 int urls_read = 0; /* total nr of urls read inc rejected */
483 int urls_rejected = 0; /* total nr of urls rejected */
484 #endif /* def FEATURE_STATISTICS */
487 static void listen_loop(void);
488 static void chat(struct client_state *csp);
490 void serve(struct client_state *csp);
491 #else /* ifndef AMIGA */
492 static void serve(struct client_state *csp);
493 #endif /* def AMIGA */
496 static int32 server_thread(void *data);
497 #endif /* def __BEOS__ */
500 #define sleep(N) Sleep(((N) * 1000))
504 #define sleep(N) DosSleep(((N) * 100))
509 #endif /* defined unix */
511 /* The vanilla wafer. */
512 static const char VANILLA_WAFER[] =
513 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
514 "Do_not_send_me_any_copyrighted_information_other_than_the_"
515 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
516 "In_particular_do_not_send_me_any_cookies_that_"
517 "are_subject_to_a_claim_of_copyright_by_anybody._"
518 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
519 "(copyright_or_otherwise)_applying_to_any_cookie._";
522 #if !defined(_WIN32) && !defined(__OS2__)
523 /*********************************************************************
525 * Function : SIG_handler
527 * Description : Signal handler for different signals.
528 * see man kill, signal ..
531 * 1 : signal - the signal cause this function to call
535 *********************************************************************/
536 static void SIG_handler( int signal )
544 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", signal);
554 /* want to exit jb so use FATAL */
555 log_error(LOG_LEVEL_FATAL, "SIG_handler: receive signal %d without handler.", signal);
560 /*********************************************************************
564 * Description : Once a connection to the client has been accepted,
565 * this function is called (via serve()) to handle the
566 * main business of the communication. When this
567 * function returns, the caller must close the client
571 * 1 : csp = Current client state (buffers, headers, etc...)
573 * Returns : On success, the number of bytes written are returned (zero
574 * indicates nothing was written). On error, -1 is returned,
575 * and errno is set appropriately. If count is zero and the
576 * file descriptor refers to a regular file, 0 will be
577 * returned without causing any other effect. For a special
578 * file, the results are not portable.
580 *********************************************************************/
581 static void chat(struct client_state *csp)
584 * This next lines are a little ugly, but they simplifies the if statements
585 * below. Basically if TOGGLE, then we want the if to test if the
586 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
587 * then we want the if to test for CSP_FLAG_FORCED , else we don't
589 #ifdef FEATURE_TOGGLE
590 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
591 #else /* ifndef FEATURE_TOGGLE */
592 # define IS_TOGGLED_ON_AND
593 #endif /* ndef FEATURE_TOGGLE */
594 #ifdef FEATURE_FORCE_LOAD
595 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
596 #else /* ifndef FEATURE_FORCE_LOAD */
597 # define IS_NOT_FORCED_AND
598 #endif /* def FEATURE_FORCE_LOAD */
600 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
602 char buf[BUFFER_SIZE];
605 int n, maxfd, server_body;
606 int ms_iis5_hack = 0;
608 const struct forward_spec * fwd;
609 struct http_request *http;
610 #ifdef FEATURE_KILL_POPUPS
611 int block_popups; /* bool, 1==will block popups */
612 int block_popups_now = 0; /* bool, 1==currently blocking popups */
613 #endif /* def FEATURE_KILL_POPUPS */
615 int pcrs_filter; /* bool, 1==will filter through pcrs */
616 int gif_deanimate; /* bool, 1==will deanimate gifs */
618 /* Function that does the content filtering for the current request */
619 char *(*content_filter)() = NULL;
621 /* Skeleton for HTTP response, if we should intercept the request */
622 struct http_response *rsp;
627 * Read the client's request. Note that since we're not using select() we
628 * could get blocked here if a client connected, then didn't say anything!
633 n = read_socket(csp->cfd, buf, sizeof(buf));
635 if (n <= 0) break; /* error! */
637 add_to_iob(csp, buf, n);
639 req = get_header(csp);
643 break; /* no HTTP request! */
648 continue; /* more to come! */
651 #ifdef FEATURE_FORCE_LOAD
652 /* If this request contains the FORCE_PREFIX,
653 * better get rid of it now and set the force flag --oes
656 if (strstr(req, FORCE_PREFIX))
658 strclean(req, FORCE_PREFIX);
659 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
660 csp->flags |= CSP_FLAG_FORCED;
663 #endif /* def FEATURE_FORCE_LOAD */
665 parse_http_request(req, http, csp);
670 if (http->cmd == NULL)
672 strcpy(buf, CHEADER);
673 write_socket(csp->cfd, buf, strlen(buf));
675 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
680 /* decide how to route the HTTP request */
682 if ((fwd = forward_url(http, csp)) == NULL)
684 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
685 /* Never get here - LOG_LEVEL_FATAL causes program exit */
688 /* build the http request to send to the server
689 * we have to do one of the following:
691 * create = use the original HTTP request to create a new
692 * HTTP request that has either the path component
693 * without the http://domainspec (w/path) or the
694 * full orininal URL (w/url)
695 * Note that the path and/or the HTTP version may
696 * have been altered by now.
698 * connect = Open a socket to the host:port of the server
699 * and short-circuit server and client socket.
701 * pass = Pass the request unchanged if forwarding a CONNECT
702 * request to a parent proxy. Note that we'll be sending
703 * the CFAIL message ourselves if connecting to the parent
704 * fails, but we won't send a CSUCCEED message if it works,
705 * since that would result in a double message (ours and the
706 * parent's). After sending the request to the parent, we simply
712 * +--------+--------+
714 * 0 | create | connect|
716 * Forwarding +--------+--------+
718 * 1 | create | pass |
720 * +--------+--------+
725 * Determine the actions for this URL
727 #ifdef FEATURE_TOGGLE
728 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
730 /* Most compatible set of actions (i.e. none) */
731 init_current_action(csp->action);
734 #endif /* ndef FEATURE_TOGGLE */
736 url_actions(http, csp);
741 * Check if a CONNECT request is allowable:
742 * In the absence of a +limit-connect action, allow only port 443.
743 * If there is an action, allow whatever matches the specificaton.
747 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
748 || (csp->action->flags & ACTION_LIMIT_CONNECT
749 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
751 strcpy(buf, CFORBIDDEN);
752 write_socket(csp->cfd, buf, strlen(buf));
754 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
755 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
763 * Downgrade http version from 1.1 to 1.0 if +downgrade
766 if ( (http->ssl == 0)
767 && (!strcmpic(http->ver, "HTTP/1.1"))
768 && (csp->action->flags & ACTION_DOWNGRADE))
771 http->ver = strdup("HTTP/1.0");
773 if (http->ver == NULL)
775 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
780 * (Re)build the HTTP request for non-SSL requests.
781 * If forwarding, use the whole URL, else, use only the path.
787 http->cmd = strdup(http->gpc);
788 string_append(&http->cmd, " ");
790 if (fwd->forward_host)
792 string_append(&http->cmd, http->url);
796 string_append(&http->cmd, http->path);
799 string_append(&http->cmd, " ");
800 string_append(&http->cmd, http->ver);
802 if (http->cmd == NULL)
804 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
807 enlist(csp->headers, http->cmd);
810 #ifdef FEATURE_COOKIE_JAR
812 * If we're logging cookies in a cookie jar, and the user has not
813 * supplied any wafers, and the user has not told us to suppress the
814 * vanilla wafer, then send the vanilla wafer.
816 if ((csp->config->jarfile != NULL)
817 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
818 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
820 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
822 #endif /* def FEATURE_COOKIE_JAR */
825 #ifdef FEATURE_KILL_POPUPS
826 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
827 #endif /* def FEATURE_KILL_POPUPS */
829 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
830 ((csp->action->flags & ACTION_FILTER) != 0);
832 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
834 /* grab the rest of the client's headers */
838 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
840 n = read_socket(csp->cfd, buf, sizeof(buf));
843 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
846 add_to_iob(csp, buf, n);
850 if (p == NULL) break;
852 enlist(csp->headers, p);
856 * We have a request. Now, check to see if we need to
857 * intercept it, i.e. If ..
861 /* a CGI call was detected and answered */
862 (NULL != (rsp = dispatch_cgi(csp)))
864 /* or we are enabled and... */
867 /* ..the request was blocked */
868 ( NULL != (rsp = block_url(csp)))
872 || ( NULL != (rsp = trust_url(csp)))
873 #endif /* def FEATURE_TRUST */
875 /* ..or a fast redirect kicked in */
876 #ifdef FEATURE_FAST_REDIRECTS
877 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
878 (NULL != (rsp = redirect_url(csp))))
879 #endif /* def FEATURE_FAST_REDIRECTS */
883 /* Write the answer to the client */
884 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
885 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
887 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
890 #ifdef FEATURE_STATISTICS
891 /* Count as a rejected request */
892 csp->flags |= CSP_FLAG_REJECTED;
893 #endif /* def FEATURE_STATISTICS */
895 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
896 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
897 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
899 /* Clean up and return */
900 free_http_response(rsp);
904 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
906 if (fwd->forward_host)
908 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
909 fwd->forward_host, fwd->forward_port, http->hostport);
913 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
916 /* here we connect to the server, gateway, or the forwarder */
918 csp->sfd = forwarded_connect(fwd, http, csp);
922 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
927 rsp = error_response(csp, "no-such-domain", errno);
929 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
930 csp->ip_addr_str, http->cmd);
934 rsp = error_response(csp, "connect-failed", errno);
936 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
937 csp->ip_addr_str, http->cmd);
941 /* Write the answer to the client */
944 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
945 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
947 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
951 free_http_response(rsp);
955 log_error(LOG_LEVEL_CONNECT, "OK");
957 hdr = sed(client_patterns, add_client_headers, csp);
960 /* FIXME Should handle error properly */
\r
961 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
\r
964 list_remove_all(csp->headers);
966 if (fwd->forward_host || (http->ssl == 0))
968 /* write the client's (modified) header to the server
969 * (along with anything else that may be in the buffer)
974 if ((write_socket(csp->sfd, hdr, n) != n)
975 || (flush_socket(csp->sfd, csp ) < 0))
977 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
980 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
981 csp->ip_addr_str, http->cmd);
983 rsp = error_response(csp, "connect-failed", errno);
987 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
988 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
990 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
994 free_http_response(rsp);
1002 * We're running an SSL tunnel and we're not forwarding,
1003 * so just send the "connect succeeded" message to the
1004 * client, flush the rest, and get out of the way.
1006 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1007 csp->ip_addr_str, http->cmd);
1009 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
1017 /* we're finished with the client's header */
1020 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1022 /* pass data between the client and server
1023 * until one or the other shuts down the connection.
1032 FD_SET(csp->cfd, &rfds);
1033 FD_SET(csp->sfd, &rfds);
1035 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1039 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1043 /* this is the body of the browser's request
1044 * just read it and write it.
1047 if (FD_ISSET(csp->cfd, &rfds))
1049 n = read_socket(csp->cfd, buf, sizeof(buf));
1053 break; /* "game over, man" */
1056 if (write_socket(csp->sfd, buf, n) != n)
1058 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1065 * The server wants to talk. It could be the header or the body.
1066 * If `hdr' is null, then it's the header otherwise it's the body.
1067 * FIXME: Does `hdr' really mean `host'? No.
1071 if (FD_ISSET(csp->sfd, &rfds))
1074 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1078 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1080 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1081 csp->ip_addr_str, http->cmd);
1083 rsp = error_response(csp, "connect-failed", errno);
1087 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1088 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1090 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1094 free_http_response(rsp);
1098 /* Add a trailing zero. This lets filter_popups
1099 * use string operations.
1103 #ifdef FEATURE_KILL_POPUPS
1104 /* Filter the popups on this read. */
1105 if (block_popups_now)
1107 filter_popups(buf, csp);
1109 #endif /* def FEATURE_KILL_POPUPS */
1111 /* Normally, this would indicate that we've read
1112 * as much as the server has sent us and we can
1113 * close the client connection. However, Microsoft
1114 * in its wisdom has released IIS/5 with a bug that
1115 * prevents it from sending the trailing \r\n in
1116 * a 302 redirect header (and possibly other headers).
1117 * To work around this if we've haven't parsed
1118 * a full header we'll append a trailing \r\n
1119 * and see if this now generates a valid one.
1121 * This hack shouldn't have any impacts. If we've
1122 * already transmitted the header or if this is a
1123 * SSL connection, then we won't bother with this
1124 * hack. So we only work on partially received
1125 * headers. If we append a \r\n and this still
1126 * doesn't generate a valid header, then we won't
1127 * transmit anything to the client.
1132 if (server_body || http->ssl)
1135 * If we have been buffering up the document,
1136 * now is the time to apply content modification
1137 * and send the result to the client.
1142 * If the content filter fails, use the original
1143 * buffer and length.
1144 * (see p != NULL ? p : csp->iob->cur below)
1146 if (NULL == (p = (*content_filter)(csp)))
1148 csp->content_length = csp->iob->eod - csp->iob->cur;
1151 hdr = sed(server_patterns, add_server_headers, csp);
1154 /* FIXME Should handle error properly */
\r
1155 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
\r
1160 if ((write_socket(csp->cfd, hdr, n) != n)
1161 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1163 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1173 break; /* "game over, man" */
1177 * This is NOT the body, so
1178 * Let's pretend the server just sent us a blank line.
1180 n = sprintf(buf, "\r\n");
1183 * Now, let the normal header parsing algorithm below do its
1184 * job. If it fails, we'll exit instead of continuing.
1191 * If this is an SSL connection or we're in the body
1192 * of the server document, just write it to the client,
1193 * unless we need to buffer the body for later content-filtering
1196 if (server_body || http->ssl)
1200 add_to_iob(csp, buf, n);
1203 * If the buffer limit will be reached on the next read,
1204 * switch to non-filtering mode, i.e. make & write the
1205 * header, flush the socket and get out of the way.
1207 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1209 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1211 hdr = sed(server_patterns, add_server_headers, csp);
1214 /* FIXME Should handle error properly */
\r
1215 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
\r
1221 if (((write_socket(csp->cfd, hdr, n) != n)
1222 || (n = flush_socket(csp->cfd, csp) < 0)))
1224 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1233 content_filter = NULL;
1240 if (write_socket(csp->cfd, buf, n) != n)
1242 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1251 /* we're still looking for the end of the
1252 * server's header ... (does that make header
1253 * parsing an "out of body experience" ?
1256 /* buffer up the data we just read */
1257 add_to_iob(csp, buf, n);
1259 /* get header lines from the iob */
1261 while ((p = get_header(csp)))
1265 /* see following note */
1268 enlist(csp->headers, p);
1272 /* NOTE: there are no "empty" headers so
1273 * if the pointer `p' is not NULL we must
1274 * assume that we reached the end of the
1275 * buffer before we hit the end of the header.
1282 /* Well, we tried our MS IIS/5
1283 * hack and it didn't work.
1284 * The header is incomplete
1285 * and there isn't anything
1286 * we can do about it.
1292 /* Since we have to wait for
1293 * more from the server before
1294 * we can parse the headers
1295 * we just continue here.
1301 /* we have now received the entire header.
1302 * filter it and send the result to the client
1305 hdr = sed(server_patterns, add_server_headers, csp);
1308 /* FIXME Should handle error properly */
\r
1309 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
\r
1314 /* write the server's (modified) header to
1315 * the client (along with anything else that
1316 * may be in the buffer)
1319 #ifdef FEATURE_KILL_POPUPS
1320 /* Start blocking popups if appropriate. */
1322 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1323 !http->ssl && /* We talk plaintext */
1324 block_popups) /* Policy allows */
1326 block_popups_now = 1;
1328 * Filter the part of the body that came in the same read
1329 * as the last headers:
1331 filter_popups(csp->iob->cur, csp);
1334 #endif /* def FEATURE_KILL_POPUPS */
1336 /* Buffer and pcrs filter this if appropriate. */
1338 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1339 !http->ssl && /* We talk plaintext */
1340 pcrs_filter) /* Policy allows */
1342 content_filter = pcrs_filter_response;
1345 /* Buffer and gif_deanimate this if appropriate. */
1347 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1348 !http->ssl && /* We talk plaintext */
1349 gif_deanimate) /* Policy allows */
1351 content_filter = gif_deanimate_response;
1356 * Only write if we're not buffering for content modification
1358 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1359 || (n = flush_socket(csp->cfd, csp) < 0)))
1361 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1363 /* the write failed, so don't bother
1364 * mentioning it to the client...
1365 * it probably can't hear us anyway.
1371 if(!content_filter) byte_count += n;
1373 /* we're finished with the server's header */
1378 /* If this was a MS IIS/5 hack then it means
1379 * the server has already closed the
1380 * connection. Nothing more to read. Time
1391 return; /* huh? we should never get here */
1394 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1395 csp->ip_addr_str, http->cmd, byte_count);
1399 /*********************************************************************
1403 * Description : This is little more than chat. We only "serve" to
1404 * to close any socket that chat may have opened.
1407 * 1 : csp = Current client state (buffers, headers, etc...)
1411 *********************************************************************/
1413 void serve(struct client_state *csp)
1414 #else /* ifndef AMIGA */
1415 static void serve(struct client_state *csp)
1416 #endif /* def AMIGA */
1419 close_socket(csp->cfd);
1423 close_socket(csp->sfd);
1426 csp->flags &= ~CSP_FLAG_ACTIVE;
1432 /*********************************************************************
1434 * Function : server_thread
1436 * Description : We only exist to call `serve' in a threaded environment.
1439 * 1 : data = Current client state (buffers, headers, etc...)
1441 * Returns : Always 0.
1443 *********************************************************************/
1444 static int32 server_thread(void *data)
1446 serve((struct client_state *) data);
1453 /*********************************************************************
1457 * Description : Load the config file and start the listen loop.
1458 * This function is a lot more *sane* with the `load_config'
1459 * and `listen_loop' functions; although it stills does
1460 * a *little* too much for my taste.
1463 * 1 : argc = Number of parameters (including $0).
1464 * 2 : argv = Array of (char *)'s to the parameters.
1466 * Returns : 1 if : can't open config file, unrecognized directive,
1467 * stats requested in multi-thread mode, can't open the
1468 * log file, can't open the jar file, listen port is invalid,
1469 * any load fails, and can't bind port.
1471 * Else main never returns, the process must be signaled
1472 * to terminate execution. Or, on Windows, use the
1473 * "File", "Exit" menu option.
1475 *********************************************************************/
1477 int real_main(int argc, const char *argv[])
1479 int main(int argc, const char *argv[])
1486 "AmiTCP:db/junkbuster/config"
1487 #elif !defined(_WIN32)
1494 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1495 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1497 printf("JunkBuster proxy version " VERSION ".\n\n"
1498 "Usage: %s [configfile]\n\n"
1499 "See " HOME_PAGE_URL " for details.\n"
1500 "This program is distributed under the GNU GPL, version 2 or later.\n",
1504 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1506 printf(VERSION "\n");
1510 if ((argc >= 2) && (strcmp(argv[1], "-d")==0))
1514 fprintf(stderr,"debugging enabled..\n");
1517 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1522 if (argc > argc_pos )
1524 configfile = argv[argc_pos];
1528 if ( *configfile != '/' )
1532 DBG(1, ("configfile before '%s'\n",configfile) );
1534 /* make config-filename absolute here */
1535 if ( !(basedir = getcwd( NULL, 1024 )))
1537 perror("get working dir failed");
1540 DBG(1, ("working dir '%s'\n",basedir) );
1541 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1543 perror("malloc failed");
1546 strcpy( abs_file, basedir );
1547 strcat( abs_file, "/" );
1548 strcat( abs_file, configfile );
1549 configfile = abs_file;
1550 DBG(1, ("configfile after '%s'\n",configfile) );
1552 #endif /* defined unix */
1559 #elif defined(_WIN32)
1564 #if !defined(_WIN32) && !defined(__OS2__)
1567 struct sigaction action;
1569 for ( sig = 1; sig < 16; sig++ )
1579 if ( signal(sig, SIG_handler) == SIG_ERR )
1580 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", sig);
1583 if ( signal(SIGPIPE, SIG_IGN) == SIG_ERR )
1584 log_error(LOG_LEVEL_FATAL, "Can't set SIG_IGN to SIGPIPE: %E");
1585 if ( signal(SIGCHLD, SIG_IGN) == SIG_ERR )
1586 log_error(LOG_LEVEL_FATAL, "Can't set SIG_IGN to SIGCHLD: %E");
1587 /* log file reload */
1588 if (!sigaction(SIGHUP,NULL,&action))
1590 action.sa_handler = &SIG_handler;
1591 action.sa_flags = SA_RESTART;
1593 if ( sigaction(SIGHUP,&action,NULL))
1594 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal SIGHUP: %E");
1598 perror("sigaction");
1599 log_error(LOG_LEVEL_FATAL, "Can't get sigaction data for signal SIGHUP");
1604 #else /* ifdef _WIN32 */
1605 # ifdef _WIN_CONSOLE
1607 * We *are* in a windows console app.
1608 * Print a verbose messages about FAQ's and such
1610 printf(win32_blurb);
1611 # endif /* def _WIN_CONSOLE */
1612 #endif /* def _WIN32 */
1615 /* Initialize the CGI subsystem */
1616 cgi_init_error_messages();
1626 * we make us a real daemon
1632 if ( pid < 0 ) /* error */
1637 else if ( pid != 0 ) /* parent */
1642 * must check for errors
1643 * child died due to missing files aso
1646 wpid = waitpid( pid, &status, WNOHANG );
1655 /* Should be more portable, but not as well tested */
1660 #else /* ndef __FreeBSD__ */
1662 #endif /* ndef __FreeBSD__ */
1663 fd = open("/dev/tty", O_RDONLY);
1666 /* no error check here */
1667 ioctl( fd, TIOCNOTTY,0 );
1671 /* should close stderr (fd 2) here too, but the test for existence
1672 ** and load config file is done in listen_loop() and puts
1673 ** some messages on stderr there.
1689 #endif /* defined unix */
1691 DBG(1, ("call listen_loop() \n") );
1700 /*********************************************************************
1702 * Function : listen_loop
1704 * Description : bind the listen port and enter a "FOREVER" listening loop.
1710 *********************************************************************/
1711 static void listen_loop(void)
1713 struct client_state *csp = NULL;
1715 struct configuration_spec * config;
1717 config = load_config();
1719 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1720 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1722 bfd = bind_port(config->haddr, config->hport);
1726 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1727 "- There may be another junkbuster or some other "
1728 "proxy running on port %d",
1729 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1730 config->hport, config->hport
1732 /* shouldn't get here */
1736 config->need_bind = 0;
1740 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1741 while (waitpid(-1, NULL, WNOHANG) > 0)
1743 /* zombie children */
1745 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1748 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1750 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1754 csp->flags |= CSP_FLAG_ACTIVE;
1757 csp->config = config = load_config();
1759 if ( config->need_bind )
1762 * Since we were listening to the "old port", we will not see
1763 * a "listen" param change until the next IJB request. So, at
1764 * least 1 more request must be made for us to find the new
1765 * setting. I am simply closing the old socket and binding the
1768 * Which-ever is correct, we will serve 1 more page via the
1769 * old settings. This should probably be a "show-proxy-args"
1770 * request. This should not be a so common of an operation
1771 * that this will hurt people's feelings.
1776 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1777 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1778 bfd = bind_port(config->haddr, config->hport);
1782 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1783 "- There may be another junkbuster or some other "
1784 "proxy running on port %d",
1785 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1786 config->hport, config->hport
1788 /* shouldn't get here */
1792 config->need_bind = 0;
1795 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1797 if (!accept_connection(csp, bfd))
1799 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1812 log_error(LOG_LEVEL_CONNECT, "OK");
1815 #ifdef FEATURE_TOGGLE
1818 csp->flags |= CSP_FLAG_TOGGLED_ON;
1820 #endif /* def FEATURE_TOGGLE */
1822 if (run_loader(csp))
1824 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1825 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1829 if (block_acl(NULL,csp))
1831 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1832 close_socket(csp->cfd);
1836 #endif /* def FEATURE_ACL */
1838 /* add it to the list of clients */
1839 csp->next = clients->next;
1840 clients->next = csp;
1842 if (config->multi_threaded)
1846 /* this is a switch () statment in the C preprocessor - ugh */
1847 #undef SELECTED_ONE_OPTION
1849 /* Use Pthreads in preference to native code */
1850 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1851 #define SELECTED_ONE_OPTION
1853 pthread_t the_thread;
1854 pthread_attr_t attrs;
1856 pthread_attr_init(&attrs);
1857 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1858 child_id = (pthread_create(&the_thread, &attrs,
1859 (void*)serve, csp) ? -1 : 0);
1860 pthread_attr_destroy(&attrs);
1864 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1865 #define SELECTED_ONE_OPTION
1866 child_id = _beginthread(
1872 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1873 #define SELECTED_ONE_OPTION
1874 child_id = _beginthread(
1881 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1882 #define SELECTED_ONE_OPTION
1884 thread_id tid = spawn_thread
1885 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1887 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1889 child_id = (int) tid;
1898 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1899 #define SELECTED_ONE_OPTION
1900 csp->cfd = ReleaseSocket(csp->cfd, -1);
1901 if((child_id = (int)CreateNewProcTags(
1902 NP_Entry, (ULONG)server_thread,
1903 NP_Output, Output(),
1904 NP_CloseOutput, FALSE,
1905 NP_Name, (ULONG)"junkbuster child",
1906 NP_StackSize, 200*1024,
1910 ((struct Task *)child_id)->tc_UserData = csp;
1911 Signal((struct Task *)child_id, SIGF_SINGLE);
1916 #if !defined(SELECTED_ONE_OPTION)
1919 /* This block is only needed when using fork().
1920 * When using threads, the server thread was
1921 * created and run by the call to _beginthread().
1923 if (child_id == 0) /* child */
1929 else if (child_id > 0) /* parent */
1931 /* in a fork()'d environment, the parent's
1932 * copy of the client socket and the CSP
1936 #if !defined(_WIN32) && defined(__CYGWIN__)
1938 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1939 close_socket(csp->cfd);
1940 csp->flags &= ~CSP_FLAG_ACTIVE;
1944 #undef SELECTED_ONE_OPTION
1945 /* end of cpp switch () */
1947 if (child_id < 0) /* failed */
1949 char buf[BUFFER_SIZE];
1951 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1953 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1955 write_socket(csp->cfd, buf, strlen(buf));
1956 close_socket(csp->cfd);
1957 csp->flags &= ~CSP_FLAG_ACTIVE;