1 const char jcc_rcs[] = "$Id: jcc.c,v 1.27 2001/07/19 19:09:47 haroon 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.27 2001/07/19 19:09:47 haroon
37 * - Added code to take care of the situation where while processing the first
38 * server response (which includes the server header), after finding the end
39 * of the headers we were not looking past the end of the headers for
40 * content modification. I enabled it for filter_popups.
41 * Someone else should look to see if other similar operations should be
42 * done to the discarded portion of the buffer.
44 * Note 2001/07/20: No, the other content modification mechanisms will process
45 * the whole iob later anyway. --oes
47 * Revision 1.26 2001/07/18 12:31:36 oes
50 * Revision 1.25 2001/07/15 19:43:49 jongfoster
51 * Supports POSIX threads.
52 * Also removed some unused #includes.
54 * Revision 1.24 2001/07/13 14:00:40 oes
55 * - Generic content modification scheme:
56 * Each feature has its own applicability flag that is set
57 * from csp->action->flags.
58 * Replaced the "filtering" int flag , by a function pointer
59 * "content_filter" to the function that will do the content
60 * modification. If it is != NULL, the document will be buffered
61 * and processed through *content_filter, which must set
62 * csp->content_length and return a modified copy of the body
63 * or return NULL (on failiure).
64 * - Changed csp->is_text to the more generic bitmap csp->content_type
65 * which can currently take the valued CT_TEXT or CT_GIF
67 * - Removed all #ifdef PCRS
69 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
70 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
71 * the `block_acl' call. This prevents a compilation error when the user
72 * does not wish to use the "ACL" feature.
74 * Revision 1.22 2001/06/29 21:45:41 oes
75 * Indentation, CRLF->LF, Tab-> Space
77 * Revision 1.21 2001/06/29 13:29:36 oes
78 * - Cleaned up, improved comments
79 * - Unified all possible interceptors (CGI,
80 * block, trust, fast_redirect) in one
81 * place, with one (CGI) answer generation
82 * mechansim. Much clearer now.
83 * - Removed the GIF image generation, which
84 * is now done in filters.c:block_url()
85 * - Made error conditions like domain lookup
86 * failiure or (various) problems while talking
87 * to the server use cgi.c:error_response()
88 * instead of generating HTML/HTTP in chat() (yuck!)
89 * - Removed logentry from cancelled commit
91 * Revision 1.20 2001/06/09 10:55:28 jongfoster
92 * Changing BUFSIZ ==> BUFFER_SIZE
94 * Revision 1.19 2001/06/07 23:12:52 jongfoster
95 * Replacing function pointer in struct gateway with a directly
96 * called function forwarded_connect().
97 * Replacing struct gateway with struct forward_spec
99 * Revision 1.18 2001/06/03 19:12:16 oes
100 * introduced new cgi handling
102 * Revision 1.17 2001/06/01 20:07:23 jongfoster
103 * Now uses action +image-blocker{} rather than config->tinygif
105 * Revision 1.16 2001/06/01 18:49:17 jongfoster
106 * Replaced "list_share" with "list" - the tiny memory gain was not
107 * worth the extra complexity.
109 * Revision 1.15 2001/05/31 21:24:47 jongfoster
110 * Changed "permission" to "action" throughout.
111 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
112 * Moved vanilla wafer check into chat(), since we must now
113 * decide whether or not to add it based on the URL.
115 * Revision 1.14 2001/05/29 20:14:01 joergs
116 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
119 * Revision 1.13 2001/05/29 09:50:24 jongfoster
120 * Unified blocklist/imagelist/permissionslist.
121 * File format is still under discussion, but the internal changes
124 * Also modified interceptor behaviour:
125 * - We now intercept all URLs beginning with one of the following
126 * prefixes (and *only* these prefixes):
128 * * http://ijbswa.sf.net/config/
129 * * http://ijbswa.sourceforge.net/config/
130 * - New interceptors "home page" - go to http://i.j.b/ to see it.
131 * - Internal changes so that intercepted and fast redirect pages
132 * are not replaced with an image.
133 * - Interceptors now have the option to send a binary page direct
134 * to the client. (i.e. ijb-send-banner uses this)
135 * - Implemented show-url-info interceptor. (Which is why I needed
136 * the above interceptors changes - a typical URL is
137 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
138 * The previous mechanism would not have intercepted that, and
139 * if it had been intercepted then it then it would have replaced
142 * Revision 1.12 2001/05/27 22:17:04 oes
144 * - re_process_buffer no longer writes the modified buffer
145 * to the client, which was very ugly. It now returns the
146 * buffer, which it is then written by chat.
148 * - content_length now adjusts the Content-Length: header
149 * for modified documents rather than crunch()ing it.
150 * (Length info in csp->content_length, which is 0 for
151 * unmodified documents)
153 * - For this to work, sed() is called twice when filtering.
155 * Revision 1.11 2001/05/26 17:27:53 jongfoster
156 * Added support for CLF and fixed LOG_LEVEL_LOG.
157 * Also did CRLF->LF fix of my previous patch.
159 * Revision 1.10 2001/05/26 15:26:15 jongfoster
160 * ACL feature now provides more security by immediately dropping
161 * connections from untrusted hosts.
163 * Revision 1.9 2001/05/26 00:28:36 jongfoster
164 * Automatic reloading of config file.
165 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
166 * Most of the global variables have been moved to a new
167 * struct configuration_spec, accessed through csp->config->globalname
168 * Most of the globals remaining are used by the Win32 GUI.
170 * Revision 1.8 2001/05/25 22:43:18 jongfoster
171 * Fixing minor memory leak and buffer overflow.
173 * Revision 1.7 2001/05/25 22:34:30 jongfoster
176 * Revision 1.6 2001/05/23 00:13:58 joergs
177 * AmigaOS support fixed.
179 * Revision 1.5 2001/05/22 18:46:04 oes
181 * - Enabled filtering banners by size rather than URL
182 * by adding patterns that replace all standard banner
183 * sizes with the "Junkbuster" gif to the re_filterfile
185 * - Enabled filtering WebBugs by providing a pattern
186 * which kills all 1x1 images
188 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
189 * which is selected by the (nonstandard and therefore
190 * capital) letter 'U' in the option string.
191 * It causes the quantifiers to be ungreedy by default.
192 * Appending a ? turns back to greedy (!).
194 * - Added a new interceptor ijb-send-banner, which
195 * sends back the "Junkbuster" gif. Without imagelist or
196 * MSIE detection support, or if tinygif = 1, or the
197 * URL isn't recognized as an imageurl, a lame HTML
198 * explanation is sent instead.
200 * - Added new feature, which permits blocking remote
201 * script redirects and firing back a local redirect
203 * The feature is conditionally compiled, i.e. it
204 * can be disabled with --disable-fast-redirects,
205 * plus it must be activated by a "fast-redirects"
206 * line in the config file, has its own log level
207 * and of course wants to be displayed by show-proxy-args
208 * Note: Boy, all the #ifdefs in 1001 locations and
209 * all the fumbling with configure.in and acconfig.h
210 * were *way* more work than the feature itself :-(
212 * - Because a generic redirect template was needed for
213 * this, tinygif = 3 now uses the same.
215 * - Moved GIFs, and other static HTTP response templates
220 * - Removed some >400 CRs again (Jon, you really worked
223 * Revision 1.4 2001/05/21 19:34:01 jongfoster
224 * Made failure to bind() a fatal error.
226 * Revision 1.3 2001/05/20 01:21:20 jongfoster
227 * Version 2.9.4 checkin.
228 * - Merged popupfile and cookiefile, and added control over PCRS
229 * filtering, in new "permissionsfile".
230 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
231 * file error you now get a message box (in the Win32 GUI) rather
232 * than the program exiting with no explanation.
233 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
235 * - Removed tabs from "config"
236 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
237 * - Bumped up version number.
239 * Revision 1.2 2001/05/17 22:34:44 oes
240 * - Added hint on GIF char array generation to jcc.c
241 * - Cleaned CRLF's from the sources and related files
242 * - Repaired logging for REF and FRC
244 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
245 * Initial import of version 2.9.3 source tree
248 *********************************************************************/
254 #include <sys/types.h>
261 #ifdef FEATURE_PTHREAD
263 #endif /* def FEATURE_PTHREAD */
266 # ifndef FEATURE_PTHREAD
267 # include <windows.h>
268 # include <process.h>
269 # endif /* ndef FEATURE_PTHREAD */
272 # ifndef _WIN_CONSOLE
274 # endif /* ndef _WIN_CONSOLE */
276 #else /* ifndef _WIN32 */
279 # include <sys/time.h>
280 # include <sys/wait.h>
281 # include <sys/stat.h>
285 # include <socket.h> /* BeOS has select() for sockets only. */
286 # include <OS.h> /* declarations for threads and stuff. */
300 #include "showargs.h"
302 #include "killpopup.h"
303 #include "miscutil.h"
305 #include "jbsockets.h"
310 const char jcc_h_rcs[] = JCC_H_VERSION;
311 const char project_h_rcs[] = PROJECT_H_VERSION;
313 struct client_state clients[1];
314 struct file_list files[1];
317 int urls_read = 0; /* total nr of urls read inc rejected */
318 int urls_rejected = 0; /* total nr of urls rejected */
319 #endif /* def STATISTICS */
322 static void listen_loop(void);
323 static void chat(struct client_state *csp);
325 void serve(struct client_state *csp);
326 #else /* ifndef AMIGA */
327 static void serve(struct client_state *csp);
328 #endif /* def AMIGA */
331 static int32 server_thread(void *data);
332 #endif /* def __BEOS__ */
335 #define sleep(N) Sleep(((N) * 1000))
339 /* The vanilla wafer. */
340 static const char VANILLA_WAFER[] =
341 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
342 "Do_not_send_me_any_copyrighted_information_other_than_the_"
343 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
344 "In_particular_do_not_send_me_any_cookies_that_"
345 "are_subject_to_a_claim_of_copyright_by_anybody._"
346 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
347 "(copyright_or_otherwise)_applying_to_any_cookie._";
350 /*********************************************************************
354 * Description : Once a connection to the client has been accepted,
355 * this function is called (via serve()) to handle the
356 * main business of the communication. When this
357 * function returns, the caller must close the client
361 * 1 : csp = Current client state (buffers, headers, etc...)
363 * Returns : On success, the number of bytes written are returned (zero
364 * indicates nothing was written). On error, -1 is returned,
365 * and errno is set appropriately. If count is zero and the
366 * file descriptor refers to a regular file, 0 will be
367 * returned without causing any other effect. For a special
368 * file, the results are not portable.
370 *********************************************************************/
371 static void chat(struct client_state *csp)
374 * This next lines are a little ugly, but they simplifies the if statements below.
375 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
376 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
379 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
380 #else /* ifndef TOGGLE */
381 # define IS_TOGGLED_ON_AND
382 #endif /* ndef TOGGLE */
384 # define IS_NOT_FORCED_AND (!csp->force) &&
385 #else /* ifndef FORCE_LOAD */
386 # define IS_NOT_FORCED_AND
387 #endif /* def FORCE_LOAD */
389 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
391 char buf[BUFFER_SIZE];
395 int n, maxfd, server_body;
396 int ms_iis5_hack = 0;
398 const struct forward_spec * fwd;
399 struct http_request *http;
401 int block_popups; /* bool, 1==will block popups */
402 int block_popups_now = 0; /* bool, 1==currently blocking popups */
403 #endif /* def KILLPOPUPS */
405 int pcrs_filter; /* bool, 1==will filter through pcrs */
406 int gif_deanimate; /* bool, 1==will deanimate gifs */
408 /* Function that does the content filtering for the current request */
409 char *(*content_filter)() = NULL;
411 /* Skeleton for HTTP response, if we should intercept the request */
412 struct http_response *rsp;
417 * Read the client's request. Note that since we're not using select() we
418 * could get blocked here if a client connected, then didn't say anything!
423 n = read_socket(csp->cfd, buf, sizeof(buf));
425 if (n <= 0) break; /* error! */
427 add_to_iob(csp, buf, n);
429 req = get_header(csp);
433 break; /* no HTTP request! */
438 continue; /* more to come! */
442 /* If this request contains the FORCE_PREFIX,
443 * better get rid of it now and set the force flag --oes
446 if (strstr(req, FORCE_PREFIX))
448 strclean(req, FORCE_PREFIX);
449 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
456 #endif /* def FORCE_LOAD */
458 parse_http_request(req, http, csp);
463 if (http->cmd == NULL)
465 strcpy(buf, CHEADER);
466 write_socket(csp->cfd, buf, strlen(buf));
468 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
473 /* decide how to route the HTTP request */
475 if ((fwd = forward_url(http, csp)) == NULL)
477 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
478 /* Never get here - LOG_LEVEL_FATAL causes program exit */
481 /* build the http request to send to the server
482 * we have to do one of the following:
484 * create = use the original HTTP request to create a new
485 * HTTP request that has only the path component
486 * without the http://domainspec
487 * pass = pass the original HTTP request unchanged
489 * drop = drop the HTTP request
494 * +--------+--------+
496 * 0 | create | drop |
498 * Forwarding +--------+--------+
502 * +--------+--------+
506 if (fwd->forward_host)
508 /* if forwarding, just pass the request as is */
509 enlist(csp->headers, http->cmd);
515 /* otherwise elide the host information from the url */
517 p = strsav(p, http->gpc);
519 p = strsav(p, http->path);
521 p = strsav(p, http->ver);
522 enlist(csp->headers, p);
527 /* decide what we're to do with cookies */
530 if (!csp->toggled_on)
532 /* Most compatible set of actions (i.e. none) */
533 init_current_action(csp->action);
536 #endif /* ndef TOGGLE */
538 url_actions(http, csp);
543 * If we're logging cookies in a cookie jar, and the user has not
544 * supplied any wafers, and the user has not told us to suppress the
545 * vanilla wafer, then send the vanilla wafer.
547 if ((csp->config->jarfile != NULL)
548 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
549 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
551 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
553 #endif /* def JAR_FILES */
556 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
557 #endif /* def KILLPOPUPS */
559 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
560 ((csp->action->flags & ACTION_FILTER) != 0);
562 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
564 /* grab the rest of the client's headers */
568 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
570 n = read_socket(csp->cfd, buf, sizeof(buf));
573 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
576 add_to_iob(csp, buf, n);
580 if (p == NULL) break;
582 enlist(csp->headers, p);
586 /* We have a request. */
588 hdr = sed(client_patterns, add_client_headers, csp);
589 destroy_list(csp->headers);
592 * Now, check to see if we need to intercept it, i.e.
597 /* a CGI call was detected and answered */
598 (NULL != (rsp = dispatch_cgi(csp)))
600 /* or we are enabled and... */
603 /* ..the request was blocked */
604 ( NULL != (rsp = block_url(csp)))
608 || ( NULL != (rsp = trust_url(csp)))
611 /* ..or a fast redirect kicked in */
612 #ifdef FAST_REDIRECTS
613 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
614 (NULL != (rsp = redirect_url(csp))))
615 #endif /* def FAST_REDIRECTS */
619 /* Write the answer to the client */
620 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
621 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
623 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
627 /* Count as a rejected request */
629 #endif /* def STATISTICS */
631 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
632 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
633 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
635 /* Clean up and return */
636 free_http_response(rsp);
641 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
643 if (fwd->forward_host)
645 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
646 fwd->forward_host, fwd->forward_port, http->hostport);
650 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
653 /* here we connect to the server, gateway, or the forwarder */
655 csp->sfd = forwarded_connect(fwd, http, csp);
659 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
664 rsp = error_response(csp, "no-such-domain", errno);
666 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
667 csp->ip_addr_str, http->cmd);
671 rsp = error_response(csp, "connect-failed", errno);
673 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
674 csp->ip_addr_str, http->cmd);
677 /* Write the answer to the client */
680 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
681 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
683 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
687 free_http_response(rsp);
692 log_error(LOG_LEVEL_CONNECT, "OK");
694 if (fwd->forward_host || (http->ssl == 0))
696 /* write the client's (modified) header to the server
697 * (along with anything else that may be in the buffer)
702 if ((write_socket(csp->sfd, hdr, n) != n)
703 || (flush_socket(csp->sfd, csp ) < 0))
705 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
708 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
709 csp->ip_addr_str, http->cmd);
711 rsp = error_response(csp, "connect-failed", errno);
715 if ((write_socket(csp->cfd, rsp->head, n) != n)
716 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
718 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
722 free_http_response(rsp);
730 * We're running an SSL tunnel and we're not forwarding,
731 * so just send the "connect succeeded" message to the
732 * client, flush the rest, and get out of the way.
734 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
735 csp->ip_addr_str, http->cmd);
737 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
745 /* we're finished with the client's header */
748 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
750 /* pass data between the client and server
751 * until one or the other shuts down the connection.
760 FD_SET(csp->cfd, &rfds);
761 FD_SET(csp->sfd, &rfds);
763 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
767 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
771 /* this is the body of the browser's request
772 * just read it and write it.
775 if (FD_ISSET(csp->cfd, &rfds))
777 n = read_socket(csp->cfd, buf, sizeof(buf));
781 break; /* "game over, man" */
784 if (write_socket(csp->sfd, buf, n) != n)
786 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
793 * The server wants to talk. It could be the header or the body.
794 * If `hdr' is null, then it's the header otherwise it's the body.
795 * FIXME: Does `hdr' really mean `host'? No.
799 if (FD_ISSET(csp->sfd, &rfds))
802 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
806 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
808 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
809 csp->ip_addr_str, http->cmd);
811 rsp = error_response(csp, "connect-failed", errno);
815 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
816 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
818 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
822 free_http_response(rsp);
826 /* Add a trailing zero. This lets filter_popups
827 * use string operations.
832 /* Filter the popups on this read. */
833 if (block_popups_now)
835 filter_popups(buf, n);
837 #endif /* def KILLPOPUPS */
839 /* Normally, this would indicate that we've read
840 * as much as the server has sent us and we can
841 * close the client connection. However, Microsoft
842 * in its wisdom has released IIS/5 with a bug that
843 * prevents it from sending the trailing \r\n in
844 * a 302 redirect header (and possibly other headers).
845 * To work around this if we've haven't parsed
846 * a full header we'll append a trailing \r\n
847 * and see if this now generates a valid one.
849 * This hack shouldn't have any impacts. If we've
850 * already transmitted the header or if this is a
851 * SSL connection, then we won't bother with this
852 * hack. So we only work on partially received
853 * headers. If we append a \r\n and this still
854 * doesn't generate a valid header, then we won't
855 * transmit anything to the client.
860 if (server_body || http->ssl)
863 * If we have been buffering up the document,
864 * now is the time to apply content modification
865 * and send the result to the client.
870 * If the content filter fails, use the original
872 * (see p != NULL ? p : csp->iob->cur below)
874 if (NULL == (p = (*content_filter)(csp)))
876 csp->content_length = csp->iob->eod - csp->iob->cur;
879 hdr = sed(server_patterns, add_server_headers, csp);
882 if ((write_socket(csp->cfd, hdr, n) != n)
883 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != csp->content_length))
885 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
893 break; /* "game over, man" */
897 * This is NOT the body, so
898 * Let's pretend the server just sent us a blank line.
900 n = sprintf(buf, "\r\n");
903 * Now, let the normal header parsing algorithm below do its
904 * job. If it fails, we'll exit instead of continuing.
911 * If this is an SSL connection or we're in the body
912 * of the server document, just write it to the client,
913 * unless we need to buffer the body for later content-filtering
916 if (server_body || http->ssl)
920 add_to_iob(csp, buf, n);
924 if (write_socket(csp->cfd, buf, n) != n)
926 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
935 /* we're still looking for the end of the
936 * server's header ... (does that make header
937 * parsing an "out of body experience" ?
940 /* buffer up the data we just read */
941 add_to_iob(csp, buf, n);
943 /* get header lines from the iob */
945 while ((p = get_header(csp)))
949 /* see following note */
952 enlist(csp->headers, p);
956 /* NOTE: there are no "empty" headers so
957 * if the pointer `p' is not NULL we must
958 * assume that we reached the end of the
959 * buffer before we hit the end of the header.
966 /* Well, we tried our MS IIS/5
967 * hack and it didn't work.
968 * The header is incomplete
969 * and there isn't anything
970 * we can do about it.
976 /* Since we have to wait for
977 * more from the server before
978 * we can parse the headers
979 * we just continue here.
985 /* we have now received the entire header.
986 * filter it and send the result to the client
989 hdr = sed(server_patterns, add_server_headers, csp);
992 /* write the server's (modified) header to
993 * the client (along with anything else that
994 * may be in the buffer)
998 /* Start blocking popups if appropriate. */
1000 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1001 !http->ssl && /* We talk plaintext */
1002 block_popups) /* Policy allows */
1004 block_popups_now = 1;
1006 * Filter the part of the body that came in the same read
1007 * as the last headers:
1009 filter_popups(csp->iob->cur, csp->iob->eod - csp->iob->cur);
1012 #endif /* def KILLPOPUPS */
1014 /* Buffer and pcrs filter this if appropriate. */
1016 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1017 !http->ssl && /* We talk plaintext */
1018 pcrs_filter) /* Policy allows */
1020 content_filter = pcrs_filter_response;
1023 /* Buffer and gif_deanimate this if appropriate. */
1025 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1026 !http->ssl && /* We talk plaintext */
1027 gif_deanimate) /* Policy allows */
1029 content_filter = gif_deanimate_response;
1034 * Only write if we're not buffering for content modification
1036 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1037 || (n = flush_socket(csp->cfd, csp) < 0)))
1039 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1041 /* the write failed, so don't bother
1042 * mentioning it to the client...
1043 * it probably can't hear us anyway.
1049 !content_filter && (byte_count += n);
1051 /* we're finished with the server's header */
1056 /* If this was a MS IIS/5 hack then it means
1057 * the server has already closed the
1058 * connection. Nothing more to read. Time
1069 return; /* huh? we should never get here */
1072 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1073 csp->ip_addr_str, http->cmd, byte_count);
1077 /*********************************************************************
1081 * Description : This is little more than chat. We only "serve" to
1082 * to close any socket that chat may have opened.
1085 * 1 : csp = Current client state (buffers, headers, etc...)
1089 *********************************************************************/
1091 void serve(struct client_state *csp)
1092 #else /* ifndef AMIGA */
1093 static void serve(struct client_state *csp)
1094 #endif /* def AMIGA */
1097 close_socket(csp->cfd);
1101 close_socket(csp->sfd);
1110 /*********************************************************************
1112 * Function : server_thread
1114 * Description : We only exist to call `serve' in a threaded environment.
1117 * 1 : data = Current client state (buffers, headers, etc...)
1119 * Returns : Always 0.
1121 *********************************************************************/
1122 static int32 server_thread(void *data)
1124 serve((struct client_state *) data);
1131 /*********************************************************************
1135 * Description : Load the config file and start the listen loop.
1136 * This function is a lot more *sane* with the `load_config'
1137 * and `listen_loop' functions; although it stills does
1138 * a *little* too much for my taste.
1141 * 1 : argc = Number of parameters (including $0).
1142 * 2 : argv = Array of (char *)'s to the parameters.
1144 * Returns : 1 if : can't open config file, unrecognized directive,
1145 * stats requested in multi-thread mode, can't open the
1146 * log file, can't open the jar file, listen port is invalid,
1147 * any load fails, and can't bind port.
1149 * Else main never returns, the process must be signaled
1150 * to terminate execution. Or, on Windows, use the
1151 * "File", "Exit" menu option.
1153 *********************************************************************/
1155 int _main(int argc, const char *argv[])
1157 int main(int argc, const char *argv[])
1162 "AmiTCP:db/junkbuster/config"
1163 #elif !defined(_WIN32)
1170 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1171 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1173 printf("JunkBuster proxy version " VERSION ".\n\n"
1174 "Usage: %s [configfile]\n\n"
1175 "See " HOME_PAGE_URL " for details.\n"
1176 "This program is distributed under the GNU GPL, version 2 or later.\n",
1180 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1182 printf(VERSION "\n");
1185 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1192 configfile = argv[1];
1199 #elif defined(_WIN32)
1205 signal(SIGPIPE, SIG_IGN);
1206 signal(SIGCHLD, SIG_IGN);
1208 #else /* ifdef _WIN32 */
1209 # ifdef _WIN_CONSOLE
1211 * We *are* in a windows console app.
1212 * Print a verbose messages about FAQ's and such
1214 printf(win32_blurb);
1215 # endif /* def _WIN_CONSOLE */
1216 #endif /* def _WIN32 */
1227 /*********************************************************************
1229 * Function : listen_loop
1231 * Description : bind the listen port and enter a "FOREVER" listening loop.
1237 *********************************************************************/
1238 static void listen_loop(void)
1240 struct client_state *csp = NULL;
1242 struct configuration_spec * config;
1244 config = load_config();
1246 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1247 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1249 bfd = bind_port(config->haddr, config->hport);
1253 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1254 "- There may be another junkbuster or some other "
1255 "proxy running on port %d",
1256 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1257 config->hport, config->hport
1259 /* shouldn't get here */
1263 config->need_bind = 0;
1268 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1269 while (waitpid(-1, NULL, WNOHANG) > 0)
1271 /* zombie children */
1273 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1276 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1278 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1282 memset(csp, '\0', sizeof(*csp));
1287 csp->config = config = load_config();
1289 if ( config->need_bind )
1292 * Since we were listening to the "old port", we will not see
1293 * a "listen" param change until the next IJB request. So, at
1294 * least 1 more request must be made for us to find the new
1295 * setting. I am simply closing the old socket and binding the
1298 * Which-ever is correct, we will serve 1 more page via the
1299 * old settings. This should probably be a "show-proxy-args"
1300 * request. This should not be a so common of an operation
1301 * that this will hurt people's feelings.
1306 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1307 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1308 bfd = bind_port(config->haddr, config->hport);
1312 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1313 "- There may be another junkbuster or some other "
1314 "proxy running on port %d",
1315 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1316 config->hport, config->hport
1318 /* shouldn't get here */
1322 config->need_bind = 0;
1325 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1327 if (!accept_connection(csp, bfd))
1329 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1342 log_error(LOG_LEVEL_CONNECT, "OK");
1346 /* by haroon - most of credit to srt19170 */
1347 csp->toggled_on = g_bToggleIJB;
1350 if (run_loader(csp))
1352 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1353 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1357 if (block_acl(NULL,csp))
1359 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1360 close_socket(csp->cfd);
1364 #endif /* def ACL_FILES */
1366 /* add it to the list of clients */
1367 csp->next = clients->next;
1368 clients->next = csp;
1370 if (config->multi_threaded)
1374 /* this is a switch () statment in the C preprocessor - ugh */
1375 #undef SELECTED_ONE_OPTION
1377 /* Use Pthreads in preference to native code */
1378 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1379 #define SELECTED_ONE_OPTION
1381 pthread_t the_thread;
1382 pthread_attr_t attrs;
1384 pthread_attr_init(&attrs);
1385 child_id = (pthread_create(&the_thread, &attrs,
1386 (void*)serve, csp) ? -1 : 0);
1387 pthread_attr_destroy(&attrs);
1391 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1392 #define SELECTED_ONE_OPTION
1393 child_id = _beginthread(
1399 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1400 #define SELECTED_ONE_OPTION
1402 thread_id tid = spawn_thread
1403 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1405 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1407 child_id = (int) tid;
1416 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1417 #define SELECTED_ONE_OPTION
1418 csp->cfd = ReleaseSocket(csp->cfd, -1);
1419 if((child_id = (int)CreateNewProcTags(
1420 NP_Entry, (ULONG)server_thread,
1421 NP_Output, Output(),
1422 NP_CloseOutput, FALSE,
1423 NP_Name, (ULONG)"junkbuster child",
1424 NP_StackSize, 200*1024,
1428 ((struct Task *)child_id)->tc_UserData = csp;
1429 Signal((struct Task *)child_id, SIGF_SINGLE);
1434 #if !defined(SELECTED_ONE_OPTION)
1437 /* This block is only needed when using fork().
1438 * When using threads, the server thread was
1439 * created and run by the call to _beginthread().
1441 if (child_id == 0) /* child */
1447 else if (child_id > 0) /* parent */
1449 /* in a fork()'d environment, the parent's
1450 * copy of the client socket and the CSP
1454 #if !defined(_WIN32) && defined(__CYGWIN__)
1456 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1457 close_socket(csp->cfd);
1462 #undef SELECTED_ONE_OPTION
1463 /* end of cpp switch () */
1465 if (child_id < 0) /* failed */
1467 char buf[BUFFER_SIZE];
1469 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1471 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1473 write_socket(csp->cfd, buf, strlen(buf));
1474 close_socket(csp->cfd);