1 const char jcc_rcs[] = "$Id: jcc.c,v 1.22 2001/06/29 21:45:41 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.22 2001/06/29 21:45:41 oes
37 * Indentation, CRLF->LF, Tab-> Space
39 * Revision 1.21 2001/06/29 13:29:36 oes
40 * - Cleaned up, improved comments
41 * - Unified all possible interceptors (CGI,
42 * block, trust, fast_redirect) in one
43 * place, with one (CGI) answer generation
44 * mechansim. Much clearer now.
45 * - Removed the GIF image generation, which
46 * is now done in filters.c:block_url()
47 * - Made error conditions like domain lookup
48 * failiure or (various) problems while talking
49 * to the server use cgi.c:error_response()
50 * instead of generating HTML/HTTP in chat() (yuck!)
51 * - Removed logentry from cancelled commit
53 * Revision 1.20 2001/06/09 10:55:28 jongfoster
54 * Changing BUFSIZ ==> BUFFER_SIZE
56 * Revision 1.19 2001/06/07 23:12:52 jongfoster
57 * Replacing function pointer in struct gateway with a directly
58 * called function forwarded_connect().
59 * Replacing struct gateway with struct forward_spec
61 * Revision 1.18 2001/06/03 19:12:16 oes
62 * introduced new cgi handling
64 * Revision 1.17 2001/06/01 20:07:23 jongfoster
65 * Now uses action +image-blocker{} rather than config->tinygif
67 * Revision 1.16 2001/06/01 18:49:17 jongfoster
68 * Replaced "list_share" with "list" - the tiny memory gain was not
69 * worth the extra complexity.
71 * Revision 1.15 2001/05/31 21:24:47 jongfoster
72 * Changed "permission" to "action" throughout.
73 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
74 * Moved vanilla wafer check into chat(), since we must now
75 * decide whether or not to add it based on the URL.
77 * Revision 1.14 2001/05/29 20:14:01 joergs
78 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
81 * Revision 1.13 2001/05/29 09:50:24 jongfoster
82 * Unified blocklist/imagelist/permissionslist.
83 * File format is still under discussion, but the internal changes
86 * Also modified interceptor behaviour:
87 * - We now intercept all URLs beginning with one of the following
88 * prefixes (and *only* these prefixes):
90 * * http://ijbswa.sf.net/config/
91 * * http://ijbswa.sourceforge.net/config/
92 * - New interceptors "home page" - go to http://i.j.b/ to see it.
93 * - Internal changes so that intercepted and fast redirect pages
94 * are not replaced with an image.
95 * - Interceptors now have the option to send a binary page direct
96 * to the client. (i.e. ijb-send-banner uses this)
97 * - Implemented show-url-info interceptor. (Which is why I needed
98 * the above interceptors changes - a typical URL is
99 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
100 * The previous mechanism would not have intercepted that, and
101 * if it had been intercepted then it then it would have replaced
104 * Revision 1.12 2001/05/27 22:17:04 oes
106 * - re_process_buffer no longer writes the modified buffer
107 * to the client, which was very ugly. It now returns the
108 * buffer, which it is then written by chat.
110 * - content_length now adjusts the Content-Length: header
111 * for modified documents rather than crunch()ing it.
112 * (Length info in csp->content_length, which is 0 for
113 * unmodified documents)
115 * - For this to work, sed() is called twice when filtering.
117 * Revision 1.11 2001/05/26 17:27:53 jongfoster
118 * Added support for CLF and fixed LOG_LEVEL_LOG.
119 * Also did CRLF->LF fix of my previous patch.
121 * Revision 1.10 2001/05/26 15:26:15 jongfoster
122 * ACL feature now provides more security by immediately dropping
123 * connections from untrusted hosts.
125 * Revision 1.9 2001/05/26 00:28:36 jongfoster
126 * Automatic reloading of config file.
127 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
128 * Most of the global variables have been moved to a new
129 * struct configuration_spec, accessed through csp->config->globalname
130 * Most of the globals remaining are used by the Win32 GUI.
132 * Revision 1.8 2001/05/25 22:43:18 jongfoster
133 * Fixing minor memory leak and buffer overflow.
135 * Revision 1.7 2001/05/25 22:34:30 jongfoster
138 * Revision 1.6 2001/05/23 00:13:58 joergs
139 * AmigaOS support fixed.
141 * Revision 1.5 2001/05/22 18:46:04 oes
143 * - Enabled filtering banners by size rather than URL
144 * by adding patterns that replace all standard banner
145 * sizes with the "Junkbuster" gif to the re_filterfile
147 * - Enabled filtering WebBugs by providing a pattern
148 * which kills all 1x1 images
150 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
151 * which is selected by the (nonstandard and therefore
152 * capital) letter 'U' in the option string.
153 * It causes the quantifiers to be ungreedy by default.
154 * Appending a ? turns back to greedy (!).
156 * - Added a new interceptor ijb-send-banner, which
157 * sends back the "Junkbuster" gif. Without imagelist or
158 * MSIE detection support, or if tinygif = 1, or the
159 * URL isn't recognized as an imageurl, a lame HTML
160 * explanation is sent instead.
162 * - Added new feature, which permits blocking remote
163 * script redirects and firing back a local redirect
165 * The feature is conditionally compiled, i.e. it
166 * can be disabled with --disable-fast-redirects,
167 * plus it must be activated by a "fast-redirects"
168 * line in the config file, has its own log level
169 * and of course wants to be displayed by show-proxy-args
170 * Note: Boy, all the #ifdefs in 1001 locations and
171 * all the fumbling with configure.in and acconfig.h
172 * were *way* more work than the feature itself :-(
174 * - Because a generic redirect template was needed for
175 * this, tinygif = 3 now uses the same.
177 * - Moved GIFs, and other static HTTP response templates
182 * - Removed some >400 CRs again (Jon, you really worked
185 * Revision 1.4 2001/05/21 19:34:01 jongfoster
186 * Made failure to bind() a fatal error.
188 * Revision 1.3 2001/05/20 01:21:20 jongfoster
189 * Version 2.9.4 checkin.
190 * - Merged popupfile and cookiefile, and added control over PCRS
191 * filtering, in new "permissionsfile".
192 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
193 * file error you now get a message box (in the Win32 GUI) rather
194 * than the program exiting with no explanation.
195 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
197 * - Removed tabs from "config"
198 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
199 * - Bumped up version number.
201 * Revision 1.2 2001/05/17 22:34:44 oes
202 * - Added hint on GIF char array generation to jcc.c
203 * - Cleaned CRLF's from the sources and related files
204 * - Repaired logging for REF and FRC
206 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
207 * Initial import of version 2.9.3 source tree
210 *********************************************************************/
216 #include <sys/types.h>
225 # include <sys/timeb.h>
226 # include <windows.h>
228 # include <process.h>
231 # endif /* def TOGGLE */
234 # ifndef _WIN_CONSOLE
236 # endif /* ndef _WIN_CONSOLE */
238 #else /* ifndef _WIN32 */
241 # include <sys/time.h>
242 # include <sys/wait.h>
243 # include <sys/stat.h>
247 # include <socket.h> /* BeOS has select() for sockets only. */
248 # include <OS.h> /* declarations for threads and stuff. */
262 #include "showargs.h"
264 #include "killpopup.h"
265 #include "miscutil.h"
267 #include "jbsockets.h"
272 const char jcc_h_rcs[] = JCC_H_VERSION;
273 const char project_h_rcs[] = PROJECT_H_VERSION;
275 struct client_state clients[1];
276 struct file_list files[1];
279 int urls_read = 0; /* total nr of urls read inc rejected */
280 int urls_rejected = 0; /* total nr of urls rejected */
281 #endif /* def STATISTICS */
284 static void listen_loop(void);
285 static void chat(struct client_state *csp);
287 void serve(struct client_state *csp);
288 #else /* ifndef AMIGA */
289 static void serve(struct client_state *csp);
290 #endif /* def AMIGA */
293 static int32 server_thread(void *data);
294 #endif /* def __BEOS__ */
297 #define sleep(N) Sleep(((N) * 1000))
301 /* The vanilla wafer. */
302 static const char VANILLA_WAFER[] =
303 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
304 "Do_not_send_me_any_copyrighted_information_other_than_the_"
305 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
306 "In_particular_do_not_send_me_any_cookies_that_"
307 "are_subject_to_a_claim_of_copyright_by_anybody._"
308 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
309 "(copyright_or_otherwise)_applying_to_any_cookie._";
312 /*********************************************************************
316 * Description : Once a connection to the client has been accepted,
317 * this function is called (via serve()) to handle the
318 * main business of the communication. When this
319 * function returns, the caller must close the client
323 * 1 : csp = Current client state (buffers, headers, etc...)
325 * Returns : On success, the number of bytes written are returned (zero
326 * indicates nothing was written). On error, -1 is returned,
327 * and errno is set appropriately. If count is zero and the
328 * file descriptor refers to a regular file, 0 will be
329 * returned without causing any other effect. For a special
330 * file, the results are not portable.
332 *********************************************************************/
333 static void chat(struct client_state *csp)
336 * This next lines are a little ugly, but they simplifies the if statements below.
337 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
338 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
341 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
342 #else /* ifndef TOGGLE */
343 # define IS_TOGGLED_ON_AND
344 #endif /* ndef TOGGLE */
346 # define IS_NOT_FORCED_AND (!csp->force) &&
347 #else /* ifndef FORCE_LOAD */
348 # define IS_NOT_FORCED_AND
349 #endif /* def FORCE_LOAD */
351 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
353 char buf[BUFFER_SIZE];
357 int n, maxfd, server_body;
358 int ms_iis5_hack = 0;
360 const struct forward_spec * fwd;
361 struct http_request *http;
363 int block_popups; /* bool, 1==will block popups */
364 int block_popups_now = 0; /* bool, 1==currently blocking popups */
365 #endif /* def KILLPOPUPS */
367 int pcrs_filter; /* bool, 1==will filter through pcrs */
368 int filtering = 0; /* bool, 1==currently filtering through pcrs */
369 #endif /* def PCRS */
370 struct http_response *rsp;
375 * Read the client's request. Note that since we're not using select() we
376 * could get blocked here if a client connected, then didn't say anything!
381 n = read_socket(csp->cfd, buf, sizeof(buf));
383 if (n <= 0) break; /* error! */
385 add_to_iob(csp, buf, n);
387 req = get_header(csp);
391 break; /* no HTTP request! */
396 continue; /* more to come! */
400 /* If this request contains the FORCE_PREFIX,
401 * better get rid of it now and set the force flag --oes
404 if (strstr(req, FORCE_PREFIX))
406 strclean(req, FORCE_PREFIX);
407 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
414 #endif /* def FORCE_LOAD */
416 parse_http_request(req, http, csp);
421 if (http->cmd == NULL)
423 strcpy(buf, CHEADER);
424 write_socket(csp->cfd, buf, strlen(buf));
426 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
431 /* decide how to route the HTTP request */
433 if ((fwd = forward_url(http, csp)) == NULL)
435 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
436 /* Never get here - LOG_LEVEL_FATAL causes program exit */
439 /* build the http request to send to the server
440 * we have to do one of the following:
442 * create = use the original HTTP request to create a new
443 * HTTP request that has only the path component
444 * without the http://domainspec
445 * pass = pass the original HTTP request unchanged
447 * drop = drop the HTTP request
452 * +--------+--------+
454 * 0 | create | drop |
456 * Forwarding +--------+--------+
460 * +--------+--------+
464 if (fwd->forward_host)
466 /* if forwarding, just pass the request as is */
467 enlist(csp->headers, http->cmd);
473 /* otherwise elide the host information from the url */
475 p = strsav(p, http->gpc);
477 p = strsav(p, http->path);
479 p = strsav(p, http->ver);
480 enlist(csp->headers, p);
485 /* decide what we're to do with cookies */
488 if (!csp->toggled_on)
490 /* Most compatible set of actions (i.e. none) */
491 init_current_action(csp->action);
494 #endif /* ndef TOGGLE */
496 url_actions(http, csp);
501 * If we're logging cookies in a cookie jar, and the user has not
502 * supplied any wafers, and the user has not told us to suppress the
503 * vanilla wafer, then send the vanilla wafer.
505 if ((csp->config->jarfile != NULL)
506 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
507 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
509 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
511 #endif /* def JAR_FILES */
514 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
515 #endif /* def KILLPOPUPS */
517 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
518 ((csp->action->flags & ACTION_FILTER) != 0);
519 #endif /* def PCRS */
522 /* grab the rest of the client's headers */
526 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
528 n = read_socket(csp->cfd, buf, sizeof(buf));
531 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
534 add_to_iob(csp, buf, n);
538 if (p == NULL) break;
540 enlist(csp->headers, p);
544 /* We have a request. */
546 hdr = sed(client_patterns, add_client_headers, csp);
547 destroy_list(csp->headers);
550 * Now, check to see if we need to intercept it, i.e.
555 /* a CGI call was detected and answered */
556 (NULL != (rsp = dispatch_cgi(csp)))
558 /* or we are enabled and... */
561 /* ..the request was blocked */
562 ( NULL != (rsp = block_url(csp)))
566 || ( NULL != (rsp = trust_url(csp)))
569 /* ..or a fast redirect kicked in */
570 #ifdef FAST_REDIRECTS
571 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
572 (NULL != (rsp = redirect_url(csp))))
573 #endif /* def FAST_REDIRECTS */
577 /* Write the answer to the client */
578 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
579 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
581 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
585 /* Count as a rejected request */
587 #endif /* def STATISTICS */
589 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
590 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
591 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
593 /* Clean up and return */
594 free_http_response(rsp);
599 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
601 if (fwd->forward_host)
603 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
604 fwd->forward_host, fwd->forward_port, http->hostport);
608 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
611 /* here we connect to the server, gateway, or the forwarder */
613 csp->sfd = forwarded_connect(fwd, http, csp);
617 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
622 rsp = error_response(csp, "no-such-domain", errno);
624 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
625 csp->ip_addr_str, http->cmd);
629 rsp = error_response(csp, "connect-failed", errno);
631 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
632 csp->ip_addr_str, http->cmd);
635 /* Write the answer to the client */
638 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
639 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
641 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
645 free_http_response(rsp);
650 log_error(LOG_LEVEL_CONNECT, "OK");
652 if (fwd->forward_host || (http->ssl == 0))
654 /* write the client's (modified) header to the server
655 * (along with anything else that may be in the buffer)
660 if ((write_socket(csp->sfd, hdr, n) != n)
661 || (flush_socket(csp->sfd, csp ) < 0))
663 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
666 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
667 csp->ip_addr_str, http->cmd);
669 rsp = error_response(csp, "connect-failed", errno);
673 if ((write_socket(csp->cfd, rsp->head, n) != n)
674 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
676 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
680 free_http_response(rsp);
688 * We're running an SSL tunnel and we're not forwarding,
689 * so just send the "connect succeeded" message to the
690 * client, flush the rest, and get out of the way.
692 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
693 csp->ip_addr_str, http->cmd);
695 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
703 /* we're finished with the client's header */
706 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
708 /* pass data between the client and server
709 * until one or the other shuts down the connection.
718 FD_SET(csp->cfd, &rfds);
719 FD_SET(csp->sfd, &rfds);
721 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
725 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
729 /* this is the body of the browser's request
730 * just read it and write it.
733 if (FD_ISSET(csp->cfd, &rfds))
735 n = read_socket(csp->cfd, buf, sizeof(buf));
739 break; /* "game over, man" */
742 if (write_socket(csp->sfd, buf, n) != n)
744 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
751 * The server wants to talk. It could be the header or the body.
752 * If `hdr' is null, then it's the header otherwise it's the body.
753 * FIXME: Does `hdr' really mean `host'?
757 if (FD_ISSET(csp->sfd, &rfds))
760 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
764 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
766 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
767 csp->ip_addr_str, http->cmd);
769 rsp = error_response(csp, "connect-failed", errno);
773 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
774 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
776 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
780 free_http_response(rsp);
784 /* Add a trailing zero. This lets filter_popups
785 * use string operations.
790 /* Filter the popups on this read. */
791 if (block_popups_now)
793 filter_popups(buf, n);
795 #endif /* def KILLPOPUPS */
797 /* Normally, this would indicate that we've read
798 * as much as the server has sent us and we can
799 * close the client connection. However, Microsoft
800 * in its wisdom has released IIS/5 with a bug that
801 * prevents it from sending the trailing \r\n in
802 * a 302 redirect header (and possibly other headers).
803 * To work around this if we've haven't parsed
804 * a full header we'll append a trailing \r\n
805 * and see if this now generates a valid one.
807 * This hack shouldn't have any impacts. If we've
808 * already transmitted the header or if this is a
809 * SSL connection, then we won't bother with this
810 * hack. So we only work on partially received
811 * headers. If we append a \r\n and this still
812 * doesn't generate a valid header, then we won't
813 * transmit anything to the client.
817 /* This hack must only be enforced for headers. */
818 if (server_body || http->ssl)
823 p = re_process_buffer(csp);
824 hdr = sed(server_patterns, add_server_headers, csp);
826 if ((write_socket(csp->cfd, hdr, n) != n)
827 || (write_socket(csp->cfd, p, csp->content_length) != csp->content_length))
829 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
835 #endif /* def PCRS */
836 break; /* "game over, man" */
839 /* Let's pretend the server just sent us a blank line. */
840 n = sprintf(buf, "\r\n");
843 * Now, let the normal header parsing algorithm below do its
844 * job. If it fails, we'll exit instead of continuing.
851 * If this is an SSL connection or we're in the body
852 * of the server document, just write it to the client.
855 if (server_body || http->ssl)
860 add_to_iob(csp, buf, n); /* Buffer the body for filtering */
863 #endif /* def PCRS */
866 if (write_socket(csp->cfd, buf, n) != n)
868 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
877 /* we're still looking for the end of the
878 * server's header ... (does that make header
879 * parsing an "out of body experience" ?
882 /* buffer up the data we just read */
883 add_to_iob(csp, buf, n);
885 /* get header lines from the iob */
887 while ((p = get_header(csp)))
891 /* see following note */
894 enlist(csp->headers, p);
898 /* NOTE: there are no "empty" headers so
899 * if the pointer `p' is not NULL we must
900 * assume that we reached the end of the
901 * buffer before we hit the end of the header.
908 /* Well, we tried our MS IIS/5
909 * hack and it didn't work.
910 * The header is incomplete
911 * and there isn't anything
912 * we can do about it.
918 /* Since we have to wait for
919 * more from the server before
920 * we can parse the headers
921 * we just continue here.
927 /* we have now received the entire header.
928 * filter it and send the result to the client
931 hdr = sed(server_patterns, add_server_headers, csp);
934 /* write the server's (modified) header to
935 * the client (along with anything else that
936 * may be in the buffer)
940 /* Start blocking popups if appropriate. */
942 if (csp->is_text && /* It's a text / * MIME-Type */
943 !http->ssl && /* We talk plaintext */
944 block_popups) /* Policy allows */
946 block_popups_now = 1;
949 #endif /* def KILLPOPUPS */
952 /* Start re_filtering this if appropriate. */
954 if (csp->is_text && /* It's a text / * MIME-Type */
955 !http->ssl && /* We talk plaintext */
956 pcrs_filter) /* Policy allows */
961 /* This next line is a little ugly, but it simplifies the if statement below. */
962 /* Basically if using PCRS, we want the OR condition to require "!filtering" */
963 #define NOT_FILTERING_AND !filtering &&
965 #else /* not def PCRS */
967 #define NOT_FILTERING_AND
969 #endif /* def PCRS */
971 if (NOT_FILTERING_AND ((write_socket(csp->cfd, hdr, n) != n)
972 || (n = flush_socket(csp->cfd, csp) < 0)))
974 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
976 /* the write failed, so don't bother
977 * mentioning it to the client...
978 * it probably can't hear us anyway.
984 NOT_FILTERING_AND (byte_count += n);
986 /* we're finished with the server's header */
991 /* If this was a MS IIS/5 hack then it means
992 * the server has already closed the
993 * connection. Nothing more to read. Time
1004 return; /* huh? we should never get here */
1007 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1008 csp->ip_addr_str, http->cmd, byte_count);
1012 /*********************************************************************
1016 * Description : This is little more than chat. We only "serve" to
1017 * to close any socket that chat may have opened.
1020 * 1 : csp = Current client state (buffers, headers, etc...)
1024 *********************************************************************/
1026 void serve(struct client_state *csp)
1027 #else /* ifndef AMIGA */
1028 static void serve(struct client_state *csp)
1029 #endif /* def AMIGA */
1032 close_socket(csp->cfd);
1036 close_socket(csp->sfd);
1045 /*********************************************************************
1047 * Function : server_thread
1049 * Description : We only exist to call `serve' in a threaded environment.
1052 * 1 : data = Current client state (buffers, headers, etc...)
1054 * Returns : Always 0.
1056 *********************************************************************/
1057 static int32 server_thread(void *data)
1059 serve((struct client_state *) data);
1066 /*********************************************************************
1070 * Description : Load the config file and start the listen loop.
1071 * This function is a lot more *sane* with the `load_config'
1072 * and `listen_loop' functions; although it stills does
1073 * a *little* too much for my taste.
1076 * 1 : argc = Number of parameters (including $0).
1077 * 2 : argv = Array of (char *)'s to the parameters.
1079 * Returns : 1 if : can't open config file, unrecognized directive,
1080 * stats requested in multi-thread mode, can't open the
1081 * log file, can't open the jar file, listen port is invalid,
1082 * any load fails, and can't bind port.
1084 * Else main never returns, the process must be signaled
1085 * to terminate execution. Or, on Windows, use the
1086 * "File", "Exit" menu option.
1088 *********************************************************************/
1090 int _main(int argc, const char *argv[])
1092 int main(int argc, const char *argv[])
1097 "AmiTCP:db/junkbuster/config"
1098 #elif !defined(_WIN32)
1105 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1106 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1108 printf("JunkBuster proxy version " VERSION ".\n\n"
1109 "Usage: %s [configfile]\n\n"
1110 "See " HOME_PAGE_URL " for details.\n"
1111 "This program is distributed under the GNU GPL, version 2 or later.\n",
1115 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1117 printf(VERSION "\n");
1120 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1127 configfile = argv[1];
1134 #elif defined(_WIN32)
1140 signal(SIGPIPE, SIG_IGN);
1141 signal(SIGCHLD, SIG_IGN);
1143 #else /* ifdef _WIN32 */
1144 # ifdef _WIN_CONSOLE
1146 * We *are* in a windows console app.
1147 * Print a verbose messages about FAQ's and such
1149 printf(win32_blurb);
1150 # endif /* def _WIN_CONSOLE */
1151 #endif /* def _WIN32 */
1162 /*********************************************************************
1164 * Function : listen_loop
1166 * Description : bind the listen port and enter a "FOREVER" listening loop.
1172 *********************************************************************/
1173 static void listen_loop(void)
1175 struct client_state *csp = NULL;
1177 struct configuration_spec * config;
1179 config = load_config();
1181 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1182 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1184 bfd = bind_port(config->haddr, config->hport);
1188 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1189 "- There may be another junkbuster or some other "
1190 "proxy running on port %d",
1191 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1192 config->hport, config->hport
1194 /* shouldn't get here */
1198 config->need_bind = 0;
1203 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1204 while (waitpid(-1, NULL, WNOHANG) > 0)
1206 /* zombie children */
1208 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1211 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1213 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1217 memset(csp, '\0', sizeof(*csp));
1222 csp->config = config = load_config();
1224 if ( config->need_bind )
1227 * Since we were listening to the "old port", we will not see
1228 * a "listen" param change until the next IJB request. So, at
1229 * least 1 more request must be made for us to find the new
1230 * setting. I am simply closing the old socket and binding the
1233 * Which-ever is correct, we will serve 1 more page via the
1234 * old settings. This should probably be a "show-proxy-args"
1235 * request. This should not be a so common of an operation
1236 * that this will hurt people's feelings.
1241 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1242 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1243 bfd = bind_port(config->haddr, config->hport);
1247 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1248 "- There may be another junkbuster or some other "
1249 "proxy running on port %d",
1250 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1251 config->hport, config->hport
1253 /* shouldn't get here */
1257 config->need_bind = 0;
1260 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1262 if (!accept_connection(csp, bfd))
1264 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1277 log_error(LOG_LEVEL_CONNECT, "OK");
1281 /* by haroon - most of credit to srt19170 */
1282 csp->toggled_on = g_bToggleIJB;
1285 if (run_loader(csp))
1287 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1288 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1292 if (block_acl(NULL,csp))
1294 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1295 close_socket(csp->cfd);
1299 #endif /* def ACL_FILES */
1301 /* add it to the list of clients */
1302 csp->next = clients->next;
1303 clients->next = csp;
1305 if (config->multi_threaded)
1309 /* this is a switch () statment in the C preprocessor - ugh */
1310 #undef SELECTED_ONE_OPTION
1312 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1313 #define SELECTED_ONE_OPTION
1314 child_id = _beginthread(
1320 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1321 #define SELECTED_ONE_OPTION
1323 thread_id tid = spawn_thread
1324 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1326 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1328 child_id = (int) tid;
1337 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1338 #define SELECTED_ONE_OPTION
1339 csp->cfd = ReleaseSocket(csp->cfd, -1);
1340 if((child_id = (int)CreateNewProcTags(
1341 NP_Entry, (ULONG)server_thread,
1342 NP_Output, Output(),
1343 NP_CloseOutput, FALSE,
1344 NP_Name, (ULONG)"junkbuster child",
1345 NP_StackSize, 200*1024,
1349 ((struct Task *)child_id)->tc_UserData = csp;
1350 Signal((struct Task *)child_id, SIGF_SINGLE);
1355 #if !defined(SELECTED_ONE_OPTION)
1359 #undef SELECTED_ONE_OPTION
1360 /* end of cpp switch () */
1362 if (child_id < 0) /* failed */
1364 char buf[BUFFER_SIZE];
1366 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1368 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1370 write_socket(csp->cfd, buf, strlen(buf));
1371 close_socket(csp->cfd);
1377 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1378 /* This block is only needed when using fork().
1379 * When using threads, the server thread was
1380 * created and run by the call to _beginthread().
1382 if (child_id == 0) /* child */
1390 /* in a fork()'d environment, the parent's
1391 * copy of the client socket and the CSP
1395 #if !defined(_WIN32) && defined(__CYGWIN__)
1397 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1398 close_socket(csp->cfd);
1401 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */