1 const char jcc_rcs[] = "$Id: jcc.c,v 1.26 2001/07/18 12:31:36 oes Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001 the SourceForge
10 * IJBSWA team. http://ijbswa.sourceforge.net
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
36 * Revision 1.26 2001/07/18 12:31:36 oes
39 * Revision 1.25 2001/07/15 19:43:49 jongfoster
40 * Supports POSIX threads.
41 * Also removed some unused #includes.
43 * Revision 1.24 2001/07/13 14:00:40 oes
44 * - Generic content modification scheme:
45 * Each feature has its own applicability flag that is set
46 * from csp->action->flags.
47 * Replaced the "filtering" int flag , by a function pointer
48 * "content_filter" to the function that will do the content
49 * modification. If it is != NULL, the document will be buffered
50 * and processed through *content_filter, which must set
51 * csp->content_length and return a modified copy of the body
52 * or return NULL (on failiure).
53 * - Changed csp->is_text to the more generic bitmap csp->content_type
54 * which can currently take the valued CT_TEXT or CT_GIF
56 * - Removed all #ifdef PCRS
58 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
59 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
60 * the `block_acl' call. This prevents a compilation error when the user
61 * does not wish to use the "ACL" feature.
63 * Revision 1.22 2001/06/29 21:45:41 oes
64 * Indentation, CRLF->LF, Tab-> Space
66 * Revision 1.21 2001/06/29 13:29:36 oes
67 * - Cleaned up, improved comments
68 * - Unified all possible interceptors (CGI,
69 * block, trust, fast_redirect) in one
70 * place, with one (CGI) answer generation
71 * mechansim. Much clearer now.
72 * - Removed the GIF image generation, which
73 * is now done in filters.c:block_url()
74 * - Made error conditions like domain lookup
75 * failiure or (various) problems while talking
76 * to the server use cgi.c:error_response()
77 * instead of generating HTML/HTTP in chat() (yuck!)
78 * - Removed logentry from cancelled commit
80 * Revision 1.20 2001/06/09 10:55:28 jongfoster
81 * Changing BUFSIZ ==> BUFFER_SIZE
83 * Revision 1.19 2001/06/07 23:12:52 jongfoster
84 * Replacing function pointer in struct gateway with a directly
85 * called function forwarded_connect().
86 * Replacing struct gateway with struct forward_spec
88 * Revision 1.18 2001/06/03 19:12:16 oes
89 * introduced new cgi handling
91 * Revision 1.17 2001/06/01 20:07:23 jongfoster
92 * Now uses action +image-blocker{} rather than config->tinygif
94 * Revision 1.16 2001/06/01 18:49:17 jongfoster
95 * Replaced "list_share" with "list" - the tiny memory gain was not
96 * worth the extra complexity.
98 * Revision 1.15 2001/05/31 21:24:47 jongfoster
99 * Changed "permission" to "action" throughout.
100 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
101 * Moved vanilla wafer check into chat(), since we must now
102 * decide whether or not to add it based on the URL.
104 * Revision 1.14 2001/05/29 20:14:01 joergs
105 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
108 * Revision 1.13 2001/05/29 09:50:24 jongfoster
109 * Unified blocklist/imagelist/permissionslist.
110 * File format is still under discussion, but the internal changes
113 * Also modified interceptor behaviour:
114 * - We now intercept all URLs beginning with one of the following
115 * prefixes (and *only* these prefixes):
117 * * http://ijbswa.sf.net/config/
118 * * http://ijbswa.sourceforge.net/config/
119 * - New interceptors "home page" - go to http://i.j.b/ to see it.
120 * - Internal changes so that intercepted and fast redirect pages
121 * are not replaced with an image.
122 * - Interceptors now have the option to send a binary page direct
123 * to the client. (i.e. ijb-send-banner uses this)
124 * - Implemented show-url-info interceptor. (Which is why I needed
125 * the above interceptors changes - a typical URL is
126 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
127 * The previous mechanism would not have intercepted that, and
128 * if it had been intercepted then it then it would have replaced
131 * Revision 1.12 2001/05/27 22:17:04 oes
133 * - re_process_buffer no longer writes the modified buffer
134 * to the client, which was very ugly. It now returns the
135 * buffer, which it is then written by chat.
137 * - content_length now adjusts the Content-Length: header
138 * for modified documents rather than crunch()ing it.
139 * (Length info in csp->content_length, which is 0 for
140 * unmodified documents)
142 * - For this to work, sed() is called twice when filtering.
144 * Revision 1.11 2001/05/26 17:27:53 jongfoster
145 * Added support for CLF and fixed LOG_LEVEL_LOG.
146 * Also did CRLF->LF fix of my previous patch.
148 * Revision 1.10 2001/05/26 15:26:15 jongfoster
149 * ACL feature now provides more security by immediately dropping
150 * connections from untrusted hosts.
152 * Revision 1.9 2001/05/26 00:28:36 jongfoster
153 * Automatic reloading of config file.
154 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
155 * Most of the global variables have been moved to a new
156 * struct configuration_spec, accessed through csp->config->globalname
157 * Most of the globals remaining are used by the Win32 GUI.
159 * Revision 1.8 2001/05/25 22:43:18 jongfoster
160 * Fixing minor memory leak and buffer overflow.
162 * Revision 1.7 2001/05/25 22:34:30 jongfoster
165 * Revision 1.6 2001/05/23 00:13:58 joergs
166 * AmigaOS support fixed.
168 * Revision 1.5 2001/05/22 18:46:04 oes
170 * - Enabled filtering banners by size rather than URL
171 * by adding patterns that replace all standard banner
172 * sizes with the "Junkbuster" gif to the re_filterfile
174 * - Enabled filtering WebBugs by providing a pattern
175 * which kills all 1x1 images
177 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
178 * which is selected by the (nonstandard and therefore
179 * capital) letter 'U' in the option string.
180 * It causes the quantifiers to be ungreedy by default.
181 * Appending a ? turns back to greedy (!).
183 * - Added a new interceptor ijb-send-banner, which
184 * sends back the "Junkbuster" gif. Without imagelist or
185 * MSIE detection support, or if tinygif = 1, or the
186 * URL isn't recognized as an imageurl, a lame HTML
187 * explanation is sent instead.
189 * - Added new feature, which permits blocking remote
190 * script redirects and firing back a local redirect
192 * The feature is conditionally compiled, i.e. it
193 * can be disabled with --disable-fast-redirects,
194 * plus it must be activated by a "fast-redirects"
195 * line in the config file, has its own log level
196 * and of course wants to be displayed by show-proxy-args
197 * Note: Boy, all the #ifdefs in 1001 locations and
198 * all the fumbling with configure.in and acconfig.h
199 * were *way* more work than the feature itself :-(
201 * - Because a generic redirect template was needed for
202 * this, tinygif = 3 now uses the same.
204 * - Moved GIFs, and other static HTTP response templates
209 * - Removed some >400 CRs again (Jon, you really worked
212 * Revision 1.4 2001/05/21 19:34:01 jongfoster
213 * Made failure to bind() a fatal error.
215 * Revision 1.3 2001/05/20 01:21:20 jongfoster
216 * Version 2.9.4 checkin.
217 * - Merged popupfile and cookiefile, and added control over PCRS
218 * filtering, in new "permissionsfile".
219 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
220 * file error you now get a message box (in the Win32 GUI) rather
221 * than the program exiting with no explanation.
222 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
224 * - Removed tabs from "config"
225 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
226 * - Bumped up version number.
228 * Revision 1.2 2001/05/17 22:34:44 oes
229 * - Added hint on GIF char array generation to jcc.c
230 * - Cleaned CRLF's from the sources and related files
231 * - Repaired logging for REF and FRC
233 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
234 * Initial import of version 2.9.3 source tree
237 *********************************************************************/
243 #include <sys/types.h>
250 #ifdef FEATURE_PTHREAD
252 #endif /* def FEATURE_PTHREAD */
255 # ifndef FEATURE_PTHREAD
256 # include <windows.h>
257 # include <process.h>
258 # endif /* ndef FEATURE_PTHREAD */
261 # ifndef _WIN_CONSOLE
263 # endif /* ndef _WIN_CONSOLE */
265 #else /* ifndef _WIN32 */
268 # include <sys/time.h>
269 # include <sys/wait.h>
270 # include <sys/stat.h>
274 # include <socket.h> /* BeOS has select() for sockets only. */
275 # include <OS.h> /* declarations for threads and stuff. */
289 #include "showargs.h"
291 #include "killpopup.h"
292 #include "miscutil.h"
294 #include "jbsockets.h"
299 const char jcc_h_rcs[] = JCC_H_VERSION;
300 const char project_h_rcs[] = PROJECT_H_VERSION;
302 struct client_state clients[1];
303 struct file_list files[1];
306 int urls_read = 0; /* total nr of urls read inc rejected */
307 int urls_rejected = 0; /* total nr of urls rejected */
308 #endif /* def STATISTICS */
311 static void listen_loop(void);
312 static void chat(struct client_state *csp);
314 void serve(struct client_state *csp);
315 #else /* ifndef AMIGA */
316 static void serve(struct client_state *csp);
317 #endif /* def AMIGA */
320 static int32 server_thread(void *data);
321 #endif /* def __BEOS__ */
324 #define sleep(N) Sleep(((N) * 1000))
328 /* The vanilla wafer. */
329 static const char VANILLA_WAFER[] =
330 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
331 "Do_not_send_me_any_copyrighted_information_other_than_the_"
332 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
333 "In_particular_do_not_send_me_any_cookies_that_"
334 "are_subject_to_a_claim_of_copyright_by_anybody._"
335 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
336 "(copyright_or_otherwise)_applying_to_any_cookie._";
339 /*********************************************************************
343 * Description : Once a connection to the client has been accepted,
344 * this function is called (via serve()) to handle the
345 * main business of the communication. When this
346 * function returns, the caller must close the client
350 * 1 : csp = Current client state (buffers, headers, etc...)
352 * Returns : On success, the number of bytes written are returned (zero
353 * indicates nothing was written). On error, -1 is returned,
354 * and errno is set appropriately. If count is zero and the
355 * file descriptor refers to a regular file, 0 will be
356 * returned without causing any other effect. For a special
357 * file, the results are not portable.
359 *********************************************************************/
360 static void chat(struct client_state *csp)
363 * This next lines are a little ugly, but they simplifies the if statements below.
364 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
365 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
368 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
369 #else /* ifndef TOGGLE */
370 # define IS_TOGGLED_ON_AND
371 #endif /* ndef TOGGLE */
373 # define IS_NOT_FORCED_AND (!csp->force) &&
374 #else /* ifndef FORCE_LOAD */
375 # define IS_NOT_FORCED_AND
376 #endif /* def FORCE_LOAD */
378 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
380 char buf[BUFFER_SIZE];
384 int n, maxfd, server_body;
385 int ms_iis5_hack = 0;
387 const struct forward_spec * fwd;
388 struct http_request *http;
390 int block_popups; /* bool, 1==will block popups */
391 int block_popups_now = 0; /* bool, 1==currently blocking popups */
392 #endif /* def KILLPOPUPS */
394 int pcrs_filter; /* bool, 1==will filter through pcrs */
395 int gif_deanimate; /* bool, 1==will deanimate gifs */
397 /* Function that does the content filtering for the current request */
398 char *(*content_filter)() = NULL;
400 /* Skeleton for HTTP response, if we should intercept the request */
401 struct http_response *rsp;
406 * Read the client's request. Note that since we're not using select() we
407 * could get blocked here if a client connected, then didn't say anything!
412 n = read_socket(csp->cfd, buf, sizeof(buf));
414 if (n <= 0) break; /* error! */
416 add_to_iob(csp, buf, n);
418 req = get_header(csp);
422 break; /* no HTTP request! */
427 continue; /* more to come! */
431 /* If this request contains the FORCE_PREFIX,
432 * better get rid of it now and set the force flag --oes
435 if (strstr(req, FORCE_PREFIX))
437 strclean(req, FORCE_PREFIX);
438 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
445 #endif /* def FORCE_LOAD */
447 parse_http_request(req, http, csp);
452 if (http->cmd == NULL)
454 strcpy(buf, CHEADER);
455 write_socket(csp->cfd, buf, strlen(buf));
457 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
462 /* decide how to route the HTTP request */
464 if ((fwd = forward_url(http, csp)) == NULL)
466 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
467 /* Never get here - LOG_LEVEL_FATAL causes program exit */
470 /* build the http request to send to the server
471 * we have to do one of the following:
473 * create = use the original HTTP request to create a new
474 * HTTP request that has only the path component
475 * without the http://domainspec
476 * pass = pass the original HTTP request unchanged
478 * drop = drop the HTTP request
483 * +--------+--------+
485 * 0 | create | drop |
487 * Forwarding +--------+--------+
491 * +--------+--------+
495 if (fwd->forward_host)
497 /* if forwarding, just pass the request as is */
498 enlist(csp->headers, http->cmd);
504 /* otherwise elide the host information from the url */
506 p = strsav(p, http->gpc);
508 p = strsav(p, http->path);
510 p = strsav(p, http->ver);
511 enlist(csp->headers, p);
516 /* decide what we're to do with cookies */
519 if (!csp->toggled_on)
521 /* Most compatible set of actions (i.e. none) */
522 init_current_action(csp->action);
525 #endif /* ndef TOGGLE */
527 url_actions(http, csp);
532 * If we're logging cookies in a cookie jar, and the user has not
533 * supplied any wafers, and the user has not told us to suppress the
534 * vanilla wafer, then send the vanilla wafer.
536 if ((csp->config->jarfile != NULL)
537 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
538 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
540 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
542 #endif /* def JAR_FILES */
545 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
546 #endif /* def KILLPOPUPS */
548 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
549 ((csp->action->flags & ACTION_FILTER) != 0);
551 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
553 /* grab the rest of the client's headers */
557 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
559 n = read_socket(csp->cfd, buf, sizeof(buf));
562 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
565 add_to_iob(csp, buf, n);
569 if (p == NULL) break;
571 enlist(csp->headers, p);
575 /* We have a request. */
577 hdr = sed(client_patterns, add_client_headers, csp);
578 destroy_list(csp->headers);
581 * Now, check to see if we need to intercept it, i.e.
586 /* a CGI call was detected and answered */
587 (NULL != (rsp = dispatch_cgi(csp)))
589 /* or we are enabled and... */
592 /* ..the request was blocked */
593 ( NULL != (rsp = block_url(csp)))
597 || ( NULL != (rsp = trust_url(csp)))
600 /* ..or a fast redirect kicked in */
601 #ifdef FAST_REDIRECTS
602 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
603 (NULL != (rsp = redirect_url(csp))))
604 #endif /* def FAST_REDIRECTS */
608 /* Write the answer to the client */
609 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
610 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
612 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
616 /* Count as a rejected request */
618 #endif /* def STATISTICS */
620 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
621 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
622 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
624 /* Clean up and return */
625 free_http_response(rsp);
630 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
632 if (fwd->forward_host)
634 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
635 fwd->forward_host, fwd->forward_port, http->hostport);
639 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
642 /* here we connect to the server, gateway, or the forwarder */
644 csp->sfd = forwarded_connect(fwd, http, csp);
648 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
653 rsp = error_response(csp, "no-such-domain", errno);
655 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
656 csp->ip_addr_str, http->cmd);
660 rsp = error_response(csp, "connect-failed", errno);
662 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
663 csp->ip_addr_str, http->cmd);
666 /* Write the answer to the client */
669 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
670 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
672 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
676 free_http_response(rsp);
681 log_error(LOG_LEVEL_CONNECT, "OK");
683 if (fwd->forward_host || (http->ssl == 0))
685 /* write the client's (modified) header to the server
686 * (along with anything else that may be in the buffer)
691 if ((write_socket(csp->sfd, hdr, n) != n)
692 || (flush_socket(csp->sfd, csp ) < 0))
694 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
697 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
698 csp->ip_addr_str, http->cmd);
700 rsp = error_response(csp, "connect-failed", errno);
704 if ((write_socket(csp->cfd, rsp->head, n) != n)
705 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
707 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
711 free_http_response(rsp);
719 * We're running an SSL tunnel and we're not forwarding,
720 * so just send the "connect succeeded" message to the
721 * client, flush the rest, and get out of the way.
723 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
724 csp->ip_addr_str, http->cmd);
726 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
734 /* we're finished with the client's header */
737 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
739 /* pass data between the client and server
740 * until one or the other shuts down the connection.
749 FD_SET(csp->cfd, &rfds);
750 FD_SET(csp->sfd, &rfds);
752 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
756 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
760 /* this is the body of the browser's request
761 * just read it and write it.
764 if (FD_ISSET(csp->cfd, &rfds))
766 n = read_socket(csp->cfd, buf, sizeof(buf));
770 break; /* "game over, man" */
773 if (write_socket(csp->sfd, buf, n) != n)
775 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
782 * The server wants to talk. It could be the header or the body.
783 * If `hdr' is null, then it's the header otherwise it's the body.
784 * FIXME: Does `hdr' really mean `host'? No.
788 if (FD_ISSET(csp->sfd, &rfds))
791 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
795 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
797 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
798 csp->ip_addr_str, http->cmd);
800 rsp = error_response(csp, "connect-failed", errno);
804 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
805 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
807 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
811 free_http_response(rsp);
815 /* Add a trailing zero. This lets filter_popups
816 * use string operations.
821 /* Filter the popups on this read. */
822 if (block_popups_now)
824 filter_popups(buf, n);
826 #endif /* def KILLPOPUPS */
828 /* Normally, this would indicate that we've read
829 * as much as the server has sent us and we can
830 * close the client connection. However, Microsoft
831 * in its wisdom has released IIS/5 with a bug that
832 * prevents it from sending the trailing \r\n in
833 * a 302 redirect header (and possibly other headers).
834 * To work around this if we've haven't parsed
835 * a full header we'll append a trailing \r\n
836 * and see if this now generates a valid one.
838 * This hack shouldn't have any impacts. If we've
839 * already transmitted the header or if this is a
840 * SSL connection, then we won't bother with this
841 * hack. So we only work on partially received
842 * headers. If we append a \r\n and this still
843 * doesn't generate a valid header, then we won't
844 * transmit anything to the client.
849 if (server_body || http->ssl)
852 * If we have been buffering up the document,
853 * now is the time to apply content modification
854 * and send the result to the client.
859 * If the content filter fails, use the original
861 * (see p != NULL ? p : csp->iob->cur below)
863 if (NULL == (p = (*content_filter)(csp)))
865 csp->content_length = csp->iob->eod - csp->iob->cur;
868 hdr = sed(server_patterns, add_server_headers, csp);
871 if ((write_socket(csp->cfd, hdr, n) != n)
872 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != csp->content_length))
874 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
882 break; /* "game over, man" */
886 * This is NOT the body, so
887 * Let's pretend the server just sent us a blank line.
889 n = sprintf(buf, "\r\n");
892 * Now, let the normal header parsing algorithm below do its
893 * job. If it fails, we'll exit instead of continuing.
900 * If this is an SSL connection or we're in the body
901 * of the server document, just write it to the client,
902 * unless we need to buffer the body for later content-filtering
905 if (server_body || http->ssl)
909 add_to_iob(csp, buf, n);
913 if (write_socket(csp->cfd, buf, n) != n)
915 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
924 /* we're still looking for the end of the
925 * server's header ... (does that make header
926 * parsing an "out of body experience" ?
929 /* buffer up the data we just read */
930 add_to_iob(csp, buf, n);
932 /* get header lines from the iob */
934 while ((p = get_header(csp)))
938 /* see following note */
941 enlist(csp->headers, p);
945 /* NOTE: there are no "empty" headers so
946 * if the pointer `p' is not NULL we must
947 * assume that we reached the end of the
948 * buffer before we hit the end of the header.
955 /* Well, we tried our MS IIS/5
956 * hack and it didn't work.
957 * The header is incomplete
958 * and there isn't anything
959 * we can do about it.
965 /* Since we have to wait for
966 * more from the server before
967 * we can parse the headers
968 * we just continue here.
974 /* we have now received the entire header.
975 * filter it and send the result to the client
978 hdr = sed(server_patterns, add_server_headers, csp);
981 /* write the server's (modified) header to
982 * the client (along with anything else that
983 * may be in the buffer)
987 /* Start blocking popups if appropriate. */
989 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
990 !http->ssl && /* We talk plaintext */
991 block_popups) /* Policy allows */
993 block_popups_now = 1;
995 * even though the header has been found, don't forget about the
996 * left over portion of the buffer which will usually contain body text
998 n = strlen(csp->iob->cur);
999 filter_popups(csp->iob->cur, n);
1002 #endif /* def KILLPOPUPS */
1004 /* Buffer and pcrs filter this if appropriate. */
1006 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1007 !http->ssl && /* We talk plaintext */
1008 pcrs_filter) /* Policy allows */
1010 content_filter = pcrs_filter_response;
1013 /* Buffer and gif_deanimate this if appropriate. */
1015 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1016 !http->ssl && /* We talk plaintext */
1017 gif_deanimate) /* Policy allows */
1019 content_filter = gif_deanimate_response;
1024 * Only write if we're not buffering for content modification
1026 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1027 || (n = flush_socket(csp->cfd, csp) < 0)))
1029 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1031 /* the write failed, so don't bother
1032 * mentioning it to the client...
1033 * it probably can't hear us anyway.
1039 !content_filter && (byte_count += n);
1041 /* we're finished with the server's header */
1046 /* If this was a MS IIS/5 hack then it means
1047 * the server has already closed the
1048 * connection. Nothing more to read. Time
1059 return; /* huh? we should never get here */
1062 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1063 csp->ip_addr_str, http->cmd, byte_count);
1067 /*********************************************************************
1071 * Description : This is little more than chat. We only "serve" to
1072 * to close any socket that chat may have opened.
1075 * 1 : csp = Current client state (buffers, headers, etc...)
1079 *********************************************************************/
1081 void serve(struct client_state *csp)
1082 #else /* ifndef AMIGA */
1083 static void serve(struct client_state *csp)
1084 #endif /* def AMIGA */
1087 close_socket(csp->cfd);
1091 close_socket(csp->sfd);
1100 /*********************************************************************
1102 * Function : server_thread
1104 * Description : We only exist to call `serve' in a threaded environment.
1107 * 1 : data = Current client state (buffers, headers, etc...)
1109 * Returns : Always 0.
1111 *********************************************************************/
1112 static int32 server_thread(void *data)
1114 serve((struct client_state *) data);
1121 /*********************************************************************
1125 * Description : Load the config file and start the listen loop.
1126 * This function is a lot more *sane* with the `load_config'
1127 * and `listen_loop' functions; although it stills does
1128 * a *little* too much for my taste.
1131 * 1 : argc = Number of parameters (including $0).
1132 * 2 : argv = Array of (char *)'s to the parameters.
1134 * Returns : 1 if : can't open config file, unrecognized directive,
1135 * stats requested in multi-thread mode, can't open the
1136 * log file, can't open the jar file, listen port is invalid,
1137 * any load fails, and can't bind port.
1139 * Else main never returns, the process must be signaled
1140 * to terminate execution. Or, on Windows, use the
1141 * "File", "Exit" menu option.
1143 *********************************************************************/
1145 int _main(int argc, const char *argv[])
1147 int main(int argc, const char *argv[])
1152 "AmiTCP:db/junkbuster/config"
1153 #elif !defined(_WIN32)
1160 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1161 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1163 printf("JunkBuster proxy version " VERSION ".\n\n"
1164 "Usage: %s [configfile]\n\n"
1165 "See " HOME_PAGE_URL " for details.\n"
1166 "This program is distributed under the GNU GPL, version 2 or later.\n",
1170 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1172 printf(VERSION "\n");
1175 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1182 configfile = argv[1];
1189 #elif defined(_WIN32)
1195 signal(SIGPIPE, SIG_IGN);
1196 signal(SIGCHLD, SIG_IGN);
1198 #else /* ifdef _WIN32 */
1199 # ifdef _WIN_CONSOLE
1201 * We *are* in a windows console app.
1202 * Print a verbose messages about FAQ's and such
1204 printf(win32_blurb);
1205 # endif /* def _WIN_CONSOLE */
1206 #endif /* def _WIN32 */
1217 /*********************************************************************
1219 * Function : listen_loop
1221 * Description : bind the listen port and enter a "FOREVER" listening loop.
1227 *********************************************************************/
1228 static void listen_loop(void)
1230 struct client_state *csp = NULL;
1232 struct configuration_spec * config;
1234 config = load_config();
1236 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1237 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1239 bfd = bind_port(config->haddr, config->hport);
1243 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1244 "- There may be another junkbuster or some other "
1245 "proxy running on port %d",
1246 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1247 config->hport, config->hport
1249 /* shouldn't get here */
1253 config->need_bind = 0;
1258 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1259 while (waitpid(-1, NULL, WNOHANG) > 0)
1261 /* zombie children */
1263 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1266 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1268 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1272 memset(csp, '\0', sizeof(*csp));
1277 csp->config = config = load_config();
1279 if ( config->need_bind )
1282 * Since we were listening to the "old port", we will not see
1283 * a "listen" param change until the next IJB request. So, at
1284 * least 1 more request must be made for us to find the new
1285 * setting. I am simply closing the old socket and binding the
1288 * Which-ever is correct, we will serve 1 more page via the
1289 * old settings. This should probably be a "show-proxy-args"
1290 * request. This should not be a so common of an operation
1291 * that this will hurt people's feelings.
1296 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1297 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1298 bfd = bind_port(config->haddr, config->hport);
1302 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1303 "- There may be another junkbuster or some other "
1304 "proxy running on port %d",
1305 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1306 config->hport, config->hport
1308 /* shouldn't get here */
1312 config->need_bind = 0;
1315 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1317 if (!accept_connection(csp, bfd))
1319 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1332 log_error(LOG_LEVEL_CONNECT, "OK");
1336 /* by haroon - most of credit to srt19170 */
1337 csp->toggled_on = g_bToggleIJB;
1340 if (run_loader(csp))
1342 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1343 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1347 if (block_acl(NULL,csp))
1349 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1350 close_socket(csp->cfd);
1354 #endif /* def ACL_FILES */
1356 /* add it to the list of clients */
1357 csp->next = clients->next;
1358 clients->next = csp;
1360 if (config->multi_threaded)
1364 /* this is a switch () statment in the C preprocessor - ugh */
1365 #undef SELECTED_ONE_OPTION
1367 /* Use Pthreads in preference to native code */
1368 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1369 #define SELECTED_ONE_OPTION
1371 pthread_t the_thread;
1372 pthread_attr_t attrs;
1374 pthread_attr_init(&attrs);
1375 child_id = (pthread_create(&the_thread, &attrs,
1376 (void*)serve, csp) ? -1 : 0);
1377 pthread_attr_destroy(&attrs);
1381 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1382 #define SELECTED_ONE_OPTION
1383 child_id = _beginthread(
1389 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1390 #define SELECTED_ONE_OPTION
1392 thread_id tid = spawn_thread
1393 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1395 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1397 child_id = (int) tid;
1406 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1407 #define SELECTED_ONE_OPTION
1408 csp->cfd = ReleaseSocket(csp->cfd, -1);
1409 if((child_id = (int)CreateNewProcTags(
1410 NP_Entry, (ULONG)server_thread,
1411 NP_Output, Output(),
1412 NP_CloseOutput, FALSE,
1413 NP_Name, (ULONG)"junkbuster child",
1414 NP_StackSize, 200*1024,
1418 ((struct Task *)child_id)->tc_UserData = csp;
1419 Signal((struct Task *)child_id, SIGF_SINGLE);
1424 #if !defined(SELECTED_ONE_OPTION)
1427 /* This block is only needed when using fork().
1428 * When using threads, the server thread was
1429 * created and run by the call to _beginthread().
1431 if (child_id == 0) /* child */
1437 else if (child_id > 0) /* parent */
1439 /* in a fork()'d environment, the parent's
1440 * copy of the client socket and the CSP
1444 #if !defined(_WIN32) && defined(__CYGWIN__)
1446 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1447 close_socket(csp->cfd);
1452 #undef SELECTED_ONE_OPTION
1453 /* end of cpp switch () */
1455 if (child_id < 0) /* failed */
1457 char buf[BUFFER_SIZE];
1459 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1461 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1463 write_socket(csp->cfd, buf, strlen(buf));
1464 close_socket(csp->cfd);