1 const char jcc_rcs[] = "$Id: jcc.c,v 1.53 2001/11/05 21:41:43 steudten 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.53 2001/11/05 21:41:43 steudten
37 * Add changes to be a real daemon just for unix os.
38 * (change cwd to /, detach from controlling tty, set
39 * process group and session leader to the own process.
41 * Add some fatal-error log message for failed malloc().
42 * Add '-d' if compiled with 'configure --with-debug' to
43 * enable debug output.
45 * Revision 1.52 2001/10/26 20:11:20 jongfoster
46 * Fixing type mismatch
48 * Revision 1.51 2001/10/26 17:38:28 oes
51 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
52 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
53 * threads to call select() simultaneously. So, it's time to do a real, live,
54 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
55 * (native). Both versions will work, but using __OS2__ offers multi-threading.
57 * Revision 1.49 2001/10/23 21:41:35 jongfoster
58 * Added call to initialize the (statically-allocated of course)
59 * "out of memory" CGI response.
61 * Revision 1.48 2001/10/10 19:56:46 jongfoster
62 * Moving some code that wasn't cookie-related out of an #ifdef
65 * Revision 1.47 2001/10/10 16:44:36 oes
66 * Added CONNECT destination port limitation check
68 * Revision 1.46 2001/10/08 15:17:41 oes
69 * Re-enabled SSL forwarding
71 * Revision 1.45 2001/10/07 15:42:11 oes
72 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
74 * Moved downgrading of the HTTP version from parse_http_request to
75 * chat(), since we can't decide if it is necessary before we have
76 * determined the actions for the URL. The HTTP command is now
77 * *always* re-built so the repairs need no longer be special-cased.
79 * filter_popups now gets a csp pointer so it can raise the new
80 * CSP_FLAG_MODIFIED flag.
84 * Added configurable size limit for the IOB. If the IOB grows so
85 * large that the next read would exceed the limit, the header
86 * is generated, and the header & unfiltered buffer are flushed
87 * to the client. Chat then continues in non-buffering,
88 * non-filtering body mode.
90 * Revision 1.44 2001/10/02 18:13:57 oes
93 * Revision 1.43 2001/10/02 15:32:13 oes
94 * Moved generation of hdr
96 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
97 * Cleaning up 2 compiler warnings on OS/2.
99 * Revision 1.41 2001/09/16 17:05:14 jongfoster
100 * Removing unused #include showarg.h
102 * Revision 1.40 2001/09/16 15:41:45 jongfoster
103 * Fixing signed/unsigned comparison warning.
105 * Revision 1.39 2001/09/16 13:21:27 jongfoster
106 * Changes to use new list functions.
108 * Revision 1.38 2001/09/16 13:01:46 jongfoster
109 * Removing redundant function call that zeroed zalloc()'d memory.
111 * Revision 1.37 2001/09/10 11:12:24 oes
112 * Deleted unused variable
114 * Revision 1.36 2001/09/10 10:56:15 oes
115 * Silenced compiler warnings
117 * Revision 1.35 2001/07/31 14:44:22 oes
118 * Deleted unused size parameter from filter_popups()
120 * Revision 1.34 2001/07/30 22:08:36 jongfoster
121 * Tidying up #defines:
122 * - All feature #defines are now of the form FEATURE_xxx
123 * - Permanently turned off WIN_GUI_EDIT
124 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
126 * Revision 1.33 2001/07/29 19:32:00 jongfoster
127 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
129 * Revision 1.32 2001/07/29 18:47:05 jongfoster
130 * Adding missing #include "loadcfg.h"
132 * Revision 1.31 2001/07/29 12:17:48 oes
133 * Applied pthread fix by Paul Lieverse
135 * Revision 1.30 2001/07/25 22:57:13 jongfoster
136 * __BEOS__ no longer overrides FEATURE_PTHREAD.
137 * This is because FEATURE_PTHREAD will soon be widely used, so I
138 * want to keep it simple.
140 * Revision 1.29 2001/07/24 12:47:06 oes
141 * Applied BeOS support update by Eugenia
143 * Revision 1.28 2001/07/23 13:26:12 oes
144 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
146 * Revision 1.27 2001/07/19 19:09:47 haroon
147 * - Added code to take care of the situation where while processing the first
148 * server response (which includes the server header), after finding the end
149 * of the headers we were not looking past the end of the headers for
150 * content modification. I enabled it for filter_popups.
151 * Someone else should look to see if other similar operations should be
152 * done to the discarded portion of the buffer.
154 * Note 2001/07/20: No, the other content modification mechanisms will process
155 * the whole iob later anyway. --oes
157 * Revision 1.26 2001/07/18 12:31:36 oes
160 * Revision 1.25 2001/07/15 19:43:49 jongfoster
161 * Supports POSIX threads.
162 * Also removed some unused #includes.
164 * Revision 1.24 2001/07/13 14:00:40 oes
165 * - Generic content modification scheme:
166 * Each feature has its own applicability flag that is set
167 * from csp->action->flags.
168 * Replaced the "filtering" int flag , by a function pointer
169 * "content_filter" to the function that will do the content
170 * modification. If it is != NULL, the document will be buffered
171 * and processed through *content_filter, which must set
172 * csp->content_length and return a modified copy of the body
173 * or return NULL (on failiure).
174 * - Changed csp->is_text to the more generic bitmap csp->content_type
175 * which can currently take the valued CT_TEXT or CT_GIF
177 * - Removed all #ifdef PCRS
179 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
180 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
181 * the `block_acl' call. This prevents a compilation error when the user
182 * does not wish to use the "ACL" feature.
184 * Revision 1.22 2001/06/29 21:45:41 oes
185 * Indentation, CRLF->LF, Tab-> Space
187 * Revision 1.21 2001/06/29 13:29:36 oes
188 * - Cleaned up, improved comments
189 * - Unified all possible interceptors (CGI,
190 * block, trust, fast_redirect) in one
191 * place, with one (CGI) answer generation
192 * mechansim. Much clearer now.
193 * - Removed the GIF image generation, which
194 * is now done in filters.c:block_url()
195 * - Made error conditions like domain lookup
196 * failiure or (various) problems while talking
197 * to the server use cgi.c:error_response()
198 * instead of generating HTML/HTTP in chat() (yuck!)
199 * - Removed logentry from cancelled commit
201 * Revision 1.20 2001/06/09 10:55:28 jongfoster
202 * Changing BUFSIZ ==> BUFFER_SIZE
204 * Revision 1.19 2001/06/07 23:12:52 jongfoster
205 * Replacing function pointer in struct gateway with a directly
206 * called function forwarded_connect().
207 * Replacing struct gateway with struct forward_spec
209 * Revision 1.18 2001/06/03 19:12:16 oes
210 * introduced new cgi handling
212 * Revision 1.17 2001/06/01 20:07:23 jongfoster
213 * Now uses action +image-blocker{} rather than config->tinygif
215 * Revision 1.16 2001/06/01 18:49:17 jongfoster
216 * Replaced "list_share" with "list" - the tiny memory gain was not
217 * worth the extra complexity.
219 * Revision 1.15 2001/05/31 21:24:47 jongfoster
220 * Changed "permission" to "action" throughout.
221 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
222 * Moved vanilla wafer check into chat(), since we must now
223 * decide whether or not to add it based on the URL.
225 * Revision 1.14 2001/05/29 20:14:01 joergs
226 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
229 * Revision 1.13 2001/05/29 09:50:24 jongfoster
230 * Unified blocklist/imagelist/permissionslist.
231 * File format is still under discussion, but the internal changes
234 * Also modified interceptor behaviour:
235 * - We now intercept all URLs beginning with one of the following
236 * prefixes (and *only* these prefixes):
238 * * http://ijbswa.sf.net/config/
239 * * http://ijbswa.sourceforge.net/config/
240 * - New interceptors "home page" - go to http://i.j.b/ to see it.
241 * - Internal changes so that intercepted and fast redirect pages
242 * are not replaced with an image.
243 * - Interceptors now have the option to send a binary page direct
244 * to the client. (i.e. ijb-send-banner uses this)
245 * - Implemented show-url-info interceptor. (Which is why I needed
246 * the above interceptors changes - a typical URL is
247 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
248 * The previous mechanism would not have intercepted that, and
249 * if it had been intercepted then it then it would have replaced
252 * Revision 1.12 2001/05/27 22:17:04 oes
254 * - re_process_buffer no longer writes the modified buffer
255 * to the client, which was very ugly. It now returns the
256 * buffer, which it is then written by chat.
258 * - content_length now adjusts the Content-Length: header
259 * for modified documents rather than crunch()ing it.
260 * (Length info in csp->content_length, which is 0 for
261 * unmodified documents)
263 * - For this to work, sed() is called twice when filtering.
265 * Revision 1.11 2001/05/26 17:27:53 jongfoster
266 * Added support for CLF and fixed LOG_LEVEL_LOG.
267 * Also did CRLF->LF fix of my previous patch.
269 * Revision 1.10 2001/05/26 15:26:15 jongfoster
270 * ACL feature now provides more security by immediately dropping
271 * connections from untrusted hosts.
273 * Revision 1.9 2001/05/26 00:28:36 jongfoster
274 * Automatic reloading of config file.
275 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
276 * Most of the global variables have been moved to a new
277 * struct configuration_spec, accessed through csp->config->globalname
278 * Most of the globals remaining are used by the Win32 GUI.
280 * Revision 1.8 2001/05/25 22:43:18 jongfoster
281 * Fixing minor memory leak and buffer overflow.
283 * Revision 1.7 2001/05/25 22:34:30 jongfoster
286 * Revision 1.6 2001/05/23 00:13:58 joergs
287 * AmigaOS support fixed.
289 * Revision 1.5 2001/05/22 18:46:04 oes
291 * - Enabled filtering banners by size rather than URL
292 * by adding patterns that replace all standard banner
293 * sizes with the "Junkbuster" gif to the re_filterfile
295 * - Enabled filtering WebBugs by providing a pattern
296 * which kills all 1x1 images
298 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
299 * which is selected by the (nonstandard and therefore
300 * capital) letter 'U' in the option string.
301 * It causes the quantifiers to be ungreedy by default.
302 * Appending a ? turns back to greedy (!).
304 * - Added a new interceptor ijb-send-banner, which
305 * sends back the "Junkbuster" gif. Without imagelist or
306 * MSIE detection support, or if tinygif = 1, or the
307 * URL isn't recognized as an imageurl, a lame HTML
308 * explanation is sent instead.
310 * - Added new feature, which permits blocking remote
311 * script redirects and firing back a local redirect
313 * The feature is conditionally compiled, i.e. it
314 * can be disabled with --disable-fast-redirects,
315 * plus it must be activated by a "fast-redirects"
316 * line in the config file, has its own log level
317 * and of course wants to be displayed by show-proxy-args
318 * Note: Boy, all the #ifdefs in 1001 locations and
319 * all the fumbling with configure.in and acconfig.h
320 * were *way* more work than the feature itself :-(
322 * - Because a generic redirect template was needed for
323 * this, tinygif = 3 now uses the same.
325 * - Moved GIFs, and other static HTTP response templates
330 * - Removed some >400 CRs again (Jon, you really worked
333 * Revision 1.4 2001/05/21 19:34:01 jongfoster
334 * Made failure to bind() a fatal error.
336 * Revision 1.3 2001/05/20 01:21:20 jongfoster
337 * Version 2.9.4 checkin.
338 * - Merged popupfile and cookiefile, and added control over PCRS
339 * filtering, in new "permissionsfile".
340 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
341 * file error you now get a message box (in the Win32 GUI) rather
342 * than the program exiting with no explanation.
343 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
345 * - Removed tabs from "config"
346 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
347 * - Bumped up version number.
349 * Revision 1.2 2001/05/17 22:34:44 oes
350 * - Added hint on GIF char array generation to jcc.c
351 * - Cleaned CRLF's from the sources and related files
352 * - Repaired logging for REF and FRC
354 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
355 * Initial import of version 2.9.3 source tree
358 *********************************************************************/
364 #include <sys/types.h>
371 #ifdef FEATURE_PTHREAD
373 #endif /* def FEATURE_PTHREAD */
376 # ifndef FEATURE_PTHREAD
377 # include <windows.h>
378 # include <process.h>
379 # endif /* ndef FEATURE_PTHREAD */
382 # ifndef _WIN_CONSOLE
384 # endif /* ndef _WIN_CONSOLE */
386 #else /* ifndef _WIN32 */
388 # if !defined (__OS2__)
390 # include <sys/wait.h>
391 # endif /* ndef __OS2__ */
392 # include <sys/time.h>
393 # include <sys/stat.h>
394 # include <sys/ioctl.h>
397 #include <sys/termios.h>
403 # include <socket.h> /* BeOS has select() for sockets only. */
404 # include <OS.h> /* declarations for threads and stuff. */
407 # if defined(__EMX__) || defined(__OS2__)
408 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
413 #define bzero(B,N) memset(B,0x00,n)
432 #include "killpopup.h"
433 #include "miscutil.h"
435 #include "jbsockets.h"
441 const char jcc_h_rcs[] = JCC_H_VERSION;
442 const char project_h_rcs[] = PROJECT_H_VERSION;
444 struct client_state clients[1];
445 struct file_list files[1];
447 #ifdef FEATURE_STATISTICS
448 int urls_read = 0; /* total nr of urls read inc rejected */
449 int urls_rejected = 0; /* total nr of urls rejected */
450 #endif /* def FEATURE_STATISTICS */
453 static void listen_loop(void);
454 static void chat(struct client_state *csp);
456 void serve(struct client_state *csp);
457 #else /* ifndef AMIGA */
458 static void serve(struct client_state *csp);
459 #endif /* def AMIGA */
462 static int32 server_thread(void *data);
463 #endif /* def __BEOS__ */
466 #define sleep(N) Sleep(((N) * 1000))
470 #define sleep(N) DosSleep(((N) * 100))
475 #endif /* defined unix */
477 /* The vanilla wafer. */
478 static const char VANILLA_WAFER[] =
479 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
480 "Do_not_send_me_any_copyrighted_information_other_than_the_"
481 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
482 "In_particular_do_not_send_me_any_cookies_that_"
483 "are_subject_to_a_claim_of_copyright_by_anybody._"
484 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
485 "(copyright_or_otherwise)_applying_to_any_cookie._";
488 /*********************************************************************
492 * Description : Once a connection to the client has been accepted,
493 * this function is called (via serve()) to handle the
494 * main business of the communication. When this
495 * function returns, the caller must close the client
499 * 1 : csp = Current client state (buffers, headers, etc...)
501 * Returns : On success, the number of bytes written are returned (zero
502 * indicates nothing was written). On error, -1 is returned,
503 * and errno is set appropriately. If count is zero and the
504 * file descriptor refers to a regular file, 0 will be
505 * returned without causing any other effect. For a special
506 * file, the results are not portable.
508 *********************************************************************/
509 static void chat(struct client_state *csp)
512 * This next lines are a little ugly, but they simplifies the if statements
513 * below. Basically if TOGGLE, then we want the if to test if the
514 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
515 * then we want the if to test for CSP_FLAG_FORCED , else we don't
517 #ifdef FEATURE_TOGGLE
518 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
519 #else /* ifndef FEATURE_TOGGLE */
520 # define IS_TOGGLED_ON_AND
521 #endif /* ndef FEATURE_TOGGLE */
522 #ifdef FEATURE_FORCE_LOAD
523 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
524 #else /* ifndef FEATURE_FORCE_LOAD */
525 # define IS_NOT_FORCED_AND
526 #endif /* def FEATURE_FORCE_LOAD */
528 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
530 char buf[BUFFER_SIZE];
533 int n, maxfd, server_body;
534 int ms_iis5_hack = 0;
536 const struct forward_spec * fwd;
537 struct http_request *http;
538 #ifdef FEATURE_KILL_POPUPS
539 int block_popups; /* bool, 1==will block popups */
540 int block_popups_now = 0; /* bool, 1==currently blocking popups */
541 #endif /* def FEATURE_KILL_POPUPS */
543 int pcrs_filter; /* bool, 1==will filter through pcrs */
544 int gif_deanimate; /* bool, 1==will deanimate gifs */
546 /* Function that does the content filtering for the current request */
547 char *(*content_filter)() = NULL;
549 /* Skeleton for HTTP response, if we should intercept the request */
550 struct http_response *rsp;
555 * Read the client's request. Note that since we're not using select() we
556 * could get blocked here if a client connected, then didn't say anything!
561 n = read_socket(csp->cfd, buf, sizeof(buf));
563 if (n <= 0) break; /* error! */
565 add_to_iob(csp, buf, n);
567 req = get_header(csp);
571 break; /* no HTTP request! */
576 continue; /* more to come! */
579 #ifdef FEATURE_FORCE_LOAD
580 /* If this request contains the FORCE_PREFIX,
581 * better get rid of it now and set the force flag --oes
584 if (strstr(req, FORCE_PREFIX))
586 strclean(req, FORCE_PREFIX);
587 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
588 csp->flags |= CSP_FLAG_FORCED;
591 #endif /* def FEATURE_FORCE_LOAD */
593 parse_http_request(req, http, csp);
598 if (http->cmd == NULL)
600 strcpy(buf, CHEADER);
601 write_socket(csp->cfd, buf, strlen(buf));
603 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
608 /* decide how to route the HTTP request */
610 if ((fwd = forward_url(http, csp)) == NULL)
612 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
613 /* Never get here - LOG_LEVEL_FATAL causes program exit */
616 /* build the http request to send to the server
617 * we have to do one of the following:
619 * create = use the original HTTP request to create a new
620 * HTTP request that has either the path component
621 * without the http://domainspec (w/path) or the
622 * full orininal URL (w/url)
623 * Note that the path and/or the HTTP version may
624 * have been altered by now.
626 * connect = Open a socket to the host:port of the server
627 * and short-circuit server and client socket.
629 * pass = Pass the request unchanged if forwarding a CONNECT
630 * request to a parent proxy. Note that we'll be sending
631 * the CFAIL message ourselves if connecting to the parent
632 * fails, but we won't send a CSUCCEED message if it works,
633 * since that would result in a double message (ours and the
634 * parent's). After sending the request to the parent, we simply
640 * +--------+--------+
642 * 0 | create | connect|
644 * Forwarding +--------+--------+
646 * 1 | create | pass |
648 * +--------+--------+
653 * Determine the actions for this URL
655 #ifdef FEATURE_TOGGLE
656 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
658 /* Most compatible set of actions (i.e. none) */
659 init_current_action(csp->action);
662 #endif /* ndef FEATURE_TOGGLE */
664 url_actions(http, csp);
669 * Check if a CONNECT request is allowable:
670 * In the absence of a +limit-connect action, allow only port 443.
671 * If there is an action, allow whatever matches the specificaton.
675 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
676 || (csp->action->flags & ACTION_LIMIT_CONNECT
677 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
679 strcpy(buf, CFORBIDDEN);
680 write_socket(csp->cfd, buf, strlen(buf));
682 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
683 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
691 * Downgrade http version from 1.1 to 1.0 if +downgrade
694 if (!strcmpic(http->ver, "HTTP/1.1") && csp->action->flags & ACTION_DOWNGRADE)
697 http->ver = strdup("HTTP/1.0");
701 * (Re)build the HTTP request for non-SSL requests.
702 * If forwarding, use the whole URL, else, use only the path.
708 http->cmd = strsav(http->cmd, http->gpc);
709 http->cmd = strsav(http->cmd, " ");
711 if (fwd->forward_host)
713 http->cmd = strsav(http->cmd, http->url);
717 http->cmd = strsav(http->cmd, http->path);
720 http->cmd = strsav(http->cmd, " ");
721 http->cmd = strsav(http->cmd, http->ver);
724 enlist(csp->headers, http->cmd);
727 #ifdef FEATURE_COOKIE_JAR
729 * If we're logging cookies in a cookie jar, and the user has not
730 * supplied any wafers, and the user has not told us to suppress the
731 * vanilla wafer, then send the vanilla wafer.
733 if ((csp->config->jarfile != NULL)
734 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
735 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
737 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
739 #endif /* def FEATURE_COOKIE_JAR */
742 #ifdef FEATURE_KILL_POPUPS
743 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
744 #endif /* def FEATURE_KILL_POPUPS */
746 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
747 ((csp->action->flags & ACTION_FILTER) != 0);
749 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
751 /* grab the rest of the client's headers */
755 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
757 n = read_socket(csp->cfd, buf, sizeof(buf));
760 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
763 add_to_iob(csp, buf, n);
767 if (p == NULL) break;
769 enlist(csp->headers, p);
773 * We have a request. Now, check to see if we need to
774 * intercept it, i.e. If ..
778 /* a CGI call was detected and answered */
779 (NULL != (rsp = dispatch_cgi(csp)))
781 /* or we are enabled and... */
784 /* ..the request was blocked */
785 ( NULL != (rsp = block_url(csp)))
789 || ( NULL != (rsp = trust_url(csp)))
790 #endif /* def FEATURE_TRUST */
792 /* ..or a fast redirect kicked in */
793 #ifdef FEATURE_FAST_REDIRECTS
794 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
795 (NULL != (rsp = redirect_url(csp))))
796 #endif /* def FEATURE_FAST_REDIRECTS */
800 /* Write the answer to the client */
801 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
802 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
804 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
807 #ifdef FEATURE_STATISTICS
808 /* Count as a rejected request */
809 csp->flags |= CSP_FLAG_REJECTED;
810 #endif /* def FEATURE_STATISTICS */
812 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
813 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
814 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
816 /* Clean up and return */
817 free_http_response(rsp);
821 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
823 if (fwd->forward_host)
825 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
826 fwd->forward_host, fwd->forward_port, http->hostport);
830 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
833 /* here we connect to the server, gateway, or the forwarder */
835 csp->sfd = forwarded_connect(fwd, http, csp);
839 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
844 rsp = error_response(csp, "no-such-domain", errno);
846 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
847 csp->ip_addr_str, http->cmd);
851 rsp = error_response(csp, "connect-failed", errno);
853 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
854 csp->ip_addr_str, http->cmd);
857 /* Write the answer to the client */
860 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
861 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
863 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
867 free_http_response(rsp);
871 log_error(LOG_LEVEL_CONNECT, "OK");
873 hdr = sed(client_patterns, add_client_headers, csp);
874 list_remove_all(csp->headers);
876 if (fwd->forward_host || (http->ssl == 0))
878 /* write the client's (modified) header to the server
879 * (along with anything else that may be in the buffer)
884 if ((write_socket(csp->sfd, hdr, n) != n)
885 || (flush_socket(csp->sfd, csp ) < 0))
887 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
890 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
891 csp->ip_addr_str, http->cmd);
893 rsp = error_response(csp, "connect-failed", errno);
897 if ((write_socket(csp->cfd, rsp->head, n) != n)
898 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
900 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
904 free_http_response(rsp);
912 * We're running an SSL tunnel and we're not forwarding,
913 * so just send the "connect succeeded" message to the
914 * client, flush the rest, and get out of the way.
916 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
917 csp->ip_addr_str, http->cmd);
919 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
927 /* we're finished with the client's header */
930 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
932 /* pass data between the client and server
933 * until one or the other shuts down the connection.
942 FD_SET(csp->cfd, &rfds);
943 FD_SET(csp->sfd, &rfds);
945 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
949 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
953 /* this is the body of the browser's request
954 * just read it and write it.
957 if (FD_ISSET(csp->cfd, &rfds))
959 n = read_socket(csp->cfd, buf, sizeof(buf));
963 break; /* "game over, man" */
966 if (write_socket(csp->sfd, buf, n) != n)
968 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
975 * The server wants to talk. It could be the header or the body.
976 * If `hdr' is null, then it's the header otherwise it's the body.
977 * FIXME: Does `hdr' really mean `host'? No.
981 if (FD_ISSET(csp->sfd, &rfds))
984 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
988 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
990 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
991 csp->ip_addr_str, http->cmd);
993 rsp = error_response(csp, "connect-failed", errno);
997 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
998 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1000 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1004 free_http_response(rsp);
1008 /* Add a trailing zero. This lets filter_popups
1009 * use string operations.
1013 #ifdef FEATURE_KILL_POPUPS
1014 /* Filter the popups on this read. */
1015 if (block_popups_now)
1017 filter_popups(buf, csp);
1019 #endif /* def FEATURE_KILL_POPUPS */
1021 /* Normally, this would indicate that we've read
1022 * as much as the server has sent us and we can
1023 * close the client connection. However, Microsoft
1024 * in its wisdom has released IIS/5 with a bug that
1025 * prevents it from sending the trailing \r\n in
1026 * a 302 redirect header (and possibly other headers).
1027 * To work around this if we've haven't parsed
1028 * a full header we'll append a trailing \r\n
1029 * and see if this now generates a valid one.
1031 * This hack shouldn't have any impacts. If we've
1032 * already transmitted the header or if this is a
1033 * SSL connection, then we won't bother with this
1034 * hack. So we only work on partially received
1035 * headers. If we append a \r\n and this still
1036 * doesn't generate a valid header, then we won't
1037 * transmit anything to the client.
1042 if (server_body || http->ssl)
1045 * If we have been buffering up the document,
1046 * now is the time to apply content modification
1047 * and send the result to the client.
1052 * If the content filter fails, use the original
1053 * buffer and length.
1054 * (see p != NULL ? p : csp->iob->cur below)
1056 if (NULL == (p = (*content_filter)(csp)))
1058 csp->content_length = csp->iob->eod - csp->iob->cur;
1061 hdr = sed(server_patterns, add_server_headers, csp);
1064 if ((write_socket(csp->cfd, hdr, n) != n)
1065 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1067 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1077 break; /* "game over, man" */
1081 * This is NOT the body, so
1082 * Let's pretend the server just sent us a blank line.
1084 n = sprintf(buf, "\r\n");
1087 * Now, let the normal header parsing algorithm below do its
1088 * job. If it fails, we'll exit instead of continuing.
1095 * If this is an SSL connection or we're in the body
1096 * of the server document, just write it to the client,
1097 * unless we need to buffer the body for later content-filtering
1100 if (server_body || http->ssl)
1104 add_to_iob(csp, buf, n);
1107 * If the buffer limit will be reached on the next read,
1108 * switch to non-filtering mode, i.e. make & write the
1109 * header, flush the socket and get out of the way.
1111 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1113 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1115 hdr = sed(server_patterns, add_server_headers, csp);
1119 if (((write_socket(csp->cfd, hdr, n) != n)
1120 || (n = flush_socket(csp->cfd, csp) < 0)))
1122 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1131 content_filter = NULL;
1138 if (write_socket(csp->cfd, buf, n) != n)
1140 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1149 /* we're still looking for the end of the
1150 * server's header ... (does that make header
1151 * parsing an "out of body experience" ?
1154 /* buffer up the data we just read */
1155 add_to_iob(csp, buf, n);
1157 /* get header lines from the iob */
1159 while ((p = get_header(csp)))
1163 /* see following note */
1166 enlist(csp->headers, p);
1170 /* NOTE: there are no "empty" headers so
1171 * if the pointer `p' is not NULL we must
1172 * assume that we reached the end of the
1173 * buffer before we hit the end of the header.
1180 /* Well, we tried our MS IIS/5
1181 * hack and it didn't work.
1182 * The header is incomplete
1183 * and there isn't anything
1184 * we can do about it.
1190 /* Since we have to wait for
1191 * more from the server before
1192 * we can parse the headers
1193 * we just continue here.
1199 /* we have now received the entire header.
1200 * filter it and send the result to the client
1203 hdr = sed(server_patterns, add_server_headers, csp);
1206 /* write the server's (modified) header to
1207 * the client (along with anything else that
1208 * may be in the buffer)
1211 #ifdef FEATURE_KILL_POPUPS
1212 /* Start blocking popups if appropriate. */
1214 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1215 !http->ssl && /* We talk plaintext */
1216 block_popups) /* Policy allows */
1218 block_popups_now = 1;
1220 * Filter the part of the body that came in the same read
1221 * as the last headers:
1223 filter_popups(csp->iob->cur, csp);
1226 #endif /* def FEATURE_KILL_POPUPS */
1228 /* Buffer and pcrs filter this if appropriate. */
1230 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1231 !http->ssl && /* We talk plaintext */
1232 pcrs_filter) /* Policy allows */
1234 content_filter = pcrs_filter_response;
1237 /* Buffer and gif_deanimate this if appropriate. */
1239 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1240 !http->ssl && /* We talk plaintext */
1241 gif_deanimate) /* Policy allows */
1243 content_filter = gif_deanimate_response;
1248 * Only write if we're not buffering for content modification
1250 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1251 || (n = flush_socket(csp->cfd, csp) < 0)))
1253 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1255 /* the write failed, so don't bother
1256 * mentioning it to the client...
1257 * it probably can't hear us anyway.
1263 if(!content_filter) byte_count += n;
1265 /* we're finished with the server's header */
1270 /* If this was a MS IIS/5 hack then it means
1271 * the server has already closed the
1272 * connection. Nothing more to read. Time
1283 return; /* huh? we should never get here */
1286 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1287 csp->ip_addr_str, http->cmd, byte_count);
1291 /*********************************************************************
1295 * Description : This is little more than chat. We only "serve" to
1296 * to close any socket that chat may have opened.
1299 * 1 : csp = Current client state (buffers, headers, etc...)
1303 *********************************************************************/
1305 void serve(struct client_state *csp)
1306 #else /* ifndef AMIGA */
1307 static void serve(struct client_state *csp)
1308 #endif /* def AMIGA */
1311 close_socket(csp->cfd);
1315 close_socket(csp->sfd);
1318 csp->flags &= ~CSP_FLAG_ACTIVE;
1324 /*********************************************************************
1326 * Function : server_thread
1328 * Description : We only exist to call `serve' in a threaded environment.
1331 * 1 : data = Current client state (buffers, headers, etc...)
1333 * Returns : Always 0.
1335 *********************************************************************/
1336 static int32 server_thread(void *data)
1338 serve((struct client_state *) data);
1345 /*********************************************************************
1349 * Description : Load the config file and start the listen loop.
1350 * This function is a lot more *sane* with the `load_config'
1351 * and `listen_loop' functions; although it stills does
1352 * a *little* too much for my taste.
1355 * 1 : argc = Number of parameters (including $0).
1356 * 2 : argv = Array of (char *)'s to the parameters.
1358 * Returns : 1 if : can't open config file, unrecognized directive,
1359 * stats requested in multi-thread mode, can't open the
1360 * log file, can't open the jar file, listen port is invalid,
1361 * any load fails, and can't bind port.
1363 * Else main never returns, the process must be signaled
1364 * to terminate execution. Or, on Windows, use the
1365 * "File", "Exit" menu option.
1367 *********************************************************************/
1369 int real_main(int argc, const char *argv[])
1371 int main(int argc, const char *argv[])
1378 "AmiTCP:db/junkbuster/config"
1379 #elif !defined(_WIN32)
1386 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1387 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1389 printf("JunkBuster proxy version " VERSION ".\n\n"
1390 "Usage: %s [configfile]\n\n"
1391 "See " HOME_PAGE_URL " for details.\n"
1392 "This program is distributed under the GNU GPL, version 2 or later.\n",
1396 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1398 printf(VERSION "\n");
1402 if ((argc >= 2) && (strcmp(argv[1], "-d")==0))
1406 fprintf(stderr,"debugging enabled..\n");
1409 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1414 if (argc > argc_pos )
1416 configfile = argv[argc_pos];
1420 if ( *configfile != '/' )
1424 DBG(1, ("configfile before '%s'\n",configfile) );
1426 /* make config-filename absolute here */
1427 if ( !(basedir = getcwd( NULL, 1024 )))
1429 perror("get working dir failed");
1432 DBG(1, ("working dir '%s'\n",basedir) );
1433 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1435 perror("malloc failed");
1438 strcpy( abs_file, basedir );
1439 strcat( abs_file, "/" );
1440 strcat( abs_file, configfile );
1441 configfile = abs_file;
1442 DBG(1, ("configfile after '%s'\n",configfile) );
1444 #endif /* defined unix */
1451 #elif defined(_WIN32)
1456 #if !defined(_WIN32) && !defined(__OS2__)
1457 signal(SIGPIPE, SIG_IGN);
1458 signal(SIGCHLD, SIG_IGN);
1460 #else /* ifdef _WIN32 */
1461 # ifdef _WIN_CONSOLE
1463 * We *are* in a windows console app.
1464 * Print a verbose messages about FAQ's and such
1466 printf(win32_blurb);
1467 # endif /* def _WIN_CONSOLE */
1468 #endif /* def _WIN32 */
1471 /* Initialize the CGI subsystem */
1472 cgi_init_error_messages();
1480 ** we make us a real daemon
1486 if ( pid < 0 ) /* error */
1491 else if ( pid != 0 ) /* parent */
1496 ** must check for errors
1497 ** child died due to missing files aso
1500 wpid = waitpid( pid, &status, WNOHANG );
1509 fd = open("/dev/tty", O_RDONLY);
1512 /* no error check here */
1513 ioctl( fd, TIOCNOTTY,0 );
1516 /* should close stderr (fd 2) here too, but the test for existence
1517 ** and load config file is done in listen_loop() and puts
1518 ** some messages on stderr there.
1522 close( 0 ); close( 1 );
1524 close( 0 ); close( 1 );
1529 #endif /* defined unix */
1531 DBG(1, ("call listen_loop() \n") );
1540 /*********************************************************************
1542 * Function : listen_loop
1544 * Description : bind the listen port and enter a "FOREVER" listening loop.
1550 *********************************************************************/
1551 static void listen_loop(void)
1553 struct client_state *csp = NULL;
1555 struct configuration_spec * config;
1557 config = load_config();
1559 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1560 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1562 bfd = bind_port(config->haddr, config->hport);
1566 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1567 "- There may be another junkbuster or some other "
1568 "proxy running on port %d",
1569 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1570 config->hport, config->hport
1572 /* shouldn't get here */
1576 config->need_bind = 0;
1580 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1581 while (waitpid(-1, NULL, WNOHANG) > 0)
1583 /* zombie children */
1585 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1588 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1590 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1594 csp->flags |= CSP_FLAG_ACTIVE;
1597 csp->config = config = load_config();
1599 if ( config->need_bind )
1602 * Since we were listening to the "old port", we will not see
1603 * a "listen" param change until the next IJB request. So, at
1604 * least 1 more request must be made for us to find the new
1605 * setting. I am simply closing the old socket and binding the
1608 * Which-ever is correct, we will serve 1 more page via the
1609 * old settings. This should probably be a "show-proxy-args"
1610 * request. This should not be a so common of an operation
1611 * that this will hurt people's feelings.
1616 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1617 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1618 bfd = bind_port(config->haddr, config->hport);
1622 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1623 "- There may be another junkbuster or some other "
1624 "proxy running on port %d",
1625 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1626 config->hport, config->hport
1628 /* shouldn't get here */
1632 config->need_bind = 0;
1635 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1637 if (!accept_connection(csp, bfd))
1639 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1652 log_error(LOG_LEVEL_CONNECT, "OK");
1655 #ifdef FEATURE_TOGGLE
1658 csp->flags |= CSP_FLAG_TOGGLED_ON;
1660 #endif /* def FEATURE_TOGGLE */
1662 if (run_loader(csp))
1664 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1665 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1669 if (block_acl(NULL,csp))
1671 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1672 close_socket(csp->cfd);
1676 #endif /* def FEATURE_ACL */
1678 /* add it to the list of clients */
1679 csp->next = clients->next;
1680 clients->next = csp;
1682 if (config->multi_threaded)
1686 /* this is a switch () statment in the C preprocessor - ugh */
1687 #undef SELECTED_ONE_OPTION
1689 /* Use Pthreads in preference to native code */
1690 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1691 #define SELECTED_ONE_OPTION
1693 pthread_t the_thread;
1694 pthread_attr_t attrs;
1696 pthread_attr_init(&attrs);
1697 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1698 child_id = (pthread_create(&the_thread, &attrs,
1699 (void*)serve, csp) ? -1 : 0);
1700 pthread_attr_destroy(&attrs);
1704 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1705 #define SELECTED_ONE_OPTION
1706 child_id = _beginthread(
1712 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1713 #define SELECTED_ONE_OPTION
1714 child_id = _beginthread(
1721 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1722 #define SELECTED_ONE_OPTION
1724 thread_id tid = spawn_thread
1725 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1727 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1729 child_id = (int) tid;
1738 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1739 #define SELECTED_ONE_OPTION
1740 csp->cfd = ReleaseSocket(csp->cfd, -1);
1741 if((child_id = (int)CreateNewProcTags(
1742 NP_Entry, (ULONG)server_thread,
1743 NP_Output, Output(),
1744 NP_CloseOutput, FALSE,
1745 NP_Name, (ULONG)"junkbuster child",
1746 NP_StackSize, 200*1024,
1750 ((struct Task *)child_id)->tc_UserData = csp;
1751 Signal((struct Task *)child_id, SIGF_SINGLE);
1756 #if !defined(SELECTED_ONE_OPTION)
1759 /* This block is only needed when using fork().
1760 * When using threads, the server thread was
1761 * created and run by the call to _beginthread().
1763 if (child_id == 0) /* child */
1769 else if (child_id > 0) /* parent */
1771 /* in a fork()'d environment, the parent's
1772 * copy of the client socket and the CSP
1776 #if !defined(_WIN32) && defined(__CYGWIN__)
1778 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1779 close_socket(csp->cfd);
1780 csp->flags &= ~CSP_FLAG_ACTIVE;
1784 #undef SELECTED_ONE_OPTION
1785 /* end of cpp switch () */
1787 if (child_id < 0) /* failed */
1789 char buf[BUFFER_SIZE];
1791 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1793 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1795 write_socket(csp->cfd, buf, strlen(buf));
1796 close_socket(csp->cfd);
1797 csp->flags &= ~CSP_FLAG_ACTIVE;