1 const char jcc_rcs[] = "$Id: jcc.c,v 1.28 2001/07/23 13:26:12 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.28 2001/07/23 13:26:12 oes
37 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
39 * Revision 1.27 2001/07/19 19:09:47 haroon
40 * - Added code to take care of the situation where while processing the first
41 * server response (which includes the server header), after finding the end
42 * of the headers we were not looking past the end of the headers for
43 * content modification. I enabled it for filter_popups.
44 * Someone else should look to see if other similar operations should be
45 * done to the discarded portion of the buffer.
47 * Note 2001/07/20: No, the other content modification mechanisms will process
48 * the whole iob later anyway. --oes
50 * Revision 1.26 2001/07/18 12:31:36 oes
53 * Revision 1.25 2001/07/15 19:43:49 jongfoster
54 * Supports POSIX threads.
55 * Also removed some unused #includes.
57 * Revision 1.24 2001/07/13 14:00:40 oes
58 * - Generic content modification scheme:
59 * Each feature has its own applicability flag that is set
60 * from csp->action->flags.
61 * Replaced the "filtering" int flag , by a function pointer
62 * "content_filter" to the function that will do the content
63 * modification. If it is != NULL, the document will be buffered
64 * and processed through *content_filter, which must set
65 * csp->content_length and return a modified copy of the body
66 * or return NULL (on failiure).
67 * - Changed csp->is_text to the more generic bitmap csp->content_type
68 * which can currently take the valued CT_TEXT or CT_GIF
70 * - Removed all #ifdef PCRS
72 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
73 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
74 * the `block_acl' call. This prevents a compilation error when the user
75 * does not wish to use the "ACL" feature.
77 * Revision 1.22 2001/06/29 21:45:41 oes
78 * Indentation, CRLF->LF, Tab-> Space
80 * Revision 1.21 2001/06/29 13:29:36 oes
81 * - Cleaned up, improved comments
82 * - Unified all possible interceptors (CGI,
83 * block, trust, fast_redirect) in one
84 * place, with one (CGI) answer generation
85 * mechansim. Much clearer now.
86 * - Removed the GIF image generation, which
87 * is now done in filters.c:block_url()
88 * - Made error conditions like domain lookup
89 * failiure or (various) problems while talking
90 * to the server use cgi.c:error_response()
91 * instead of generating HTML/HTTP in chat() (yuck!)
92 * - Removed logentry from cancelled commit
94 * Revision 1.20 2001/06/09 10:55:28 jongfoster
95 * Changing BUFSIZ ==> BUFFER_SIZE
97 * Revision 1.19 2001/06/07 23:12:52 jongfoster
98 * Replacing function pointer in struct gateway with a directly
99 * called function forwarded_connect().
100 * Replacing struct gateway with struct forward_spec
102 * Revision 1.18 2001/06/03 19:12:16 oes
103 * introduced new cgi handling
105 * Revision 1.17 2001/06/01 20:07:23 jongfoster
106 * Now uses action +image-blocker{} rather than config->tinygif
108 * Revision 1.16 2001/06/01 18:49:17 jongfoster
109 * Replaced "list_share" with "list" - the tiny memory gain was not
110 * worth the extra complexity.
112 * Revision 1.15 2001/05/31 21:24:47 jongfoster
113 * Changed "permission" to "action" throughout.
114 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
115 * Moved vanilla wafer check into chat(), since we must now
116 * decide whether or not to add it based on the URL.
118 * Revision 1.14 2001/05/29 20:14:01 joergs
119 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
122 * Revision 1.13 2001/05/29 09:50:24 jongfoster
123 * Unified blocklist/imagelist/permissionslist.
124 * File format is still under discussion, but the internal changes
127 * Also modified interceptor behaviour:
128 * - We now intercept all URLs beginning with one of the following
129 * prefixes (and *only* these prefixes):
131 * * http://ijbswa.sf.net/config/
132 * * http://ijbswa.sourceforge.net/config/
133 * - New interceptors "home page" - go to http://i.j.b/ to see it.
134 * - Internal changes so that intercepted and fast redirect pages
135 * are not replaced with an image.
136 * - Interceptors now have the option to send a binary page direct
137 * to the client. (i.e. ijb-send-banner uses this)
138 * - Implemented show-url-info interceptor. (Which is why I needed
139 * the above interceptors changes - a typical URL is
140 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
141 * The previous mechanism would not have intercepted that, and
142 * if it had been intercepted then it then it would have replaced
145 * Revision 1.12 2001/05/27 22:17:04 oes
147 * - re_process_buffer no longer writes the modified buffer
148 * to the client, which was very ugly. It now returns the
149 * buffer, which it is then written by chat.
151 * - content_length now adjusts the Content-Length: header
152 * for modified documents rather than crunch()ing it.
153 * (Length info in csp->content_length, which is 0 for
154 * unmodified documents)
156 * - For this to work, sed() is called twice when filtering.
158 * Revision 1.11 2001/05/26 17:27:53 jongfoster
159 * Added support for CLF and fixed LOG_LEVEL_LOG.
160 * Also did CRLF->LF fix of my previous patch.
162 * Revision 1.10 2001/05/26 15:26:15 jongfoster
163 * ACL feature now provides more security by immediately dropping
164 * connections from untrusted hosts.
166 * Revision 1.9 2001/05/26 00:28:36 jongfoster
167 * Automatic reloading of config file.
168 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
169 * Most of the global variables have been moved to a new
170 * struct configuration_spec, accessed through csp->config->globalname
171 * Most of the globals remaining are used by the Win32 GUI.
173 * Revision 1.8 2001/05/25 22:43:18 jongfoster
174 * Fixing minor memory leak and buffer overflow.
176 * Revision 1.7 2001/05/25 22:34:30 jongfoster
179 * Revision 1.6 2001/05/23 00:13:58 joergs
180 * AmigaOS support fixed.
182 * Revision 1.5 2001/05/22 18:46:04 oes
184 * - Enabled filtering banners by size rather than URL
185 * by adding patterns that replace all standard banner
186 * sizes with the "Junkbuster" gif to the re_filterfile
188 * - Enabled filtering WebBugs by providing a pattern
189 * which kills all 1x1 images
191 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
192 * which is selected by the (nonstandard and therefore
193 * capital) letter 'U' in the option string.
194 * It causes the quantifiers to be ungreedy by default.
195 * Appending a ? turns back to greedy (!).
197 * - Added a new interceptor ijb-send-banner, which
198 * sends back the "Junkbuster" gif. Without imagelist or
199 * MSIE detection support, or if tinygif = 1, or the
200 * URL isn't recognized as an imageurl, a lame HTML
201 * explanation is sent instead.
203 * - Added new feature, which permits blocking remote
204 * script redirects and firing back a local redirect
206 * The feature is conditionally compiled, i.e. it
207 * can be disabled with --disable-fast-redirects,
208 * plus it must be activated by a "fast-redirects"
209 * line in the config file, has its own log level
210 * and of course wants to be displayed by show-proxy-args
211 * Note: Boy, all the #ifdefs in 1001 locations and
212 * all the fumbling with configure.in and acconfig.h
213 * were *way* more work than the feature itself :-(
215 * - Because a generic redirect template was needed for
216 * this, tinygif = 3 now uses the same.
218 * - Moved GIFs, and other static HTTP response templates
223 * - Removed some >400 CRs again (Jon, you really worked
226 * Revision 1.4 2001/05/21 19:34:01 jongfoster
227 * Made failure to bind() a fatal error.
229 * Revision 1.3 2001/05/20 01:21:20 jongfoster
230 * Version 2.9.4 checkin.
231 * - Merged popupfile and cookiefile, and added control over PCRS
232 * filtering, in new "permissionsfile".
233 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
234 * file error you now get a message box (in the Win32 GUI) rather
235 * than the program exiting with no explanation.
236 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
238 * - Removed tabs from "config"
239 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
240 * - Bumped up version number.
242 * Revision 1.2 2001/05/17 22:34:44 oes
243 * - Added hint on GIF char array generation to jcc.c
244 * - Cleaned CRLF's from the sources and related files
245 * - Repaired logging for REF and FRC
247 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
248 * Initial import of version 2.9.3 source tree
251 *********************************************************************/
257 #include <sys/types.h>
264 #if defined(FEATURE_PTHREAD) && !defined(__BEOS__)
266 #endif /* def FEATURE_PTHREAD && ndef __BEOS__ */
269 # ifndef FEATURE_PTHREAD
270 # include <windows.h>
271 # include <process.h>
272 # endif /* ndef FEATURE_PTHREAD */
275 # ifndef _WIN_CONSOLE
277 # endif /* ndef _WIN_CONSOLE */
279 #else /* ifndef _WIN32 */
282 # include <sys/time.h>
283 # include <sys/wait.h>
284 # include <sys/stat.h>
288 # include <socket.h> /* BeOS has select() for sockets only. */
289 # include <OS.h> /* declarations for threads and stuff. */
303 #include "showargs.h"
305 #include "killpopup.h"
306 #include "miscutil.h"
308 #include "jbsockets.h"
313 const char jcc_h_rcs[] = JCC_H_VERSION;
314 const char project_h_rcs[] = PROJECT_H_VERSION;
316 struct client_state clients[1];
317 struct file_list files[1];
320 int urls_read = 0; /* total nr of urls read inc rejected */
321 int urls_rejected = 0; /* total nr of urls rejected */
322 #endif /* def STATISTICS */
325 static void listen_loop(void);
326 static void chat(struct client_state *csp);
328 void serve(struct client_state *csp);
329 #else /* ifndef AMIGA */
330 static void serve(struct client_state *csp);
331 #endif /* def AMIGA */
334 static int32 server_thread(void *data);
335 #endif /* def __BEOS__ */
338 #define sleep(N) Sleep(((N) * 1000))
342 /* The vanilla wafer. */
343 static const char VANILLA_WAFER[] =
344 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
345 "Do_not_send_me_any_copyrighted_information_other_than_the_"
346 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
347 "In_particular_do_not_send_me_any_cookies_that_"
348 "are_subject_to_a_claim_of_copyright_by_anybody._"
349 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
350 "(copyright_or_otherwise)_applying_to_any_cookie._";
353 /*********************************************************************
357 * Description : Once a connection to the client has been accepted,
358 * this function is called (via serve()) to handle the
359 * main business of the communication. When this
360 * function returns, the caller must close the client
364 * 1 : csp = Current client state (buffers, headers, etc...)
366 * Returns : On success, the number of bytes written are returned (zero
367 * indicates nothing was written). On error, -1 is returned,
368 * and errno is set appropriately. If count is zero and the
369 * file descriptor refers to a regular file, 0 will be
370 * returned without causing any other effect. For a special
371 * file, the results are not portable.
373 *********************************************************************/
374 static void chat(struct client_state *csp)
377 * This next lines are a little ugly, but they simplifies the if statements below.
378 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
379 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
382 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
383 #else /* ifndef TOGGLE */
384 # define IS_TOGGLED_ON_AND
385 #endif /* ndef TOGGLE */
387 # define IS_NOT_FORCED_AND (!csp->force) &&
388 #else /* ifndef FORCE_LOAD */
389 # define IS_NOT_FORCED_AND
390 #endif /* def FORCE_LOAD */
392 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
394 char buf[BUFFER_SIZE];
398 int n, maxfd, server_body;
399 int ms_iis5_hack = 0;
401 const struct forward_spec * fwd;
402 struct http_request *http;
404 int block_popups; /* bool, 1==will block popups */
405 int block_popups_now = 0; /* bool, 1==currently blocking popups */
406 #endif /* def KILLPOPUPS */
408 int pcrs_filter; /* bool, 1==will filter through pcrs */
409 int gif_deanimate; /* bool, 1==will deanimate gifs */
411 /* Function that does the content filtering for the current request */
412 char *(*content_filter)() = NULL;
414 /* Skeleton for HTTP response, if we should intercept the request */
415 struct http_response *rsp;
420 * Read the client's request. Note that since we're not using select() we
421 * could get blocked here if a client connected, then didn't say anything!
426 n = read_socket(csp->cfd, buf, sizeof(buf));
428 if (n <= 0) break; /* error! */
430 add_to_iob(csp, buf, n);
432 req = get_header(csp);
436 break; /* no HTTP request! */
441 continue; /* more to come! */
445 /* If this request contains the FORCE_PREFIX,
446 * better get rid of it now and set the force flag --oes
449 if (strstr(req, FORCE_PREFIX))
451 strclean(req, FORCE_PREFIX);
452 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
459 #endif /* def FORCE_LOAD */
461 parse_http_request(req, http, csp);
466 if (http->cmd == NULL)
468 strcpy(buf, CHEADER);
469 write_socket(csp->cfd, buf, strlen(buf));
471 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
476 /* decide how to route the HTTP request */
478 if ((fwd = forward_url(http, csp)) == NULL)
480 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
481 /* Never get here - LOG_LEVEL_FATAL causes program exit */
484 /* build the http request to send to the server
485 * we have to do one of the following:
487 * create = use the original HTTP request to create a new
488 * HTTP request that has only the path component
489 * without the http://domainspec
490 * pass = pass the original HTTP request unchanged
492 * drop = drop the HTTP request
497 * +--------+--------+
499 * 0 | create | drop |
501 * Forwarding +--------+--------+
505 * +--------+--------+
509 if (fwd->forward_host)
511 /* if forwarding, just pass the request as is */
512 enlist(csp->headers, http->cmd);
518 /* otherwise elide the host information from the url */
520 p = strsav(p, http->gpc);
522 p = strsav(p, http->path);
524 p = strsav(p, http->ver);
525 enlist(csp->headers, p);
530 /* decide what we're to do with cookies */
533 if (!csp->toggled_on)
535 /* Most compatible set of actions (i.e. none) */
536 init_current_action(csp->action);
539 #endif /* ndef TOGGLE */
541 url_actions(http, csp);
546 * If we're logging cookies in a cookie jar, and the user has not
547 * supplied any wafers, and the user has not told us to suppress the
548 * vanilla wafer, then send the vanilla wafer.
550 if ((csp->config->jarfile != NULL)
551 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
552 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
554 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
556 #endif /* def JAR_FILES */
559 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
560 #endif /* def KILLPOPUPS */
562 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
563 ((csp->action->flags & ACTION_FILTER) != 0);
565 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
567 /* grab the rest of the client's headers */
571 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
573 n = read_socket(csp->cfd, buf, sizeof(buf));
576 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
579 add_to_iob(csp, buf, n);
583 if (p == NULL) break;
585 enlist(csp->headers, p);
589 /* We have a request. */
591 hdr = sed(client_patterns, add_client_headers, csp);
592 destroy_list(csp->headers);
595 * Now, check to see if we need to intercept it, i.e.
600 /* a CGI call was detected and answered */
601 (NULL != (rsp = dispatch_cgi(csp)))
603 /* or we are enabled and... */
606 /* ..the request was blocked */
607 ( NULL != (rsp = block_url(csp)))
611 || ( NULL != (rsp = trust_url(csp)))
614 /* ..or a fast redirect kicked in */
615 #ifdef FAST_REDIRECTS
616 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
617 (NULL != (rsp = redirect_url(csp))))
618 #endif /* def FAST_REDIRECTS */
622 /* Write the answer to the client */
623 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
624 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
626 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
630 /* Count as a rejected request */
632 #endif /* def STATISTICS */
634 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
635 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
636 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
638 /* Clean up and return */
639 free_http_response(rsp);
644 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
646 if (fwd->forward_host)
648 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
649 fwd->forward_host, fwd->forward_port, http->hostport);
653 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
656 /* here we connect to the server, gateway, or the forwarder */
658 csp->sfd = forwarded_connect(fwd, http, csp);
662 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
667 rsp = error_response(csp, "no-such-domain", errno);
669 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
670 csp->ip_addr_str, http->cmd);
674 rsp = error_response(csp, "connect-failed", errno);
676 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
677 csp->ip_addr_str, http->cmd);
680 /* Write the answer to the client */
683 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
684 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
686 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
690 free_http_response(rsp);
695 log_error(LOG_LEVEL_CONNECT, "OK");
697 if (fwd->forward_host || (http->ssl == 0))
699 /* write the client's (modified) header to the server
700 * (along with anything else that may be in the buffer)
705 if ((write_socket(csp->sfd, hdr, n) != n)
706 || (flush_socket(csp->sfd, csp ) < 0))
708 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
711 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
712 csp->ip_addr_str, http->cmd);
714 rsp = error_response(csp, "connect-failed", errno);
718 if ((write_socket(csp->cfd, rsp->head, n) != n)
719 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
721 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
725 free_http_response(rsp);
733 * We're running an SSL tunnel and we're not forwarding,
734 * so just send the "connect succeeded" message to the
735 * client, flush the rest, and get out of the way.
737 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
738 csp->ip_addr_str, http->cmd);
740 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
748 /* we're finished with the client's header */
751 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
753 /* pass data between the client and server
754 * until one or the other shuts down the connection.
763 FD_SET(csp->cfd, &rfds);
764 FD_SET(csp->sfd, &rfds);
766 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
770 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
774 /* this is the body of the browser's request
775 * just read it and write it.
778 if (FD_ISSET(csp->cfd, &rfds))
780 n = read_socket(csp->cfd, buf, sizeof(buf));
784 break; /* "game over, man" */
787 if (write_socket(csp->sfd, buf, n) != n)
789 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
796 * The server wants to talk. It could be the header or the body.
797 * If `hdr' is null, then it's the header otherwise it's the body.
798 * FIXME: Does `hdr' really mean `host'? No.
802 if (FD_ISSET(csp->sfd, &rfds))
805 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
809 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
811 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
812 csp->ip_addr_str, http->cmd);
814 rsp = error_response(csp, "connect-failed", errno);
818 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
819 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
821 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
825 free_http_response(rsp);
829 /* Add a trailing zero. This lets filter_popups
830 * use string operations.
835 /* Filter the popups on this read. */
836 if (block_popups_now)
838 filter_popups(buf, n);
840 #endif /* def KILLPOPUPS */
842 /* Normally, this would indicate that we've read
843 * as much as the server has sent us and we can
844 * close the client connection. However, Microsoft
845 * in its wisdom has released IIS/5 with a bug that
846 * prevents it from sending the trailing \r\n in
847 * a 302 redirect header (and possibly other headers).
848 * To work around this if we've haven't parsed
849 * a full header we'll append a trailing \r\n
850 * and see if this now generates a valid one.
852 * This hack shouldn't have any impacts. If we've
853 * already transmitted the header or if this is a
854 * SSL connection, then we won't bother with this
855 * hack. So we only work on partially received
856 * headers. If we append a \r\n and this still
857 * doesn't generate a valid header, then we won't
858 * transmit anything to the client.
863 if (server_body || http->ssl)
866 * If we have been buffering up the document,
867 * now is the time to apply content modification
868 * and send the result to the client.
873 * If the content filter fails, use the original
875 * (see p != NULL ? p : csp->iob->cur below)
877 if (NULL == (p = (*content_filter)(csp)))
879 csp->content_length = csp->iob->eod - csp->iob->cur;
882 hdr = sed(server_patterns, add_server_headers, csp);
885 if ((write_socket(csp->cfd, hdr, n) != n)
886 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != csp->content_length))
888 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
896 break; /* "game over, man" */
900 * This is NOT the body, so
901 * Let's pretend the server just sent us a blank line.
903 n = sprintf(buf, "\r\n");
906 * Now, let the normal header parsing algorithm below do its
907 * job. If it fails, we'll exit instead of continuing.
914 * If this is an SSL connection or we're in the body
915 * of the server document, just write it to the client,
916 * unless we need to buffer the body for later content-filtering
919 if (server_body || http->ssl)
923 add_to_iob(csp, buf, n);
927 if (write_socket(csp->cfd, buf, n) != n)
929 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
938 /* we're still looking for the end of the
939 * server's header ... (does that make header
940 * parsing an "out of body experience" ?
943 /* buffer up the data we just read */
944 add_to_iob(csp, buf, n);
946 /* get header lines from the iob */
948 while ((p = get_header(csp)))
952 /* see following note */
955 enlist(csp->headers, p);
959 /* NOTE: there are no "empty" headers so
960 * if the pointer `p' is not NULL we must
961 * assume that we reached the end of the
962 * buffer before we hit the end of the header.
969 /* Well, we tried our MS IIS/5
970 * hack and it didn't work.
971 * The header is incomplete
972 * and there isn't anything
973 * we can do about it.
979 /* Since we have to wait for
980 * more from the server before
981 * we can parse the headers
982 * we just continue here.
988 /* we have now received the entire header.
989 * filter it and send the result to the client
992 hdr = sed(server_patterns, add_server_headers, csp);
995 /* write the server's (modified) header to
996 * the client (along with anything else that
997 * may be in the buffer)
1001 /* Start blocking popups if appropriate. */
1003 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1004 !http->ssl && /* We talk plaintext */
1005 block_popups) /* Policy allows */
1007 block_popups_now = 1;
1009 * Filter the part of the body that came in the same read
1010 * as the last headers:
1012 filter_popups(csp->iob->cur, csp->iob->eod - csp->iob->cur);
1015 #endif /* def KILLPOPUPS */
1017 /* Buffer and pcrs filter this if appropriate. */
1019 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1020 !http->ssl && /* We talk plaintext */
1021 pcrs_filter) /* Policy allows */
1023 content_filter = pcrs_filter_response;
1026 /* Buffer and gif_deanimate this if appropriate. */
1028 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1029 !http->ssl && /* We talk plaintext */
1030 gif_deanimate) /* Policy allows */
1032 content_filter = gif_deanimate_response;
1037 * Only write if we're not buffering for content modification
1039 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1040 || (n = flush_socket(csp->cfd, csp) < 0)))
1042 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1044 /* the write failed, so don't bother
1045 * mentioning it to the client...
1046 * it probably can't hear us anyway.
1052 !content_filter && (byte_count += n);
1054 /* we're finished with the server's header */
1059 /* If this was a MS IIS/5 hack then it means
1060 * the server has already closed the
1061 * connection. Nothing more to read. Time
1072 return; /* huh? we should never get here */
1075 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1076 csp->ip_addr_str, http->cmd, byte_count);
1080 /*********************************************************************
1084 * Description : This is little more than chat. We only "serve" to
1085 * to close any socket that chat may have opened.
1088 * 1 : csp = Current client state (buffers, headers, etc...)
1092 *********************************************************************/
1094 void serve(struct client_state *csp)
1095 #else /* ifndef AMIGA */
1096 static void serve(struct client_state *csp)
1097 #endif /* def AMIGA */
1100 close_socket(csp->cfd);
1104 close_socket(csp->sfd);
1113 /*********************************************************************
1115 * Function : server_thread
1117 * Description : We only exist to call `serve' in a threaded environment.
1120 * 1 : data = Current client state (buffers, headers, etc...)
1122 * Returns : Always 0.
1124 *********************************************************************/
1125 static int32 server_thread(void *data)
1127 serve((struct client_state *) data);
1134 /*********************************************************************
1138 * Description : Load the config file and start the listen loop.
1139 * This function is a lot more *sane* with the `load_config'
1140 * and `listen_loop' functions; although it stills does
1141 * a *little* too much for my taste.
1144 * 1 : argc = Number of parameters (including $0).
1145 * 2 : argv = Array of (char *)'s to the parameters.
1147 * Returns : 1 if : can't open config file, unrecognized directive,
1148 * stats requested in multi-thread mode, can't open the
1149 * log file, can't open the jar file, listen port is invalid,
1150 * any load fails, and can't bind port.
1152 * Else main never returns, the process must be signaled
1153 * to terminate execution. Or, on Windows, use the
1154 * "File", "Exit" menu option.
1156 *********************************************************************/
1158 int _main(int argc, const char *argv[])
1160 int main(int argc, const char *argv[])
1165 "AmiTCP:db/junkbuster/config"
1166 #elif !defined(_WIN32)
1173 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1174 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1176 printf("JunkBuster proxy version " VERSION ".\n\n"
1177 "Usage: %s [configfile]\n\n"
1178 "See " HOME_PAGE_URL " for details.\n"
1179 "This program is distributed under the GNU GPL, version 2 or later.\n",
1183 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1185 printf(VERSION "\n");
1188 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1195 configfile = argv[1];
1202 #elif defined(_WIN32)
1208 signal(SIGPIPE, SIG_IGN);
1209 signal(SIGCHLD, SIG_IGN);
1211 #else /* ifdef _WIN32 */
1212 # ifdef _WIN_CONSOLE
1214 * We *are* in a windows console app.
1215 * Print a verbose messages about FAQ's and such
1217 printf(win32_blurb);
1218 # endif /* def _WIN_CONSOLE */
1219 #endif /* def _WIN32 */
1230 /*********************************************************************
1232 * Function : listen_loop
1234 * Description : bind the listen port and enter a "FOREVER" listening loop.
1240 *********************************************************************/
1241 static void listen_loop(void)
1243 struct client_state *csp = NULL;
1245 struct configuration_spec * config;
1247 config = load_config();
1249 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1250 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1252 bfd = bind_port(config->haddr, config->hport);
1256 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1257 "- There may be another junkbuster or some other "
1258 "proxy running on port %d",
1259 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1260 config->hport, config->hport
1262 /* shouldn't get here */
1266 config->need_bind = 0;
1271 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1272 while (waitpid(-1, NULL, WNOHANG) > 0)
1274 /* zombie children */
1276 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1279 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1281 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1285 memset(csp, '\0', sizeof(*csp));
1290 csp->config = config = load_config();
1292 if ( config->need_bind )
1295 * Since we were listening to the "old port", we will not see
1296 * a "listen" param change until the next IJB request. So, at
1297 * least 1 more request must be made for us to find the new
1298 * setting. I am simply closing the old socket and binding the
1301 * Which-ever is correct, we will serve 1 more page via the
1302 * old settings. This should probably be a "show-proxy-args"
1303 * request. This should not be a so common of an operation
1304 * that this will hurt people's feelings.
1309 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1310 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1311 bfd = bind_port(config->haddr, config->hport);
1315 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1316 "- There may be another junkbuster or some other "
1317 "proxy running on port %d",
1318 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1319 config->hport, config->hport
1321 /* shouldn't get here */
1325 config->need_bind = 0;
1328 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1330 if (!accept_connection(csp, bfd))
1332 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1345 log_error(LOG_LEVEL_CONNECT, "OK");
1349 /* by haroon - most of credit to srt19170 */
1350 csp->toggled_on = g_bToggleIJB;
1353 if (run_loader(csp))
1355 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1356 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1360 if (block_acl(NULL,csp))
1362 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1363 close_socket(csp->cfd);
1367 #endif /* def ACL_FILES */
1369 /* add it to the list of clients */
1370 csp->next = clients->next;
1371 clients->next = csp;
1373 if (config->multi_threaded)
1377 /* this is a switch () statment in the C preprocessor - ugh */
1378 #undef SELECTED_ONE_OPTION
1380 /* Use Pthreads in preference to native code */
1381 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1382 #define SELECTED_ONE_OPTION
1384 pthread_t the_thread;
1385 pthread_attr_t attrs;
1387 pthread_attr_init(&attrs);
1388 child_id = (pthread_create(&the_thread, &attrs,
1389 (void*)serve, csp) ? -1 : 0);
1390 pthread_attr_destroy(&attrs);
1394 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1395 #define SELECTED_ONE_OPTION
1396 child_id = _beginthread(
1402 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1403 #define SELECTED_ONE_OPTION
1405 thread_id tid = spawn_thread
1406 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1408 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1410 child_id = (int) tid;
1419 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1420 #define SELECTED_ONE_OPTION
1421 csp->cfd = ReleaseSocket(csp->cfd, -1);
1422 if((child_id = (int)CreateNewProcTags(
1423 NP_Entry, (ULONG)server_thread,
1424 NP_Output, Output(),
1425 NP_CloseOutput, FALSE,
1426 NP_Name, (ULONG)"junkbuster child",
1427 NP_StackSize, 200*1024,
1431 ((struct Task *)child_id)->tc_UserData = csp;
1432 Signal((struct Task *)child_id, SIGF_SINGLE);
1437 #if !defined(SELECTED_ONE_OPTION)
1440 /* This block is only needed when using fork().
1441 * When using threads, the server thread was
1442 * created and run by the call to _beginthread().
1444 if (child_id == 0) /* child */
1450 else if (child_id > 0) /* parent */
1452 /* in a fork()'d environment, the parent's
1453 * copy of the client socket and the CSP
1457 #if !defined(_WIN32) && defined(__CYGWIN__)
1459 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1460 close_socket(csp->cfd);
1465 #undef SELECTED_ONE_OPTION
1466 /* end of cpp switch () */
1468 if (child_id < 0) /* failed */
1470 char buf[BUFFER_SIZE];
1472 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1474 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1476 write_socket(csp->cfd, buf, strlen(buf));
1477 close_socket(csp->cfd);