1 const char jcc_rcs[] = "$Id: jcc.c,v 1.20 2001/06/09 10:55:28 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.20 2001/06/09 10:55:28 jongfoster
37 * Changing BUFSIZ ==> BUFFER_SIZE
39 * Revision 1.19 2001/06/07 23:12:52 jongfoster
40 * Replacing function pointer in struct gateway with a directly
41 * called function forwarded_connect().
42 * Replacing struct gateway with struct forward_spec
44 * Revision 1.18 2001/06/03 19:12:16 oes
45 * introduced new cgi handling
47 * Revision 1.17 2001/06/01 20:07:23 jongfoster
48 * Now uses action +image-blocker{} rather than config->tinygif
50 * Revision 1.16 2001/06/01 18:49:17 jongfoster
51 * Replaced "list_share" with "list" - the tiny memory gain was not
52 * worth the extra complexity.
54 * Revision 1.15 2001/05/31 21:24:47 jongfoster
55 * Changed "permission" to "action" throughout.
56 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
57 * Moved vanilla wafer check into chat(), since we must now
58 * decide whether or not to add it based on the URL.
60 * Revision 1.14 2001/05/29 20:14:01 joergs
61 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
64 * Revision 1.13 2001/05/29 09:50:24 jongfoster
65 * Unified blocklist/imagelist/permissionslist.
66 * File format is still under discussion, but the internal changes
69 * Also modified interceptor behaviour:
70 * - We now intercept all URLs beginning with one of the following
71 * prefixes (and *only* these prefixes):
73 * * http://ijbswa.sf.net/config/
74 * * http://ijbswa.sourceforge.net/config/
75 * - New interceptors "home page" - go to http://i.j.b/ to see it.
76 * - Internal changes so that intercepted and fast redirect pages
77 * are not replaced with an image.
78 * - Interceptors now have the option to send a binary page direct
79 * to the client. (i.e. ijb-send-banner uses this)
80 * - Implemented show-url-info interceptor. (Which is why I needed
81 * the above interceptors changes - a typical URL is
82 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
83 * The previous mechanism would not have intercepted that, and
84 * if it had been intercepted then it then it would have replaced
87 * Revision 1.12 2001/05/27 22:17:04 oes
89 * - re_process_buffer no longer writes the modified buffer
90 * to the client, which was very ugly. It now returns the
91 * buffer, which it is then written by chat.
93 * - content_length now adjusts the Content-Length: header
94 * for modified documents rather than crunch()ing it.
95 * (Length info in csp->content_length, which is 0 for
96 * unmodified documents)
98 * - For this to work, sed() is called twice when filtering.
100 * Revision 1.11 2001/05/26 17:27:53 jongfoster
101 * Added support for CLF and fixed LOG_LEVEL_LOG.
102 * Also did CRLF->LF fix of my previous patch.
104 * Revision 1.10 2001/05/26 15:26:15 jongfoster
105 * ACL feature now provides more security by immediately dropping
106 * connections from untrusted hosts.
108 * Revision 1.9 2001/05/26 00:28:36 jongfoster
109 * Automatic reloading of config file.
110 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
111 * Most of the global variables have been moved to a new
112 * struct configuration_spec, accessed through csp->config->globalname
113 * Most of the globals remaining are used by the Win32 GUI.
115 * Revision 1.8 2001/05/25 22:43:18 jongfoster
116 * Fixing minor memory leak and buffer overflow.
118 * Revision 1.7 2001/05/25 22:34:30 jongfoster
121 * Revision 1.6 2001/05/23 00:13:58 joergs
122 * AmigaOS support fixed.
124 * Revision 1.5 2001/05/22 18:46:04 oes
126 * - Enabled filtering banners by size rather than URL
127 * by adding patterns that replace all standard banner
128 * sizes with the "Junkbuster" gif to the re_filterfile
130 * - Enabled filtering WebBugs by providing a pattern
131 * which kills all 1x1 images
133 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
134 * which is selected by the (nonstandard and therefore
135 * capital) letter 'U' in the option string.
136 * It causes the quantifiers to be ungreedy by default.
137 * Appending a ? turns back to greedy (!).
139 * - Added a new interceptor ijb-send-banner, which
140 * sends back the "Junkbuster" gif. Without imagelist or
141 * MSIE detection support, or if tinygif = 1, or the
142 * URL isn't recognized as an imageurl, a lame HTML
143 * explanation is sent instead.
145 * - Added new feature, which permits blocking remote
146 * script redirects and firing back a local redirect
148 * The feature is conditionally compiled, i.e. it
149 * can be disabled with --disable-fast-redirects,
150 * plus it must be activated by a "fast-redirects"
151 * line in the config file, has its own log level
152 * and of course wants to be displayed by show-proxy-args
153 * Note: Boy, all the #ifdefs in 1001 locations and
154 * all the fumbling with configure.in and acconfig.h
155 * were *way* more work than the feature itself :-(
157 * - Because a generic redirect template was needed for
158 * this, tinygif = 3 now uses the same.
160 * - Moved GIFs, and other static HTTP response templates
165 * - Removed some >400 CRs again (Jon, you really worked
168 * Revision 1.4 2001/05/21 19:34:01 jongfoster
169 * Made failure to bind() a fatal error.
171 * Revision 1.3 2001/05/20 01:21:20 jongfoster
172 * Version 2.9.4 checkin.
173 * - Merged popupfile and cookiefile, and added control over PCRS
174 * filtering, in new "permissionsfile".
175 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
176 * file error you now get a message box (in the Win32 GUI) rather
177 * than the program exiting with no explanation.
178 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
180 * - Removed tabs from "config"
181 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
182 * - Bumped up version number.
184 * Revision 1.2 2001/05/17 22:34:44 oes
185 * - Added hint on GIF char array generation to jcc.c
186 * - Cleaned CRLF's from the sources and related files
187 * - Repaired logging for REF and FRC
189 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
190 * Initial import of version 2.9.3 source tree
193 *********************************************************************/
199 #include <sys/types.h>
208 # include <sys/timeb.h>
209 # include <windows.h>
211 # include <process.h>
214 # endif /* def TOGGLE */
217 # ifndef _WIN_CONSOLE
219 # endif /* ndef _WIN_CONSOLE */
221 #else /* ifndef _WIN32 */
224 # include <sys/time.h>
225 # include <sys/wait.h>
226 # include <sys/stat.h>
230 # include <socket.h> /* BeOS has select() for sockets only. */
231 # include <OS.h> /* declarations for threads and stuff. */
245 #include "showargs.h"
247 #include "killpopup.h"
248 #include "miscutil.h"
250 #include "jbsockets.h"
255 const char jcc_h_rcs[] = JCC_H_VERSION;
256 const char project_h_rcs[] = PROJECT_H_VERSION;
258 struct client_state clients[1];
259 struct file_list files[1];
262 int urls_read = 0; /* total nr of urls read inc rejected */
263 int urls_rejected = 0; /* total nr of urls rejected */
264 #endif /* def STATISTICS */
267 static void listen_loop(void);
268 static void chat(struct client_state *csp);
270 void serve(struct client_state *csp);
271 #else /* ifndef AMIGA */
272 static void serve(struct client_state *csp);
273 #endif /* def AMIGA */
276 static int32 server_thread(void *data);
277 #endif /* def __BEOS__ */
280 #define sleep(N) Sleep(((N) * 1000))
284 /* The vanilla wafer. */
285 static const char VANILLA_WAFER[] =
286 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
287 "Do_not_send_me_any_copyrighted_information_other_than_the_"
288 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
289 "In_particular_do_not_send_me_any_cookies_that_"
290 "are_subject_to_a_claim_of_copyright_by_anybody._"
291 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
292 "(copyright_or_otherwise)_applying_to_any_cookie._";
295 /*********************************************************************
299 * Description : Once a connection to the client has been accepted,
300 * this function is called (via serve()) to handle the
301 * main business of the communication. When this
302 * function returns, the caller must close the client
306 * 1 : csp = Current client state (buffers, headers, etc...)
308 * Returns : On success, the number of bytes written are returned (zero
309 * indicates nothing was written). On error, -1 is returned,
310 * and errno is set appropriately. If count is zero and the
311 * file descriptor refers to a regular file, 0 will be
312 * returned without causing any other effect. For a special
313 * file, the results are not portable.
315 *********************************************************************/
316 static void chat(struct client_state *csp)
319 * This next lines are a little ugly, but they simplifies the if statements below.
320 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
321 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
324 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
325 #else /* ifndef TOGGLE */
326 # define IS_TOGGLED_ON_AND
327 #endif /* ndef TOGGLE */
329 # define IS_NOT_FORCED_AND (!csp->force) &&
330 #else /* ifndef FORCE_LOAD */
331 # define IS_NOT_FORCED_AND
332 #endif /* def FORCE_LOAD */
334 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
336 char buf[BUFFER_SIZE];
\r
340 int n, maxfd, server_body;
341 int ms_iis5_hack = 0;
343 const struct forward_spec * fwd;
344 struct http_request *http;
346 int block_popups; /* bool, 1==will block popups */
347 int block_popups_now = 0; /* bool, 1==currently blocking popups */
348 #endif /* def KILLPOPUPS */
350 int pcrs_filter; /* bool, 1==will filter through pcrs */
351 int filtering = 0; /* bool, 1==currently filtering through pcrs */
352 #endif /* def PCRS */
353 struct http_response *rsp;
358 * Read the client's request. Note that since we're not using select() we
359 * could get blocked here if a client connected, then didn't say anything!
364 n = read_socket(csp->cfd, buf, sizeof(buf));
366 if (n <= 0) break; /* error! */
368 add_to_iob(csp, buf, n);
370 req = get_header(csp);
374 break; /* no HTTP request! */
379 continue; /* more to come! */
383 /* If this request contains the FORCE_PREFIX,
384 * better get rid of it now and set the force flag --oes
387 if (strstr(req, FORCE_PREFIX))
389 strclean(req, FORCE_PREFIX);
390 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
397 #endif /* def FORCE_LOAD */
399 parse_http_request(req, http, csp);
404 if (http->cmd == NULL)
406 strcpy(buf, CHEADER);
407 write_socket(csp->cfd, buf, strlen(buf));
409 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
414 /* decide how to route the HTTP request */
416 if ((fwd = forward_url(http, csp)) == NULL)
418 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
419 /* Never get here - LOG_LEVEL_FATAL causes program exit */
422 /* build the http request to send to the server
423 * we have to do one of the following:
425 * create = use the original HTTP request to create a new
426 * HTTP request that has only the path component
427 * without the http://domainspec
428 * pass = pass the original HTTP request unchanged
430 * drop = drop the HTTP request
435 * +--------+--------+
437 * 0 | create | drop |
439 * Forwarding +--------+--------+
443 * +--------+--------+
447 if (fwd->forward_host)
449 /* if forwarding, just pass the request as is */
450 enlist(csp->headers, http->cmd);
456 /* otherwise elide the host information from the url */
458 p = strsav(p, http->gpc);
460 p = strsav(p, http->path);
462 p = strsav(p, http->ver);
463 enlist(csp->headers, p);
468 /* decide what we're to do with cookies */
471 if (!csp->toggled_on)
473 /* Most compatible set of actions (i.e. none) */
474 init_current_action(csp->action);
477 #endif /* ndef TOGGLE */
479 url_actions(http, csp);
484 * If we're logging cookies in a cookie jar, and the user has not
485 * supplied any wafers, and the user has not told us to suppress the
486 * vanilla wafer, then send the vanilla wafer.
488 if ((csp->config->jarfile != NULL)
489 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
490 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
492 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
494 #endif /* def JAR_FILES */
497 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
498 #endif /* def KILLPOPUPS */
500 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
501 ((csp->action->flags & ACTION_FILTER) != 0);
502 #endif /* def PCRS */
505 /* grab the rest of the client's headers */
509 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
511 n = read_socket(csp->cfd, buf, sizeof(buf));
514 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
517 add_to_iob(csp, buf, n);
521 if (p == NULL) break;
523 enlist(csp->headers, p);
527 /* We have a request. */
529 hdr = sed(client_patterns, add_client_headers, csp);
530 destroy_list(csp->headers);
533 * Now, check to see if we need to intercept it, i.e.
538 /* a CGI call was detected and answered */
539 (NULL != (rsp = dispatch_cgi(csp)))
541 /* or we are enabled and... */
544 /* ..the request was blocked */
545 ( NULL != (rsp = block_url(csp)))
549 || ( NULL != (rsp = trust_url(csp)))
552 /* ..or a fast redirect kicked in */
553 #ifdef FAST_REDIRECTS
554 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
555 (NULL != (rsp = redirect_url(csp))))
556 #endif /* def FAST_REDIRECTS */
560 /* Write the answer to the client */
561 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
562 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
564 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
568 /* Count as a rejected request */
570 #endif /* def STATISTICS */
572 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
573 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
574 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
576 /* Clean up and return */
577 free_http_response(rsp);
582 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
584 if (fwd->forward_host)
586 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
587 fwd->forward_host, fwd->forward_port, http->hostport);
591 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
594 /* here we connect to the server, gateway, or the forwarder */
596 csp->sfd = forwarded_connect(fwd, http, csp);
600 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
605 rsp = error_response(csp, "no-such-domain", errno);
607 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
608 csp->ip_addr_str, http->cmd);
612 rsp = error_response(csp, "connect-failed", errno);
614 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
615 csp->ip_addr_str, http->cmd);
618 /* Write the answer to the client */
621 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
622 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
624 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
628 free_http_response(rsp);
633 log_error(LOG_LEVEL_CONNECT, "OK");
635 if (fwd->forward_host || (http->ssl == 0))
637 /* write the client's (modified) header to the server
638 * (along with anything else that may be in the buffer)
643 if ((write_socket(csp->sfd, hdr, n) != n)
644 || (flush_socket(csp->sfd, csp ) < 0))
646 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
649 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
650 csp->ip_addr_str, http->cmd);
652 rsp = error_response(csp, "connect-failed", errno);
656 if ((write_socket(csp->cfd, rsp->head, n) != n)
657 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
659 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
663 free_http_response(rsp);
671 * We're running an SSL tunnel and we're not forwarding,
672 * so just send the "connect succeeded" message to the
673 * client, flush the rest, and get out of the way.
675 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
676 csp->ip_addr_str, http->cmd);
678 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
686 /* we're finished with the client's header */
689 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
691 /* pass data between the client and server
692 * until one or the other shuts down the connection.
701 FD_SET(csp->cfd, &rfds);
702 FD_SET(csp->sfd, &rfds);
704 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
708 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
712 /* this is the body of the browser's request
713 * just read it and write it.
716 if (FD_ISSET(csp->cfd, &rfds))
718 n = read_socket(csp->cfd, buf, sizeof(buf));
722 break; /* "game over, man" */
725 if (write_socket(csp->sfd, buf, n) != n)
727 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
734 * The server wants to talk. It could be the header or the body.
735 * If `hdr' is null, then it's the header otherwise it's the body.
736 * FIXME: Does `hdr' really mean `host'?
740 if (FD_ISSET(csp->sfd, &rfds))
743 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
747 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
749 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
750 csp->ip_addr_str, http->cmd);
752 rsp = error_response(csp, "connect-failed", errno);
756 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
757 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
759 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
763 free_http_response(rsp);
767 /* Add a trailing zero. This lets filter_popups
768 * use string operations.
773 /* Filter the popups on this read. */
774 if (block_popups_now)
776 filter_popups(buf, n);
778 #endif /* def KILLPOPUPS */
780 /* Normally, this would indicate that we've read
781 * as much as the server has sent us and we can
782 * close the client connection. However, Microsoft
783 * in its wisdom has released IIS/5 with a bug that
784 * prevents it from sending the trailing \r\n in
785 * a 302 redirect header (and possibly other headers).
786 * To work around this if we've haven't parsed
787 * a full header we'll append a trailing \r\n
788 * and see if this now generates a valid one.
790 * This hack shouldn't have any impacts. If we've
791 * already transmitted the header or if this is a
792 * SSL connection, then we won't bother with this
793 * hack. So we only work on partially received
794 * headers. If we append a \r\n and this still
795 * doesn't generate a valid header, then we won't
796 * transmit anything to the client.
800 /* This hack must only be enforced for headers. */
801 if (server_body || http->ssl)
806 p = re_process_buffer(csp);
807 hdr = sed(server_patterns, add_server_headers, csp);
809 if ((write_socket(csp->cfd, hdr, n) != n)
810 || (write_socket(csp->cfd, p, csp->content_length) != csp->content_length))
812 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
818 #endif /* def PCRS */
819 break; /* "game over, man" */
822 /* Let's pretend the server just sent us a blank line. */
823 n = sprintf(buf, "\r\n");
826 * Now, let the normal header parsing algorithm below do its
827 * job. If it fails, we'll exit instead of continuing.
834 * If this is an SSL connection or we're in the body
835 * of the server document, just write it to the client.
838 if (server_body || http->ssl)
843 add_to_iob(csp, buf, n); /* Buffer the body for filtering */
846 #endif /* def PCRS */
849 if (write_socket(csp->cfd, buf, n) != n)
851 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
860 /* we're still looking for the end of the
861 * server's header ... (does that make header
862 * parsing an "out of body experience" ?
865 /* buffer up the data we just read */
866 add_to_iob(csp, buf, n);
868 /* get header lines from the iob */
870 while ((p = get_header(csp)))
874 /* see following note */
877 enlist(csp->headers, p);
881 /* NOTE: there are no "empty" headers so
882 * if the pointer `p' is not NULL we must
883 * assume that we reached the end of the
884 * buffer before we hit the end of the header.
891 /* Well, we tried our MS IIS/5
892 * hack and it didn't work.
893 * The header is incomplete
894 * and there isn't anything
895 * we can do about it.
901 /* Since we have to wait for
902 * more from the server before
903 * we can parse the headers
904 * we just continue here.
910 /* we have now received the entire header.
911 * filter it and send the result to the client
914 hdr = sed(server_patterns, add_server_headers, csp);
917 /* write the server's (modified) header to
918 * the client (along with anything else that
919 * may be in the buffer)
923 /* Start blocking popups if appropriate. */
925 if (csp->is_text && /* It's a text / * MIME-Type */
926 !http->ssl && /* We talk plaintext */
927 block_popups) /* Policy allows */
929 block_popups_now = 1;
932 #endif /* def KILLPOPUPS */
935 /* Start re_filtering this if appropriate. */
937 if (csp->is_text && /* It's a text / * MIME-Type */
938 !http->ssl && /* We talk plaintext */
939 pcrs_filter) /* Policy allows */
944 /* This next line is a little ugly, but it simplifies the if statement below. */
945 /* Basically if using PCRS, we want the OR condition to require "!filtering" */
946 #define NOT_FILTERING_AND !filtering &&
948 #else /* not def PCRS */
950 #define NOT_FILTERING_AND
952 #endif /* def PCRS */
954 if (NOT_FILTERING_AND ((write_socket(csp->cfd, hdr, n) != n)
955 || (n = flush_socket(csp->cfd, csp) < 0)))
957 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
959 /* the write failed, so don't bother
960 * mentioning it to the client...
961 * it probably can't hear us anyway.
967 NOT_FILTERING_AND (byte_count += n);
969 /* we're finished with the server's header */
974 /* If this was a MS IIS/5 hack then it means
975 * the server has already closed the
976 * connection. Nothing more to read. Time
987 return; /* huh? we should never get here */
990 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
991 csp->ip_addr_str, http->cmd, byte_count);
995 /*********************************************************************
999 * Description : This is little more than chat. We only "serve" to
1000 * to close any socket that chat may have opened.
1003 * 1 : csp = Current client state (buffers, headers, etc...)
1007 *********************************************************************/
1009 void serve(struct client_state *csp)
1010 #else /* ifndef AMIGA */
1011 static void serve(struct client_state *csp)
1012 #endif /* def AMIGA */
1015 close_socket(csp->cfd);
1019 close_socket(csp->sfd);
1029 /*********************************************************************
1031 * Function : server_thread
1033 * Description : We only exist to call `serve' in a threaded environment.
1036 * 1 : data = Current client state (buffers, headers, etc...)
1038 * Returns : Always 0.
1040 *********************************************************************/
1041 static int32 server_thread(void *data)
1043 serve((struct client_state *) data);
1051 /*********************************************************************
1055 * Description : Load the config file and start the listen loop.
1056 * This function is a lot more *sane* with the `load_config'
1057 * and `listen_loop' functions; although it stills does
1058 * a *little* too much for my taste.
1061 * 1 : argc = Number of parameters (including $0).
1062 * 2 : argv = Array of (char *)'s to the parameters.
1064 * Returns : 1 if : can't open config file, unrecognized directive,
1065 * stats requested in multi-thread mode, can't open the
1066 * log file, can't open the jar file, listen port is invalid,
1067 * any load fails, and can't bind port.
1069 * Else main never returns, the process must be signaled
1070 * to terminate execution. Or, on Windows, use the
1071 * "File", "Exit" menu option.
1073 *********************************************************************/
1075 int _main(int argc, const char *argv[])
1077 int main(int argc, const char *argv[])
1082 "AmiTCP:db/junkbuster/config"
1083 #elif !defined(_WIN32)
1090 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1091 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1093 printf("JunkBuster proxy version " VERSION ".\n\n"
1094 "Usage: %s [configfile]\n\n"
1095 "See " HOME_PAGE_URL " for details.\n"
1096 "This program is distributed under the GNU GPL, version 2 or later.\n",
1100 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1102 printf(VERSION "\n");
1105 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1112 configfile = argv[1];
1119 #elif defined(_WIN32)
1125 signal(SIGPIPE, SIG_IGN);
1126 signal(SIGCHLD, SIG_IGN);
1128 #else /* ifdef _WIN32 */
1129 # ifdef _WIN_CONSOLE
1131 * We *are* in a windows console app.
1132 * Print a verbose messages about FAQ's and such
1134 printf(win32_blurb);
1135 # endif /* def _WIN_CONSOLE */
1136 #endif /* def _WIN32 */
1147 /*********************************************************************
1149 * Function : listen_loop
1151 * Description : bind the listen port and enter a "FOREVER" listening loop.
1157 *********************************************************************/
1158 static void listen_loop(void)
1160 struct client_state *csp = NULL;
1162 struct configuration_spec * config;
1164 config = load_config();
1166 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1167 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1169 bfd = bind_port(config->haddr, config->hport);
1173 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1174 "- There may be another junkbuster or some other "
1175 "proxy running on port %d",
1176 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1177 config->hport, config->hport
1179 /* shouldn't get here */
1183 config->need_bind = 0;
1188 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1189 while (waitpid(-1, NULL, WNOHANG) > 0)
1191 /* zombie children */
1193 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1196 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1198 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1202 memset(csp, '\0', sizeof(*csp));
1207 csp->config = config = load_config();
1209 if ( config->need_bind )
1212 * Since we were listening to the "old port", we will not see
1213 * a "listen" param change until the next IJB request. So, at
1214 * least 1 more request must be made for us to find the new
1215 * setting. I am simply closing the old socket and binding the
1218 * Which-ever is correct, we will serve 1 more page via the
1219 * old settings. This should probably be a "show-proxy-args"
1220 * request. This should not be a so common of an operation
1221 * that this will hurt people's feelings.
1226 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1227 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1228 bfd = bind_port(config->haddr, config->hport);
1232 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1233 "- There may be another junkbuster or some other "
1234 "proxy running on port %d",
1235 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1236 config->hport, config->hport
1238 /* shouldn't get here */
1242 config->need_bind = 0;
1245 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1247 if (!accept_connection(csp, bfd))
1249 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1262 log_error(LOG_LEVEL_CONNECT, "OK");
1266 /* by haroon - most of credit to srt19170 */
1267 csp->toggled_on = g_bToggleIJB;
1270 if (run_loader(csp))
1272 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1273 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1276 if (block_acl(NULL,csp))
1278 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1279 close_socket(csp->cfd);
1284 /* add it to the list of clients */
1285 csp->next = clients->next;
1286 clients->next = csp;
1288 if (config->multi_threaded)
1292 /* this is a switch () statment in the C preprocessor - ugh */
1293 #undef SELECTED_ONE_OPTION
1295 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1296 #define SELECTED_ONE_OPTION
1297 child_id = _beginthread(
1303 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1304 #define SELECTED_ONE_OPTION
1306 thread_id tid = spawn_thread
1307 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1309 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1311 child_id = (int) tid;
1320 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1321 #define SELECTED_ONE_OPTION
1322 csp->cfd = ReleaseSocket(csp->cfd, -1);
1323 if((child_id = (int)CreateNewProcTags(
1324 NP_Entry, (ULONG)server_thread,
1325 NP_Output, Output(),
1326 NP_CloseOutput, FALSE,
1327 NP_Name, (ULONG)"junkbuster child",
1328 NP_StackSize, 200*1024,
1332 ((struct Task *)child_id)->tc_UserData = csp;
1333 Signal((struct Task *)child_id, SIGF_SINGLE);
1338 #if !defined(SELECTED_ONE_OPTION)
1342 #undef SELECTED_ONE_OPTION
1343 /* end of cpp switch () */
1345 if (child_id < 0) /* failed */
1347 char buf[BUFFER_SIZE];
1349 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1351 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1353 write_socket(csp->cfd, buf, strlen(buf));
1354 close_socket(csp->cfd);
1360 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1361 /* This block is only needed when using fork().
1362 * When using threads, the server thread was
1363 * created and run by the call to _beginthread().
1365 if (child_id == 0) /* child */
1373 /* in a fork()'d environment, the parent's
1374 * copy of the client socket and the CSP
1378 #if !defined(_WIN32) && defined(__CYGWIN__)
1380 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1381 close_socket(csp->cfd);
1384 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */