1 const char jcc_rcs[] = "$Id: jcc.c,v 1.47 2001/10/10 16:44:36 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.47 2001/10/10 16:44:36 oes
37 * Added CONNECT destination port limitation check
39 * Revision 1.46 2001/10/08 15:17:41 oes
40 * Re-enabled SSL forwarding
42 * Revision 1.45 2001/10/07 15:42:11 oes
43 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
45 * Moved downgrading of the HTTP version from parse_http_request to
46 * chat(), since we can't decide if it is necessary before we have
47 * determined the actions for the URL. The HTTP command is now
48 * *always* re-built so the repairs need no longer be special-cased.
50 * filter_popups now gets a csp pointer so it can raise the new
51 * CSP_FLAG_MODIFIED flag.
55 * Added configurable size limit for the IOB. If the IOB grows so
56 * large that the next read would exceed the limit, the header
57 * is generated, and the header & unfiltered buffer are flushed
58 * to the client. Chat then continues in non-buffering,
59 * non-filtering body mode.
61 * Revision 1.44 2001/10/02 18:13:57 oes
64 * Revision 1.43 2001/10/02 15:32:13 oes
65 * Moved generation of hdr
67 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
68 * Cleaning up 2 compiler warnings on OS/2.
70 * Revision 1.41 2001/09/16 17:05:14 jongfoster
71 * Removing unused #include showarg.h
73 * Revision 1.40 2001/09/16 15:41:45 jongfoster
74 * Fixing signed/unsigned comparison warning.
76 * Revision 1.39 2001/09/16 13:21:27 jongfoster
77 * Changes to use new list functions.
79 * Revision 1.38 2001/09/16 13:01:46 jongfoster
80 * Removing redundant function call that zeroed zalloc()'d memory.
82 * Revision 1.37 2001/09/10 11:12:24 oes
83 * Deleted unused variable
85 * Revision 1.36 2001/09/10 10:56:15 oes
86 * Silenced compiler warnings
88 * Revision 1.35 2001/07/31 14:44:22 oes
89 * Deleted unused size parameter from filter_popups()
91 * Revision 1.34 2001/07/30 22:08:36 jongfoster
92 * Tidying up #defines:
93 * - All feature #defines are now of the form FEATURE_xxx
94 * - Permanently turned off WIN_GUI_EDIT
95 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
97 * Revision 1.33 2001/07/29 19:32:00 jongfoster
98 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
100 * Revision 1.32 2001/07/29 18:47:05 jongfoster
101 * Adding missing #include "loadcfg.h"
103 * Revision 1.31 2001/07/29 12:17:48 oes
104 * Applied pthread fix by Paul Lieverse
106 * Revision 1.30 2001/07/25 22:57:13 jongfoster
107 * __BEOS__ no longer overrides FEATURE_PTHREAD.
108 * This is because FEATURE_PTHREAD will soon be widely used, so I
109 * want to keep it simple.
111 * Revision 1.29 2001/07/24 12:47:06 oes
112 * Applied BeOS support update by Eugenia
114 * Revision 1.28 2001/07/23 13:26:12 oes
115 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
117 * Revision 1.27 2001/07/19 19:09:47 haroon
118 * - Added code to take care of the situation where while processing the first
119 * server response (which includes the server header), after finding the end
120 * of the headers we were not looking past the end of the headers for
121 * content modification. I enabled it for filter_popups.
122 * Someone else should look to see if other similar operations should be
123 * done to the discarded portion of the buffer.
125 * Note 2001/07/20: No, the other content modification mechanisms will process
126 * the whole iob later anyway. --oes
128 * Revision 1.26 2001/07/18 12:31:36 oes
131 * Revision 1.25 2001/07/15 19:43:49 jongfoster
132 * Supports POSIX threads.
133 * Also removed some unused #includes.
135 * Revision 1.24 2001/07/13 14:00:40 oes
136 * - Generic content modification scheme:
137 * Each feature has its own applicability flag that is set
138 * from csp->action->flags.
139 * Replaced the "filtering" int flag , by a function pointer
140 * "content_filter" to the function that will do the content
141 * modification. If it is != NULL, the document will be buffered
142 * and processed through *content_filter, which must set
143 * csp->content_length and return a modified copy of the body
144 * or return NULL (on failiure).
145 * - Changed csp->is_text to the more generic bitmap csp->content_type
146 * which can currently take the valued CT_TEXT or CT_GIF
148 * - Removed all #ifdef PCRS
150 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
151 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
152 * the `block_acl' call. This prevents a compilation error when the user
153 * does not wish to use the "ACL" feature.
155 * Revision 1.22 2001/06/29 21:45:41 oes
156 * Indentation, CRLF->LF, Tab-> Space
158 * Revision 1.21 2001/06/29 13:29:36 oes
159 * - Cleaned up, improved comments
160 * - Unified all possible interceptors (CGI,
161 * block, trust, fast_redirect) in one
162 * place, with one (CGI) answer generation
163 * mechansim. Much clearer now.
164 * - Removed the GIF image generation, which
165 * is now done in filters.c:block_url()
166 * - Made error conditions like domain lookup
167 * failiure or (various) problems while talking
168 * to the server use cgi.c:error_response()
169 * instead of generating HTML/HTTP in chat() (yuck!)
170 * - Removed logentry from cancelled commit
172 * Revision 1.20 2001/06/09 10:55:28 jongfoster
173 * Changing BUFSIZ ==> BUFFER_SIZE
175 * Revision 1.19 2001/06/07 23:12:52 jongfoster
176 * Replacing function pointer in struct gateway with a directly
177 * called function forwarded_connect().
178 * Replacing struct gateway with struct forward_spec
180 * Revision 1.18 2001/06/03 19:12:16 oes
181 * introduced new cgi handling
183 * Revision 1.17 2001/06/01 20:07:23 jongfoster
184 * Now uses action +image-blocker{} rather than config->tinygif
186 * Revision 1.16 2001/06/01 18:49:17 jongfoster
187 * Replaced "list_share" with "list" - the tiny memory gain was not
188 * worth the extra complexity.
190 * Revision 1.15 2001/05/31 21:24:47 jongfoster
191 * Changed "permission" to "action" throughout.
192 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
193 * Moved vanilla wafer check into chat(), since we must now
194 * decide whether or not to add it based on the URL.
196 * Revision 1.14 2001/05/29 20:14:01 joergs
197 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
200 * Revision 1.13 2001/05/29 09:50:24 jongfoster
201 * Unified blocklist/imagelist/permissionslist.
202 * File format is still under discussion, but the internal changes
205 * Also modified interceptor behaviour:
206 * - We now intercept all URLs beginning with one of the following
207 * prefixes (and *only* these prefixes):
209 * * http://ijbswa.sf.net/config/
210 * * http://ijbswa.sourceforge.net/config/
211 * - New interceptors "home page" - go to http://i.j.b/ to see it.
212 * - Internal changes so that intercepted and fast redirect pages
213 * are not replaced with an image.
214 * - Interceptors now have the option to send a binary page direct
215 * to the client. (i.e. ijb-send-banner uses this)
216 * - Implemented show-url-info interceptor. (Which is why I needed
217 * the above interceptors changes - a typical URL is
218 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
219 * The previous mechanism would not have intercepted that, and
220 * if it had been intercepted then it then it would have replaced
223 * Revision 1.12 2001/05/27 22:17:04 oes
225 * - re_process_buffer no longer writes the modified buffer
226 * to the client, which was very ugly. It now returns the
227 * buffer, which it is then written by chat.
229 * - content_length now adjusts the Content-Length: header
230 * for modified documents rather than crunch()ing it.
231 * (Length info in csp->content_length, which is 0 for
232 * unmodified documents)
234 * - For this to work, sed() is called twice when filtering.
236 * Revision 1.11 2001/05/26 17:27:53 jongfoster
237 * Added support for CLF and fixed LOG_LEVEL_LOG.
238 * Also did CRLF->LF fix of my previous patch.
240 * Revision 1.10 2001/05/26 15:26:15 jongfoster
241 * ACL feature now provides more security by immediately dropping
242 * connections from untrusted hosts.
244 * Revision 1.9 2001/05/26 00:28:36 jongfoster
245 * Automatic reloading of config file.
246 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
247 * Most of the global variables have been moved to a new
248 * struct configuration_spec, accessed through csp->config->globalname
249 * Most of the globals remaining are used by the Win32 GUI.
251 * Revision 1.8 2001/05/25 22:43:18 jongfoster
252 * Fixing minor memory leak and buffer overflow.
254 * Revision 1.7 2001/05/25 22:34:30 jongfoster
257 * Revision 1.6 2001/05/23 00:13:58 joergs
258 * AmigaOS support fixed.
260 * Revision 1.5 2001/05/22 18:46:04 oes
262 * - Enabled filtering banners by size rather than URL
263 * by adding patterns that replace all standard banner
264 * sizes with the "Junkbuster" gif to the re_filterfile
266 * - Enabled filtering WebBugs by providing a pattern
267 * which kills all 1x1 images
269 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
270 * which is selected by the (nonstandard and therefore
271 * capital) letter 'U' in the option string.
272 * It causes the quantifiers to be ungreedy by default.
273 * Appending a ? turns back to greedy (!).
275 * - Added a new interceptor ijb-send-banner, which
276 * sends back the "Junkbuster" gif. Without imagelist or
277 * MSIE detection support, or if tinygif = 1, or the
278 * URL isn't recognized as an imageurl, a lame HTML
279 * explanation is sent instead.
281 * - Added new feature, which permits blocking remote
282 * script redirects and firing back a local redirect
284 * The feature is conditionally compiled, i.e. it
285 * can be disabled with --disable-fast-redirects,
286 * plus it must be activated by a "fast-redirects"
287 * line in the config file, has its own log level
288 * and of course wants to be displayed by show-proxy-args
289 * Note: Boy, all the #ifdefs in 1001 locations and
290 * all the fumbling with configure.in and acconfig.h
291 * were *way* more work than the feature itself :-(
293 * - Because a generic redirect template was needed for
294 * this, tinygif = 3 now uses the same.
296 * - Moved GIFs, and other static HTTP response templates
301 * - Removed some >400 CRs again (Jon, you really worked
304 * Revision 1.4 2001/05/21 19:34:01 jongfoster
305 * Made failure to bind() a fatal error.
307 * Revision 1.3 2001/05/20 01:21:20 jongfoster
308 * Version 2.9.4 checkin.
309 * - Merged popupfile and cookiefile, and added control over PCRS
310 * filtering, in new "permissionsfile".
311 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
312 * file error you now get a message box (in the Win32 GUI) rather
313 * than the program exiting with no explanation.
314 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
316 * - Removed tabs from "config"
317 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
318 * - Bumped up version number.
320 * Revision 1.2 2001/05/17 22:34:44 oes
321 * - Added hint on GIF char array generation to jcc.c
322 * - Cleaned CRLF's from the sources and related files
323 * - Repaired logging for REF and FRC
325 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
326 * Initial import of version 2.9.3 source tree
329 *********************************************************************/
335 #include <sys/types.h>
342 #ifdef FEATURE_PTHREAD
344 #endif /* def FEATURE_PTHREAD */
347 # ifndef FEATURE_PTHREAD
348 # include <windows.h>
349 # include <process.h>
350 # endif /* ndef FEATURE_PTHREAD */
353 # ifndef _WIN_CONSOLE
355 # endif /* ndef _WIN_CONSOLE */
357 #else /* ifndef _WIN32 */
360 # include <sys/time.h>
361 # include <sys/wait.h>
362 # include <sys/stat.h>
366 # include <socket.h> /* BeOS has select() for sockets only. */
367 # include <OS.h> /* declarations for threads and stuff. */
371 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
386 #include "killpopup.h"
387 #include "miscutil.h"
389 #include "jbsockets.h"
395 const char jcc_h_rcs[] = JCC_H_VERSION;
396 const char project_h_rcs[] = PROJECT_H_VERSION;
398 struct client_state clients[1];
399 struct file_list files[1];
401 #ifdef FEATURE_STATISTICS
402 int urls_read = 0; /* total nr of urls read inc rejected */
403 int urls_rejected = 0; /* total nr of urls rejected */
404 #endif /* def FEATURE_STATISTICS */
407 static void listen_loop(void);
408 static void chat(struct client_state *csp);
410 void serve(struct client_state *csp);
411 #else /* ifndef AMIGA */
412 static void serve(struct client_state *csp);
413 #endif /* def AMIGA */
416 static int32 server_thread(void *data);
417 #endif /* def __BEOS__ */
420 #define sleep(N) Sleep(((N) * 1000))
424 /* The vanilla wafer. */
425 static const char VANILLA_WAFER[] =
426 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
427 "Do_not_send_me_any_copyrighted_information_other_than_the_"
428 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
429 "In_particular_do_not_send_me_any_cookies_that_"
430 "are_subject_to_a_claim_of_copyright_by_anybody._"
431 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
432 "(copyright_or_otherwise)_applying_to_any_cookie._";
435 /*********************************************************************
439 * Description : Once a connection to the client has been accepted,
440 * this function is called (via serve()) to handle the
441 * main business of the communication. When this
442 * function returns, the caller must close the client
446 * 1 : csp = Current client state (buffers, headers, etc...)
448 * Returns : On success, the number of bytes written are returned (zero
449 * indicates nothing was written). On error, -1 is returned,
450 * and errno is set appropriately. If count is zero and the
451 * file descriptor refers to a regular file, 0 will be
452 * returned without causing any other effect. For a special
453 * file, the results are not portable.
455 *********************************************************************/
456 static void chat(struct client_state *csp)
459 * This next lines are a little ugly, but they simplifies the if statements
460 * below. Basically if TOGGLE, then we want the if to test if the
461 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
462 * then we want the if to test for CSP_FLAG_FORCED , else we don't
464 #ifdef FEATURE_TOGGLE
465 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
466 #else /* ifndef FEATURE_TOGGLE */
467 # define IS_TOGGLED_ON_AND
468 #endif /* ndef FEATURE_TOGGLE */
469 #ifdef FEATURE_FORCE_LOAD
470 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
471 #else /* ifndef FEATURE_FORCE_LOAD */
472 # define IS_NOT_FORCED_AND
473 #endif /* def FEATURE_FORCE_LOAD */
475 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
477 char buf[BUFFER_SIZE];
480 int n, maxfd, server_body;
481 int ms_iis5_hack = 0;
483 const struct forward_spec * fwd;
484 struct http_request *http;
485 #ifdef FEATURE_KILL_POPUPS
486 int block_popups; /* bool, 1==will block popups */
487 int block_popups_now = 0; /* bool, 1==currently blocking popups */
488 #endif /* def FEATURE_KILL_POPUPS */
490 int pcrs_filter; /* bool, 1==will filter through pcrs */
491 int gif_deanimate; /* bool, 1==will deanimate gifs */
493 /* Function that does the content filtering for the current request */
494 char *(*content_filter)() = NULL;
496 /* Skeleton for HTTP response, if we should intercept the request */
497 struct http_response *rsp;
502 * Read the client's request. Note that since we're not using select() we
503 * could get blocked here if a client connected, then didn't say anything!
508 n = read_socket(csp->cfd, buf, sizeof(buf));
510 if (n <= 0) break; /* error! */
512 add_to_iob(csp, buf, n);
514 req = get_header(csp);
518 break; /* no HTTP request! */
523 continue; /* more to come! */
526 #ifdef FEATURE_FORCE_LOAD
527 /* If this request contains the FORCE_PREFIX,
528 * better get rid of it now and set the force flag --oes
531 if (strstr(req, FORCE_PREFIX))
533 strclean(req, FORCE_PREFIX);
534 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
535 csp->flags |= CSP_FLAG_FORCED;
538 #endif /* def FEATURE_FORCE_LOAD */
540 parse_http_request(req, http, csp);
545 if (http->cmd == NULL)
547 strcpy(buf, CHEADER);
548 write_socket(csp->cfd, buf, strlen(buf));
550 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
555 /* decide how to route the HTTP request */
557 if ((fwd = forward_url(http, csp)) == NULL)
559 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
560 /* Never get here - LOG_LEVEL_FATAL causes program exit */
563 /* build the http request to send to the server
564 * we have to do one of the following:
566 * create = use the original HTTP request to create a new
567 * HTTP request that has either the path component
568 * without the http://domainspec (w/path) or the
569 * full orininal URL (w/url)
570 * Note that the path and/or the HTTP version may
571 * have been altered by now.
573 * connect = Open a socket to the host:port of the server
574 * and short-circuit server and client socket.
576 * pass = Pass the request unchanged if forwarding a CONNECT
577 * request to a parent proxy. Note that we'll be sending
578 * the CFAIL message ourselves if connecting to the parent
579 * fails, but we won't send a CSUCCEED message if it works,
580 * since that would result in a double message (ours and the
581 * parent's). After sending the request to the parent, we simply
587 * +--------+--------+
589 * 0 | create | connect|
591 * Forwarding +--------+--------+
593 * 1 | create | pass |
595 * +--------+--------+
600 * Determine the actions for this URL
602 #ifdef FEATURE_TOGGLE
603 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
605 /* Most compatible set of actions (i.e. none) */
606 init_current_action(csp->action);
609 #endif /* ndef FEATURE_TOGGLE */
611 url_actions(http, csp);
616 * Check if a CONNECT request is allowable:
617 * In the absence of a +limit-connect action, allow only port 443.
618 * If there is an action, allow whatever matches the specificaton.
622 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
623 || (csp->action->flags & ACTION_LIMIT_CONNECT
624 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
626 strcpy(buf, CFORBIDDEN);
627 write_socket(csp->cfd, buf, strlen(buf));
629 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
630 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
638 * Downgrade http version from 1.1 to 1.0 if +downgrade
641 if (!strcmpic(http->ver, "HTTP/1.1") && csp->action->flags & ACTION_DOWNGRADE)
644 http->ver = strdup("HTTP/1.0");
648 * (Re)build the HTTP request for non-SSL requests.
649 * If forwarding, use the whole URL, else, use only the path.
655 http->cmd = strsav(http->cmd, http->gpc);
656 http->cmd = strsav(http->cmd, " ");
658 if (fwd->forward_host)
660 http->cmd = strsav(http->cmd, http->url);
664 http->cmd = strsav(http->cmd, http->path);
667 http->cmd = strsav(http->cmd, " ");
668 http->cmd = strsav(http->cmd, http->ver);
671 enlist(csp->headers, http->cmd);
674 #ifdef FEATURE_COOKIE_JAR
676 * If we're logging cookies in a cookie jar, and the user has not
677 * supplied any wafers, and the user has not told us to suppress the
678 * vanilla wafer, then send the vanilla wafer.
680 if ((csp->config->jarfile != NULL)
681 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
682 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
684 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
686 #endif /* def FEATURE_COOKIE_JAR */
689 #ifdef FEATURE_KILL_POPUPS
690 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
691 #endif /* def FEATURE_KILL_POPUPS */
693 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
694 ((csp->action->flags & ACTION_FILTER) != 0);
696 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
698 /* grab the rest of the client's headers */
702 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
704 n = read_socket(csp->cfd, buf, sizeof(buf));
707 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
710 add_to_iob(csp, buf, n);
714 if (p == NULL) break;
716 enlist(csp->headers, p);
720 /* We have a request. */
723 * Now, check to see if we need to intercept it, i.e.
728 /* a CGI call was detected and answered */
729 (NULL != (rsp = dispatch_cgi(csp)))
731 /* or we are enabled and... */
734 /* ..the request was blocked */
735 ( NULL != (rsp = block_url(csp)))
739 || ( NULL != (rsp = trust_url(csp)))
740 #endif /* def FEATURE_TRUST */
742 /* ..or a fast redirect kicked in */
743 #ifdef FEATURE_FAST_REDIRECTS
744 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
745 (NULL != (rsp = redirect_url(csp))))
746 #endif /* def FEATURE_FAST_REDIRECTS */
750 /* Write the answer to the client */
751 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
752 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
754 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
757 #ifdef FEATURE_STATISTICS
758 /* Count as a rejected request */
759 csp->flags |= CSP_FLAG_REJECTED;
760 #endif /* def FEATURE_STATISTICS */
762 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
763 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
764 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
766 /* Clean up and return */
767 free_http_response(rsp);
771 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
773 if (fwd->forward_host)
775 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
776 fwd->forward_host, fwd->forward_port, http->hostport);
780 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
783 /* here we connect to the server, gateway, or the forwarder */
785 csp->sfd = forwarded_connect(fwd, http, csp);
789 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
794 rsp = error_response(csp, "no-such-domain", errno);
796 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
797 csp->ip_addr_str, http->cmd);
801 rsp = error_response(csp, "connect-failed", errno);
803 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
804 csp->ip_addr_str, http->cmd);
807 /* Write the answer to the client */
810 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
811 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
813 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
817 free_http_response(rsp);
821 log_error(LOG_LEVEL_CONNECT, "OK");
823 hdr = sed(client_patterns, add_client_headers, csp);
824 list_remove_all(csp->headers);
826 if (fwd->forward_host || (http->ssl == 0))
828 /* write the client's (modified) header to the server
829 * (along with anything else that may be in the buffer)
834 if ((write_socket(csp->sfd, hdr, n) != n)
835 || (flush_socket(csp->sfd, csp ) < 0))
837 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
840 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
841 csp->ip_addr_str, http->cmd);
843 rsp = error_response(csp, "connect-failed", errno);
847 if ((write_socket(csp->cfd, rsp->head, n) != n)
848 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
850 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
854 free_http_response(rsp);
862 * We're running an SSL tunnel and we're not forwarding,
863 * so just send the "connect succeeded" message to the
864 * client, flush the rest, and get out of the way.
866 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
867 csp->ip_addr_str, http->cmd);
869 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
877 /* we're finished with the client's header */
880 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
882 /* pass data between the client and server
883 * until one or the other shuts down the connection.
892 FD_SET(csp->cfd, &rfds);
893 FD_SET(csp->sfd, &rfds);
895 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
899 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
903 /* this is the body of the browser's request
904 * just read it and write it.
907 if (FD_ISSET(csp->cfd, &rfds))
909 n = read_socket(csp->cfd, buf, sizeof(buf));
913 break; /* "game over, man" */
916 if (write_socket(csp->sfd, buf, n) != n)
918 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
925 * The server wants to talk. It could be the header or the body.
926 * If `hdr' is null, then it's the header otherwise it's the body.
927 * FIXME: Does `hdr' really mean `host'? No.
931 if (FD_ISSET(csp->sfd, &rfds))
934 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
938 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
940 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
941 csp->ip_addr_str, http->cmd);
943 rsp = error_response(csp, "connect-failed", errno);
947 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
948 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
950 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
954 free_http_response(rsp);
958 /* Add a trailing zero. This lets filter_popups
959 * use string operations.
963 #ifdef FEATURE_KILL_POPUPS
964 /* Filter the popups on this read. */
965 if (block_popups_now)
967 filter_popups(buf, csp);
969 #endif /* def FEATURE_KILL_POPUPS */
971 /* Normally, this would indicate that we've read
972 * as much as the server has sent us and we can
973 * close the client connection. However, Microsoft
974 * in its wisdom has released IIS/5 with a bug that
975 * prevents it from sending the trailing \r\n in
976 * a 302 redirect header (and possibly other headers).
977 * To work around this if we've haven't parsed
978 * a full header we'll append a trailing \r\n
979 * and see if this now generates a valid one.
981 * This hack shouldn't have any impacts. If we've
982 * already transmitted the header or if this is a
983 * SSL connection, then we won't bother with this
984 * hack. So we only work on partially received
985 * headers. If we append a \r\n and this still
986 * doesn't generate a valid header, then we won't
987 * transmit anything to the client.
992 if (server_body || http->ssl)
995 * If we have been buffering up the document,
996 * now is the time to apply content modification
997 * and send the result to the client.
1002 * If the content filter fails, use the original
1003 * buffer and length.
1004 * (see p != NULL ? p : csp->iob->cur below)
1006 if (NULL == (p = (*content_filter)(csp)))
1008 csp->content_length = csp->iob->eod - csp->iob->cur;
1011 hdr = sed(server_patterns, add_server_headers, csp);
1014 if ((write_socket(csp->cfd, hdr, n) != n)
1015 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1017 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1027 break; /* "game over, man" */
1031 * This is NOT the body, so
1032 * Let's pretend the server just sent us a blank line.
1034 n = sprintf(buf, "\r\n");
1037 * Now, let the normal header parsing algorithm below do its
1038 * job. If it fails, we'll exit instead of continuing.
1045 * If this is an SSL connection or we're in the body
1046 * of the server document, just write it to the client,
1047 * unless we need to buffer the body for later content-filtering
1050 if (server_body || http->ssl)
1054 add_to_iob(csp, buf, n);
1057 * If the buffer limit will be reached on the next read,
1058 * switch to non-filtering mode, i.e. make & write the
1059 * header, flush the socket and get out of the way.
1061 if (csp->iob->eod - csp->iob->buf + BUFFER_SIZE > csp->config->buffer_limit)
1063 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1065 hdr = sed(server_patterns, add_server_headers, csp);
1069 if (((write_socket(csp->cfd, hdr, n) != n)
1070 || (n = flush_socket(csp->cfd, csp) < 0)))
1072 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1081 content_filter = NULL;
1088 if (write_socket(csp->cfd, buf, n) != n)
1090 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1099 /* we're still looking for the end of the
1100 * server's header ... (does that make header
1101 * parsing an "out of body experience" ?
1104 /* buffer up the data we just read */
1105 add_to_iob(csp, buf, n);
1107 /* get header lines from the iob */
1109 while ((p = get_header(csp)))
1113 /* see following note */
1116 enlist(csp->headers, p);
1120 /* NOTE: there are no "empty" headers so
1121 * if the pointer `p' is not NULL we must
1122 * assume that we reached the end of the
1123 * buffer before we hit the end of the header.
1130 /* Well, we tried our MS IIS/5
1131 * hack and it didn't work.
1132 * The header is incomplete
1133 * and there isn't anything
1134 * we can do about it.
1140 /* Since we have to wait for
1141 * more from the server before
1142 * we can parse the headers
1143 * we just continue here.
1149 /* we have now received the entire header.
1150 * filter it and send the result to the client
1153 hdr = sed(server_patterns, add_server_headers, csp);
1156 /* write the server's (modified) header to
1157 * the client (along with anything else that
1158 * may be in the buffer)
1161 #ifdef FEATURE_KILL_POPUPS
1162 /* Start blocking popups if appropriate. */
1164 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1165 !http->ssl && /* We talk plaintext */
1166 block_popups) /* Policy allows */
1168 block_popups_now = 1;
1170 * Filter the part of the body that came in the same read
1171 * as the last headers:
1173 filter_popups(csp->iob->cur, csp);
1176 #endif /* def FEATURE_KILL_POPUPS */
1178 /* Buffer and pcrs filter this if appropriate. */
1180 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1181 !http->ssl && /* We talk plaintext */
1182 pcrs_filter) /* Policy allows */
1184 content_filter = pcrs_filter_response;
1187 /* Buffer and gif_deanimate this if appropriate. */
1189 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1190 !http->ssl && /* We talk plaintext */
1191 gif_deanimate) /* Policy allows */
1193 content_filter = gif_deanimate_response;
1198 * Only write if we're not buffering for content modification
1200 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1201 || (n = flush_socket(csp->cfd, csp) < 0)))
1203 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1205 /* the write failed, so don't bother
1206 * mentioning it to the client...
1207 * it probably can't hear us anyway.
1213 if(!content_filter) byte_count += n;
1215 /* we're finished with the server's header */
1220 /* If this was a MS IIS/5 hack then it means
1221 * the server has already closed the
1222 * connection. Nothing more to read. Time
1233 return; /* huh? we should never get here */
1236 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1237 csp->ip_addr_str, http->cmd, byte_count);
1241 /*********************************************************************
1245 * Description : This is little more than chat. We only "serve" to
1246 * to close any socket that chat may have opened.
1249 * 1 : csp = Current client state (buffers, headers, etc...)
1253 *********************************************************************/
1255 void serve(struct client_state *csp)
1256 #else /* ifndef AMIGA */
1257 static void serve(struct client_state *csp)
1258 #endif /* def AMIGA */
1261 close_socket(csp->cfd);
1265 close_socket(csp->sfd);
1268 csp->flags &= ~CSP_FLAG_ACTIVE;
1274 /*********************************************************************
1276 * Function : server_thread
1278 * Description : We only exist to call `serve' in a threaded environment.
1281 * 1 : data = Current client state (buffers, headers, etc...)
1283 * Returns : Always 0.
1285 *********************************************************************/
1286 static int32 server_thread(void *data)
1288 serve((struct client_state *) data);
1295 /*********************************************************************
1299 * Description : Load the config file and start the listen loop.
1300 * This function is a lot more *sane* with the `load_config'
1301 * and `listen_loop' functions; although it stills does
1302 * a *little* too much for my taste.
1305 * 1 : argc = Number of parameters (including $0).
1306 * 2 : argv = Array of (char *)'s to the parameters.
1308 * Returns : 1 if : can't open config file, unrecognized directive,
1309 * stats requested in multi-thread mode, can't open the
1310 * log file, can't open the jar file, listen port is invalid,
1311 * any load fails, and can't bind port.
1313 * Else main never returns, the process must be signaled
1314 * to terminate execution. Or, on Windows, use the
1315 * "File", "Exit" menu option.
1317 *********************************************************************/
1319 int real_main(int argc, const char *argv[])
1321 int main(int argc, const char *argv[])
1326 "AmiTCP:db/junkbuster/config"
1327 #elif !defined(_WIN32)
1334 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1335 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1337 printf("JunkBuster proxy version " VERSION ".\n\n"
1338 "Usage: %s [configfile]\n\n"
1339 "See " HOME_PAGE_URL " for details.\n"
1340 "This program is distributed under the GNU GPL, version 2 or later.\n",
1344 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1346 printf(VERSION "\n");
1349 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1356 configfile = argv[1];
1363 #elif defined(_WIN32)
1369 signal(SIGPIPE, SIG_IGN);
1370 signal(SIGCHLD, SIG_IGN);
1372 #else /* ifdef _WIN32 */
1373 # ifdef _WIN_CONSOLE
1375 * We *are* in a windows console app.
1376 * Print a verbose messages about FAQ's and such
1378 printf(win32_blurb);
1379 # endif /* def _WIN_CONSOLE */
1380 #endif /* def _WIN32 */
1391 /*********************************************************************
1393 * Function : listen_loop
1395 * Description : bind the listen port and enter a "FOREVER" listening loop.
1401 *********************************************************************/
1402 static void listen_loop(void)
1404 struct client_state *csp = NULL;
1406 struct configuration_spec * config;
1408 config = load_config();
1410 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1411 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1413 bfd = bind_port(config->haddr, config->hport);
1417 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1418 "- There may be another junkbuster or some other "
1419 "proxy running on port %d",
1420 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1421 config->hport, config->hport
1423 /* shouldn't get here */
1427 config->need_bind = 0;
1432 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1433 while (waitpid(-1, NULL, WNOHANG) > 0)
1435 /* zombie children */
1437 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1440 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1442 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1446 csp->flags |= CSP_FLAG_ACTIVE;
1449 csp->config = config = load_config();
1451 if ( config->need_bind )
1454 * Since we were listening to the "old port", we will not see
1455 * a "listen" param change until the next IJB request. So, at
1456 * least 1 more request must be made for us to find the new
1457 * setting. I am simply closing the old socket and binding the
1460 * Which-ever is correct, we will serve 1 more page via the
1461 * old settings. This should probably be a "show-proxy-args"
1462 * request. This should not be a so common of an operation
1463 * that this will hurt people's feelings.
1468 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1469 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1470 bfd = bind_port(config->haddr, config->hport);
1474 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1475 "- There may be another junkbuster or some other "
1476 "proxy running on port %d",
1477 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1478 config->hport, config->hport
1480 /* shouldn't get here */
1484 config->need_bind = 0;
1487 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1489 if (!accept_connection(csp, bfd))
1491 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1504 log_error(LOG_LEVEL_CONNECT, "OK");
1507 #ifdef FEATURE_TOGGLE
1510 csp->flags |= CSP_FLAG_TOGGLED_ON;
1512 #endif /* def FEATURE_TOGGLE */
1514 if (run_loader(csp))
1516 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1517 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1521 if (block_acl(NULL,csp))
1523 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1524 close_socket(csp->cfd);
1528 #endif /* def FEATURE_ACL */
1530 /* add it to the list of clients */
1531 csp->next = clients->next;
1532 clients->next = csp;
1534 if (config->multi_threaded)
1538 /* this is a switch () statment in the C preprocessor - ugh */
1539 #undef SELECTED_ONE_OPTION
1541 /* Use Pthreads in preference to native code */
1542 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1543 #define SELECTED_ONE_OPTION
1545 pthread_t the_thread;
1546 pthread_attr_t attrs;
1548 pthread_attr_init(&attrs);
1549 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1550 child_id = (pthread_create(&the_thread, &attrs,
1551 (void*)serve, csp) ? -1 : 0);
1552 pthread_attr_destroy(&attrs);
1556 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1557 #define SELECTED_ONE_OPTION
1558 child_id = _beginthread(
1564 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1565 #define SELECTED_ONE_OPTION
1567 thread_id tid = spawn_thread
1568 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1570 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1572 child_id = (int) tid;
1581 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1582 #define SELECTED_ONE_OPTION
1583 csp->cfd = ReleaseSocket(csp->cfd, -1);
1584 if((child_id = (int)CreateNewProcTags(
1585 NP_Entry, (ULONG)server_thread,
1586 NP_Output, Output(),
1587 NP_CloseOutput, FALSE,
1588 NP_Name, (ULONG)"junkbuster child",
1589 NP_StackSize, 200*1024,
1593 ((struct Task *)child_id)->tc_UserData = csp;
1594 Signal((struct Task *)child_id, SIGF_SINGLE);
1599 #if !defined(SELECTED_ONE_OPTION)
1602 /* This block is only needed when using fork().
1603 * When using threads, the server thread was
1604 * created and run by the call to _beginthread().
1606 if (child_id == 0) /* child */
1612 else if (child_id > 0) /* parent */
1614 /* in a fork()'d environment, the parent's
1615 * copy of the client socket and the CSP
1619 #if !defined(_WIN32) && defined(__CYGWIN__)
1621 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1622 close_socket(csp->cfd);
1623 csp->flags &= ~CSP_FLAG_ACTIVE;
1627 #undef SELECTED_ONE_OPTION
1628 /* end of cpp switch () */
1630 if (child_id < 0) /* failed */
1632 char buf[BUFFER_SIZE];
1634 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1636 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1638 write_socket(csp->cfd, buf, strlen(buf));
1639 close_socket(csp->cfd);
1640 csp->flags &= ~CSP_FLAG_ACTIVE;