1 const char jcc_rcs[] = "$Id: jcc.c,v 1.57 2001/11/16 00:47:43 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.57 2001/11/16 00:47:43 jongfoster
37 * Changing the tty-disconnection code to use setsid().
39 * Revision 1.56 2001/11/13 20:20:54 jongfoster
40 * Tabs->spaces, fixing a bug with missing {} around an if()
42 * Revision 1.55 2001/11/13 20:14:53 jongfoster
43 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
45 * Revision 1.54 2001/11/07 00:03:14 steudten
46 * Give reliable return value if an error
47 * occurs not just 0 with new daemon mode.
49 * Revision 1.53 2001/11/05 21:41:43 steudten
50 * Add changes to be a real daemon just for unix os.
51 * (change cwd to /, detach from controlling tty, set
52 * process group and session leader to the own process.
54 * Add some fatal-error log message for failed malloc().
55 * Add '-d' if compiled with 'configure --with-debug' to
56 * enable debug output.
58 * Revision 1.52 2001/10/26 20:11:20 jongfoster
59 * Fixing type mismatch
61 * Revision 1.51 2001/10/26 17:38:28 oes
64 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
65 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
66 * threads to call select() simultaneously. So, it's time to do a real, live,
67 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
68 * (native). Both versions will work, but using __OS2__ offers multi-threading.
70 * Revision 1.49 2001/10/23 21:41:35 jongfoster
71 * Added call to initialize the (statically-allocated of course)
72 * "out of memory" CGI response.
74 * Revision 1.48 2001/10/10 19:56:46 jongfoster
75 * Moving some code that wasn't cookie-related out of an #ifdef
78 * Revision 1.47 2001/10/10 16:44:36 oes
79 * Added CONNECT destination port limitation check
81 * Revision 1.46 2001/10/08 15:17:41 oes
82 * Re-enabled SSL forwarding
84 * Revision 1.45 2001/10/07 15:42:11 oes
85 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
87 * Moved downgrading of the HTTP version from parse_http_request to
88 * chat(), since we can't decide if it is necessary before we have
89 * determined the actions for the URL. The HTTP command is now
90 * *always* re-built so the repairs need no longer be special-cased.
92 * filter_popups now gets a csp pointer so it can raise the new
93 * CSP_FLAG_MODIFIED flag.
97 * Added configurable size limit for the IOB. If the IOB grows so
98 * large that the next read would exceed the limit, the header
99 * is generated, and the header & unfiltered buffer are flushed
100 * to the client. Chat then continues in non-buffering,
101 * non-filtering body mode.
103 * Revision 1.44 2001/10/02 18:13:57 oes
106 * Revision 1.43 2001/10/02 15:32:13 oes
107 * Moved generation of hdr
109 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
110 * Cleaning up 2 compiler warnings on OS/2.
112 * Revision 1.41 2001/09/16 17:05:14 jongfoster
113 * Removing unused #include showarg.h
115 * Revision 1.40 2001/09/16 15:41:45 jongfoster
116 * Fixing signed/unsigned comparison warning.
118 * Revision 1.39 2001/09/16 13:21:27 jongfoster
119 * Changes to use new list functions.
121 * Revision 1.38 2001/09/16 13:01:46 jongfoster
122 * Removing redundant function call that zeroed zalloc()'d memory.
124 * Revision 1.37 2001/09/10 11:12:24 oes
125 * Deleted unused variable
127 * Revision 1.36 2001/09/10 10:56:15 oes
128 * Silenced compiler warnings
130 * Revision 1.35 2001/07/31 14:44:22 oes
131 * Deleted unused size parameter from filter_popups()
133 * Revision 1.34 2001/07/30 22:08:36 jongfoster
134 * Tidying up #defines:
135 * - All feature #defines are now of the form FEATURE_xxx
136 * - Permanently turned off WIN_GUI_EDIT
137 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
139 * Revision 1.33 2001/07/29 19:32:00 jongfoster
140 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
142 * Revision 1.32 2001/07/29 18:47:05 jongfoster
143 * Adding missing #include "loadcfg.h"
145 * Revision 1.31 2001/07/29 12:17:48 oes
146 * Applied pthread fix by Paul Lieverse
148 * Revision 1.30 2001/07/25 22:57:13 jongfoster
149 * __BEOS__ no longer overrides FEATURE_PTHREAD.
150 * This is because FEATURE_PTHREAD will soon be widely used, so I
151 * want to keep it simple.
153 * Revision 1.29 2001/07/24 12:47:06 oes
154 * Applied BeOS support update by Eugenia
156 * Revision 1.28 2001/07/23 13:26:12 oes
157 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
159 * Revision 1.27 2001/07/19 19:09:47 haroon
160 * - Added code to take care of the situation where while processing the first
161 * server response (which includes the server header), after finding the end
162 * of the headers we were not looking past the end of the headers for
163 * content modification. I enabled it for filter_popups.
164 * Someone else should look to see if other similar operations should be
165 * done to the discarded portion of the buffer.
167 * Note 2001/07/20: No, the other content modification mechanisms will process
168 * the whole iob later anyway. --oes
170 * Revision 1.26 2001/07/18 12:31:36 oes
173 * Revision 1.25 2001/07/15 19:43:49 jongfoster
174 * Supports POSIX threads.
175 * Also removed some unused #includes.
177 * Revision 1.24 2001/07/13 14:00:40 oes
178 * - Generic content modification scheme:
179 * Each feature has its own applicability flag that is set
180 * from csp->action->flags.
181 * Replaced the "filtering" int flag , by a function pointer
182 * "content_filter" to the function that will do the content
183 * modification. If it is != NULL, the document will be buffered
184 * and processed through *content_filter, which must set
185 * csp->content_length and return a modified copy of the body
186 * or return NULL (on failiure).
187 * - Changed csp->is_text to the more generic bitmap csp->content_type
188 * which can currently take the valued CT_TEXT or CT_GIF
190 * - Removed all #ifdef PCRS
192 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
193 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
194 * the `block_acl' call. This prevents a compilation error when the user
195 * does not wish to use the "ACL" feature.
197 * Revision 1.22 2001/06/29 21:45:41 oes
198 * Indentation, CRLF->LF, Tab-> Space
200 * Revision 1.21 2001/06/29 13:29:36 oes
201 * - Cleaned up, improved comments
202 * - Unified all possible interceptors (CGI,
203 * block, trust, fast_redirect) in one
204 * place, with one (CGI) answer generation
205 * mechansim. Much clearer now.
206 * - Removed the GIF image generation, which
207 * is now done in filters.c:block_url()
208 * - Made error conditions like domain lookup
209 * failiure or (various) problems while talking
210 * to the server use cgi.c:error_response()
211 * instead of generating HTML/HTTP in chat() (yuck!)
212 * - Removed logentry from cancelled commit
214 * Revision 1.20 2001/06/09 10:55:28 jongfoster
215 * Changing BUFSIZ ==> BUFFER_SIZE
217 * Revision 1.19 2001/06/07 23:12:52 jongfoster
218 * Replacing function pointer in struct gateway with a directly
219 * called function forwarded_connect().
220 * Replacing struct gateway with struct forward_spec
222 * Revision 1.18 2001/06/03 19:12:16 oes
223 * introduced new cgi handling
225 * Revision 1.17 2001/06/01 20:07:23 jongfoster
226 * Now uses action +image-blocker{} rather than config->tinygif
228 * Revision 1.16 2001/06/01 18:49:17 jongfoster
229 * Replaced "list_share" with "list" - the tiny memory gain was not
230 * worth the extra complexity.
232 * Revision 1.15 2001/05/31 21:24:47 jongfoster
233 * Changed "permission" to "action" throughout.
234 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
235 * Moved vanilla wafer check into chat(), since we must now
236 * decide whether or not to add it based on the URL.
238 * Revision 1.14 2001/05/29 20:14:01 joergs
239 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
242 * Revision 1.13 2001/05/29 09:50:24 jongfoster
243 * Unified blocklist/imagelist/permissionslist.
244 * File format is still under discussion, but the internal changes
247 * Also modified interceptor behaviour:
248 * - We now intercept all URLs beginning with one of the following
249 * prefixes (and *only* these prefixes):
251 * * http://ijbswa.sf.net/config/
252 * * http://ijbswa.sourceforge.net/config/
253 * - New interceptors "home page" - go to http://i.j.b/ to see it.
254 * - Internal changes so that intercepted and fast redirect pages
255 * are not replaced with an image.
256 * - Interceptors now have the option to send a binary page direct
257 * to the client. (i.e. ijb-send-banner uses this)
258 * - Implemented show-url-info interceptor. (Which is why I needed
259 * the above interceptors changes - a typical URL is
260 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
261 * The previous mechanism would not have intercepted that, and
262 * if it had been intercepted then it then it would have replaced
265 * Revision 1.12 2001/05/27 22:17:04 oes
267 * - re_process_buffer no longer writes the modified buffer
268 * to the client, which was very ugly. It now returns the
269 * buffer, which it is then written by chat.
271 * - content_length now adjusts the Content-Length: header
272 * for modified documents rather than crunch()ing it.
273 * (Length info in csp->content_length, which is 0 for
274 * unmodified documents)
276 * - For this to work, sed() is called twice when filtering.
278 * Revision 1.11 2001/05/26 17:27:53 jongfoster
279 * Added support for CLF and fixed LOG_LEVEL_LOG.
280 * Also did CRLF->LF fix of my previous patch.
282 * Revision 1.10 2001/05/26 15:26:15 jongfoster
283 * ACL feature now provides more security by immediately dropping
284 * connections from untrusted hosts.
286 * Revision 1.9 2001/05/26 00:28:36 jongfoster
287 * Automatic reloading of config file.
288 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
289 * Most of the global variables have been moved to a new
290 * struct configuration_spec, accessed through csp->config->globalname
291 * Most of the globals remaining are used by the Win32 GUI.
293 * Revision 1.8 2001/05/25 22:43:18 jongfoster
294 * Fixing minor memory leak and buffer overflow.
296 * Revision 1.7 2001/05/25 22:34:30 jongfoster
299 * Revision 1.6 2001/05/23 00:13:58 joergs
300 * AmigaOS support fixed.
302 * Revision 1.5 2001/05/22 18:46:04 oes
304 * - Enabled filtering banners by size rather than URL
305 * by adding patterns that replace all standard banner
306 * sizes with the "Junkbuster" gif to the re_filterfile
308 * - Enabled filtering WebBugs by providing a pattern
309 * which kills all 1x1 images
311 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
312 * which is selected by the (nonstandard and therefore
313 * capital) letter 'U' in the option string.
314 * It causes the quantifiers to be ungreedy by default.
315 * Appending a ? turns back to greedy (!).
317 * - Added a new interceptor ijb-send-banner, which
318 * sends back the "Junkbuster" gif. Without imagelist or
319 * MSIE detection support, or if tinygif = 1, or the
320 * URL isn't recognized as an imageurl, a lame HTML
321 * explanation is sent instead.
323 * - Added new feature, which permits blocking remote
324 * script redirects and firing back a local redirect
326 * The feature is conditionally compiled, i.e. it
327 * can be disabled with --disable-fast-redirects,
328 * plus it must be activated by a "fast-redirects"
329 * line in the config file, has its own log level
330 * and of course wants to be displayed by show-proxy-args
331 * Note: Boy, all the #ifdefs in 1001 locations and
332 * all the fumbling with configure.in and acconfig.h
333 * were *way* more work than the feature itself :-(
335 * - Because a generic redirect template was needed for
336 * this, tinygif = 3 now uses the same.
338 * - Moved GIFs, and other static HTTP response templates
343 * - Removed some >400 CRs again (Jon, you really worked
346 * Revision 1.4 2001/05/21 19:34:01 jongfoster
347 * Made failure to bind() a fatal error.
349 * Revision 1.3 2001/05/20 01:21:20 jongfoster
350 * Version 2.9.4 checkin.
351 * - Merged popupfile and cookiefile, and added control over PCRS
352 * filtering, in new "permissionsfile".
353 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
354 * file error you now get a message box (in the Win32 GUI) rather
355 * than the program exiting with no explanation.
356 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
358 * - Removed tabs from "config"
359 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
360 * - Bumped up version number.
362 * Revision 1.2 2001/05/17 22:34:44 oes
363 * - Added hint on GIF char array generation to jcc.c
364 * - Cleaned CRLF's from the sources and related files
365 * - Repaired logging for REF and FRC
367 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
368 * Initial import of version 2.9.3 source tree
371 *********************************************************************/
377 #include <sys/types.h>
384 #ifdef FEATURE_PTHREAD
386 #endif /* def FEATURE_PTHREAD */
389 # ifndef FEATURE_PTHREAD
390 # include <windows.h>
391 # include <process.h>
392 # endif /* ndef FEATURE_PTHREAD */
395 # ifndef _WIN_CONSOLE
397 # endif /* ndef _WIN_CONSOLE */
399 #else /* ifndef _WIN32 */
401 # if !defined (__OS2__)
403 # include <sys/wait.h>
404 # endif /* ndef __OS2__ */
405 # include <sys/time.h>
406 # include <sys/stat.h>
407 # include <sys/ioctl.h>
410 #include <sys/termios.h>
416 # include <socket.h> /* BeOS has select() for sockets only. */
417 # include <OS.h> /* declarations for threads and stuff. */
420 # if defined(__EMX__) || defined(__OS2__)
421 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
426 #define bzero(B,N) memset(B,0x00,n)
445 #include "killpopup.h"
446 #include "miscutil.h"
448 #include "jbsockets.h"
454 const char jcc_h_rcs[] = JCC_H_VERSION;
455 const char project_h_rcs[] = PROJECT_H_VERSION;
457 struct client_state clients[1];
458 struct file_list files[1];
460 #ifdef FEATURE_STATISTICS
461 int urls_read = 0; /* total nr of urls read inc rejected */
462 int urls_rejected = 0; /* total nr of urls rejected */
463 #endif /* def FEATURE_STATISTICS */
466 static void listen_loop(void);
467 static void chat(struct client_state *csp);
469 void serve(struct client_state *csp);
470 #else /* ifndef AMIGA */
471 static void serve(struct client_state *csp);
472 #endif /* def AMIGA */
475 static int32 server_thread(void *data);
476 #endif /* def __BEOS__ */
479 #define sleep(N) Sleep(((N) * 1000))
483 #define sleep(N) DosSleep(((N) * 100))
488 #endif /* defined unix */
490 /* The vanilla wafer. */
491 static const char VANILLA_WAFER[] =
492 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
493 "Do_not_send_me_any_copyrighted_information_other_than_the_"
494 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
495 "In_particular_do_not_send_me_any_cookies_that_"
496 "are_subject_to_a_claim_of_copyright_by_anybody._"
497 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
498 "(copyright_or_otherwise)_applying_to_any_cookie._";
501 /*********************************************************************
505 * Description : Once a connection to the client has been accepted,
506 * this function is called (via serve()) to handle the
507 * main business of the communication. When this
508 * function returns, the caller must close the client
512 * 1 : csp = Current client state (buffers, headers, etc...)
514 * Returns : On success, the number of bytes written are returned (zero
515 * indicates nothing was written). On error, -1 is returned,
516 * and errno is set appropriately. If count is zero and the
517 * file descriptor refers to a regular file, 0 will be
518 * returned without causing any other effect. For a special
519 * file, the results are not portable.
521 *********************************************************************/
522 static void chat(struct client_state *csp)
525 * This next lines are a little ugly, but they simplifies the if statements
526 * below. Basically if TOGGLE, then we want the if to test if the
527 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
528 * then we want the if to test for CSP_FLAG_FORCED , else we don't
530 #ifdef FEATURE_TOGGLE
531 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
532 #else /* ifndef FEATURE_TOGGLE */
533 # define IS_TOGGLED_ON_AND
534 #endif /* ndef FEATURE_TOGGLE */
535 #ifdef FEATURE_FORCE_LOAD
536 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
537 #else /* ifndef FEATURE_FORCE_LOAD */
538 # define IS_NOT_FORCED_AND
539 #endif /* def FEATURE_FORCE_LOAD */
541 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
543 char buf[BUFFER_SIZE];
546 int n, maxfd, server_body;
547 int ms_iis5_hack = 0;
549 const struct forward_spec * fwd;
550 struct http_request *http;
551 #ifdef FEATURE_KILL_POPUPS
552 int block_popups; /* bool, 1==will block popups */
553 int block_popups_now = 0; /* bool, 1==currently blocking popups */
554 #endif /* def FEATURE_KILL_POPUPS */
556 int pcrs_filter; /* bool, 1==will filter through pcrs */
557 int gif_deanimate; /* bool, 1==will deanimate gifs */
559 /* Function that does the content filtering for the current request */
560 char *(*content_filter)() = NULL;
562 /* Skeleton for HTTP response, if we should intercept the request */
563 struct http_response *rsp;
568 * Read the client's request. Note that since we're not using select() we
569 * could get blocked here if a client connected, then didn't say anything!
574 n = read_socket(csp->cfd, buf, sizeof(buf));
576 if (n <= 0) break; /* error! */
578 add_to_iob(csp, buf, n);
580 req = get_header(csp);
584 break; /* no HTTP request! */
589 continue; /* more to come! */
592 #ifdef FEATURE_FORCE_LOAD
593 /* If this request contains the FORCE_PREFIX,
594 * better get rid of it now and set the force flag --oes
597 if (strstr(req, FORCE_PREFIX))
599 strclean(req, FORCE_PREFIX);
600 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
601 csp->flags |= CSP_FLAG_FORCED;
604 #endif /* def FEATURE_FORCE_LOAD */
606 parse_http_request(req, http, csp);
611 if (http->cmd == NULL)
613 strcpy(buf, CHEADER);
614 write_socket(csp->cfd, buf, strlen(buf));
616 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
621 /* decide how to route the HTTP request */
623 if ((fwd = forward_url(http, csp)) == NULL)
625 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
626 /* Never get here - LOG_LEVEL_FATAL causes program exit */
629 /* build the http request to send to the server
630 * we have to do one of the following:
632 * create = use the original HTTP request to create a new
633 * HTTP request that has either the path component
634 * without the http://domainspec (w/path) or the
635 * full orininal URL (w/url)
636 * Note that the path and/or the HTTP version may
637 * have been altered by now.
639 * connect = Open a socket to the host:port of the server
640 * and short-circuit server and client socket.
642 * pass = Pass the request unchanged if forwarding a CONNECT
643 * request to a parent proxy. Note that we'll be sending
644 * the CFAIL message ourselves if connecting to the parent
645 * fails, but we won't send a CSUCCEED message if it works,
646 * since that would result in a double message (ours and the
647 * parent's). After sending the request to the parent, we simply
653 * +--------+--------+
655 * 0 | create | connect|
657 * Forwarding +--------+--------+
659 * 1 | create | pass |
661 * +--------+--------+
666 * Determine the actions for this URL
668 #ifdef FEATURE_TOGGLE
669 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
671 /* Most compatible set of actions (i.e. none) */
672 init_current_action(csp->action);
675 #endif /* ndef FEATURE_TOGGLE */
677 url_actions(http, csp);
682 * Check if a CONNECT request is allowable:
683 * In the absence of a +limit-connect action, allow only port 443.
684 * If there is an action, allow whatever matches the specificaton.
688 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
689 || (csp->action->flags & ACTION_LIMIT_CONNECT
690 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
692 strcpy(buf, CFORBIDDEN);
693 write_socket(csp->cfd, buf, strlen(buf));
695 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
696 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
704 * Downgrade http version from 1.1 to 1.0 if +downgrade
707 if (!strcmpic(http->ver, "HTTP/1.1") && csp->action->flags & ACTION_DOWNGRADE)
710 http->ver = strdup("HTTP/1.0");
714 * (Re)build the HTTP request for non-SSL requests.
715 * If forwarding, use the whole URL, else, use only the path.
721 http->cmd = strsav(http->cmd, http->gpc);
722 http->cmd = strsav(http->cmd, " ");
724 if (fwd->forward_host)
726 http->cmd = strsav(http->cmd, http->url);
730 http->cmd = strsav(http->cmd, http->path);
733 http->cmd = strsav(http->cmd, " ");
734 http->cmd = strsav(http->cmd, http->ver);
737 enlist(csp->headers, http->cmd);
740 #ifdef FEATURE_COOKIE_JAR
742 * If we're logging cookies in a cookie jar, and the user has not
743 * supplied any wafers, and the user has not told us to suppress the
744 * vanilla wafer, then send the vanilla wafer.
746 if ((csp->config->jarfile != NULL)
747 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
748 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
750 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
752 #endif /* def FEATURE_COOKIE_JAR */
755 #ifdef FEATURE_KILL_POPUPS
756 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
757 #endif /* def FEATURE_KILL_POPUPS */
759 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
760 ((csp->action->flags & ACTION_FILTER) != 0);
762 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
764 /* grab the rest of the client's headers */
768 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
770 n = read_socket(csp->cfd, buf, sizeof(buf));
773 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
776 add_to_iob(csp, buf, n);
780 if (p == NULL) break;
782 enlist(csp->headers, p);
786 * We have a request. Now, check to see if we need to
787 * intercept it, i.e. If ..
791 /* a CGI call was detected and answered */
792 (NULL != (rsp = dispatch_cgi(csp)))
794 /* or we are enabled and... */
797 /* ..the request was blocked */
798 ( NULL != (rsp = block_url(csp)))
802 || ( NULL != (rsp = trust_url(csp)))
803 #endif /* def FEATURE_TRUST */
805 /* ..or a fast redirect kicked in */
806 #ifdef FEATURE_FAST_REDIRECTS
807 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
808 (NULL != (rsp = redirect_url(csp))))
809 #endif /* def FEATURE_FAST_REDIRECTS */
813 /* Write the answer to the client */
814 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
815 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
817 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
820 #ifdef FEATURE_STATISTICS
821 /* Count as a rejected request */
822 csp->flags |= CSP_FLAG_REJECTED;
823 #endif /* def FEATURE_STATISTICS */
825 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
826 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
827 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
829 /* Clean up and return */
830 free_http_response(rsp);
834 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
836 if (fwd->forward_host)
838 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
839 fwd->forward_host, fwd->forward_port, http->hostport);
843 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
846 /* here we connect to the server, gateway, or the forwarder */
848 csp->sfd = forwarded_connect(fwd, http, csp);
852 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
857 rsp = error_response(csp, "no-such-domain", errno);
859 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
860 csp->ip_addr_str, http->cmd);
864 rsp = error_response(csp, "connect-failed", errno);
866 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
867 csp->ip_addr_str, http->cmd);
870 /* Write the answer to the client */
873 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
874 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
876 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
880 free_http_response(rsp);
884 log_error(LOG_LEVEL_CONNECT, "OK");
886 hdr = sed(client_patterns, add_client_headers, csp);
887 list_remove_all(csp->headers);
889 if (fwd->forward_host || (http->ssl == 0))
891 /* write the client's (modified) header to the server
892 * (along with anything else that may be in the buffer)
897 if ((write_socket(csp->sfd, hdr, n) != n)
898 || (flush_socket(csp->sfd, csp ) < 0))
900 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
903 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
904 csp->ip_addr_str, http->cmd);
906 rsp = error_response(csp, "connect-failed", errno);
910 if ((write_socket(csp->cfd, rsp->head, n) != n)
911 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
913 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
917 free_http_response(rsp);
925 * We're running an SSL tunnel and we're not forwarding,
926 * so just send the "connect succeeded" message to the
927 * client, flush the rest, and get out of the way.
929 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
930 csp->ip_addr_str, http->cmd);
932 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
940 /* we're finished with the client's header */
943 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
945 /* pass data between the client and server
946 * until one or the other shuts down the connection.
955 FD_SET(csp->cfd, &rfds);
956 FD_SET(csp->sfd, &rfds);
958 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
962 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
966 /* this is the body of the browser's request
967 * just read it and write it.
970 if (FD_ISSET(csp->cfd, &rfds))
972 n = read_socket(csp->cfd, buf, sizeof(buf));
976 break; /* "game over, man" */
979 if (write_socket(csp->sfd, buf, n) != n)
981 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
988 * The server wants to talk. It could be the header or the body.
989 * If `hdr' is null, then it's the header otherwise it's the body.
990 * FIXME: Does `hdr' really mean `host'? No.
994 if (FD_ISSET(csp->sfd, &rfds))
997 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1001 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1003 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1004 csp->ip_addr_str, http->cmd);
1006 rsp = error_response(csp, "connect-failed", errno);
1010 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1011 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1013 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1017 free_http_response(rsp);
1021 /* Add a trailing zero. This lets filter_popups
1022 * use string operations.
1026 #ifdef FEATURE_KILL_POPUPS
1027 /* Filter the popups on this read. */
1028 if (block_popups_now)
1030 filter_popups(buf, csp);
1032 #endif /* def FEATURE_KILL_POPUPS */
1034 /* Normally, this would indicate that we've read
1035 * as much as the server has sent us and we can
1036 * close the client connection. However, Microsoft
1037 * in its wisdom has released IIS/5 with a bug that
1038 * prevents it from sending the trailing \r\n in
1039 * a 302 redirect header (and possibly other headers).
1040 * To work around this if we've haven't parsed
1041 * a full header we'll append a trailing \r\n
1042 * and see if this now generates a valid one.
1044 * This hack shouldn't have any impacts. If we've
1045 * already transmitted the header or if this is a
1046 * SSL connection, then we won't bother with this
1047 * hack. So we only work on partially received
1048 * headers. If we append a \r\n and this still
1049 * doesn't generate a valid header, then we won't
1050 * transmit anything to the client.
1055 if (server_body || http->ssl)
1058 * If we have been buffering up the document,
1059 * now is the time to apply content modification
1060 * and send the result to the client.
1065 * If the content filter fails, use the original
1066 * buffer and length.
1067 * (see p != NULL ? p : csp->iob->cur below)
1069 if (NULL == (p = (*content_filter)(csp)))
1071 csp->content_length = csp->iob->eod - csp->iob->cur;
1074 hdr = sed(server_patterns, add_server_headers, csp);
1077 if ((write_socket(csp->cfd, hdr, n) != n)
1078 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1080 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1090 break; /* "game over, man" */
1094 * This is NOT the body, so
1095 * Let's pretend the server just sent us a blank line.
1097 n = sprintf(buf, "\r\n");
1100 * Now, let the normal header parsing algorithm below do its
1101 * job. If it fails, we'll exit instead of continuing.
1108 * If this is an SSL connection or we're in the body
1109 * of the server document, just write it to the client,
1110 * unless we need to buffer the body for later content-filtering
1113 if (server_body || http->ssl)
1117 add_to_iob(csp, buf, n);
1120 * If the buffer limit will be reached on the next read,
1121 * switch to non-filtering mode, i.e. make & write the
1122 * header, flush the socket and get out of the way.
1124 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1126 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1128 hdr = sed(server_patterns, add_server_headers, csp);
1132 if (((write_socket(csp->cfd, hdr, n) != n)
1133 || (n = flush_socket(csp->cfd, csp) < 0)))
1135 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1144 content_filter = NULL;
1151 if (write_socket(csp->cfd, buf, n) != n)
1153 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1162 /* we're still looking for the end of the
1163 * server's header ... (does that make header
1164 * parsing an "out of body experience" ?
1167 /* buffer up the data we just read */
1168 add_to_iob(csp, buf, n);
1170 /* get header lines from the iob */
1172 while ((p = get_header(csp)))
1176 /* see following note */
1179 enlist(csp->headers, p);
1183 /* NOTE: there are no "empty" headers so
1184 * if the pointer `p' is not NULL we must
1185 * assume that we reached the end of the
1186 * buffer before we hit the end of the header.
1193 /* Well, we tried our MS IIS/5
1194 * hack and it didn't work.
1195 * The header is incomplete
1196 * and there isn't anything
1197 * we can do about it.
1203 /* Since we have to wait for
1204 * more from the server before
1205 * we can parse the headers
1206 * we just continue here.
1212 /* we have now received the entire header.
1213 * filter it and send the result to the client
1216 hdr = sed(server_patterns, add_server_headers, csp);
1219 /* write the server's (modified) header to
1220 * the client (along with anything else that
1221 * may be in the buffer)
1224 #ifdef FEATURE_KILL_POPUPS
1225 /* Start blocking popups if appropriate. */
1227 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1228 !http->ssl && /* We talk plaintext */
1229 block_popups) /* Policy allows */
1231 block_popups_now = 1;
1233 * Filter the part of the body that came in the same read
1234 * as the last headers:
1236 filter_popups(csp->iob->cur, csp);
1239 #endif /* def FEATURE_KILL_POPUPS */
1241 /* Buffer and pcrs filter this if appropriate. */
1243 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1244 !http->ssl && /* We talk plaintext */
1245 pcrs_filter) /* Policy allows */
1247 content_filter = pcrs_filter_response;
1250 /* Buffer and gif_deanimate this if appropriate. */
1252 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1253 !http->ssl && /* We talk plaintext */
1254 gif_deanimate) /* Policy allows */
1256 content_filter = gif_deanimate_response;
1261 * Only write if we're not buffering for content modification
1263 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1264 || (n = flush_socket(csp->cfd, csp) < 0)))
1266 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1268 /* the write failed, so don't bother
1269 * mentioning it to the client...
1270 * it probably can't hear us anyway.
1276 if(!content_filter) byte_count += n;
1278 /* we're finished with the server's header */
1283 /* If this was a MS IIS/5 hack then it means
1284 * the server has already closed the
1285 * connection. Nothing more to read. Time
1296 return; /* huh? we should never get here */
1299 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1300 csp->ip_addr_str, http->cmd, byte_count);
1304 /*********************************************************************
1308 * Description : This is little more than chat. We only "serve" to
1309 * to close any socket that chat may have opened.
1312 * 1 : csp = Current client state (buffers, headers, etc...)
1316 *********************************************************************/
1318 void serve(struct client_state *csp)
1319 #else /* ifndef AMIGA */
1320 static void serve(struct client_state *csp)
1321 #endif /* def AMIGA */
1324 close_socket(csp->cfd);
1328 close_socket(csp->sfd);
1331 csp->flags &= ~CSP_FLAG_ACTIVE;
1337 /*********************************************************************
1339 * Function : server_thread
1341 * Description : We only exist to call `serve' in a threaded environment.
1344 * 1 : data = Current client state (buffers, headers, etc...)
1346 * Returns : Always 0.
1348 *********************************************************************/
1349 static int32 server_thread(void *data)
1351 serve((struct client_state *) data);
1358 /*********************************************************************
1362 * Description : Load the config file and start the listen loop.
1363 * This function is a lot more *sane* with the `load_config'
1364 * and `listen_loop' functions; although it stills does
1365 * a *little* too much for my taste.
1368 * 1 : argc = Number of parameters (including $0).
1369 * 2 : argv = Array of (char *)'s to the parameters.
1371 * Returns : 1 if : can't open config file, unrecognized directive,
1372 * stats requested in multi-thread mode, can't open the
1373 * log file, can't open the jar file, listen port is invalid,
1374 * any load fails, and can't bind port.
1376 * Else main never returns, the process must be signaled
1377 * to terminate execution. Or, on Windows, use the
1378 * "File", "Exit" menu option.
1380 *********************************************************************/
1382 int real_main(int argc, const char *argv[])
1384 int main(int argc, const char *argv[])
1391 "AmiTCP:db/junkbuster/config"
1392 #elif !defined(_WIN32)
1399 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1400 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1402 printf("JunkBuster proxy version " VERSION ".\n\n"
1403 "Usage: %s [configfile]\n\n"
1404 "See " HOME_PAGE_URL " for details.\n"
1405 "This program is distributed under the GNU GPL, version 2 or later.\n",
1409 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1411 printf(VERSION "\n");
1415 if ((argc >= 2) && (strcmp(argv[1], "-d")==0))
1419 fprintf(stderr,"debugging enabled..\n");
1422 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1427 if (argc > argc_pos )
1429 configfile = argv[argc_pos];
1433 if ( *configfile != '/' )
1437 DBG(1, ("configfile before '%s'\n",configfile) );
1439 /* make config-filename absolute here */
1440 if ( !(basedir = getcwd( NULL, 1024 )))
1442 perror("get working dir failed");
1445 DBG(1, ("working dir '%s'\n",basedir) );
1446 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1448 perror("malloc failed");
1451 strcpy( abs_file, basedir );
1452 strcat( abs_file, "/" );
1453 strcat( abs_file, configfile );
1454 configfile = abs_file;
1455 DBG(1, ("configfile after '%s'\n",configfile) );
1457 #endif /* defined unix */
1464 #elif defined(_WIN32)
1469 #if !defined(_WIN32) && !defined(__OS2__)
1470 signal(SIGPIPE, SIG_IGN);
1471 signal(SIGCHLD, SIG_IGN);
1473 #else /* ifdef _WIN32 */
1474 # ifdef _WIN_CONSOLE
1476 * We *are* in a windows console app.
1477 * Print a verbose messages about FAQ's and such
1479 printf(win32_blurb);
1480 # endif /* def _WIN_CONSOLE */
1481 #endif /* def _WIN32 */
1484 /* Initialize the CGI subsystem */
1485 cgi_init_error_messages();
1495 * we make us a real daemon
1501 if ( pid < 0 ) /* error */
1506 else if ( pid != 0 ) /* parent */
1511 * must check for errors
1512 * child died due to missing files aso
1515 wpid = waitpid( pid, &status, WNOHANG );
1524 /* Should be more portable, but not as well tested */
1529 #else /* ndef __FreeBSD__ */
1531 #endif /* ndef __FreeBSD__ */
1532 fd = open("/dev/tty", O_RDONLY);
1535 /* no error check here */
1536 ioctl( fd, TIOCNOTTY,0 );
1540 /* should close stderr (fd 2) here too, but the test for existence
1541 ** and load config file is done in listen_loop() and puts
1542 ** some messages on stderr there.
1557 #endif /* defined unix */
1559 DBG(1, ("call listen_loop() \n") );
1568 /*********************************************************************
1570 * Function : listen_loop
1572 * Description : bind the listen port and enter a "FOREVER" listening loop.
1578 *********************************************************************/
1579 static void listen_loop(void)
1581 struct client_state *csp = NULL;
1583 struct configuration_spec * config;
1585 config = load_config();
1587 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1588 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1590 bfd = bind_port(config->haddr, config->hport);
1594 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1595 "- There may be another junkbuster or some other "
1596 "proxy running on port %d",
1597 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1598 config->hport, config->hport
1600 /* shouldn't get here */
1604 config->need_bind = 0;
1608 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1609 while (waitpid(-1, NULL, WNOHANG) > 0)
1611 /* zombie children */
1613 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1616 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1618 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1622 csp->flags |= CSP_FLAG_ACTIVE;
1625 csp->config = config = load_config();
1627 if ( config->need_bind )
1630 * Since we were listening to the "old port", we will not see
1631 * a "listen" param change until the next IJB request. So, at
1632 * least 1 more request must be made for us to find the new
1633 * setting. I am simply closing the old socket and binding the
1636 * Which-ever is correct, we will serve 1 more page via the
1637 * old settings. This should probably be a "show-proxy-args"
1638 * request. This should not be a so common of an operation
1639 * that this will hurt people's feelings.
1644 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1645 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1646 bfd = bind_port(config->haddr, config->hport);
1650 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1651 "- There may be another junkbuster or some other "
1652 "proxy running on port %d",
1653 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1654 config->hport, config->hport
1656 /* shouldn't get here */
1660 config->need_bind = 0;
1663 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1665 if (!accept_connection(csp, bfd))
1667 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1680 log_error(LOG_LEVEL_CONNECT, "OK");
1683 #ifdef FEATURE_TOGGLE
1686 csp->flags |= CSP_FLAG_TOGGLED_ON;
1688 #endif /* def FEATURE_TOGGLE */
1690 if (run_loader(csp))
1692 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1693 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1697 if (block_acl(NULL,csp))
1699 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1700 close_socket(csp->cfd);
1704 #endif /* def FEATURE_ACL */
1706 /* add it to the list of clients */
1707 csp->next = clients->next;
1708 clients->next = csp;
1710 if (config->multi_threaded)
1714 /* this is a switch () statment in the C preprocessor - ugh */
1715 #undef SELECTED_ONE_OPTION
1717 /* Use Pthreads in preference to native code */
1718 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1719 #define SELECTED_ONE_OPTION
1721 pthread_t the_thread;
1722 pthread_attr_t attrs;
1724 pthread_attr_init(&attrs);
1725 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1726 child_id = (pthread_create(&the_thread, &attrs,
1727 (void*)serve, csp) ? -1 : 0);
1728 pthread_attr_destroy(&attrs);
1732 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1733 #define SELECTED_ONE_OPTION
1734 child_id = _beginthread(
1740 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1741 #define SELECTED_ONE_OPTION
1742 child_id = _beginthread(
1749 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1750 #define SELECTED_ONE_OPTION
1752 thread_id tid = spawn_thread
1753 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1755 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1757 child_id = (int) tid;
1766 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1767 #define SELECTED_ONE_OPTION
1768 csp->cfd = ReleaseSocket(csp->cfd, -1);
1769 if((child_id = (int)CreateNewProcTags(
1770 NP_Entry, (ULONG)server_thread,
1771 NP_Output, Output(),
1772 NP_CloseOutput, FALSE,
1773 NP_Name, (ULONG)"junkbuster child",
1774 NP_StackSize, 200*1024,
1778 ((struct Task *)child_id)->tc_UserData = csp;
1779 Signal((struct Task *)child_id, SIGF_SINGLE);
1784 #if !defined(SELECTED_ONE_OPTION)
1787 /* This block is only needed when using fork().
1788 * When using threads, the server thread was
1789 * created and run by the call to _beginthread().
1791 if (child_id == 0) /* child */
1797 else if (child_id > 0) /* parent */
1799 /* in a fork()'d environment, the parent's
1800 * copy of the client socket and the CSP
1804 #if !defined(_WIN32) && defined(__CYGWIN__)
1806 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1807 close_socket(csp->cfd);
1808 csp->flags &= ~CSP_FLAG_ACTIVE;
1812 #undef SELECTED_ONE_OPTION
1813 /* end of cpp switch () */
1815 if (child_id < 0) /* failed */
1817 char buf[BUFFER_SIZE];
1819 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1821 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1823 write_socket(csp->cfd, buf, strlen(buf));
1824 close_socket(csp->cfd);
1825 csp->flags &= ~CSP_FLAG_ACTIVE;