1 const char jcc_rcs[] = "$Id: jcc.c,v 1.46 2001/10/08 15:17:41 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.46 2001/10/08 15:17:41 oes
37 * Re-enabled SSL forwarding
39 * Revision 1.45 2001/10/07 15:42:11 oes
40 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
42 * Moved downgrading of the HTTP version from parse_http_request to
43 * chat(), since we can't decide if it is necessary before we have
44 * determined the actions for the URL. The HTTP command is now
45 * *always* re-built so the repairs need no longer be special-cased.
47 * filter_popups now gets a csp pointer so it can raise the new
48 * CSP_FLAG_MODIFIED flag.
52 * Added configurable size limit for the IOB. If the IOB grows so
53 * large that the next read would exceed the limit, the header
54 * is generated, and the header & unfiltered buffer are flushed
55 * to the client. Chat then continues in non-buffering,
56 * non-filtering body mode.
58 * Revision 1.44 2001/10/02 18:13:57 oes
61 * Revision 1.43 2001/10/02 15:32:13 oes
62 * Moved generation of hdr
64 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
65 * Cleaning up 2 compiler warnings on OS/2.
67 * Revision 1.41 2001/09/16 17:05:14 jongfoster
68 * Removing unused #include showarg.h
70 * Revision 1.40 2001/09/16 15:41:45 jongfoster
71 * Fixing signed/unsigned comparison warning.
73 * Revision 1.39 2001/09/16 13:21:27 jongfoster
74 * Changes to use new list functions.
76 * Revision 1.38 2001/09/16 13:01:46 jongfoster
77 * Removing redundant function call that zeroed zalloc()'d memory.
79 * Revision 1.37 2001/09/10 11:12:24 oes
80 * Deleted unused variable
82 * Revision 1.36 2001/09/10 10:56:15 oes
83 * Silenced compiler warnings
85 * Revision 1.35 2001/07/31 14:44:22 oes
86 * Deleted unused size parameter from filter_popups()
88 * Revision 1.34 2001/07/30 22:08:36 jongfoster
89 * Tidying up #defines:
90 * - All feature #defines are now of the form FEATURE_xxx
91 * - Permanently turned off WIN_GUI_EDIT
92 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
94 * Revision 1.33 2001/07/29 19:32:00 jongfoster
95 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
97 * Revision 1.32 2001/07/29 18:47:05 jongfoster
98 * Adding missing #include "loadcfg.h"
100 * Revision 1.31 2001/07/29 12:17:48 oes
101 * Applied pthread fix by Paul Lieverse
103 * Revision 1.30 2001/07/25 22:57:13 jongfoster
104 * __BEOS__ no longer overrides FEATURE_PTHREAD.
105 * This is because FEATURE_PTHREAD will soon be widely used, so I
106 * want to keep it simple.
108 * Revision 1.29 2001/07/24 12:47:06 oes
109 * Applied BeOS support update by Eugenia
111 * Revision 1.28 2001/07/23 13:26:12 oes
112 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
114 * Revision 1.27 2001/07/19 19:09:47 haroon
115 * - Added code to take care of the situation where while processing the first
116 * server response (which includes the server header), after finding the end
117 * of the headers we were not looking past the end of the headers for
118 * content modification. I enabled it for filter_popups.
119 * Someone else should look to see if other similar operations should be
120 * done to the discarded portion of the buffer.
122 * Note 2001/07/20: No, the other content modification mechanisms will process
123 * the whole iob later anyway. --oes
125 * Revision 1.26 2001/07/18 12:31:36 oes
128 * Revision 1.25 2001/07/15 19:43:49 jongfoster
129 * Supports POSIX threads.
130 * Also removed some unused #includes.
132 * Revision 1.24 2001/07/13 14:00:40 oes
133 * - Generic content modification scheme:
134 * Each feature has its own applicability flag that is set
135 * from csp->action->flags.
136 * Replaced the "filtering" int flag , by a function pointer
137 * "content_filter" to the function that will do the content
138 * modification. If it is != NULL, the document will be buffered
139 * and processed through *content_filter, which must set
140 * csp->content_length and return a modified copy of the body
141 * or return NULL (on failiure).
142 * - Changed csp->is_text to the more generic bitmap csp->content_type
143 * which can currently take the valued CT_TEXT or CT_GIF
145 * - Removed all #ifdef PCRS
147 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
148 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
149 * the `block_acl' call. This prevents a compilation error when the user
150 * does not wish to use the "ACL" feature.
152 * Revision 1.22 2001/06/29 21:45:41 oes
153 * Indentation, CRLF->LF, Tab-> Space
155 * Revision 1.21 2001/06/29 13:29:36 oes
156 * - Cleaned up, improved comments
157 * - Unified all possible interceptors (CGI,
158 * block, trust, fast_redirect) in one
159 * place, with one (CGI) answer generation
160 * mechansim. Much clearer now.
161 * - Removed the GIF image generation, which
162 * is now done in filters.c:block_url()
163 * - Made error conditions like domain lookup
164 * failiure or (various) problems while talking
165 * to the server use cgi.c:error_response()
166 * instead of generating HTML/HTTP in chat() (yuck!)
167 * - Removed logentry from cancelled commit
169 * Revision 1.20 2001/06/09 10:55:28 jongfoster
170 * Changing BUFSIZ ==> BUFFER_SIZE
172 * Revision 1.19 2001/06/07 23:12:52 jongfoster
173 * Replacing function pointer in struct gateway with a directly
174 * called function forwarded_connect().
175 * Replacing struct gateway with struct forward_spec
177 * Revision 1.18 2001/06/03 19:12:16 oes
178 * introduced new cgi handling
180 * Revision 1.17 2001/06/01 20:07:23 jongfoster
181 * Now uses action +image-blocker{} rather than config->tinygif
183 * Revision 1.16 2001/06/01 18:49:17 jongfoster
184 * Replaced "list_share" with "list" - the tiny memory gain was not
185 * worth the extra complexity.
187 * Revision 1.15 2001/05/31 21:24:47 jongfoster
188 * Changed "permission" to "action" throughout.
189 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
190 * Moved vanilla wafer check into chat(), since we must now
191 * decide whether or not to add it based on the URL.
193 * Revision 1.14 2001/05/29 20:14:01 joergs
194 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
197 * Revision 1.13 2001/05/29 09:50:24 jongfoster
198 * Unified blocklist/imagelist/permissionslist.
199 * File format is still under discussion, but the internal changes
202 * Also modified interceptor behaviour:
203 * - We now intercept all URLs beginning with one of the following
204 * prefixes (and *only* these prefixes):
206 * * http://ijbswa.sf.net/config/
207 * * http://ijbswa.sourceforge.net/config/
208 * - New interceptors "home page" - go to http://i.j.b/ to see it.
209 * - Internal changes so that intercepted and fast redirect pages
210 * are not replaced with an image.
211 * - Interceptors now have the option to send a binary page direct
212 * to the client. (i.e. ijb-send-banner uses this)
213 * - Implemented show-url-info interceptor. (Which is why I needed
214 * the above interceptors changes - a typical URL is
215 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
216 * The previous mechanism would not have intercepted that, and
217 * if it had been intercepted then it then it would have replaced
220 * Revision 1.12 2001/05/27 22:17:04 oes
222 * - re_process_buffer no longer writes the modified buffer
223 * to the client, which was very ugly. It now returns the
224 * buffer, which it is then written by chat.
226 * - content_length now adjusts the Content-Length: header
227 * for modified documents rather than crunch()ing it.
228 * (Length info in csp->content_length, which is 0 for
229 * unmodified documents)
231 * - For this to work, sed() is called twice when filtering.
233 * Revision 1.11 2001/05/26 17:27:53 jongfoster
234 * Added support for CLF and fixed LOG_LEVEL_LOG.
235 * Also did CRLF->LF fix of my previous patch.
237 * Revision 1.10 2001/05/26 15:26:15 jongfoster
238 * ACL feature now provides more security by immediately dropping
239 * connections from untrusted hosts.
241 * Revision 1.9 2001/05/26 00:28:36 jongfoster
242 * Automatic reloading of config file.
243 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
244 * Most of the global variables have been moved to a new
245 * struct configuration_spec, accessed through csp->config->globalname
246 * Most of the globals remaining are used by the Win32 GUI.
248 * Revision 1.8 2001/05/25 22:43:18 jongfoster
249 * Fixing minor memory leak and buffer overflow.
251 * Revision 1.7 2001/05/25 22:34:30 jongfoster
254 * Revision 1.6 2001/05/23 00:13:58 joergs
255 * AmigaOS support fixed.
257 * Revision 1.5 2001/05/22 18:46:04 oes
259 * - Enabled filtering banners by size rather than URL
260 * by adding patterns that replace all standard banner
261 * sizes with the "Junkbuster" gif to the re_filterfile
263 * - Enabled filtering WebBugs by providing a pattern
264 * which kills all 1x1 images
266 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
267 * which is selected by the (nonstandard and therefore
268 * capital) letter 'U' in the option string.
269 * It causes the quantifiers to be ungreedy by default.
270 * Appending a ? turns back to greedy (!).
272 * - Added a new interceptor ijb-send-banner, which
273 * sends back the "Junkbuster" gif. Without imagelist or
274 * MSIE detection support, or if tinygif = 1, or the
275 * URL isn't recognized as an imageurl, a lame HTML
276 * explanation is sent instead.
278 * - Added new feature, which permits blocking remote
279 * script redirects and firing back a local redirect
281 * The feature is conditionally compiled, i.e. it
282 * can be disabled with --disable-fast-redirects,
283 * plus it must be activated by a "fast-redirects"
284 * line in the config file, has its own log level
285 * and of course wants to be displayed by show-proxy-args
286 * Note: Boy, all the #ifdefs in 1001 locations and
287 * all the fumbling with configure.in and acconfig.h
288 * were *way* more work than the feature itself :-(
290 * - Because a generic redirect template was needed for
291 * this, tinygif = 3 now uses the same.
293 * - Moved GIFs, and other static HTTP response templates
298 * - Removed some >400 CRs again (Jon, you really worked
301 * Revision 1.4 2001/05/21 19:34:01 jongfoster
302 * Made failure to bind() a fatal error.
304 * Revision 1.3 2001/05/20 01:21:20 jongfoster
305 * Version 2.9.4 checkin.
306 * - Merged popupfile and cookiefile, and added control over PCRS
307 * filtering, in new "permissionsfile".
308 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
309 * file error you now get a message box (in the Win32 GUI) rather
310 * than the program exiting with no explanation.
311 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
313 * - Removed tabs from "config"
314 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
315 * - Bumped up version number.
317 * Revision 1.2 2001/05/17 22:34:44 oes
318 * - Added hint on GIF char array generation to jcc.c
319 * - Cleaned CRLF's from the sources and related files
320 * - Repaired logging for REF and FRC
322 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
323 * Initial import of version 2.9.3 source tree
326 *********************************************************************/
332 #include <sys/types.h>
339 #ifdef FEATURE_PTHREAD
341 #endif /* def FEATURE_PTHREAD */
344 # ifndef FEATURE_PTHREAD
345 # include <windows.h>
346 # include <process.h>
347 # endif /* ndef FEATURE_PTHREAD */
350 # ifndef _WIN_CONSOLE
352 # endif /* ndef _WIN_CONSOLE */
354 #else /* ifndef _WIN32 */
357 # include <sys/time.h>
358 # include <sys/wait.h>
359 # include <sys/stat.h>
363 # include <socket.h> /* BeOS has select() for sockets only. */
364 # include <OS.h> /* declarations for threads and stuff. */
368 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
383 #include "killpopup.h"
384 #include "miscutil.h"
386 #include "jbsockets.h"
392 const char jcc_h_rcs[] = JCC_H_VERSION;
393 const char project_h_rcs[] = PROJECT_H_VERSION;
395 struct client_state clients[1];
396 struct file_list files[1];
398 #ifdef FEATURE_STATISTICS
399 int urls_read = 0; /* total nr of urls read inc rejected */
400 int urls_rejected = 0; /* total nr of urls rejected */
401 #endif /* def FEATURE_STATISTICS */
404 static void listen_loop(void);
405 static void chat(struct client_state *csp);
407 void serve(struct client_state *csp);
408 #else /* ifndef AMIGA */
409 static void serve(struct client_state *csp);
410 #endif /* def AMIGA */
413 static int32 server_thread(void *data);
414 #endif /* def __BEOS__ */
417 #define sleep(N) Sleep(((N) * 1000))
421 /* The vanilla wafer. */
422 static const char VANILLA_WAFER[] =
423 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
424 "Do_not_send_me_any_copyrighted_information_other_than_the_"
425 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
426 "In_particular_do_not_send_me_any_cookies_that_"
427 "are_subject_to_a_claim_of_copyright_by_anybody._"
428 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
429 "(copyright_or_otherwise)_applying_to_any_cookie._";
432 /*********************************************************************
436 * Description : Once a connection to the client has been accepted,
437 * this function is called (via serve()) to handle the
438 * main business of the communication. When this
439 * function returns, the caller must close the client
443 * 1 : csp = Current client state (buffers, headers, etc...)
445 * Returns : On success, the number of bytes written are returned (zero
446 * indicates nothing was written). On error, -1 is returned,
447 * and errno is set appropriately. If count is zero and the
448 * file descriptor refers to a regular file, 0 will be
449 * returned without causing any other effect. For a special
450 * file, the results are not portable.
452 *********************************************************************/
453 static void chat(struct client_state *csp)
456 * This next lines are a little ugly, but they simplifies the if statements
457 * below. Basically if TOGGLE, then we want the if to test if the
458 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
459 * then we want the if to test for CSP_FLAG_FORCED , else we don't
461 #ifdef FEATURE_TOGGLE
462 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
463 #else /* ifndef FEATURE_TOGGLE */
464 # define IS_TOGGLED_ON_AND
465 #endif /* ndef FEATURE_TOGGLE */
466 #ifdef FEATURE_FORCE_LOAD
467 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
468 #else /* ifndef FEATURE_FORCE_LOAD */
469 # define IS_NOT_FORCED_AND
470 #endif /* def FEATURE_FORCE_LOAD */
472 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
474 char buf[BUFFER_SIZE];
477 int n, maxfd, server_body;
478 int ms_iis5_hack = 0;
480 const struct forward_spec * fwd;
481 struct http_request *http;
482 #ifdef FEATURE_KILL_POPUPS
483 int block_popups; /* bool, 1==will block popups */
484 int block_popups_now = 0; /* bool, 1==currently blocking popups */
485 #endif /* def FEATURE_KILL_POPUPS */
487 int pcrs_filter; /* bool, 1==will filter through pcrs */
488 int gif_deanimate; /* bool, 1==will deanimate gifs */
490 /* Function that does the content filtering for the current request */
491 char *(*content_filter)() = NULL;
493 /* Skeleton for HTTP response, if we should intercept the request */
494 struct http_response *rsp;
499 * Read the client's request. Note that since we're not using select() we
500 * could get blocked here if a client connected, then didn't say anything!
505 n = read_socket(csp->cfd, buf, sizeof(buf));
507 if (n <= 0) break; /* error! */
509 add_to_iob(csp, buf, n);
511 req = get_header(csp);
515 break; /* no HTTP request! */
520 continue; /* more to come! */
523 #ifdef FEATURE_FORCE_LOAD
524 /* If this request contains the FORCE_PREFIX,
525 * better get rid of it now and set the force flag --oes
528 if (strstr(req, FORCE_PREFIX))
530 strclean(req, FORCE_PREFIX);
531 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
532 csp->flags |= CSP_FLAG_FORCED;
535 #endif /* def FEATURE_FORCE_LOAD */
537 parse_http_request(req, http, csp);
542 if (http->cmd == NULL)
544 strcpy(buf, CHEADER);
545 write_socket(csp->cfd, buf, strlen(buf));
547 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
552 /* decide how to route the HTTP request */
554 if ((fwd = forward_url(http, csp)) == NULL)
556 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
557 /* Never get here - LOG_LEVEL_FATAL causes program exit */
560 /* build the http request to send to the server
561 * we have to do one of the following:
563 * create = use the original HTTP request to create a new
564 * HTTP request that has either the path component
565 * without the http://domainspec (w/path) or the
566 * full orininal URL (w/url)
567 * Note that the path and/or the HTTP version may
568 * have been altered by now.
570 * connect = Open a socket to the host:port of the server
571 * and short-circuit server and client socket.
573 * pass = Pass the request unchanged if forwarding a CONNECT
574 * request to a parent proxy. Note that we'll be sending
575 * the CFAIL message ourselves if connecting to the parent
576 * fails, but we won't send a CSUCCEED message if it works,
577 * since that would result in a double message (ours and the
578 * parent's). After sending the request to the parent, we simply
584 * +--------+--------+
586 * 0 | create | connect|
588 * Forwarding +--------+--------+
590 * 1 | create | pass |
592 * +--------+--------+
597 * Determine the actions for this URL
599 #ifdef FEATURE_TOGGLE
600 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
602 /* Most compatible set of actions (i.e. none) */
603 init_current_action(csp->action);
606 #endif /* ndef FEATURE_TOGGLE */
608 url_actions(http, csp);
611 #ifdef FEATURE_COOKIE_JAR
614 * Check if a CONNECT request is allowable:
615 * In the absence of a +limit-connect action, allow only port 443.
616 * If there is an action, allow whatever matches the specificaton.
620 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
621 || (csp->action->flags & ACTION_LIMIT_CONNECT
622 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
624 strcpy(buf, CFORBIDDEN);
625 write_socket(csp->cfd, buf, strlen(buf));
627 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
628 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
636 * Downgrade http version from 1.1 to 1.0 if +downgrade
639 if (!strcmpic(http->ver, "HTTP/1.1") && csp->action->flags & ACTION_DOWNGRADE)
642 http->ver = strdup("HTTP/1.0");
646 * (Re)build the HTTP request for non-SSL requests.
647 * If forwarding, use the whole URL, else, use only the path.
653 http->cmd = strsav(http->cmd, http->gpc);
654 http->cmd = strsav(http->cmd, " ");
656 if (fwd->forward_host)
658 http->cmd = strsav(http->cmd, http->url);
662 http->cmd = strsav(http->cmd, http->path);
665 http->cmd = strsav(http->cmd, " ");
666 http->cmd = strsav(http->cmd, http->ver);
669 enlist(csp->headers, http->cmd);
673 * If we're logging cookies in a cookie jar, and the user has not
674 * supplied any wafers, and the user has not told us to suppress the
675 * vanilla wafer, then send the vanilla wafer.
677 if ((csp->config->jarfile != NULL)
678 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
679 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
681 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
683 #endif /* def FEATURE_COOKIE_JAR */
685 #ifdef FEATURE_KILL_POPUPS
686 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
687 #endif /* def FEATURE_KILL_POPUPS */
689 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
690 ((csp->action->flags & ACTION_FILTER) != 0);
692 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
694 /* grab the rest of the client's headers */
698 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
700 n = read_socket(csp->cfd, buf, sizeof(buf));
703 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
706 add_to_iob(csp, buf, n);
710 if (p == NULL) break;
712 enlist(csp->headers, p);
716 /* We have a request. */
719 * Now, check to see if we need to intercept it, i.e.
724 /* a CGI call was detected and answered */
725 (NULL != (rsp = dispatch_cgi(csp)))
727 /* or we are enabled and... */
730 /* ..the request was blocked */
731 ( NULL != (rsp = block_url(csp)))
735 || ( NULL != (rsp = trust_url(csp)))
736 #endif /* def FEATURE_TRUST */
738 /* ..or a fast redirect kicked in */
739 #ifdef FEATURE_FAST_REDIRECTS
740 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
741 (NULL != (rsp = redirect_url(csp))))
742 #endif /* def FEATURE_FAST_REDIRECTS */
746 /* Write the answer to the client */
747 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
748 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
750 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
753 #ifdef FEATURE_STATISTICS
754 /* Count as a rejected request */
755 csp->flags |= CSP_FLAG_REJECTED;
756 #endif /* def FEATURE_STATISTICS */
758 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
759 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
760 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
762 /* Clean up and return */
763 free_http_response(rsp);
767 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
769 if (fwd->forward_host)
771 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
772 fwd->forward_host, fwd->forward_port, http->hostport);
776 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
779 /* here we connect to the server, gateway, or the forwarder */
781 csp->sfd = forwarded_connect(fwd, http, csp);
785 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
790 rsp = error_response(csp, "no-such-domain", errno);
792 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
793 csp->ip_addr_str, http->cmd);
797 rsp = error_response(csp, "connect-failed", errno);
799 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
800 csp->ip_addr_str, http->cmd);
803 /* Write the answer to the client */
806 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
807 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
809 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
813 free_http_response(rsp);
817 log_error(LOG_LEVEL_CONNECT, "OK");
819 hdr = sed(client_patterns, add_client_headers, csp);
820 list_remove_all(csp->headers);
822 if (fwd->forward_host || (http->ssl == 0))
824 /* write the client's (modified) header to the server
825 * (along with anything else that may be in the buffer)
830 if ((write_socket(csp->sfd, hdr, n) != n)
831 || (flush_socket(csp->sfd, csp ) < 0))
833 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
836 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
837 csp->ip_addr_str, http->cmd);
839 rsp = error_response(csp, "connect-failed", errno);
843 if ((write_socket(csp->cfd, rsp->head, n) != n)
844 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
846 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
850 free_http_response(rsp);
858 * We're running an SSL tunnel and we're not forwarding,
859 * so just send the "connect succeeded" message to the
860 * client, flush the rest, and get out of the way.
862 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
863 csp->ip_addr_str, http->cmd);
865 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
873 /* we're finished with the client's header */
876 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
878 /* pass data between the client and server
879 * until one or the other shuts down the connection.
888 FD_SET(csp->cfd, &rfds);
889 FD_SET(csp->sfd, &rfds);
891 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
895 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
899 /* this is the body of the browser's request
900 * just read it and write it.
903 if (FD_ISSET(csp->cfd, &rfds))
905 n = read_socket(csp->cfd, buf, sizeof(buf));
909 break; /* "game over, man" */
912 if (write_socket(csp->sfd, buf, n) != n)
914 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
921 * The server wants to talk. It could be the header or the body.
922 * If `hdr' is null, then it's the header otherwise it's the body.
923 * FIXME: Does `hdr' really mean `host'? No.
927 if (FD_ISSET(csp->sfd, &rfds))
930 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
934 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
936 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
937 csp->ip_addr_str, http->cmd);
939 rsp = error_response(csp, "connect-failed", errno);
943 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
944 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
946 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
950 free_http_response(rsp);
954 /* Add a trailing zero. This lets filter_popups
955 * use string operations.
959 #ifdef FEATURE_KILL_POPUPS
960 /* Filter the popups on this read. */
961 if (block_popups_now)
963 filter_popups(buf, csp);
965 #endif /* def FEATURE_KILL_POPUPS */
967 /* Normally, this would indicate that we've read
968 * as much as the server has sent us and we can
969 * close the client connection. However, Microsoft
970 * in its wisdom has released IIS/5 with a bug that
971 * prevents it from sending the trailing \r\n in
972 * a 302 redirect header (and possibly other headers).
973 * To work around this if we've haven't parsed
974 * a full header we'll append a trailing \r\n
975 * and see if this now generates a valid one.
977 * This hack shouldn't have any impacts. If we've
978 * already transmitted the header or if this is a
979 * SSL connection, then we won't bother with this
980 * hack. So we only work on partially received
981 * headers. If we append a \r\n and this still
982 * doesn't generate a valid header, then we won't
983 * transmit anything to the client.
988 if (server_body || http->ssl)
991 * If we have been buffering up the document,
992 * now is the time to apply content modification
993 * and send the result to the client.
998 * If the content filter fails, use the original
1000 * (see p != NULL ? p : csp->iob->cur below)
1002 if (NULL == (p = (*content_filter)(csp)))
1004 csp->content_length = csp->iob->eod - csp->iob->cur;
1007 hdr = sed(server_patterns, add_server_headers, csp);
1010 if ((write_socket(csp->cfd, hdr, n) != n)
1011 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1013 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1023 break; /* "game over, man" */
1027 * This is NOT the body, so
1028 * Let's pretend the server just sent us a blank line.
1030 n = sprintf(buf, "\r\n");
1033 * Now, let the normal header parsing algorithm below do its
1034 * job. If it fails, we'll exit instead of continuing.
1041 * If this is an SSL connection or we're in the body
1042 * of the server document, just write it to the client,
1043 * unless we need to buffer the body for later content-filtering
1046 if (server_body || http->ssl)
1050 add_to_iob(csp, buf, n);
1053 * If the buffer limit will be reached on the next read,
1054 * switch to non-filtering mode, i.e. make & write the
1055 * header, flush the socket and get out of the way.
1057 if (csp->iob->eod - csp->iob->buf + BUFFER_SIZE > csp->config->buffer_limit)
1059 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1061 hdr = sed(server_patterns, add_server_headers, csp);
1065 if (((write_socket(csp->cfd, hdr, n) != n)
1066 || (n = flush_socket(csp->cfd, csp) < 0)))
1068 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1077 content_filter = NULL;
1084 if (write_socket(csp->cfd, buf, n) != n)
1086 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1095 /* we're still looking for the end of the
1096 * server's header ... (does that make header
1097 * parsing an "out of body experience" ?
1100 /* buffer up the data we just read */
1101 add_to_iob(csp, buf, n);
1103 /* get header lines from the iob */
1105 while ((p = get_header(csp)))
1109 /* see following note */
1112 enlist(csp->headers, p);
1116 /* NOTE: there are no "empty" headers so
1117 * if the pointer `p' is not NULL we must
1118 * assume that we reached the end of the
1119 * buffer before we hit the end of the header.
1126 /* Well, we tried our MS IIS/5
1127 * hack and it didn't work.
1128 * The header is incomplete
1129 * and there isn't anything
1130 * we can do about it.
1136 /* Since we have to wait for
1137 * more from the server before
1138 * we can parse the headers
1139 * we just continue here.
1145 /* we have now received the entire header.
1146 * filter it and send the result to the client
1149 hdr = sed(server_patterns, add_server_headers, csp);
1152 /* write the server's (modified) header to
1153 * the client (along with anything else that
1154 * may be in the buffer)
1157 #ifdef FEATURE_KILL_POPUPS
1158 /* Start blocking popups if appropriate. */
1160 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1161 !http->ssl && /* We talk plaintext */
1162 block_popups) /* Policy allows */
1164 block_popups_now = 1;
1166 * Filter the part of the body that came in the same read
1167 * as the last headers:
1169 filter_popups(csp->iob->cur, csp);
1172 #endif /* def FEATURE_KILL_POPUPS */
1174 /* Buffer and pcrs filter this if appropriate. */
1176 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1177 !http->ssl && /* We talk plaintext */
1178 pcrs_filter) /* Policy allows */
1180 content_filter = pcrs_filter_response;
1183 /* Buffer and gif_deanimate this if appropriate. */
1185 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1186 !http->ssl && /* We talk plaintext */
1187 gif_deanimate) /* Policy allows */
1189 content_filter = gif_deanimate_response;
1194 * Only write if we're not buffering for content modification
1196 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1197 || (n = flush_socket(csp->cfd, csp) < 0)))
1199 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1201 /* the write failed, so don't bother
1202 * mentioning it to the client...
1203 * it probably can't hear us anyway.
1209 if(!content_filter) byte_count += n;
1211 /* we're finished with the server's header */
1216 /* If this was a MS IIS/5 hack then it means
1217 * the server has already closed the
1218 * connection. Nothing more to read. Time
1229 return; /* huh? we should never get here */
1232 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1233 csp->ip_addr_str, http->cmd, byte_count);
1237 /*********************************************************************
1241 * Description : This is little more than chat. We only "serve" to
1242 * to close any socket that chat may have opened.
1245 * 1 : csp = Current client state (buffers, headers, etc...)
1249 *********************************************************************/
1251 void serve(struct client_state *csp)
1252 #else /* ifndef AMIGA */
1253 static void serve(struct client_state *csp)
1254 #endif /* def AMIGA */
1257 close_socket(csp->cfd);
1261 close_socket(csp->sfd);
1264 csp->flags &= ~CSP_FLAG_ACTIVE;
1270 /*********************************************************************
1272 * Function : server_thread
1274 * Description : We only exist to call `serve' in a threaded environment.
1277 * 1 : data = Current client state (buffers, headers, etc...)
1279 * Returns : Always 0.
1281 *********************************************************************/
1282 static int32 server_thread(void *data)
1284 serve((struct client_state *) data);
1291 /*********************************************************************
1295 * Description : Load the config file and start the listen loop.
1296 * This function is a lot more *sane* with the `load_config'
1297 * and `listen_loop' functions; although it stills does
1298 * a *little* too much for my taste.
1301 * 1 : argc = Number of parameters (including $0).
1302 * 2 : argv = Array of (char *)'s to the parameters.
1304 * Returns : 1 if : can't open config file, unrecognized directive,
1305 * stats requested in multi-thread mode, can't open the
1306 * log file, can't open the jar file, listen port is invalid,
1307 * any load fails, and can't bind port.
1309 * Else main never returns, the process must be signaled
1310 * to terminate execution. Or, on Windows, use the
1311 * "File", "Exit" menu option.
1313 *********************************************************************/
1315 int real_main(int argc, const char *argv[])
1317 int main(int argc, const char *argv[])
1322 "AmiTCP:db/junkbuster/config"
1323 #elif !defined(_WIN32)
1330 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1331 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1333 printf("JunkBuster proxy version " VERSION ".\n\n"
1334 "Usage: %s [configfile]\n\n"
1335 "See " HOME_PAGE_URL " for details.\n"
1336 "This program is distributed under the GNU GPL, version 2 or later.\n",
1340 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1342 printf(VERSION "\n");
1345 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1352 configfile = argv[1];
1359 #elif defined(_WIN32)
1365 signal(SIGPIPE, SIG_IGN);
1366 signal(SIGCHLD, SIG_IGN);
1368 #else /* ifdef _WIN32 */
1369 # ifdef _WIN_CONSOLE
1371 * We *are* in a windows console app.
1372 * Print a verbose messages about FAQ's and such
1374 printf(win32_blurb);
1375 # endif /* def _WIN_CONSOLE */
1376 #endif /* def _WIN32 */
1387 /*********************************************************************
1389 * Function : listen_loop
1391 * Description : bind the listen port and enter a "FOREVER" listening loop.
1397 *********************************************************************/
1398 static void listen_loop(void)
1400 struct client_state *csp = NULL;
1402 struct configuration_spec * config;
1404 config = load_config();
1406 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1407 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1409 bfd = bind_port(config->haddr, config->hport);
1413 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1414 "- There may be another junkbuster or some other "
1415 "proxy running on port %d",
1416 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1417 config->hport, config->hport
1419 /* shouldn't get here */
1423 config->need_bind = 0;
1428 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1429 while (waitpid(-1, NULL, WNOHANG) > 0)
1431 /* zombie children */
1433 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1436 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1438 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1442 csp->flags |= CSP_FLAG_ACTIVE;
1445 csp->config = config = load_config();
1447 if ( config->need_bind )
1450 * Since we were listening to the "old port", we will not see
1451 * a "listen" param change until the next IJB request. So, at
1452 * least 1 more request must be made for us to find the new
1453 * setting. I am simply closing the old socket and binding the
1456 * Which-ever is correct, we will serve 1 more page via the
1457 * old settings. This should probably be a "show-proxy-args"
1458 * request. This should not be a so common of an operation
1459 * that this will hurt people's feelings.
1464 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1465 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1466 bfd = bind_port(config->haddr, config->hport);
1470 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1471 "- There may be another junkbuster or some other "
1472 "proxy running on port %d",
1473 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1474 config->hport, config->hport
1476 /* shouldn't get here */
1480 config->need_bind = 0;
1483 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1485 if (!accept_connection(csp, bfd))
1487 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1500 log_error(LOG_LEVEL_CONNECT, "OK");
1503 #ifdef FEATURE_TOGGLE
1506 csp->flags |= CSP_FLAG_TOGGLED_ON;
1508 #endif /* def FEATURE_TOGGLE */
1510 if (run_loader(csp))
1512 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1513 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1517 if (block_acl(NULL,csp))
1519 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1520 close_socket(csp->cfd);
1524 #endif /* def FEATURE_ACL */
1526 /* add it to the list of clients */
1527 csp->next = clients->next;
1528 clients->next = csp;
1530 if (config->multi_threaded)
1534 /* this is a switch () statment in the C preprocessor - ugh */
1535 #undef SELECTED_ONE_OPTION
1537 /* Use Pthreads in preference to native code */
1538 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1539 #define SELECTED_ONE_OPTION
1541 pthread_t the_thread;
1542 pthread_attr_t attrs;
1544 pthread_attr_init(&attrs);
1545 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1546 child_id = (pthread_create(&the_thread, &attrs,
1547 (void*)serve, csp) ? -1 : 0);
1548 pthread_attr_destroy(&attrs);
1552 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1553 #define SELECTED_ONE_OPTION
1554 child_id = _beginthread(
1560 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1561 #define SELECTED_ONE_OPTION
1563 thread_id tid = spawn_thread
1564 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1566 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1568 child_id = (int) tid;
1577 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1578 #define SELECTED_ONE_OPTION
1579 csp->cfd = ReleaseSocket(csp->cfd, -1);
1580 if((child_id = (int)CreateNewProcTags(
1581 NP_Entry, (ULONG)server_thread,
1582 NP_Output, Output(),
1583 NP_CloseOutput, FALSE,
1584 NP_Name, (ULONG)"junkbuster child",
1585 NP_StackSize, 200*1024,
1589 ((struct Task *)child_id)->tc_UserData = csp;
1590 Signal((struct Task *)child_id, SIGF_SINGLE);
1595 #if !defined(SELECTED_ONE_OPTION)
1598 /* This block is only needed when using fork().
1599 * When using threads, the server thread was
1600 * created and run by the call to _beginthread().
1602 if (child_id == 0) /* child */
1608 else if (child_id > 0) /* parent */
1610 /* in a fork()'d environment, the parent's
1611 * copy of the client socket and the CSP
1615 #if !defined(_WIN32) && defined(__CYGWIN__)
1617 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1618 close_socket(csp->cfd);
1619 csp->flags &= ~CSP_FLAG_ACTIVE;
1623 #undef SELECTED_ONE_OPTION
1624 /* end of cpp switch () */
1626 if (child_id < 0) /* failed */
1628 char buf[BUFFER_SIZE];
1630 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1632 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1634 write_socket(csp->cfd, buf, strlen(buf));
1635 close_socket(csp->cfd);
1636 csp->flags &= ~CSP_FLAG_ACTIVE;