1 const char jcc_rcs[] = "$Id: jcc.c,v 1.15 2001/05/31 21:24:47 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.15 2001/05/31 21:24:47 jongfoster
37 * Changed "permission" to "action" throughout.
38 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
39 * Moved vanilla wafer check into chat(), since we must now
40 * decide whether or not to add it based on the URL.
42 * Revision 1.14 2001/05/29 20:14:01 joergs
43 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
46 * Revision 1.13 2001/05/29 09:50:24 jongfoster
47 * Unified blocklist/imagelist/permissionslist.
48 * File format is still under discussion, but the internal changes
51 * Also modified interceptor behaviour:
52 * - We now intercept all URLs beginning with one of the following
53 * prefixes (and *only* these prefixes):
55 * * http://ijbswa.sf.net/config/
56 * * http://ijbswa.sourceforge.net/config/
57 * - New interceptors "home page" - go to http://i.j.b/ to see it.
58 * - Internal changes so that intercepted and fast redirect pages
59 * are not replaced with an image.
60 * - Interceptors now have the option to send a binary page direct
61 * to the client. (i.e. ijb-send-banner uses this)
62 * - Implemented show-url-info interceptor. (Which is why I needed
63 * the above interceptors changes - a typical URL is
64 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
65 * The previous mechanism would not have intercepted that, and
66 * if it had been intercepted then it then it would have replaced
69 * Revision 1.12 2001/05/27 22:17:04 oes
71 * - re_process_buffer no longer writes the modified buffer
72 * to the client, which was very ugly. It now returns the
73 * buffer, which it is then written by chat.
75 * - content_length now adjusts the Content-Length: header
76 * for modified documents rather than crunch()ing it.
77 * (Length info in csp->content_length, which is 0 for
78 * unmodified documents)
80 * - For this to work, sed() is called twice when filtering.
82 * Revision 1.11 2001/05/26 17:27:53 jongfoster
83 * Added support for CLF and fixed LOG_LEVEL_LOG.
84 * Also did CRLF->LF fix of my previous patch.
86 * Revision 1.10 2001/05/26 15:26:15 jongfoster
87 * ACL feature now provides more security by immediately dropping
88 * connections from untrusted hosts.
90 * Revision 1.9 2001/05/26 00:28:36 jongfoster
91 * Automatic reloading of config file.
92 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
93 * Most of the global variables have been moved to a new
94 * struct configuration_spec, accessed through csp->config->globalname
95 * Most of the globals remaining are used by the Win32 GUI.
97 * Revision 1.8 2001/05/25 22:43:18 jongfoster
98 * Fixing minor memory leak and buffer overflow.
100 * Revision 1.7 2001/05/25 22:34:30 jongfoster
103 * Revision 1.6 2001/05/23 00:13:58 joergs
104 * AmigaOS support fixed.
106 * Revision 1.5 2001/05/22 18:46:04 oes
108 * - Enabled filtering banners by size rather than URL
109 * by adding patterns that replace all standard banner
110 * sizes with the "Junkbuster" gif to the re_filterfile
112 * - Enabled filtering WebBugs by providing a pattern
113 * which kills all 1x1 images
115 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
116 * which is selected by the (nonstandard and therefore
117 * capital) letter 'U' in the option string.
118 * It causes the quantifiers to be ungreedy by default.
119 * Appending a ? turns back to greedy (!).
121 * - Added a new interceptor ijb-send-banner, which
122 * sends back the "Junkbuster" gif. Without imagelist or
123 * MSIE detection support, or if tinygif = 1, or the
124 * URL isn't recognized as an imageurl, a lame HTML
125 * explanation is sent instead.
127 * - Added new feature, which permits blocking remote
128 * script redirects and firing back a local redirect
130 * The feature is conditionally compiled, i.e. it
131 * can be disabled with --disable-fast-redirects,
132 * plus it must be activated by a "fast-redirects"
133 * line in the config file, has its own log level
134 * and of course wants to be displayed by show-proxy-args
135 * Note: Boy, all the #ifdefs in 1001 locations and
136 * all the fumbling with configure.in and acconfig.h
137 * were *way* more work than the feature itself :-(
139 * - Because a generic redirect template was needed for
140 * this, tinygif = 3 now uses the same.
142 * - Moved GIFs, and other static HTTP response templates
147 * - Removed some >400 CRs again (Jon, you really worked
150 * Revision 1.4 2001/05/21 19:34:01 jongfoster
151 * Made failure to bind() a fatal error.
153 * Revision 1.3 2001/05/20 01:21:20 jongfoster
154 * Version 2.9.4 checkin.
155 * - Merged popupfile and cookiefile, and added control over PCRS
156 * filtering, in new "permissionsfile".
157 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
158 * file error you now get a message box (in the Win32 GUI) rather
159 * than the program exiting with no explanation.
160 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
162 * - Removed tabs from "config"
163 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
164 * - Bumped up version number.
166 * Revision 1.2 2001/05/17 22:34:44 oes
167 * - Added hint on GIF char array generation to jcc.c
168 * - Cleaned CRLF's from the sources and related files
169 * - Repaired logging for REF and FRC
171 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
172 * Initial import of version 2.9.3 source tree
175 *********************************************************************/
181 #include <sys/types.h>
190 # include <sys/timeb.h>
191 # include <windows.h>
193 # include <process.h>
196 # endif /* def TOGGLE */
199 # ifndef _WIN_CONSOLE
201 # endif /* ndef _WIN_CONSOLE */
203 #else /* ifndef _WIN32 */
206 # include <sys/time.h>
207 # include <sys/wait.h>
208 # include <sys/stat.h>
212 # include <socket.h> /* BeOS has select() for sockets only. */
213 # include <OS.h> /* declarations for threads and stuff. */
227 #include "showargs.h"
229 #include "killpopup.h"
230 #include "miscutil.h"
232 #include "jbsockets.h"
236 const char jcc_h_rcs[] = JCC_H_VERSION;
237 const char project_h_rcs[] = PROJECT_H_VERSION;
239 struct client_state clients[1];
240 struct file_list files[1];
243 int urls_read = 0; /* total nr of urls read inc rejected */
244 int urls_rejected = 0; /* total nr of urls rejected */
245 #endif /* def STATISTICS */
248 static void listen_loop(void);
249 static void chat(struct client_state *csp);
251 void serve(struct client_state *csp);
252 #else /* ifndef AMIGA */
253 static void serve(struct client_state *csp);
254 #endif /* def AMIGA */
257 static int32 server_thread(void *data);
258 #endif /* def __BEOS__ */
261 #define sleep(N) Sleep(((N) * 1000))
265 /* The vanilla wafer. */
266 static const char VANILLA_WAFER[] =
267 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
268 "Do_not_send_me_any_copyrighted_information_other_than_the_"
269 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
270 "In_particular_do_not_send_me_any_cookies_that_"
271 "are_subject_to_a_claim_of_copyright_by_anybody._"
272 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
273 "(copyright_or_otherwise)_applying_to_any_cookie._";
276 /*********************************************************************
280 * Description : Once a connection to the client has been accepted,
281 * this function is called (via serve()) to handle the
282 * main business of the communication. When this
283 * function returns, the caller must close the client
287 * 1 : csp = Current client state (buffers, headers, etc...)
289 * Returns : On success, the number of bytes written are returned (zero
290 * indicates nothing was written). On error, -1 is returned,
291 * and errno is set appropriately. If count is zero and the
292 * file descriptor refers to a regular file, 0 will be
293 * returned without causing any other effect. For a special
294 * file, the results are not portable.
296 *********************************************************************/
297 static void chat(struct client_state *csp)
300 * This next lines are a little ugly, but they simplifies the if statements below.
301 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
302 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
305 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
306 #else /* ifndef TOGGLE */
307 # define IS_TOGGLED_ON_AND
308 #endif /* ndef TOGGLE */
310 # define IS_NOT_FORCED_AND (!csp->force) &&
311 #else /* ifndef TOGGLE */
312 # define IS_NOT_FORCED_AND
313 #endif /* def FORCE_LOAD */
315 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
317 char buf[BUFSIZ], *hdr, *p, *req;
321 int n, maxfd, server_body;
322 int ms_iis5_hack = 0;
324 const struct gateway *gw;
325 struct http_request *http;
327 int block_popups; /* bool, 1==will block popups */
328 int block_popups_now = 0; /* bool, 1==currently blocking popups */
329 #endif /* def KILLPOPUPS */
331 int pcrs_filter; /* bool, 1==will filter through pcrs */
332 int filtering = 0; /* bool, 1==currently filtering through pcrs */
333 #endif /* def PCRS */
338 * Read the client's request. Note that since we're not using select() we
339 * could get blocked here if a client connected, then didn't say anything!
344 n = read_socket(csp->cfd, buf, sizeof(buf));
346 if (n <= 0) break; /* error! */
348 add_to_iob(csp, buf, n);
350 req = get_header(csp);
354 break; /* no HTTP request! */
359 continue; /* more to come! */
363 /* If this request contains the FORCE_PREFIX,
364 * better get rid of it now and set the force flag --oes
367 if (strstr(req, FORCE_PREFIX))
369 strclean(req, FORCE_PREFIX);
370 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
377 #endif /* def FORCE_LOAD */
379 parse_http_request(req, http, csp);
384 if (http->cmd == NULL)
386 strcpy(buf, CHEADER);
387 write_socket(csp->cfd, buf, strlen(buf));
389 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
394 /* decide how to route the HTTP request */
396 if ((gw = forward_url(http, csp)) == NULL)
398 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
399 /* Never get here - LOG_LEVEL_FATAL causes program exit */
402 /* build the http request to send to the server
403 * we have to do one of the following:
405 * create = use the original HTTP request to create a new
406 * HTTP request that has only the path component
407 * without the http://domainspec
408 * pass = pass the original HTTP request unchanged
410 * drop = drop the HTTP request
415 * +--------+--------+
417 * 0 | create | drop |
419 * Forwarding +--------+--------+
423 * +--------+--------+
427 if (gw->forward_host)
429 /* if forwarding, just pass the request as is */
430 enlist(csp->headers, http->cmd);
436 /* otherwise elide the host information from the url */
438 p = strsav(p, http->gpc);
440 p = strsav(p, http->path);
442 p = strsav(p, http->ver);
443 enlist(csp->headers, p);
448 /* decide what we're to do with cookies */
451 if (!csp->toggled_on)
453 /* Most compatible set of actions (i.e. none) */
454 init_current_action(csp->action);
457 #endif /* ndef TOGGLE */
459 url_actions(http, csp);
464 * If we're logging cookies in a cookie jar, and the user has not
465 * supplied any wafers, and the user has not told us to suppress the
466 * vanilla wafer, then send the vanilla wafer.
468 if ((csp->config->jarfile != NULL)
469 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
470 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
472 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
474 #endif /* def JAR_FILES */
477 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
478 #endif /* def KILLPOPUPS */
480 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
481 ((csp->action->flags & ACTION_FILTER) != 0);
482 #endif /* def PCRS */
485 /* grab the rest of the client's headers */
489 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
491 n = read_socket(csp->cfd, buf, sizeof(buf));
494 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
497 add_to_iob(csp, buf, n);
501 if (p == NULL) break;
503 enlist(csp->headers, p);
507 /* filter it as required */
509 hdr = sed(client_patterns, add_client_headers, csp);
511 destroy_list(csp->headers);
513 /* Check the request against all rules, unless
514 * we're toggled off or in force mode.
517 if (intercept_url(http, csp))
520 * The interceptor will write out the data.
521 * We don't need to do anything else
526 #endif /* def STATISTICS */
532 #ifdef FAST_REDIRECTS
533 else if (IS_ENABLED_AND
534 ((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
535 (p = redirect_url(http, csp)))
537 /* This must be blocked as HTML */
540 #endif /* def STATISTICS */
542 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
544 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
545 csp->ip_addr_str, http->cmd);
547 /* Send HTML redirection result */
548 write_socket(csp->cfd, p, strlen(p));
554 #endif /* def FAST_REDIRECTS */
556 else if (IS_ENABLED_AND (
558 (p = trust_url(http, csp)) ||
559 #endif /* def TRUST_FILES */
560 (p = block_url(http, csp)) ))
562 /* Block as HTML or image */
565 #endif /* def STATISTICS */
567 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
569 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 1",
570 csp->ip_addr_str, http->cmd);
572 #ifdef IMAGE_BLOCKING
573 /* Block as image? */
574 if ( (csp->config->tinygif > 0) && block_imageurl(http, csp) )
576 /* Send "blocked" image */
577 log_error(LOG_LEVEL_GPC, "%s%s image crunch!",
578 http->hostport, http->path);
580 if (csp->config->tinygif == 1)
582 write_socket(csp->cfd, BLANKGIF, sizeof(BLANKGIF)-1);
584 else if (csp->config->tinygif == 2)
586 write_socket(csp->cfd, JBGIF, sizeof(JBGIF)-1);
588 else if ((csp->config->tinygif == 3) && (csp->config->tinygifurl))
591 p = (char *)malloc(sizeof(HTTP_REDIRECT_TEMPLATE)
592 + strlen(csp->config->tinygifurl));
593 sprintf(p, HTTP_REDIRECT_TEMPLATE, csp->config->tinygifurl);
594 write_socket(csp->cfd, p, strlen(p));
598 /* Should never happen */
599 write_socket(csp->cfd, JBGIF, sizeof(JBGIF)-1);
603 #endif /* def IMAGE_BLOCKING */
606 /* Send HTML "blocked" message, interception, or redirection result */
607 write_socket(csp->cfd, p, strlen(p));
615 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
617 if (gw->forward_host)
619 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
620 gw->forward_host, gw->forward_port, http->hostport);
624 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
627 /* here we connect to the server, gateway, or the forwarder */
629 csp->sfd = (gw->conn)(gw, http, csp);
633 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
638 err = zalloc(strlen(CNXDOM) + strlen(http->host));
639 sprintf(err, CNXDOM, http->host);
641 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
642 csp->ip_addr_str, http->cmd);
646 eno = safe_strerror(errno);
647 err = zalloc(strlen(CFAIL) + strlen(http->hostport) + strlen(eno));
648 sprintf(err, CFAIL, http->hostport, eno);
650 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
651 csp->ip_addr_str, http->cmd);
654 write_socket(csp->cfd, err, strlen(err));
661 log_error(LOG_LEVEL_CONNECT, "OK");
663 if (gw->forward_host || (http->ssl == 0))
665 /* write the client's (modified) header to the server
666 * (along with anything else that may be in the buffer)
671 if ((write_socket(csp->sfd, hdr, n) != n)
672 || (flush_socket(csp->sfd, csp ) < 0))
674 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
677 eno = safe_strerror(errno);
678 err = zalloc(strlen(CFAIL) + strlen(http->hostport) + strlen(eno));
679 sprintf(err, CFAIL, http->hostport, eno);
680 write_socket(csp->cfd, err, strlen(err));
682 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
683 csp->ip_addr_str, http->cmd);
693 * We're running an SSL tunnel and we're not forwarding,
694 * so just send the "connect succeeded" message to the
695 * client, flush the rest, and get out of the way.
697 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
698 csp->ip_addr_str, http->cmd);
700 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
708 /* we're finished with the client's header */
711 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
713 /* pass data between the client and server
714 * until one or the other shuts down the connection.
723 FD_SET(csp->cfd, &rfds);
724 FD_SET(csp->sfd, &rfds);
726 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
730 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
734 /* this is the body of the browser's request
735 * just read it and write it.
738 if (FD_ISSET(csp->cfd, &rfds))
740 n = read_socket(csp->cfd, buf, sizeof(buf));
744 break; /* "game over, man" */
747 if (write_socket(csp->sfd, buf, n) != n)
749 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
756 * The server wants to talk. It could be the header or the body.
757 * If `hdr' is null, then it's the header otherwise it's the body.
758 * FIXME: Does `hdr' really mean `host'?
762 if (FD_ISSET(csp->sfd, &rfds))
765 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
769 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
771 eno = safe_strerror(errno);
772 sprintf(buf, CFAIL, http->hostport, eno);
775 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
776 csp->ip_addr_str, http->cmd);
778 write_socket(csp->cfd, buf, strlen(buf));
782 /* Add a trailing zero. This lets filter_popups
783 * use string operations.
788 /* Filter the popups on this read. */
789 if (block_popups_now)
791 filter_popups(buf, n);
793 #endif /* def KILLPOPUPS */
795 /* Normally, this would indicate that we've read
796 * as much as the server has sent us and we can
797 * close the client connection. However, Microsoft
798 * in its wisdom has released IIS/5 with a bug that
799 * prevents it from sending the trailing \r\n in
800 * a 302 redirect header (and possibly other headers).
801 * To work around this if we've haven't parsed
802 * a full header we'll append a trailing \r\n
803 * and see if this now generates a valid one.
805 * This hack shouldn't have any impacts. If we've
806 * already transmitted the header or if this is a
807 * SSL connection, then we won't bother with this
808 * hack. So we only work on partially received
809 * headers. If we append a \r\n and this still
810 * doesn't generate a valid header, then we won't
811 * transmit anything to the client.
815 /* This hack must only be enforced for headers. */
816 if (server_body || http->ssl)
821 p = re_process_buffer(csp);
822 hdr = sed(server_patterns, add_server_headers, csp);
824 if ((write_socket(csp->cfd, hdr, n) != n)
825 || (write_socket(csp->cfd, p, csp->content_length) != csp->content_length))
827 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
833 #endif /* def PCRS */
834 break; /* "game over, man" */
837 /* Let's pretend the server just sent us a blank line. */
838 n = sprintf(buf, "\r\n");
841 * Now, let the normal header parsing algorithm below do its
842 * job. If it fails, we'll exit instead of continuing.
849 * If this is an SSL connection or we're in the body
850 * of the server document, just write it to the client.
853 if (server_body || http->ssl)
858 add_to_iob(csp, buf, n); /* Buffer the body for filtering */
861 #endif /* def PCRS */
864 if (write_socket(csp->cfd, buf, n) != n)
866 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
875 /* we're still looking for the end of the
876 * server's header ... (does that make header
877 * parsing an "out of body experience" ?
880 /* buffer up the data we just read */
881 add_to_iob(csp, buf, n);
883 /* get header lines from the iob */
885 while ((p = get_header(csp)))
889 /* see following note */
892 enlist(csp->headers, p);
896 /* NOTE: there are no "empty" headers so
897 * if the pointer `p' is not NULL we must
898 * assume that we reached the end of the
899 * buffer before we hit the end of the header.
906 /* Well, we tried our MS IIS/5
907 * hack and it didn't work.
908 * The header is incomplete
909 * and there isn't anything
910 * we can do about it.
916 /* Since we have to wait for
917 * more from the server before
918 * we can parse the headers
919 * we just continue here.
925 /* we have now received the entire header.
926 * filter it and send the result to the client
929 hdr = sed(server_patterns, add_server_headers, csp);
932 /* write the server's (modified) header to
933 * the client (along with anything else that
934 * may be in the buffer)
938 /* Start blocking popups if appropriate. */
940 if (csp->is_text && /* It's a text / * MIME-Type */
941 !http->ssl && /* We talk plaintext */
942 block_popups) /* Policy allows */
944 block_popups_now = 1;
947 #endif /* def KILLPOPUPS */
950 /* Start re_filtering this if appropriate. */
952 if (csp->is_text && /* It's a text / * MIME-Type */
953 !http->ssl && /* We talk plaintext */
954 pcrs_filter) /* Policy allows */
959 /* This next line is a little ugly, but it simplifies the if statement below. */
960 /* Basically if using PCRS, we want the OR condition to require "!filtering" */
961 #define NOT_FILTERING_AND !filtering &&
963 #else /* not def PCRS */
965 #define NOT_FILTERING_AND
967 #endif /* def PCRS */
969 if (NOT_FILTERING_AND ((write_socket(csp->cfd, hdr, n) != n)
970 || (n = flush_socket(csp->cfd, csp) < 0)))
972 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
974 /* the write failed, so don't bother
975 * mentioning it to the client...
976 * it probably can't hear us anyway.
982 NOT_FILTERING_AND (byte_count += n);
984 /* we're finished with the server's header */
989 /* If this was a MS IIS/5 hack then it means
990 * the server has already closed the
991 * connection. Nothing more to read. Time
1002 return; /* huh? we should never get here */
1005 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1006 csp->ip_addr_str, http->cmd, byte_count);
1010 /*********************************************************************
1014 * Description : This is little more than chat. We only "serve" to
1015 * to close any socket that chat may have opened.
1018 * 1 : csp = Current client state (buffers, headers, etc...)
1022 *********************************************************************/
1024 void serve(struct client_state *csp)
1025 #else /* ifndef AMIGA */
1026 static void serve(struct client_state *csp)
1027 #endif /* def AMIGA */
1030 close_socket(csp->cfd);
1034 close_socket(csp->sfd);
1044 /*********************************************************************
1046 * Function : server_thread
1048 * Description : We only exist to call `serve' in a threaded environment.
1051 * 1 : data = Current client state (buffers, headers, etc...)
1053 * Returns : Always 0.
1055 *********************************************************************/
1056 static int32 server_thread(void *data)
1058 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 */
1291 if (block_acl(NULL,csp))
1293 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1294 close_socket(csp->cfd);
1299 /* add it to the list of clients */
1300 csp->next = clients->next;
1301 clients->next = csp;
1303 if (config->multi_threaded)
1307 /* this is a switch () statment in the C preprocessor - ugh */
1308 #undef SELECTED_ONE_OPTION
1310 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1311 #define SELECTED_ONE_OPTION
1312 child_id = _beginthread(
1318 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1319 #define SELECTED_ONE_OPTION
1321 thread_id tid = spawn_thread
1322 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1324 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1326 child_id = (int) tid;
1335 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1336 #define SELECTED_ONE_OPTION
1337 csp->cfd = ReleaseSocket(csp->cfd, -1);
1338 if((child_id = (int)CreateNewProcTags(
1339 NP_Entry, (ULONG)server_thread,
1340 NP_Output, Output(),
1341 NP_CloseOutput, FALSE,
1342 NP_Name, (ULONG)"junkbuster child",
1343 NP_StackSize, 200*1024,
1347 ((struct Task *)child_id)->tc_UserData = csp;
1348 Signal((struct Task *)child_id, SIGF_SINGLE);
1353 #if !defined(SELECTED_ONE_OPTION)
1357 #undef SELECTED_ONE_OPTION
1358 /* end of cpp switch () */
1360 if (child_id < 0) /* failed */
1364 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1366 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1368 write_socket(csp->cfd, buf, strlen(buf));
1369 close_socket(csp->cfd);
1375 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1376 /* This block is only needed when using fork().
1377 * When using threads, the server thread was
1378 * created and run by the call to _beginthread().
1380 if (child_id == 0) /* child */
1388 /* in a fork()'d environment, the parent's
1389 * copy of the client socket and the CSP
1393 #if !defined(_WIN32) && defined(__CYGWIN__)
1395 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1396 close_socket(csp->cfd);
1399 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */