1 const char jcc_rcs[] = "$Id: jcc.c,v 1.19 2001/06/07 23:12:52 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.19 2001/06/07 23:12:52 jongfoster
37 * Replacing function pointer in struct gateway with a directly
38 * called function forwarded_connect().
39 * Replacing struct gateway with struct forward_spec
41 * Revision 1.18 2001/06/03 19:12:16 oes
42 * introduced new cgi handling
44 * Revision 1.18 2001/06/03 11:03:48 oes
51 * adapted to new enlist_unique arg format
55 * introduced confdir option
57 * filters.c filtrers.h
59 * extracted-CGI relevant stuff
67 * support for new cgi mechansim
71 * functions for new list type: "map"
72 * extended enlist_unique
79 * deleted const struct interceptors
87 * added struct http_response
88 * changes struct interceptors to struct cgi_dispatcher
89 * moved HTML stuff to cgi.h
98 * Revision 1.17 2001/06/01 20:07:23 jongfoster
99 * Now uses action +image-blocker{} rather than config->tinygif
101 * Revision 1.16 2001/06/01 18:49:17 jongfoster
102 * Replaced "list_share" with "list" - the tiny memory gain was not
103 * worth the extra complexity.
105 * Revision 1.15 2001/05/31 21:24:47 jongfoster
106 * Changed "permission" to "action" throughout.
107 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
108 * Moved vanilla wafer check into chat(), since we must now
109 * decide whether or not to add it based on the URL.
111 * Revision 1.14 2001/05/29 20:14:01 joergs
112 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
115 * Revision 1.13 2001/05/29 09:50:24 jongfoster
116 * Unified blocklist/imagelist/permissionslist.
117 * File format is still under discussion, but the internal changes
120 * Also modified interceptor behaviour:
121 * - We now intercept all URLs beginning with one of the following
122 * prefixes (and *only* these prefixes):
124 * * http://ijbswa.sf.net/config/
125 * * http://ijbswa.sourceforge.net/config/
126 * - New interceptors "home page" - go to http://i.j.b/ to see it.
127 * - Internal changes so that intercepted and fast redirect pages
128 * are not replaced with an image.
129 * - Interceptors now have the option to send a binary page direct
130 * to the client. (i.e. ijb-send-banner uses this)
131 * - Implemented show-url-info interceptor. (Which is why I needed
132 * the above interceptors changes - a typical URL is
133 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
134 * The previous mechanism would not have intercepted that, and
135 * if it had been intercepted then it then it would have replaced
138 * Revision 1.12 2001/05/27 22:17:04 oes
140 * - re_process_buffer no longer writes the modified buffer
141 * to the client, which was very ugly. It now returns the
142 * buffer, which it is then written by chat.
144 * - content_length now adjusts the Content-Length: header
145 * for modified documents rather than crunch()ing it.
146 * (Length info in csp->content_length, which is 0 for
147 * unmodified documents)
149 * - For this to work, sed() is called twice when filtering.
151 * Revision 1.11 2001/05/26 17:27:53 jongfoster
152 * Added support for CLF and fixed LOG_LEVEL_LOG.
153 * Also did CRLF->LF fix of my previous patch.
155 * Revision 1.10 2001/05/26 15:26:15 jongfoster
156 * ACL feature now provides more security by immediately dropping
157 * connections from untrusted hosts.
159 * Revision 1.9 2001/05/26 00:28:36 jongfoster
160 * Automatic reloading of config file.
161 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
162 * Most of the global variables have been moved to a new
163 * struct configuration_spec, accessed through csp->config->globalname
164 * Most of the globals remaining are used by the Win32 GUI.
166 * Revision 1.8 2001/05/25 22:43:18 jongfoster
167 * Fixing minor memory leak and buffer overflow.
169 * Revision 1.7 2001/05/25 22:34:30 jongfoster
172 * Revision 1.6 2001/05/23 00:13:58 joergs
173 * AmigaOS support fixed.
175 * Revision 1.5 2001/05/22 18:46:04 oes
177 * - Enabled filtering banners by size rather than URL
178 * by adding patterns that replace all standard banner
179 * sizes with the "Junkbuster" gif to the re_filterfile
181 * - Enabled filtering WebBugs by providing a pattern
182 * which kills all 1x1 images
184 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
185 * which is selected by the (nonstandard and therefore
186 * capital) letter 'U' in the option string.
187 * It causes the quantifiers to be ungreedy by default.
188 * Appending a ? turns back to greedy (!).
190 * - Added a new interceptor ijb-send-banner, which
191 * sends back the "Junkbuster" gif. Without imagelist or
192 * MSIE detection support, or if tinygif = 1, or the
193 * URL isn't recognized as an imageurl, a lame HTML
194 * explanation is sent instead.
196 * - Added new feature, which permits blocking remote
197 * script redirects and firing back a local redirect
199 * The feature is conditionally compiled, i.e. it
200 * can be disabled with --disable-fast-redirects,
201 * plus it must be activated by a "fast-redirects"
202 * line in the config file, has its own log level
203 * and of course wants to be displayed by show-proxy-args
204 * Note: Boy, all the #ifdefs in 1001 locations and
205 * all the fumbling with configure.in and acconfig.h
206 * were *way* more work than the feature itself :-(
208 * - Because a generic redirect template was needed for
209 * this, tinygif = 3 now uses the same.
211 * - Moved GIFs, and other static HTTP response templates
216 * - Removed some >400 CRs again (Jon, you really worked
219 * Revision 1.4 2001/05/21 19:34:01 jongfoster
220 * Made failure to bind() a fatal error.
222 * Revision 1.3 2001/05/20 01:21:20 jongfoster
223 * Version 2.9.4 checkin.
224 * - Merged popupfile and cookiefile, and added control over PCRS
225 * filtering, in new "permissionsfile".
226 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
227 * file error you now get a message box (in the Win32 GUI) rather
228 * than the program exiting with no explanation.
229 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
231 * - Removed tabs from "config"
232 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
233 * - Bumped up version number.
235 * Revision 1.2 2001/05/17 22:34:44 oes
236 * - Added hint on GIF char array generation to jcc.c
237 * - Cleaned CRLF's from the sources and related files
238 * - Repaired logging for REF and FRC
240 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
241 * Initial import of version 2.9.3 source tree
244 *********************************************************************/
250 #include <sys/types.h>
259 # include <sys/timeb.h>
260 # include <windows.h>
262 # include <process.h>
265 # endif /* def TOGGLE */
268 # ifndef _WIN_CONSOLE
270 # endif /* ndef _WIN_CONSOLE */
272 #else /* ifndef _WIN32 */
275 # include <sys/time.h>
276 # include <sys/wait.h>
277 # include <sys/stat.h>
281 # include <socket.h> /* BeOS has select() for sockets only. */
282 # include <OS.h> /* declarations for threads and stuff. */
296 #include "showargs.h"
298 #include "killpopup.h"
299 #include "miscutil.h"
301 #include "jbsockets.h"
306 const char jcc_h_rcs[] = JCC_H_VERSION;
307 const char project_h_rcs[] = PROJECT_H_VERSION;
309 struct client_state clients[1];
310 struct file_list files[1];
313 int urls_read = 0; /* total nr of urls read inc rejected */
314 int urls_rejected = 0; /* total nr of urls rejected */
315 #endif /* def STATISTICS */
318 static void listen_loop(void);
319 static void chat(struct client_state *csp);
321 void serve(struct client_state *csp);
322 #else /* ifndef AMIGA */
323 static void serve(struct client_state *csp);
324 #endif /* def AMIGA */
327 static int32 server_thread(void *data);
328 #endif /* def __BEOS__ */
331 #define sleep(N) Sleep(((N) * 1000))
335 /* The vanilla wafer. */
336 static const char VANILLA_WAFER[] =
337 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
338 "Do_not_send_me_any_copyrighted_information_other_than_the_"
339 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
340 "In_particular_do_not_send_me_any_cookies_that_"
341 "are_subject_to_a_claim_of_copyright_by_anybody._"
342 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
343 "(copyright_or_otherwise)_applying_to_any_cookie._";
346 /*********************************************************************
350 * Description : Once a connection to the client has been accepted,
351 * this function is called (via serve()) to handle the
352 * main business of the communication. When this
353 * function returns, the caller must close the client
357 * 1 : csp = Current client state (buffers, headers, etc...)
359 * Returns : On success, the number of bytes written are returned (zero
360 * indicates nothing was written). On error, -1 is returned,
361 * and errno is set appropriately. If count is zero and the
362 * file descriptor refers to a regular file, 0 will be
363 * returned without causing any other effect. For a special
364 * file, the results are not portable.
366 *********************************************************************/
367 static void chat(struct client_state *csp)
370 * This next lines are a little ugly, but they simplifies the if statements below.
371 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
372 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
375 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
376 #else /* ifndef TOGGLE */
377 # define IS_TOGGLED_ON_AND
378 #endif /* ndef TOGGLE */
380 # define IS_NOT_FORCED_AND (!csp->force) &&
381 #else /* ifndef FORCE_LOAD */
382 # define IS_NOT_FORCED_AND
383 #endif /* def FORCE_LOAD */
385 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
387 char buf[BUFFER_SIZE];
\r
392 int n, maxfd, server_body;
393 int ms_iis5_hack = 0;
395 const struct forward_spec * fwd;
396 struct http_request *http;
398 int block_popups; /* bool, 1==will block popups */
399 int block_popups_now = 0; /* bool, 1==currently blocking popups */
400 #endif /* def KILLPOPUPS */
402 int pcrs_filter; /* bool, 1==will filter through pcrs */
403 int filtering = 0; /* bool, 1==currently filtering through pcrs */
404 #endif /* def PCRS */
405 struct http_response *rsp;
410 * Read the client's request. Note that since we're not using select() we
411 * could get blocked here if a client connected, then didn't say anything!
416 n = read_socket(csp->cfd, buf, sizeof(buf));
418 if (n <= 0) break; /* error! */
420 add_to_iob(csp, buf, n);
422 req = get_header(csp);
426 break; /* no HTTP request! */
431 continue; /* more to come! */
435 /* If this request contains the FORCE_PREFIX,
436 * better get rid of it now and set the force flag --oes
439 if (strstr(req, FORCE_PREFIX))
441 strclean(req, FORCE_PREFIX);
442 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
449 #endif /* def FORCE_LOAD */
451 parse_http_request(req, http, csp);
456 if (http->cmd == NULL)
458 strcpy(buf, CHEADER);
459 write_socket(csp->cfd, buf, strlen(buf));
461 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
466 /* decide how to route the HTTP request */
468 if ((fwd = forward_url(http, csp)) == NULL)
470 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
471 /* Never get here - LOG_LEVEL_FATAL causes program exit */
474 /* build the http request to send to the server
475 * we have to do one of the following:
477 * create = use the original HTTP request to create a new
478 * HTTP request that has only the path component
479 * without the http://domainspec
480 * pass = pass the original HTTP request unchanged
482 * drop = drop the HTTP request
487 * +--------+--------+
489 * 0 | create | drop |
491 * Forwarding +--------+--------+
495 * +--------+--------+
499 if (fwd->forward_host)
501 /* if forwarding, just pass the request as is */
502 enlist(csp->headers, http->cmd);
508 /* otherwise elide the host information from the url */
510 p = strsav(p, http->gpc);
512 p = strsav(p, http->path);
514 p = strsav(p, http->ver);
515 enlist(csp->headers, p);
520 /* decide what we're to do with cookies */
523 if (!csp->toggled_on)
525 /* Most compatible set of actions (i.e. none) */
526 init_current_action(csp->action);
529 #endif /* ndef TOGGLE */
531 url_actions(http, csp);
536 * If we're logging cookies in a cookie jar, and the user has not
537 * supplied any wafers, and the user has not told us to suppress the
538 * vanilla wafer, then send the vanilla wafer.
540 if ((csp->config->jarfile != NULL)
541 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
542 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
544 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
546 #endif /* def JAR_FILES */
549 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
550 #endif /* def KILLPOPUPS */
552 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
553 ((csp->action->flags & ACTION_FILTER) != 0);
554 #endif /* def PCRS */
557 /* grab the rest of the client's headers */
561 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
563 n = read_socket(csp->cfd, buf, sizeof(buf));
566 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
569 add_to_iob(csp, buf, n);
573 if (p == NULL) break;
575 enlist(csp->headers, p);
579 /* filter it as required */
581 hdr = sed(client_patterns, add_client_headers, csp);
583 destroy_list(csp->headers);
585 /* Check the request against all rules, unless
586 * we're toggled off or in force mode.
589 if (NULL != (rsp = cgi_dispatch(csp)))
591 if(0 != (n = make_http_response(rsp)))
593 if ((write_socket(csp->cfd, rsp->head, n) != n)
594 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
596 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
603 #endif /* def STATISTICS */
605 free_http_response(rsp);
610 #ifdef FAST_REDIRECTS
611 else if (IS_ENABLED_AND
612 ((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
613 (p = redirect_url(http, csp)))
615 /* This must be blocked as HTML */
618 #endif /* def STATISTICS */
620 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
622 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
623 csp->ip_addr_str, http->cmd);
625 /* Send HTML redirection result */
626 write_socket(csp->cfd, p, strlen(p));
632 #endif /* def FAST_REDIRECTS */
634 else if (IS_ENABLED_AND (
636 (p = trust_url(http, csp)) ||
637 #endif /* def TRUST_FILES */
638 (p = block_url(http, csp)) ))
640 /* Block as HTML or image */
643 #endif /* def STATISTICS */
645 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
647 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 1",
648 csp->ip_addr_str, http->cmd);
650 #ifdef IMAGE_BLOCKING
651 /* Block as image? */
652 if ( ((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
653 && block_imageurl(http, csp) )
655 /* Send "blocked" image */
656 const char * blocker = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
658 log_error(LOG_LEVEL_GPC, "%s%s image crunch! --> %s",
659 http->hostport, http->path, (blocker ? blocker : "logo"));
661 if ((blocker == NULL) || (0 == strcmpic(blocker, "logo")))
663 write_socket(csp->cfd, JBGIF, sizeof(JBGIF)-1);
665 else if (0 == strcmpic(blocker, "blank"))
667 write_socket(csp->cfd, BLANKGIF, sizeof(BLANKGIF)-1);
672 p = (char *)malloc(sizeof(HTTP_REDIRECT_TEMPLATE) + strlen(blocker));
673 sprintf(p, HTTP_REDIRECT_TEMPLATE, blocker);
674 write_socket(csp->cfd, p, strlen(p));
678 #endif /* def IMAGE_BLOCKING */
681 /* Send HTML "blocked" message */
682 write_socket(csp->cfd, p, strlen(p));
690 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
692 if (fwd->forward_host)
694 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
695 fwd->forward_host, fwd->forward_port, http->hostport);
699 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
702 /* here we connect to the server, gateway, or the forwarder */
704 csp->sfd = forwarded_connect(fwd, http, csp);
708 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
713 err = zalloc(strlen(CNXDOM) + strlen(http->host));
714 sprintf(err, CNXDOM, http->host);
716 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
717 csp->ip_addr_str, http->cmd);
721 eno = safe_strerror(errno);
722 err = zalloc(strlen(CFAIL) + strlen(http->hostport) + strlen(eno));
723 sprintf(err, CFAIL, http->hostport, eno);
725 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
726 csp->ip_addr_str, http->cmd);
729 write_socket(csp->cfd, err, strlen(err));
736 log_error(LOG_LEVEL_CONNECT, "OK");
738 if (fwd->forward_host || (http->ssl == 0))
740 /* write the client's (modified) header to the server
741 * (along with anything else that may be in the buffer)
746 if ((write_socket(csp->sfd, hdr, n) != n)
747 || (flush_socket(csp->sfd, csp ) < 0))
749 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
752 eno = safe_strerror(errno);
753 err = zalloc(strlen(CFAIL) + strlen(http->hostport) + strlen(eno));
754 sprintf(err, CFAIL, http->hostport, eno);
755 write_socket(csp->cfd, err, strlen(err));
757 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
758 csp->ip_addr_str, http->cmd);
768 * We're running an SSL tunnel and we're not forwarding,
769 * so just send the "connect succeeded" message to the
770 * client, flush the rest, and get out of the way.
772 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
773 csp->ip_addr_str, http->cmd);
775 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
783 /* we're finished with the client's header */
786 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
788 /* pass data between the client and server
789 * until one or the other shuts down the connection.
798 FD_SET(csp->cfd, &rfds);
799 FD_SET(csp->sfd, &rfds);
801 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
805 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
809 /* this is the body of the browser's request
810 * just read it and write it.
813 if (FD_ISSET(csp->cfd, &rfds))
815 n = read_socket(csp->cfd, buf, sizeof(buf));
819 break; /* "game over, man" */
822 if (write_socket(csp->sfd, buf, n) != n)
824 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
831 * The server wants to talk. It could be the header or the body.
832 * If `hdr' is null, then it's the header otherwise it's the body.
833 * FIXME: Does `hdr' really mean `host'?
837 if (FD_ISSET(csp->sfd, &rfds))
840 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
844 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
846 eno = safe_strerror(errno);
847 sprintf(buf, CFAIL, http->hostport, eno);
850 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
851 csp->ip_addr_str, http->cmd);
853 write_socket(csp->cfd, buf, strlen(buf));
857 /* Add a trailing zero. This lets filter_popups
858 * use string operations.
863 /* Filter the popups on this read. */
864 if (block_popups_now)
866 filter_popups(buf, n);
868 #endif /* def KILLPOPUPS */
870 /* Normally, this would indicate that we've read
871 * as much as the server has sent us and we can
872 * close the client connection. However, Microsoft
873 * in its wisdom has released IIS/5 with a bug that
874 * prevents it from sending the trailing \r\n in
875 * a 302 redirect header (and possibly other headers).
876 * To work around this if we've haven't parsed
877 * a full header we'll append a trailing \r\n
878 * and see if this now generates a valid one.
880 * This hack shouldn't have any impacts. If we've
881 * already transmitted the header or if this is a
882 * SSL connection, then we won't bother with this
883 * hack. So we only work on partially received
884 * headers. If we append a \r\n and this still
885 * doesn't generate a valid header, then we won't
886 * transmit anything to the client.
890 /* This hack must only be enforced for headers. */
891 if (server_body || http->ssl)
896 p = re_process_buffer(csp);
897 hdr = sed(server_patterns, add_server_headers, csp);
899 if ((write_socket(csp->cfd, hdr, n) != n)
900 || (write_socket(csp->cfd, p, csp->content_length) != csp->content_length))
902 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
908 #endif /* def PCRS */
909 break; /* "game over, man" */
912 /* Let's pretend the server just sent us a blank line. */
913 n = sprintf(buf, "\r\n");
916 * Now, let the normal header parsing algorithm below do its
917 * job. If it fails, we'll exit instead of continuing.
924 * If this is an SSL connection or we're in the body
925 * of the server document, just write it to the client.
928 if (server_body || http->ssl)
933 add_to_iob(csp, buf, n); /* Buffer the body for filtering */
936 #endif /* def PCRS */
939 if (write_socket(csp->cfd, buf, n) != n)
941 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
950 /* we're still looking for the end of the
951 * server's header ... (does that make header
952 * parsing an "out of body experience" ?
955 /* buffer up the data we just read */
956 add_to_iob(csp, buf, n);
958 /* get header lines from the iob */
960 while ((p = get_header(csp)))
964 /* see following note */
967 enlist(csp->headers, p);
971 /* NOTE: there are no "empty" headers so
972 * if the pointer `p' is not NULL we must
973 * assume that we reached the end of the
974 * buffer before we hit the end of the header.
981 /* Well, we tried our MS IIS/5
982 * hack and it didn't work.
983 * The header is incomplete
984 * and there isn't anything
985 * we can do about it.
991 /* Since we have to wait for
992 * more from the server before
993 * we can parse the headers
994 * we just continue here.
1000 /* we have now received the entire header.
1001 * filter it and send the result to the client
1004 hdr = sed(server_patterns, add_server_headers, csp);
1007 /* write the server's (modified) header to
1008 * the client (along with anything else that
1009 * may be in the buffer)
1013 /* Start blocking popups if appropriate. */
1015 if (csp->is_text && /* It's a text / * MIME-Type */
1016 !http->ssl && /* We talk plaintext */
1017 block_popups) /* Policy allows */
1019 block_popups_now = 1;
1022 #endif /* def KILLPOPUPS */
1025 /* Start re_filtering this if appropriate. */
1027 if (csp->is_text && /* It's a text / * MIME-Type */
1028 !http->ssl && /* We talk plaintext */
1029 pcrs_filter) /* Policy allows */
1034 /* This next line is a little ugly, but it simplifies the if statement below. */
1035 /* Basically if using PCRS, we want the OR condition to require "!filtering" */
1036 #define NOT_FILTERING_AND !filtering &&
1038 #else /* not def PCRS */
1040 #define NOT_FILTERING_AND
1042 #endif /* def PCRS */
1044 if (NOT_FILTERING_AND ((write_socket(csp->cfd, hdr, n) != n)
1045 || (n = flush_socket(csp->cfd, csp) < 0)))
1047 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1049 /* the write failed, so don't bother
1050 * mentioning it to the client...
1051 * it probably can't hear us anyway.
1057 NOT_FILTERING_AND (byte_count += n);
1059 /* we're finished with the server's header */
1064 /* If this was a MS IIS/5 hack then it means
1065 * the server has already closed the
1066 * connection. Nothing more to read. Time
1077 return; /* huh? we should never get here */
1080 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1081 csp->ip_addr_str, http->cmd, byte_count);
1085 /*********************************************************************
1089 * Description : This is little more than chat. We only "serve" to
1090 * to close any socket that chat may have opened.
1093 * 1 : csp = Current client state (buffers, headers, etc...)
1097 *********************************************************************/
1099 void serve(struct client_state *csp)
1100 #else /* ifndef AMIGA */
1101 static void serve(struct client_state *csp)
1102 #endif /* def AMIGA */
1105 close_socket(csp->cfd);
1109 close_socket(csp->sfd);
1119 /*********************************************************************
1121 * Function : server_thread
1123 * Description : We only exist to call `serve' in a threaded environment.
1126 * 1 : data = Current client state (buffers, headers, etc...)
1128 * Returns : Always 0.
1130 *********************************************************************/
1131 static int32 server_thread(void *data)
1133 serve((struct client_state *) data);
1141 /*********************************************************************
1145 * Description : Load the config file and start the listen loop.
1146 * This function is a lot more *sane* with the `load_config'
1147 * and `listen_loop' functions; although it stills does
1148 * a *little* too much for my taste.
1151 * 1 : argc = Number of parameters (including $0).
1152 * 2 : argv = Array of (char *)'s to the parameters.
1154 * Returns : 1 if : can't open config file, unrecognized directive,
1155 * stats requested in multi-thread mode, can't open the
1156 * log file, can't open the jar file, listen port is invalid,
1157 * any load fails, and can't bind port.
1159 * Else main never returns, the process must be signaled
1160 * to terminate execution. Or, on Windows, use the
1161 * "File", "Exit" menu option.
1163 *********************************************************************/
1165 int _main(int argc, const char *argv[])
1167 int main(int argc, const char *argv[])
1172 "AmiTCP:db/junkbuster/config"
1173 #elif !defined(_WIN32)
1180 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1181 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1183 printf("JunkBuster proxy version " VERSION ".\n\n"
1184 "Usage: %s [configfile]\n\n"
1185 "See " HOME_PAGE_URL " for details.\n"
1186 "This program is distributed under the GNU GPL, version 2 or later.\n",
1190 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1192 printf(VERSION "\n");
1195 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1202 configfile = argv[1];
1209 #elif defined(_WIN32)
1215 signal(SIGPIPE, SIG_IGN);
1216 signal(SIGCHLD, SIG_IGN);
1218 #else /* ifdef _WIN32 */
1219 # ifdef _WIN_CONSOLE
1221 * We *are* in a windows console app.
1222 * Print a verbose messages about FAQ's and such
1224 printf(win32_blurb);
1225 # endif /* def _WIN_CONSOLE */
1226 #endif /* def _WIN32 */
1237 /*********************************************************************
1239 * Function : listen_loop
1241 * Description : bind the listen port and enter a "FOREVER" listening loop.
1247 *********************************************************************/
1248 static void listen_loop(void)
1250 struct client_state *csp = NULL;
1252 struct configuration_spec * config;
1254 config = load_config();
1256 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1257 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1259 bfd = bind_port(config->haddr, config->hport);
1263 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1264 "- There may be another junkbuster or some other "
1265 "proxy running on port %d",
1266 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1267 config->hport, config->hport
1269 /* shouldn't get here */
1273 config->need_bind = 0;
1278 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1279 while (waitpid(-1, NULL, WNOHANG) > 0)
1281 /* zombie children */
1283 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1286 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1288 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1292 memset(csp, '\0', sizeof(*csp));
1297 csp->config = config = load_config();
1299 if ( config->need_bind )
1302 * Since we were listening to the "old port", we will not see
1303 * a "listen" param change until the next IJB request. So, at
1304 * least 1 more request must be made for us to find the new
1305 * setting. I am simply closing the old socket and binding the
1308 * Which-ever is correct, we will serve 1 more page via the
1309 * old settings. This should probably be a "show-proxy-args"
1310 * request. This should not be a so common of an operation
1311 * that this will hurt people's feelings.
1316 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1317 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1318 bfd = bind_port(config->haddr, config->hport);
1322 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1323 "- There may be another junkbuster or some other "
1324 "proxy running on port %d",
1325 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1326 config->hport, config->hport
1328 /* shouldn't get here */
1332 config->need_bind = 0;
1335 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1337 if (!accept_connection(csp, bfd))
1339 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1352 log_error(LOG_LEVEL_CONNECT, "OK");
1356 /* by haroon - most of credit to srt19170 */
1357 csp->toggled_on = g_bToggleIJB;
1360 if (run_loader(csp))
1362 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1363 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1366 if (block_acl(NULL,csp))
1368 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1369 close_socket(csp->cfd);
1374 /* add it to the list of clients */
1375 csp->next = clients->next;
1376 clients->next = csp;
1378 if (config->multi_threaded)
1382 /* this is a switch () statment in the C preprocessor - ugh */
1383 #undef SELECTED_ONE_OPTION
1385 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1386 #define SELECTED_ONE_OPTION
1387 child_id = _beginthread(
1393 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1394 #define SELECTED_ONE_OPTION
1396 thread_id tid = spawn_thread
1397 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1399 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1401 child_id = (int) tid;
1410 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1411 #define SELECTED_ONE_OPTION
1412 csp->cfd = ReleaseSocket(csp->cfd, -1);
1413 if((child_id = (int)CreateNewProcTags(
1414 NP_Entry, (ULONG)server_thread,
1415 NP_Output, Output(),
1416 NP_CloseOutput, FALSE,
1417 NP_Name, (ULONG)"junkbuster child",
1418 NP_StackSize, 200*1024,
1422 ((struct Task *)child_id)->tc_UserData = csp;
1423 Signal((struct Task *)child_id, SIGF_SINGLE);
1428 #if !defined(SELECTED_ONE_OPTION)
1432 #undef SELECTED_ONE_OPTION
1433 /* end of cpp switch () */
1435 if (child_id < 0) /* failed */
1437 char buf[BUFFER_SIZE];
1439 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1441 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1443 write_socket(csp->cfd, buf, strlen(buf));
1444 close_socket(csp->cfd);
1450 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1451 /* This block is only needed when using fork().
1452 * When using threads, the server thread was
1453 * created and run by the call to _beginthread().
1455 if (child_id == 0) /* child */
1463 /* in a fork()'d environment, the parent's
1464 * copy of the client socket and the CSP
1468 #if !defined(_WIN32) && defined(__CYGWIN__)
1470 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1471 close_socket(csp->cfd);
1474 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */