1 const char jcc_rcs[] = "$Id: jcc.c,v 1.51 2001/10/26 17:38:28 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.51 2001/10/26 17:38:28 oes
39 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
40 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
41 * threads to call select() simultaneously. So, it's time to do a real, live,
42 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
43 * (native). Both versions will work, but using __OS2__ offers multi-threading.
45 * Revision 1.49 2001/10/23 21:41:35 jongfoster
46 * Added call to initialize the (statically-allocated of course)
47 * "out of memory" CGI response.
49 * Revision 1.48 2001/10/10 19:56:46 jongfoster
50 * Moving some code that wasn't cookie-related out of an #ifdef
53 * Revision 1.47 2001/10/10 16:44:36 oes
54 * Added CONNECT destination port limitation check
56 * Revision 1.46 2001/10/08 15:17:41 oes
57 * Re-enabled SSL forwarding
59 * Revision 1.45 2001/10/07 15:42:11 oes
60 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
62 * Moved downgrading of the HTTP version from parse_http_request to
63 * chat(), since we can't decide if it is necessary before we have
64 * determined the actions for the URL. The HTTP command is now
65 * *always* re-built so the repairs need no longer be special-cased.
67 * filter_popups now gets a csp pointer so it can raise the new
68 * CSP_FLAG_MODIFIED flag.
72 * Added configurable size limit for the IOB. If the IOB grows so
73 * large that the next read would exceed the limit, the header
74 * is generated, and the header & unfiltered buffer are flushed
75 * to the client. Chat then continues in non-buffering,
76 * non-filtering body mode.
78 * Revision 1.44 2001/10/02 18:13:57 oes
81 * Revision 1.43 2001/10/02 15:32:13 oes
82 * Moved generation of hdr
84 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
85 * Cleaning up 2 compiler warnings on OS/2.
87 * Revision 1.41 2001/09/16 17:05:14 jongfoster
88 * Removing unused #include showarg.h
90 * Revision 1.40 2001/09/16 15:41:45 jongfoster
91 * Fixing signed/unsigned comparison warning.
93 * Revision 1.39 2001/09/16 13:21:27 jongfoster
94 * Changes to use new list functions.
96 * Revision 1.38 2001/09/16 13:01:46 jongfoster
97 * Removing redundant function call that zeroed zalloc()'d memory.
99 * Revision 1.37 2001/09/10 11:12:24 oes
100 * Deleted unused variable
102 * Revision 1.36 2001/09/10 10:56:15 oes
103 * Silenced compiler warnings
105 * Revision 1.35 2001/07/31 14:44:22 oes
106 * Deleted unused size parameter from filter_popups()
108 * Revision 1.34 2001/07/30 22:08:36 jongfoster
109 * Tidying up #defines:
110 * - All feature #defines are now of the form FEATURE_xxx
111 * - Permanently turned off WIN_GUI_EDIT
112 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
114 * Revision 1.33 2001/07/29 19:32:00 jongfoster
115 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
117 * Revision 1.32 2001/07/29 18:47:05 jongfoster
118 * Adding missing #include "loadcfg.h"
120 * Revision 1.31 2001/07/29 12:17:48 oes
121 * Applied pthread fix by Paul Lieverse
123 * Revision 1.30 2001/07/25 22:57:13 jongfoster
124 * __BEOS__ no longer overrides FEATURE_PTHREAD.
125 * This is because FEATURE_PTHREAD will soon be widely used, so I
126 * want to keep it simple.
128 * Revision 1.29 2001/07/24 12:47:06 oes
129 * Applied BeOS support update by Eugenia
131 * Revision 1.28 2001/07/23 13:26:12 oes
132 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
134 * Revision 1.27 2001/07/19 19:09:47 haroon
135 * - Added code to take care of the situation where while processing the first
136 * server response (which includes the server header), after finding the end
137 * of the headers we were not looking past the end of the headers for
138 * content modification. I enabled it for filter_popups.
139 * Someone else should look to see if other similar operations should be
140 * done to the discarded portion of the buffer.
142 * Note 2001/07/20: No, the other content modification mechanisms will process
143 * the whole iob later anyway. --oes
145 * Revision 1.26 2001/07/18 12:31:36 oes
148 * Revision 1.25 2001/07/15 19:43:49 jongfoster
149 * Supports POSIX threads.
150 * Also removed some unused #includes.
152 * Revision 1.24 2001/07/13 14:00:40 oes
153 * - Generic content modification scheme:
154 * Each feature has its own applicability flag that is set
155 * from csp->action->flags.
156 * Replaced the "filtering" int flag , by a function pointer
157 * "content_filter" to the function that will do the content
158 * modification. If it is != NULL, the document will be buffered
159 * and processed through *content_filter, which must set
160 * csp->content_length and return a modified copy of the body
161 * or return NULL (on failiure).
162 * - Changed csp->is_text to the more generic bitmap csp->content_type
163 * which can currently take the valued CT_TEXT or CT_GIF
165 * - Removed all #ifdef PCRS
167 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
168 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
169 * the `block_acl' call. This prevents a compilation error when the user
170 * does not wish to use the "ACL" feature.
172 * Revision 1.22 2001/06/29 21:45:41 oes
173 * Indentation, CRLF->LF, Tab-> Space
175 * Revision 1.21 2001/06/29 13:29:36 oes
176 * - Cleaned up, improved comments
177 * - Unified all possible interceptors (CGI,
178 * block, trust, fast_redirect) in one
179 * place, with one (CGI) answer generation
180 * mechansim. Much clearer now.
181 * - Removed the GIF image generation, which
182 * is now done in filters.c:block_url()
183 * - Made error conditions like domain lookup
184 * failiure or (various) problems while talking
185 * to the server use cgi.c:error_response()
186 * instead of generating HTML/HTTP in chat() (yuck!)
187 * - Removed logentry from cancelled commit
189 * Revision 1.20 2001/06/09 10:55:28 jongfoster
190 * Changing BUFSIZ ==> BUFFER_SIZE
192 * Revision 1.19 2001/06/07 23:12:52 jongfoster
193 * Replacing function pointer in struct gateway with a directly
194 * called function forwarded_connect().
195 * Replacing struct gateway with struct forward_spec
197 * Revision 1.18 2001/06/03 19:12:16 oes
198 * introduced new cgi handling
200 * Revision 1.17 2001/06/01 20:07:23 jongfoster
201 * Now uses action +image-blocker{} rather than config->tinygif
203 * Revision 1.16 2001/06/01 18:49:17 jongfoster
204 * Replaced "list_share" with "list" - the tiny memory gain was not
205 * worth the extra complexity.
207 * Revision 1.15 2001/05/31 21:24:47 jongfoster
208 * Changed "permission" to "action" throughout.
209 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
210 * Moved vanilla wafer check into chat(), since we must now
211 * decide whether or not to add it based on the URL.
213 * Revision 1.14 2001/05/29 20:14:01 joergs
214 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
217 * Revision 1.13 2001/05/29 09:50:24 jongfoster
218 * Unified blocklist/imagelist/permissionslist.
219 * File format is still under discussion, but the internal changes
222 * Also modified interceptor behaviour:
223 * - We now intercept all URLs beginning with one of the following
224 * prefixes (and *only* these prefixes):
226 * * http://ijbswa.sf.net/config/
227 * * http://ijbswa.sourceforge.net/config/
228 * - New interceptors "home page" - go to http://i.j.b/ to see it.
229 * - Internal changes so that intercepted and fast redirect pages
230 * are not replaced with an image.
231 * - Interceptors now have the option to send a binary page direct
232 * to the client. (i.e. ijb-send-banner uses this)
233 * - Implemented show-url-info interceptor. (Which is why I needed
234 * the above interceptors changes - a typical URL is
235 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
236 * The previous mechanism would not have intercepted that, and
237 * if it had been intercepted then it then it would have replaced
240 * Revision 1.12 2001/05/27 22:17:04 oes
242 * - re_process_buffer no longer writes the modified buffer
243 * to the client, which was very ugly. It now returns the
244 * buffer, which it is then written by chat.
246 * - content_length now adjusts the Content-Length: header
247 * for modified documents rather than crunch()ing it.
248 * (Length info in csp->content_length, which is 0 for
249 * unmodified documents)
251 * - For this to work, sed() is called twice when filtering.
253 * Revision 1.11 2001/05/26 17:27:53 jongfoster
254 * Added support for CLF and fixed LOG_LEVEL_LOG.
255 * Also did CRLF->LF fix of my previous patch.
257 * Revision 1.10 2001/05/26 15:26:15 jongfoster
258 * ACL feature now provides more security by immediately dropping
259 * connections from untrusted hosts.
261 * Revision 1.9 2001/05/26 00:28:36 jongfoster
262 * Automatic reloading of config file.
263 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
264 * Most of the global variables have been moved to a new
265 * struct configuration_spec, accessed through csp->config->globalname
266 * Most of the globals remaining are used by the Win32 GUI.
268 * Revision 1.8 2001/05/25 22:43:18 jongfoster
269 * Fixing minor memory leak and buffer overflow.
271 * Revision 1.7 2001/05/25 22:34:30 jongfoster
274 * Revision 1.6 2001/05/23 00:13:58 joergs
275 * AmigaOS support fixed.
277 * Revision 1.5 2001/05/22 18:46:04 oes
279 * - Enabled filtering banners by size rather than URL
280 * by adding patterns that replace all standard banner
281 * sizes with the "Junkbuster" gif to the re_filterfile
283 * - Enabled filtering WebBugs by providing a pattern
284 * which kills all 1x1 images
286 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
287 * which is selected by the (nonstandard and therefore
288 * capital) letter 'U' in the option string.
289 * It causes the quantifiers to be ungreedy by default.
290 * Appending a ? turns back to greedy (!).
292 * - Added a new interceptor ijb-send-banner, which
293 * sends back the "Junkbuster" gif. Without imagelist or
294 * MSIE detection support, or if tinygif = 1, or the
295 * URL isn't recognized as an imageurl, a lame HTML
296 * explanation is sent instead.
298 * - Added new feature, which permits blocking remote
299 * script redirects and firing back a local redirect
301 * The feature is conditionally compiled, i.e. it
302 * can be disabled with --disable-fast-redirects,
303 * plus it must be activated by a "fast-redirects"
304 * line in the config file, has its own log level
305 * and of course wants to be displayed by show-proxy-args
306 * Note: Boy, all the #ifdefs in 1001 locations and
307 * all the fumbling with configure.in and acconfig.h
308 * were *way* more work than the feature itself :-(
310 * - Because a generic redirect template was needed for
311 * this, tinygif = 3 now uses the same.
313 * - Moved GIFs, and other static HTTP response templates
318 * - Removed some >400 CRs again (Jon, you really worked
321 * Revision 1.4 2001/05/21 19:34:01 jongfoster
322 * Made failure to bind() a fatal error.
324 * Revision 1.3 2001/05/20 01:21:20 jongfoster
325 * Version 2.9.4 checkin.
326 * - Merged popupfile and cookiefile, and added control over PCRS
327 * filtering, in new "permissionsfile".
328 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
329 * file error you now get a message box (in the Win32 GUI) rather
330 * than the program exiting with no explanation.
331 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
333 * - Removed tabs from "config"
334 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
335 * - Bumped up version number.
337 * Revision 1.2 2001/05/17 22:34:44 oes
338 * - Added hint on GIF char array generation to jcc.c
339 * - Cleaned CRLF's from the sources and related files
340 * - Repaired logging for REF and FRC
342 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
343 * Initial import of version 2.9.3 source tree
346 *********************************************************************/
352 #include <sys/types.h>
359 #ifdef FEATURE_PTHREAD
361 #endif /* def FEATURE_PTHREAD */
364 # ifndef FEATURE_PTHREAD
365 # include <windows.h>
366 # include <process.h>
367 # endif /* ndef FEATURE_PTHREAD */
370 # ifndef _WIN_CONSOLE
372 # endif /* ndef _WIN_CONSOLE */
374 #else /* ifndef _WIN32 */
376 # if !defined (__OS2__)
378 # include <sys/wait.h>
379 # endif /* ndef __OS2__ */
380 # include <sys/time.h>
381 # include <sys/stat.h>
385 # include <socket.h> /* BeOS has select() for sockets only. */
386 # include <OS.h> /* declarations for threads and stuff. */
389 # if defined(__EMX__) || defined(__OS2__)
390 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
395 #define bzero(B,N) memset(B,0x00,n)
410 #include "killpopup.h"
411 #include "miscutil.h"
413 #include "jbsockets.h"
419 const char jcc_h_rcs[] = JCC_H_VERSION;
420 const char project_h_rcs[] = PROJECT_H_VERSION;
422 struct client_state clients[1];
423 struct file_list files[1];
425 #ifdef FEATURE_STATISTICS
426 int urls_read = 0; /* total nr of urls read inc rejected */
427 int urls_rejected = 0; /* total nr of urls rejected */
428 #endif /* def FEATURE_STATISTICS */
431 static void listen_loop(void);
432 static void chat(struct client_state *csp);
434 void serve(struct client_state *csp);
435 #else /* ifndef AMIGA */
436 static void serve(struct client_state *csp);
437 #endif /* def AMIGA */
440 static int32 server_thread(void *data);
441 #endif /* def __BEOS__ */
444 #define sleep(N) Sleep(((N) * 1000))
448 #define sleep(N) DosSleep(((N) * 100))
452 /* The vanilla wafer. */
453 static const char VANILLA_WAFER[] =
454 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
455 "Do_not_send_me_any_copyrighted_information_other_than_the_"
456 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
457 "In_particular_do_not_send_me_any_cookies_that_"
458 "are_subject_to_a_claim_of_copyright_by_anybody._"
459 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
460 "(copyright_or_otherwise)_applying_to_any_cookie._";
463 /*********************************************************************
467 * Description : Once a connection to the client has been accepted,
468 * this function is called (via serve()) to handle the
469 * main business of the communication. When this
470 * function returns, the caller must close the client
474 * 1 : csp = Current client state (buffers, headers, etc...)
476 * Returns : On success, the number of bytes written are returned (zero
477 * indicates nothing was written). On error, -1 is returned,
478 * and errno is set appropriately. If count is zero and the
479 * file descriptor refers to a regular file, 0 will be
480 * returned without causing any other effect. For a special
481 * file, the results are not portable.
483 *********************************************************************/
484 static void chat(struct client_state *csp)
487 * This next lines are a little ugly, but they simplifies the if statements
488 * below. Basically if TOGGLE, then we want the if to test if the
489 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
490 * then we want the if to test for CSP_FLAG_FORCED , else we don't
492 #ifdef FEATURE_TOGGLE
493 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
494 #else /* ifndef FEATURE_TOGGLE */
495 # define IS_TOGGLED_ON_AND
496 #endif /* ndef FEATURE_TOGGLE */
497 #ifdef FEATURE_FORCE_LOAD
498 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
499 #else /* ifndef FEATURE_FORCE_LOAD */
500 # define IS_NOT_FORCED_AND
501 #endif /* def FEATURE_FORCE_LOAD */
503 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
505 char buf[BUFFER_SIZE];
508 int n, maxfd, server_body;
509 int ms_iis5_hack = 0;
511 const struct forward_spec * fwd;
512 struct http_request *http;
513 #ifdef FEATURE_KILL_POPUPS
514 int block_popups; /* bool, 1==will block popups */
515 int block_popups_now = 0; /* bool, 1==currently blocking popups */
516 #endif /* def FEATURE_KILL_POPUPS */
518 int pcrs_filter; /* bool, 1==will filter through pcrs */
519 int gif_deanimate; /* bool, 1==will deanimate gifs */
521 /* Function that does the content filtering for the current request */
522 char *(*content_filter)() = NULL;
524 /* Skeleton for HTTP response, if we should intercept the request */
525 struct http_response *rsp;
530 * Read the client's request. Note that since we're not using select() we
531 * could get blocked here if a client connected, then didn't say anything!
536 n = read_socket(csp->cfd, buf, sizeof(buf));
538 if (n <= 0) break; /* error! */
540 add_to_iob(csp, buf, n);
542 req = get_header(csp);
546 break; /* no HTTP request! */
551 continue; /* more to come! */
554 #ifdef FEATURE_FORCE_LOAD
555 /* If this request contains the FORCE_PREFIX,
556 * better get rid of it now and set the force flag --oes
559 if (strstr(req, FORCE_PREFIX))
561 strclean(req, FORCE_PREFIX);
562 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
563 csp->flags |= CSP_FLAG_FORCED;
566 #endif /* def FEATURE_FORCE_LOAD */
568 parse_http_request(req, http, csp);
573 if (http->cmd == NULL)
575 strcpy(buf, CHEADER);
576 write_socket(csp->cfd, buf, strlen(buf));
578 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
583 /* decide how to route the HTTP request */
585 if ((fwd = forward_url(http, csp)) == NULL)
587 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
588 /* Never get here - LOG_LEVEL_FATAL causes program exit */
591 /* build the http request to send to the server
592 * we have to do one of the following:
594 * create = use the original HTTP request to create a new
595 * HTTP request that has either the path component
596 * without the http://domainspec (w/path) or the
597 * full orininal URL (w/url)
598 * Note that the path and/or the HTTP version may
599 * have been altered by now.
601 * connect = Open a socket to the host:port of the server
602 * and short-circuit server and client socket.
604 * pass = Pass the request unchanged if forwarding a CONNECT
605 * request to a parent proxy. Note that we'll be sending
606 * the CFAIL message ourselves if connecting to the parent
607 * fails, but we won't send a CSUCCEED message if it works,
608 * since that would result in a double message (ours and the
609 * parent's). After sending the request to the parent, we simply
615 * +--------+--------+
617 * 0 | create | connect|
619 * Forwarding +--------+--------+
621 * 1 | create | pass |
623 * +--------+--------+
628 * Determine the actions for this URL
630 #ifdef FEATURE_TOGGLE
631 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
633 /* Most compatible set of actions (i.e. none) */
634 init_current_action(csp->action);
637 #endif /* ndef FEATURE_TOGGLE */
639 url_actions(http, csp);
644 * Check if a CONNECT request is allowable:
645 * In the absence of a +limit-connect action, allow only port 443.
646 * If there is an action, allow whatever matches the specificaton.
650 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
651 || (csp->action->flags & ACTION_LIMIT_CONNECT
652 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
654 strcpy(buf, CFORBIDDEN);
655 write_socket(csp->cfd, buf, strlen(buf));
657 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
658 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
666 * Downgrade http version from 1.1 to 1.0 if +downgrade
669 if (!strcmpic(http->ver, "HTTP/1.1") && csp->action->flags & ACTION_DOWNGRADE)
672 http->ver = strdup("HTTP/1.0");
676 * (Re)build the HTTP request for non-SSL requests.
677 * If forwarding, use the whole URL, else, use only the path.
683 http->cmd = strsav(http->cmd, http->gpc);
684 http->cmd = strsav(http->cmd, " ");
686 if (fwd->forward_host)
688 http->cmd = strsav(http->cmd, http->url);
692 http->cmd = strsav(http->cmd, http->path);
695 http->cmd = strsav(http->cmd, " ");
696 http->cmd = strsav(http->cmd, http->ver);
699 enlist(csp->headers, http->cmd);
702 #ifdef FEATURE_COOKIE_JAR
704 * If we're logging cookies in a cookie jar, and the user has not
705 * supplied any wafers, and the user has not told us to suppress the
706 * vanilla wafer, then send the vanilla wafer.
708 if ((csp->config->jarfile != NULL)
709 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
710 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
712 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
714 #endif /* def FEATURE_COOKIE_JAR */
717 #ifdef FEATURE_KILL_POPUPS
718 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
719 #endif /* def FEATURE_KILL_POPUPS */
721 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
722 ((csp->action->flags & ACTION_FILTER) != 0);
724 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
726 /* grab the rest of the client's headers */
730 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
732 n = read_socket(csp->cfd, buf, sizeof(buf));
735 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
738 add_to_iob(csp, buf, n);
742 if (p == NULL) break;
744 enlist(csp->headers, p);
748 * We have a request. Now, check to see if we need to
749 * intercept it, i.e. If ..
753 /* a CGI call was detected and answered */
754 (NULL != (rsp = dispatch_cgi(csp)))
756 /* or we are enabled and... */
759 /* ..the request was blocked */
760 ( NULL != (rsp = block_url(csp)))
764 || ( NULL != (rsp = trust_url(csp)))
765 #endif /* def FEATURE_TRUST */
767 /* ..or a fast redirect kicked in */
768 #ifdef FEATURE_FAST_REDIRECTS
769 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
770 (NULL != (rsp = redirect_url(csp))))
771 #endif /* def FEATURE_FAST_REDIRECTS */
775 /* Write the answer to the client */
776 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
777 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
779 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
782 #ifdef FEATURE_STATISTICS
783 /* Count as a rejected request */
784 csp->flags |= CSP_FLAG_REJECTED;
785 #endif /* def FEATURE_STATISTICS */
787 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
788 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
789 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
791 /* Clean up and return */
792 free_http_response(rsp);
796 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
798 if (fwd->forward_host)
800 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
801 fwd->forward_host, fwd->forward_port, http->hostport);
805 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
808 /* here we connect to the server, gateway, or the forwarder */
810 csp->sfd = forwarded_connect(fwd, http, csp);
814 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
819 rsp = error_response(csp, "no-such-domain", errno);
821 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
822 csp->ip_addr_str, http->cmd);
826 rsp = error_response(csp, "connect-failed", errno);
828 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
829 csp->ip_addr_str, http->cmd);
832 /* Write the answer to the client */
835 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
836 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
838 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
842 free_http_response(rsp);
846 log_error(LOG_LEVEL_CONNECT, "OK");
848 hdr = sed(client_patterns, add_client_headers, csp);
849 list_remove_all(csp->headers);
851 if (fwd->forward_host || (http->ssl == 0))
853 /* write the client's (modified) header to the server
854 * (along with anything else that may be in the buffer)
859 if ((write_socket(csp->sfd, hdr, n) != n)
860 || (flush_socket(csp->sfd, csp ) < 0))
862 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
865 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
866 csp->ip_addr_str, http->cmd);
868 rsp = error_response(csp, "connect-failed", errno);
872 if ((write_socket(csp->cfd, rsp->head, n) != n)
873 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
875 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
879 free_http_response(rsp);
887 * We're running an SSL tunnel and we're not forwarding,
888 * so just send the "connect succeeded" message to the
889 * client, flush the rest, and get out of the way.
891 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
892 csp->ip_addr_str, http->cmd);
894 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
902 /* we're finished with the client's header */
905 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
907 /* pass data between the client and server
908 * until one or the other shuts down the connection.
917 FD_SET(csp->cfd, &rfds);
918 FD_SET(csp->sfd, &rfds);
920 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
924 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
928 /* this is the body of the browser's request
929 * just read it and write it.
932 if (FD_ISSET(csp->cfd, &rfds))
934 n = read_socket(csp->cfd, buf, sizeof(buf));
938 break; /* "game over, man" */
941 if (write_socket(csp->sfd, buf, n) != n)
943 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
950 * The server wants to talk. It could be the header or the body.
951 * If `hdr' is null, then it's the header otherwise it's the body.
952 * FIXME: Does `hdr' really mean `host'? No.
956 if (FD_ISSET(csp->sfd, &rfds))
959 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
963 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
965 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
966 csp->ip_addr_str, http->cmd);
968 rsp = error_response(csp, "connect-failed", errno);
972 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
973 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
975 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
979 free_http_response(rsp);
983 /* Add a trailing zero. This lets filter_popups
984 * use string operations.
988 #ifdef FEATURE_KILL_POPUPS
989 /* Filter the popups on this read. */
990 if (block_popups_now)
992 filter_popups(buf, csp);
994 #endif /* def FEATURE_KILL_POPUPS */
996 /* Normally, this would indicate that we've read
997 * as much as the server has sent us and we can
998 * close the client connection. However, Microsoft
999 * in its wisdom has released IIS/5 with a bug that
1000 * prevents it from sending the trailing \r\n in
1001 * a 302 redirect header (and possibly other headers).
1002 * To work around this if we've haven't parsed
1003 * a full header we'll append a trailing \r\n
1004 * and see if this now generates a valid one.
1006 * This hack shouldn't have any impacts. If we've
1007 * already transmitted the header or if this is a
1008 * SSL connection, then we won't bother with this
1009 * hack. So we only work on partially received
1010 * headers. If we append a \r\n and this still
1011 * doesn't generate a valid header, then we won't
1012 * transmit anything to the client.
1017 if (server_body || http->ssl)
1020 * If we have been buffering up the document,
1021 * now is the time to apply content modification
1022 * and send the result to the client.
1027 * If the content filter fails, use the original
1028 * buffer and length.
1029 * (see p != NULL ? p : csp->iob->cur below)
1031 if (NULL == (p = (*content_filter)(csp)))
1033 csp->content_length = csp->iob->eod - csp->iob->cur;
1036 hdr = sed(server_patterns, add_server_headers, csp);
1039 if ((write_socket(csp->cfd, hdr, n) != n)
1040 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1042 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1052 break; /* "game over, man" */
1056 * This is NOT the body, so
1057 * Let's pretend the server just sent us a blank line.
1059 n = sprintf(buf, "\r\n");
1062 * Now, let the normal header parsing algorithm below do its
1063 * job. If it fails, we'll exit instead of continuing.
1070 * If this is an SSL connection or we're in the body
1071 * of the server document, just write it to the client,
1072 * unless we need to buffer the body for later content-filtering
1075 if (server_body || http->ssl)
1079 add_to_iob(csp, buf, n);
1082 * If the buffer limit will be reached on the next read,
1083 * switch to non-filtering mode, i.e. make & write the
1084 * header, flush the socket and get out of the way.
1086 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1088 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1090 hdr = sed(server_patterns, add_server_headers, csp);
1094 if (((write_socket(csp->cfd, hdr, n) != n)
1095 || (n = flush_socket(csp->cfd, csp) < 0)))
1097 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1106 content_filter = NULL;
1113 if (write_socket(csp->cfd, buf, n) != n)
1115 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1124 /* we're still looking for the end of the
1125 * server's header ... (does that make header
1126 * parsing an "out of body experience" ?
1129 /* buffer up the data we just read */
1130 add_to_iob(csp, buf, n);
1132 /* get header lines from the iob */
1134 while ((p = get_header(csp)))
1138 /* see following note */
1141 enlist(csp->headers, p);
1145 /* NOTE: there are no "empty" headers so
1146 * if the pointer `p' is not NULL we must
1147 * assume that we reached the end of the
1148 * buffer before we hit the end of the header.
1155 /* Well, we tried our MS IIS/5
1156 * hack and it didn't work.
1157 * The header is incomplete
1158 * and there isn't anything
1159 * we can do about it.
1165 /* Since we have to wait for
1166 * more from the server before
1167 * we can parse the headers
1168 * we just continue here.
1174 /* we have now received the entire header.
1175 * filter it and send the result to the client
1178 hdr = sed(server_patterns, add_server_headers, csp);
1181 /* write the server's (modified) header to
1182 * the client (along with anything else that
1183 * may be in the buffer)
1186 #ifdef FEATURE_KILL_POPUPS
1187 /* Start blocking popups if appropriate. */
1189 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1190 !http->ssl && /* We talk plaintext */
1191 block_popups) /* Policy allows */
1193 block_popups_now = 1;
1195 * Filter the part of the body that came in the same read
1196 * as the last headers:
1198 filter_popups(csp->iob->cur, csp);
1201 #endif /* def FEATURE_KILL_POPUPS */
1203 /* Buffer and pcrs filter this if appropriate. */
1205 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1206 !http->ssl && /* We talk plaintext */
1207 pcrs_filter) /* Policy allows */
1209 content_filter = pcrs_filter_response;
1212 /* Buffer and gif_deanimate this if appropriate. */
1214 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1215 !http->ssl && /* We talk plaintext */
1216 gif_deanimate) /* Policy allows */
1218 content_filter = gif_deanimate_response;
1223 * Only write if we're not buffering for content modification
1225 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1226 || (n = flush_socket(csp->cfd, csp) < 0)))
1228 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1230 /* the write failed, so don't bother
1231 * mentioning it to the client...
1232 * it probably can't hear us anyway.
1238 if(!content_filter) byte_count += n;
1240 /* we're finished with the server's header */
1245 /* If this was a MS IIS/5 hack then it means
1246 * the server has already closed the
1247 * connection. Nothing more to read. Time
1258 return; /* huh? we should never get here */
1261 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1262 csp->ip_addr_str, http->cmd, byte_count);
1266 /*********************************************************************
1270 * Description : This is little more than chat. We only "serve" to
1271 * to close any socket that chat may have opened.
1274 * 1 : csp = Current client state (buffers, headers, etc...)
1278 *********************************************************************/
1280 void serve(struct client_state *csp)
1281 #else /* ifndef AMIGA */
1282 static void serve(struct client_state *csp)
1283 #endif /* def AMIGA */
1286 close_socket(csp->cfd);
1290 close_socket(csp->sfd);
1293 csp->flags &= ~CSP_FLAG_ACTIVE;
1299 /*********************************************************************
1301 * Function : server_thread
1303 * Description : We only exist to call `serve' in a threaded environment.
1306 * 1 : data = Current client state (buffers, headers, etc...)
1308 * Returns : Always 0.
1310 *********************************************************************/
1311 static int32 server_thread(void *data)
1313 serve((struct client_state *) data);
1320 /*********************************************************************
1324 * Description : Load the config file and start the listen loop.
1325 * This function is a lot more *sane* with the `load_config'
1326 * and `listen_loop' functions; although it stills does
1327 * a *little* too much for my taste.
1330 * 1 : argc = Number of parameters (including $0).
1331 * 2 : argv = Array of (char *)'s to the parameters.
1333 * Returns : 1 if : can't open config file, unrecognized directive,
1334 * stats requested in multi-thread mode, can't open the
1335 * log file, can't open the jar file, listen port is invalid,
1336 * any load fails, and can't bind port.
1338 * Else main never returns, the process must be signaled
1339 * to terminate execution. Or, on Windows, use the
1340 * "File", "Exit" menu option.
1342 *********************************************************************/
1344 int real_main(int argc, const char *argv[])
1346 int main(int argc, const char *argv[])
1351 "AmiTCP:db/junkbuster/config"
1352 #elif !defined(_WIN32)
1359 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1360 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1362 printf("JunkBuster proxy version " VERSION ".\n\n"
1363 "Usage: %s [configfile]\n\n"
1364 "See " HOME_PAGE_URL " for details.\n"
1365 "This program is distributed under the GNU GPL, version 2 or later.\n",
1369 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1371 printf(VERSION "\n");
1374 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1381 configfile = argv[1];
1388 #elif defined(_WIN32)
1393 #if !defined(_WIN32) && !defined(__OS2__)
1394 signal(SIGPIPE, SIG_IGN);
1395 signal(SIGCHLD, SIG_IGN);
1397 #else /* ifdef _WIN32 */
1398 # ifdef _WIN_CONSOLE
1400 * We *are* in a windows console app.
1401 * Print a verbose messages about FAQ's and such
1403 printf(win32_blurb);
1404 # endif /* def _WIN_CONSOLE */
1405 #endif /* def _WIN32 */
1408 /* Initialize the CGI subsystem */
1409 cgi_init_error_messages();
1419 /*********************************************************************
1421 * Function : listen_loop
1423 * Description : bind the listen port and enter a "FOREVER" listening loop.
1429 *********************************************************************/
1430 static void listen_loop(void)
1432 struct client_state *csp = NULL;
1434 struct configuration_spec * config;
1436 config = load_config();
1438 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1439 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1441 bfd = bind_port(config->haddr, config->hport);
1445 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1446 "- There may be another junkbuster or some other "
1447 "proxy running on port %d",
1448 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1449 config->hport, config->hport
1451 /* shouldn't get here */
1455 config->need_bind = 0;
1460 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1461 while (waitpid(-1, NULL, WNOHANG) > 0)
1463 /* zombie children */
1465 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1468 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1470 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1474 csp->flags |= CSP_FLAG_ACTIVE;
1477 csp->config = config = load_config();
1479 if ( config->need_bind )
1482 * Since we were listening to the "old port", we will not see
1483 * a "listen" param change until the next IJB request. So, at
1484 * least 1 more request must be made for us to find the new
1485 * setting. I am simply closing the old socket and binding the
1488 * Which-ever is correct, we will serve 1 more page via the
1489 * old settings. This should probably be a "show-proxy-args"
1490 * request. This should not be a so common of an operation
1491 * that this will hurt people's feelings.
1496 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1497 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1498 bfd = bind_port(config->haddr, config->hport);
1502 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1503 "- There may be another junkbuster or some other "
1504 "proxy running on port %d",
1505 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1506 config->hport, config->hport
1508 /* shouldn't get here */
1512 config->need_bind = 0;
1515 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1517 if (!accept_connection(csp, bfd))
1519 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1532 log_error(LOG_LEVEL_CONNECT, "OK");
1535 #ifdef FEATURE_TOGGLE
1538 csp->flags |= CSP_FLAG_TOGGLED_ON;
1540 #endif /* def FEATURE_TOGGLE */
1542 if (run_loader(csp))
1544 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1545 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1549 if (block_acl(NULL,csp))
1551 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1552 close_socket(csp->cfd);
1556 #endif /* def FEATURE_ACL */
1558 /* add it to the list of clients */
1559 csp->next = clients->next;
1560 clients->next = csp;
1562 if (config->multi_threaded)
1566 /* this is a switch () statment in the C preprocessor - ugh */
1567 #undef SELECTED_ONE_OPTION
1569 /* Use Pthreads in preference to native code */
1570 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1571 #define SELECTED_ONE_OPTION
1573 pthread_t the_thread;
1574 pthread_attr_t attrs;
1576 pthread_attr_init(&attrs);
1577 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1578 child_id = (pthread_create(&the_thread, &attrs,
1579 (void*)serve, csp) ? -1 : 0);
1580 pthread_attr_destroy(&attrs);
1584 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1585 #define SELECTED_ONE_OPTION
1586 child_id = _beginthread(
1592 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1593 #define SELECTED_ONE_OPTION
1594 child_id = _beginthread(
1601 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1602 #define SELECTED_ONE_OPTION
1604 thread_id tid = spawn_thread
1605 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1607 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1609 child_id = (int) tid;
1618 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1619 #define SELECTED_ONE_OPTION
1620 csp->cfd = ReleaseSocket(csp->cfd, -1);
1621 if((child_id = (int)CreateNewProcTags(
1622 NP_Entry, (ULONG)server_thread,
1623 NP_Output, Output(),
1624 NP_CloseOutput, FALSE,
1625 NP_Name, (ULONG)"junkbuster child",
1626 NP_StackSize, 200*1024,
1630 ((struct Task *)child_id)->tc_UserData = csp;
1631 Signal((struct Task *)child_id, SIGF_SINGLE);
1636 #if !defined(SELECTED_ONE_OPTION)
1639 /* This block is only needed when using fork().
1640 * When using threads, the server thread was
1641 * created and run by the call to _beginthread().
1643 if (child_id == 0) /* child */
1649 else if (child_id > 0) /* parent */
1651 /* in a fork()'d environment, the parent's
1652 * copy of the client socket and the CSP
1656 #if !defined(_WIN32) && defined(__CYGWIN__)
1658 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1659 close_socket(csp->cfd);
1660 csp->flags &= ~CSP_FLAG_ACTIVE;
1664 #undef SELECTED_ONE_OPTION
1665 /* end of cpp switch () */
1667 if (child_id < 0) /* failed */
1669 char buf[BUFFER_SIZE];
1671 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1673 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1675 write_socket(csp->cfd, buf, strlen(buf));
1676 close_socket(csp->cfd);
1677 csp->flags &= ~CSP_FLAG_ACTIVE;