1 const char jcc_rcs[] = "$Id: jcc.c,v 1.21 2001/06/29 13:29:36 oes 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.21 2001/06/29 13:29:36 oes
37 * - Cleaned up, improved comments
38 * - Unified all possible interceptors (CGI,
39 * block, trust, fast_redirect) in one
40 * place, with one (CGI) answer generation
41 * mechansim. Much clearer now.
42 * - Removed the GIF image generation, which
43 * is now done in filters.c:block_url()
44 * - Made error conditions like domain lookup
45 * failiure or (various) problems while talking
46 * to the server use cgi.c:error_response()
47 * instead of generating HTML/HTTP in chat() (yuck!)
48 * - Removed logentry from cancelled commit
50 * Revision 1.20 2001/06/09 10:55:28 jongfoster
51 * Changing BUFSIZ ==> BUFFER_SIZE
53 * Revision 1.19 2001/06/07 23:12:52 jongfoster
54 * Replacing function pointer in struct gateway with a directly
55 * called function forwarded_connect().
56 * Replacing struct gateway with struct forward_spec
58 * Revision 1.18 2001/06/03 19:12:16 oes
59 * introduced new cgi handling
61 * Revision 1.17 2001/06/01 20:07:23 jongfoster
62 * Now uses action +image-blocker{} rather than config->tinygif
64 * Revision 1.16 2001/06/01 18:49:17 jongfoster
65 * Replaced "list_share" with "list" - the tiny memory gain was not
66 * worth the extra complexity.
68 * Revision 1.15 2001/05/31 21:24:47 jongfoster
69 * Changed "permission" to "action" throughout.
70 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
71 * Moved vanilla wafer check into chat(), since we must now
72 * decide whether or not to add it based on the URL.
74 * Revision 1.14 2001/05/29 20:14:01 joergs
75 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
78 * Revision 1.13 2001/05/29 09:50:24 jongfoster
79 * Unified blocklist/imagelist/permissionslist.
80 * File format is still under discussion, but the internal changes
83 * Also modified interceptor behaviour:
84 * - We now intercept all URLs beginning with one of the following
85 * prefixes (and *only* these prefixes):
87 * * http://ijbswa.sf.net/config/
88 * * http://ijbswa.sourceforge.net/config/
89 * - New interceptors "home page" - go to http://i.j.b/ to see it.
90 * - Internal changes so that intercepted and fast redirect pages
91 * are not replaced with an image.
92 * - Interceptors now have the option to send a binary page direct
93 * to the client. (i.e. ijb-send-banner uses this)
94 * - Implemented show-url-info interceptor. (Which is why I needed
95 * the above interceptors changes - a typical URL is
96 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
97 * The previous mechanism would not have intercepted that, and
98 * if it had been intercepted then it then it would have replaced
101 * Revision 1.12 2001/05/27 22:17:04 oes
103 * - re_process_buffer no longer writes the modified buffer
104 * to the client, which was very ugly. It now returns the
105 * buffer, which it is then written by chat.
107 * - content_length now adjusts the Content-Length: header
108 * for modified documents rather than crunch()ing it.
109 * (Length info in csp->content_length, which is 0 for
110 * unmodified documents)
112 * - For this to work, sed() is called twice when filtering.
114 * Revision 1.11 2001/05/26 17:27:53 jongfoster
115 * Added support for CLF and fixed LOG_LEVEL_LOG.
116 * Also did CRLF->LF fix of my previous patch.
118 * Revision 1.10 2001/05/26 15:26:15 jongfoster
119 * ACL feature now provides more security by immediately dropping
120 * connections from untrusted hosts.
122 * Revision 1.9 2001/05/26 00:28:36 jongfoster
123 * Automatic reloading of config file.
124 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
125 * Most of the global variables have been moved to a new
126 * struct configuration_spec, accessed through csp->config->globalname
127 * Most of the globals remaining are used by the Win32 GUI.
129 * Revision 1.8 2001/05/25 22:43:18 jongfoster
130 * Fixing minor memory leak and buffer overflow.
132 * Revision 1.7 2001/05/25 22:34:30 jongfoster
135 * Revision 1.6 2001/05/23 00:13:58 joergs
136 * AmigaOS support fixed.
138 * Revision 1.5 2001/05/22 18:46:04 oes
140 * - Enabled filtering banners by size rather than URL
141 * by adding patterns that replace all standard banner
142 * sizes with the "Junkbuster" gif to the re_filterfile
144 * - Enabled filtering WebBugs by providing a pattern
145 * which kills all 1x1 images
147 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
148 * which is selected by the (nonstandard and therefore
149 * capital) letter 'U' in the option string.
150 * It causes the quantifiers to be ungreedy by default.
151 * Appending a ? turns back to greedy (!).
153 * - Added a new interceptor ijb-send-banner, which
154 * sends back the "Junkbuster" gif. Without imagelist or
155 * MSIE detection support, or if tinygif = 1, or the
156 * URL isn't recognized as an imageurl, a lame HTML
157 * explanation is sent instead.
159 * - Added new feature, which permits blocking remote
160 * script redirects and firing back a local redirect
162 * The feature is conditionally compiled, i.e. it
163 * can be disabled with --disable-fast-redirects,
164 * plus it must be activated by a "fast-redirects"
165 * line in the config file, has its own log level
166 * and of course wants to be displayed by show-proxy-args
167 * Note: Boy, all the #ifdefs in 1001 locations and
168 * all the fumbling with configure.in and acconfig.h
169 * were *way* more work than the feature itself :-(
171 * - Because a generic redirect template was needed for
172 * this, tinygif = 3 now uses the same.
174 * - Moved GIFs, and other static HTTP response templates
179 * - Removed some >400 CRs again (Jon, you really worked
182 * Revision 1.4 2001/05/21 19:34:01 jongfoster
183 * Made failure to bind() a fatal error.
185 * Revision 1.3 2001/05/20 01:21:20 jongfoster
186 * Version 2.9.4 checkin.
187 * - Merged popupfile and cookiefile, and added control over PCRS
188 * filtering, in new "permissionsfile".
189 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
190 * file error you now get a message box (in the Win32 GUI) rather
191 * than the program exiting with no explanation.
192 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
194 * - Removed tabs from "config"
195 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
196 * - Bumped up version number.
198 * Revision 1.2 2001/05/17 22:34:44 oes
199 * - Added hint on GIF char array generation to jcc.c
200 * - Cleaned CRLF's from the sources and related files
201 * - Repaired logging for REF and FRC
203 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
204 * Initial import of version 2.9.3 source tree
207 *********************************************************************/
213 #include <sys/types.h>
222 # include <sys/timeb.h>
223 # include <windows.h>
225 # include <process.h>
228 # endif /* def TOGGLE */
231 # ifndef _WIN_CONSOLE
233 # endif /* ndef _WIN_CONSOLE */
235 #else /* ifndef _WIN32 */
238 # include <sys/time.h>
239 # include <sys/wait.h>
240 # include <sys/stat.h>
244 # include <socket.h> /* BeOS has select() for sockets only. */
245 # include <OS.h> /* declarations for threads and stuff. */
259 #include "showargs.h"
261 #include "killpopup.h"
262 #include "miscutil.h"
264 #include "jbsockets.h"
269 const char jcc_h_rcs[] = JCC_H_VERSION;
270 const char project_h_rcs[] = PROJECT_H_VERSION;
272 struct client_state clients[1];
273 struct file_list files[1];
276 int urls_read = 0; /* total nr of urls read inc rejected */
277 int urls_rejected = 0; /* total nr of urls rejected */
278 #endif /* def STATISTICS */
281 static void listen_loop(void);
282 static void chat(struct client_state *csp);
284 void serve(struct client_state *csp);
285 #else /* ifndef AMIGA */
286 static void serve(struct client_state *csp);
287 #endif /* def AMIGA */
290 static int32 server_thread(void *data);
291 #endif /* def __BEOS__ */
294 #define sleep(N) Sleep(((N) * 1000))
298 /* The vanilla wafer. */
299 static const char VANILLA_WAFER[] =
300 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
301 "Do_not_send_me_any_copyrighted_information_other_than_the_"
302 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
303 "In_particular_do_not_send_me_any_cookies_that_"
304 "are_subject_to_a_claim_of_copyright_by_anybody._"
305 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
306 "(copyright_or_otherwise)_applying_to_any_cookie._";
309 /*********************************************************************
313 * Description : Once a connection to the client has been accepted,
314 * this function is called (via serve()) to handle the
315 * main business of the communication. When this
316 * function returns, the caller must close the client
320 * 1 : csp = Current client state (buffers, headers, etc...)
322 * Returns : On success, the number of bytes written are returned (zero
323 * indicates nothing was written). On error, -1 is returned,
324 * and errno is set appropriately. If count is zero and the
325 * file descriptor refers to a regular file, 0 will be
326 * returned without causing any other effect. For a special
327 * file, the results are not portable.
329 *********************************************************************/
330 static void chat(struct client_state *csp)
333 * This next lines are a little ugly, but they simplifies the if statements below.
334 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
335 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
338 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
339 #else /* ifndef TOGGLE */
340 # define IS_TOGGLED_ON_AND
341 #endif /* ndef TOGGLE */
343 # define IS_NOT_FORCED_AND (!csp->force) &&
344 #else /* ifndef FORCE_LOAD */
345 # define IS_NOT_FORCED_AND
346 #endif /* def FORCE_LOAD */
348 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
350 char buf[BUFFER_SIZE];
354 int n, maxfd, server_body;
355 int ms_iis5_hack = 0;
357 const struct forward_spec * fwd;
358 struct http_request *http;
360 int block_popups; /* bool, 1==will block popups */
361 int block_popups_now = 0; /* bool, 1==currently blocking popups */
362 #endif /* def KILLPOPUPS */
364 int pcrs_filter; /* bool, 1==will filter through pcrs */
365 int filtering = 0; /* bool, 1==currently filtering through pcrs */
366 #endif /* def PCRS */
367 struct http_response *rsp;
372 * Read the client's request. Note that since we're not using select() we
373 * could get blocked here if a client connected, then didn't say anything!
378 n = read_socket(csp->cfd, buf, sizeof(buf));
380 if (n <= 0) break; /* error! */
382 add_to_iob(csp, buf, n);
384 req = get_header(csp);
388 break; /* no HTTP request! */
393 continue; /* more to come! */
397 /* If this request contains the FORCE_PREFIX,
398 * better get rid of it now and set the force flag --oes
401 if (strstr(req, FORCE_PREFIX))
403 strclean(req, FORCE_PREFIX);
404 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
411 #endif /* def FORCE_LOAD */
413 parse_http_request(req, http, csp);
418 if (http->cmd == NULL)
420 strcpy(buf, CHEADER);
421 write_socket(csp->cfd, buf, strlen(buf));
423 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
428 /* decide how to route the HTTP request */
430 if ((fwd = forward_url(http, csp)) == NULL)
432 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
433 /* Never get here - LOG_LEVEL_FATAL causes program exit */
436 /* build the http request to send to the server
437 * we have to do one of the following:
439 * create = use the original HTTP request to create a new
440 * HTTP request that has only the path component
441 * without the http://domainspec
442 * pass = pass the original HTTP request unchanged
444 * drop = drop the HTTP request
449 * +--------+--------+
451 * 0 | create | drop |
453 * Forwarding +--------+--------+
457 * +--------+--------+
461 if (fwd->forward_host)
463 /* if forwarding, just pass the request as is */
464 enlist(csp->headers, http->cmd);
470 /* otherwise elide the host information from the url */
472 p = strsav(p, http->gpc);
474 p = strsav(p, http->path);
476 p = strsav(p, http->ver);
477 enlist(csp->headers, p);
482 /* decide what we're to do with cookies */
485 if (!csp->toggled_on)
487 /* Most compatible set of actions (i.e. none) */
488 init_current_action(csp->action);
491 #endif /* ndef TOGGLE */
493 url_actions(http, csp);
498 * If we're logging cookies in a cookie jar, and the user has not
499 * supplied any wafers, and the user has not told us to suppress the
500 * vanilla wafer, then send the vanilla wafer.
502 if ((csp->config->jarfile != NULL)
503 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
504 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
506 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
508 #endif /* def JAR_FILES */
511 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
512 #endif /* def KILLPOPUPS */
514 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
515 ((csp->action->flags & ACTION_FILTER) != 0);
516 #endif /* def PCRS */
519 /* grab the rest of the client's headers */
523 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
525 n = read_socket(csp->cfd, buf, sizeof(buf));
528 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
531 add_to_iob(csp, buf, n);
535 if (p == NULL) break;
537 enlist(csp->headers, p);
541 /* We have a request. */
543 hdr = sed(client_patterns, add_client_headers, csp);
544 destroy_list(csp->headers);
547 * Now, check to see if we need to intercept it, i.e.
552 /* a CGI call was detected and answered */
553 (NULL != (rsp = dispatch_cgi(csp)))
555 /* or we are enabled and... */
558 /* ..the request was blocked */
559 ( NULL != (rsp = block_url(csp)))
563 || ( NULL != (rsp = trust_url(csp)))
566 /* ..or a fast redirect kicked in */
567 #ifdef FAST_REDIRECTS
568 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
569 (NULL != (rsp = redirect_url(csp))))
570 #endif /* def FAST_REDIRECTS */
574 /* Write the answer to the client */
575 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
576 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
578 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
582 /* Count as a rejected request */
584 #endif /* def STATISTICS */
586 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
587 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
588 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
590 /* Clean up and return */
591 free_http_response(rsp);
596 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
598 if (fwd->forward_host)
600 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
601 fwd->forward_host, fwd->forward_port, http->hostport);
605 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
608 /* here we connect to the server, gateway, or the forwarder */
610 csp->sfd = forwarded_connect(fwd, http, csp);
614 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
619 rsp = error_response(csp, "no-such-domain", errno);
621 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
622 csp->ip_addr_str, http->cmd);
626 rsp = error_response(csp, "connect-failed", errno);
628 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
629 csp->ip_addr_str, http->cmd);
632 /* Write the answer to the client */
635 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
636 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
638 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
642 free_http_response(rsp);
647 log_error(LOG_LEVEL_CONNECT, "OK");
649 if (fwd->forward_host || (http->ssl == 0))
651 /* write the client's (modified) header to the server
652 * (along with anything else that may be in the buffer)
657 if ((write_socket(csp->sfd, hdr, n) != n)
658 || (flush_socket(csp->sfd, csp ) < 0))
660 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
663 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
664 csp->ip_addr_str, http->cmd);
666 rsp = error_response(csp, "connect-failed", errno);
670 if ((write_socket(csp->cfd, rsp->head, n) != n)
671 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
673 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
677 free_http_response(rsp);
685 * We're running an SSL tunnel and we're not forwarding,
686 * so just send the "connect succeeded" message to the
687 * client, flush the rest, and get out of the way.
689 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
690 csp->ip_addr_str, http->cmd);
692 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
700 /* we're finished with the client's header */
703 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
705 /* pass data between the client and server
706 * until one or the other shuts down the connection.
715 FD_SET(csp->cfd, &rfds);
716 FD_SET(csp->sfd, &rfds);
718 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
722 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
726 /* this is the body of the browser's request
727 * just read it and write it.
730 if (FD_ISSET(csp->cfd, &rfds))
732 n = read_socket(csp->cfd, buf, sizeof(buf));
736 break; /* "game over, man" */
739 if (write_socket(csp->sfd, buf, n) != n)
741 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
748 * The server wants to talk. It could be the header or the body.
749 * If `hdr' is null, then it's the header otherwise it's the body.
750 * FIXME: Does `hdr' really mean `host'?
754 if (FD_ISSET(csp->sfd, &rfds))
757 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
761 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
763 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
764 csp->ip_addr_str, http->cmd);
766 rsp = error_response(csp, "connect-failed", errno);
770 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
771 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
773 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
777 free_http_response(rsp);
781 /* Add a trailing zero. This lets filter_popups
782 * use string operations.
787 /* Filter the popups on this read. */
788 if (block_popups_now)
790 filter_popups(buf, n);
792 #endif /* def KILLPOPUPS */
794 /* Normally, this would indicate that we've read
795 * as much as the server has sent us and we can
796 * close the client connection. However, Microsoft
797 * in its wisdom has released IIS/5 with a bug that
798 * prevents it from sending the trailing \r\n in
799 * a 302 redirect header (and possibly other headers).
800 * To work around this if we've haven't parsed
801 * a full header we'll append a trailing \r\n
802 * and see if this now generates a valid one.
804 * This hack shouldn't have any impacts. If we've
805 * already transmitted the header or if this is a
806 * SSL connection, then we won't bother with this
807 * hack. So we only work on partially received
808 * headers. If we append a \r\n and this still
809 * doesn't generate a valid header, then we won't
810 * transmit anything to the client.
814 /* This hack must only be enforced for headers. */
815 if (server_body || http->ssl)
820 p = re_process_buffer(csp);
821 hdr = sed(server_patterns, add_server_headers, csp);
823 if ((write_socket(csp->cfd, hdr, n) != n)
824 || (write_socket(csp->cfd, p, csp->content_length) != csp->content_length))
826 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
832 #endif /* def PCRS */
833 break; /* "game over, man" */
836 /* Let's pretend the server just sent us a blank line. */
837 n = sprintf(buf, "\r\n");
840 * Now, let the normal header parsing algorithm below do its
841 * job. If it fails, we'll exit instead of continuing.
848 * If this is an SSL connection or we're in the body
849 * of the server document, just write it to the client.
852 if (server_body || http->ssl)
857 add_to_iob(csp, buf, n); /* Buffer the body for filtering */
860 #endif /* def PCRS */
863 if (write_socket(csp->cfd, buf, n) != n)
865 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
874 /* we're still looking for the end of the
875 * server's header ... (does that make header
876 * parsing an "out of body experience" ?
879 /* buffer up the data we just read */
880 add_to_iob(csp, buf, n);
882 /* get header lines from the iob */
884 while ((p = get_header(csp)))
888 /* see following note */
891 enlist(csp->headers, p);
895 /* NOTE: there are no "empty" headers so
896 * if the pointer `p' is not NULL we must
897 * assume that we reached the end of the
898 * buffer before we hit the end of the header.
905 /* Well, we tried our MS IIS/5
906 * hack and it didn't work.
907 * The header is incomplete
908 * and there isn't anything
909 * we can do about it.
915 /* Since we have to wait for
916 * more from the server before
917 * we can parse the headers
918 * we just continue here.
924 /* we have now received the entire header.
925 * filter it and send the result to the client
928 hdr = sed(server_patterns, add_server_headers, csp);
931 /* write the server's (modified) header to
932 * the client (along with anything else that
933 * may be in the buffer)
937 /* Start blocking popups if appropriate. */
939 if (csp->is_text && /* It's a text / * MIME-Type */
940 !http->ssl && /* We talk plaintext */
941 block_popups) /* Policy allows */
943 block_popups_now = 1;
946 #endif /* def KILLPOPUPS */
949 /* Start re_filtering this if appropriate. */
951 if (csp->is_text && /* It's a text / * MIME-Type */
952 !http->ssl && /* We talk plaintext */
953 pcrs_filter) /* Policy allows */
958 /* This next line is a little ugly, but it simplifies the if statement below. */
959 /* Basically if using PCRS, we want the OR condition to require "!filtering" */
960 #define NOT_FILTERING_AND !filtering &&
962 #else /* not def PCRS */
964 #define NOT_FILTERING_AND
966 #endif /* def PCRS */
968 if (NOT_FILTERING_AND ((write_socket(csp->cfd, hdr, n) != n)
969 || (n = flush_socket(csp->cfd, csp) < 0)))
971 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
973 /* the write failed, so don't bother
974 * mentioning it to the client...
975 * it probably can't hear us anyway.
981 NOT_FILTERING_AND (byte_count += n);
983 /* we're finished with the server's header */
988 /* If this was a MS IIS/5 hack then it means
989 * the server has already closed the
990 * connection. Nothing more to read. Time
1001 return; /* huh? we should never get here */
1004 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1005 csp->ip_addr_str, http->cmd, byte_count);
1009 /*********************************************************************
1013 * Description : This is little more than chat. We only "serve" to
1014 * to close any socket that chat may have opened.
1017 * 1 : csp = Current client state (buffers, headers, etc...)
1021 *********************************************************************/
1023 void serve(struct client_state *csp)
1024 #else /* ifndef AMIGA */
1025 static void serve(struct client_state *csp)
1026 #endif /* def AMIGA */
1029 close_socket(csp->cfd);
1033 close_socket(csp->sfd);
1042 /*********************************************************************
1044 * Function : server_thread
1046 * Description : We only exist to call `serve' in a threaded environment.
1049 * 1 : data = Current client state (buffers, headers, etc...)
1051 * Returns : Always 0.
1053 *********************************************************************/
1054 static int32 server_thread(void *data)
1056 serve((struct client_state *) data);
1063 /*********************************************************************
1067 * Description : Load the config file and start the listen loop.
1068 * This function is a lot more *sane* with the `load_config'
1069 * and `listen_loop' functions; although it stills does
1070 * a *little* too much for my taste.
1073 * 1 : argc = Number of parameters (including $0).
1074 * 2 : argv = Array of (char *)'s to the parameters.
1076 * Returns : 1 if : can't open config file, unrecognized directive,
1077 * stats requested in multi-thread mode, can't open the
1078 * log file, can't open the jar file, listen port is invalid,
1079 * any load fails, and can't bind port.
1081 * Else main never returns, the process must be signaled
1082 * to terminate execution. Or, on Windows, use the
1083 * "File", "Exit" menu option.
1085 *********************************************************************/
1087 int _main(int argc, const char *argv[])
1089 int main(int argc, const char *argv[])
1094 "AmiTCP:db/junkbuster/config"
1095 #elif !defined(_WIN32)
1102 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1103 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1105 printf("JunkBuster proxy version " VERSION ".\n\n"
1106 "Usage: %s [configfile]\n\n"
1107 "See " HOME_PAGE_URL " for details.\n"
1108 "This program is distributed under the GNU GPL, version 2 or later.\n",
1112 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1114 printf(VERSION "\n");
1117 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1124 configfile = argv[1];
1131 #elif defined(_WIN32)
1137 signal(SIGPIPE, SIG_IGN);
1138 signal(SIGCHLD, SIG_IGN);
1140 #else /* ifdef _WIN32 */
1141 # ifdef _WIN_CONSOLE
1143 * We *are* in a windows console app.
1144 * Print a verbose messages about FAQ's and such
1146 printf(win32_blurb);
1147 # endif /* def _WIN_CONSOLE */
1148 #endif /* def _WIN32 */
1159 /*********************************************************************
1161 * Function : listen_loop
1163 * Description : bind the listen port and enter a "FOREVER" listening loop.
1169 *********************************************************************/
1170 static void listen_loop(void)
1172 struct client_state *csp = NULL;
1174 struct configuration_spec * config;
1176 config = load_config();
1178 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1179 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1181 bfd = bind_port(config->haddr, config->hport);
1185 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1186 "- There may be another junkbuster or some other "
1187 "proxy running on port %d",
1188 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1189 config->hport, config->hport
1191 /* shouldn't get here */
1195 config->need_bind = 0;
1200 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1201 while (waitpid(-1, NULL, WNOHANG) > 0)
1203 /* zombie children */
1205 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1208 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1210 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1214 memset(csp, '\0', sizeof(*csp));
1219 csp->config = config = load_config();
1221 if ( config->need_bind )
1224 * Since we were listening to the "old port", we will not see
1225 * a "listen" param change until the next IJB request. So, at
1226 * least 1 more request must be made for us to find the new
1227 * setting. I am simply closing the old socket and binding the
1230 * Which-ever is correct, we will serve 1 more page via the
1231 * old settings. This should probably be a "show-proxy-args"
1232 * request. This should not be a so common of an operation
1233 * that this will hurt people's feelings.
1238 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1239 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1240 bfd = bind_port(config->haddr, config->hport);
1244 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1245 "- There may be another junkbuster or some other "
1246 "proxy running on port %d",
1247 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1248 config->hport, config->hport
1250 /* shouldn't get here */
1254 config->need_bind = 0;
1257 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1259 if (!accept_connection(csp, bfd))
1261 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1274 log_error(LOG_LEVEL_CONNECT, "OK");
1278 /* by haroon - most of credit to srt19170 */
1279 csp->toggled_on = g_bToggleIJB;
1282 if (run_loader(csp))
1284 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1285 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1288 if (block_acl(NULL,csp))
1290 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1291 close_socket(csp->cfd);
1296 /* add it to the list of clients */
1297 csp->next = clients->next;
1298 clients->next = csp;
1300 if (config->multi_threaded)
1304 /* this is a switch () statment in the C preprocessor - ugh */
1305 #undef SELECTED_ONE_OPTION
1307 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1308 #define SELECTED_ONE_OPTION
1309 child_id = _beginthread(
1315 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1316 #define SELECTED_ONE_OPTION
1318 thread_id tid = spawn_thread
1319 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1321 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1323 child_id = (int) tid;
1332 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1333 #define SELECTED_ONE_OPTION
1334 csp->cfd = ReleaseSocket(csp->cfd, -1);
1335 if((child_id = (int)CreateNewProcTags(
1336 NP_Entry, (ULONG)server_thread,
1337 NP_Output, Output(),
1338 NP_CloseOutput, FALSE,
1339 NP_Name, (ULONG)"junkbuster child",
1340 NP_StackSize, 200*1024,
1344 ((struct Task *)child_id)->tc_UserData = csp;
1345 Signal((struct Task *)child_id, SIGF_SINGLE);
1350 #if !defined(SELECTED_ONE_OPTION)
1354 #undef SELECTED_ONE_OPTION
1355 /* end of cpp switch () */
1357 if (child_id < 0) /* failed */
1359 char buf[BUFFER_SIZE];
1361 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1363 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1365 write_socket(csp->cfd, buf, strlen(buf));
1366 close_socket(csp->cfd);
1372 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1373 /* This block is only needed when using fork().
1374 * When using threads, the server thread was
1375 * created and run by the call to _beginthread().
1377 if (child_id == 0) /* child */
1385 /* in a fork()'d environment, the parent's
1386 * copy of the client socket and the CSP
1390 #if !defined(_WIN32) && defined(__CYGWIN__)
1392 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1393 close_socket(csp->cfd);
1396 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */