1 const char jcc_rcs[] = "$Id: jcc.c,v 1.32 2001/07/29 18:47:05 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.32 2001/07/29 18:47:05 jongfoster
37 * Adding missing #include "loadcfg.h"
39 * Revision 1.31 2001/07/29 12:17:48 oes
40 * Applied pthread fix by Paul Lieverse
42 * Revision 1.30 2001/07/25 22:57:13 jongfoster
43 * __BEOS__ no longer overrides FEATURE_PTHREAD.
44 * This is because FEATURE_PTHREAD will soon be widely used, so I
45 * want to keep it simple.
47 * Revision 1.29 2001/07/24 12:47:06 oes
48 * Applied BeOS support update by Eugenia
50 * Revision 1.28 2001/07/23 13:26:12 oes
51 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
53 * Revision 1.27 2001/07/19 19:09:47 haroon
54 * - Added code to take care of the situation where while processing the first
55 * server response (which includes the server header), after finding the end
56 * of the headers we were not looking past the end of the headers for
57 * content modification. I enabled it for filter_popups.
58 * Someone else should look to see if other similar operations should be
59 * done to the discarded portion of the buffer.
61 * Note 2001/07/20: No, the other content modification mechanisms will process
62 * the whole iob later anyway. --oes
64 * Revision 1.26 2001/07/18 12:31:36 oes
67 * Revision 1.25 2001/07/15 19:43:49 jongfoster
68 * Supports POSIX threads.
69 * Also removed some unused #includes.
71 * Revision 1.24 2001/07/13 14:00:40 oes
72 * - Generic content modification scheme:
73 * Each feature has its own applicability flag that is set
74 * from csp->action->flags.
75 * Replaced the "filtering" int flag , by a function pointer
76 * "content_filter" to the function that will do the content
77 * modification. If it is != NULL, the document will be buffered
78 * and processed through *content_filter, which must set
79 * csp->content_length and return a modified copy of the body
80 * or return NULL (on failiure).
81 * - Changed csp->is_text to the more generic bitmap csp->content_type
82 * which can currently take the valued CT_TEXT or CT_GIF
84 * - Removed all #ifdef PCRS
86 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
87 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
88 * the `block_acl' call. This prevents a compilation error when the user
89 * does not wish to use the "ACL" feature.
91 * Revision 1.22 2001/06/29 21:45:41 oes
92 * Indentation, CRLF->LF, Tab-> Space
94 * Revision 1.21 2001/06/29 13:29:36 oes
95 * - Cleaned up, improved comments
96 * - Unified all possible interceptors (CGI,
97 * block, trust, fast_redirect) in one
98 * place, with one (CGI) answer generation
99 * mechansim. Much clearer now.
100 * - Removed the GIF image generation, which
101 * is now done in filters.c:block_url()
102 * - Made error conditions like domain lookup
103 * failiure or (various) problems while talking
104 * to the server use cgi.c:error_response()
105 * instead of generating HTML/HTTP in chat() (yuck!)
106 * - Removed logentry from cancelled commit
108 * Revision 1.20 2001/06/09 10:55:28 jongfoster
109 * Changing BUFSIZ ==> BUFFER_SIZE
111 * Revision 1.19 2001/06/07 23:12:52 jongfoster
112 * Replacing function pointer in struct gateway with a directly
113 * called function forwarded_connect().
114 * Replacing struct gateway with struct forward_spec
116 * Revision 1.18 2001/06/03 19:12:16 oes
117 * introduced new cgi handling
119 * Revision 1.17 2001/06/01 20:07:23 jongfoster
120 * Now uses action +image-blocker{} rather than config->tinygif
122 * Revision 1.16 2001/06/01 18:49:17 jongfoster
123 * Replaced "list_share" with "list" - the tiny memory gain was not
124 * worth the extra complexity.
126 * Revision 1.15 2001/05/31 21:24:47 jongfoster
127 * Changed "permission" to "action" throughout.
128 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
129 * Moved vanilla wafer check into chat(), since we must now
130 * decide whether or not to add it based on the URL.
132 * Revision 1.14 2001/05/29 20:14:01 joergs
133 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
136 * Revision 1.13 2001/05/29 09:50:24 jongfoster
137 * Unified blocklist/imagelist/permissionslist.
138 * File format is still under discussion, but the internal changes
141 * Also modified interceptor behaviour:
142 * - We now intercept all URLs beginning with one of the following
143 * prefixes (and *only* these prefixes):
145 * * http://ijbswa.sf.net/config/
146 * * http://ijbswa.sourceforge.net/config/
147 * - New interceptors "home page" - go to http://i.j.b/ to see it.
148 * - Internal changes so that intercepted and fast redirect pages
149 * are not replaced with an image.
150 * - Interceptors now have the option to send a binary page direct
151 * to the client. (i.e. ijb-send-banner uses this)
152 * - Implemented show-url-info interceptor. (Which is why I needed
153 * the above interceptors changes - a typical URL is
154 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
155 * The previous mechanism would not have intercepted that, and
156 * if it had been intercepted then it then it would have replaced
159 * Revision 1.12 2001/05/27 22:17:04 oes
161 * - re_process_buffer no longer writes the modified buffer
162 * to the client, which was very ugly. It now returns the
163 * buffer, which it is then written by chat.
165 * - content_length now adjusts the Content-Length: header
166 * for modified documents rather than crunch()ing it.
167 * (Length info in csp->content_length, which is 0 for
168 * unmodified documents)
170 * - For this to work, sed() is called twice when filtering.
172 * Revision 1.11 2001/05/26 17:27:53 jongfoster
173 * Added support for CLF and fixed LOG_LEVEL_LOG.
174 * Also did CRLF->LF fix of my previous patch.
176 * Revision 1.10 2001/05/26 15:26:15 jongfoster
177 * ACL feature now provides more security by immediately dropping
178 * connections from untrusted hosts.
180 * Revision 1.9 2001/05/26 00:28:36 jongfoster
181 * Automatic reloading of config file.
182 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
183 * Most of the global variables have been moved to a new
184 * struct configuration_spec, accessed through csp->config->globalname
185 * Most of the globals remaining are used by the Win32 GUI.
187 * Revision 1.8 2001/05/25 22:43:18 jongfoster
188 * Fixing minor memory leak and buffer overflow.
190 * Revision 1.7 2001/05/25 22:34:30 jongfoster
193 * Revision 1.6 2001/05/23 00:13:58 joergs
194 * AmigaOS support fixed.
196 * Revision 1.5 2001/05/22 18:46:04 oes
198 * - Enabled filtering banners by size rather than URL
199 * by adding patterns that replace all standard banner
200 * sizes with the "Junkbuster" gif to the re_filterfile
202 * - Enabled filtering WebBugs by providing a pattern
203 * which kills all 1x1 images
205 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
206 * which is selected by the (nonstandard and therefore
207 * capital) letter 'U' in the option string.
208 * It causes the quantifiers to be ungreedy by default.
209 * Appending a ? turns back to greedy (!).
211 * - Added a new interceptor ijb-send-banner, which
212 * sends back the "Junkbuster" gif. Without imagelist or
213 * MSIE detection support, or if tinygif = 1, or the
214 * URL isn't recognized as an imageurl, a lame HTML
215 * explanation is sent instead.
217 * - Added new feature, which permits blocking remote
218 * script redirects and firing back a local redirect
220 * The feature is conditionally compiled, i.e. it
221 * can be disabled with --disable-fast-redirects,
222 * plus it must be activated by a "fast-redirects"
223 * line in the config file, has its own log level
224 * and of course wants to be displayed by show-proxy-args
225 * Note: Boy, all the #ifdefs in 1001 locations and
226 * all the fumbling with configure.in and acconfig.h
227 * were *way* more work than the feature itself :-(
229 * - Because a generic redirect template was needed for
230 * this, tinygif = 3 now uses the same.
232 * - Moved GIFs, and other static HTTP response templates
237 * - Removed some >400 CRs again (Jon, you really worked
240 * Revision 1.4 2001/05/21 19:34:01 jongfoster
241 * Made failure to bind() a fatal error.
243 * Revision 1.3 2001/05/20 01:21:20 jongfoster
244 * Version 2.9.4 checkin.
245 * - Merged popupfile and cookiefile, and added control over PCRS
246 * filtering, in new "permissionsfile".
247 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
248 * file error you now get a message box (in the Win32 GUI) rather
249 * than the program exiting with no explanation.
250 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
252 * - Removed tabs from "config"
253 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
254 * - Bumped up version number.
256 * Revision 1.2 2001/05/17 22:34:44 oes
257 * - Added hint on GIF char array generation to jcc.c
258 * - Cleaned CRLF's from the sources and related files
259 * - Repaired logging for REF and FRC
261 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
262 * Initial import of version 2.9.3 source tree
265 *********************************************************************/
271 #include <sys/types.h>
278 #ifdef FEATURE_PTHREAD
280 #endif /* def FEATURE_PTHREAD */
283 # ifndef FEATURE_PTHREAD
284 # include <windows.h>
285 # include <process.h>
286 # endif /* ndef FEATURE_PTHREAD */
289 # ifndef _WIN_CONSOLE
291 # endif /* ndef _WIN_CONSOLE */
293 #else /* ifndef _WIN32 */
296 # include <sys/time.h>
297 # include <sys/wait.h>
298 # include <sys/stat.h>
302 # include <socket.h> /* BeOS has select() for sockets only. */
303 # include <OS.h> /* declarations for threads and stuff. */
317 #include "showargs.h"
319 #include "killpopup.h"
320 #include "miscutil.h"
322 #include "jbsockets.h"
328 const char jcc_h_rcs[] = JCC_H_VERSION;
329 const char project_h_rcs[] = PROJECT_H_VERSION;
331 struct client_state clients[1];
332 struct file_list files[1];
335 int urls_read = 0; /* total nr of urls read inc rejected */
336 int urls_rejected = 0; /* total nr of urls rejected */
337 #endif /* def STATISTICS */
340 static void listen_loop(void);
341 static void chat(struct client_state *csp);
343 void serve(struct client_state *csp);
344 #else /* ifndef AMIGA */
345 static void serve(struct client_state *csp);
346 #endif /* def AMIGA */
349 static int32 server_thread(void *data);
350 #endif /* def __BEOS__ */
353 #define sleep(N) Sleep(((N) * 1000))
357 /* The vanilla wafer. */
358 static const char VANILLA_WAFER[] =
359 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
360 "Do_not_send_me_any_copyrighted_information_other_than_the_"
361 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
362 "In_particular_do_not_send_me_any_cookies_that_"
363 "are_subject_to_a_claim_of_copyright_by_anybody._"
364 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
365 "(copyright_or_otherwise)_applying_to_any_cookie._";
368 /*********************************************************************
372 * Description : Once a connection to the client has been accepted,
373 * this function is called (via serve()) to handle the
374 * main business of the communication. When this
375 * function returns, the caller must close the client
379 * 1 : csp = Current client state (buffers, headers, etc...)
381 * Returns : On success, the number of bytes written are returned (zero
382 * indicates nothing was written). On error, -1 is returned,
383 * and errno is set appropriately. If count is zero and the
384 * file descriptor refers to a regular file, 0 will be
385 * returned without causing any other effect. For a special
386 * file, the results are not portable.
388 *********************************************************************/
389 static void chat(struct client_state *csp)
392 * This next lines are a little ugly, but they simplifies the if statements below.
393 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
394 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
397 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
398 #else /* ifndef TOGGLE */
399 # define IS_TOGGLED_ON_AND
400 #endif /* ndef TOGGLE */
402 # define IS_NOT_FORCED_AND (!csp->force) &&
403 #else /* ifndef FORCE_LOAD */
404 # define IS_NOT_FORCED_AND
405 #endif /* def FORCE_LOAD */
407 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
409 char buf[BUFFER_SIZE];
413 int n, maxfd, server_body;
414 int ms_iis5_hack = 0;
416 const struct forward_spec * fwd;
417 struct http_request *http;
419 int block_popups; /* bool, 1==will block popups */
420 int block_popups_now = 0; /* bool, 1==currently blocking popups */
421 #endif /* def KILLPOPUPS */
423 int pcrs_filter; /* bool, 1==will filter through pcrs */
424 int gif_deanimate; /* bool, 1==will deanimate gifs */
426 /* Function that does the content filtering for the current request */
427 char *(*content_filter)() = NULL;
429 /* Skeleton for HTTP response, if we should intercept the request */
430 struct http_response *rsp;
435 * Read the client's request. Note that since we're not using select() we
436 * could get blocked here if a client connected, then didn't say anything!
441 n = read_socket(csp->cfd, buf, sizeof(buf));
443 if (n <= 0) break; /* error! */
445 add_to_iob(csp, buf, n);
447 req = get_header(csp);
451 break; /* no HTTP request! */
456 continue; /* more to come! */
460 /* If this request contains the FORCE_PREFIX,
461 * better get rid of it now and set the force flag --oes
464 if (strstr(req, FORCE_PREFIX))
466 strclean(req, FORCE_PREFIX);
467 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
474 #endif /* def FORCE_LOAD */
476 parse_http_request(req, http, csp);
481 if (http->cmd == NULL)
483 strcpy(buf, CHEADER);
484 write_socket(csp->cfd, buf, strlen(buf));
486 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
491 /* decide how to route the HTTP request */
493 if ((fwd = forward_url(http, csp)) == NULL)
495 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
496 /* Never get here - LOG_LEVEL_FATAL causes program exit */
499 /* build the http request to send to the server
500 * we have to do one of the following:
502 * create = use the original HTTP request to create a new
503 * HTTP request that has only the path component
504 * without the http://domainspec
505 * pass = pass the original HTTP request unchanged
507 * drop = drop the HTTP request
512 * +--------+--------+
514 * 0 | create | drop |
516 * Forwarding +--------+--------+
520 * +--------+--------+
524 if (fwd->forward_host)
526 /* if forwarding, just pass the request as is */
527 enlist(csp->headers, http->cmd);
533 /* otherwise elide the host information from the url */
535 p = strsav(p, http->gpc);
537 p = strsav(p, http->path);
539 p = strsav(p, http->ver);
540 enlist(csp->headers, p);
545 /* decide what we're to do with cookies */
548 if (!csp->toggled_on)
550 /* Most compatible set of actions (i.e. none) */
551 init_current_action(csp->action);
554 #endif /* ndef TOGGLE */
556 url_actions(http, csp);
561 * If we're logging cookies in a cookie jar, and the user has not
562 * supplied any wafers, and the user has not told us to suppress the
563 * vanilla wafer, then send the vanilla wafer.
565 if ((csp->config->jarfile != NULL)
566 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
567 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
569 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
571 #endif /* def JAR_FILES */
574 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
575 #endif /* def KILLPOPUPS */
577 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
578 ((csp->action->flags & ACTION_FILTER) != 0);
580 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
582 /* grab the rest of the client's headers */
586 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
588 n = read_socket(csp->cfd, buf, sizeof(buf));
591 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
594 add_to_iob(csp, buf, n);
598 if (p == NULL) break;
600 enlist(csp->headers, p);
604 /* We have a request. */
606 hdr = sed(client_patterns, add_client_headers, csp);
607 destroy_list(csp->headers);
610 * Now, check to see if we need to intercept it, i.e.
615 /* a CGI call was detected and answered */
616 (NULL != (rsp = dispatch_cgi(csp)))
618 /* or we are enabled and... */
621 /* ..the request was blocked */
622 ( NULL != (rsp = block_url(csp)))
626 || ( NULL != (rsp = trust_url(csp)))
629 /* ..or a fast redirect kicked in */
630 #ifdef FAST_REDIRECTS
631 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
632 (NULL != (rsp = redirect_url(csp))))
633 #endif /* def FAST_REDIRECTS */
637 /* Write the answer to the client */
638 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
639 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
641 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
645 /* Count as a rejected request */
647 #endif /* def STATISTICS */
649 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
650 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
651 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
653 /* Clean up and return */
654 free_http_response(rsp);
659 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
661 if (fwd->forward_host)
663 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
664 fwd->forward_host, fwd->forward_port, http->hostport);
668 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
671 /* here we connect to the server, gateway, or the forwarder */
673 csp->sfd = forwarded_connect(fwd, http, csp);
677 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
682 rsp = error_response(csp, "no-such-domain", errno);
684 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
685 csp->ip_addr_str, http->cmd);
689 rsp = error_response(csp, "connect-failed", errno);
691 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
692 csp->ip_addr_str, http->cmd);
695 /* Write the answer to the client */
698 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
699 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
701 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
705 free_http_response(rsp);
710 log_error(LOG_LEVEL_CONNECT, "OK");
712 if (fwd->forward_host || (http->ssl == 0))
714 /* write the client's (modified) header to the server
715 * (along with anything else that may be in the buffer)
720 if ((write_socket(csp->sfd, hdr, n) != n)
721 || (flush_socket(csp->sfd, csp ) < 0))
723 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
726 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
727 csp->ip_addr_str, http->cmd);
729 rsp = error_response(csp, "connect-failed", errno);
733 if ((write_socket(csp->cfd, rsp->head, n) != n)
734 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
736 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
740 free_http_response(rsp);
748 * We're running an SSL tunnel and we're not forwarding,
749 * so just send the "connect succeeded" message to the
750 * client, flush the rest, and get out of the way.
752 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
753 csp->ip_addr_str, http->cmd);
755 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
763 /* we're finished with the client's header */
766 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
768 /* pass data between the client and server
769 * until one or the other shuts down the connection.
778 FD_SET(csp->cfd, &rfds);
779 FD_SET(csp->sfd, &rfds);
781 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
785 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
789 /* this is the body of the browser's request
790 * just read it and write it.
793 if (FD_ISSET(csp->cfd, &rfds))
795 n = read_socket(csp->cfd, buf, sizeof(buf));
799 break; /* "game over, man" */
802 if (write_socket(csp->sfd, buf, n) != n)
804 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
811 * The server wants to talk. It could be the header or the body.
812 * If `hdr' is null, then it's the header otherwise it's the body.
813 * FIXME: Does `hdr' really mean `host'? No.
817 if (FD_ISSET(csp->sfd, &rfds))
820 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
824 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
826 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
827 csp->ip_addr_str, http->cmd);
829 rsp = error_response(csp, "connect-failed", errno);
833 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
834 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
836 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
840 free_http_response(rsp);
844 /* Add a trailing zero. This lets filter_popups
845 * use string operations.
850 /* Filter the popups on this read. */
851 if (block_popups_now)
853 filter_popups(buf, n);
855 #endif /* def KILLPOPUPS */
857 /* Normally, this would indicate that we've read
858 * as much as the server has sent us and we can
859 * close the client connection. However, Microsoft
860 * in its wisdom has released IIS/5 with a bug that
861 * prevents it from sending the trailing \r\n in
862 * a 302 redirect header (and possibly other headers).
863 * To work around this if we've haven't parsed
864 * a full header we'll append a trailing \r\n
865 * and see if this now generates a valid one.
867 * This hack shouldn't have any impacts. If we've
868 * already transmitted the header or if this is a
869 * SSL connection, then we won't bother with this
870 * hack. So we only work on partially received
871 * headers. If we append a \r\n and this still
872 * doesn't generate a valid header, then we won't
873 * transmit anything to the client.
878 if (server_body || http->ssl)
881 * If we have been buffering up the document,
882 * now is the time to apply content modification
883 * and send the result to the client.
888 * If the content filter fails, use the original
890 * (see p != NULL ? p : csp->iob->cur below)
892 if (NULL == (p = (*content_filter)(csp)))
894 csp->content_length = csp->iob->eod - csp->iob->cur;
897 hdr = sed(server_patterns, add_server_headers, csp);
900 if ((write_socket(csp->cfd, hdr, n) != n)
901 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != csp->content_length))
903 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
911 break; /* "game over, man" */
915 * This is NOT the body, so
916 * Let's pretend the server just sent us a blank line.
918 n = sprintf(buf, "\r\n");
921 * Now, let the normal header parsing algorithm below do its
922 * job. If it fails, we'll exit instead of continuing.
929 * If this is an SSL connection or we're in the body
930 * of the server document, just write it to the client,
931 * unless we need to buffer the body for later content-filtering
934 if (server_body || http->ssl)
938 add_to_iob(csp, buf, n);
942 if (write_socket(csp->cfd, buf, n) != n)
944 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
953 /* we're still looking for the end of the
954 * server's header ... (does that make header
955 * parsing an "out of body experience" ?
958 /* buffer up the data we just read */
959 add_to_iob(csp, buf, n);
961 /* get header lines from the iob */
963 while ((p = get_header(csp)))
967 /* see following note */
970 enlist(csp->headers, p);
974 /* NOTE: there are no "empty" headers so
975 * if the pointer `p' is not NULL we must
976 * assume that we reached the end of the
977 * buffer before we hit the end of the header.
984 /* Well, we tried our MS IIS/5
985 * hack and it didn't work.
986 * The header is incomplete
987 * and there isn't anything
988 * we can do about it.
994 /* Since we have to wait for
995 * more from the server before
996 * we can parse the headers
997 * we just continue here.
1003 /* we have now received the entire header.
1004 * filter it and send the result to the client
1007 hdr = sed(server_patterns, add_server_headers, csp);
1010 /* write the server's (modified) header to
1011 * the client (along with anything else that
1012 * may be in the buffer)
1016 /* Start blocking popups if appropriate. */
1018 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1019 !http->ssl && /* We talk plaintext */
1020 block_popups) /* Policy allows */
1022 block_popups_now = 1;
1024 * Filter the part of the body that came in the same read
1025 * as the last headers:
1027 filter_popups(csp->iob->cur, csp->iob->eod - csp->iob->cur);
1030 #endif /* def KILLPOPUPS */
1032 /* Buffer and pcrs filter this if appropriate. */
1034 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1035 !http->ssl && /* We talk plaintext */
1036 pcrs_filter) /* Policy allows */
1038 content_filter = pcrs_filter_response;
1041 /* Buffer and gif_deanimate this if appropriate. */
1043 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1044 !http->ssl && /* We talk plaintext */
1045 gif_deanimate) /* Policy allows */
1047 content_filter = gif_deanimate_response;
1052 * Only write if we're not buffering for content modification
1054 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1055 || (n = flush_socket(csp->cfd, csp) < 0)))
1057 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1059 /* the write failed, so don't bother
1060 * mentioning it to the client...
1061 * it probably can't hear us anyway.
1067 !content_filter && (byte_count += n);
1069 /* we're finished with the server's header */
1074 /* If this was a MS IIS/5 hack then it means
1075 * the server has already closed the
1076 * connection. Nothing more to read. Time
1087 return; /* huh? we should never get here */
1090 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1091 csp->ip_addr_str, http->cmd, byte_count);
1095 /*********************************************************************
1099 * Description : This is little more than chat. We only "serve" to
1100 * to close any socket that chat may have opened.
1103 * 1 : csp = Current client state (buffers, headers, etc...)
1107 *********************************************************************/
1109 void serve(struct client_state *csp)
1110 #else /* ifndef AMIGA */
1111 static void serve(struct client_state *csp)
1112 #endif /* def AMIGA */
1115 close_socket(csp->cfd);
1119 close_socket(csp->sfd);
1128 /*********************************************************************
1130 * Function : server_thread
1132 * Description : We only exist to call `serve' in a threaded environment.
1135 * 1 : data = Current client state (buffers, headers, etc...)
1137 * Returns : Always 0.
1139 *********************************************************************/
1140 static int32 server_thread(void *data)
1142 serve((struct client_state *) data);
1149 /*********************************************************************
1153 * Description : Load the config file and start the listen loop.
1154 * This function is a lot more *sane* with the `load_config'
1155 * and `listen_loop' functions; although it stills does
1156 * a *little* too much for my taste.
1159 * 1 : argc = Number of parameters (including $0).
1160 * 2 : argv = Array of (char *)'s to the parameters.
1162 * Returns : 1 if : can't open config file, unrecognized directive,
1163 * stats requested in multi-thread mode, can't open the
1164 * log file, can't open the jar file, listen port is invalid,
1165 * any load fails, and can't bind port.
1167 * Else main never returns, the process must be signaled
1168 * to terminate execution. Or, on Windows, use the
1169 * "File", "Exit" menu option.
1171 *********************************************************************/
1173 int real_main(int argc, const char *argv[])
1175 int main(int argc, const char *argv[])
1180 "AmiTCP:db/junkbuster/config"
1181 #elif !defined(_WIN32)
1188 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1189 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1191 printf("JunkBuster proxy version " VERSION ".\n\n"
1192 "Usage: %s [configfile]\n\n"
1193 "See " HOME_PAGE_URL " for details.\n"
1194 "This program is distributed under the GNU GPL, version 2 or later.\n",
1198 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1200 printf(VERSION "\n");
1203 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1210 configfile = argv[1];
1217 #elif defined(_WIN32)
1223 signal(SIGPIPE, SIG_IGN);
1224 signal(SIGCHLD, SIG_IGN);
1226 #else /* ifdef _WIN32 */
1227 # ifdef _WIN_CONSOLE
1229 * We *are* in a windows console app.
1230 * Print a verbose messages about FAQ's and such
1232 printf(win32_blurb);
1233 # endif /* def _WIN_CONSOLE */
1234 #endif /* def _WIN32 */
1245 /*********************************************************************
1247 * Function : listen_loop
1249 * Description : bind the listen port and enter a "FOREVER" listening loop.
1255 *********************************************************************/
1256 static void listen_loop(void)
1258 struct client_state *csp = NULL;
1260 struct configuration_spec * config;
1262 config = load_config();
1264 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1265 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1267 bfd = bind_port(config->haddr, config->hport);
1271 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1272 "- There may be another junkbuster or some other "
1273 "proxy running on port %d",
1274 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1275 config->hport, config->hport
1277 /* shouldn't get here */
1281 config->need_bind = 0;
1286 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1287 while (waitpid(-1, NULL, WNOHANG) > 0)
1289 /* zombie children */
1291 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1294 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1296 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1300 memset(csp, '\0', sizeof(*csp));
1305 csp->config = config = load_config();
1307 if ( config->need_bind )
1310 * Since we were listening to the "old port", we will not see
1311 * a "listen" param change until the next IJB request. So, at
1312 * least 1 more request must be made for us to find the new
1313 * setting. I am simply closing the old socket and binding the
1316 * Which-ever is correct, we will serve 1 more page via the
1317 * old settings. This should probably be a "show-proxy-args"
1318 * request. This should not be a so common of an operation
1319 * that this will hurt people's feelings.
1324 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1325 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1326 bfd = bind_port(config->haddr, config->hport);
1330 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1331 "- There may be another junkbuster or some other "
1332 "proxy running on port %d",
1333 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1334 config->hport, config->hport
1336 /* shouldn't get here */
1340 config->need_bind = 0;
1343 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1345 if (!accept_connection(csp, bfd))
1347 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1360 log_error(LOG_LEVEL_CONNECT, "OK");
1364 /* by haroon - most of credit to srt19170 */
1365 csp->toggled_on = g_bToggleIJB;
1368 if (run_loader(csp))
1370 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1371 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1375 if (block_acl(NULL,csp))
1377 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1378 close_socket(csp->cfd);
1382 #endif /* def ACL_FILES */
1384 /* add it to the list of clients */
1385 csp->next = clients->next;
1386 clients->next = csp;
1388 if (config->multi_threaded)
1392 /* this is a switch () statment in the C preprocessor - ugh */
1393 #undef SELECTED_ONE_OPTION
1395 /* Use Pthreads in preference to native code */
1396 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1397 #define SELECTED_ONE_OPTION
1399 pthread_t the_thread;
1400 pthread_attr_t attrs;
1402 pthread_attr_init(&attrs);
1403 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1404 child_id = (pthread_create(&the_thread, &attrs,
1405 (void*)serve, csp) ? -1 : 0);
1406 pthread_attr_destroy(&attrs);
1410 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1411 #define SELECTED_ONE_OPTION
1412 child_id = _beginthread(
1418 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1419 #define SELECTED_ONE_OPTION
1421 thread_id tid = spawn_thread
1422 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1424 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1426 child_id = (int) tid;
1435 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1436 #define SELECTED_ONE_OPTION
1437 csp->cfd = ReleaseSocket(csp->cfd, -1);
1438 if((child_id = (int)CreateNewProcTags(
1439 NP_Entry, (ULONG)server_thread,
1440 NP_Output, Output(),
1441 NP_CloseOutput, FALSE,
1442 NP_Name, (ULONG)"junkbuster child",
1443 NP_StackSize, 200*1024,
1447 ((struct Task *)child_id)->tc_UserData = csp;
1448 Signal((struct Task *)child_id, SIGF_SINGLE);
1453 #if !defined(SELECTED_ONE_OPTION)
1456 /* This block is only needed when using fork().
1457 * When using threads, the server thread was
1458 * created and run by the call to _beginthread().
1460 if (child_id == 0) /* child */
1466 else if (child_id > 0) /* parent */
1468 /* in a fork()'d environment, the parent's
1469 * copy of the client socket and the CSP
1473 #if !defined(_WIN32) && defined(__CYGWIN__)
1475 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1476 close_socket(csp->cfd);
1481 #undef SELECTED_ONE_OPTION
1482 /* end of cpp switch () */
1484 if (child_id < 0) /* failed */
1486 char buf[BUFFER_SIZE];
1488 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1490 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1492 write_socket(csp->cfd, buf, strlen(buf));
1493 close_socket(csp->cfd);