1 const char jcc_rcs[] = "$Id: jcc.c,v 1.52 2001/10/26 20:11:20 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.52 2001/10/26 20:11:20 jongfoster
37 * Fixing type mismatch
39 * Revision 1.51 2001/10/26 17:38:28 oes
42 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
43 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
44 * threads to call select() simultaneously. So, it's time to do a real, live,
45 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
46 * (native). Both versions will work, but using __OS2__ offers multi-threading.
48 * Revision 1.49 2001/10/23 21:41:35 jongfoster
49 * Added call to initialize the (statically-allocated of course)
50 * "out of memory" CGI response.
52 * Revision 1.48 2001/10/10 19:56:46 jongfoster
53 * Moving some code that wasn't cookie-related out of an #ifdef
56 * Revision 1.47 2001/10/10 16:44:36 oes
57 * Added CONNECT destination port limitation check
59 * Revision 1.46 2001/10/08 15:17:41 oes
60 * Re-enabled SSL forwarding
62 * Revision 1.45 2001/10/07 15:42:11 oes
63 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
65 * Moved downgrading of the HTTP version from parse_http_request to
66 * chat(), since we can't decide if it is necessary before we have
67 * determined the actions for the URL. The HTTP command is now
68 * *always* re-built so the repairs need no longer be special-cased.
70 * filter_popups now gets a csp pointer so it can raise the new
71 * CSP_FLAG_MODIFIED flag.
75 * Added configurable size limit for the IOB. If the IOB grows so
76 * large that the next read would exceed the limit, the header
77 * is generated, and the header & unfiltered buffer are flushed
78 * to the client. Chat then continues in non-buffering,
79 * non-filtering body mode.
81 * Revision 1.44 2001/10/02 18:13:57 oes
84 * Revision 1.43 2001/10/02 15:32:13 oes
85 * Moved generation of hdr
87 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
88 * Cleaning up 2 compiler warnings on OS/2.
90 * Revision 1.41 2001/09/16 17:05:14 jongfoster
91 * Removing unused #include showarg.h
93 * Revision 1.40 2001/09/16 15:41:45 jongfoster
94 * Fixing signed/unsigned comparison warning.
96 * Revision 1.39 2001/09/16 13:21:27 jongfoster
97 * Changes to use new list functions.
99 * Revision 1.38 2001/09/16 13:01:46 jongfoster
100 * Removing redundant function call that zeroed zalloc()'d memory.
102 * Revision 1.37 2001/09/10 11:12:24 oes
103 * Deleted unused variable
105 * Revision 1.36 2001/09/10 10:56:15 oes
106 * Silenced compiler warnings
108 * Revision 1.35 2001/07/31 14:44:22 oes
109 * Deleted unused size parameter from filter_popups()
111 * Revision 1.34 2001/07/30 22:08:36 jongfoster
112 * Tidying up #defines:
113 * - All feature #defines are now of the form FEATURE_xxx
114 * - Permanently turned off WIN_GUI_EDIT
115 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
117 * Revision 1.33 2001/07/29 19:32:00 jongfoster
118 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
120 * Revision 1.32 2001/07/29 18:47:05 jongfoster
121 * Adding missing #include "loadcfg.h"
123 * Revision 1.31 2001/07/29 12:17:48 oes
124 * Applied pthread fix by Paul Lieverse
126 * Revision 1.30 2001/07/25 22:57:13 jongfoster
127 * __BEOS__ no longer overrides FEATURE_PTHREAD.
128 * This is because FEATURE_PTHREAD will soon be widely used, so I
129 * want to keep it simple.
131 * Revision 1.29 2001/07/24 12:47:06 oes
132 * Applied BeOS support update by Eugenia
134 * Revision 1.28 2001/07/23 13:26:12 oes
135 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
137 * Revision 1.27 2001/07/19 19:09:47 haroon
138 * - Added code to take care of the situation where while processing the first
139 * server response (which includes the server header), after finding the end
140 * of the headers we were not looking past the end of the headers for
141 * content modification. I enabled it for filter_popups.
142 * Someone else should look to see if other similar operations should be
143 * done to the discarded portion of the buffer.
145 * Note 2001/07/20: No, the other content modification mechanisms will process
146 * the whole iob later anyway. --oes
148 * Revision 1.26 2001/07/18 12:31:36 oes
151 * Revision 1.25 2001/07/15 19:43:49 jongfoster
152 * Supports POSIX threads.
153 * Also removed some unused #includes.
155 * Revision 1.24 2001/07/13 14:00:40 oes
156 * - Generic content modification scheme:
157 * Each feature has its own applicability flag that is set
158 * from csp->action->flags.
159 * Replaced the "filtering" int flag , by a function pointer
160 * "content_filter" to the function that will do the content
161 * modification. If it is != NULL, the document will be buffered
162 * and processed through *content_filter, which must set
163 * csp->content_length and return a modified copy of the body
164 * or return NULL (on failiure).
165 * - Changed csp->is_text to the more generic bitmap csp->content_type
166 * which can currently take the valued CT_TEXT or CT_GIF
168 * - Removed all #ifdef PCRS
170 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
171 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
172 * the `block_acl' call. This prevents a compilation error when the user
173 * does not wish to use the "ACL" feature.
175 * Revision 1.22 2001/06/29 21:45:41 oes
176 * Indentation, CRLF->LF, Tab-> Space
178 * Revision 1.21 2001/06/29 13:29:36 oes
179 * - Cleaned up, improved comments
180 * - Unified all possible interceptors (CGI,
181 * block, trust, fast_redirect) in one
182 * place, with one (CGI) answer generation
183 * mechansim. Much clearer now.
184 * - Removed the GIF image generation, which
185 * is now done in filters.c:block_url()
186 * - Made error conditions like domain lookup
187 * failiure or (various) problems while talking
188 * to the server use cgi.c:error_response()
189 * instead of generating HTML/HTTP in chat() (yuck!)
190 * - Removed logentry from cancelled commit
192 * Revision 1.20 2001/06/09 10:55:28 jongfoster
193 * Changing BUFSIZ ==> BUFFER_SIZE
195 * Revision 1.19 2001/06/07 23:12:52 jongfoster
196 * Replacing function pointer in struct gateway with a directly
197 * called function forwarded_connect().
198 * Replacing struct gateway with struct forward_spec
200 * Revision 1.18 2001/06/03 19:12:16 oes
201 * introduced new cgi handling
203 * Revision 1.17 2001/06/01 20:07:23 jongfoster
204 * Now uses action +image-blocker{} rather than config->tinygif
206 * Revision 1.16 2001/06/01 18:49:17 jongfoster
207 * Replaced "list_share" with "list" - the tiny memory gain was not
208 * worth the extra complexity.
210 * Revision 1.15 2001/05/31 21:24:47 jongfoster
211 * Changed "permission" to "action" throughout.
212 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
213 * Moved vanilla wafer check into chat(), since we must now
214 * decide whether or not to add it based on the URL.
216 * Revision 1.14 2001/05/29 20:14:01 joergs
217 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
220 * Revision 1.13 2001/05/29 09:50:24 jongfoster
221 * Unified blocklist/imagelist/permissionslist.
222 * File format is still under discussion, but the internal changes
225 * Also modified interceptor behaviour:
226 * - We now intercept all URLs beginning with one of the following
227 * prefixes (and *only* these prefixes):
229 * * http://ijbswa.sf.net/config/
230 * * http://ijbswa.sourceforge.net/config/
231 * - New interceptors "home page" - go to http://i.j.b/ to see it.
232 * - Internal changes so that intercepted and fast redirect pages
233 * are not replaced with an image.
234 * - Interceptors now have the option to send a binary page direct
235 * to the client. (i.e. ijb-send-banner uses this)
236 * - Implemented show-url-info interceptor. (Which is why I needed
237 * the above interceptors changes - a typical URL is
238 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
239 * The previous mechanism would not have intercepted that, and
240 * if it had been intercepted then it then it would have replaced
243 * Revision 1.12 2001/05/27 22:17:04 oes
245 * - re_process_buffer no longer writes the modified buffer
246 * to the client, which was very ugly. It now returns the
247 * buffer, which it is then written by chat.
249 * - content_length now adjusts the Content-Length: header
250 * for modified documents rather than crunch()ing it.
251 * (Length info in csp->content_length, which is 0 for
252 * unmodified documents)
254 * - For this to work, sed() is called twice when filtering.
256 * Revision 1.11 2001/05/26 17:27:53 jongfoster
257 * Added support for CLF and fixed LOG_LEVEL_LOG.
258 * Also did CRLF->LF fix of my previous patch.
260 * Revision 1.10 2001/05/26 15:26:15 jongfoster
261 * ACL feature now provides more security by immediately dropping
262 * connections from untrusted hosts.
264 * Revision 1.9 2001/05/26 00:28:36 jongfoster
265 * Automatic reloading of config file.
266 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
267 * Most of the global variables have been moved to a new
268 * struct configuration_spec, accessed through csp->config->globalname
269 * Most of the globals remaining are used by the Win32 GUI.
271 * Revision 1.8 2001/05/25 22:43:18 jongfoster
272 * Fixing minor memory leak and buffer overflow.
274 * Revision 1.7 2001/05/25 22:34:30 jongfoster
277 * Revision 1.6 2001/05/23 00:13:58 joergs
278 * AmigaOS support fixed.
280 * Revision 1.5 2001/05/22 18:46:04 oes
282 * - Enabled filtering banners by size rather than URL
283 * by adding patterns that replace all standard banner
284 * sizes with the "Junkbuster" gif to the re_filterfile
286 * - Enabled filtering WebBugs by providing a pattern
287 * which kills all 1x1 images
289 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
290 * which is selected by the (nonstandard and therefore
291 * capital) letter 'U' in the option string.
292 * It causes the quantifiers to be ungreedy by default.
293 * Appending a ? turns back to greedy (!).
295 * - Added a new interceptor ijb-send-banner, which
296 * sends back the "Junkbuster" gif. Without imagelist or
297 * MSIE detection support, or if tinygif = 1, or the
298 * URL isn't recognized as an imageurl, a lame HTML
299 * explanation is sent instead.
301 * - Added new feature, which permits blocking remote
302 * script redirects and firing back a local redirect
304 * The feature is conditionally compiled, i.e. it
305 * can be disabled with --disable-fast-redirects,
306 * plus it must be activated by a "fast-redirects"
307 * line in the config file, has its own log level
308 * and of course wants to be displayed by show-proxy-args
309 * Note: Boy, all the #ifdefs in 1001 locations and
310 * all the fumbling with configure.in and acconfig.h
311 * were *way* more work than the feature itself :-(
313 * - Because a generic redirect template was needed for
314 * this, tinygif = 3 now uses the same.
316 * - Moved GIFs, and other static HTTP response templates
321 * - Removed some >400 CRs again (Jon, you really worked
324 * Revision 1.4 2001/05/21 19:34:01 jongfoster
325 * Made failure to bind() a fatal error.
327 * Revision 1.3 2001/05/20 01:21:20 jongfoster
328 * Version 2.9.4 checkin.
329 * - Merged popupfile and cookiefile, and added control over PCRS
330 * filtering, in new "permissionsfile".
331 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
332 * file error you now get a message box (in the Win32 GUI) rather
333 * than the program exiting with no explanation.
334 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
336 * - Removed tabs from "config"
337 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
338 * - Bumped up version number.
340 * Revision 1.2 2001/05/17 22:34:44 oes
341 * - Added hint on GIF char array generation to jcc.c
342 * - Cleaned CRLF's from the sources and related files
343 * - Repaired logging for REF and FRC
345 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
346 * Initial import of version 2.9.3 source tree
349 *********************************************************************/
355 #include <sys/types.h>
362 #ifdef FEATURE_PTHREAD
364 #endif /* def FEATURE_PTHREAD */
367 # ifndef FEATURE_PTHREAD
368 # include <windows.h>
369 # include <process.h>
370 # endif /* ndef FEATURE_PTHREAD */
373 # ifndef _WIN_CONSOLE
375 # endif /* ndef _WIN_CONSOLE */
377 #else /* ifndef _WIN32 */
379 # if !defined (__OS2__)
381 # include <sys/wait.h>
382 # endif /* ndef __OS2__ */
383 # include <sys/time.h>
384 # include <sys/stat.h>
385 # include <sys/ioctl.h>
388 #include <sys/termios.h>
394 # include <socket.h> /* BeOS has select() for sockets only. */
395 # include <OS.h> /* declarations for threads and stuff. */
398 # if defined(__EMX__) || defined(__OS2__)
399 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
404 #define bzero(B,N) memset(B,0x00,n)
423 #include "killpopup.h"
424 #include "miscutil.h"
426 #include "jbsockets.h"
432 const char jcc_h_rcs[] = JCC_H_VERSION;
433 const char project_h_rcs[] = PROJECT_H_VERSION;
435 struct client_state clients[1];
436 struct file_list files[1];
438 #ifdef FEATURE_STATISTICS
439 int urls_read = 0; /* total nr of urls read inc rejected */
440 int urls_rejected = 0; /* total nr of urls rejected */
441 #endif /* def FEATURE_STATISTICS */
444 static void listen_loop(void);
445 static void chat(struct client_state *csp);
447 void serve(struct client_state *csp);
448 #else /* ifndef AMIGA */
449 static void serve(struct client_state *csp);
450 #endif /* def AMIGA */
453 static int32 server_thread(void *data);
454 #endif /* def __BEOS__ */
457 #define sleep(N) Sleep(((N) * 1000))
461 #define sleep(N) DosSleep(((N) * 100))
466 #endif /* defined unix */
468 /* The vanilla wafer. */
469 static const char VANILLA_WAFER[] =
470 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
471 "Do_not_send_me_any_copyrighted_information_other_than_the_"
472 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
473 "In_particular_do_not_send_me_any_cookies_that_"
474 "are_subject_to_a_claim_of_copyright_by_anybody._"
475 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
476 "(copyright_or_otherwise)_applying_to_any_cookie._";
479 /*********************************************************************
483 * Description : Once a connection to the client has been accepted,
484 * this function is called (via serve()) to handle the
485 * main business of the communication. When this
486 * function returns, the caller must close the client
490 * 1 : csp = Current client state (buffers, headers, etc...)
492 * Returns : On success, the number of bytes written are returned (zero
493 * indicates nothing was written). On error, -1 is returned,
494 * and errno is set appropriately. If count is zero and the
495 * file descriptor refers to a regular file, 0 will be
496 * returned without causing any other effect. For a special
497 * file, the results are not portable.
499 *********************************************************************/
500 static void chat(struct client_state *csp)
503 * This next lines are a little ugly, but they simplifies the if statements
504 * below. Basically if TOGGLE, then we want the if to test if the
505 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
506 * then we want the if to test for CSP_FLAG_FORCED , else we don't
508 #ifdef FEATURE_TOGGLE
509 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
510 #else /* ifndef FEATURE_TOGGLE */
511 # define IS_TOGGLED_ON_AND
512 #endif /* ndef FEATURE_TOGGLE */
513 #ifdef FEATURE_FORCE_LOAD
514 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
515 #else /* ifndef FEATURE_FORCE_LOAD */
516 # define IS_NOT_FORCED_AND
517 #endif /* def FEATURE_FORCE_LOAD */
519 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
521 char buf[BUFFER_SIZE];
524 int n, maxfd, server_body;
525 int ms_iis5_hack = 0;
527 const struct forward_spec * fwd;
528 struct http_request *http;
529 #ifdef FEATURE_KILL_POPUPS
530 int block_popups; /* bool, 1==will block popups */
531 int block_popups_now = 0; /* bool, 1==currently blocking popups */
532 #endif /* def FEATURE_KILL_POPUPS */
534 int pcrs_filter; /* bool, 1==will filter through pcrs */
535 int gif_deanimate; /* bool, 1==will deanimate gifs */
537 /* Function that does the content filtering for the current request */
538 char *(*content_filter)() = NULL;
540 /* Skeleton for HTTP response, if we should intercept the request */
541 struct http_response *rsp;
546 * Read the client's request. Note that since we're not using select() we
547 * could get blocked here if a client connected, then didn't say anything!
552 n = read_socket(csp->cfd, buf, sizeof(buf));
554 if (n <= 0) break; /* error! */
556 add_to_iob(csp, buf, n);
558 req = get_header(csp);
562 break; /* no HTTP request! */
567 continue; /* more to come! */
570 #ifdef FEATURE_FORCE_LOAD
571 /* If this request contains the FORCE_PREFIX,
572 * better get rid of it now and set the force flag --oes
575 if (strstr(req, FORCE_PREFIX))
577 strclean(req, FORCE_PREFIX);
578 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
579 csp->flags |= CSP_FLAG_FORCED;
582 #endif /* def FEATURE_FORCE_LOAD */
584 parse_http_request(req, http, csp);
589 if (http->cmd == NULL)
591 strcpy(buf, CHEADER);
592 write_socket(csp->cfd, buf, strlen(buf));
594 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
599 /* decide how to route the HTTP request */
601 if ((fwd = forward_url(http, csp)) == NULL)
603 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
604 /* Never get here - LOG_LEVEL_FATAL causes program exit */
607 /* build the http request to send to the server
608 * we have to do one of the following:
610 * create = use the original HTTP request to create a new
611 * HTTP request that has either the path component
612 * without the http://domainspec (w/path) or the
613 * full orininal URL (w/url)
614 * Note that the path and/or the HTTP version may
615 * have been altered by now.
617 * connect = Open a socket to the host:port of the server
618 * and short-circuit server and client socket.
620 * pass = Pass the request unchanged if forwarding a CONNECT
621 * request to a parent proxy. Note that we'll be sending
622 * the CFAIL message ourselves if connecting to the parent
623 * fails, but we won't send a CSUCCEED message if it works,
624 * since that would result in a double message (ours and the
625 * parent's). After sending the request to the parent, we simply
631 * +--------+--------+
633 * 0 | create | connect|
635 * Forwarding +--------+--------+
637 * 1 | create | pass |
639 * +--------+--------+
644 * Determine the actions for this URL
646 #ifdef FEATURE_TOGGLE
647 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
649 /* Most compatible set of actions (i.e. none) */
650 init_current_action(csp->action);
653 #endif /* ndef FEATURE_TOGGLE */
655 url_actions(http, csp);
660 * Check if a CONNECT request is allowable:
661 * In the absence of a +limit-connect action, allow only port 443.
662 * If there is an action, allow whatever matches the specificaton.
666 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
667 || (csp->action->flags & ACTION_LIMIT_CONNECT
668 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
670 strcpy(buf, CFORBIDDEN);
671 write_socket(csp->cfd, buf, strlen(buf));
673 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
674 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
682 * Downgrade http version from 1.1 to 1.0 if +downgrade
685 if (!strcmpic(http->ver, "HTTP/1.1") && csp->action->flags & ACTION_DOWNGRADE)
688 http->ver = strdup("HTTP/1.0");
692 * (Re)build the HTTP request for non-SSL requests.
693 * If forwarding, use the whole URL, else, use only the path.
699 http->cmd = strsav(http->cmd, http->gpc);
700 http->cmd = strsav(http->cmd, " ");
702 if (fwd->forward_host)
704 http->cmd = strsav(http->cmd, http->url);
708 http->cmd = strsav(http->cmd, http->path);
711 http->cmd = strsav(http->cmd, " ");
712 http->cmd = strsav(http->cmd, http->ver);
715 enlist(csp->headers, http->cmd);
718 #ifdef FEATURE_COOKIE_JAR
720 * If we're logging cookies in a cookie jar, and the user has not
721 * supplied any wafers, and the user has not told us to suppress the
722 * vanilla wafer, then send the vanilla wafer.
724 if ((csp->config->jarfile != NULL)
725 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
726 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
728 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
730 #endif /* def FEATURE_COOKIE_JAR */
733 #ifdef FEATURE_KILL_POPUPS
734 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
735 #endif /* def FEATURE_KILL_POPUPS */
737 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
738 ((csp->action->flags & ACTION_FILTER) != 0);
740 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
742 /* grab the rest of the client's headers */
746 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
748 n = read_socket(csp->cfd, buf, sizeof(buf));
751 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
754 add_to_iob(csp, buf, n);
758 if (p == NULL) break;
760 enlist(csp->headers, p);
764 * We have a request. Now, check to see if we need to
765 * intercept it, i.e. If ..
769 /* a CGI call was detected and answered */
770 (NULL != (rsp = dispatch_cgi(csp)))
772 /* or we are enabled and... */
775 /* ..the request was blocked */
776 ( NULL != (rsp = block_url(csp)))
780 || ( NULL != (rsp = trust_url(csp)))
781 #endif /* def FEATURE_TRUST */
783 /* ..or a fast redirect kicked in */
784 #ifdef FEATURE_FAST_REDIRECTS
785 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
786 (NULL != (rsp = redirect_url(csp))))
787 #endif /* def FEATURE_FAST_REDIRECTS */
791 /* Write the answer to the client */
792 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
793 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
795 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
798 #ifdef FEATURE_STATISTICS
799 /* Count as a rejected request */
800 csp->flags |= CSP_FLAG_REJECTED;
801 #endif /* def FEATURE_STATISTICS */
803 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
804 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
805 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
807 /* Clean up and return */
808 free_http_response(rsp);
812 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
814 if (fwd->forward_host)
816 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
817 fwd->forward_host, fwd->forward_port, http->hostport);
821 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
824 /* here we connect to the server, gateway, or the forwarder */
826 csp->sfd = forwarded_connect(fwd, http, csp);
830 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
835 rsp = error_response(csp, "no-such-domain", errno);
837 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
838 csp->ip_addr_str, http->cmd);
842 rsp = error_response(csp, "connect-failed", errno);
844 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
845 csp->ip_addr_str, http->cmd);
848 /* Write the answer to the client */
851 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
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);
862 log_error(LOG_LEVEL_CONNECT, "OK");
864 hdr = sed(client_patterns, add_client_headers, csp);
865 list_remove_all(csp->headers);
867 if (fwd->forward_host || (http->ssl == 0))
869 /* write the client's (modified) header to the server
870 * (along with anything else that may be in the buffer)
875 if ((write_socket(csp->sfd, hdr, n) != n)
876 || (flush_socket(csp->sfd, csp ) < 0))
878 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
881 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
882 csp->ip_addr_str, http->cmd);
884 rsp = error_response(csp, "connect-failed", errno);
888 if ((write_socket(csp->cfd, rsp->head, n) != n)
889 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
891 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
895 free_http_response(rsp);
903 * We're running an SSL tunnel and we're not forwarding,
904 * so just send the "connect succeeded" message to the
905 * client, flush the rest, and get out of the way.
907 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
908 csp->ip_addr_str, http->cmd);
910 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
918 /* we're finished with the client's header */
921 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
923 /* pass data between the client and server
924 * until one or the other shuts down the connection.
933 FD_SET(csp->cfd, &rfds);
934 FD_SET(csp->sfd, &rfds);
936 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
940 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
944 /* this is the body of the browser's request
945 * just read it and write it.
948 if (FD_ISSET(csp->cfd, &rfds))
950 n = read_socket(csp->cfd, buf, sizeof(buf));
954 break; /* "game over, man" */
957 if (write_socket(csp->sfd, buf, n) != n)
959 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
966 * The server wants to talk. It could be the header or the body.
967 * If `hdr' is null, then it's the header otherwise it's the body.
968 * FIXME: Does `hdr' really mean `host'? No.
972 if (FD_ISSET(csp->sfd, &rfds))
975 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
979 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
981 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
982 csp->ip_addr_str, http->cmd);
984 rsp = error_response(csp, "connect-failed", errno);
988 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
989 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
991 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
995 free_http_response(rsp);
999 /* Add a trailing zero. This lets filter_popups
1000 * use string operations.
1004 #ifdef FEATURE_KILL_POPUPS
1005 /* Filter the popups on this read. */
1006 if (block_popups_now)
1008 filter_popups(buf, csp);
1010 #endif /* def FEATURE_KILL_POPUPS */
1012 /* Normally, this would indicate that we've read
1013 * as much as the server has sent us and we can
1014 * close the client connection. However, Microsoft
1015 * in its wisdom has released IIS/5 with a bug that
1016 * prevents it from sending the trailing \r\n in
1017 * a 302 redirect header (and possibly other headers).
1018 * To work around this if we've haven't parsed
1019 * a full header we'll append a trailing \r\n
1020 * and see if this now generates a valid one.
1022 * This hack shouldn't have any impacts. If we've
1023 * already transmitted the header or if this is a
1024 * SSL connection, then we won't bother with this
1025 * hack. So we only work on partially received
1026 * headers. If we append a \r\n and this still
1027 * doesn't generate a valid header, then we won't
1028 * transmit anything to the client.
1033 if (server_body || http->ssl)
1036 * If we have been buffering up the document,
1037 * now is the time to apply content modification
1038 * and send the result to the client.
1043 * If the content filter fails, use the original
1044 * buffer and length.
1045 * (see p != NULL ? p : csp->iob->cur below)
1047 if (NULL == (p = (*content_filter)(csp)))
1049 csp->content_length = csp->iob->eod - csp->iob->cur;
1052 hdr = sed(server_patterns, add_server_headers, csp);
1055 if ((write_socket(csp->cfd, hdr, n) != n)
1056 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1058 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1068 break; /* "game over, man" */
1072 * This is NOT the body, so
1073 * Let's pretend the server just sent us a blank line.
1075 n = sprintf(buf, "\r\n");
1078 * Now, let the normal header parsing algorithm below do its
1079 * job. If it fails, we'll exit instead of continuing.
1086 * If this is an SSL connection or we're in the body
1087 * of the server document, just write it to the client,
1088 * unless we need to buffer the body for later content-filtering
1091 if (server_body || http->ssl)
1095 add_to_iob(csp, buf, n);
1098 * If the buffer limit will be reached on the next read,
1099 * switch to non-filtering mode, i.e. make & write the
1100 * header, flush the socket and get out of the way.
1102 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1104 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1106 hdr = sed(server_patterns, add_server_headers, csp);
1110 if (((write_socket(csp->cfd, hdr, n) != n)
1111 || (n = flush_socket(csp->cfd, csp) < 0)))
1113 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1122 content_filter = NULL;
1129 if (write_socket(csp->cfd, buf, n) != n)
1131 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1140 /* we're still looking for the end of the
1141 * server's header ... (does that make header
1142 * parsing an "out of body experience" ?
1145 /* buffer up the data we just read */
1146 add_to_iob(csp, buf, n);
1148 /* get header lines from the iob */
1150 while ((p = get_header(csp)))
1154 /* see following note */
1157 enlist(csp->headers, p);
1161 /* NOTE: there are no "empty" headers so
1162 * if the pointer `p' is not NULL we must
1163 * assume that we reached the end of the
1164 * buffer before we hit the end of the header.
1171 /* Well, we tried our MS IIS/5
1172 * hack and it didn't work.
1173 * The header is incomplete
1174 * and there isn't anything
1175 * we can do about it.
1181 /* Since we have to wait for
1182 * more from the server before
1183 * we can parse the headers
1184 * we just continue here.
1190 /* we have now received the entire header.
1191 * filter it and send the result to the client
1194 hdr = sed(server_patterns, add_server_headers, csp);
1197 /* write the server's (modified) header to
1198 * the client (along with anything else that
1199 * may be in the buffer)
1202 #ifdef FEATURE_KILL_POPUPS
1203 /* Start blocking popups if appropriate. */
1205 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1206 !http->ssl && /* We talk plaintext */
1207 block_popups) /* Policy allows */
1209 block_popups_now = 1;
1211 * Filter the part of the body that came in the same read
1212 * as the last headers:
1214 filter_popups(csp->iob->cur, csp);
1217 #endif /* def FEATURE_KILL_POPUPS */
1219 /* Buffer and pcrs filter this if appropriate. */
1221 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1222 !http->ssl && /* We talk plaintext */
1223 pcrs_filter) /* Policy allows */
1225 content_filter = pcrs_filter_response;
1228 /* Buffer and gif_deanimate this if appropriate. */
1230 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1231 !http->ssl && /* We talk plaintext */
1232 gif_deanimate) /* Policy allows */
1234 content_filter = gif_deanimate_response;
1239 * Only write if we're not buffering for content modification
1241 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1242 || (n = flush_socket(csp->cfd, csp) < 0)))
1244 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1246 /* the write failed, so don't bother
1247 * mentioning it to the client...
1248 * it probably can't hear us anyway.
1254 if(!content_filter) byte_count += n;
1256 /* we're finished with the server's header */
1261 /* If this was a MS IIS/5 hack then it means
1262 * the server has already closed the
1263 * connection. Nothing more to read. Time
1274 return; /* huh? we should never get here */
1277 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1278 csp->ip_addr_str, http->cmd, byte_count);
1282 /*********************************************************************
1286 * Description : This is little more than chat. We only "serve" to
1287 * to close any socket that chat may have opened.
1290 * 1 : csp = Current client state (buffers, headers, etc...)
1294 *********************************************************************/
1296 void serve(struct client_state *csp)
1297 #else /* ifndef AMIGA */
1298 static void serve(struct client_state *csp)
1299 #endif /* def AMIGA */
1302 close_socket(csp->cfd);
1306 close_socket(csp->sfd);
1309 csp->flags &= ~CSP_FLAG_ACTIVE;
1315 /*********************************************************************
1317 * Function : server_thread
1319 * Description : We only exist to call `serve' in a threaded environment.
1322 * 1 : data = Current client state (buffers, headers, etc...)
1324 * Returns : Always 0.
1326 *********************************************************************/
1327 static int32 server_thread(void *data)
1329 serve((struct client_state *) data);
1336 /*********************************************************************
1340 * Description : Load the config file and start the listen loop.
1341 * This function is a lot more *sane* with the `load_config'
1342 * and `listen_loop' functions; although it stills does
1343 * a *little* too much for my taste.
1346 * 1 : argc = Number of parameters (including $0).
1347 * 2 : argv = Array of (char *)'s to the parameters.
1349 * Returns : 1 if : can't open config file, unrecognized directive,
1350 * stats requested in multi-thread mode, can't open the
1351 * log file, can't open the jar file, listen port is invalid,
1352 * any load fails, and can't bind port.
1354 * Else main never returns, the process must be signaled
1355 * to terminate execution. Or, on Windows, use the
1356 * "File", "Exit" menu option.
1358 *********************************************************************/
1360 int real_main(int argc, const char *argv[])
1362 int main(int argc, const char *argv[])
1369 "AmiTCP:db/junkbuster/config"
1370 #elif !defined(_WIN32)
1377 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1378 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1380 printf("JunkBuster proxy version " VERSION ".\n\n"
1381 "Usage: %s [configfile]\n\n"
1382 "See " HOME_PAGE_URL " for details.\n"
1383 "This program is distributed under the GNU GPL, version 2 or later.\n",
1387 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1389 printf(VERSION "\n");
1393 if ((argc >= 2) && (strcmp(argv[1], "-d")==0))
1397 fprintf(stderr,"debugging enabled..\n");
1400 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1405 if (argc > argc_pos )
1407 configfile = argv[argc_pos];
1411 if ( *configfile != '/' )
1415 DBG(1, ("configfile before '%s'\n",configfile) );
1417 /* make config-filename absolute here */
1418 if ( !(basedir = getcwd( NULL, 1024 )))
1420 perror("get working dir");
1422 DBG(1, ("working dir '%s'\n",basedir) );
1423 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1425 perror("malloc failed");
1428 strcpy( abs_file, basedir );
1429 strcat( abs_file, "/" );
1430 strcat( abs_file, configfile );
1431 configfile = abs_file;
1432 DBG(1, ("configfile after '%s'\n",configfile) );
1434 #endif /* defined unix */
1441 #elif defined(_WIN32)
1446 #if !defined(_WIN32) && !defined(__OS2__)
1447 signal(SIGPIPE, SIG_IGN);
1448 signal(SIGCHLD, SIG_IGN);
1450 #else /* ifdef _WIN32 */
1451 # ifdef _WIN_CONSOLE
1453 * We *are* in a windows console app.
1454 * Print a verbose messages about FAQ's and such
1456 printf(win32_blurb);
1457 # endif /* def _WIN_CONSOLE */
1458 #endif /* def _WIN32 */
1461 /* Initialize the CGI subsystem */
1462 cgi_init_error_messages();
1470 ** we make us a real daemon
1476 if ( pid < 0 ) /* error */
1481 else if ( pid != 0 ) /* parent */
1487 fd = open("/dev/tty", O_RDONLY);
1490 /* no error check here */
1491 ioctl( fd, TIOCNOTTY,0 );
1494 /* should close stderr (fd 2) here too, but the test for existence
1495 ** and load config file is done in listen_loop() and puts
1496 ** some messages on stderr there.
1500 close( 0 ); close( 1 );
1502 close( 0 ); close( 1 );
1507 #endif /* defined unix */
1509 DBG(1, ("call listen_loop() \n") );
1518 /*********************************************************************
1520 * Function : listen_loop
1522 * Description : bind the listen port and enter a "FOREVER" listening loop.
1528 *********************************************************************/
1529 static void listen_loop(void)
1531 struct client_state *csp = NULL;
1533 struct configuration_spec * config;
1535 config = load_config();
1537 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1538 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1540 bfd = bind_port(config->haddr, config->hport);
1544 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1545 "- There may be another junkbuster or some other "
1546 "proxy running on port %d",
1547 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1548 config->hport, config->hport
1550 /* shouldn't get here */
1554 config->need_bind = 0;
1559 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1560 while (waitpid(-1, NULL, WNOHANG) > 0)
1562 /* zombie children */
1564 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1567 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1569 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1573 csp->flags |= CSP_FLAG_ACTIVE;
1576 csp->config = config = load_config();
1578 if ( config->need_bind )
1581 * Since we were listening to the "old port", we will not see
1582 * a "listen" param change until the next IJB request. So, at
1583 * least 1 more request must be made for us to find the new
1584 * setting. I am simply closing the old socket and binding the
1587 * Which-ever is correct, we will serve 1 more page via the
1588 * old settings. This should probably be a "show-proxy-args"
1589 * request. This should not be a so common of an operation
1590 * that this will hurt people's feelings.
1595 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1596 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1597 bfd = bind_port(config->haddr, config->hport);
1601 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1602 "- There may be another junkbuster or some other "
1603 "proxy running on port %d",
1604 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1605 config->hport, config->hport
1607 /* shouldn't get here */
1611 config->need_bind = 0;
1614 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1616 if (!accept_connection(csp, bfd))
1618 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1631 log_error(LOG_LEVEL_CONNECT, "OK");
1634 #ifdef FEATURE_TOGGLE
1637 csp->flags |= CSP_FLAG_TOGGLED_ON;
1639 #endif /* def FEATURE_TOGGLE */
1641 if (run_loader(csp))
1643 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1644 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1648 if (block_acl(NULL,csp))
1650 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1651 close_socket(csp->cfd);
1655 #endif /* def FEATURE_ACL */
1657 /* add it to the list of clients */
1658 csp->next = clients->next;
1659 clients->next = csp;
1661 if (config->multi_threaded)
1665 /* this is a switch () statment in the C preprocessor - ugh */
1666 #undef SELECTED_ONE_OPTION
1668 /* Use Pthreads in preference to native code */
1669 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1670 #define SELECTED_ONE_OPTION
1672 pthread_t the_thread;
1673 pthread_attr_t attrs;
1675 pthread_attr_init(&attrs);
1676 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1677 child_id = (pthread_create(&the_thread, &attrs,
1678 (void*)serve, csp) ? -1 : 0);
1679 pthread_attr_destroy(&attrs);
1683 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1684 #define SELECTED_ONE_OPTION
1685 child_id = _beginthread(
1691 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1692 #define SELECTED_ONE_OPTION
1693 child_id = _beginthread(
1700 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1701 #define SELECTED_ONE_OPTION
1703 thread_id tid = spawn_thread
1704 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1706 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1708 child_id = (int) tid;
1717 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1718 #define SELECTED_ONE_OPTION
1719 csp->cfd = ReleaseSocket(csp->cfd, -1);
1720 if((child_id = (int)CreateNewProcTags(
1721 NP_Entry, (ULONG)server_thread,
1722 NP_Output, Output(),
1723 NP_CloseOutput, FALSE,
1724 NP_Name, (ULONG)"junkbuster child",
1725 NP_StackSize, 200*1024,
1729 ((struct Task *)child_id)->tc_UserData = csp;
1730 Signal((struct Task *)child_id, SIGF_SINGLE);
1735 #if !defined(SELECTED_ONE_OPTION)
1738 /* This block is only needed when using fork().
1739 * When using threads, the server thread was
1740 * created and run by the call to _beginthread().
1742 if (child_id == 0) /* child */
1748 else if (child_id > 0) /* parent */
1750 /* in a fork()'d environment, the parent's
1751 * copy of the client socket and the CSP
1755 #if !defined(_WIN32) && defined(__CYGWIN__)
1757 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1758 close_socket(csp->cfd);
1759 csp->flags &= ~CSP_FLAG_ACTIVE;
1763 #undef SELECTED_ONE_OPTION
1764 /* end of cpp switch () */
1766 if (child_id < 0) /* failed */
1768 char buf[BUFFER_SIZE];
1770 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1772 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1774 write_socket(csp->cfd, buf, strlen(buf));
1775 close_socket(csp->cfd);
1776 csp->flags &= ~CSP_FLAG_ACTIVE;