1 const char jcc_rcs[] = "$Id: jcc.c,v 1.35 2001/07/31 14:44:22 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.35 2001/07/31 14:44:22 oes
37 * Deleted unused size parameter from filter_popups()
39 * Revision 1.34 2001/07/30 22:08:36 jongfoster
40 * Tidying up #defines:
41 * - All feature #defines are now of the form FEATURE_xxx
42 * - Permanently turned off WIN_GUI_EDIT
43 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
45 * Revision 1.33 2001/07/29 19:32:00 jongfoster
46 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
48 * Revision 1.32 2001/07/29 18:47:05 jongfoster
49 * Adding missing #include "loadcfg.h"
51 * Revision 1.31 2001/07/29 12:17:48 oes
52 * Applied pthread fix by Paul Lieverse
54 * Revision 1.30 2001/07/25 22:57:13 jongfoster
55 * __BEOS__ no longer overrides FEATURE_PTHREAD.
56 * This is because FEATURE_PTHREAD will soon be widely used, so I
57 * want to keep it simple.
59 * Revision 1.29 2001/07/24 12:47:06 oes
60 * Applied BeOS support update by Eugenia
62 * Revision 1.28 2001/07/23 13:26:12 oes
63 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
65 * Revision 1.27 2001/07/19 19:09:47 haroon
66 * - Added code to take care of the situation where while processing the first
67 * server response (which includes the server header), after finding the end
68 * of the headers we were not looking past the end of the headers for
69 * content modification. I enabled it for filter_popups.
70 * Someone else should look to see if other similar operations should be
71 * done to the discarded portion of the buffer.
73 * Note 2001/07/20: No, the other content modification mechanisms will process
74 * the whole iob later anyway. --oes
76 * Revision 1.26 2001/07/18 12:31:36 oes
79 * Revision 1.25 2001/07/15 19:43:49 jongfoster
80 * Supports POSIX threads.
81 * Also removed some unused #includes.
83 * Revision 1.24 2001/07/13 14:00:40 oes
84 * - Generic content modification scheme:
85 * Each feature has its own applicability flag that is set
86 * from csp->action->flags.
87 * Replaced the "filtering" int flag , by a function pointer
88 * "content_filter" to the function that will do the content
89 * modification. If it is != NULL, the document will be buffered
90 * and processed through *content_filter, which must set
91 * csp->content_length and return a modified copy of the body
92 * or return NULL (on failiure).
93 * - Changed csp->is_text to the more generic bitmap csp->content_type
94 * which can currently take the valued CT_TEXT or CT_GIF
96 * - Removed all #ifdef PCRS
98 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
99 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
100 * the `block_acl' call. This prevents a compilation error when the user
101 * does not wish to use the "ACL" feature.
103 * Revision 1.22 2001/06/29 21:45:41 oes
104 * Indentation, CRLF->LF, Tab-> Space
106 * Revision 1.21 2001/06/29 13:29:36 oes
107 * - Cleaned up, improved comments
108 * - Unified all possible interceptors (CGI,
109 * block, trust, fast_redirect) in one
110 * place, with one (CGI) answer generation
111 * mechansim. Much clearer now.
112 * - Removed the GIF image generation, which
113 * is now done in filters.c:block_url()
114 * - Made error conditions like domain lookup
115 * failiure or (various) problems while talking
116 * to the server use cgi.c:error_response()
117 * instead of generating HTML/HTTP in chat() (yuck!)
118 * - Removed logentry from cancelled commit
120 * Revision 1.20 2001/06/09 10:55:28 jongfoster
121 * Changing BUFSIZ ==> BUFFER_SIZE
123 * Revision 1.19 2001/06/07 23:12:52 jongfoster
124 * Replacing function pointer in struct gateway with a directly
125 * called function forwarded_connect().
126 * Replacing struct gateway with struct forward_spec
128 * Revision 1.18 2001/06/03 19:12:16 oes
129 * introduced new cgi handling
131 * Revision 1.17 2001/06/01 20:07:23 jongfoster
132 * Now uses action +image-blocker{} rather than config->tinygif
134 * Revision 1.16 2001/06/01 18:49:17 jongfoster
135 * Replaced "list_share" with "list" - the tiny memory gain was not
136 * worth the extra complexity.
138 * Revision 1.15 2001/05/31 21:24:47 jongfoster
139 * Changed "permission" to "action" throughout.
140 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
141 * Moved vanilla wafer check into chat(), since we must now
142 * decide whether or not to add it based on the URL.
144 * Revision 1.14 2001/05/29 20:14:01 joergs
145 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
148 * Revision 1.13 2001/05/29 09:50:24 jongfoster
149 * Unified blocklist/imagelist/permissionslist.
150 * File format is still under discussion, but the internal changes
153 * Also modified interceptor behaviour:
154 * - We now intercept all URLs beginning with one of the following
155 * prefixes (and *only* these prefixes):
157 * * http://ijbswa.sf.net/config/
158 * * http://ijbswa.sourceforge.net/config/
159 * - New interceptors "home page" - go to http://i.j.b/ to see it.
160 * - Internal changes so that intercepted and fast redirect pages
161 * are not replaced with an image.
162 * - Interceptors now have the option to send a binary page direct
163 * to the client. (i.e. ijb-send-banner uses this)
164 * - Implemented show-url-info interceptor. (Which is why I needed
165 * the above interceptors changes - a typical URL is
166 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
167 * The previous mechanism would not have intercepted that, and
168 * if it had been intercepted then it then it would have replaced
171 * Revision 1.12 2001/05/27 22:17:04 oes
173 * - re_process_buffer no longer writes the modified buffer
174 * to the client, which was very ugly. It now returns the
175 * buffer, which it is then written by chat.
177 * - content_length now adjusts the Content-Length: header
178 * for modified documents rather than crunch()ing it.
179 * (Length info in csp->content_length, which is 0 for
180 * unmodified documents)
182 * - For this to work, sed() is called twice when filtering.
184 * Revision 1.11 2001/05/26 17:27:53 jongfoster
185 * Added support for CLF and fixed LOG_LEVEL_LOG.
186 * Also did CRLF->LF fix of my previous patch.
188 * Revision 1.10 2001/05/26 15:26:15 jongfoster
189 * ACL feature now provides more security by immediately dropping
190 * connections from untrusted hosts.
192 * Revision 1.9 2001/05/26 00:28:36 jongfoster
193 * Automatic reloading of config file.
194 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
195 * Most of the global variables have been moved to a new
196 * struct configuration_spec, accessed through csp->config->globalname
197 * Most of the globals remaining are used by the Win32 GUI.
199 * Revision 1.8 2001/05/25 22:43:18 jongfoster
200 * Fixing minor memory leak and buffer overflow.
202 * Revision 1.7 2001/05/25 22:34:30 jongfoster
205 * Revision 1.6 2001/05/23 00:13:58 joergs
206 * AmigaOS support fixed.
208 * Revision 1.5 2001/05/22 18:46:04 oes
210 * - Enabled filtering banners by size rather than URL
211 * by adding patterns that replace all standard banner
212 * sizes with the "Junkbuster" gif to the re_filterfile
214 * - Enabled filtering WebBugs by providing a pattern
215 * which kills all 1x1 images
217 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
218 * which is selected by the (nonstandard and therefore
219 * capital) letter 'U' in the option string.
220 * It causes the quantifiers to be ungreedy by default.
221 * Appending a ? turns back to greedy (!).
223 * - Added a new interceptor ijb-send-banner, which
224 * sends back the "Junkbuster" gif. Without imagelist or
225 * MSIE detection support, or if tinygif = 1, or the
226 * URL isn't recognized as an imageurl, a lame HTML
227 * explanation is sent instead.
229 * - Added new feature, which permits blocking remote
230 * script redirects and firing back a local redirect
232 * The feature is conditionally compiled, i.e. it
233 * can be disabled with --disable-fast-redirects,
234 * plus it must be activated by a "fast-redirects"
235 * line in the config file, has its own log level
236 * and of course wants to be displayed by show-proxy-args
237 * Note: Boy, all the #ifdefs in 1001 locations and
238 * all the fumbling with configure.in and acconfig.h
239 * were *way* more work than the feature itself :-(
241 * - Because a generic redirect template was needed for
242 * this, tinygif = 3 now uses the same.
244 * - Moved GIFs, and other static HTTP response templates
249 * - Removed some >400 CRs again (Jon, you really worked
252 * Revision 1.4 2001/05/21 19:34:01 jongfoster
253 * Made failure to bind() a fatal error.
255 * Revision 1.3 2001/05/20 01:21:20 jongfoster
256 * Version 2.9.4 checkin.
257 * - Merged popupfile and cookiefile, and added control over PCRS
258 * filtering, in new "permissionsfile".
259 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
260 * file error you now get a message box (in the Win32 GUI) rather
261 * than the program exiting with no explanation.
262 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
264 * - Removed tabs from "config"
265 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
266 * - Bumped up version number.
268 * Revision 1.2 2001/05/17 22:34:44 oes
269 * - Added hint on GIF char array generation to jcc.c
270 * - Cleaned CRLF's from the sources and related files
271 * - Repaired logging for REF and FRC
273 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
274 * Initial import of version 2.9.3 source tree
277 *********************************************************************/
283 #include <sys/types.h>
290 #ifdef FEATURE_PTHREAD
292 #endif /* def FEATURE_PTHREAD */
295 # ifndef FEATURE_PTHREAD
296 # include <windows.h>
297 # include <process.h>
298 # endif /* ndef FEATURE_PTHREAD */
301 # ifndef _WIN_CONSOLE
303 # endif /* ndef _WIN_CONSOLE */
305 #else /* ifndef _WIN32 */
308 # include <sys/time.h>
309 # include <sys/wait.h>
310 # include <sys/stat.h>
314 # include <socket.h> /* BeOS has select() for sockets only. */
315 # include <OS.h> /* declarations for threads and stuff. */
329 #include "showargs.h"
331 #include "killpopup.h"
332 #include "miscutil.h"
334 #include "jbsockets.h"
340 const char jcc_h_rcs[] = JCC_H_VERSION;
341 const char project_h_rcs[] = PROJECT_H_VERSION;
343 struct client_state clients[1];
344 struct file_list files[1];
346 #ifdef FEATURE_STATISTICS
347 int urls_read = 0; /* total nr of urls read inc rejected */
348 int urls_rejected = 0; /* total nr of urls rejected */
349 #endif /* def FEATURE_STATISTICS */
352 static void listen_loop(void);
353 static void chat(struct client_state *csp);
355 void serve(struct client_state *csp);
356 #else /* ifndef AMIGA */
357 static void serve(struct client_state *csp);
358 #endif /* def AMIGA */
361 static int32 server_thread(void *data);
362 #endif /* def __BEOS__ */
365 #define sleep(N) Sleep(((N) * 1000))
369 /* The vanilla wafer. */
370 static const char VANILLA_WAFER[] =
371 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
372 "Do_not_send_me_any_copyrighted_information_other_than_the_"
373 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
374 "In_particular_do_not_send_me_any_cookies_that_"
375 "are_subject_to_a_claim_of_copyright_by_anybody._"
376 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
377 "(copyright_or_otherwise)_applying_to_any_cookie._";
380 /*********************************************************************
384 * Description : Once a connection to the client has been accepted,
385 * this function is called (via serve()) to handle the
386 * main business of the communication. When this
387 * function returns, the caller must close the client
391 * 1 : csp = Current client state (buffers, headers, etc...)
393 * Returns : On success, the number of bytes written are returned (zero
394 * indicates nothing was written). On error, -1 is returned,
395 * and errno is set appropriately. If count is zero and the
396 * file descriptor refers to a regular file, 0 will be
397 * returned without causing any other effect. For a special
398 * file, the results are not portable.
400 *********************************************************************/
401 static void chat(struct client_state *csp)
404 * This next lines are a little ugly, but they simplifies the if statements
405 * below. Basically if TOGGLE, then we want the if to test "csp->toggled_on",
406 * else we don't. And if FEATURE_FORCE_LOAD, then we want the if to test
407 * "csp->toggled_on", else we don't
409 #ifdef FEATURE_TOGGLE
410 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
411 #else /* ifndef FEATURE_TOGGLE */
412 # define IS_TOGGLED_ON_AND
413 #endif /* ndef FEATURE_TOGGLE */
414 #ifdef FEATURE_FORCE_LOAD
415 # define IS_NOT_FORCED_AND (!csp->force) &&
416 #else /* ifndef FEATURE_FORCE_LOAD */
417 # define IS_NOT_FORCED_AND
418 #endif /* def FEATURE_FORCE_LOAD */
420 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
422 char buf[BUFFER_SIZE];
426 int n, maxfd, server_body;
427 int ms_iis5_hack = 0;
429 const struct forward_spec * fwd;
430 struct http_request *http;
431 #ifdef FEATURE_KILL_POPUPS
432 int block_popups; /* bool, 1==will block popups */
433 int block_popups_now = 0; /* bool, 1==currently blocking popups */
434 #endif /* def FEATURE_KILL_POPUPS */
436 int pcrs_filter; /* bool, 1==will filter through pcrs */
437 int gif_deanimate; /* bool, 1==will deanimate gifs */
439 /* Function that does the content filtering for the current request */
440 char *(*content_filter)() = NULL;
442 /* Skeleton for HTTP response, if we should intercept the request */
443 struct http_response *rsp;
448 * Read the client's request. Note that since we're not using select() we
449 * could get blocked here if a client connected, then didn't say anything!
454 n = read_socket(csp->cfd, buf, sizeof(buf));
456 if (n <= 0) break; /* error! */
458 add_to_iob(csp, buf, n);
460 req = get_header(csp);
464 break; /* no HTTP request! */
469 continue; /* more to come! */
472 #ifdef FEATURE_FORCE_LOAD
473 /* If this request contains the FORCE_PREFIX,
474 * better get rid of it now and set the force flag --oes
477 if (strstr(req, FORCE_PREFIX))
479 strclean(req, FORCE_PREFIX);
480 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
487 #endif /* def FEATURE_FORCE_LOAD */
489 parse_http_request(req, http, csp);
494 if (http->cmd == NULL)
496 strcpy(buf, CHEADER);
497 write_socket(csp->cfd, buf, strlen(buf));
499 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
504 /* decide how to route the HTTP request */
506 if ((fwd = forward_url(http, csp)) == NULL)
508 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
509 /* Never get here - LOG_LEVEL_FATAL causes program exit */
512 /* build the http request to send to the server
513 * we have to do one of the following:
515 * create = use the original HTTP request to create a new
516 * HTTP request that has only the path component
517 * without the http://domainspec
518 * pass = pass the original HTTP request unchanged
520 * drop = drop the HTTP request
525 * +--------+--------+
527 * 0 | create | drop |
529 * Forwarding +--------+--------+
533 * +--------+--------+
537 if (fwd->forward_host)
539 /* if forwarding, just pass the request as is */
540 enlist(csp->headers, http->cmd);
546 /* otherwise elide the host information from the url */
548 p = strsav(p, http->gpc);
550 p = strsav(p, http->path);
552 p = strsav(p, http->ver);
553 enlist(csp->headers, p);
558 /* decide what we're to do with cookies */
560 #ifdef FEATURE_TOGGLE
561 if (!csp->toggled_on)
563 /* Most compatible set of actions (i.e. none) */
564 init_current_action(csp->action);
567 #endif /* ndef FEATURE_TOGGLE */
569 url_actions(http, csp);
572 #ifdef FEATURE_COOKIE_JAR
574 * If we're logging cookies in a cookie jar, and the user has not
575 * supplied any wafers, and the user has not told us to suppress the
576 * vanilla wafer, then send the vanilla wafer.
578 if ((csp->config->jarfile != NULL)
579 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
580 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
582 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
584 #endif /* def FEATURE_COOKIE_JAR */
586 #ifdef FEATURE_KILL_POPUPS
587 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
588 #endif /* def FEATURE_KILL_POPUPS */
590 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
591 ((csp->action->flags & ACTION_FILTER) != 0);
593 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
595 /* grab the rest of the client's headers */
599 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
601 n = read_socket(csp->cfd, buf, sizeof(buf));
604 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
607 add_to_iob(csp, buf, n);
611 if (p == NULL) break;
613 enlist(csp->headers, p);
617 /* We have a request. */
619 hdr = sed(client_patterns, add_client_headers, csp);
620 destroy_list(csp->headers);
623 * Now, check to see if we need to intercept it, i.e.
628 /* a CGI call was detected and answered */
629 (NULL != (rsp = dispatch_cgi(csp)))
631 /* or we are enabled and... */
634 /* ..the request was blocked */
635 ( NULL != (rsp = block_url(csp)))
639 || ( NULL != (rsp = trust_url(csp)))
640 #endif /* def FEATURE_TRUST */
642 /* ..or a fast redirect kicked in */
643 #ifdef FEATURE_FAST_REDIRECTS
644 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
645 (NULL != (rsp = redirect_url(csp))))
646 #endif /* def FEATURE_FAST_REDIRECTS */
650 /* Write the answer to the client */
651 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
652 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
654 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
657 #ifdef FEATURE_STATISTICS
658 /* Count as a rejected request */
660 #endif /* def FEATURE_STATISTICS */
662 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
663 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
664 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
666 /* Clean up and return */
667 free_http_response(rsp);
672 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
674 if (fwd->forward_host)
676 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
677 fwd->forward_host, fwd->forward_port, http->hostport);
681 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
684 /* here we connect to the server, gateway, or the forwarder */
686 csp->sfd = forwarded_connect(fwd, http, csp);
690 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
695 rsp = error_response(csp, "no-such-domain", errno);
697 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
698 csp->ip_addr_str, http->cmd);
702 rsp = error_response(csp, "connect-failed", errno);
704 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
705 csp->ip_addr_str, http->cmd);
708 /* Write the answer to the client */
711 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
712 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
714 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
718 free_http_response(rsp);
723 log_error(LOG_LEVEL_CONNECT, "OK");
725 if (fwd->forward_host || (http->ssl == 0))
727 /* write the client's (modified) header to the server
728 * (along with anything else that may be in the buffer)
733 if ((write_socket(csp->sfd, hdr, n) != n)
734 || (flush_socket(csp->sfd, csp ) < 0))
736 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
739 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
740 csp->ip_addr_str, http->cmd);
742 rsp = error_response(csp, "connect-failed", errno);
746 if ((write_socket(csp->cfd, rsp->head, n) != n)
747 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
749 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
753 free_http_response(rsp);
761 * We're running an SSL tunnel and we're not forwarding,
762 * so just send the "connect succeeded" message to the
763 * client, flush the rest, and get out of the way.
765 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
766 csp->ip_addr_str, http->cmd);
768 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
776 /* we're finished with the client's header */
779 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
781 /* pass data between the client and server
782 * until one or the other shuts down the connection.
791 FD_SET(csp->cfd, &rfds);
792 FD_SET(csp->sfd, &rfds);
794 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
798 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
802 /* this is the body of the browser's request
803 * just read it and write it.
806 if (FD_ISSET(csp->cfd, &rfds))
808 n = read_socket(csp->cfd, buf, sizeof(buf));
812 break; /* "game over, man" */
815 if (write_socket(csp->sfd, buf, n) != n)
817 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
824 * The server wants to talk. It could be the header or the body.
825 * If `hdr' is null, then it's the header otherwise it's the body.
826 * FIXME: Does `hdr' really mean `host'? No.
830 if (FD_ISSET(csp->sfd, &rfds))
833 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
837 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
839 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
840 csp->ip_addr_str, http->cmd);
842 rsp = error_response(csp, "connect-failed", errno);
846 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
847 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
849 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
853 free_http_response(rsp);
857 /* Add a trailing zero. This lets filter_popups
858 * use string operations.
862 #ifdef FEATURE_KILL_POPUPS
863 /* Filter the popups on this read. */
864 if (block_popups_now)
868 #endif /* def FEATURE_KILL_POPUPS */
870 /* Normally, this would indicate that we've read
871 * as much as the server has sent us and we can
872 * close the client connection. However, Microsoft
873 * in its wisdom has released IIS/5 with a bug that
874 * prevents it from sending the trailing \r\n in
875 * a 302 redirect header (and possibly other headers).
876 * To work around this if we've haven't parsed
877 * a full header we'll append a trailing \r\n
878 * and see if this now generates a valid one.
880 * This hack shouldn't have any impacts. If we've
881 * already transmitted the header or if this is a
882 * SSL connection, then we won't bother with this
883 * hack. So we only work on partially received
884 * headers. If we append a \r\n and this still
885 * doesn't generate a valid header, then we won't
886 * transmit anything to the client.
891 if (server_body || http->ssl)
894 * If we have been buffering up the document,
895 * now is the time to apply content modification
896 * and send the result to the client.
901 * If the content filter fails, use the original
903 * (see p != NULL ? p : csp->iob->cur below)
905 if (NULL == (p = (*content_filter)(csp)))
907 csp->content_length = csp->iob->eod - csp->iob->cur;
910 hdr = sed(server_patterns, add_server_headers, csp);
913 if ((write_socket(csp->cfd, hdr, n) != n)
914 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != csp->content_length))
916 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
924 break; /* "game over, man" */
928 * This is NOT the body, so
929 * Let's pretend the server just sent us a blank line.
931 n = sprintf(buf, "\r\n");
934 * Now, let the normal header parsing algorithm below do its
935 * job. If it fails, we'll exit instead of continuing.
942 * If this is an SSL connection or we're in the body
943 * of the server document, just write it to the client,
944 * unless we need to buffer the body for later content-filtering
947 if (server_body || http->ssl)
951 add_to_iob(csp, buf, n);
955 if (write_socket(csp->cfd, buf, n) != n)
957 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
966 /* we're still looking for the end of the
967 * server's header ... (does that make header
968 * parsing an "out of body experience" ?
971 /* buffer up the data we just read */
972 add_to_iob(csp, buf, n);
974 /* get header lines from the iob */
976 while ((p = get_header(csp)))
980 /* see following note */
983 enlist(csp->headers, p);
987 /* NOTE: there are no "empty" headers so
988 * if the pointer `p' is not NULL we must
989 * assume that we reached the end of the
990 * buffer before we hit the end of the header.
997 /* Well, we tried our MS IIS/5
998 * hack and it didn't work.
999 * The header is incomplete
1000 * and there isn't anything
1001 * we can do about it.
1007 /* Since we have to wait for
1008 * more from the server before
1009 * we can parse the headers
1010 * we just continue here.
1016 /* we have now received the entire header.
1017 * filter it and send the result to the client
1020 hdr = sed(server_patterns, add_server_headers, csp);
1023 /* write the server's (modified) header to
1024 * the client (along with anything else that
1025 * may be in the buffer)
1028 #ifdef FEATURE_KILL_POPUPS
1029 /* Start blocking popups if appropriate. */
1031 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1032 !http->ssl && /* We talk plaintext */
1033 block_popups) /* Policy allows */
1035 block_popups_now = 1;
1037 * Filter the part of the body that came in the same read
1038 * as the last headers:
1040 filter_popups(csp->iob->cur);
1043 #endif /* def FEATURE_KILL_POPUPS */
1045 /* Buffer and pcrs filter this if appropriate. */
1047 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1048 !http->ssl && /* We talk plaintext */
1049 pcrs_filter) /* Policy allows */
1051 content_filter = pcrs_filter_response;
1054 /* Buffer and gif_deanimate this if appropriate. */
1056 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1057 !http->ssl && /* We talk plaintext */
1058 gif_deanimate) /* Policy allows */
1060 content_filter = gif_deanimate_response;
1065 * Only write if we're not buffering for content modification
1067 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1068 || (n = flush_socket(csp->cfd, csp) < 0)))
1070 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1072 /* the write failed, so don't bother
1073 * mentioning it to the client...
1074 * it probably can't hear us anyway.
1080 if(!content_filter) byte_count += n;
1082 /* we're finished with the server's header */
1087 /* If this was a MS IIS/5 hack then it means
1088 * the server has already closed the
1089 * connection. Nothing more to read. Time
1100 return; /* huh? we should never get here */
1103 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1104 csp->ip_addr_str, http->cmd, byte_count);
1108 /*********************************************************************
1112 * Description : This is little more than chat. We only "serve" to
1113 * to close any socket that chat may have opened.
1116 * 1 : csp = Current client state (buffers, headers, etc...)
1120 *********************************************************************/
1122 void serve(struct client_state *csp)
1123 #else /* ifndef AMIGA */
1124 static void serve(struct client_state *csp)
1125 #endif /* def AMIGA */
1128 close_socket(csp->cfd);
1132 close_socket(csp->sfd);
1141 /*********************************************************************
1143 * Function : server_thread
1145 * Description : We only exist to call `serve' in a threaded environment.
1148 * 1 : data = Current client state (buffers, headers, etc...)
1150 * Returns : Always 0.
1152 *********************************************************************/
1153 static int32 server_thread(void *data)
1155 serve((struct client_state *) data);
1162 /*********************************************************************
1166 * Description : Load the config file and start the listen loop.
1167 * This function is a lot more *sane* with the `load_config'
1168 * and `listen_loop' functions; although it stills does
1169 * a *little* too much for my taste.
1172 * 1 : argc = Number of parameters (including $0).
1173 * 2 : argv = Array of (char *)'s to the parameters.
1175 * Returns : 1 if : can't open config file, unrecognized directive,
1176 * stats requested in multi-thread mode, can't open the
1177 * log file, can't open the jar file, listen port is invalid,
1178 * any load fails, and can't bind port.
1180 * Else main never returns, the process must be signaled
1181 * to terminate execution. Or, on Windows, use the
1182 * "File", "Exit" menu option.
1184 *********************************************************************/
1186 int real_main(int argc, const char *argv[])
1188 int main(int argc, const char *argv[])
1193 "AmiTCP:db/junkbuster/config"
1194 #elif !defined(_WIN32)
1201 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1202 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1204 printf("JunkBuster proxy version " VERSION ".\n\n"
1205 "Usage: %s [configfile]\n\n"
1206 "See " HOME_PAGE_URL " for details.\n"
1207 "This program is distributed under the GNU GPL, version 2 or later.\n",
1211 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1213 printf(VERSION "\n");
1216 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1223 configfile = argv[1];
1230 #elif defined(_WIN32)
1236 signal(SIGPIPE, SIG_IGN);
1237 signal(SIGCHLD, SIG_IGN);
1239 #else /* ifdef _WIN32 */
1240 # ifdef _WIN_CONSOLE
1242 * We *are* in a windows console app.
1243 * Print a verbose messages about FAQ's and such
1245 printf(win32_blurb);
1246 # endif /* def _WIN_CONSOLE */
1247 #endif /* def _WIN32 */
1258 /*********************************************************************
1260 * Function : listen_loop
1262 * Description : bind the listen port and enter a "FOREVER" listening loop.
1268 *********************************************************************/
1269 static void listen_loop(void)
1271 struct client_state *csp = NULL;
1273 struct configuration_spec * config;
1275 config = load_config();
1277 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1278 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1280 bfd = bind_port(config->haddr, config->hport);
1284 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1285 "- There may be another junkbuster or some other "
1286 "proxy running on port %d",
1287 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1288 config->hport, config->hport
1290 /* shouldn't get here */
1294 config->need_bind = 0;
1299 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1300 while (waitpid(-1, NULL, WNOHANG) > 0)
1302 /* zombie children */
1304 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1307 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1309 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1313 memset(csp, '\0', sizeof(*csp));
1318 csp->config = config = load_config();
1320 if ( config->need_bind )
1323 * Since we were listening to the "old port", we will not see
1324 * a "listen" param change until the next IJB request. So, at
1325 * least 1 more request must be made for us to find the new
1326 * setting. I am simply closing the old socket and binding the
1329 * Which-ever is correct, we will serve 1 more page via the
1330 * old settings. This should probably be a "show-proxy-args"
1331 * request. This should not be a so common of an operation
1332 * that this will hurt people's feelings.
1337 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1338 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1339 bfd = bind_port(config->haddr, config->hport);
1343 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1344 "- There may be another junkbuster or some other "
1345 "proxy running on port %d",
1346 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1347 config->hport, config->hport
1349 /* shouldn't get here */
1353 config->need_bind = 0;
1356 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1358 if (!accept_connection(csp, bfd))
1360 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1373 log_error(LOG_LEVEL_CONNECT, "OK");
1376 #ifdef FEATURE_TOGGLE
1377 /* by haroon - most of credit to srt19170 */
1378 csp->toggled_on = g_bToggleIJB;
1379 #endif /* def FEATURE_TOGGLE */
1381 if (run_loader(csp))
1383 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1384 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1388 if (block_acl(NULL,csp))
1390 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1391 close_socket(csp->cfd);
1395 #endif /* def FEATURE_ACL */
1397 /* add it to the list of clients */
1398 csp->next = clients->next;
1399 clients->next = csp;
1401 if (config->multi_threaded)
1405 /* this is a switch () statment in the C preprocessor - ugh */
1406 #undef SELECTED_ONE_OPTION
1408 /* Use Pthreads in preference to native code */
1409 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1410 #define SELECTED_ONE_OPTION
1412 pthread_t the_thread;
1413 pthread_attr_t attrs;
1415 pthread_attr_init(&attrs);
1416 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1417 child_id = (pthread_create(&the_thread, &attrs,
1418 (void*)serve, csp) ? -1 : 0);
1419 pthread_attr_destroy(&attrs);
1423 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1424 #define SELECTED_ONE_OPTION
1425 child_id = _beginthread(
1431 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1432 #define SELECTED_ONE_OPTION
1434 thread_id tid = spawn_thread
1435 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1437 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1439 child_id = (int) tid;
1448 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1449 #define SELECTED_ONE_OPTION
1450 csp->cfd = ReleaseSocket(csp->cfd, -1);
1451 if((child_id = (int)CreateNewProcTags(
1452 NP_Entry, (ULONG)server_thread,
1453 NP_Output, Output(),
1454 NP_CloseOutput, FALSE,
1455 NP_Name, (ULONG)"junkbuster child",
1456 NP_StackSize, 200*1024,
1460 ((struct Task *)child_id)->tc_UserData = csp;
1461 Signal((struct Task *)child_id, SIGF_SINGLE);
1466 #if !defined(SELECTED_ONE_OPTION)
1469 /* This block is only needed when using fork().
1470 * When using threads, the server thread was
1471 * created and run by the call to _beginthread().
1473 if (child_id == 0) /* child */
1479 else if (child_id > 0) /* parent */
1481 /* in a fork()'d environment, the parent's
1482 * copy of the client socket and the CSP
1486 #if !defined(_WIN32) && defined(__CYGWIN__)
1488 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1489 close_socket(csp->cfd);
1494 #undef SELECTED_ONE_OPTION
1495 /* end of cpp switch () */
1497 if (child_id < 0) /* failed */
1499 char buf[BUFFER_SIZE];
1501 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1503 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1505 write_socket(csp->cfd, buf, strlen(buf));
1506 close_socket(csp->cfd);