1 const char jcc_rcs[] = "$Id: jcc.c,v 1.75 2002/03/06 10:02:19 oes Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001 the SourceForge
10 * IJBSWA team. http://ijbswa.sourceforge.net
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
36 * Revision 1.75 2002/03/06 10:02:19 oes
37 * Fixed stupid bug when --user was not given
39 * Revision 1.74 2002/03/06 00:49:31 jongfoster
40 * Fixing warning on Windows
41 * Making #ifdefs that refer to the same variable consistently
42 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
44 * Revision 1.73 2002/03/05 23:57:30 hal9
45 * Stray character 's' on line 1618 was breaking build.
47 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
48 * - Re-enable OS/2 building after new parms were added
49 * - Fix false out of memory report when resolving CGI templates when no IP
50 * address is available of failed attempt (a la no such domain)
52 * Revision 1.71 2002/03/05 18:13:56 oes
55 * Revision 1.70 2002/03/05 04:52:42 oes
56 * Deleted non-errlog debugging code
58 * Revision 1.69 2002/03/04 23:50:00 jongfoster
59 * Splitting off bind_port() call into bind_port_helper(), with
62 * Revision 1.68 2002/03/04 20:17:32 oes
65 * Revision 1.67 2002/03/04 18:18:57 oes
66 * - Removed _DEBUG mode
67 * - Cleand up cmdline parsing
68 * - Introduced --no-daemon, --pidfile options
69 * - Cleaned up signal handling:
70 * - Terminate cleanly on INT, TERM and ABRT
71 * - Schedule logfile for re-opening on HUP
72 * - Ignore CHLD and PIPE
73 * - Leave the rest with their default handlers
74 * - Uniform handler registration
75 * - Added usage() function
76 * - Played styleguide police
78 * Revision 1.66 2002/03/03 15:06:55 oes
79 * Re-enabled automatic config reloading
81 * Revision 1.65 2002/03/03 14:49:11 oes
82 * Fixed CLF logging: Now uses client's original HTTP request
84 * Revision 1.64 2002/03/03 09:18:03 joergs
85 * Made jumbjuster work on AmigaOS again.
87 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
88 * Clean up a little CRLF unpleasantness that suddenly appeared
90 * Revision 1.62 2002/02/20 23:17:23 jongfoster
91 * Detecting some out-of memory conditions and exiting with a log message.
93 * Revision 1.61 2002/01/17 21:01:52 jongfoster
94 * Moving all our URL and URL pattern parsing code to urlmatch.c.
96 * Revision 1.60 2001/12/30 14:07:32 steudten
97 * - Add signal handling (unix)
98 * - Add SIGHUP handler (unix)
99 * - Add creation of pidfile (unix)
100 * - Add action 'top' in rc file (RH)
101 * - Add entry 'SIGNALS' to manpage
102 * - Add exit message to logfile (unix)
104 * Revision 1.59 2001/12/13 14:07:18 oes
105 * Fixed Bug: 503 error page now sent OK
107 * Revision 1.58 2001/11/30 23:37:24 jongfoster
108 * Renaming the Win32 config file to config.txt - this is almost the
109 * same as the corresponding UNIX name "config"
111 * Revision 1.57 2001/11/16 00:47:43 jongfoster
112 * Changing the tty-disconnection code to use setsid().
114 * Revision 1.56 2001/11/13 20:20:54 jongfoster
115 * Tabs->spaces, fixing a bug with missing {} around an if()
117 * Revision 1.55 2001/11/13 20:14:53 jongfoster
118 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
120 * Revision 1.54 2001/11/07 00:03:14 steudten
121 * Give reliable return value if an error
122 * occurs not just 0 with new daemon mode.
124 * Revision 1.53 2001/11/05 21:41:43 steudten
125 * Add changes to be a real daemon just for unix os.
126 * (change cwd to /, detach from controlling tty, set
127 * process group and session leader to the own process.
129 * Add some fatal-error log message for failed malloc().
130 * Add '-d' if compiled with 'configure --with-debug' to
131 * enable debug output.
133 * Revision 1.52 2001/10/26 20:11:20 jongfoster
134 * Fixing type mismatch
136 * Revision 1.51 2001/10/26 17:38:28 oes
139 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
140 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
141 * threads to call select() simultaneously. So, it's time to do a real, live,
142 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
143 * (native). Both versions will work, but using __OS2__ offers multi-threading.
145 * Revision 1.49 2001/10/23 21:41:35 jongfoster
146 * Added call to initialize the (statically-allocated of course)
147 * "out of memory" CGI response.
149 * Revision 1.48 2001/10/10 19:56:46 jongfoster
150 * Moving some code that wasn't cookie-related out of an #ifdef
153 * Revision 1.47 2001/10/10 16:44:36 oes
154 * Added CONNECT destination port limitation check
156 * Revision 1.46 2001/10/08 15:17:41 oes
157 * Re-enabled SSL forwarding
159 * Revision 1.45 2001/10/07 15:42:11 oes
160 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
162 * Moved downgrading of the HTTP version from parse_http_request to
163 * chat(), since we can't decide if it is necessary before we have
164 * determined the actions for the URL. The HTTP command is now
165 * *always* re-built so the repairs need no longer be special-cased.
167 * filter_popups now gets a csp pointer so it can raise the new
168 * CSP_FLAG_MODIFIED flag.
172 * Added configurable size limit for the IOB. If the IOB grows so
173 * large that the next read would exceed the limit, the header
174 * is generated, and the header & unfiltered buffer are flushed
175 * to the client. Chat then continues in non-buffering,
176 * non-filtering body mode.
178 * Revision 1.44 2001/10/02 18:13:57 oes
181 * Revision 1.43 2001/10/02 15:32:13 oes
182 * Moved generation of hdr
184 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
185 * Cleaning up 2 compiler warnings on OS/2.
187 * Revision 1.41 2001/09/16 17:05:14 jongfoster
188 * Removing unused #include showarg.h
190 * Revision 1.40 2001/09/16 15:41:45 jongfoster
191 * Fixing signed/unsigned comparison warning.
193 * Revision 1.39 2001/09/16 13:21:27 jongfoster
194 * Changes to use new list functions.
196 * Revision 1.38 2001/09/16 13:01:46 jongfoster
197 * Removing redundant function call that zeroed zalloc()'d memory.
199 * Revision 1.37 2001/09/10 11:12:24 oes
200 * Deleted unused variable
202 * Revision 1.36 2001/09/10 10:56:15 oes
203 * Silenced compiler warnings
205 * Revision 1.35 2001/07/31 14:44:22 oes
206 * Deleted unused size parameter from filter_popups()
208 * Revision 1.34 2001/07/30 22:08:36 jongfoster
209 * Tidying up #defines:
210 * - All feature #defines are now of the form FEATURE_xxx
211 * - Permanently turned off WIN_GUI_EDIT
212 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
214 * Revision 1.33 2001/07/29 19:32:00 jongfoster
215 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
217 * Revision 1.32 2001/07/29 18:47:05 jongfoster
218 * Adding missing #include "loadcfg.h"
220 * Revision 1.31 2001/07/29 12:17:48 oes
221 * Applied pthread fix by Paul Lieverse
223 * Revision 1.30 2001/07/25 22:57:13 jongfoster
224 * __BEOS__ no longer overrides FEATURE_PTHREAD.
225 * This is because FEATURE_PTHREAD will soon be widely used, so I
226 * want to keep it simple.
228 * Revision 1.29 2001/07/24 12:47:06 oes
229 * Applied BeOS support update by Eugenia
231 * Revision 1.28 2001/07/23 13:26:12 oes
232 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
234 * Revision 1.27 2001/07/19 19:09:47 haroon
235 * - Added code to take care of the situation where while processing the first
236 * server response (which includes the server header), after finding the end
237 * of the headers we were not looking past the end of the headers for
238 * content modification. I enabled it for filter_popups.
239 * Someone else should look to see if other similar operations should be
240 * done to the discarded portion of the buffer.
242 * Note 2001/07/20: No, the other content modification mechanisms will process
243 * the whole iob later anyway. --oes
245 * Revision 1.26 2001/07/18 12:31:36 oes
248 * Revision 1.25 2001/07/15 19:43:49 jongfoster
249 * Supports POSIX threads.
250 * Also removed some unused #includes.
252 * Revision 1.24 2001/07/13 14:00:40 oes
253 * - Generic content modification scheme:
254 * Each feature has its own applicability flag that is set
255 * from csp->action->flags.
256 * Replaced the "filtering" int flag , by a function pointer
257 * "content_filter" to the function that will do the content
258 * modification. If it is != NULL, the document will be buffered
259 * and processed through *content_filter, which must set
260 * csp->content_length and return a modified copy of the body
261 * or return NULL (on failiure).
262 * - Changed csp->is_text to the more generic bitmap csp->content_type
263 * which can currently take the valued CT_TEXT or CT_GIF
265 * - Removed all #ifdef PCRS
267 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
268 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
269 * the `block_acl' call. This prevents a compilation error when the user
270 * does not wish to use the "ACL" feature.
272 * Revision 1.22 2001/06/29 21:45:41 oes
273 * Indentation, CRLF->LF, Tab-> Space
275 * Revision 1.21 2001/06/29 13:29:36 oes
276 * - Cleaned up, improved comments
277 * - Unified all possible interceptors (CGI,
278 * block, trust, fast_redirect) in one
279 * place, with one (CGI) answer generation
280 * mechansim. Much clearer now.
281 * - Removed the GIF image generation, which
282 * is now done in filters.c:block_url()
283 * - Made error conditions like domain lookup
284 * failiure or (various) problems while talking
285 * to the server use cgi.c:error_response()
286 * instead of generating HTML/HTTP in chat() (yuck!)
287 * - Removed logentry from cancelled commit
289 * Revision 1.20 2001/06/09 10:55:28 jongfoster
290 * Changing BUFSIZ ==> BUFFER_SIZE
292 * Revision 1.19 2001/06/07 23:12:52 jongfoster
293 * Replacing function pointer in struct gateway with a directly
294 * called function forwarded_connect().
295 * Replacing struct gateway with struct forward_spec
297 * Revision 1.18 2001/06/03 19:12:16 oes
298 * introduced new cgi handling
300 * Revision 1.17 2001/06/01 20:07:23 jongfoster
301 * Now uses action +image-blocker{} rather than config->tinygif
303 * Revision 1.16 2001/06/01 18:49:17 jongfoster
304 * Replaced "list_share" with "list" - the tiny memory gain was not
305 * worth the extra complexity.
307 * Revision 1.15 2001/05/31 21:24:47 jongfoster
308 * Changed "permission" to "action" throughout.
309 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
310 * Moved vanilla wafer check into chat(), since we must now
311 * decide whether or not to add it based on the URL.
313 * Revision 1.14 2001/05/29 20:14:01 joergs
314 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
317 * Revision 1.13 2001/05/29 09:50:24 jongfoster
318 * Unified blocklist/imagelist/permissionslist.
319 * File format is still under discussion, but the internal changes
322 * Also modified interceptor behaviour:
323 * - We now intercept all URLs beginning with one of the following
324 * prefixes (and *only* these prefixes):
326 * * http://ijbswa.sf.net/config/
327 * * http://ijbswa.sourceforge.net/config/
328 * - New interceptors "home page" - go to http://i.j.b/ to see it.
329 * - Internal changes so that intercepted and fast redirect pages
330 * are not replaced with an image.
331 * - Interceptors now have the option to send a binary page direct
332 * to the client. (i.e. ijb-send-banner uses this)
333 * - Implemented show-url-info interceptor. (Which is why I needed
334 * the above interceptors changes - a typical URL is
335 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
336 * The previous mechanism would not have intercepted that, and
337 * if it had been intercepted then it then it would have replaced
340 * Revision 1.12 2001/05/27 22:17:04 oes
342 * - re_process_buffer no longer writes the modified buffer
343 * to the client, which was very ugly. It now returns the
344 * buffer, which it is then written by chat.
346 * - content_length now adjusts the Content-Length: header
347 * for modified documents rather than crunch()ing it.
348 * (Length info in csp->content_length, which is 0 for
349 * unmodified documents)
351 * - For this to work, sed() is called twice when filtering.
353 * Revision 1.11 2001/05/26 17:27:53 jongfoster
354 * Added support for CLF and fixed LOG_LEVEL_LOG.
355 * Also did CRLF->LF fix of my previous patch.
357 * Revision 1.10 2001/05/26 15:26:15 jongfoster
358 * ACL feature now provides more security by immediately dropping
359 * connections from untrusted hosts.
361 * Revision 1.9 2001/05/26 00:28:36 jongfoster
362 * Automatic reloading of config file.
363 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
364 * Most of the global variables have been moved to a new
365 * struct configuration_spec, accessed through csp->config->globalname
366 * Most of the globals remaining are used by the Win32 GUI.
368 * Revision 1.8 2001/05/25 22:43:18 jongfoster
369 * Fixing minor memory leak and buffer overflow.
371 * Revision 1.7 2001/05/25 22:34:30 jongfoster
374 * Revision 1.6 2001/05/23 00:13:58 joergs
375 * AmigaOS support fixed.
377 * Revision 1.5 2001/05/22 18:46:04 oes
379 * - Enabled filtering banners by size rather than URL
380 * by adding patterns that replace all standard banner
381 * sizes with the "Junkbuster" gif to the re_filterfile
383 * - Enabled filtering WebBugs by providing a pattern
384 * which kills all 1x1 images
386 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
387 * which is selected by the (nonstandard and therefore
388 * capital) letter 'U' in the option string.
389 * It causes the quantifiers to be ungreedy by default.
390 * Appending a ? turns back to greedy (!).
392 * - Added a new interceptor ijb-send-banner, which
393 * sends back the "Junkbuster" gif. Without imagelist or
394 * MSIE detection support, or if tinygif = 1, or the
395 * URL isn't recognized as an imageurl, a lame HTML
396 * explanation is sent instead.
398 * - Added new feature, which permits blocking remote
399 * script redirects and firing back a local redirect
401 * The feature is conditionally compiled, i.e. it
402 * can be disabled with --disable-fast-redirects,
403 * plus it must be activated by a "fast-redirects"
404 * line in the config file, has its own log level
405 * and of course wants to be displayed by show-proxy-args
406 * Note: Boy, all the #ifdefs in 1001 locations and
407 * all the fumbling with configure.in and acconfig.h
408 * were *way* more work than the feature itself :-(
410 * - Because a generic redirect template was needed for
411 * this, tinygif = 3 now uses the same.
413 * - Moved GIFs, and other static HTTP response templates
418 * - Removed some >400 CRs again (Jon, you really worked
421 * Revision 1.4 2001/05/21 19:34:01 jongfoster
422 * Made failure to bind() a fatal error.
424 * Revision 1.3 2001/05/20 01:21:20 jongfoster
425 * Version 2.9.4 checkin.
426 * - Merged popupfile and cookiefile, and added control over PCRS
427 * filtering, in new "permissionsfile".
428 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
429 * file error you now get a message box (in the Win32 GUI) rather
430 * than the program exiting with no explanation.
431 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
433 * - Removed tabs from "config"
434 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
435 * - Bumped up version number.
437 * Revision 1.2 2001/05/17 22:34:44 oes
438 * - Added hint on GIF char array generation to jcc.c
439 * - Cleaned CRLF's from the sources and related files
440 * - Repaired logging for REF and FRC
442 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
443 * Initial import of version 2.9.3 source tree
446 *********************************************************************/
452 #include <sys/types.h>
459 #ifdef FEATURE_PTHREAD
461 #endif /* def FEATURE_PTHREAD */
464 # ifndef FEATURE_PTHREAD
465 # include <windows.h>
466 # include <process.h>
467 # endif /* ndef FEATURE_PTHREAD */
470 # ifndef _WIN_CONSOLE
472 # endif /* ndef _WIN_CONSOLE */
474 #else /* ifndef _WIN32 */
476 # if !defined (__OS2__)
478 # include <sys/wait.h>
479 # endif /* ndef __OS2__ */
480 # include <sys/time.h>
481 # include <sys/stat.h>
482 # include <sys/ioctl.h>
485 #include <sys/termios.h>
495 # include <socket.h> /* BeOS has select() for sockets only. */
496 # include <OS.h> /* declarations for threads and stuff. */
499 # if defined(__EMX__) || defined(__OS2__)
500 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
505 #define bzero(B,N) memset(B,0x00,n)
520 #include "killpopup.h"
521 #include "miscutil.h"
523 #include "jbsockets.h"
528 #include "urlmatch.h"
530 const char jcc_h_rcs[] = JCC_H_VERSION;
531 const char project_h_rcs[] = PROJECT_H_VERSION;
534 struct client_state clients[1];
535 struct file_list files[1];
537 #ifdef FEATURE_STATISTICS
538 int urls_read = 0; /* total nr of urls read inc rejected */
539 int urls_rejected = 0; /* total nr of urls rejected */
540 #endif /* def FEATURE_STATISTICS */
543 static void listen_loop(void);
544 static void chat(struct client_state *csp);
546 void serve(struct client_state *csp);
547 #else /* ifndef AMIGA */
548 static void serve(struct client_state *csp);
549 #endif /* def AMIGA */
552 static int32 server_thread(void *data);
553 #endif /* def __BEOS__ */
556 #define sleep(N) Sleep(((N) * 1000))
560 #define sleep(N) DosSleep(((N) * 100))
565 const char *pidfile = NULL;
566 int received_hup_signal = 0;
567 #endif /* defined unix */
569 /* The vanilla wafer. */
570 static const char VANILLA_WAFER[] =
571 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
572 "Do_not_send_me_any_copyrighted_information_other_than_the_"
573 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
574 "In_particular_do_not_send_me_any_cookies_that_"
575 "are_subject_to_a_claim_of_copyright_by_anybody._"
576 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
577 "(copyright_or_otherwise)_applying_to_any_cookie._";
580 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
581 /*********************************************************************
583 * Function : sig_handler
585 * Description : Signal handler for different signals.
586 * Exit gracefully on ABRT, TERM and INT
587 * or set a flag that will cause the errlog
588 * to be reopened by the main thread on HUP.
591 * 1 : the_signal = the signal cause this function to call
595 *********************************************************************/
596 static void sig_handler(int the_signal)
603 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
611 received_hup_signal = 1;
616 * We shouldn't be here, unless we catch signals
617 * in main() that we can't handle here!
619 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
627 /*********************************************************************
631 * Description : Once a connection to the client has been accepted,
632 * this function is called (via serve()) to handle the
633 * main business of the communication. When this
634 * function returns, the caller must close the client
638 * 1 : csp = Current client state (buffers, headers, etc...)
640 * Returns : On success, the number of bytes written are returned (zero
641 * indicates nothing was written). On error, -1 is returned,
642 * and errno is set appropriately. If count is zero and the
643 * file descriptor refers to a regular file, 0 will be
644 * returned without causing any other effect. For a special
645 * file, the results are not portable.
647 *********************************************************************/
648 static void chat(struct client_state *csp)
651 * This next lines are a little ugly, but they simplifies the if statements
652 * below. Basically if TOGGLE, then we want the if to test if the
653 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
654 * then we want the if to test for CSP_FLAG_FORCED , else we don't
656 #ifdef FEATURE_TOGGLE
657 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
658 #else /* ifndef FEATURE_TOGGLE */
659 # define IS_TOGGLED_ON_AND
660 #endif /* ndef FEATURE_TOGGLE */
661 #ifdef FEATURE_FORCE_LOAD
662 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
663 #else /* ifndef FEATURE_FORCE_LOAD */
664 # define IS_NOT_FORCED_AND
665 #endif /* def FEATURE_FORCE_LOAD */
667 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
669 char buf[BUFFER_SIZE];
672 int n, maxfd, server_body;
673 int ms_iis5_hack = 0;
675 const struct forward_spec * fwd;
676 struct http_request *http;
677 #ifdef FEATURE_KILL_POPUPS
678 int block_popups; /* bool, 1==will block popups */
679 int block_popups_now = 0; /* bool, 1==currently blocking popups */
680 #endif /* def FEATURE_KILL_POPUPS */
682 int pcrs_filter; /* bool, 1==will filter through pcrs */
683 int gif_deanimate; /* bool, 1==will deanimate gifs */
685 /* Function that does the content filtering for the current request */
686 char *(*content_filter)() = NULL;
688 /* Skeleton for HTTP response, if we should intercept the request */
689 struct http_response *rsp;
694 * Read the client's request. Note that since we're not using select() we
695 * could get blocked here if a client connected, then didn't say anything!
700 n = read_socket(csp->cfd, buf, sizeof(buf));
702 if (n <= 0) break; /* error! */
704 add_to_iob(csp, buf, n);
706 req = get_header(csp);
710 break; /* no HTTP request! */
715 continue; /* more to come! */
718 #ifdef FEATURE_FORCE_LOAD
719 /* If this request contains the FORCE_PREFIX,
720 * better get rid of it now and set the force flag --oes
723 if (strstr(req, FORCE_PREFIX))
725 strclean(req, FORCE_PREFIX);
726 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
727 csp->flags |= CSP_FLAG_FORCED;
730 #endif /* def FEATURE_FORCE_LOAD */
732 parse_http_request(req, http, csp);
737 if (http->cmd == NULL)
739 strcpy(buf, CHEADER);
740 write_socket(csp->cfd, buf, strlen(buf));
742 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
747 /* decide how to route the HTTP request */
749 if ((fwd = forward_url(http, csp)) == NULL)
751 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
752 /* Never get here - LOG_LEVEL_FATAL causes program exit */
755 /* build the http request to send to the server
756 * we have to do one of the following:
758 * create = use the original HTTP request to create a new
759 * HTTP request that has either the path component
760 * without the http://domainspec (w/path) or the
761 * full orininal URL (w/url)
762 * Note that the path and/or the HTTP version may
763 * have been altered by now.
765 * connect = Open a socket to the host:port of the server
766 * and short-circuit server and client socket.
768 * pass = Pass the request unchanged if forwarding a CONNECT
769 * request to a parent proxy. Note that we'll be sending
770 * the CFAIL message ourselves if connecting to the parent
771 * fails, but we won't send a CSUCCEED message if it works,
772 * since that would result in a double message (ours and the
773 * parent's). After sending the request to the parent, we simply
779 * +--------+--------+
781 * 0 | create | connect|
783 * Forwarding +--------+--------+
785 * 1 | create | pass |
787 * +--------+--------+
792 * Determine the actions for this URL
794 #ifdef FEATURE_TOGGLE
795 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
797 /* Most compatible set of actions (i.e. none) */
798 init_current_action(csp->action);
801 #endif /* ndef FEATURE_TOGGLE */
803 url_actions(http, csp);
808 * Check if a CONNECT request is allowable:
809 * In the absence of a +limit-connect action, allow only port 443.
810 * If there is an action, allow whatever matches the specificaton.
814 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
815 || (csp->action->flags & ACTION_LIMIT_CONNECT
816 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
818 strcpy(buf, CFORBIDDEN);
819 write_socket(csp->cfd, buf, strlen(buf));
821 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
822 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
830 * Downgrade http version from 1.1 to 1.0 if +downgrade
833 if ( (http->ssl == 0)
834 && (!strcmpic(http->ver, "HTTP/1.1"))
835 && (csp->action->flags & ACTION_DOWNGRADE))
838 http->ver = strdup("HTTP/1.0");
840 if (http->ver == NULL)
842 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
847 * Save a copy of the original request for logging
849 http->ocmd = strdup(http->cmd);
851 if (http->ocmd == NULL)
853 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
857 * (Re)build the HTTP request for non-SSL requests.
858 * If forwarding, use the whole URL, else, use only the path.
864 http->cmd = strdup(http->gpc);
865 string_append(&http->cmd, " ");
867 if (fwd->forward_host)
869 string_append(&http->cmd, http->url);
873 string_append(&http->cmd, http->path);
876 string_append(&http->cmd, " ");
877 string_append(&http->cmd, http->ver);
879 if (http->cmd == NULL)
881 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
884 enlist(csp->headers, http->cmd);
887 #ifdef FEATURE_COOKIE_JAR
889 * If we're logging cookies in a cookie jar, and the user has not
890 * supplied any wafers, and the user has not told us to suppress the
891 * vanilla wafer, then send the vanilla wafer.
893 if ((csp->config->jarfile != NULL)
894 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
895 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
897 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
899 #endif /* def FEATURE_COOKIE_JAR */
902 #ifdef FEATURE_KILL_POPUPS
903 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
904 #endif /* def FEATURE_KILL_POPUPS */
906 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
907 ((csp->action->flags & ACTION_FILTER) != 0);
909 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
911 /* grab the rest of the client's headers */
915 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
917 n = read_socket(csp->cfd, buf, sizeof(buf));
920 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
923 add_to_iob(csp, buf, n);
927 if (p == NULL) break;
929 enlist(csp->headers, p);
933 * We have a request. Now, check to see if we need to
934 * intercept it, i.e. If ..
938 /* a CGI call was detected and answered */
939 (NULL != (rsp = dispatch_cgi(csp)))
941 /* or we are enabled and... */
944 /* ..the request was blocked */
945 ( NULL != (rsp = block_url(csp)))
949 || ( NULL != (rsp = trust_url(csp)))
950 #endif /* def FEATURE_TRUST */
952 /* ..or a fast redirect kicked in */
953 #ifdef FEATURE_FAST_REDIRECTS
954 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
955 (NULL != (rsp = redirect_url(csp))))
956 #endif /* def FEATURE_FAST_REDIRECTS */
960 /* Write the answer to the client */
961 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
962 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
964 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
967 #ifdef FEATURE_STATISTICS
968 /* Count as a rejected request */
969 csp->flags |= CSP_FLAG_REJECTED;
970 #endif /* def FEATURE_STATISTICS */
972 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
973 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
974 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
976 /* Clean up and return */
977 free_http_response(rsp);
981 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
983 if (fwd->forward_host)
985 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
986 fwd->forward_host, fwd->forward_port, http->hostport);
990 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
993 /* here we connect to the server, gateway, or the forwarder */
995 csp->sfd = forwarded_connect(fwd, http, csp);
999 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1002 if (errno == EINVAL)
1004 rsp = error_response(csp, "no-such-domain", errno);
1006 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1007 csp->ip_addr_str, http->ocmd);
1011 rsp = error_response(csp, "connect-failed", errno);
1013 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1014 csp->ip_addr_str, http->ocmd);
1018 /* Write the answer to the client */
1021 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1022 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1024 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1028 free_http_response(rsp);
1032 log_error(LOG_LEVEL_CONNECT, "OK");
1034 hdr = sed(client_patterns, add_client_headers, csp);
1037 /* FIXME Should handle error properly */
1038 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1041 list_remove_all(csp->headers);
1043 if (fwd->forward_host || (http->ssl == 0))
1045 /* write the client's (modified) header to the server
1046 * (along with anything else that may be in the buffer)
1051 if ((write_socket(csp->sfd, hdr, n) != n)
1052 || (flush_socket(csp->sfd, csp ) < 0))
1054 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1057 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1058 csp->ip_addr_str, http->ocmd);
1060 rsp = error_response(csp, "connect-failed", errno);
1064 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1065 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1067 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1071 free_http_response(rsp);
1079 * We're running an SSL tunnel and we're not forwarding,
1080 * so just send the "connect succeeded" message to the
1081 * client, flush the rest, and get out of the way.
1083 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1084 csp->ip_addr_str, http->ocmd);
1086 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
1094 /* we're finished with the client's header */
1097 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1099 /* pass data between the client and server
1100 * until one or the other shuts down the connection.
1109 FD_SET(csp->cfd, &rfds);
1110 FD_SET(csp->sfd, &rfds);
1112 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
1116 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1120 /* this is the body of the browser's request
1121 * just read it and write it.
1124 if (FD_ISSET(csp->cfd, &rfds))
1126 n = read_socket(csp->cfd, buf, sizeof(buf));
1130 break; /* "game over, man" */
1133 if (write_socket(csp->sfd, buf, n) != n)
1135 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1142 * The server wants to talk. It could be the header or the body.
1143 * If `hdr' is null, then it's the header otherwise it's the body.
1144 * FIXME: Does `hdr' really mean `host'? No.
1148 if (FD_ISSET(csp->sfd, &rfds))
1151 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1155 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1157 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1158 csp->ip_addr_str, http->ocmd);
1160 rsp = error_response(csp, "connect-failed", errno);
1164 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1165 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1167 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1171 free_http_response(rsp);
1175 /* Add a trailing zero. This lets filter_popups
1176 * use string operations.
1180 #ifdef FEATURE_KILL_POPUPS
1181 /* Filter the popups on this read. */
1182 if (block_popups_now)
1184 filter_popups(buf, csp);
1186 #endif /* def FEATURE_KILL_POPUPS */
1188 /* Normally, this would indicate that we've read
1189 * as much as the server has sent us and we can
1190 * close the client connection. However, Microsoft
1191 * in its wisdom has released IIS/5 with a bug that
1192 * prevents it from sending the trailing \r\n in
1193 * a 302 redirect header (and possibly other headers).
1194 * To work around this if we've haven't parsed
1195 * a full header we'll append a trailing \r\n
1196 * and see if this now generates a valid one.
1198 * This hack shouldn't have any impacts. If we've
1199 * already transmitted the header or if this is a
1200 * SSL connection, then we won't bother with this
1201 * hack. So we only work on partially received
1202 * headers. If we append a \r\n and this still
1203 * doesn't generate a valid header, then we won't
1204 * transmit anything to the client.
1209 if (server_body || http->ssl)
1212 * If we have been buffering up the document,
1213 * now is the time to apply content modification
1214 * and send the result to the client.
1219 * If the content filter fails, use the original
1220 * buffer and length.
1221 * (see p != NULL ? p : csp->iob->cur below)
1223 if (NULL == (p = (*content_filter)(csp)))
1225 csp->content_length = csp->iob->eod - csp->iob->cur;
1228 hdr = sed(server_patterns, add_server_headers, csp);
1231 /* FIXME Should handle error properly */
1232 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1237 if ((write_socket(csp->cfd, hdr, n) != n)
1238 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1240 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1250 break; /* "game over, man" */
1254 * This is NOT the body, so
1255 * Let's pretend the server just sent us a blank line.
1257 n = sprintf(buf, "\r\n");
1260 * Now, let the normal header parsing algorithm below do its
1261 * job. If it fails, we'll exit instead of continuing.
1268 * If this is an SSL connection or we're in the body
1269 * of the server document, just write it to the client,
1270 * unless we need to buffer the body for later content-filtering
1273 if (server_body || http->ssl)
1277 add_to_iob(csp, buf, n);
1280 * If the buffer limit will be reached on the next read,
1281 * switch to non-filtering mode, i.e. make & write the
1282 * header, flush the socket and get out of the way.
1284 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1286 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1288 hdr = sed(server_patterns, add_server_headers, csp);
1291 /* FIXME Should handle error properly */
1292 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1298 if (((write_socket(csp->cfd, hdr, n) != n)
1299 || (n = flush_socket(csp->cfd, csp) < 0)))
1301 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1310 content_filter = NULL;
1317 if (write_socket(csp->cfd, buf, n) != n)
1319 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1328 /* we're still looking for the end of the
1329 * server's header ... (does that make header
1330 * parsing an "out of body experience" ?
1333 /* buffer up the data we just read */
1334 add_to_iob(csp, buf, n);
1336 /* get header lines from the iob */
1338 while ((p = get_header(csp)))
1342 /* see following note */
1345 enlist(csp->headers, p);
1349 /* NOTE: there are no "empty" headers so
1350 * if the pointer `p' is not NULL we must
1351 * assume that we reached the end of the
1352 * buffer before we hit the end of the header.
1359 /* Well, we tried our MS IIS/5
1360 * hack and it didn't work.
1361 * The header is incomplete
1362 * and there isn't anything
1363 * we can do about it.
1369 /* Since we have to wait for
1370 * more from the server before
1371 * we can parse the headers
1372 * we just continue here.
1378 /* we have now received the entire header.
1379 * filter it and send the result to the client
1382 hdr = sed(server_patterns, add_server_headers, csp);
1385 /* FIXME Should handle error properly */
1386 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1391 /* write the server's (modified) header to
1392 * the client (along with anything else that
1393 * may be in the buffer)
1396 #ifdef FEATURE_KILL_POPUPS
1397 /* Start blocking popups if appropriate. */
1399 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1400 !http->ssl && /* We talk plaintext */
1401 block_popups) /* Policy allows */
1403 block_popups_now = 1;
1405 * Filter the part of the body that came in the same read
1406 * as the last headers:
1408 filter_popups(csp->iob->cur, csp);
1411 #endif /* def FEATURE_KILL_POPUPS */
1413 /* Buffer and pcrs filter this if appropriate. */
1415 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1416 !http->ssl && /* We talk plaintext */
1417 pcrs_filter) /* Policy allows */
1419 content_filter = pcrs_filter_response;
1422 /* Buffer and gif_deanimate this if appropriate. */
1424 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1425 !http->ssl && /* We talk plaintext */
1426 gif_deanimate) /* Policy allows */
1428 content_filter = gif_deanimate_response;
1433 * Only write if we're not buffering for content modification
1435 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1436 || (n = flush_socket(csp->cfd, csp) < 0)))
1438 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1440 /* the write failed, so don't bother
1441 * mentioning it to the client...
1442 * it probably can't hear us anyway.
1448 if(!content_filter) byte_count += n;
1450 /* we're finished with the server's header */
1455 /* If this was a MS IIS/5 hack then it means
1456 * the server has already closed the
1457 * connection. Nothing more to read. Time
1468 return; /* huh? we should never get here */
1471 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1472 csp->ip_addr_str, http->ocmd, byte_count);
1476 /*********************************************************************
1480 * Description : This is little more than chat. We only "serve" to
1481 * to close any socket that chat may have opened.
1484 * 1 : csp = Current client state (buffers, headers, etc...)
1488 *********************************************************************/
1490 void serve(struct client_state *csp)
1491 #else /* ifndef AMIGA */
1492 static void serve(struct client_state *csp)
1493 #endif /* def AMIGA */
1496 close_socket(csp->cfd);
1500 close_socket(csp->sfd);
1503 csp->flags &= ~CSP_FLAG_ACTIVE;
1509 /*********************************************************************
1511 * Function : server_thread
1513 * Description : We only exist to call `serve' in a threaded environment.
1516 * 1 : data = Current client state (buffers, headers, etc...)
1518 * Returns : Always 0.
1520 *********************************************************************/
1521 static int32 server_thread(void *data)
1523 serve((struct client_state *) data);
1530 /*********************************************************************
1534 * Description : Print usage info & exit.
1536 * Parameters : Pointer to argv[0] for identifying ourselves
1540 *********************************************************************/
1541 void usage(const char *myname)
1543 printf("JunkBuster proxy version " VERSION " (" HOME_PAGE_URL ")\n"
1544 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user] [configfile]\n"
1545 "Aborting.\n", myname);
1552 /*********************************************************************
1556 * Description : Load the config file and start the listen loop.
1557 * This function is a lot more *sane* with the `load_config'
1558 * and `listen_loop' functions; although it stills does
1559 * a *little* too much for my taste.
1562 * 1 : argc = Number of parameters (including $0).
1563 * 2 : argv = Array of (char *)'s to the parameters.
1565 * Returns : 1 if : can't open config file, unrecognized directive,
1566 * stats requested in multi-thread mode, can't open the
1567 * log file, can't open the jar file, listen port is invalid,
1568 * any load fails, and can't bind port.
1570 * Else main never returns, the process must be signaled
1571 * to terminate execution. Or, on Windows, use the
1572 * "File", "Exit" menu option.
1574 *********************************************************************/
1576 int real_main(int argc, const char *argv[])
1578 int main(int argc, const char *argv[])
1583 struct passwd *pw = NULL;
1590 #if !defined(_WIN32)
1598 * Parse the command line arguments
1600 while (++argc_pos < argc)
1602 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1604 if (strcmp(argv[argc_pos], "--help") == 0)
1609 else if(strcmp(argv[argc_pos], "--version") == 0)
1611 printf("Junkbuster version " VERSION " (" HOME_PAGE_URL ")\n");
1615 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1620 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1622 if (++argc_pos == argc) usage(argv[0]);
1623 pidfile = strdup(argv[argc_pos]);
1626 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1628 if (++argc_pos == argc) usage(argv[0]);
1629 pw = getpwnam(argv[argc_pos]);
1633 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1636 #endif /* defined(unix) */
1638 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1640 configfile = argv[argc_pos];
1643 } /* -END- while (more arguments) */
1646 if ( *configfile != '/' )
1650 /* make config-filename absolute here */
1651 if ( !(basedir = getcwd( NULL, 1024 )))
1653 perror("get working dir failed");
1657 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1659 perror("malloc failed");
1662 strcpy( abs_file, basedir );
1663 strcat( abs_file, "/" );
1664 strcat( abs_file, configfile );
1665 configfile = abs_file;
1667 #endif /* defined unix */
1674 #elif defined(_WIN32)
1679 * Unix signal handling
1681 * Catch the abort, interrupt and terminate signals for a graceful exit
1682 * Catch the hangup signal so the errlog can be reopened.
1683 * Ignore the broken pipe and child signals
1684 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1686 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1689 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1690 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1692 for (idx = 0; catched_signals[idx] != 0; idx++)
1694 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1696 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1700 for (idx = 0; ignored_signals[idx] != 0; idx++)
1702 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1704 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1709 #else /* ifdef _WIN32 */
1710 # ifdef _WIN_CONSOLE
1712 * We *are* in a windows console app.
1713 * Print a verbose messages about FAQ's and such
1715 printf(win32_blurb);
1716 # endif /* def _WIN_CONSOLE */
1717 #endif /* def _WIN32 */
1720 /* Initialize the CGI subsystem */
1721 cgi_init_error_messages();
1724 * If runnig on unix and without the --nodaemon
1725 * option, become a daemon. I.e. fork, detach
1726 * from tty and get process group leadership
1739 if ( pid < 0 ) /* error */
1744 else if ( pid != 0 ) /* parent */
1749 * must check for errors
1750 * child died due to missing files aso
1753 wpid = waitpid( pid, &status, WNOHANG );
1762 /* Should be more portable, but not as well tested */
1767 #else /* ndef __FreeBSD__ */
1769 #endif /* ndef __FreeBSD__ */
1770 fd = open("/dev/tty", O_RDONLY);
1773 /* no error check here */
1774 ioctl( fd, TIOCNOTTY,0 );
1778 /* FIXME: should close stderr (fd 2) here too, but the test
1780 * and load config file is done in listen_loop() and puts
1781 * some messages on stderr there.
1788 } /* -END- if (!no_daemon) */
1791 * As soon as we have written the PID file, we can switch
1792 * to the user ID indicated by the --user option
1796 if ((NULL != pw) && setuid(pw->pw_uid))
1798 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1802 #endif /* defined unix */
1812 /*********************************************************************
1814 * Function : bind_port_helper
1816 * Description : Bind the listen port. Handles logging, and aborts
1820 * 1 : config = Junkbuster configuration. Specifies port
1823 * Returns : Port that was opened.
1825 *********************************************************************/
1826 static int bind_port_helper(struct configuration_spec * config)
1830 if ( (config->haddr != NULL)
1831 && (config->haddr[0] == '1')
1832 && (config->haddr[1] == '2')
1833 && (config->haddr[2] == '7')
1834 && (config->haddr[3] == '.') )
1836 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1839 else if (config->haddr == NULL)
1841 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1846 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1847 config->hport, config->haddr);
1850 bfd = bind_port(config->haddr, config->hport);
1854 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1855 "- There may be another junkbuster or some other "
1856 "proxy running on port %d",
1857 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1858 config->hport, config->hport
1860 /* shouldn't get here */
1864 config->need_bind = 0;
1870 /*********************************************************************
1872 * Function : listen_loop
1874 * Description : bind the listen port and enter a "FOREVER" listening loop.
1880 *********************************************************************/
1881 static void listen_loop(void)
1883 struct client_state *csp = NULL;
1885 struct configuration_spec * config;
1887 config = load_config();
1889 bfd = bind_port_helper(config);
1893 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1894 while (waitpid(-1, NULL, WNOHANG) > 0)
1896 /* zombie children */
1898 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1901 * Free data that was used by died threads
1907 * Re-open the errlog after HUP signal
1909 if (received_hup_signal)
1911 init_error_log(Argv[0], config->logfile, config->debug);
1912 received_hup_signal = 0;
1916 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1918 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1922 csp->flags |= CSP_FLAG_ACTIVE;
1925 csp->config = config = load_config();
1927 if ( config->need_bind )
1930 * Since we were listening to the "old port", we will not see
1931 * a "listen" param change until the next IJB request. So, at
1932 * least 1 more request must be made for us to find the new
1933 * setting. I am simply closing the old socket and binding the
1936 * Which-ever is correct, we will serve 1 more page via the
1937 * old settings. This should probably be a "show-proxy-args"
1938 * request. This should not be a so common of an operation
1939 * that this will hurt people's feelings.
1944 bfd = bind_port_helper(config);
1947 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1949 if (!accept_connection(csp, bfd))
1951 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1964 log_error(LOG_LEVEL_CONNECT, "OK");
1967 #ifdef FEATURE_TOGGLE
1970 csp->flags |= CSP_FLAG_TOGGLED_ON;
1972 #endif /* def FEATURE_TOGGLE */
1974 if (run_loader(csp))
1976 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1977 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1981 if (block_acl(NULL,csp))
1983 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1984 close_socket(csp->cfd);
1988 #endif /* def FEATURE_ACL */
1990 /* add it to the list of clients */
1991 csp->next = clients->next;
1992 clients->next = csp;
1994 if (config->multi_threaded)
1998 /* this is a switch () statment in the C preprocessor - ugh */
1999 #undef SELECTED_ONE_OPTION
2001 /* Use Pthreads in preference to native code */
2002 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2003 #define SELECTED_ONE_OPTION
2005 pthread_t the_thread;
2006 pthread_attr_t attrs;
2008 pthread_attr_init(&attrs);
2009 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2010 child_id = (pthread_create(&the_thread, &attrs,
2011 (void*)serve, csp) ? -1 : 0);
2012 pthread_attr_destroy(&attrs);
2016 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2017 #define SELECTED_ONE_OPTION
2018 child_id = _beginthread(
2024 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2025 #define SELECTED_ONE_OPTION
2026 child_id = _beginthread(
2033 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2034 #define SELECTED_ONE_OPTION
2036 thread_id tid = spawn_thread
2037 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2039 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2041 child_id = (int) tid;
2050 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2051 #define SELECTED_ONE_OPTION
2052 csp->cfd = ReleaseSocket(csp->cfd, -1);
2053 if((child_id = (int)CreateNewProcTags(
2054 NP_Entry, (ULONG)server_thread,
2055 NP_Output, Output(),
2056 NP_CloseOutput, FALSE,
2057 NP_Name, (ULONG)"junkbuster child",
2058 NP_StackSize, 200*1024,
2062 ((struct Task *)child_id)->tc_UserData = csp;
2063 Signal((struct Task *)child_id, SIGF_SINGLE);
2068 #if !defined(SELECTED_ONE_OPTION)
2071 /* This block is only needed when using fork().
2072 * When using threads, the server thread was
2073 * created and run by the call to _beginthread().
2075 if (child_id == 0) /* child */
2081 else if (child_id > 0) /* parent */
2083 /* in a fork()'d environment, the parent's
2084 * copy of the client socket and the CSP
2088 #if !defined(_WIN32) && defined(__CYGWIN__)
2090 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2091 close_socket(csp->cfd);
2092 csp->flags &= ~CSP_FLAG_ACTIVE;
2096 #undef SELECTED_ONE_OPTION
2097 /* end of cpp switch () */
2099 if (child_id < 0) /* failed */
2101 char buf[BUFFER_SIZE];
2103 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2105 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
2107 write_socket(csp->cfd, buf, strlen(buf));
2108 close_socket(csp->cfd);
2109 csp->flags &= ~CSP_FLAG_ACTIVE;