1 const char jcc_rcs[] = "$Id: jcc.c,v 1.24 2001/07/13 14:00:40 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.24 2001/07/13 14:00:40 oes
37 * - Generic content modification scheme:
38 * Each feature has its own applicability flag that is set
39 * from csp->action->flags.
40 * Replaced the "filtering" int flag , by a function pointer
41 * "content_filter" to the function that will do the content
42 * modification. If it is != NULL, the document will be buffered
43 * and processed through *content_filter, which must set
44 * csp->content_length and return a modified copy of the body
45 * or return NULL (on failiure).
46 * - Changed csp->is_text to the more generic bitmap csp->content_type
47 * which can currently take the valued CT_TEXT or CT_GIF
49 * - Removed all #ifdef PCRS
51 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
52 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
53 * the `block_acl' call. This prevents a compilation error when the user
54 * does not wish to use the "ACL" feature.
56 * Revision 1.22 2001/06/29 21:45:41 oes
57 * Indentation, CRLF->LF, Tab-> Space
59 * Revision 1.21 2001/06/29 13:29:36 oes
60 * - Cleaned up, improved comments
61 * - Unified all possible interceptors (CGI,
62 * block, trust, fast_redirect) in one
63 * place, with one (CGI) answer generation
64 * mechansim. Much clearer now.
65 * - Removed the GIF image generation, which
66 * is now done in filters.c:block_url()
67 * - Made error conditions like domain lookup
68 * failiure or (various) problems while talking
69 * to the server use cgi.c:error_response()
70 * instead of generating HTML/HTTP in chat() (yuck!)
71 * - Removed logentry from cancelled commit
73 * Revision 1.20 2001/06/09 10:55:28 jongfoster
74 * Changing BUFSIZ ==> BUFFER_SIZE
76 * Revision 1.19 2001/06/07 23:12:52 jongfoster
77 * Replacing function pointer in struct gateway with a directly
78 * called function forwarded_connect().
79 * Replacing struct gateway with struct forward_spec
81 * Revision 1.18 2001/06/03 19:12:16 oes
82 * introduced new cgi handling
84 * Revision 1.17 2001/06/01 20:07:23 jongfoster
85 * Now uses action +image-blocker{} rather than config->tinygif
87 * Revision 1.16 2001/06/01 18:49:17 jongfoster
88 * Replaced "list_share" with "list" - the tiny memory gain was not
89 * worth the extra complexity.
91 * Revision 1.15 2001/05/31 21:24:47 jongfoster
92 * Changed "permission" to "action" throughout.
93 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
94 * Moved vanilla wafer check into chat(), since we must now
95 * decide whether or not to add it based on the URL.
97 * Revision 1.14 2001/05/29 20:14:01 joergs
98 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
101 * Revision 1.13 2001/05/29 09:50:24 jongfoster
102 * Unified blocklist/imagelist/permissionslist.
103 * File format is still under discussion, but the internal changes
106 * Also modified interceptor behaviour:
107 * - We now intercept all URLs beginning with one of the following
108 * prefixes (and *only* these prefixes):
110 * * http://ijbswa.sf.net/config/
111 * * http://ijbswa.sourceforge.net/config/
112 * - New interceptors "home page" - go to http://i.j.b/ to see it.
113 * - Internal changes so that intercepted and fast redirect pages
114 * are not replaced with an image.
115 * - Interceptors now have the option to send a binary page direct
116 * to the client. (i.e. ijb-send-banner uses this)
117 * - Implemented show-url-info interceptor. (Which is why I needed
118 * the above interceptors changes - a typical URL is
119 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
120 * The previous mechanism would not have intercepted that, and
121 * if it had been intercepted then it then it would have replaced
124 * Revision 1.12 2001/05/27 22:17:04 oes
126 * - re_process_buffer no longer writes the modified buffer
127 * to the client, which was very ugly. It now returns the
128 * buffer, which it is then written by chat.
130 * - content_length now adjusts the Content-Length: header
131 * for modified documents rather than crunch()ing it.
132 * (Length info in csp->content_length, which is 0 for
133 * unmodified documents)
135 * - For this to work, sed() is called twice when filtering.
137 * Revision 1.11 2001/05/26 17:27:53 jongfoster
138 * Added support for CLF and fixed LOG_LEVEL_LOG.
139 * Also did CRLF->LF fix of my previous patch.
141 * Revision 1.10 2001/05/26 15:26:15 jongfoster
142 * ACL feature now provides more security by immediately dropping
143 * connections from untrusted hosts.
145 * Revision 1.9 2001/05/26 00:28:36 jongfoster
146 * Automatic reloading of config file.
147 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
148 * Most of the global variables have been moved to a new
149 * struct configuration_spec, accessed through csp->config->globalname
150 * Most of the globals remaining are used by the Win32 GUI.
152 * Revision 1.8 2001/05/25 22:43:18 jongfoster
153 * Fixing minor memory leak and buffer overflow.
155 * Revision 1.7 2001/05/25 22:34:30 jongfoster
158 * Revision 1.6 2001/05/23 00:13:58 joergs
159 * AmigaOS support fixed.
161 * Revision 1.5 2001/05/22 18:46:04 oes
163 * - Enabled filtering banners by size rather than URL
164 * by adding patterns that replace all standard banner
165 * sizes with the "Junkbuster" gif to the re_filterfile
167 * - Enabled filtering WebBugs by providing a pattern
168 * which kills all 1x1 images
170 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
171 * which is selected by the (nonstandard and therefore
172 * capital) letter 'U' in the option string.
173 * It causes the quantifiers to be ungreedy by default.
174 * Appending a ? turns back to greedy (!).
176 * - Added a new interceptor ijb-send-banner, which
177 * sends back the "Junkbuster" gif. Without imagelist or
178 * MSIE detection support, or if tinygif = 1, or the
179 * URL isn't recognized as an imageurl, a lame HTML
180 * explanation is sent instead.
182 * - Added new feature, which permits blocking remote
183 * script redirects and firing back a local redirect
185 * The feature is conditionally compiled, i.e. it
186 * can be disabled with --disable-fast-redirects,
187 * plus it must be activated by a "fast-redirects"
188 * line in the config file, has its own log level
189 * and of course wants to be displayed by show-proxy-args
190 * Note: Boy, all the #ifdefs in 1001 locations and
191 * all the fumbling with configure.in and acconfig.h
192 * were *way* more work than the feature itself :-(
194 * - Because a generic redirect template was needed for
195 * this, tinygif = 3 now uses the same.
197 * - Moved GIFs, and other static HTTP response templates
202 * - Removed some >400 CRs again (Jon, you really worked
205 * Revision 1.4 2001/05/21 19:34:01 jongfoster
206 * Made failure to bind() a fatal error.
208 * Revision 1.3 2001/05/20 01:21:20 jongfoster
209 * Version 2.9.4 checkin.
210 * - Merged popupfile and cookiefile, and added control over PCRS
211 * filtering, in new "permissionsfile".
212 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
213 * file error you now get a message box (in the Win32 GUI) rather
214 * than the program exiting with no explanation.
215 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
217 * - Removed tabs from "config"
218 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
219 * - Bumped up version number.
221 * Revision 1.2 2001/05/17 22:34:44 oes
222 * - Added hint on GIF char array generation to jcc.c
223 * - Cleaned CRLF's from the sources and related files
224 * - Repaired logging for REF and FRC
226 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
227 * Initial import of version 2.9.3 source tree
230 *********************************************************************/
236 #include <sys/types.h>
243 #ifdef FEATURE_PTHREAD
245 #endif /* def FEATURE_PTHREAD */
248 # ifndef FEATURE_PTHREAD
249 # include <windows.h>
250 # include <process.h>
251 # endif /* ndef FEATURE_PTHREAD */
254 # ifndef _WIN_CONSOLE
256 # endif /* ndef _WIN_CONSOLE */
258 #else /* ifndef _WIN32 */
261 # include <sys/time.h>
262 # include <sys/wait.h>
263 # include <sys/stat.h>
267 # include <socket.h> /* BeOS has select() for sockets only. */
268 # include <OS.h> /* declarations for threads and stuff. */
282 #include "showargs.h"
284 #include "killpopup.h"
285 #include "miscutil.h"
287 #include "jbsockets.h"
292 const char jcc_h_rcs[] = JCC_H_VERSION;
293 const char project_h_rcs[] = PROJECT_H_VERSION;
295 struct client_state clients[1];
296 struct file_list files[1];
299 int urls_read = 0; /* total nr of urls read inc rejected */
300 int urls_rejected = 0; /* total nr of urls rejected */
301 #endif /* def STATISTICS */
304 static void listen_loop(void);
305 static void chat(struct client_state *csp);
307 void serve(struct client_state *csp);
308 #else /* ifndef AMIGA */
309 static void serve(struct client_state *csp);
310 #endif /* def AMIGA */
313 static int32 server_thread(void *data);
314 #endif /* def __BEOS__ */
317 #define sleep(N) Sleep(((N) * 1000))
321 /* The vanilla wafer. */
322 static const char VANILLA_WAFER[] =
323 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
324 "Do_not_send_me_any_copyrighted_information_other_than_the_"
325 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
326 "In_particular_do_not_send_me_any_cookies_that_"
327 "are_subject_to_a_claim_of_copyright_by_anybody._"
328 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
329 "(copyright_or_otherwise)_applying_to_any_cookie._";
332 /*********************************************************************
336 * Description : Once a connection to the client has been accepted,
337 * this function is called (via serve()) to handle the
338 * main business of the communication. When this
339 * function returns, the caller must close the client
343 * 1 : csp = Current client state (buffers, headers, etc...)
345 * Returns : On success, the number of bytes written are returned (zero
346 * indicates nothing was written). On error, -1 is returned,
347 * and errno is set appropriately. If count is zero and the
348 * file descriptor refers to a regular file, 0 will be
349 * returned without causing any other effect. For a special
350 * file, the results are not portable.
352 *********************************************************************/
353 static void chat(struct client_state *csp)
356 * This next lines are a little ugly, but they simplifies the if statements below.
357 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
358 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
361 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
362 #else /* ifndef TOGGLE */
363 # define IS_TOGGLED_ON_AND
364 #endif /* ndef TOGGLE */
366 # define IS_NOT_FORCED_AND (!csp->force) &&
367 #else /* ifndef FORCE_LOAD */
368 # define IS_NOT_FORCED_AND
369 #endif /* def FORCE_LOAD */
371 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
373 char buf[BUFFER_SIZE];
377 int n, maxfd, server_body;
378 int ms_iis5_hack = 0;
380 const struct forward_spec * fwd;
381 struct http_request *http;
383 int block_popups; /* bool, 1==will block popups */
384 int block_popups_now = 0; /* bool, 1==currently blocking popups */
385 #endif /* def KILLPOPUPS */
387 int pcrs_filter; /* bool, 1==will filter through pcrs */
388 int gif_deanimate; /* bool, 1==will deanimate gifs */
390 /* Function that does the content filtering for the current request */
391 char *(*content_filter)() = NULL;
393 /* Skeleton for HTTP response, if we should intercept the request */
394 struct http_response *rsp;
399 * Read the client's request. Note that since we're not using select() we
400 * could get blocked here if a client connected, then didn't say anything!
405 n = read_socket(csp->cfd, buf, sizeof(buf));
407 if (n <= 0) break; /* error! */
409 add_to_iob(csp, buf, n);
411 req = get_header(csp);
415 break; /* no HTTP request! */
420 continue; /* more to come! */
424 /* If this request contains the FORCE_PREFIX,
425 * better get rid of it now and set the force flag --oes
428 if (strstr(req, FORCE_PREFIX))
430 strclean(req, FORCE_PREFIX);
431 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
438 #endif /* def FORCE_LOAD */
440 parse_http_request(req, http, csp);
445 if (http->cmd == NULL)
447 strcpy(buf, CHEADER);
448 write_socket(csp->cfd, buf, strlen(buf));
450 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
455 /* decide how to route the HTTP request */
457 if ((fwd = forward_url(http, csp)) == NULL)
459 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
460 /* Never get here - LOG_LEVEL_FATAL causes program exit */
463 /* build the http request to send to the server
464 * we have to do one of the following:
466 * create = use the original HTTP request to create a new
467 * HTTP request that has only the path component
468 * without the http://domainspec
469 * pass = pass the original HTTP request unchanged
471 * drop = drop the HTTP request
476 * +--------+--------+
478 * 0 | create | drop |
480 * Forwarding +--------+--------+
484 * +--------+--------+
488 if (fwd->forward_host)
490 /* if forwarding, just pass the request as is */
491 enlist(csp->headers, http->cmd);
497 /* otherwise elide the host information from the url */
499 p = strsav(p, http->gpc);
501 p = strsav(p, http->path);
503 p = strsav(p, http->ver);
504 enlist(csp->headers, p);
509 /* decide what we're to do with cookies */
512 if (!csp->toggled_on)
514 /* Most compatible set of actions (i.e. none) */
515 init_current_action(csp->action);
518 #endif /* ndef TOGGLE */
520 url_actions(http, csp);
525 * If we're logging cookies in a cookie jar, and the user has not
526 * supplied any wafers, and the user has not told us to suppress the
527 * vanilla wafer, then send the vanilla wafer.
529 if ((csp->config->jarfile != NULL)
530 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
531 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
533 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
535 #endif /* def JAR_FILES */
538 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
539 #endif /* def KILLPOPUPS */
541 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
542 ((csp->action->flags & ACTION_FILTER) != 0);
544 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
546 /* grab the rest of the client's headers */
550 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
552 n = read_socket(csp->cfd, buf, sizeof(buf));
555 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
558 add_to_iob(csp, buf, n);
562 if (p == NULL) break;
564 enlist(csp->headers, p);
568 /* We have a request. */
570 hdr = sed(client_patterns, add_client_headers, csp);
571 destroy_list(csp->headers);
574 * Now, check to see if we need to intercept it, i.e.
579 /* a CGI call was detected and answered */
580 (NULL != (rsp = dispatch_cgi(csp)))
582 /* or we are enabled and... */
585 /* ..the request was blocked */
586 ( NULL != (rsp = block_url(csp)))
590 || ( NULL != (rsp = trust_url(csp)))
593 /* ..or a fast redirect kicked in */
594 #ifdef FAST_REDIRECTS
595 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
596 (NULL != (rsp = redirect_url(csp))))
597 #endif /* def FAST_REDIRECTS */
601 /* Write the answer to the client */
602 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
603 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
605 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
609 /* Count as a rejected request */
611 #endif /* def STATISTICS */
613 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
614 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
615 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
617 /* Clean up and return */
618 free_http_response(rsp);
623 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
625 if (fwd->forward_host)
627 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
628 fwd->forward_host, fwd->forward_port, http->hostport);
632 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
635 /* here we connect to the server, gateway, or the forwarder */
637 csp->sfd = forwarded_connect(fwd, http, csp);
641 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
646 rsp = error_response(csp, "no-such-domain", errno);
648 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
649 csp->ip_addr_str, http->cmd);
653 rsp = error_response(csp, "connect-failed", errno);
655 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
656 csp->ip_addr_str, http->cmd);
659 /* Write the answer to the client */
662 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
663 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
665 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
669 free_http_response(rsp);
674 log_error(LOG_LEVEL_CONNECT, "OK");
676 if (fwd->forward_host || (http->ssl == 0))
678 /* write the client's (modified) header to the server
679 * (along with anything else that may be in the buffer)
684 if ((write_socket(csp->sfd, hdr, n) != n)
685 || (flush_socket(csp->sfd, csp ) < 0))
687 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
690 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
691 csp->ip_addr_str, http->cmd);
693 rsp = error_response(csp, "connect-failed", errno);
697 if ((write_socket(csp->cfd, rsp->head, n) != n)
698 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
700 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
704 free_http_response(rsp);
712 * We're running an SSL tunnel and we're not forwarding,
713 * so just send the "connect succeeded" message to the
714 * client, flush the rest, and get out of the way.
716 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
717 csp->ip_addr_str, http->cmd);
719 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
727 /* we're finished with the client's header */
730 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
732 /* pass data between the client and server
733 * until one or the other shuts down the connection.
742 FD_SET(csp->cfd, &rfds);
743 FD_SET(csp->sfd, &rfds);
745 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
749 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
753 /* this is the body of the browser's request
754 * just read it and write it.
757 if (FD_ISSET(csp->cfd, &rfds))
759 n = read_socket(csp->cfd, buf, sizeof(buf));
763 break; /* "game over, man" */
766 if (write_socket(csp->sfd, buf, n) != n)
768 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
775 * The server wants to talk. It could be the header or the body.
776 * If `hdr' is null, then it's the header otherwise it's the body.
777 * FIXME: Does `hdr' really mean `host'? No.
781 if (FD_ISSET(csp->sfd, &rfds))
784 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
788 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
790 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
791 csp->ip_addr_str, http->cmd);
793 rsp = error_response(csp, "connect-failed", errno);
797 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
798 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
800 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
804 free_http_response(rsp);
808 /* Add a trailing zero. This lets filter_popups
809 * use string operations.
814 /* Filter the popups on this read. */
815 if (block_popups_now)
817 filter_popups(buf, n);
819 #endif /* def KILLPOPUPS */
821 /* Normally, this would indicate that we've read
822 * as much as the server has sent us and we can
823 * close the client connection. However, Microsoft
824 * in its wisdom has released IIS/5 with a bug that
825 * prevents it from sending the trailing \r\n in
826 * a 302 redirect header (and possibly other headers).
827 * To work around this if we've haven't parsed
828 * a full header we'll append a trailing \r\n
829 * and see if this now generates a valid one.
831 * This hack shouldn't have any impacts. If we've
832 * already transmitted the header or if this is a
833 * SSL connection, then we won't bother with this
834 * hack. So we only work on partially received
835 * headers. If we append a \r\n and this still
836 * doesn't generate a valid header, then we won't
837 * transmit anything to the client.
842 if (server_body || http->ssl)
845 * If we have been buffering up the document,
846 * now is the time to apply content modification
847 * and send the result to the client.
852 * If the content filter fails, use the original
854 * (see p != NULL ? p : csp->iob->cur below)
856 if (NULL == (p = (*content_filter)(csp)))
858 csp->content_length = csp->iob->eod - csp->iob->cur;
861 hdr = sed(server_patterns, add_server_headers, csp);
864 if ((write_socket(csp->cfd, hdr, n) != n)
865 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != csp->content_length))
867 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
875 break; /* "game over, man" */
879 * This is NOT the body, so
880 * Let's pretend the server just sent us a blank line.
882 n = sprintf(buf, "\r\n");
885 * Now, let the normal header parsing algorithm below do its
886 * job. If it fails, we'll exit instead of continuing.
893 * If this is an SSL connection or we're in the body
894 * of the server document, just write it to the client.
897 if (server_body || http->ssl)
902 add_to_iob(csp, buf, n); /* Buffer the body for filtering */
908 if (write_socket(csp->cfd, buf, n) != n)
910 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
919 /* we're still looking for the end of the
920 * server's header ... (does that make header
921 * parsing an "out of body experience" ?
924 /* buffer up the data we just read */
925 add_to_iob(csp, buf, n);
927 /* get header lines from the iob */
929 while ((p = get_header(csp)))
933 /* see following note */
936 enlist(csp->headers, p);
940 /* NOTE: there are no "empty" headers so
941 * if the pointer `p' is not NULL we must
942 * assume that we reached the end of the
943 * buffer before we hit the end of the header.
950 /* Well, we tried our MS IIS/5
951 * hack and it didn't work.
952 * The header is incomplete
953 * and there isn't anything
954 * we can do about it.
960 /* Since we have to wait for
961 * more from the server before
962 * we can parse the headers
963 * we just continue here.
969 /* we have now received the entire header.
970 * filter it and send the result to the client
973 hdr = sed(server_patterns, add_server_headers, csp);
976 /* write the server's (modified) header to
977 * the client (along with anything else that
978 * may be in the buffer)
982 /* Start blocking popups if appropriate. */
984 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
985 !http->ssl && /* We talk plaintext */
986 block_popups) /* Policy allows */
988 block_popups_now = 1;
991 #endif /* def KILLPOPUPS */
993 /* Buffer and pcrs filter this if appropriate. */
995 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
996 !http->ssl && /* We talk plaintext */
997 pcrs_filter) /* Policy allows */
999 content_filter = pcrs_filter_response;
1002 /* Buffer and gif_deanimate this if appropriate. */
1004 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1005 !http->ssl && /* We talk plaintext */
1006 gif_deanimate) /* Policy allows */
1008 content_filter = gif_deanimate_response;
1013 * Only write if we're not buffering for content modification
1015 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1016 || (n = flush_socket(csp->cfd, csp) < 0)))
1018 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1020 /* the write failed, so don't bother
1021 * mentioning it to the client...
1022 * it probably can't hear us anyway.
1028 !content_filter && (byte_count += n);
1030 /* we're finished with the server's header */
1035 /* If this was a MS IIS/5 hack then it means
1036 * the server has already closed the
1037 * connection. Nothing more to read. Time
1048 return; /* huh? we should never get here */
1051 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1052 csp->ip_addr_str, http->cmd, byte_count);
1056 /*********************************************************************
1060 * Description : This is little more than chat. We only "serve" to
1061 * to close any socket that chat may have opened.
1064 * 1 : csp = Current client state (buffers, headers, etc...)
1068 *********************************************************************/
1070 void serve(struct client_state *csp)
1071 #else /* ifndef AMIGA */
1072 static void serve(struct client_state *csp)
1073 #endif /* def AMIGA */
1076 close_socket(csp->cfd);
1080 close_socket(csp->sfd);
1089 /*********************************************************************
1091 * Function : server_thread
1093 * Description : We only exist to call `serve' in a threaded environment.
1096 * 1 : data = Current client state (buffers, headers, etc...)
1098 * Returns : Always 0.
1100 *********************************************************************/
1101 static int32 server_thread(void *data)
1103 serve((struct client_state *) data);
1110 /*********************************************************************
1114 * Description : Load the config file and start the listen loop.
1115 * This function is a lot more *sane* with the `load_config'
1116 * and `listen_loop' functions; although it stills does
1117 * a *little* too much for my taste.
1120 * 1 : argc = Number of parameters (including $0).
1121 * 2 : argv = Array of (char *)'s to the parameters.
1123 * Returns : 1 if : can't open config file, unrecognized directive,
1124 * stats requested in multi-thread mode, can't open the
1125 * log file, can't open the jar file, listen port is invalid,
1126 * any load fails, and can't bind port.
1128 * Else main never returns, the process must be signaled
1129 * to terminate execution. Or, on Windows, use the
1130 * "File", "Exit" menu option.
1132 *********************************************************************/
1134 int _main(int argc, const char *argv[])
1136 int main(int argc, const char *argv[])
1141 "AmiTCP:db/junkbuster/config"
1142 #elif !defined(_WIN32)
1149 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1150 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1152 printf("JunkBuster proxy version " VERSION ".\n\n"
1153 "Usage: %s [configfile]\n\n"
1154 "See " HOME_PAGE_URL " for details.\n"
1155 "This program is distributed under the GNU GPL, version 2 or later.\n",
1159 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1161 printf(VERSION "\n");
1164 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1171 configfile = argv[1];
1178 #elif defined(_WIN32)
1184 signal(SIGPIPE, SIG_IGN);
1185 signal(SIGCHLD, SIG_IGN);
1187 #else /* ifdef _WIN32 */
1188 # ifdef _WIN_CONSOLE
1190 * We *are* in a windows console app.
1191 * Print a verbose messages about FAQ's and such
1193 printf(win32_blurb);
1194 # endif /* def _WIN_CONSOLE */
1195 #endif /* def _WIN32 */
1206 /*********************************************************************
1208 * Function : listen_loop
1210 * Description : bind the listen port and enter a "FOREVER" listening loop.
1216 *********************************************************************/
1217 static void listen_loop(void)
1219 struct client_state *csp = NULL;
1221 struct configuration_spec * config;
1223 config = load_config();
1225 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1226 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1228 bfd = bind_port(config->haddr, config->hport);
1232 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1233 "- There may be another junkbuster or some other "
1234 "proxy running on port %d",
1235 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1236 config->hport, config->hport
1238 /* shouldn't get here */
1242 config->need_bind = 0;
1247 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1248 while (waitpid(-1, NULL, WNOHANG) > 0)
1250 /* zombie children */
1252 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1255 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1257 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1261 memset(csp, '\0', sizeof(*csp));
1266 csp->config = config = load_config();
1268 if ( config->need_bind )
1271 * Since we were listening to the "old port", we will not see
1272 * a "listen" param change until the next IJB request. So, at
1273 * least 1 more request must be made for us to find the new
1274 * setting. I am simply closing the old socket and binding the
1277 * Which-ever is correct, we will serve 1 more page via the
1278 * old settings. This should probably be a "show-proxy-args"
1279 * request. This should not be a so common of an operation
1280 * that this will hurt people's feelings.
1285 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1286 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1287 bfd = bind_port(config->haddr, config->hport);
1291 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1292 "- There may be another junkbuster or some other "
1293 "proxy running on port %d",
1294 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1295 config->hport, config->hport
1297 /* shouldn't get here */
1301 config->need_bind = 0;
1304 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1306 if (!accept_connection(csp, bfd))
1308 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1321 log_error(LOG_LEVEL_CONNECT, "OK");
1325 /* by haroon - most of credit to srt19170 */
1326 csp->toggled_on = g_bToggleIJB;
1329 if (run_loader(csp))
1331 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1332 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1336 if (block_acl(NULL,csp))
1338 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1339 close_socket(csp->cfd);
1343 #endif /* def ACL_FILES */
1345 /* add it to the list of clients */
1346 csp->next = clients->next;
1347 clients->next = csp;
1349 if (config->multi_threaded)
1353 /* this is a switch () statment in the C preprocessor - ugh */
1354 #undef SELECTED_ONE_OPTION
1356 /* Use Pthreads in preference to native code */
1357 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1358 #define SELECTED_ONE_OPTION
1360 pthread_t the_thread;
1361 pthread_attr_t attrs;
1363 pthread_attr_init(&attrs);
1364 child_id = (pthread_create(&the_thread, &attrs,
1365 (void*)serve, csp) ? -1 : 0);
1366 pthread_attr_destroy(&attrs);
1370 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1371 #define SELECTED_ONE_OPTION
1372 child_id = _beginthread(
1378 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1379 #define SELECTED_ONE_OPTION
1381 thread_id tid = spawn_thread
1382 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1384 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1386 child_id = (int) tid;
1395 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1396 #define SELECTED_ONE_OPTION
1397 csp->cfd = ReleaseSocket(csp->cfd, -1);
1398 if((child_id = (int)CreateNewProcTags(
1399 NP_Entry, (ULONG)server_thread,
1400 NP_Output, Output(),
1401 NP_CloseOutput, FALSE,
1402 NP_Name, (ULONG)"junkbuster child",
1403 NP_StackSize, 200*1024,
1407 ((struct Task *)child_id)->tc_UserData = csp;
1408 Signal((struct Task *)child_id, SIGF_SINGLE);
1413 #if !defined(SELECTED_ONE_OPTION)
1416 /* This block is only needed when using fork().
1417 * When using threads, the server thread was
1418 * created and run by the call to _beginthread().
1420 if (child_id == 0) /* child */
1426 else if (child_id > 0) /* parent */
1428 /* in a fork()'d environment, the parent's
1429 * copy of the client socket and the CSP
1433 #if !defined(_WIN32) && defined(__CYGWIN__)
1435 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1436 close_socket(csp->cfd);
1441 #undef SELECTED_ONE_OPTION
1442 /* end of cpp switch () */
1444 if (child_id < 0) /* failed */
1446 char buf[BUFFER_SIZE];
1448 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1450 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1452 write_socket(csp->cfd, buf, strlen(buf));
1453 close_socket(csp->cfd);