1 const char jcc_rcs[] = "$Id: jcc.c,v 1.13 2001/05/29 09:50:24 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.13 2001/05/29 09:50:24 jongfoster
37 * Unified blocklist/imagelist/permissionslist.
38 * File format is still under discussion, but the internal changes
41 * Also modified interceptor behaviour:
42 * - We now intercept all URLs beginning with one of the following
43 * prefixes (and *only* these prefixes):
45 * * http://ijbswa.sf.net/config/
46 * * http://ijbswa.sourceforge.net/config/
47 * - New interceptors "home page" - go to http://i.j.b/ to see it.
48 * - Internal changes so that intercepted and fast redirect pages
49 * are not replaced with an image.
50 * - Interceptors now have the option to send a binary page direct
51 * to the client. (i.e. ijb-send-banner uses this)
52 * - Implemented show-url-info interceptor. (Which is why I needed
53 * the above interceptors changes - a typical URL is
54 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
55 * The previous mechanism would not have intercepted that, and
56 * if it had been intercepted then it then it would have replaced
59 * Revision 1.12 2001/05/27 22:17:04 oes
61 * - re_process_buffer no longer writes the modified buffer
62 * to the client, which was very ugly. It now returns the
63 * buffer, which it is then written by chat.
65 * - content_length now adjusts the Content-Length: header
66 * for modified documents rather than crunch()ing it.
67 * (Length info in csp->content_length, which is 0 for
68 * unmodified documents)
70 * - For this to work, sed() is called twice when filtering.
72 * Revision 1.11 2001/05/26 17:27:53 jongfoster
73 * Added support for CLF and fixed LOG_LEVEL_LOG.
74 * Also did CRLF->LF fix of my previous patch.
76 * Revision 1.10 2001/05/26 15:26:15 jongfoster
77 * ACL feature now provides more security by immediately dropping
78 * connections from untrusted hosts.
80 * Revision 1.9 2001/05/26 00:28:36 jongfoster
81 * Automatic reloading of config file.
82 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
83 * Most of the global variables have been moved to a new
84 * struct configuration_spec, accessed through csp->config->globalname
85 * Most of the globals remaining are used by the Win32 GUI.
87 * Revision 1.8 2001/05/25 22:43:18 jongfoster
88 * Fixing minor memory leak and buffer overflow.
90 * Revision 1.7 2001/05/25 22:34:30 jongfoster
93 * Revision 1.6 2001/05/23 00:13:58 joergs
94 * AmigaOS support fixed.
96 * Revision 1.5 2001/05/22 18:46:04 oes
98 * - Enabled filtering banners by size rather than URL
99 * by adding patterns that replace all standard banner
100 * sizes with the "Junkbuster" gif to the re_filterfile
102 * - Enabled filtering WebBugs by providing a pattern
103 * which kills all 1x1 images
105 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
106 * which is selected by the (nonstandard and therefore
107 * capital) letter 'U' in the option string.
108 * It causes the quantifiers to be ungreedy by default.
109 * Appending a ? turns back to greedy (!).
111 * - Added a new interceptor ijb-send-banner, which
112 * sends back the "Junkbuster" gif. Without imagelist or
113 * MSIE detection support, or if tinygif = 1, or the
114 * URL isn't recognized as an imageurl, a lame HTML
115 * explanation is sent instead.
117 * - Added new feature, which permits blocking remote
118 * script redirects and firing back a local redirect
120 * The feature is conditionally compiled, i.e. it
121 * can be disabled with --disable-fast-redirects,
122 * plus it must be activated by a "fast-redirects"
123 * line in the config file, has its own log level
124 * and of course wants to be displayed by show-proxy-args
125 * Note: Boy, all the #ifdefs in 1001 locations and
126 * all the fumbling with configure.in and acconfig.h
127 * were *way* more work than the feature itself :-(
129 * - Because a generic redirect template was needed for
130 * this, tinygif = 3 now uses the same.
132 * - Moved GIFs, and other static HTTP response templates
137 * - Removed some >400 CRs again (Jon, you really worked
140 * Revision 1.4 2001/05/21 19:34:01 jongfoster
141 * Made failure to bind() a fatal error.
143 * Revision 1.3 2001/05/20 01:21:20 jongfoster
144 * Version 2.9.4 checkin.
145 * - Merged popupfile and cookiefile, and added control over PCRS
146 * filtering, in new "permissionsfile".
147 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
148 * file error you now get a message box (in the Win32 GUI) rather
149 * than the program exiting with no explanation.
150 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
152 * - Removed tabs from "config"
153 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
154 * - Bumped up version number.
156 * Revision 1.2 2001/05/17 22:34:44 oes
157 * - Added hint on GIF char array generation to jcc.c
158 * - Cleaned CRLF's from the sources and related files
159 * - Repaired logging for REF and FRC
161 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
162 * Initial import of version 2.9.3 source tree
165 *********************************************************************/
171 #include <sys/types.h>
180 # include <sys/timeb.h>
181 # include <windows.h>
183 # include <process.h>
186 # endif /* def TOGGLE */
189 # ifndef _WIN_CONSOLE
191 # endif /* ndef _WIN_CONSOLE */
193 #else /* ifndef _WIN32 */
196 # include <sys/time.h>
197 # include <sys/wait.h>
198 # include <sys/stat.h>
202 # include <socket.h> /* BeOS has select() for sockets only. */
203 # include <OS.h> /* declarations for threads and stuff. */
216 #include "showargs.h"
218 #include "killpopup.h"
219 #include "miscutil.h"
221 #include "jbsockets.h"
224 const char jcc_h_rcs[] = JCC_H_VERSION;
225 const char project_h_rcs[] = PROJECT_H_VERSION;
227 const char DEFAULT_USER_AGENT[] ="User-Agent: Mozilla (X11; I; Linux 2.0.32 i586)";
229 struct client_state clients[1];
230 struct file_list files[1];
233 int urls_read = 0; /* total nr of urls read inc rejected */
234 int urls_rejected = 0; /* total nr of urls rejected */
235 #endif /* def STATISTICS */
238 static void listen_loop(void);
239 static void chat(struct client_state *csp);
241 void serve(struct client_state *csp);
242 #else /* ifndef AMIGA */
243 static void serve(struct client_state *csp);
244 #endif /* def AMIGA */
247 static int32 server_thread(void *data);
248 #endif /* def __BEOS__ */
251 #define sleep(N) Sleep(((N) * 1000))
255 /*********************************************************************
259 * Description : Once a connection to the client has been accepted,
260 * this function is called (via serve()) to handle the
261 * main business of the communication. When this
262 * function returns, the caller must close the client
266 * 1 : csp = Current client state (buffers, headers, etc...)
268 * Returns : On success, the number of bytes written are returned (zero
269 * indicates nothing was written). On error, -1 is returned,
270 * and errno is set appropriately. If count is zero and the
271 * file descriptor refers to a regular file, 0 will be
272 * returned without causing any other effect. For a special
273 * file, the results are not portable.
275 *********************************************************************/
276 static void chat(struct client_state *csp)
279 * This next lines are a little ugly, but they simplifies the if statements below.
280 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
281 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
284 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
285 #else /* ifndef TOGGLE */
286 # define IS_TOGGLED_ON_AND
287 #endif /* ndef TOGGLE */
289 # define IS_NOT_FORCED_AND (!csp->force) &&
290 #else /* ifndef TOGGLE */
291 # define IS_NOT_FORCED_AND
292 #endif /* def FORCE_LOAD */
294 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
296 char buf[BUFSIZ], *hdr, *p, *req;
300 int n, maxfd, server_body;
301 int ms_iis5_hack = 0;
303 const struct gateway *gw;
304 struct http_request *http;
306 int block_popups; /* bool, 1==will block popups */
307 int block_popups_now = 0; /* bool, 1==currently blocking popups */
308 #endif /* def KILLPOPUPS */
310 int pcrs_filter; /* bool, 1==will filter through pcrs */
311 int filtering = 0; /* bool, 1==currently filtering through pcrs */
312 #endif /* def PCRS */
317 * Read the client's request. Note that since we're not using select() we
318 * could get blocked here if a client connected, then didn't say anything!
323 n = read_socket(csp->cfd, buf, sizeof(buf));
325 if (n <= 0) break; /* error! */
327 add_to_iob(csp, buf, n);
329 req = get_header(csp);
333 break; /* no HTTP request! */
338 continue; /* more to come! */
342 /* If this request contains the FORCE_PREFIX,
343 * better get rid of it now and set the force flag --oes
346 if (strstr(req, FORCE_PREFIX))
348 strclean(req, FORCE_PREFIX);
349 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
356 #endif /* def FORCE_LOAD */
358 parse_http_request(req, http, csp);
363 if (http->cmd == NULL)
365 strcpy(buf, CHEADER);
366 write_socket(csp->cfd, buf, strlen(buf));
368 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
373 /* decide how to route the HTTP request */
375 if ((gw = forward_url(http, csp)) == NULL)
377 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
378 /* Never get here - LOG_LEVEL_FATAL causes program exit */
381 /* build the http request to send to the server
382 * we have to do one of the following:
384 * create = use the original HTTP request to create a new
385 * HTTP request that has only the path component
386 * without the http://domainspec
387 * pass = pass the original HTTP request unchanged
389 * drop = drop the HTTP request
394 * +--------+--------+
396 * 0 | create | drop |
398 * Forwarding +--------+--------+
402 * +--------+--------+
406 if (gw->forward_host)
408 /* if forwarding, just pass the request as is */
409 enlist(csp->headers, http->cmd);
415 /* otherwise elide the host information from the url */
417 p = strsav(p, http->gpc);
419 p = strsav(p, http->path);
421 p = strsav(p, http->ver);
422 enlist(csp->headers, p);
427 /* decide what we're to do with cookies */
430 if (!csp->toggled_on)
432 /* Most compatible set of permissions */
433 csp->permissions = PERMIT_MOST_COMPATIBLE;
436 #endif /* ndef TOGGLE */
438 csp->permissions = url_permissions(http, csp);
442 block_popups = ((csp->permissions & PERMIT_POPUPS) == 0);
443 #endif /* def KILLPOPUPS */
445 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
446 ((csp->permissions & PERMIT_RE_FILTER) != 0);
447 #endif /* def PCRS */
450 /* grab the rest of the client's headers */
454 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
456 n = read_socket(csp->cfd, buf, sizeof(buf));
459 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
462 add_to_iob(csp, buf, n);
466 if (p == NULL) break;
468 enlist(csp->headers, p);
472 /* filter it as required */
474 hdr = sed(client_patterns, add_client_headers, csp);
476 destroy_list(csp->headers);
478 /* Check the request against all rules, unless
479 * we're toggled off or in force mode.
482 if (intercept_url(http, csp))
485 * The interceptor will write out the data.
486 * We don't need to do anything else
491 #endif /* def STATISTICS */
497 #ifdef FAST_REDIRECTS
498 else if (IS_ENABLED_AND
499 ((csp->permissions & PERMIT_FAST_REDIRECTS) != 0) &&
500 (p = redirect_url(http, csp)))
502 /* This must be blocked as HTML */
505 #endif /* def STATISTICS */
507 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
509 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
510 csp->ip_addr_str, http->cmd);
512 /* Send HTML redirection result */
513 write_socket(csp->cfd, p, strlen(p));
519 #endif /* def FAST_REDIRECTS */
521 else if (IS_ENABLED_AND (
523 (p = trust_url(http, csp)) ||
524 #endif /* def TRUST_FILES */
525 (p = block_url(http, csp)) ))
527 /* Block as HTML or image */
530 #endif /* def STATISTICS */
532 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
534 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 1",
535 csp->ip_addr_str, http->cmd);
537 #ifdef IMAGE_BLOCKING
538 /* Block as image? */
539 if ( (csp->config->tinygif > 0) && block_imageurl(http, csp) )
541 /* Send "blocked" image */
542 log_error(LOG_LEVEL_GPC, "%s%s image crunch!",
543 http->hostport, http->path);
545 if (csp->config->tinygif == 1)
547 write_socket(csp->cfd, BLANKGIF, sizeof(BLANKGIF)-1);
549 else if (csp->config->tinygif == 2)
551 write_socket(csp->cfd, JBGIF, sizeof(JBGIF)-1);
553 else if ((csp->config->tinygif == 3) && (csp->config->tinygifurl))
556 p = (char *)malloc(sizeof(HTTP_REDIRECT_TEMPLATE)
557 + strlen(csp->config->tinygifurl));
558 sprintf(p, HTTP_REDIRECT_TEMPLATE, csp->config->tinygifurl);
559 write_socket(csp->cfd, p, strlen(p));
563 /* Should never happen */
564 write_socket(csp->cfd, JBGIF, sizeof(JBGIF)-1);
568 #endif /* def IMAGE_BLOCKING */
571 /* Send HTML "blocked" message, interception, or redirection result */
572 write_socket(csp->cfd, p, strlen(p));
580 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
582 if (gw->forward_host)
584 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
585 gw->forward_host, gw->forward_port, http->hostport);
589 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
592 /* here we connect to the server, gateway, or the forwarder */
594 csp->sfd = (gw->conn)(gw, http, csp);
598 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
603 err = zalloc(strlen(CNXDOM) + strlen(http->host));
604 sprintf(err, CNXDOM, http->host);
606 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
607 csp->ip_addr_str, http->cmd);
611 eno = safe_strerror(errno);
612 err = zalloc(strlen(CFAIL) + strlen(http->hostport) + strlen(eno));
613 sprintf(err, CFAIL, http->hostport, eno);
615 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
616 csp->ip_addr_str, http->cmd);
619 write_socket(csp->cfd, err, strlen(err));
626 log_error(LOG_LEVEL_CONNECT, "OK");
628 if (gw->forward_host || (http->ssl == 0))
630 /* write the client's (modified) header to the server
631 * (along with anything else that may be in the buffer)
636 if ((write_socket(csp->sfd, hdr, n) != n)
637 || (flush_socket(csp->sfd, csp ) < 0))
639 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
642 eno = safe_strerror(errno);
643 err = zalloc(strlen(CFAIL) + strlen(http->hostport) + strlen(eno));
644 sprintf(err, CFAIL, http->hostport, eno);
645 write_socket(csp->cfd, err, strlen(err));
647 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
648 csp->ip_addr_str, http->cmd);
658 * We're running an SSL tunnel and we're not forwarding,
659 * so just send the "connect succeeded" message to the
660 * client, flush the rest, and get out of the way.
662 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
663 csp->ip_addr_str, http->cmd);
665 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
673 /* we're finished with the client's header */
676 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
678 /* pass data between the client and server
679 * until one or the other shuts down the connection.
688 FD_SET(csp->cfd, &rfds);
689 FD_SET(csp->sfd, &rfds);
691 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
695 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
699 /* this is the body of the browser's request
700 * just read it and write it.
703 if (FD_ISSET(csp->cfd, &rfds))
705 n = read_socket(csp->cfd, buf, sizeof(buf));
709 break; /* "game over, man" */
712 if (write_socket(csp->sfd, buf, n) != n)
714 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
721 * The server wants to talk. It could be the header or the body.
722 * If `hdr' is null, then it's the header otherwise it's the body.
723 * FIXME: Does `hdr' really mean `host'?
727 if (FD_ISSET(csp->sfd, &rfds))
730 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
734 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
736 eno = safe_strerror(errno);
737 sprintf(buf, CFAIL, http->hostport, eno);
740 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
741 csp->ip_addr_str, http->cmd);
743 write_socket(csp->cfd, buf, strlen(buf));
747 /* Add a trailing zero. This lets filter_popups
748 * use string operations.
753 /* Filter the popups on this read. */
754 if (block_popups_now)
756 filter_popups(buf, n);
758 #endif /* def KILLPOPUPS */
760 /* Normally, this would indicate that we've read
761 * as much as the server has sent us and we can
762 * close the client connection. However, Microsoft
763 * in its wisdom has released IIS/5 with a bug that
764 * prevents it from sending the trailing \r\n in
765 * a 302 redirect header (and possibly other headers).
766 * To work around this if we've haven't parsed
767 * a full header we'll append a trailing \r\n
768 * and see if this now generates a valid one.
770 * This hack shouldn't have any impacts. If we've
771 * already transmitted the header or if this is a
772 * SSL connection, then we won't bother with this
773 * hack. So we only work on partially received
774 * headers. If we append a \r\n and this still
775 * doesn't generate a valid header, then we won't
776 * transmit anything to the client.
780 /* This hack must only be enforced for headers. */
781 if (server_body || http->ssl)
786 p = re_process_buffer(csp);
787 hdr = sed(server_patterns, add_server_headers, csp);
789 if ((write_socket(csp->cfd, hdr, n) != n)
790 || (write_socket(csp->cfd, p, csp->content_length) != csp->content_length))
792 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
798 #endif /* def PCRS */
799 break; /* "game over, man" */
802 /* Let's pretend the server just sent us a blank line. */
803 n = sprintf(buf, "\r\n");
806 * Now, let the normal header parsing algorithm below do its
807 * job. If it fails, we'll exit instead of continuing.
814 * If this is an SSL connection or we're in the body
815 * of the server document, just write it to the client.
818 if (server_body || http->ssl)
823 add_to_iob(csp, buf, n); /* Buffer the body for filtering */
826 #endif /* def PCRS */
829 if (write_socket(csp->cfd, buf, n) != n)
831 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
840 /* we're still looking for the end of the
841 * server's header ... (does that make header
842 * parsing an "out of body experience" ?
845 /* buffer up the data we just read */
846 add_to_iob(csp, buf, n);
848 /* get header lines from the iob */
850 while ((p = get_header(csp)))
854 /* see following note */
857 enlist(csp->headers, p);
861 /* NOTE: there are no "empty" headers so
862 * if the pointer `p' is not NULL we must
863 * assume that we reached the end of the
864 * buffer before we hit the end of the header.
871 /* Well, we tried our MS IIS/5
872 * hack and it didn't work.
873 * The header is incomplete
874 * and there isn't anything
875 * we can do about it.
881 /* Since we have to wait for
882 * more from the server before
883 * we can parse the headers
884 * we just continue here.
890 /* we have now received the entire header.
891 * filter it and send the result to the client
894 hdr = sed(server_patterns, add_server_headers, csp);
897 /* write the server's (modified) header to
898 * the client (along with anything else that
899 * may be in the buffer)
903 /* Start blocking popups if appropriate. */
905 if (csp->is_text && /* It's a text / * MIME-Type */
906 !http->ssl && /* We talk plaintext */
907 block_popups) /* Policy allows */
909 block_popups_now = 1;
912 #endif /* def KILLPOPUPS */
915 /* Start re_filtering this if appropriate. */
917 if (csp->is_text && /* It's a text / * MIME-Type */
918 !http->ssl && /* We talk plaintext */
919 pcrs_filter) /* Policy allows */
924 /* This next line is a little ugly, but it simplifies the if statement below. */
925 /* Basically if using PCRS, we want the OR condition to require "!filtering" */
926 #define NOT_FILTERING_AND !filtering &&
928 #else /* not def PCRS */
930 #define NOT_FILTERING_AND
932 #endif /* def PCRS */
934 if (NOT_FILTERING_AND ((write_socket(csp->cfd, hdr, n) != n)
935 || (n = flush_socket(csp->cfd, csp) < 0)))
937 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
939 /* the write failed, so don't bother
940 * mentioning it to the client...
941 * it probably can't hear us anyway.
947 NOT_FILTERING_AND (byte_count += n);
949 /* we're finished with the server's header */
954 /* If this was a MS IIS/5 hack then it means
955 * the server has already closed the
956 * connection. Nothing more to read. Time
967 return; /* huh? we should never get here */
970 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
971 csp->ip_addr_str, http->cmd, byte_count);
975 /*********************************************************************
979 * Description : This is little more than chat. We only "serve" to
980 * to close any socket that chat may have opened.
983 * 1 : csp = Current client state (buffers, headers, etc...)
987 *********************************************************************/
989 void serve(struct client_state *csp)
990 #else /* ifndef AMIGA */
991 static void serve(struct client_state *csp)
992 #endif /* def AMIGA */
995 close_socket(csp->cfd);
999 close_socket(csp->sfd);
1009 /*********************************************************************
1011 * Function : server_thread
1013 * Description : We only exist to call `serve' in a threaded environment.
1016 * 1 : data = Current client state (buffers, headers, etc...)
1018 * Returns : Always 0.
1020 *********************************************************************/
1021 static int32 server_thread(void *data)
1023 serve((struct client_state *) data);
1031 /*********************************************************************
1035 * Description : Load the config file and start the listen loop.
1036 * This function is a lot more *sane* with the `load_config'
1037 * and `listen_loop' functions; although it stills does
1038 * a *little* too much for my taste.
1041 * 1 : argc = Number of parameters (including $0).
1042 * 2 : argv = Array of (char *)'s to the parameters.
1044 * Returns : 1 if : can't open config file, unrecognized directive,
1045 * stats requested in multi-thread mode, can't open the
1046 * log file, can't open the jar file, listen port is invalid,
1047 * any load fails, and can't bind port.
1049 * Else main never returns, the process must be signaled
1050 * to terminate execution. Or, on Windows, use the
1051 * "File", "Exit" menu option.
1053 *********************************************************************/
1055 int _main(int argc, const char *argv[])
1057 int main(int argc, const char *argv[])
1062 "AmiTCP:db/junkbuster/config"
1063 #elif !defined(_WIN32)
1070 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1071 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1073 printf("JunkBuster proxy version " VERSION ".\n\n"
1074 "Usage: %s [configfile]\n\n"
1075 "See " HOME_PAGE_URL " for details.\n"
1076 "This program is distributed under the GNU GPL, version 2 or later.\n",
1080 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1082 printf(VERSION "\n");
1085 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1092 configfile = argv[1];
1099 #elif defined(_WIN32)
1105 signal(SIGPIPE, SIG_IGN);
1106 signal(SIGCHLD, SIG_IGN);
1108 #else /* ifdef _WIN32 */
1109 # ifdef _WIN_CONSOLE
1111 * We *are* in a windows console app.
1112 * Print a verbose messages about FAQ's and such
1114 printf(win32_blurb);
1115 # endif /* def _WIN_CONSOLE */
1116 #endif /* def _WIN32 */
1127 /*********************************************************************
1129 * Function : listen_loop
1131 * Description : bind the listen port and enter a "FOREVER" listening loop.
1137 *********************************************************************/
1138 static void listen_loop(void)
1140 struct client_state *csp = NULL;
1142 struct configuration_spec * config;
1144 config = load_config();
1146 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1147 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1149 bfd = bind_port(config->haddr, config->hport);
1153 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1154 "- There may be another junkbuster or some other "
1155 "proxy running on port %d",
1156 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1157 config->hport, config->hport
1159 /* shouldn't get here */
1163 config->need_bind = 0;
1168 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1169 while (waitpid(-1, NULL, WNOHANG) > 0)
1171 /* zombie children */
1173 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1176 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1178 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1182 memset(csp, '\0', sizeof(*csp));
1187 csp->config = config = load_config();
1189 if ( config->need_bind )
1192 * Since we were listening to the "old port", we will not see
1193 * a "listen" param change until the next IJB request. So, at
1194 * least 1 more request must be made for us to find the new
1195 * setting. I am simply closing the old socket and binding the
1198 * Which-ever is correct, we will serve 1 more page via the
1199 * old settings. This should probably be a "show-proxy-args"
1200 * request. This should not be a so common of an operation
1201 * that this will hurt people's feelings.
1206 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1207 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1208 bfd = bind_port(config->haddr, config->hport);
1212 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1213 "- There may be another junkbuster or some other "
1214 "proxy running on port %d",
1215 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1216 config->hport, config->hport
1218 /* shouldn't get here */
1222 config->need_bind = 0;
1225 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1227 if (!accept_connection(csp, bfd))
1229 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1242 log_error(LOG_LEVEL_CONNECT, "OK");
1246 /* by haroon - most of credit to srt19170 */
1247 csp->toggled_on = g_bToggleIJB;
1250 if (run_loader(csp))
1252 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1253 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1256 if (block_acl(NULL,csp))
1258 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1259 close_socket(csp->cfd);
1264 /* add it to the list of clients */
1265 csp->next = clients->next;
1266 clients->next = csp;
1268 if (config->multi_threaded)
1272 /* this is a switch () statment in the C preprocessor - ugh */
1273 #undef SELECTED_ONE_OPTION
1275 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1276 #define SELECTED_ONE_OPTION
1277 child_id = _beginthread(
1283 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1284 #define SELECTED_ONE_OPTION
1286 thread_id tid = spawn_thread
1287 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1289 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1291 child_id = (int) tid;
1300 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1301 #define SELECTED_ONE_OPTION
1302 csp->cfd = ReleaseSocket(csp->cfd, -1);
1303 if((child_id = (int)CreateNewProcTags(
1304 NP_Entry, (ULONG)server_thread,
1305 NP_Output, Output(),
1306 NP_CloseOutput, FALSE,
1307 NP_Name, (ULONG)"junkbuster child",
1308 NP_StackSize, 200*1024,
1312 ((struct Task *)child_id)->tc_UserData = csp;
1313 Signal((struct Task *)child_id, SIGF_SINGLE);
1318 #if !defined(SELECTED_ONE_OPTION)
1322 #undef SELECTED_ONE_OPTION
1323 /* end of cpp switch () */
1325 if (child_id < 0) /* failed */
1329 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1331 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1333 write_socket(csp->cfd, buf, strlen(buf));
1334 close_socket(csp->cfd);
1340 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1341 /* This block is only needed when using fork().
1342 * When using threads, the server thread was
1343 * created and run by the call to _beginthread().
1345 if (child_id == 0) /* child */
1353 /* in a fork()'d environment, the parent's
1354 * copy of the client socket and the CSP
1358 #if !defined(_WIN32) && defined(__CYGWIN__)
1360 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1361 close_socket(csp->cfd);
1364 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */