1 const char jcc_rcs[] = "$Id: jcc.c,v 1.38 2001/09/16 13:01:46 jongfoster Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001 the SourceForge
10 * IJBSWA team. http://ijbswa.sourceforge.net
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
36 * Revision 1.38 2001/09/16 13:01:46 jongfoster
37 * Removing redundant function call that zeroed zalloc()'d memory.
39 * Revision 1.37 2001/09/10 11:12:24 oes
40 * Deleted unused variable
42 * Revision 1.36 2001/09/10 10:56:15 oes
43 * Silenced compiler warnings
45 * Revision 1.35 2001/07/31 14:44:22 oes
46 * Deleted unused size parameter from filter_popups()
48 * Revision 1.34 2001/07/30 22:08:36 jongfoster
49 * Tidying up #defines:
50 * - All feature #defines are now of the form FEATURE_xxx
51 * - Permanently turned off WIN_GUI_EDIT
52 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
54 * Revision 1.33 2001/07/29 19:32:00 jongfoster
55 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
57 * Revision 1.32 2001/07/29 18:47:05 jongfoster
58 * Adding missing #include "loadcfg.h"
60 * Revision 1.31 2001/07/29 12:17:48 oes
61 * Applied pthread fix by Paul Lieverse
63 * Revision 1.30 2001/07/25 22:57:13 jongfoster
64 * __BEOS__ no longer overrides FEATURE_PTHREAD.
65 * This is because FEATURE_PTHREAD will soon be widely used, so I
66 * want to keep it simple.
68 * Revision 1.29 2001/07/24 12:47:06 oes
69 * Applied BeOS support update by Eugenia
71 * Revision 1.28 2001/07/23 13:26:12 oes
72 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
74 * Revision 1.27 2001/07/19 19:09:47 haroon
75 * - Added code to take care of the situation where while processing the first
76 * server response (which includes the server header), after finding the end
77 * of the headers we were not looking past the end of the headers for
78 * content modification. I enabled it for filter_popups.
79 * Someone else should look to see if other similar operations should be
80 * done to the discarded portion of the buffer.
82 * Note 2001/07/20: No, the other content modification mechanisms will process
83 * the whole iob later anyway. --oes
85 * Revision 1.26 2001/07/18 12:31:36 oes
88 * Revision 1.25 2001/07/15 19:43:49 jongfoster
89 * Supports POSIX threads.
90 * Also removed some unused #includes.
92 * Revision 1.24 2001/07/13 14:00:40 oes
93 * - Generic content modification scheme:
94 * Each feature has its own applicability flag that is set
95 * from csp->action->flags.
96 * Replaced the "filtering" int flag , by a function pointer
97 * "content_filter" to the function that will do the content
98 * modification. If it is != NULL, the document will be buffered
99 * and processed through *content_filter, which must set
100 * csp->content_length and return a modified copy of the body
101 * or return NULL (on failiure).
102 * - Changed csp->is_text to the more generic bitmap csp->content_type
103 * which can currently take the valued CT_TEXT or CT_GIF
105 * - Removed all #ifdef PCRS
107 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
108 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
109 * the `block_acl' call. This prevents a compilation error when the user
110 * does not wish to use the "ACL" feature.
112 * Revision 1.22 2001/06/29 21:45:41 oes
113 * Indentation, CRLF->LF, Tab-> Space
115 * Revision 1.21 2001/06/29 13:29:36 oes
116 * - Cleaned up, improved comments
117 * - Unified all possible interceptors (CGI,
118 * block, trust, fast_redirect) in one
119 * place, with one (CGI) answer generation
120 * mechansim. Much clearer now.
121 * - Removed the GIF image generation, which
122 * is now done in filters.c:block_url()
123 * - Made error conditions like domain lookup
124 * failiure or (various) problems while talking
125 * to the server use cgi.c:error_response()
126 * instead of generating HTML/HTTP in chat() (yuck!)
127 * - Removed logentry from cancelled commit
129 * Revision 1.20 2001/06/09 10:55:28 jongfoster
130 * Changing BUFSIZ ==> BUFFER_SIZE
132 * Revision 1.19 2001/06/07 23:12:52 jongfoster
133 * Replacing function pointer in struct gateway with a directly
134 * called function forwarded_connect().
135 * Replacing struct gateway with struct forward_spec
137 * Revision 1.18 2001/06/03 19:12:16 oes
138 * introduced new cgi handling
140 * Revision 1.17 2001/06/01 20:07:23 jongfoster
141 * Now uses action +image-blocker{} rather than config->tinygif
143 * Revision 1.16 2001/06/01 18:49:17 jongfoster
144 * Replaced "list_share" with "list" - the tiny memory gain was not
145 * worth the extra complexity.
147 * Revision 1.15 2001/05/31 21:24:47 jongfoster
148 * Changed "permission" to "action" throughout.
149 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
150 * Moved vanilla wafer check into chat(), since we must now
151 * decide whether or not to add it based on the URL.
153 * Revision 1.14 2001/05/29 20:14:01 joergs
154 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
157 * Revision 1.13 2001/05/29 09:50:24 jongfoster
158 * Unified blocklist/imagelist/permissionslist.
159 * File format is still under discussion, but the internal changes
162 * Also modified interceptor behaviour:
163 * - We now intercept all URLs beginning with one of the following
164 * prefixes (and *only* these prefixes):
166 * * http://ijbswa.sf.net/config/
167 * * http://ijbswa.sourceforge.net/config/
168 * - New interceptors "home page" - go to http://i.j.b/ to see it.
169 * - Internal changes so that intercepted and fast redirect pages
170 * are not replaced with an image.
171 * - Interceptors now have the option to send a binary page direct
172 * to the client. (i.e. ijb-send-banner uses this)
173 * - Implemented show-url-info interceptor. (Which is why I needed
174 * the above interceptors changes - a typical URL is
175 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
176 * The previous mechanism would not have intercepted that, and
177 * if it had been intercepted then it then it would have replaced
180 * Revision 1.12 2001/05/27 22:17:04 oes
182 * - re_process_buffer no longer writes the modified buffer
183 * to the client, which was very ugly. It now returns the
184 * buffer, which it is then written by chat.
186 * - content_length now adjusts the Content-Length: header
187 * for modified documents rather than crunch()ing it.
188 * (Length info in csp->content_length, which is 0 for
189 * unmodified documents)
191 * - For this to work, sed() is called twice when filtering.
193 * Revision 1.11 2001/05/26 17:27:53 jongfoster
194 * Added support for CLF and fixed LOG_LEVEL_LOG.
195 * Also did CRLF->LF fix of my previous patch.
197 * Revision 1.10 2001/05/26 15:26:15 jongfoster
198 * ACL feature now provides more security by immediately dropping
199 * connections from untrusted hosts.
201 * Revision 1.9 2001/05/26 00:28:36 jongfoster
202 * Automatic reloading of config file.
203 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
204 * Most of the global variables have been moved to a new
205 * struct configuration_spec, accessed through csp->config->globalname
206 * Most of the globals remaining are used by the Win32 GUI.
208 * Revision 1.8 2001/05/25 22:43:18 jongfoster
209 * Fixing minor memory leak and buffer overflow.
211 * Revision 1.7 2001/05/25 22:34:30 jongfoster
214 * Revision 1.6 2001/05/23 00:13:58 joergs
215 * AmigaOS support fixed.
217 * Revision 1.5 2001/05/22 18:46:04 oes
219 * - Enabled filtering banners by size rather than URL
220 * by adding patterns that replace all standard banner
221 * sizes with the "Junkbuster" gif to the re_filterfile
223 * - Enabled filtering WebBugs by providing a pattern
224 * which kills all 1x1 images
226 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
227 * which is selected by the (nonstandard and therefore
228 * capital) letter 'U' in the option string.
229 * It causes the quantifiers to be ungreedy by default.
230 * Appending a ? turns back to greedy (!).
232 * - Added a new interceptor ijb-send-banner, which
233 * sends back the "Junkbuster" gif. Without imagelist or
234 * MSIE detection support, or if tinygif = 1, or the
235 * URL isn't recognized as an imageurl, a lame HTML
236 * explanation is sent instead.
238 * - Added new feature, which permits blocking remote
239 * script redirects and firing back a local redirect
241 * The feature is conditionally compiled, i.e. it
242 * can be disabled with --disable-fast-redirects,
243 * plus it must be activated by a "fast-redirects"
244 * line in the config file, has its own log level
245 * and of course wants to be displayed by show-proxy-args
246 * Note: Boy, all the #ifdefs in 1001 locations and
247 * all the fumbling with configure.in and acconfig.h
248 * were *way* more work than the feature itself :-(
250 * - Because a generic redirect template was needed for
251 * this, tinygif = 3 now uses the same.
253 * - Moved GIFs, and other static HTTP response templates
258 * - Removed some >400 CRs again (Jon, you really worked
261 * Revision 1.4 2001/05/21 19:34:01 jongfoster
262 * Made failure to bind() a fatal error.
264 * Revision 1.3 2001/05/20 01:21:20 jongfoster
265 * Version 2.9.4 checkin.
266 * - Merged popupfile and cookiefile, and added control over PCRS
267 * filtering, in new "permissionsfile".
268 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
269 * file error you now get a message box (in the Win32 GUI) rather
270 * than the program exiting with no explanation.
271 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
273 * - Removed tabs from "config"
274 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
275 * - Bumped up version number.
277 * Revision 1.2 2001/05/17 22:34:44 oes
278 * - Added hint on GIF char array generation to jcc.c
279 * - Cleaned CRLF's from the sources and related files
280 * - Repaired logging for REF and FRC
282 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
283 * Initial import of version 2.9.3 source tree
286 *********************************************************************/
292 #include <sys/types.h>
299 #ifdef FEATURE_PTHREAD
301 #endif /* def FEATURE_PTHREAD */
304 # ifndef FEATURE_PTHREAD
305 # include <windows.h>
306 # include <process.h>
307 # endif /* ndef FEATURE_PTHREAD */
310 # ifndef _WIN_CONSOLE
312 # endif /* ndef _WIN_CONSOLE */
314 #else /* ifndef _WIN32 */
317 # include <sys/time.h>
318 # include <sys/wait.h>
319 # include <sys/stat.h>
323 # include <socket.h> /* BeOS has select() for sockets only. */
324 # include <OS.h> /* declarations for threads and stuff. */
338 #include "showargs.h"
340 #include "killpopup.h"
341 #include "miscutil.h"
343 #include "jbsockets.h"
349 const char jcc_h_rcs[] = JCC_H_VERSION;
350 const char project_h_rcs[] = PROJECT_H_VERSION;
352 struct client_state clients[1];
353 struct file_list files[1];
355 #ifdef FEATURE_STATISTICS
356 int urls_read = 0; /* total nr of urls read inc rejected */
357 int urls_rejected = 0; /* total nr of urls rejected */
358 #endif /* def FEATURE_STATISTICS */
361 static void listen_loop(void);
362 static void chat(struct client_state *csp);
364 void serve(struct client_state *csp);
365 #else /* ifndef AMIGA */
366 static void serve(struct client_state *csp);
367 #endif /* def AMIGA */
370 static int32 server_thread(void *data);
371 #endif /* def __BEOS__ */
374 #define sleep(N) Sleep(((N) * 1000))
378 /* The vanilla wafer. */
379 static const char VANILLA_WAFER[] =
380 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
381 "Do_not_send_me_any_copyrighted_information_other_than_the_"
382 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
383 "In_particular_do_not_send_me_any_cookies_that_"
384 "are_subject_to_a_claim_of_copyright_by_anybody._"
385 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
386 "(copyright_or_otherwise)_applying_to_any_cookie._";
389 /*********************************************************************
393 * Description : Once a connection to the client has been accepted,
394 * this function is called (via serve()) to handle the
395 * main business of the communication. When this
396 * function returns, the caller must close the client
400 * 1 : csp = Current client state (buffers, headers, etc...)
402 * Returns : On success, the number of bytes written are returned (zero
403 * indicates nothing was written). On error, -1 is returned,
404 * and errno is set appropriately. If count is zero and the
405 * file descriptor refers to a regular file, 0 will be
406 * returned without causing any other effect. For a special
407 * file, the results are not portable.
409 *********************************************************************/
410 static void chat(struct client_state *csp)
413 * This next lines are a little ugly, but they simplifies the if statements
414 * below. Basically if TOGGLE, then we want the if to test "csp->toggled_on",
415 * else we don't. And if FEATURE_FORCE_LOAD, then we want the if to test
416 * "csp->toggled_on", else we don't
418 #ifdef FEATURE_TOGGLE
419 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
420 #else /* ifndef FEATURE_TOGGLE */
421 # define IS_TOGGLED_ON_AND
422 #endif /* ndef FEATURE_TOGGLE */
423 #ifdef FEATURE_FORCE_LOAD
424 # define IS_NOT_FORCED_AND (!csp->force) &&
425 #else /* ifndef FEATURE_FORCE_LOAD */
426 # define IS_NOT_FORCED_AND
427 #endif /* def FEATURE_FORCE_LOAD */
429 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
431 char buf[BUFFER_SIZE];
434 int n, maxfd, server_body;
435 int ms_iis5_hack = 0;
437 const struct forward_spec * fwd;
438 struct http_request *http;
439 #ifdef FEATURE_KILL_POPUPS
440 int block_popups; /* bool, 1==will block popups */
441 int block_popups_now = 0; /* bool, 1==currently blocking popups */
442 #endif /* def FEATURE_KILL_POPUPS */
444 int pcrs_filter; /* bool, 1==will filter through pcrs */
445 int gif_deanimate; /* bool, 1==will deanimate gifs */
447 /* Function that does the content filtering for the current request */
448 char *(*content_filter)() = NULL;
450 /* Skeleton for HTTP response, if we should intercept the request */
451 struct http_response *rsp;
456 * Read the client's request. Note that since we're not using select() we
457 * could get blocked here if a client connected, then didn't say anything!
462 n = read_socket(csp->cfd, buf, sizeof(buf));
464 if (n <= 0) break; /* error! */
466 add_to_iob(csp, buf, n);
468 req = get_header(csp);
472 break; /* no HTTP request! */
477 continue; /* more to come! */
480 #ifdef FEATURE_FORCE_LOAD
481 /* If this request contains the FORCE_PREFIX,
482 * better get rid of it now and set the force flag --oes
485 if (strstr(req, FORCE_PREFIX))
487 strclean(req, FORCE_PREFIX);
488 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
495 #endif /* def FEATURE_FORCE_LOAD */
497 parse_http_request(req, http, csp);
502 if (http->cmd == NULL)
504 strcpy(buf, CHEADER);
505 write_socket(csp->cfd, buf, strlen(buf));
507 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
512 /* decide how to route the HTTP request */
514 if ((fwd = forward_url(http, csp)) == NULL)
516 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
517 /* Never get here - LOG_LEVEL_FATAL causes program exit */
520 /* build the http request to send to the server
521 * we have to do one of the following:
523 * create = use the original HTTP request to create a new
524 * HTTP request that has only the path component
525 * without the http://domainspec
526 * pass = pass the original HTTP request unchanged
528 * drop = drop the HTTP request
533 * +--------+--------+
535 * 0 | create | drop |
537 * Forwarding +--------+--------+
541 * +--------+--------+
545 if (fwd->forward_host)
547 /* if forwarding, just pass the request as is */
548 enlist(csp->headers, http->cmd);
554 /* otherwise elide the host information from the url */
556 p = strsav(p, http->gpc);
558 p = strsav(p, http->path);
560 p = strsav(p, http->ver);
561 enlist(csp->headers, p);
566 /* decide what we're to do with cookies */
568 #ifdef FEATURE_TOGGLE
569 if (!csp->toggled_on)
571 /* Most compatible set of actions (i.e. none) */
572 init_current_action(csp->action);
575 #endif /* ndef FEATURE_TOGGLE */
577 url_actions(http, csp);
580 #ifdef FEATURE_COOKIE_JAR
582 * If we're logging cookies in a cookie jar, and the user has not
583 * supplied any wafers, and the user has not told us to suppress the
584 * vanilla wafer, then send the vanilla wafer.
586 if ((csp->config->jarfile != NULL)
587 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
588 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
590 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
592 #endif /* def FEATURE_COOKIE_JAR */
594 #ifdef FEATURE_KILL_POPUPS
595 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
596 #endif /* def FEATURE_KILL_POPUPS */
598 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
599 ((csp->action->flags & ACTION_FILTER) != 0);
601 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
603 /* grab the rest of the client's headers */
607 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
609 n = read_socket(csp->cfd, buf, sizeof(buf));
612 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
615 add_to_iob(csp, buf, n);
619 if (p == NULL) break;
621 enlist(csp->headers, p);
625 /* We have a request. */
627 hdr = sed(client_patterns, add_client_headers, csp);
628 list_remove_all(csp->headers);
631 * Now, check to see if we need to intercept it, i.e.
636 /* a CGI call was detected and answered */
637 (NULL != (rsp = dispatch_cgi(csp)))
639 /* or we are enabled and... */
642 /* ..the request was blocked */
643 ( NULL != (rsp = block_url(csp)))
647 || ( NULL != (rsp = trust_url(csp)))
648 #endif /* def FEATURE_TRUST */
650 /* ..or a fast redirect kicked in */
651 #ifdef FEATURE_FAST_REDIRECTS
652 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
653 (NULL != (rsp = redirect_url(csp))))
654 #endif /* def FEATURE_FAST_REDIRECTS */
658 /* Write the answer to the client */
659 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
660 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
662 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
665 #ifdef FEATURE_STATISTICS
666 /* Count as a rejected request */
668 #endif /* def FEATURE_STATISTICS */
670 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
671 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
672 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
674 /* Clean up and return */
675 free_http_response(rsp);
680 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
682 if (fwd->forward_host)
684 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
685 fwd->forward_host, fwd->forward_port, http->hostport);
689 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
692 /* here we connect to the server, gateway, or the forwarder */
694 csp->sfd = forwarded_connect(fwd, http, csp);
698 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
703 rsp = error_response(csp, "no-such-domain", errno);
705 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
706 csp->ip_addr_str, http->cmd);
710 rsp = error_response(csp, "connect-failed", errno);
712 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
713 csp->ip_addr_str, http->cmd);
716 /* Write the answer to the client */
719 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
720 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
722 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
726 free_http_response(rsp);
731 log_error(LOG_LEVEL_CONNECT, "OK");
733 if (fwd->forward_host || (http->ssl == 0))
735 /* write the client's (modified) header to the server
736 * (along with anything else that may be in the buffer)
741 if ((write_socket(csp->sfd, hdr, n) != n)
742 || (flush_socket(csp->sfd, csp ) < 0))
744 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
747 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
748 csp->ip_addr_str, http->cmd);
750 rsp = error_response(csp, "connect-failed", errno);
754 if ((write_socket(csp->cfd, rsp->head, n) != n)
755 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
757 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
761 free_http_response(rsp);
769 * We're running an SSL tunnel and we're not forwarding,
770 * so just send the "connect succeeded" message to the
771 * client, flush the rest, and get out of the way.
773 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
774 csp->ip_addr_str, http->cmd);
776 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
784 /* we're finished with the client's header */
787 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
789 /* pass data between the client and server
790 * until one or the other shuts down the connection.
799 FD_SET(csp->cfd, &rfds);
800 FD_SET(csp->sfd, &rfds);
802 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
806 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
810 /* this is the body of the browser's request
811 * just read it and write it.
814 if (FD_ISSET(csp->cfd, &rfds))
816 n = read_socket(csp->cfd, buf, sizeof(buf));
820 break; /* "game over, man" */
823 if (write_socket(csp->sfd, buf, n) != n)
825 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
832 * The server wants to talk. It could be the header or the body.
833 * If `hdr' is null, then it's the header otherwise it's the body.
834 * FIXME: Does `hdr' really mean `host'? No.
838 if (FD_ISSET(csp->sfd, &rfds))
841 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
845 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
847 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
848 csp->ip_addr_str, http->cmd);
850 rsp = error_response(csp, "connect-failed", errno);
854 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
855 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
857 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
861 free_http_response(rsp);
865 /* Add a trailing zero. This lets filter_popups
866 * use string operations.
870 #ifdef FEATURE_KILL_POPUPS
871 /* Filter the popups on this read. */
872 if (block_popups_now)
876 #endif /* def FEATURE_KILL_POPUPS */
878 /* Normally, this would indicate that we've read
879 * as much as the server has sent us and we can
880 * close the client connection. However, Microsoft
881 * in its wisdom has released IIS/5 with a bug that
882 * prevents it from sending the trailing \r\n in
883 * a 302 redirect header (and possibly other headers).
884 * To work around this if we've haven't parsed
885 * a full header we'll append a trailing \r\n
886 * and see if this now generates a valid one.
888 * This hack shouldn't have any impacts. If we've
889 * already transmitted the header or if this is a
890 * SSL connection, then we won't bother with this
891 * hack. So we only work on partially received
892 * headers. If we append a \r\n and this still
893 * doesn't generate a valid header, then we won't
894 * transmit anything to the client.
899 if (server_body || http->ssl)
902 * If we have been buffering up the document,
903 * now is the time to apply content modification
904 * and send the result to the client.
909 * If the content filter fails, use the original
911 * (see p != NULL ? p : csp->iob->cur below)
913 if (NULL == (p = (*content_filter)(csp)))
915 csp->content_length = csp->iob->eod - csp->iob->cur;
918 hdr = sed(server_patterns, add_server_headers, csp);
921 if ((write_socket(csp->cfd, hdr, n) != n)
922 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != csp->content_length))
924 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
932 break; /* "game over, man" */
936 * This is NOT the body, so
937 * Let's pretend the server just sent us a blank line.
939 n = sprintf(buf, "\r\n");
942 * Now, let the normal header parsing algorithm below do its
943 * job. If it fails, we'll exit instead of continuing.
950 * If this is an SSL connection or we're in the body
951 * of the server document, just write it to the client,
952 * unless we need to buffer the body for later content-filtering
955 if (server_body || http->ssl)
959 add_to_iob(csp, buf, n);
963 if (write_socket(csp->cfd, buf, n) != n)
965 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
974 /* we're still looking for the end of the
975 * server's header ... (does that make header
976 * parsing an "out of body experience" ?
979 /* buffer up the data we just read */
980 add_to_iob(csp, buf, n);
982 /* get header lines from the iob */
984 while ((p = get_header(csp)))
988 /* see following note */
991 enlist(csp->headers, p);
995 /* NOTE: there are no "empty" headers so
996 * if the pointer `p' is not NULL we must
997 * assume that we reached the end of the
998 * buffer before we hit the end of the header.
1005 /* Well, we tried our MS IIS/5
1006 * hack and it didn't work.
1007 * The header is incomplete
1008 * and there isn't anything
1009 * we can do about it.
1015 /* Since we have to wait for
1016 * more from the server before
1017 * we can parse the headers
1018 * we just continue here.
1024 /* we have now received the entire header.
1025 * filter it and send the result to the client
1028 hdr = sed(server_patterns, add_server_headers, csp);
1031 /* write the server's (modified) header to
1032 * the client (along with anything else that
1033 * may be in the buffer)
1036 #ifdef FEATURE_KILL_POPUPS
1037 /* Start blocking popups if appropriate. */
1039 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1040 !http->ssl && /* We talk plaintext */
1041 block_popups) /* Policy allows */
1043 block_popups_now = 1;
1045 * Filter the part of the body that came in the same read
1046 * as the last headers:
1048 filter_popups(csp->iob->cur);
1051 #endif /* def FEATURE_KILL_POPUPS */
1053 /* Buffer and pcrs filter this if appropriate. */
1055 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1056 !http->ssl && /* We talk plaintext */
1057 pcrs_filter) /* Policy allows */
1059 content_filter = pcrs_filter_response;
1062 /* Buffer and gif_deanimate this if appropriate. */
1064 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1065 !http->ssl && /* We talk plaintext */
1066 gif_deanimate) /* Policy allows */
1068 content_filter = gif_deanimate_response;
1073 * Only write if we're not buffering for content modification
1075 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1076 || (n = flush_socket(csp->cfd, csp) < 0)))
1078 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1080 /* the write failed, so don't bother
1081 * mentioning it to the client...
1082 * it probably can't hear us anyway.
1088 if(!content_filter) byte_count += n;
1090 /* we're finished with the server's header */
1095 /* If this was a MS IIS/5 hack then it means
1096 * the server has already closed the
1097 * connection. Nothing more to read. Time
1108 return; /* huh? we should never get here */
1111 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1112 csp->ip_addr_str, http->cmd, byte_count);
1116 /*********************************************************************
1120 * Description : This is little more than chat. We only "serve" to
1121 * to close any socket that chat may have opened.
1124 * 1 : csp = Current client state (buffers, headers, etc...)
1128 *********************************************************************/
1130 void serve(struct client_state *csp)
1131 #else /* ifndef AMIGA */
1132 static void serve(struct client_state *csp)
1133 #endif /* def AMIGA */
1136 close_socket(csp->cfd);
1140 close_socket(csp->sfd);
1149 /*********************************************************************
1151 * Function : server_thread
1153 * Description : We only exist to call `serve' in a threaded environment.
1156 * 1 : data = Current client state (buffers, headers, etc...)
1158 * Returns : Always 0.
1160 *********************************************************************/
1161 static int32 server_thread(void *data)
1163 serve((struct client_state *) data);
1170 /*********************************************************************
1174 * Description : Load the config file and start the listen loop.
1175 * This function is a lot more *sane* with the `load_config'
1176 * and `listen_loop' functions; although it stills does
1177 * a *little* too much for my taste.
1180 * 1 : argc = Number of parameters (including $0).
1181 * 2 : argv = Array of (char *)'s to the parameters.
1183 * Returns : 1 if : can't open config file, unrecognized directive,
1184 * stats requested in multi-thread mode, can't open the
1185 * log file, can't open the jar file, listen port is invalid,
1186 * any load fails, and can't bind port.
1188 * Else main never returns, the process must be signaled
1189 * to terminate execution. Or, on Windows, use the
1190 * "File", "Exit" menu option.
1192 *********************************************************************/
1194 int real_main(int argc, const char *argv[])
1196 int main(int argc, const char *argv[])
1201 "AmiTCP:db/junkbuster/config"
1202 #elif !defined(_WIN32)
1209 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1210 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1212 printf("JunkBuster proxy version " VERSION ".\n\n"
1213 "Usage: %s [configfile]\n\n"
1214 "See " HOME_PAGE_URL " for details.\n"
1215 "This program is distributed under the GNU GPL, version 2 or later.\n",
1219 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1221 printf(VERSION "\n");
1224 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1231 configfile = argv[1];
1238 #elif defined(_WIN32)
1244 signal(SIGPIPE, SIG_IGN);
1245 signal(SIGCHLD, SIG_IGN);
1247 #else /* ifdef _WIN32 */
1248 # ifdef _WIN_CONSOLE
1250 * We *are* in a windows console app.
1251 * Print a verbose messages about FAQ's and such
1253 printf(win32_blurb);
1254 # endif /* def _WIN_CONSOLE */
1255 #endif /* def _WIN32 */
1266 /*********************************************************************
1268 * Function : listen_loop
1270 * Description : bind the listen port and enter a "FOREVER" listening loop.
1276 *********************************************************************/
1277 static void listen_loop(void)
1279 struct client_state *csp = NULL;
1281 struct configuration_spec * config;
1283 config = load_config();
1285 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1286 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1288 bfd = bind_port(config->haddr, config->hport);
1292 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1293 "- There may be another junkbuster or some other "
1294 "proxy running on port %d",
1295 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1296 config->hport, config->hport
1298 /* shouldn't get here */
1302 config->need_bind = 0;
1307 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1308 while (waitpid(-1, NULL, WNOHANG) > 0)
1310 /* zombie children */
1312 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1315 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1317 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1324 csp->config = config = load_config();
1326 if ( config->need_bind )
1329 * Since we were listening to the "old port", we will not see
1330 * a "listen" param change until the next IJB request. So, at
1331 * least 1 more request must be made for us to find the new
1332 * setting. I am simply closing the old socket and binding the
1335 * Which-ever is correct, we will serve 1 more page via the
1336 * old settings. This should probably be a "show-proxy-args"
1337 * request. This should not be a so common of an operation
1338 * that this will hurt people's feelings.
1343 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1344 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1345 bfd = bind_port(config->haddr, config->hport);
1349 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1350 "- There may be another junkbuster or some other "
1351 "proxy running on port %d",
1352 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1353 config->hport, config->hport
1355 /* shouldn't get here */
1359 config->need_bind = 0;
1362 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1364 if (!accept_connection(csp, bfd))
1366 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1379 log_error(LOG_LEVEL_CONNECT, "OK");
1382 #ifdef FEATURE_TOGGLE
1383 /* by haroon - most of credit to srt19170 */
1384 csp->toggled_on = g_bToggleIJB;
1385 #endif /* def FEATURE_TOGGLE */
1387 if (run_loader(csp))
1389 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1390 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1394 if (block_acl(NULL,csp))
1396 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1397 close_socket(csp->cfd);
1401 #endif /* def FEATURE_ACL */
1403 /* add it to the list of clients */
1404 csp->next = clients->next;
1405 clients->next = csp;
1407 if (config->multi_threaded)
1411 /* this is a switch () statment in the C preprocessor - ugh */
1412 #undef SELECTED_ONE_OPTION
1414 /* Use Pthreads in preference to native code */
1415 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1416 #define SELECTED_ONE_OPTION
1418 pthread_t the_thread;
1419 pthread_attr_t attrs;
1421 pthread_attr_init(&attrs);
1422 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1423 child_id = (pthread_create(&the_thread, &attrs,
1424 (void*)serve, csp) ? -1 : 0);
1425 pthread_attr_destroy(&attrs);
1429 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1430 #define SELECTED_ONE_OPTION
1431 child_id = _beginthread(
1437 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1438 #define SELECTED_ONE_OPTION
1440 thread_id tid = spawn_thread
1441 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1443 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1445 child_id = (int) tid;
1454 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1455 #define SELECTED_ONE_OPTION
1456 csp->cfd = ReleaseSocket(csp->cfd, -1);
1457 if((child_id = (int)CreateNewProcTags(
1458 NP_Entry, (ULONG)server_thread,
1459 NP_Output, Output(),
1460 NP_CloseOutput, FALSE,
1461 NP_Name, (ULONG)"junkbuster child",
1462 NP_StackSize, 200*1024,
1466 ((struct Task *)child_id)->tc_UserData = csp;
1467 Signal((struct Task *)child_id, SIGF_SINGLE);
1472 #if !defined(SELECTED_ONE_OPTION)
1475 /* This block is only needed when using fork().
1476 * When using threads, the server thread was
1477 * created and run by the call to _beginthread().
1479 if (child_id == 0) /* child */
1485 else if (child_id > 0) /* parent */
1487 /* in a fork()'d environment, the parent's
1488 * copy of the client socket and the CSP
1492 #if !defined(_WIN32) && defined(__CYGWIN__)
1494 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1495 close_socket(csp->cfd);
1500 #undef SELECTED_ONE_OPTION
1501 /* end of cpp switch () */
1503 if (child_id < 0) /* failed */
1505 char buf[BUFFER_SIZE];
1507 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1509 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1511 write_socket(csp->cfd, buf, strlen(buf));
1512 close_socket(csp->cfd);