1 const char jcc_rcs[] = "$Id: jcc.c,v 1.16 2001/06/01 18:49:17 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.16 2001/06/01 18:49:17 jongfoster
37 * Replaced "list_share" with "list" - the tiny memory gain was not
38 * worth the extra complexity.
40 * Revision 1.15 2001/05/31 21:24:47 jongfoster
41 * Changed "permission" to "action" throughout.
42 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
43 * Moved vanilla wafer check into chat(), since we must now
44 * decide whether or not to add it based on the URL.
46 * Revision 1.14 2001/05/29 20:14:01 joergs
47 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
50 * Revision 1.13 2001/05/29 09:50:24 jongfoster
51 * Unified blocklist/imagelist/permissionslist.
52 * File format is still under discussion, but the internal changes
55 * Also modified interceptor behaviour:
56 * - We now intercept all URLs beginning with one of the following
57 * prefixes (and *only* these prefixes):
59 * * http://ijbswa.sf.net/config/
60 * * http://ijbswa.sourceforge.net/config/
61 * - New interceptors "home page" - go to http://i.j.b/ to see it.
62 * - Internal changes so that intercepted and fast redirect pages
63 * are not replaced with an image.
64 * - Interceptors now have the option to send a binary page direct
65 * to the client. (i.e. ijb-send-banner uses this)
66 * - Implemented show-url-info interceptor. (Which is why I needed
67 * the above interceptors changes - a typical URL is
68 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
69 * The previous mechanism would not have intercepted that, and
70 * if it had been intercepted then it then it would have replaced
73 * Revision 1.12 2001/05/27 22:17:04 oes
75 * - re_process_buffer no longer writes the modified buffer
76 * to the client, which was very ugly. It now returns the
77 * buffer, which it is then written by chat.
79 * - content_length now adjusts the Content-Length: header
80 * for modified documents rather than crunch()ing it.
81 * (Length info in csp->content_length, which is 0 for
82 * unmodified documents)
84 * - For this to work, sed() is called twice when filtering.
86 * Revision 1.11 2001/05/26 17:27:53 jongfoster
87 * Added support for CLF and fixed LOG_LEVEL_LOG.
88 * Also did CRLF->LF fix of my previous patch.
90 * Revision 1.10 2001/05/26 15:26:15 jongfoster
91 * ACL feature now provides more security by immediately dropping
92 * connections from untrusted hosts.
94 * Revision 1.9 2001/05/26 00:28:36 jongfoster
95 * Automatic reloading of config file.
96 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
97 * Most of the global variables have been moved to a new
98 * struct configuration_spec, accessed through csp->config->globalname
99 * Most of the globals remaining are used by the Win32 GUI.
101 * Revision 1.8 2001/05/25 22:43:18 jongfoster
102 * Fixing minor memory leak and buffer overflow.
104 * Revision 1.7 2001/05/25 22:34:30 jongfoster
107 * Revision 1.6 2001/05/23 00:13:58 joergs
108 * AmigaOS support fixed.
110 * Revision 1.5 2001/05/22 18:46:04 oes
112 * - Enabled filtering banners by size rather than URL
113 * by adding patterns that replace all standard banner
114 * sizes with the "Junkbuster" gif to the re_filterfile
116 * - Enabled filtering WebBugs by providing a pattern
117 * which kills all 1x1 images
119 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
120 * which is selected by the (nonstandard and therefore
121 * capital) letter 'U' in the option string.
122 * It causes the quantifiers to be ungreedy by default.
123 * Appending a ? turns back to greedy (!).
125 * - Added a new interceptor ijb-send-banner, which
126 * sends back the "Junkbuster" gif. Without imagelist or
127 * MSIE detection support, or if tinygif = 1, or the
128 * URL isn't recognized as an imageurl, a lame HTML
129 * explanation is sent instead.
131 * - Added new feature, which permits blocking remote
132 * script redirects and firing back a local redirect
134 * The feature is conditionally compiled, i.e. it
135 * can be disabled with --disable-fast-redirects,
136 * plus it must be activated by a "fast-redirects"
137 * line in the config file, has its own log level
138 * and of course wants to be displayed by show-proxy-args
139 * Note: Boy, all the #ifdefs in 1001 locations and
140 * all the fumbling with configure.in and acconfig.h
141 * were *way* more work than the feature itself :-(
143 * - Because a generic redirect template was needed for
144 * this, tinygif = 3 now uses the same.
146 * - Moved GIFs, and other static HTTP response templates
151 * - Removed some >400 CRs again (Jon, you really worked
154 * Revision 1.4 2001/05/21 19:34:01 jongfoster
155 * Made failure to bind() a fatal error.
157 * Revision 1.3 2001/05/20 01:21:20 jongfoster
158 * Version 2.9.4 checkin.
159 * - Merged popupfile and cookiefile, and added control over PCRS
160 * filtering, in new "permissionsfile".
161 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
162 * file error you now get a message box (in the Win32 GUI) rather
163 * than the program exiting with no explanation.
164 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
166 * - Removed tabs from "config"
167 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
168 * - Bumped up version number.
170 * Revision 1.2 2001/05/17 22:34:44 oes
171 * - Added hint on GIF char array generation to jcc.c
172 * - Cleaned CRLF's from the sources and related files
173 * - Repaired logging for REF and FRC
175 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
176 * Initial import of version 2.9.3 source tree
179 *********************************************************************/
185 #include <sys/types.h>
194 # include <sys/timeb.h>
195 # include <windows.h>
197 # include <process.h>
200 # endif /* def TOGGLE */
203 # ifndef _WIN_CONSOLE
205 # endif /* ndef _WIN_CONSOLE */
207 #else /* ifndef _WIN32 */
210 # include <sys/time.h>
211 # include <sys/wait.h>
212 # include <sys/stat.h>
216 # include <socket.h> /* BeOS has select() for sockets only. */
217 # include <OS.h> /* declarations for threads and stuff. */
231 #include "showargs.h"
233 #include "killpopup.h"
234 #include "miscutil.h"
236 #include "jbsockets.h"
240 const char jcc_h_rcs[] = JCC_H_VERSION;
241 const char project_h_rcs[] = PROJECT_H_VERSION;
243 struct client_state clients[1];
244 struct file_list files[1];
247 int urls_read = 0; /* total nr of urls read inc rejected */
248 int urls_rejected = 0; /* total nr of urls rejected */
249 #endif /* def STATISTICS */
252 static void listen_loop(void);
253 static void chat(struct client_state *csp);
255 void serve(struct client_state *csp);
256 #else /* ifndef AMIGA */
257 static void serve(struct client_state *csp);
258 #endif /* def AMIGA */
261 static int32 server_thread(void *data);
262 #endif /* def __BEOS__ */
265 #define sleep(N) Sleep(((N) * 1000))
269 /* The vanilla wafer. */
270 static const char VANILLA_WAFER[] =
271 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
272 "Do_not_send_me_any_copyrighted_information_other_than_the_"
273 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
274 "In_particular_do_not_send_me_any_cookies_that_"
275 "are_subject_to_a_claim_of_copyright_by_anybody._"
276 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
277 "(copyright_or_otherwise)_applying_to_any_cookie._";
280 /*********************************************************************
284 * Description : Once a connection to the client has been accepted,
285 * this function is called (via serve()) to handle the
286 * main business of the communication. When this
287 * function returns, the caller must close the client
291 * 1 : csp = Current client state (buffers, headers, etc...)
293 * Returns : On success, the number of bytes written are returned (zero
294 * indicates nothing was written). On error, -1 is returned,
295 * and errno is set appropriately. If count is zero and the
296 * file descriptor refers to a regular file, 0 will be
297 * returned without causing any other effect. For a special
298 * file, the results are not portable.
300 *********************************************************************/
301 static void chat(struct client_state *csp)
304 * This next lines are a little ugly, but they simplifies the if statements below.
305 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
306 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
309 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
310 #else /* ifndef TOGGLE */
311 # define IS_TOGGLED_ON_AND
312 #endif /* ndef TOGGLE */
314 # define IS_NOT_FORCED_AND (!csp->force) &&
315 #else /* ifndef TOGGLE */
316 # define IS_NOT_FORCED_AND
317 #endif /* def FORCE_LOAD */
319 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
321 char buf[BUFSIZ], *hdr, *p, *req;
325 int n, maxfd, server_body;
326 int ms_iis5_hack = 0;
328 const struct gateway *gw;
329 struct http_request *http;
331 int block_popups; /* bool, 1==will block popups */
332 int block_popups_now = 0; /* bool, 1==currently blocking popups */
333 #endif /* def KILLPOPUPS */
335 int pcrs_filter; /* bool, 1==will filter through pcrs */
336 int filtering = 0; /* bool, 1==currently filtering through pcrs */
337 #endif /* def PCRS */
342 * Read the client's request. Note that since we're not using select() we
343 * could get blocked here if a client connected, then didn't say anything!
348 n = read_socket(csp->cfd, buf, sizeof(buf));
350 if (n <= 0) break; /* error! */
352 add_to_iob(csp, buf, n);
354 req = get_header(csp);
358 break; /* no HTTP request! */
363 continue; /* more to come! */
367 /* If this request contains the FORCE_PREFIX,
368 * better get rid of it now and set the force flag --oes
371 if (strstr(req, FORCE_PREFIX))
373 strclean(req, FORCE_PREFIX);
374 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
381 #endif /* def FORCE_LOAD */
383 parse_http_request(req, http, csp);
388 if (http->cmd == NULL)
390 strcpy(buf, CHEADER);
391 write_socket(csp->cfd, buf, strlen(buf));
393 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
398 /* decide how to route the HTTP request */
400 if ((gw = forward_url(http, csp)) == NULL)
402 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
403 /* Never get here - LOG_LEVEL_FATAL causes program exit */
406 /* build the http request to send to the server
407 * we have to do one of the following:
409 * create = use the original HTTP request to create a new
410 * HTTP request that has only the path component
411 * without the http://domainspec
412 * pass = pass the original HTTP request unchanged
414 * drop = drop the HTTP request
419 * +--------+--------+
421 * 0 | create | drop |
423 * Forwarding +--------+--------+
427 * +--------+--------+
431 if (gw->forward_host)
433 /* if forwarding, just pass the request as is */
434 enlist(csp->headers, http->cmd);
440 /* otherwise elide the host information from the url */
442 p = strsav(p, http->gpc);
444 p = strsav(p, http->path);
446 p = strsav(p, http->ver);
447 enlist(csp->headers, p);
452 /* decide what we're to do with cookies */
455 if (!csp->toggled_on)
457 /* Most compatible set of actions (i.e. none) */
458 init_current_action(csp->action);
461 #endif /* ndef TOGGLE */
463 url_actions(http, csp);
468 * If we're logging cookies in a cookie jar, and the user has not
469 * supplied any wafers, and the user has not told us to suppress the
470 * vanilla wafer, then send the vanilla wafer.
472 if ((csp->config->jarfile != NULL)
473 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
474 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
476 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
478 #endif /* def JAR_FILES */
481 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
482 #endif /* def KILLPOPUPS */
484 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
485 ((csp->action->flags & ACTION_FILTER) != 0);
486 #endif /* def PCRS */
489 /* grab the rest of the client's headers */
493 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
495 n = read_socket(csp->cfd, buf, sizeof(buf));
498 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
501 add_to_iob(csp, buf, n);
505 if (p == NULL) break;
507 enlist(csp->headers, p);
511 /* filter it as required */
513 hdr = sed(client_patterns, add_client_headers, csp);
515 destroy_list(csp->headers);
517 /* Check the request against all rules, unless
518 * we're toggled off or in force mode.
521 if (intercept_url(http, csp))
524 * The interceptor will write out the data.
525 * We don't need to do anything else
530 #endif /* def STATISTICS */
536 #ifdef FAST_REDIRECTS
537 else if (IS_ENABLED_AND
538 ((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
539 (p = redirect_url(http, csp)))
541 /* This must be blocked as HTML */
544 #endif /* def STATISTICS */
546 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
548 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
549 csp->ip_addr_str, http->cmd);
551 /* Send HTML redirection result */
552 write_socket(csp->cfd, p, strlen(p));
558 #endif /* def FAST_REDIRECTS */
560 else if (IS_ENABLED_AND (
562 (p = trust_url(http, csp)) ||
563 #endif /* def TRUST_FILES */
564 (p = block_url(http, csp)) ))
566 /* Block as HTML or image */
569 #endif /* def STATISTICS */
571 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
573 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 1",
574 csp->ip_addr_str, http->cmd);
576 #ifdef IMAGE_BLOCKING
577 /* Block as image? */
578 if ( ((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
579 && block_imageurl(http, csp) )
581 /* Send "blocked" image */
582 const char * blocker = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
584 log_error(LOG_LEVEL_GPC, "%s%s image crunch! --> %s",
585 http->hostport, http->path, (blocker ? blocker : "logo"));
587 if ((blocker == NULL) || (0 == strcmpic(blocker, "logo")))
589 write_socket(csp->cfd, JBGIF, sizeof(JBGIF)-1);
591 else if (0 == strcmpic(blocker, "blank"))
593 write_socket(csp->cfd, BLANKGIF, sizeof(BLANKGIF)-1);
598 p = (char *)malloc(sizeof(HTTP_REDIRECT_TEMPLATE) + strlen(blocker));
599 sprintf(p, HTTP_REDIRECT_TEMPLATE, blocker);
600 write_socket(csp->cfd, p, strlen(p));
604 #endif /* def IMAGE_BLOCKING */
607 /* Send HTML "blocked" message */
608 write_socket(csp->cfd, p, strlen(p));
616 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
618 if (gw->forward_host)
620 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
621 gw->forward_host, gw->forward_port, http->hostport);
625 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
628 /* here we connect to the server, gateway, or the forwarder */
630 csp->sfd = (gw->conn)(gw, http, csp);
634 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
639 err = zalloc(strlen(CNXDOM) + strlen(http->host));
640 sprintf(err, CNXDOM, http->host);
642 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
643 csp->ip_addr_str, http->cmd);
647 eno = safe_strerror(errno);
648 err = zalloc(strlen(CFAIL) + strlen(http->hostport) + strlen(eno));
649 sprintf(err, CFAIL, http->hostport, eno);
651 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
652 csp->ip_addr_str, http->cmd);
655 write_socket(csp->cfd, err, strlen(err));
662 log_error(LOG_LEVEL_CONNECT, "OK");
664 if (gw->forward_host || (http->ssl == 0))
666 /* write the client's (modified) header to the server
667 * (along with anything else that may be in the buffer)
672 if ((write_socket(csp->sfd, hdr, n) != n)
673 || (flush_socket(csp->sfd, csp ) < 0))
675 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
678 eno = safe_strerror(errno);
679 err = zalloc(strlen(CFAIL) + strlen(http->hostport) + strlen(eno));
680 sprintf(err, CFAIL, http->hostport, eno);
681 write_socket(csp->cfd, err, strlen(err));
683 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
684 csp->ip_addr_str, http->cmd);
694 * We're running an SSL tunnel and we're not forwarding,
695 * so just send the "connect succeeded" message to the
696 * client, flush the rest, and get out of the way.
698 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
699 csp->ip_addr_str, http->cmd);
701 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
709 /* we're finished with the client's header */
712 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
714 /* pass data between the client and server
715 * until one or the other shuts down the connection.
724 FD_SET(csp->cfd, &rfds);
725 FD_SET(csp->sfd, &rfds);
727 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
731 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
735 /* this is the body of the browser's request
736 * just read it and write it.
739 if (FD_ISSET(csp->cfd, &rfds))
741 n = read_socket(csp->cfd, buf, sizeof(buf));
745 break; /* "game over, man" */
748 if (write_socket(csp->sfd, buf, n) != n)
750 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
757 * The server wants to talk. It could be the header or the body.
758 * If `hdr' is null, then it's the header otherwise it's the body.
759 * FIXME: Does `hdr' really mean `host'?
763 if (FD_ISSET(csp->sfd, &rfds))
766 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
770 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
772 eno = safe_strerror(errno);
773 sprintf(buf, CFAIL, http->hostport, eno);
776 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
777 csp->ip_addr_str, http->cmd);
779 write_socket(csp->cfd, buf, strlen(buf));
783 /* Add a trailing zero. This lets filter_popups
784 * use string operations.
789 /* Filter the popups on this read. */
790 if (block_popups_now)
792 filter_popups(buf, n);
794 #endif /* def KILLPOPUPS */
796 /* Normally, this would indicate that we've read
797 * as much as the server has sent us and we can
798 * close the client connection. However, Microsoft
799 * in its wisdom has released IIS/5 with a bug that
800 * prevents it from sending the trailing \r\n in
801 * a 302 redirect header (and possibly other headers).
802 * To work around this if we've haven't parsed
803 * a full header we'll append a trailing \r\n
804 * and see if this now generates a valid one.
806 * This hack shouldn't have any impacts. If we've
807 * already transmitted the header or if this is a
808 * SSL connection, then we won't bother with this
809 * hack. So we only work on partially received
810 * headers. If we append a \r\n and this still
811 * doesn't generate a valid header, then we won't
812 * transmit anything to the client.
816 /* This hack must only be enforced for headers. */
817 if (server_body || http->ssl)
822 p = re_process_buffer(csp);
823 hdr = sed(server_patterns, add_server_headers, csp);
825 if ((write_socket(csp->cfd, hdr, n) != n)
826 || (write_socket(csp->cfd, p, csp->content_length) != csp->content_length))
828 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
834 #endif /* def PCRS */
835 break; /* "game over, man" */
838 /* Let's pretend the server just sent us a blank line. */
839 n = sprintf(buf, "\r\n");
842 * Now, let the normal header parsing algorithm below do its
843 * job. If it fails, we'll exit instead of continuing.
850 * If this is an SSL connection or we're in the body
851 * of the server document, just write it to the client.
854 if (server_body || http->ssl)
859 add_to_iob(csp, buf, n); /* Buffer the body for filtering */
862 #endif /* def PCRS */
865 if (write_socket(csp->cfd, buf, n) != n)
867 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
876 /* we're still looking for the end of the
877 * server's header ... (does that make header
878 * parsing an "out of body experience" ?
881 /* buffer up the data we just read */
882 add_to_iob(csp, buf, n);
884 /* get header lines from the iob */
886 while ((p = get_header(csp)))
890 /* see following note */
893 enlist(csp->headers, p);
897 /* NOTE: there are no "empty" headers so
898 * if the pointer `p' is not NULL we must
899 * assume that we reached the end of the
900 * buffer before we hit the end of the header.
907 /* Well, we tried our MS IIS/5
908 * hack and it didn't work.
909 * The header is incomplete
910 * and there isn't anything
911 * we can do about it.
917 /* Since we have to wait for
918 * more from the server before
919 * we can parse the headers
920 * we just continue here.
926 /* we have now received the entire header.
927 * filter it and send the result to the client
930 hdr = sed(server_patterns, add_server_headers, csp);
933 /* write the server's (modified) header to
934 * the client (along with anything else that
935 * may be in the buffer)
939 /* Start blocking popups if appropriate. */
941 if (csp->is_text && /* It's a text / * MIME-Type */
942 !http->ssl && /* We talk plaintext */
943 block_popups) /* Policy allows */
945 block_popups_now = 1;
948 #endif /* def KILLPOPUPS */
951 /* Start re_filtering this if appropriate. */
953 if (csp->is_text && /* It's a text / * MIME-Type */
954 !http->ssl && /* We talk plaintext */
955 pcrs_filter) /* Policy allows */
960 /* This next line is a little ugly, but it simplifies the if statement below. */
961 /* Basically if using PCRS, we want the OR condition to require "!filtering" */
962 #define NOT_FILTERING_AND !filtering &&
964 #else /* not def PCRS */
966 #define NOT_FILTERING_AND
968 #endif /* def PCRS */
970 if (NOT_FILTERING_AND ((write_socket(csp->cfd, hdr, n) != n)
971 || (n = flush_socket(csp->cfd, csp) < 0)))
973 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
975 /* the write failed, so don't bother
976 * mentioning it to the client...
977 * it probably can't hear us anyway.
983 NOT_FILTERING_AND (byte_count += n);
985 /* we're finished with the server's header */
990 /* If this was a MS IIS/5 hack then it means
991 * the server has already closed the
992 * connection. Nothing more to read. Time
1003 return; /* huh? we should never get here */
1006 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1007 csp->ip_addr_str, http->cmd, byte_count);
1011 /*********************************************************************
1015 * Description : This is little more than chat. We only "serve" to
1016 * to close any socket that chat may have opened.
1019 * 1 : csp = Current client state (buffers, headers, etc...)
1023 *********************************************************************/
1025 void serve(struct client_state *csp)
1026 #else /* ifndef AMIGA */
1027 static void serve(struct client_state *csp)
1028 #endif /* def AMIGA */
1031 close_socket(csp->cfd);
1035 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);
1067 /*********************************************************************
1071 * Description : Load the config file and start the listen loop.
1072 * This function is a lot more *sane* with the `load_config'
1073 * and `listen_loop' functions; although it stills does
1074 * a *little* too much for my taste.
1077 * 1 : argc = Number of parameters (including $0).
1078 * 2 : argv = Array of (char *)'s to the parameters.
1080 * Returns : 1 if : can't open config file, unrecognized directive,
1081 * stats requested in multi-thread mode, can't open the
1082 * log file, can't open the jar file, listen port is invalid,
1083 * any load fails, and can't bind port.
1085 * Else main never returns, the process must be signaled
1086 * to terminate execution. Or, on Windows, use the
1087 * "File", "Exit" menu option.
1089 *********************************************************************/
1091 int _main(int argc, const char *argv[])
1093 int main(int argc, const char *argv[])
1098 "AmiTCP:db/junkbuster/config"
1099 #elif !defined(_WIN32)
1106 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1107 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1109 printf("JunkBuster proxy version " VERSION ".\n\n"
1110 "Usage: %s [configfile]\n\n"
1111 "See " HOME_PAGE_URL " for details.\n"
1112 "This program is distributed under the GNU GPL, version 2 or later.\n",
1116 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1118 printf(VERSION "\n");
1121 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1128 configfile = argv[1];
1135 #elif defined(_WIN32)
1141 signal(SIGPIPE, SIG_IGN);
1142 signal(SIGCHLD, SIG_IGN);
1144 #else /* ifdef _WIN32 */
1145 # ifdef _WIN_CONSOLE
1147 * We *are* in a windows console app.
1148 * Print a verbose messages about FAQ's and such
1150 printf(win32_blurb);
1151 # endif /* def _WIN_CONSOLE */
1152 #endif /* def _WIN32 */
1163 /*********************************************************************
1165 * Function : listen_loop
1167 * Description : bind the listen port and enter a "FOREVER" listening loop.
1173 *********************************************************************/
1174 static void listen_loop(void)
1176 struct client_state *csp = NULL;
1178 struct configuration_spec * config;
1180 config = load_config();
1182 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1183 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1185 bfd = bind_port(config->haddr, config->hport);
1189 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1190 "- There may be another junkbuster or some other "
1191 "proxy running on port %d",
1192 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1193 config->hport, config->hport
1195 /* shouldn't get here */
1199 config->need_bind = 0;
1204 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1205 while (waitpid(-1, NULL, WNOHANG) > 0)
1207 /* zombie children */
1209 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1212 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1214 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1218 memset(csp, '\0', sizeof(*csp));
1223 csp->config = config = load_config();
1225 if ( config->need_bind )
1228 * Since we were listening to the "old port", we will not see
1229 * a "listen" param change until the next IJB request. So, at
1230 * least 1 more request must be made for us to find the new
1231 * setting. I am simply closing the old socket and binding the
1234 * Which-ever is correct, we will serve 1 more page via the
1235 * old settings. This should probably be a "show-proxy-args"
1236 * request. This should not be a so common of an operation
1237 * that this will hurt people's feelings.
1242 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1243 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1244 bfd = bind_port(config->haddr, config->hport);
1248 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1249 "- There may be another junkbuster or some other "
1250 "proxy running on port %d",
1251 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1252 config->hport, config->hport
1254 /* shouldn't get here */
1258 config->need_bind = 0;
1261 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1263 if (!accept_connection(csp, bfd))
1265 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1278 log_error(LOG_LEVEL_CONNECT, "OK");
1282 /* by haroon - most of credit to srt19170 */
1283 csp->toggled_on = g_bToggleIJB;
1286 if (run_loader(csp))
1288 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1289 /* 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);
1300 /* add it to the list of clients */
1301 csp->next = clients->next;
1302 clients->next = csp;
1304 if (config->multi_threaded)
1308 /* this is a switch () statment in the C preprocessor - ugh */
1309 #undef SELECTED_ONE_OPTION
1311 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1312 #define SELECTED_ONE_OPTION
1313 child_id = _beginthread(
1319 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1320 #define SELECTED_ONE_OPTION
1322 thread_id tid = spawn_thread
1323 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1325 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1327 child_id = (int) tid;
1336 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1337 #define SELECTED_ONE_OPTION
1338 csp->cfd = ReleaseSocket(csp->cfd, -1);
1339 if((child_id = (int)CreateNewProcTags(
1340 NP_Entry, (ULONG)server_thread,
1341 NP_Output, Output(),
1342 NP_CloseOutput, FALSE,
1343 NP_Name, (ULONG)"junkbuster child",
1344 NP_StackSize, 200*1024,
1348 ((struct Task *)child_id)->tc_UserData = csp;
1349 Signal((struct Task *)child_id, SIGF_SINGLE);
1354 #if !defined(SELECTED_ONE_OPTION)
1358 #undef SELECTED_ONE_OPTION
1359 /* end of cpp switch () */
1361 if (child_id < 0) /* failed */
1365 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1367 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1369 write_socket(csp->cfd, buf, strlen(buf));
1370 close_socket(csp->cfd);
1376 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1377 /* This block is only needed when using fork().
1378 * When using threads, the server thread was
1379 * created and run by the call to _beginthread().
1381 if (child_id == 0) /* child */
1389 /* in a fork()'d environment, the parent's
1390 * copy of the client socket and the CSP
1394 #if !defined(_WIN32) && defined(__CYGWIN__)
1396 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1397 close_socket(csp->cfd);
1400 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */