1 const char jcc_rcs[] = "$Id: jcc.c,v 1.44 2001/10/02 18:13:57 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.44 2001/10/02 18:13:57 oes
39 * Revision 1.43 2001/10/02 15:32:13 oes
40 * Moved generation of hdr
42 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
43 * Cleaning up 2 compiler warnings on OS/2.
45 * Revision 1.41 2001/09/16 17:05:14 jongfoster
46 * Removing unused #include showarg.h
48 * Revision 1.40 2001/09/16 15:41:45 jongfoster
49 * Fixing signed/unsigned comparison warning.
51 * Revision 1.39 2001/09/16 13:21:27 jongfoster
52 * Changes to use new list functions.
54 * Revision 1.38 2001/09/16 13:01:46 jongfoster
55 * Removing redundant function call that zeroed zalloc()'d memory.
57 * Revision 1.37 2001/09/10 11:12:24 oes
58 * Deleted unused variable
60 * Revision 1.36 2001/09/10 10:56:15 oes
61 * Silenced compiler warnings
63 * Revision 1.35 2001/07/31 14:44:22 oes
64 * Deleted unused size parameter from filter_popups()
66 * Revision 1.34 2001/07/30 22:08:36 jongfoster
67 * Tidying up #defines:
68 * - All feature #defines are now of the form FEATURE_xxx
69 * - Permanently turned off WIN_GUI_EDIT
70 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
72 * Revision 1.33 2001/07/29 19:32:00 jongfoster
73 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
75 * Revision 1.32 2001/07/29 18:47:05 jongfoster
76 * Adding missing #include "loadcfg.h"
78 * Revision 1.31 2001/07/29 12:17:48 oes
79 * Applied pthread fix by Paul Lieverse
81 * Revision 1.30 2001/07/25 22:57:13 jongfoster
82 * __BEOS__ no longer overrides FEATURE_PTHREAD.
83 * This is because FEATURE_PTHREAD will soon be widely used, so I
84 * want to keep it simple.
86 * Revision 1.29 2001/07/24 12:47:06 oes
87 * Applied BeOS support update by Eugenia
89 * Revision 1.28 2001/07/23 13:26:12 oes
90 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
92 * Revision 1.27 2001/07/19 19:09:47 haroon
93 * - Added code to take care of the situation where while processing the first
94 * server response (which includes the server header), after finding the end
95 * of the headers we were not looking past the end of the headers for
96 * content modification. I enabled it for filter_popups.
97 * Someone else should look to see if other similar operations should be
98 * done to the discarded portion of the buffer.
100 * Note 2001/07/20: No, the other content modification mechanisms will process
101 * the whole iob later anyway. --oes
103 * Revision 1.26 2001/07/18 12:31:36 oes
106 * Revision 1.25 2001/07/15 19:43:49 jongfoster
107 * Supports POSIX threads.
108 * Also removed some unused #includes.
110 * Revision 1.24 2001/07/13 14:00:40 oes
111 * - Generic content modification scheme:
112 * Each feature has its own applicability flag that is set
113 * from csp->action->flags.
114 * Replaced the "filtering" int flag , by a function pointer
115 * "content_filter" to the function that will do the content
116 * modification. If it is != NULL, the document will be buffered
117 * and processed through *content_filter, which must set
118 * csp->content_length and return a modified copy of the body
119 * or return NULL (on failiure).
120 * - Changed csp->is_text to the more generic bitmap csp->content_type
121 * which can currently take the valued CT_TEXT or CT_GIF
123 * - Removed all #ifdef PCRS
125 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
126 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
127 * the `block_acl' call. This prevents a compilation error when the user
128 * does not wish to use the "ACL" feature.
130 * Revision 1.22 2001/06/29 21:45:41 oes
131 * Indentation, CRLF->LF, Tab-> Space
133 * Revision 1.21 2001/06/29 13:29:36 oes
134 * - Cleaned up, improved comments
135 * - Unified all possible interceptors (CGI,
136 * block, trust, fast_redirect) in one
137 * place, with one (CGI) answer generation
138 * mechansim. Much clearer now.
139 * - Removed the GIF image generation, which
140 * is now done in filters.c:block_url()
141 * - Made error conditions like domain lookup
142 * failiure or (various) problems while talking
143 * to the server use cgi.c:error_response()
144 * instead of generating HTML/HTTP in chat() (yuck!)
145 * - Removed logentry from cancelled commit
147 * Revision 1.20 2001/06/09 10:55:28 jongfoster
148 * Changing BUFSIZ ==> BUFFER_SIZE
150 * Revision 1.19 2001/06/07 23:12:52 jongfoster
151 * Replacing function pointer in struct gateway with a directly
152 * called function forwarded_connect().
153 * Replacing struct gateway with struct forward_spec
155 * Revision 1.18 2001/06/03 19:12:16 oes
156 * introduced new cgi handling
158 * Revision 1.17 2001/06/01 20:07:23 jongfoster
159 * Now uses action +image-blocker{} rather than config->tinygif
161 * Revision 1.16 2001/06/01 18:49:17 jongfoster
162 * Replaced "list_share" with "list" - the tiny memory gain was not
163 * worth the extra complexity.
165 * Revision 1.15 2001/05/31 21:24:47 jongfoster
166 * Changed "permission" to "action" throughout.
167 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
168 * Moved vanilla wafer check into chat(), since we must now
169 * decide whether or not to add it based on the URL.
171 * Revision 1.14 2001/05/29 20:14:01 joergs
172 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
175 * Revision 1.13 2001/05/29 09:50:24 jongfoster
176 * Unified blocklist/imagelist/permissionslist.
177 * File format is still under discussion, but the internal changes
180 * Also modified interceptor behaviour:
181 * - We now intercept all URLs beginning with one of the following
182 * prefixes (and *only* these prefixes):
184 * * http://ijbswa.sf.net/config/
185 * * http://ijbswa.sourceforge.net/config/
186 * - New interceptors "home page" - go to http://i.j.b/ to see it.
187 * - Internal changes so that intercepted and fast redirect pages
188 * are not replaced with an image.
189 * - Interceptors now have the option to send a binary page direct
190 * to the client. (i.e. ijb-send-banner uses this)
191 * - Implemented show-url-info interceptor. (Which is why I needed
192 * the above interceptors changes - a typical URL is
193 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
194 * The previous mechanism would not have intercepted that, and
195 * if it had been intercepted then it then it would have replaced
198 * Revision 1.12 2001/05/27 22:17:04 oes
200 * - re_process_buffer no longer writes the modified buffer
201 * to the client, which was very ugly. It now returns the
202 * buffer, which it is then written by chat.
204 * - content_length now adjusts the Content-Length: header
205 * for modified documents rather than crunch()ing it.
206 * (Length info in csp->content_length, which is 0 for
207 * unmodified documents)
209 * - For this to work, sed() is called twice when filtering.
211 * Revision 1.11 2001/05/26 17:27:53 jongfoster
212 * Added support for CLF and fixed LOG_LEVEL_LOG.
213 * Also did CRLF->LF fix of my previous patch.
215 * Revision 1.10 2001/05/26 15:26:15 jongfoster
216 * ACL feature now provides more security by immediately dropping
217 * connections from untrusted hosts.
219 * Revision 1.9 2001/05/26 00:28:36 jongfoster
220 * Automatic reloading of config file.
221 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
222 * Most of the global variables have been moved to a new
223 * struct configuration_spec, accessed through csp->config->globalname
224 * Most of the globals remaining are used by the Win32 GUI.
226 * Revision 1.8 2001/05/25 22:43:18 jongfoster
227 * Fixing minor memory leak and buffer overflow.
229 * Revision 1.7 2001/05/25 22:34:30 jongfoster
232 * Revision 1.6 2001/05/23 00:13:58 joergs
233 * AmigaOS support fixed.
235 * Revision 1.5 2001/05/22 18:46:04 oes
237 * - Enabled filtering banners by size rather than URL
238 * by adding patterns that replace all standard banner
239 * sizes with the "Junkbuster" gif to the re_filterfile
241 * - Enabled filtering WebBugs by providing a pattern
242 * which kills all 1x1 images
244 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
245 * which is selected by the (nonstandard and therefore
246 * capital) letter 'U' in the option string.
247 * It causes the quantifiers to be ungreedy by default.
248 * Appending a ? turns back to greedy (!).
250 * - Added a new interceptor ijb-send-banner, which
251 * sends back the "Junkbuster" gif. Without imagelist or
252 * MSIE detection support, or if tinygif = 1, or the
253 * URL isn't recognized as an imageurl, a lame HTML
254 * explanation is sent instead.
256 * - Added new feature, which permits blocking remote
257 * script redirects and firing back a local redirect
259 * The feature is conditionally compiled, i.e. it
260 * can be disabled with --disable-fast-redirects,
261 * plus it must be activated by a "fast-redirects"
262 * line in the config file, has its own log level
263 * and of course wants to be displayed by show-proxy-args
264 * Note: Boy, all the #ifdefs in 1001 locations and
265 * all the fumbling with configure.in and acconfig.h
266 * were *way* more work than the feature itself :-(
268 * - Because a generic redirect template was needed for
269 * this, tinygif = 3 now uses the same.
271 * - Moved GIFs, and other static HTTP response templates
276 * - Removed some >400 CRs again (Jon, you really worked
279 * Revision 1.4 2001/05/21 19:34:01 jongfoster
280 * Made failure to bind() a fatal error.
282 * Revision 1.3 2001/05/20 01:21:20 jongfoster
283 * Version 2.9.4 checkin.
284 * - Merged popupfile and cookiefile, and added control over PCRS
285 * filtering, in new "permissionsfile".
286 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
287 * file error you now get a message box (in the Win32 GUI) rather
288 * than the program exiting with no explanation.
289 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
291 * - Removed tabs from "config"
292 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
293 * - Bumped up version number.
295 * Revision 1.2 2001/05/17 22:34:44 oes
296 * - Added hint on GIF char array generation to jcc.c
297 * - Cleaned CRLF's from the sources and related files
298 * - Repaired logging for REF and FRC
300 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
301 * Initial import of version 2.9.3 source tree
304 *********************************************************************/
310 #include <sys/types.h>
317 #ifdef FEATURE_PTHREAD
319 #endif /* def FEATURE_PTHREAD */
322 # ifndef FEATURE_PTHREAD
323 # include <windows.h>
324 # include <process.h>
325 # endif /* ndef FEATURE_PTHREAD */
328 # ifndef _WIN_CONSOLE
330 # endif /* ndef _WIN_CONSOLE */
332 #else /* ifndef _WIN32 */
335 # include <sys/time.h>
336 # include <sys/wait.h>
337 # include <sys/stat.h>
341 # include <socket.h> /* BeOS has select() for sockets only. */
342 # include <OS.h> /* declarations for threads and stuff. */
346 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
361 #include "killpopup.h"
362 #include "miscutil.h"
364 #include "jbsockets.h"
370 const char jcc_h_rcs[] = JCC_H_VERSION;
371 const char project_h_rcs[] = PROJECT_H_VERSION;
373 struct client_state clients[1];
374 struct file_list files[1];
376 #ifdef FEATURE_STATISTICS
377 int urls_read = 0; /* total nr of urls read inc rejected */
378 int urls_rejected = 0; /* total nr of urls rejected */
379 #endif /* def FEATURE_STATISTICS */
382 static void listen_loop(void);
383 static void chat(struct client_state *csp);
385 void serve(struct client_state *csp);
386 #else /* ifndef AMIGA */
387 static void serve(struct client_state *csp);
388 #endif /* def AMIGA */
391 static int32 server_thread(void *data);
392 #endif /* def __BEOS__ */
395 #define sleep(N) Sleep(((N) * 1000))
399 /* The vanilla wafer. */
400 static const char VANILLA_WAFER[] =
401 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
402 "Do_not_send_me_any_copyrighted_information_other_than_the_"
403 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
404 "In_particular_do_not_send_me_any_cookies_that_"
405 "are_subject_to_a_claim_of_copyright_by_anybody._"
406 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
407 "(copyright_or_otherwise)_applying_to_any_cookie._";
410 /*********************************************************************
414 * Description : Once a connection to the client has been accepted,
415 * this function is called (via serve()) to handle the
416 * main business of the communication. When this
417 * function returns, the caller must close the client
421 * 1 : csp = Current client state (buffers, headers, etc...)
423 * Returns : On success, the number of bytes written are returned (zero
424 * indicates nothing was written). On error, -1 is returned,
425 * and errno is set appropriately. If count is zero and the
426 * file descriptor refers to a regular file, 0 will be
427 * returned without causing any other effect. For a special
428 * file, the results are not portable.
430 *********************************************************************/
431 static void chat(struct client_state *csp)
434 * This next lines are a little ugly, but they simplifies the if statements
435 * below. Basically if TOGGLE, then we want the if to test if the
436 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
437 * then we want the if to test for CSP_FLAG_FORCED , else we don't
439 #ifdef FEATURE_TOGGLE
440 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
441 #else /* ifndef FEATURE_TOGGLE */
442 # define IS_TOGGLED_ON_AND
443 #endif /* ndef FEATURE_TOGGLE */
444 #ifdef FEATURE_FORCE_LOAD
445 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
446 #else /* ifndef FEATURE_FORCE_LOAD */
447 # define IS_NOT_FORCED_AND
448 #endif /* def FEATURE_FORCE_LOAD */
450 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
452 char buf[BUFFER_SIZE];
455 int n, maxfd, server_body;
456 int ms_iis5_hack = 0;
458 const struct forward_spec * fwd;
459 struct http_request *http;
460 #ifdef FEATURE_KILL_POPUPS
461 int block_popups; /* bool, 1==will block popups */
462 int block_popups_now = 0; /* bool, 1==currently blocking popups */
463 #endif /* def FEATURE_KILL_POPUPS */
465 int pcrs_filter; /* bool, 1==will filter through pcrs */
466 int gif_deanimate; /* bool, 1==will deanimate gifs */
468 /* Function that does the content filtering for the current request */
469 char *(*content_filter)() = NULL;
471 /* Skeleton for HTTP response, if we should intercept the request */
472 struct http_response *rsp;
477 * Read the client's request. Note that since we're not using select() we
478 * could get blocked here if a client connected, then didn't say anything!
483 n = read_socket(csp->cfd, buf, sizeof(buf));
485 if (n <= 0) break; /* error! */
487 add_to_iob(csp, buf, n);
489 req = get_header(csp);
493 break; /* no HTTP request! */
498 continue; /* more to come! */
501 #ifdef FEATURE_FORCE_LOAD
502 /* If this request contains the FORCE_PREFIX,
503 * better get rid of it now and set the force flag --oes
506 if (strstr(req, FORCE_PREFIX))
508 strclean(req, FORCE_PREFIX);
509 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
510 csp->flags |= CSP_FLAG_FORCED;
513 #endif /* def FEATURE_FORCE_LOAD */
515 parse_http_request(req, http, csp);
520 if (http->cmd == NULL)
522 strcpy(buf, CHEADER);
523 write_socket(csp->cfd, buf, strlen(buf));
525 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
530 /* decide how to route the HTTP request */
532 if ((fwd = forward_url(http, csp)) == NULL)
534 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
535 /* Never get here - LOG_LEVEL_FATAL causes program exit */
538 /* build the http request to send to the server
539 * we have to do one of the following:
541 * create = use the original HTTP request to create a new
542 * HTTP request that has only the path component
543 * without the http://domainspec
544 * pass = pass the original HTTP request unchanged
546 * drop = drop the HTTP request
551 * +--------+--------+
553 * 0 | create | drop |
555 * Forwarding +--------+--------+
559 * +--------+--------+
564 * Determine the actions for this URL
566 #ifdef FEATURE_TOGGLE
567 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
569 /* Most compatible set of actions (i.e. none) */
570 init_current_action(csp->action);
573 #endif /* ndef FEATURE_TOGGLE */
575 url_actions(http, csp);
578 #ifdef FEATURE_COOKIE_JAR
581 * Downgrade http version from 1.1 to 1.0 if +downgrade
584 if (!strcmpic(http->ver, "HTTP/1.1") && csp->action->flags & ACTION_DOWNGRADE)
587 http->ver = strdup("HTTP/1.0");
591 * (Re)build the HTTP request. If forwarding, use the whole URL,
592 * else, use only the path.
598 http->cmd = strsav(http->cmd, http->gpc);
599 http->cmd = strsav(http->cmd, " ");
601 if (fwd->forward_host)
603 http->cmd = strsav(http->cmd, http->url);
607 http->cmd = strsav(http->cmd, http->path);
610 http->cmd = strsav(http->cmd, " ");
611 http->cmd = strsav(http->cmd, http->ver);
613 enlist(csp->headers, http->cmd);
618 * If we're logging cookies in a cookie jar, and the user has not
619 * supplied any wafers, and the user has not told us to suppress the
620 * vanilla wafer, then send the vanilla wafer.
622 if ((csp->config->jarfile != NULL)
623 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
624 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
626 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
628 #endif /* def FEATURE_COOKIE_JAR */
630 #ifdef FEATURE_KILL_POPUPS
631 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
632 #endif /* def FEATURE_KILL_POPUPS */
634 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
635 ((csp->action->flags & ACTION_FILTER) != 0);
637 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
639 /* grab the rest of the client's headers */
643 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
645 n = read_socket(csp->cfd, buf, sizeof(buf));
648 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
651 add_to_iob(csp, buf, n);
655 if (p == NULL) break;
657 enlist(csp->headers, p);
661 /* We have a request. */
664 * Now, check to see if we need to intercept it, i.e.
669 /* a CGI call was detected and answered */
670 (NULL != (rsp = dispatch_cgi(csp)))
672 /* or we are enabled and... */
675 /* ..the request was blocked */
676 ( NULL != (rsp = block_url(csp)))
680 || ( NULL != (rsp = trust_url(csp)))
681 #endif /* def FEATURE_TRUST */
683 /* ..or a fast redirect kicked in */
684 #ifdef FEATURE_FAST_REDIRECTS
685 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
686 (NULL != (rsp = redirect_url(csp))))
687 #endif /* def FEATURE_FAST_REDIRECTS */
691 /* Write the answer to the client */
692 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
693 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
695 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
698 #ifdef FEATURE_STATISTICS
699 /* Count as a rejected request */
700 csp->flags |= CSP_FLAG_REJECTED;
701 #endif /* def FEATURE_STATISTICS */
703 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
704 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
705 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
707 /* Clean up and return */
708 free_http_response(rsp);
712 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
714 if (fwd->forward_host)
716 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
717 fwd->forward_host, fwd->forward_port, http->hostport);
721 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
724 /* here we connect to the server, gateway, or the forwarder */
726 csp->sfd = forwarded_connect(fwd, http, csp);
730 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
735 rsp = error_response(csp, "no-such-domain", errno);
737 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
738 csp->ip_addr_str, http->cmd);
742 rsp = error_response(csp, "connect-failed", errno);
744 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
745 csp->ip_addr_str, http->cmd);
748 /* Write the answer to the client */
751 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
752 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
754 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
758 free_http_response(rsp);
762 log_error(LOG_LEVEL_CONNECT, "OK");
764 hdr = sed(client_patterns, add_client_headers, csp);
765 list_remove_all(csp->headers);
767 if (fwd->forward_host || (http->ssl == 0))
769 /* write the client's (modified) header to the server
770 * (along with anything else that may be in the buffer)
775 if ((write_socket(csp->sfd, hdr, n) != n)
776 || (flush_socket(csp->sfd, csp ) < 0))
778 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
781 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
782 csp->ip_addr_str, http->cmd);
784 rsp = error_response(csp, "connect-failed", errno);
788 if ((write_socket(csp->cfd, rsp->head, n) != n)
789 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
791 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
795 free_http_response(rsp);
803 * We're running an SSL tunnel and we're not forwarding,
804 * so just send the "connect succeeded" message to the
805 * client, flush the rest, and get out of the way.
807 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
808 csp->ip_addr_str, http->cmd);
810 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
818 /* we're finished with the client's header */
821 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
823 /* pass data between the client and server
824 * until one or the other shuts down the connection.
833 FD_SET(csp->cfd, &rfds);
834 FD_SET(csp->sfd, &rfds);
836 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
840 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
844 /* this is the body of the browser's request
845 * just read it and write it.
848 if (FD_ISSET(csp->cfd, &rfds))
850 n = read_socket(csp->cfd, buf, sizeof(buf));
854 break; /* "game over, man" */
857 if (write_socket(csp->sfd, buf, n) != n)
859 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
866 * The server wants to talk. It could be the header or the body.
867 * If `hdr' is null, then it's the header otherwise it's the body.
868 * FIXME: Does `hdr' really mean `host'? No.
872 if (FD_ISSET(csp->sfd, &rfds))
875 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
879 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
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, rsp->head_length) != rsp->head_length)
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);
899 /* Add a trailing zero. This lets filter_popups
900 * use string operations.
904 #ifdef FEATURE_KILL_POPUPS
905 /* Filter the popups on this read. */
906 if (block_popups_now)
908 filter_popups(buf, csp);
910 #endif /* def FEATURE_KILL_POPUPS */
912 /* Normally, this would indicate that we've read
913 * as much as the server has sent us and we can
914 * close the client connection. However, Microsoft
915 * in its wisdom has released IIS/5 with a bug that
916 * prevents it from sending the trailing \r\n in
917 * a 302 redirect header (and possibly other headers).
918 * To work around this if we've haven't parsed
919 * a full header we'll append a trailing \r\n
920 * and see if this now generates a valid one.
922 * This hack shouldn't have any impacts. If we've
923 * already transmitted the header or if this is a
924 * SSL connection, then we won't bother with this
925 * hack. So we only work on partially received
926 * headers. If we append a \r\n and this still
927 * doesn't generate a valid header, then we won't
928 * transmit anything to the client.
933 if (server_body || http->ssl)
936 * If we have been buffering up the document,
937 * now is the time to apply content modification
938 * and send the result to the client.
943 * If the content filter fails, use the original
945 * (see p != NULL ? p : csp->iob->cur below)
947 if (NULL == (p = (*content_filter)(csp)))
949 csp->content_length = csp->iob->eod - csp->iob->cur;
952 hdr = sed(server_patterns, add_server_headers, csp);
955 if ((write_socket(csp->cfd, hdr, n) != n)
956 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
958 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
968 break; /* "game over, man" */
972 * This is NOT the body, so
973 * Let's pretend the server just sent us a blank line.
975 n = sprintf(buf, "\r\n");
978 * Now, let the normal header parsing algorithm below do its
979 * job. If it fails, we'll exit instead of continuing.
986 * If this is an SSL connection or we're in the body
987 * of the server document, just write it to the client,
988 * unless we need to buffer the body for later content-filtering
991 if (server_body || http->ssl)
995 add_to_iob(csp, buf, n);
998 * If the buffer limit will be reached on the next read,
999 * switch to non-filtering mode, i.e. make & write the
1000 * header, flush the socket and get out of the way.
1002 if (csp->iob->eod - csp->iob->buf + BUFFER_SIZE > csp->config->buffer_limit)
1004 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1006 hdr = sed(server_patterns, add_server_headers, csp);
1010 if (((write_socket(csp->cfd, hdr, n) != n)
1011 || (n = flush_socket(csp->cfd, csp) < 0)))
1013 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1022 content_filter = NULL;
1029 if (write_socket(csp->cfd, buf, n) != n)
1031 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1040 /* we're still looking for the end of the
1041 * server's header ... (does that make header
1042 * parsing an "out of body experience" ?
1045 /* buffer up the data we just read */
1046 add_to_iob(csp, buf, n);
1048 /* get header lines from the iob */
1050 while ((p = get_header(csp)))
1054 /* see following note */
1057 enlist(csp->headers, p);
1061 /* NOTE: there are no "empty" headers so
1062 * if the pointer `p' is not NULL we must
1063 * assume that we reached the end of the
1064 * buffer before we hit the end of the header.
1071 /* Well, we tried our MS IIS/5
1072 * hack and it didn't work.
1073 * The header is incomplete
1074 * and there isn't anything
1075 * we can do about it.
1081 /* Since we have to wait for
1082 * more from the server before
1083 * we can parse the headers
1084 * we just continue here.
1090 /* we have now received the entire header.
1091 * filter it and send the result to the client
1094 hdr = sed(server_patterns, add_server_headers, csp);
1097 /* write the server's (modified) header to
1098 * the client (along with anything else that
1099 * may be in the buffer)
1102 #ifdef FEATURE_KILL_POPUPS
1103 /* Start blocking popups if appropriate. */
1105 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1106 !http->ssl && /* We talk plaintext */
1107 block_popups) /* Policy allows */
1109 block_popups_now = 1;
1111 * Filter the part of the body that came in the same read
1112 * as the last headers:
1114 filter_popups(csp->iob->cur, csp);
1117 #endif /* def FEATURE_KILL_POPUPS */
1119 /* Buffer and pcrs filter this if appropriate. */
1121 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1122 !http->ssl && /* We talk plaintext */
1123 pcrs_filter) /* Policy allows */
1125 content_filter = pcrs_filter_response;
1128 /* Buffer and gif_deanimate this if appropriate. */
1130 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1131 !http->ssl && /* We talk plaintext */
1132 gif_deanimate) /* Policy allows */
1134 content_filter = gif_deanimate_response;
1139 * Only write if we're not buffering for content modification
1141 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1142 || (n = flush_socket(csp->cfd, csp) < 0)))
1144 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1146 /* the write failed, so don't bother
1147 * mentioning it to the client...
1148 * it probably can't hear us anyway.
1154 if(!content_filter) byte_count += n;
1156 /* we're finished with the server's header */
1161 /* If this was a MS IIS/5 hack then it means
1162 * the server has already closed the
1163 * connection. Nothing more to read. Time
1174 return; /* huh? we should never get here */
1177 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1178 csp->ip_addr_str, http->cmd, byte_count);
1182 /*********************************************************************
1186 * Description : This is little more than chat. We only "serve" to
1187 * to close any socket that chat may have opened.
1190 * 1 : csp = Current client state (buffers, headers, etc...)
1194 *********************************************************************/
1196 void serve(struct client_state *csp)
1197 #else /* ifndef AMIGA */
1198 static void serve(struct client_state *csp)
1199 #endif /* def AMIGA */
1202 close_socket(csp->cfd);
1206 close_socket(csp->sfd);
1209 csp->flags &= ~CSP_FLAG_ACTIVE;
1215 /*********************************************************************
1217 * Function : server_thread
1219 * Description : We only exist to call `serve' in a threaded environment.
1222 * 1 : data = Current client state (buffers, headers, etc...)
1224 * Returns : Always 0.
1226 *********************************************************************/
1227 static int32 server_thread(void *data)
1229 serve((struct client_state *) data);
1236 /*********************************************************************
1240 * Description : Load the config file and start the listen loop.
1241 * This function is a lot more *sane* with the `load_config'
1242 * and `listen_loop' functions; although it stills does
1243 * a *little* too much for my taste.
1246 * 1 : argc = Number of parameters (including $0).
1247 * 2 : argv = Array of (char *)'s to the parameters.
1249 * Returns : 1 if : can't open config file, unrecognized directive,
1250 * stats requested in multi-thread mode, can't open the
1251 * log file, can't open the jar file, listen port is invalid,
1252 * any load fails, and can't bind port.
1254 * Else main never returns, the process must be signaled
1255 * to terminate execution. Or, on Windows, use the
1256 * "File", "Exit" menu option.
1258 *********************************************************************/
1260 int real_main(int argc, const char *argv[])
1262 int main(int argc, const char *argv[])
1267 "AmiTCP:db/junkbuster/config"
1268 #elif !defined(_WIN32)
1275 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1276 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1278 printf("JunkBuster proxy version " VERSION ".\n\n"
1279 "Usage: %s [configfile]\n\n"
1280 "See " HOME_PAGE_URL " for details.\n"
1281 "This program is distributed under the GNU GPL, version 2 or later.\n",
1285 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1287 printf(VERSION "\n");
1290 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1297 configfile = argv[1];
1304 #elif defined(_WIN32)
1310 signal(SIGPIPE, SIG_IGN);
1311 signal(SIGCHLD, SIG_IGN);
1313 #else /* ifdef _WIN32 */
1314 # ifdef _WIN_CONSOLE
1316 * We *are* in a windows console app.
1317 * Print a verbose messages about FAQ's and such
1319 printf(win32_blurb);
1320 # endif /* def _WIN_CONSOLE */
1321 #endif /* def _WIN32 */
1332 /*********************************************************************
1334 * Function : listen_loop
1336 * Description : bind the listen port and enter a "FOREVER" listening loop.
1342 *********************************************************************/
1343 static void listen_loop(void)
1345 struct client_state *csp = NULL;
1347 struct configuration_spec * config;
1349 config = load_config();
1351 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1352 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1354 bfd = bind_port(config->haddr, config->hport);
1358 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1359 "- There may be another junkbuster or some other "
1360 "proxy running on port %d",
1361 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1362 config->hport, config->hport
1364 /* shouldn't get here */
1368 config->need_bind = 0;
1373 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1374 while (waitpid(-1, NULL, WNOHANG) > 0)
1376 /* zombie children */
1378 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1381 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1383 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1387 csp->flags |= CSP_FLAG_ACTIVE;
1390 csp->config = config = load_config();
1392 if ( config->need_bind )
1395 * Since we were listening to the "old port", we will not see
1396 * a "listen" param change until the next IJB request. So, at
1397 * least 1 more request must be made for us to find the new
1398 * setting. I am simply closing the old socket and binding the
1401 * Which-ever is correct, we will serve 1 more page via the
1402 * old settings. This should probably be a "show-proxy-args"
1403 * request. This should not be a so common of an operation
1404 * that this will hurt people's feelings.
1409 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1410 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1411 bfd = bind_port(config->haddr, config->hport);
1415 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1416 "- There may be another junkbuster or some other "
1417 "proxy running on port %d",
1418 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1419 config->hport, config->hport
1421 /* shouldn't get here */
1425 config->need_bind = 0;
1428 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1430 if (!accept_connection(csp, bfd))
1432 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1445 log_error(LOG_LEVEL_CONNECT, "OK");
1448 #ifdef FEATURE_TOGGLE
1451 csp->flags |= CSP_FLAG_TOGGLED_ON;
1453 #endif /* def FEATURE_TOGGLE */
1455 if (run_loader(csp))
1457 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1458 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1462 if (block_acl(NULL,csp))
1464 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1465 close_socket(csp->cfd);
1469 #endif /* def FEATURE_ACL */
1471 /* add it to the list of clients */
1472 csp->next = clients->next;
1473 clients->next = csp;
1475 if (config->multi_threaded)
1479 /* this is a switch () statment in the C preprocessor - ugh */
1480 #undef SELECTED_ONE_OPTION
1482 /* Use Pthreads in preference to native code */
1483 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1484 #define SELECTED_ONE_OPTION
1486 pthread_t the_thread;
1487 pthread_attr_t attrs;
1489 pthread_attr_init(&attrs);
1490 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1491 child_id = (pthread_create(&the_thread, &attrs,
1492 (void*)serve, csp) ? -1 : 0);
1493 pthread_attr_destroy(&attrs);
1497 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1498 #define SELECTED_ONE_OPTION
1499 child_id = _beginthread(
1505 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1506 #define SELECTED_ONE_OPTION
1508 thread_id tid = spawn_thread
1509 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1511 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1513 child_id = (int) tid;
1522 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1523 #define SELECTED_ONE_OPTION
1524 csp->cfd = ReleaseSocket(csp->cfd, -1);
1525 if((child_id = (int)CreateNewProcTags(
1526 NP_Entry, (ULONG)server_thread,
1527 NP_Output, Output(),
1528 NP_CloseOutput, FALSE,
1529 NP_Name, (ULONG)"junkbuster child",
1530 NP_StackSize, 200*1024,
1534 ((struct Task *)child_id)->tc_UserData = csp;
1535 Signal((struct Task *)child_id, SIGF_SINGLE);
1540 #if !defined(SELECTED_ONE_OPTION)
1543 /* This block is only needed when using fork().
1544 * When using threads, the server thread was
1545 * created and run by the call to _beginthread().
1547 if (child_id == 0) /* child */
1553 else if (child_id > 0) /* parent */
1555 /* in a fork()'d environment, the parent's
1556 * copy of the client socket and the CSP
1560 #if !defined(_WIN32) && defined(__CYGWIN__)
1562 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1563 close_socket(csp->cfd);
1564 csp->flags &= ~CSP_FLAG_ACTIVE;
1568 #undef SELECTED_ONE_OPTION
1569 /* end of cpp switch () */
1571 if (child_id < 0) /* failed */
1573 char buf[BUFFER_SIZE];
1575 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1577 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1579 write_socket(csp->cfd, buf, strlen(buf));
1580 close_socket(csp->cfd);
1581 csp->flags &= ~CSP_FLAG_ACTIVE;