1 const char jcc_rcs[] = "$Id: jcc.c,v 1.48 2001/10/10 19:56:46 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.48 2001/10/10 19:56:46 jongfoster
37 * Moving some code that wasn't cookie-related out of an #ifdef
40 * Revision 1.47 2001/10/10 16:44:36 oes
41 * Added CONNECT destination port limitation check
43 * Revision 1.46 2001/10/08 15:17:41 oes
44 * Re-enabled SSL forwarding
46 * Revision 1.45 2001/10/07 15:42:11 oes
47 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
49 * Moved downgrading of the HTTP version from parse_http_request to
50 * chat(), since we can't decide if it is necessary before we have
51 * determined the actions for the URL. The HTTP command is now
52 * *always* re-built so the repairs need no longer be special-cased.
54 * filter_popups now gets a csp pointer so it can raise the new
55 * CSP_FLAG_MODIFIED flag.
59 * Added configurable size limit for the IOB. If the IOB grows so
60 * large that the next read would exceed the limit, the header
61 * is generated, and the header & unfiltered buffer are flushed
62 * to the client. Chat then continues in non-buffering,
63 * non-filtering body mode.
65 * Revision 1.44 2001/10/02 18:13:57 oes
68 * Revision 1.43 2001/10/02 15:32:13 oes
69 * Moved generation of hdr
71 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
72 * Cleaning up 2 compiler warnings on OS/2.
74 * Revision 1.41 2001/09/16 17:05:14 jongfoster
75 * Removing unused #include showarg.h
77 * Revision 1.40 2001/09/16 15:41:45 jongfoster
78 * Fixing signed/unsigned comparison warning.
80 * Revision 1.39 2001/09/16 13:21:27 jongfoster
81 * Changes to use new list functions.
83 * Revision 1.38 2001/09/16 13:01:46 jongfoster
84 * Removing redundant function call that zeroed zalloc()'d memory.
86 * Revision 1.37 2001/09/10 11:12:24 oes
87 * Deleted unused variable
89 * Revision 1.36 2001/09/10 10:56:15 oes
90 * Silenced compiler warnings
92 * Revision 1.35 2001/07/31 14:44:22 oes
93 * Deleted unused size parameter from filter_popups()
95 * Revision 1.34 2001/07/30 22:08:36 jongfoster
96 * Tidying up #defines:
97 * - All feature #defines are now of the form FEATURE_xxx
98 * - Permanently turned off WIN_GUI_EDIT
99 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
101 * Revision 1.33 2001/07/29 19:32:00 jongfoster
102 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
104 * Revision 1.32 2001/07/29 18:47:05 jongfoster
105 * Adding missing #include "loadcfg.h"
107 * Revision 1.31 2001/07/29 12:17:48 oes
108 * Applied pthread fix by Paul Lieverse
110 * Revision 1.30 2001/07/25 22:57:13 jongfoster
111 * __BEOS__ no longer overrides FEATURE_PTHREAD.
112 * This is because FEATURE_PTHREAD will soon be widely used, so I
113 * want to keep it simple.
115 * Revision 1.29 2001/07/24 12:47:06 oes
116 * Applied BeOS support update by Eugenia
118 * Revision 1.28 2001/07/23 13:26:12 oes
119 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
121 * Revision 1.27 2001/07/19 19:09:47 haroon
122 * - Added code to take care of the situation where while processing the first
123 * server response (which includes the server header), after finding the end
124 * of the headers we were not looking past the end of the headers for
125 * content modification. I enabled it for filter_popups.
126 * Someone else should look to see if other similar operations should be
127 * done to the discarded portion of the buffer.
129 * Note 2001/07/20: No, the other content modification mechanisms will process
130 * the whole iob later anyway. --oes
132 * Revision 1.26 2001/07/18 12:31:36 oes
135 * Revision 1.25 2001/07/15 19:43:49 jongfoster
136 * Supports POSIX threads.
137 * Also removed some unused #includes.
139 * Revision 1.24 2001/07/13 14:00:40 oes
140 * - Generic content modification scheme:
141 * Each feature has its own applicability flag that is set
142 * from csp->action->flags.
143 * Replaced the "filtering" int flag , by a function pointer
144 * "content_filter" to the function that will do the content
145 * modification. If it is != NULL, the document will be buffered
146 * and processed through *content_filter, which must set
147 * csp->content_length and return a modified copy of the body
148 * or return NULL (on failiure).
149 * - Changed csp->is_text to the more generic bitmap csp->content_type
150 * which can currently take the valued CT_TEXT or CT_GIF
152 * - Removed all #ifdef PCRS
154 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
155 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
156 * the `block_acl' call. This prevents a compilation error when the user
157 * does not wish to use the "ACL" feature.
159 * Revision 1.22 2001/06/29 21:45:41 oes
160 * Indentation, CRLF->LF, Tab-> Space
162 * Revision 1.21 2001/06/29 13:29:36 oes
163 * - Cleaned up, improved comments
164 * - Unified all possible interceptors (CGI,
165 * block, trust, fast_redirect) in one
166 * place, with one (CGI) answer generation
167 * mechansim. Much clearer now.
168 * - Removed the GIF image generation, which
169 * is now done in filters.c:block_url()
170 * - Made error conditions like domain lookup
171 * failiure or (various) problems while talking
172 * to the server use cgi.c:error_response()
173 * instead of generating HTML/HTTP in chat() (yuck!)
174 * - Removed logentry from cancelled commit
176 * Revision 1.20 2001/06/09 10:55:28 jongfoster
177 * Changing BUFSIZ ==> BUFFER_SIZE
179 * Revision 1.19 2001/06/07 23:12:52 jongfoster
180 * Replacing function pointer in struct gateway with a directly
181 * called function forwarded_connect().
182 * Replacing struct gateway with struct forward_spec
184 * Revision 1.18 2001/06/03 19:12:16 oes
185 * introduced new cgi handling
187 * Revision 1.17 2001/06/01 20:07:23 jongfoster
188 * Now uses action +image-blocker{} rather than config->tinygif
190 * Revision 1.16 2001/06/01 18:49:17 jongfoster
191 * Replaced "list_share" with "list" - the tiny memory gain was not
192 * worth the extra complexity.
194 * Revision 1.15 2001/05/31 21:24:47 jongfoster
195 * Changed "permission" to "action" throughout.
196 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
197 * Moved vanilla wafer check into chat(), since we must now
198 * decide whether or not to add it based on the URL.
200 * Revision 1.14 2001/05/29 20:14:01 joergs
201 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
204 * Revision 1.13 2001/05/29 09:50:24 jongfoster
205 * Unified blocklist/imagelist/permissionslist.
206 * File format is still under discussion, but the internal changes
209 * Also modified interceptor behaviour:
210 * - We now intercept all URLs beginning with one of the following
211 * prefixes (and *only* these prefixes):
213 * * http://ijbswa.sf.net/config/
214 * * http://ijbswa.sourceforge.net/config/
215 * - New interceptors "home page" - go to http://i.j.b/ to see it.
216 * - Internal changes so that intercepted and fast redirect pages
217 * are not replaced with an image.
218 * - Interceptors now have the option to send a binary page direct
219 * to the client. (i.e. ijb-send-banner uses this)
220 * - Implemented show-url-info interceptor. (Which is why I needed
221 * the above interceptors changes - a typical URL is
222 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
223 * The previous mechanism would not have intercepted that, and
224 * if it had been intercepted then it then it would have replaced
227 * Revision 1.12 2001/05/27 22:17:04 oes
229 * - re_process_buffer no longer writes the modified buffer
230 * to the client, which was very ugly. It now returns the
231 * buffer, which it is then written by chat.
233 * - content_length now adjusts the Content-Length: header
234 * for modified documents rather than crunch()ing it.
235 * (Length info in csp->content_length, which is 0 for
236 * unmodified documents)
238 * - For this to work, sed() is called twice when filtering.
240 * Revision 1.11 2001/05/26 17:27:53 jongfoster
241 * Added support for CLF and fixed LOG_LEVEL_LOG.
242 * Also did CRLF->LF fix of my previous patch.
244 * Revision 1.10 2001/05/26 15:26:15 jongfoster
245 * ACL feature now provides more security by immediately dropping
246 * connections from untrusted hosts.
248 * Revision 1.9 2001/05/26 00:28:36 jongfoster
249 * Automatic reloading of config file.
250 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
251 * Most of the global variables have been moved to a new
252 * struct configuration_spec, accessed through csp->config->globalname
253 * Most of the globals remaining are used by the Win32 GUI.
255 * Revision 1.8 2001/05/25 22:43:18 jongfoster
256 * Fixing minor memory leak and buffer overflow.
258 * Revision 1.7 2001/05/25 22:34:30 jongfoster
261 * Revision 1.6 2001/05/23 00:13:58 joergs
262 * AmigaOS support fixed.
264 * Revision 1.5 2001/05/22 18:46:04 oes
266 * - Enabled filtering banners by size rather than URL
267 * by adding patterns that replace all standard banner
268 * sizes with the "Junkbuster" gif to the re_filterfile
270 * - Enabled filtering WebBugs by providing a pattern
271 * which kills all 1x1 images
273 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
274 * which is selected by the (nonstandard and therefore
275 * capital) letter 'U' in the option string.
276 * It causes the quantifiers to be ungreedy by default.
277 * Appending a ? turns back to greedy (!).
279 * - Added a new interceptor ijb-send-banner, which
280 * sends back the "Junkbuster" gif. Without imagelist or
281 * MSIE detection support, or if tinygif = 1, or the
282 * URL isn't recognized as an imageurl, a lame HTML
283 * explanation is sent instead.
285 * - Added new feature, which permits blocking remote
286 * script redirects and firing back a local redirect
288 * The feature is conditionally compiled, i.e. it
289 * can be disabled with --disable-fast-redirects,
290 * plus it must be activated by a "fast-redirects"
291 * line in the config file, has its own log level
292 * and of course wants to be displayed by show-proxy-args
293 * Note: Boy, all the #ifdefs in 1001 locations and
294 * all the fumbling with configure.in and acconfig.h
295 * were *way* more work than the feature itself :-(
297 * - Because a generic redirect template was needed for
298 * this, tinygif = 3 now uses the same.
300 * - Moved GIFs, and other static HTTP response templates
305 * - Removed some >400 CRs again (Jon, you really worked
308 * Revision 1.4 2001/05/21 19:34:01 jongfoster
309 * Made failure to bind() a fatal error.
311 * Revision 1.3 2001/05/20 01:21:20 jongfoster
312 * Version 2.9.4 checkin.
313 * - Merged popupfile and cookiefile, and added control over PCRS
314 * filtering, in new "permissionsfile".
315 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
316 * file error you now get a message box (in the Win32 GUI) rather
317 * than the program exiting with no explanation.
318 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
320 * - Removed tabs from "config"
321 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
322 * - Bumped up version number.
324 * Revision 1.2 2001/05/17 22:34:44 oes
325 * - Added hint on GIF char array generation to jcc.c
326 * - Cleaned CRLF's from the sources and related files
327 * - Repaired logging for REF and FRC
329 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
330 * Initial import of version 2.9.3 source tree
333 *********************************************************************/
339 #include <sys/types.h>
346 #ifdef FEATURE_PTHREAD
348 #endif /* def FEATURE_PTHREAD */
351 # ifndef FEATURE_PTHREAD
352 # include <windows.h>
353 # include <process.h>
354 # endif /* ndef FEATURE_PTHREAD */
357 # ifndef _WIN_CONSOLE
359 # endif /* ndef _WIN_CONSOLE */
361 #else /* ifndef _WIN32 */
364 # include <sys/time.h>
365 # include <sys/wait.h>
366 # include <sys/stat.h>
370 # include <socket.h> /* BeOS has select() for sockets only. */
371 # include <OS.h> /* declarations for threads and stuff. */
375 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
390 #include "killpopup.h"
391 #include "miscutil.h"
393 #include "jbsockets.h"
399 const char jcc_h_rcs[] = JCC_H_VERSION;
400 const char project_h_rcs[] = PROJECT_H_VERSION;
402 struct client_state clients[1];
403 struct file_list files[1];
405 #ifdef FEATURE_STATISTICS
406 int urls_read = 0; /* total nr of urls read inc rejected */
407 int urls_rejected = 0; /* total nr of urls rejected */
408 #endif /* def FEATURE_STATISTICS */
411 static void listen_loop(void);
412 static void chat(struct client_state *csp);
414 void serve(struct client_state *csp);
415 #else /* ifndef AMIGA */
416 static void serve(struct client_state *csp);
417 #endif /* def AMIGA */
420 static int32 server_thread(void *data);
421 #endif /* def __BEOS__ */
424 #define sleep(N) Sleep(((N) * 1000))
428 /* The vanilla wafer. */
429 static const char VANILLA_WAFER[] =
430 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
431 "Do_not_send_me_any_copyrighted_information_other_than_the_"
432 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
433 "In_particular_do_not_send_me_any_cookies_that_"
434 "are_subject_to_a_claim_of_copyright_by_anybody._"
435 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
436 "(copyright_or_otherwise)_applying_to_any_cookie._";
439 /*********************************************************************
443 * Description : Once a connection to the client has been accepted,
444 * this function is called (via serve()) to handle the
445 * main business of the communication. When this
446 * function returns, the caller must close the client
450 * 1 : csp = Current client state (buffers, headers, etc...)
452 * Returns : On success, the number of bytes written are returned (zero
453 * indicates nothing was written). On error, -1 is returned,
454 * and errno is set appropriately. If count is zero and the
455 * file descriptor refers to a regular file, 0 will be
456 * returned without causing any other effect. For a special
457 * file, the results are not portable.
459 *********************************************************************/
460 static void chat(struct client_state *csp)
463 * This next lines are a little ugly, but they simplifies the if statements
464 * below. Basically if TOGGLE, then we want the if to test if the
465 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
466 * then we want the if to test for CSP_FLAG_FORCED , else we don't
468 #ifdef FEATURE_TOGGLE
469 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
470 #else /* ifndef FEATURE_TOGGLE */
471 # define IS_TOGGLED_ON_AND
472 #endif /* ndef FEATURE_TOGGLE */
473 #ifdef FEATURE_FORCE_LOAD
474 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
475 #else /* ifndef FEATURE_FORCE_LOAD */
476 # define IS_NOT_FORCED_AND
477 #endif /* def FEATURE_FORCE_LOAD */
479 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
481 char buf[BUFFER_SIZE];
484 int n, maxfd, server_body;
485 int ms_iis5_hack = 0;
487 const struct forward_spec * fwd;
488 struct http_request *http;
489 #ifdef FEATURE_KILL_POPUPS
490 int block_popups; /* bool, 1==will block popups */
491 int block_popups_now = 0; /* bool, 1==currently blocking popups */
492 #endif /* def FEATURE_KILL_POPUPS */
494 int pcrs_filter; /* bool, 1==will filter through pcrs */
495 int gif_deanimate; /* bool, 1==will deanimate gifs */
497 /* Function that does the content filtering for the current request */
498 char *(*content_filter)() = NULL;
500 /* Skeleton for HTTP response, if we should intercept the request */
501 struct http_response *rsp;
506 * Read the client's request. Note that since we're not using select() we
507 * could get blocked here if a client connected, then didn't say anything!
512 n = read_socket(csp->cfd, buf, sizeof(buf));
514 if (n <= 0) break; /* error! */
516 add_to_iob(csp, buf, n);
518 req = get_header(csp);
522 break; /* no HTTP request! */
527 continue; /* more to come! */
530 #ifdef FEATURE_FORCE_LOAD
531 /* If this request contains the FORCE_PREFIX,
532 * better get rid of it now and set the force flag --oes
535 if (strstr(req, FORCE_PREFIX))
537 strclean(req, FORCE_PREFIX);
538 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
539 csp->flags |= CSP_FLAG_FORCED;
542 #endif /* def FEATURE_FORCE_LOAD */
544 parse_http_request(req, http, csp);
549 if (http->cmd == NULL)
551 strcpy(buf, CHEADER);
552 write_socket(csp->cfd, buf, strlen(buf));
554 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
559 /* decide how to route the HTTP request */
561 if ((fwd = forward_url(http, csp)) == NULL)
563 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
564 /* Never get here - LOG_LEVEL_FATAL causes program exit */
567 /* build the http request to send to the server
568 * we have to do one of the following:
570 * create = use the original HTTP request to create a new
571 * HTTP request that has either the path component
572 * without the http://domainspec (w/path) or the
573 * full orininal URL (w/url)
574 * Note that the path and/or the HTTP version may
575 * have been altered by now.
577 * connect = Open a socket to the host:port of the server
578 * and short-circuit server and client socket.
580 * pass = Pass the request unchanged if forwarding a CONNECT
581 * request to a parent proxy. Note that we'll be sending
582 * the CFAIL message ourselves if connecting to the parent
583 * fails, but we won't send a CSUCCEED message if it works,
584 * since that would result in a double message (ours and the
585 * parent's). After sending the request to the parent, we simply
591 * +--------+--------+
593 * 0 | create | connect|
595 * Forwarding +--------+--------+
597 * 1 | create | pass |
599 * +--------+--------+
604 * Determine the actions for this URL
606 #ifdef FEATURE_TOGGLE
607 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
609 /* Most compatible set of actions (i.e. none) */
610 init_current_action(csp->action);
613 #endif /* ndef FEATURE_TOGGLE */
615 url_actions(http, csp);
620 * Check if a CONNECT request is allowable:
621 * In the absence of a +limit-connect action, allow only port 443.
622 * If there is an action, allow whatever matches the specificaton.
626 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
627 || (csp->action->flags & ACTION_LIMIT_CONNECT
628 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
630 strcpy(buf, CFORBIDDEN);
631 write_socket(csp->cfd, buf, strlen(buf));
633 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
634 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
642 * Downgrade http version from 1.1 to 1.0 if +downgrade
645 if (!strcmpic(http->ver, "HTTP/1.1") && csp->action->flags & ACTION_DOWNGRADE)
648 http->ver = strdup("HTTP/1.0");
652 * (Re)build the HTTP request for non-SSL requests.
653 * If forwarding, use the whole URL, else, use only the path.
659 http->cmd = strsav(http->cmd, http->gpc);
660 http->cmd = strsav(http->cmd, " ");
662 if (fwd->forward_host)
664 http->cmd = strsav(http->cmd, http->url);
668 http->cmd = strsav(http->cmd, http->path);
671 http->cmd = strsav(http->cmd, " ");
672 http->cmd = strsav(http->cmd, http->ver);
675 enlist(csp->headers, http->cmd);
678 #ifdef FEATURE_COOKIE_JAR
680 * If we're logging cookies in a cookie jar, and the user has not
681 * supplied any wafers, and the user has not told us to suppress the
682 * vanilla wafer, then send the vanilla wafer.
684 if ((csp->config->jarfile != NULL)
685 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
686 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
688 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
690 #endif /* def FEATURE_COOKIE_JAR */
693 #ifdef FEATURE_KILL_POPUPS
694 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
695 #endif /* def FEATURE_KILL_POPUPS */
697 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
698 ((csp->action->flags & ACTION_FILTER) != 0);
700 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
702 /* grab the rest of the client's headers */
706 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
708 n = read_socket(csp->cfd, buf, sizeof(buf));
711 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
714 add_to_iob(csp, buf, n);
718 if (p == NULL) break;
720 enlist(csp->headers, p);
724 /* We have a request. */
727 * Now, check to see if we need to intercept it, i.e.
732 /* a CGI call was detected and answered */
733 (NULL != (rsp = dispatch_cgi(csp)))
735 /* or we are enabled and... */
738 /* ..the request was blocked */
739 ( NULL != (rsp = block_url(csp)))
743 || ( NULL != (rsp = trust_url(csp)))
744 #endif /* def FEATURE_TRUST */
746 /* ..or a fast redirect kicked in */
747 #ifdef FEATURE_FAST_REDIRECTS
748 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
749 (NULL != (rsp = redirect_url(csp))))
750 #endif /* def FEATURE_FAST_REDIRECTS */
754 /* Write the answer to the client */
755 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
756 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
758 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
761 #ifdef FEATURE_STATISTICS
762 /* Count as a rejected request */
763 csp->flags |= CSP_FLAG_REJECTED;
764 #endif /* def FEATURE_STATISTICS */
766 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
767 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
768 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
770 /* Clean up and return */
771 free_http_response(rsp);
775 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
777 if (fwd->forward_host)
779 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
780 fwd->forward_host, fwd->forward_port, http->hostport);
784 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
787 /* here we connect to the server, gateway, or the forwarder */
789 csp->sfd = forwarded_connect(fwd, http, csp);
793 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
798 rsp = error_response(csp, "no-such-domain", errno);
800 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
801 csp->ip_addr_str, http->cmd);
805 rsp = error_response(csp, "connect-failed", errno);
807 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
808 csp->ip_addr_str, http->cmd);
811 /* 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);
821 free_http_response(rsp);
825 log_error(LOG_LEVEL_CONNECT, "OK");
827 hdr = sed(client_patterns, add_client_headers, csp);
828 list_remove_all(csp->headers);
830 if (fwd->forward_host || (http->ssl == 0))
832 /* write the client's (modified) header to the server
833 * (along with anything else that may be in the buffer)
838 if ((write_socket(csp->sfd, hdr, n) != n)
839 || (flush_socket(csp->sfd, csp ) < 0))
841 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
844 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
845 csp->ip_addr_str, http->cmd);
847 rsp = error_response(csp, "connect-failed", errno);
851 if ((write_socket(csp->cfd, rsp->head, n) != n)
852 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
854 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
858 free_http_response(rsp);
866 * We're running an SSL tunnel and we're not forwarding,
867 * so just send the "connect succeeded" message to the
868 * client, flush the rest, and get out of the way.
870 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
871 csp->ip_addr_str, http->cmd);
873 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
881 /* we're finished with the client's header */
884 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
886 /* pass data between the client and server
887 * until one or the other shuts down the connection.
896 FD_SET(csp->cfd, &rfds);
897 FD_SET(csp->sfd, &rfds);
899 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
903 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
907 /* this is the body of the browser's request
908 * just read it and write it.
911 if (FD_ISSET(csp->cfd, &rfds))
913 n = read_socket(csp->cfd, buf, sizeof(buf));
917 break; /* "game over, man" */
920 if (write_socket(csp->sfd, buf, n) != n)
922 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
929 * The server wants to talk. It could be the header or the body.
930 * If `hdr' is null, then it's the header otherwise it's the body.
931 * FIXME: Does `hdr' really mean `host'? No.
935 if (FD_ISSET(csp->sfd, &rfds))
938 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
942 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
944 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
945 csp->ip_addr_str, http->cmd);
947 rsp = error_response(csp, "connect-failed", errno);
951 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
952 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
954 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
958 free_http_response(rsp);
962 /* Add a trailing zero. This lets filter_popups
963 * use string operations.
967 #ifdef FEATURE_KILL_POPUPS
968 /* Filter the popups on this read. */
969 if (block_popups_now)
971 filter_popups(buf, csp);
973 #endif /* def FEATURE_KILL_POPUPS */
975 /* Normally, this would indicate that we've read
976 * as much as the server has sent us and we can
977 * close the client connection. However, Microsoft
978 * in its wisdom has released IIS/5 with a bug that
979 * prevents it from sending the trailing \r\n in
980 * a 302 redirect header (and possibly other headers).
981 * To work around this if we've haven't parsed
982 * a full header we'll append a trailing \r\n
983 * and see if this now generates a valid one.
985 * This hack shouldn't have any impacts. If we've
986 * already transmitted the header or if this is a
987 * SSL connection, then we won't bother with this
988 * hack. So we only work on partially received
989 * headers. If we append a \r\n and this still
990 * doesn't generate a valid header, then we won't
991 * transmit anything to the client.
996 if (server_body || http->ssl)
999 * If we have been buffering up the document,
1000 * now is the time to apply content modification
1001 * and send the result to the client.
1006 * If the content filter fails, use the original
1007 * buffer and length.
1008 * (see p != NULL ? p : csp->iob->cur below)
1010 if (NULL == (p = (*content_filter)(csp)))
1012 csp->content_length = csp->iob->eod - csp->iob->cur;
1015 hdr = sed(server_patterns, add_server_headers, csp);
1018 if ((write_socket(csp->cfd, hdr, n) != n)
1019 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1021 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1031 break; /* "game over, man" */
1035 * This is NOT the body, so
1036 * Let's pretend the server just sent us a blank line.
1038 n = sprintf(buf, "\r\n");
1041 * Now, let the normal header parsing algorithm below do its
1042 * job. If it fails, we'll exit instead of continuing.
1049 * If this is an SSL connection or we're in the body
1050 * of the server document, just write it to the client,
1051 * unless we need to buffer the body for later content-filtering
1054 if (server_body || http->ssl)
1058 add_to_iob(csp, buf, n);
1061 * If the buffer limit will be reached on the next read,
1062 * switch to non-filtering mode, i.e. make & write the
1063 * header, flush the socket and get out of the way.
1065 if (csp->iob->eod - csp->iob->buf + BUFFER_SIZE > csp->config->buffer_limit)
1067 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1069 hdr = sed(server_patterns, add_server_headers, csp);
1073 if (((write_socket(csp->cfd, hdr, n) != n)
1074 || (n = flush_socket(csp->cfd, csp) < 0)))
1076 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1085 content_filter = NULL;
1092 if (write_socket(csp->cfd, buf, n) != n)
1094 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1103 /* we're still looking for the end of the
1104 * server's header ... (does that make header
1105 * parsing an "out of body experience" ?
1108 /* buffer up the data we just read */
1109 add_to_iob(csp, buf, n);
1111 /* get header lines from the iob */
1113 while ((p = get_header(csp)))
1117 /* see following note */
1120 enlist(csp->headers, p);
1124 /* NOTE: there are no "empty" headers so
1125 * if the pointer `p' is not NULL we must
1126 * assume that we reached the end of the
1127 * buffer before we hit the end of the header.
1134 /* Well, we tried our MS IIS/5
1135 * hack and it didn't work.
1136 * The header is incomplete
1137 * and there isn't anything
1138 * we can do about it.
1144 /* Since we have to wait for
1145 * more from the server before
1146 * we can parse the headers
1147 * we just continue here.
1153 /* we have now received the entire header.
1154 * filter it and send the result to the client
1157 hdr = sed(server_patterns, add_server_headers, csp);
1160 /* write the server's (modified) header to
1161 * the client (along with anything else that
1162 * may be in the buffer)
1165 #ifdef FEATURE_KILL_POPUPS
1166 /* Start blocking popups if appropriate. */
1168 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1169 !http->ssl && /* We talk plaintext */
1170 block_popups) /* Policy allows */
1172 block_popups_now = 1;
1174 * Filter the part of the body that came in the same read
1175 * as the last headers:
1177 filter_popups(csp->iob->cur, csp);
1180 #endif /* def FEATURE_KILL_POPUPS */
1182 /* Buffer and pcrs filter this if appropriate. */
1184 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1185 !http->ssl && /* We talk plaintext */
1186 pcrs_filter) /* Policy allows */
1188 content_filter = pcrs_filter_response;
1191 /* Buffer and gif_deanimate this if appropriate. */
1193 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1194 !http->ssl && /* We talk plaintext */
1195 gif_deanimate) /* Policy allows */
1197 content_filter = gif_deanimate_response;
1202 * Only write if we're not buffering for content modification
1204 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1205 || (n = flush_socket(csp->cfd, csp) < 0)))
1207 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1209 /* the write failed, so don't bother
1210 * mentioning it to the client...
1211 * it probably can't hear us anyway.
1217 if(!content_filter) byte_count += n;
1219 /* we're finished with the server's header */
1224 /* If this was a MS IIS/5 hack then it means
1225 * the server has already closed the
1226 * connection. Nothing more to read. Time
1237 return; /* huh? we should never get here */
1240 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1241 csp->ip_addr_str, http->cmd, byte_count);
1245 /*********************************************************************
1249 * Description : This is little more than chat. We only "serve" to
1250 * to close any socket that chat may have opened.
1253 * 1 : csp = Current client state (buffers, headers, etc...)
1257 *********************************************************************/
1259 void serve(struct client_state *csp)
1260 #else /* ifndef AMIGA */
1261 static void serve(struct client_state *csp)
1262 #endif /* def AMIGA */
1265 close_socket(csp->cfd);
1269 close_socket(csp->sfd);
1272 csp->flags &= ~CSP_FLAG_ACTIVE;
1278 /*********************************************************************
1280 * Function : server_thread
1282 * Description : We only exist to call `serve' in a threaded environment.
1285 * 1 : data = Current client state (buffers, headers, etc...)
1287 * Returns : Always 0.
1289 *********************************************************************/
1290 static int32 server_thread(void *data)
1292 serve((struct client_state *) data);
1299 /*********************************************************************
1303 * Description : Load the config file and start the listen loop.
1304 * This function is a lot more *sane* with the `load_config'
1305 * and `listen_loop' functions; although it stills does
1306 * a *little* too much for my taste.
1309 * 1 : argc = Number of parameters (including $0).
1310 * 2 : argv = Array of (char *)'s to the parameters.
1312 * Returns : 1 if : can't open config file, unrecognized directive,
1313 * stats requested in multi-thread mode, can't open the
1314 * log file, can't open the jar file, listen port is invalid,
1315 * any load fails, and can't bind port.
1317 * Else main never returns, the process must be signaled
1318 * to terminate execution. Or, on Windows, use the
1319 * "File", "Exit" menu option.
1321 *********************************************************************/
1323 int real_main(int argc, const char *argv[])
1325 int main(int argc, const char *argv[])
1330 "AmiTCP:db/junkbuster/config"
1331 #elif !defined(_WIN32)
1338 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1339 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1341 printf("JunkBuster proxy version " VERSION ".\n\n"
1342 "Usage: %s [configfile]\n\n"
1343 "See " HOME_PAGE_URL " for details.\n"
1344 "This program is distributed under the GNU GPL, version 2 or later.\n",
1348 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1350 printf(VERSION "\n");
1353 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1360 configfile = argv[1];
1367 #elif defined(_WIN32)
1373 signal(SIGPIPE, SIG_IGN);
1374 signal(SIGCHLD, SIG_IGN);
1376 #else /* ifdef _WIN32 */
1377 # ifdef _WIN_CONSOLE
1379 * We *are* in a windows console app.
1380 * Print a verbose messages about FAQ's and such
1382 printf(win32_blurb);
1383 # endif /* def _WIN_CONSOLE */
1384 #endif /* def _WIN32 */
1387 /* Initialize the CGI subsystem */
1388 cgi_init_error_messages();
1398 /*********************************************************************
1400 * Function : listen_loop
1402 * Description : bind the listen port and enter a "FOREVER" listening loop.
1408 *********************************************************************/
1409 static void listen_loop(void)
1411 struct client_state *csp = NULL;
1413 struct configuration_spec * config;
1415 config = load_config();
1417 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1418 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1420 bfd = bind_port(config->haddr, config->hport);
1424 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1425 "- There may be another junkbuster or some other "
1426 "proxy running on port %d",
1427 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1428 config->hport, config->hport
1430 /* shouldn't get here */
1434 config->need_bind = 0;
1439 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1440 while (waitpid(-1, NULL, WNOHANG) > 0)
1442 /* zombie children */
1444 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1447 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1449 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1453 csp->flags |= CSP_FLAG_ACTIVE;
1456 csp->config = config = load_config();
1458 if ( config->need_bind )
1461 * Since we were listening to the "old port", we will not see
1462 * a "listen" param change until the next IJB request. So, at
1463 * least 1 more request must be made for us to find the new
1464 * setting. I am simply closing the old socket and binding the
1467 * Which-ever is correct, we will serve 1 more page via the
1468 * old settings. This should probably be a "show-proxy-args"
1469 * request. This should not be a so common of an operation
1470 * that this will hurt people's feelings.
1475 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1476 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1477 bfd = bind_port(config->haddr, config->hport);
1481 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1482 "- There may be another junkbuster or some other "
1483 "proxy running on port %d",
1484 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1485 config->hport, config->hport
1487 /* shouldn't get here */
1491 config->need_bind = 0;
1494 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1496 if (!accept_connection(csp, bfd))
1498 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1511 log_error(LOG_LEVEL_CONNECT, "OK");
1514 #ifdef FEATURE_TOGGLE
1517 csp->flags |= CSP_FLAG_TOGGLED_ON;
1519 #endif /* def FEATURE_TOGGLE */
1521 if (run_loader(csp))
1523 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1524 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1528 if (block_acl(NULL,csp))
1530 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1531 close_socket(csp->cfd);
1535 #endif /* def FEATURE_ACL */
1537 /* add it to the list of clients */
1538 csp->next = clients->next;
1539 clients->next = csp;
1541 if (config->multi_threaded)
1545 /* this is a switch () statment in the C preprocessor - ugh */
1546 #undef SELECTED_ONE_OPTION
1548 /* Use Pthreads in preference to native code */
1549 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1550 #define SELECTED_ONE_OPTION
1552 pthread_t the_thread;
1553 pthread_attr_t attrs;
1555 pthread_attr_init(&attrs);
1556 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1557 child_id = (pthread_create(&the_thread, &attrs,
1558 (void*)serve, csp) ? -1 : 0);
1559 pthread_attr_destroy(&attrs);
1563 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1564 #define SELECTED_ONE_OPTION
1565 child_id = _beginthread(
1571 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1572 #define SELECTED_ONE_OPTION
1574 thread_id tid = spawn_thread
1575 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1577 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1579 child_id = (int) tid;
1588 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1589 #define SELECTED_ONE_OPTION
1590 csp->cfd = ReleaseSocket(csp->cfd, -1);
1591 if((child_id = (int)CreateNewProcTags(
1592 NP_Entry, (ULONG)server_thread,
1593 NP_Output, Output(),
1594 NP_CloseOutput, FALSE,
1595 NP_Name, (ULONG)"junkbuster child",
1596 NP_StackSize, 200*1024,
1600 ((struct Task *)child_id)->tc_UserData = csp;
1601 Signal((struct Task *)child_id, SIGF_SINGLE);
1606 #if !defined(SELECTED_ONE_OPTION)
1609 /* This block is only needed when using fork().
1610 * When using threads, the server thread was
1611 * created and run by the call to _beginthread().
1613 if (child_id == 0) /* child */
1619 else if (child_id > 0) /* parent */
1621 /* in a fork()'d environment, the parent's
1622 * copy of the client socket and the CSP
1626 #if !defined(_WIN32) && defined(__CYGWIN__)
1628 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1629 close_socket(csp->cfd);
1630 csp->flags &= ~CSP_FLAG_ACTIVE;
1634 #undef SELECTED_ONE_OPTION
1635 /* end of cpp switch () */
1637 if (child_id < 0) /* failed */
1639 char buf[BUFFER_SIZE];
1641 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1643 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1645 write_socket(csp->cfd, buf, strlen(buf));
1646 close_socket(csp->cfd);
1647 csp->flags &= ~CSP_FLAG_ACTIVE;