1 const char jcc_rcs[] = "$Id: jcc.c,v 1.49 2001/10/23 21:41:35 jongfoster Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001 the SourceForge
10 * IJBSWA team. http://ijbswa.sourceforge.net
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
36 * Revision 1.49 2001/10/23 21:41:35 jongfoster
37 * Added call to initialize the (statically-allocated of course)
38 * "out of memory" CGI response.
40 * Revision 1.48 2001/10/10 19:56:46 jongfoster
41 * Moving some code that wasn't cookie-related out of an #ifdef
44 * Revision 1.47 2001/10/10 16:44:36 oes
45 * Added CONNECT destination port limitation check
47 * Revision 1.46 2001/10/08 15:17:41 oes
48 * Re-enabled SSL forwarding
50 * Revision 1.45 2001/10/07 15:42:11 oes
51 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
53 * Moved downgrading of the HTTP version from parse_http_request to
54 * chat(), since we can't decide if it is necessary before we have
55 * determined the actions for the URL. The HTTP command is now
56 * *always* re-built so the repairs need no longer be special-cased.
58 * filter_popups now gets a csp pointer so it can raise the new
59 * CSP_FLAG_MODIFIED flag.
63 * Added configurable size limit for the IOB. If the IOB grows so
64 * large that the next read would exceed the limit, the header
65 * is generated, and the header & unfiltered buffer are flushed
66 * to the client. Chat then continues in non-buffering,
67 * non-filtering body mode.
69 * Revision 1.44 2001/10/02 18:13:57 oes
72 * Revision 1.43 2001/10/02 15:32:13 oes
73 * Moved generation of hdr
75 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
76 * Cleaning up 2 compiler warnings on OS/2.
78 * Revision 1.41 2001/09/16 17:05:14 jongfoster
79 * Removing unused #include showarg.h
81 * Revision 1.40 2001/09/16 15:41:45 jongfoster
82 * Fixing signed/unsigned comparison warning.
84 * Revision 1.39 2001/09/16 13:21:27 jongfoster
85 * Changes to use new list functions.
87 * Revision 1.38 2001/09/16 13:01:46 jongfoster
88 * Removing redundant function call that zeroed zalloc()'d memory.
90 * Revision 1.37 2001/09/10 11:12:24 oes
91 * Deleted unused variable
93 * Revision 1.36 2001/09/10 10:56:15 oes
94 * Silenced compiler warnings
96 * Revision 1.35 2001/07/31 14:44:22 oes
97 * Deleted unused size parameter from filter_popups()
99 * Revision 1.34 2001/07/30 22:08:36 jongfoster
100 * Tidying up #defines:
101 * - All feature #defines are now of the form FEATURE_xxx
102 * - Permanently turned off WIN_GUI_EDIT
103 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
105 * Revision 1.33 2001/07/29 19:32:00 jongfoster
106 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
108 * Revision 1.32 2001/07/29 18:47:05 jongfoster
109 * Adding missing #include "loadcfg.h"
111 * Revision 1.31 2001/07/29 12:17:48 oes
112 * Applied pthread fix by Paul Lieverse
114 * Revision 1.30 2001/07/25 22:57:13 jongfoster
115 * __BEOS__ no longer overrides FEATURE_PTHREAD.
116 * This is because FEATURE_PTHREAD will soon be widely used, so I
117 * want to keep it simple.
119 * Revision 1.29 2001/07/24 12:47:06 oes
120 * Applied BeOS support update by Eugenia
122 * Revision 1.28 2001/07/23 13:26:12 oes
123 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
125 * Revision 1.27 2001/07/19 19:09:47 haroon
126 * - Added code to take care of the situation where while processing the first
127 * server response (which includes the server header), after finding the end
128 * of the headers we were not looking past the end of the headers for
129 * content modification. I enabled it for filter_popups.
130 * Someone else should look to see if other similar operations should be
131 * done to the discarded portion of the buffer.
133 * Note 2001/07/20: No, the other content modification mechanisms will process
134 * the whole iob later anyway. --oes
136 * Revision 1.26 2001/07/18 12:31:36 oes
139 * Revision 1.25 2001/07/15 19:43:49 jongfoster
140 * Supports POSIX threads.
141 * Also removed some unused #includes.
143 * Revision 1.24 2001/07/13 14:00:40 oes
144 * - Generic content modification scheme:
145 * Each feature has its own applicability flag that is set
146 * from csp->action->flags.
147 * Replaced the "filtering" int flag , by a function pointer
148 * "content_filter" to the function that will do the content
149 * modification. If it is != NULL, the document will be buffered
150 * and processed through *content_filter, which must set
151 * csp->content_length and return a modified copy of the body
152 * or return NULL (on failiure).
153 * - Changed csp->is_text to the more generic bitmap csp->content_type
154 * which can currently take the valued CT_TEXT or CT_GIF
156 * - Removed all #ifdef PCRS
158 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
159 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
160 * the `block_acl' call. This prevents a compilation error when the user
161 * does not wish to use the "ACL" feature.
163 * Revision 1.22 2001/06/29 21:45:41 oes
164 * Indentation, CRLF->LF, Tab-> Space
166 * Revision 1.21 2001/06/29 13:29:36 oes
167 * - Cleaned up, improved comments
168 * - Unified all possible interceptors (CGI,
169 * block, trust, fast_redirect) in one
170 * place, with one (CGI) answer generation
171 * mechansim. Much clearer now.
172 * - Removed the GIF image generation, which
173 * is now done in filters.c:block_url()
174 * - Made error conditions like domain lookup
175 * failiure or (various) problems while talking
176 * to the server use cgi.c:error_response()
177 * instead of generating HTML/HTTP in chat() (yuck!)
178 * - Removed logentry from cancelled commit
180 * Revision 1.20 2001/06/09 10:55:28 jongfoster
181 * Changing BUFSIZ ==> BUFFER_SIZE
183 * Revision 1.19 2001/06/07 23:12:52 jongfoster
184 * Replacing function pointer in struct gateway with a directly
185 * called function forwarded_connect().
186 * Replacing struct gateway with struct forward_spec
188 * Revision 1.18 2001/06/03 19:12:16 oes
189 * introduced new cgi handling
191 * Revision 1.17 2001/06/01 20:07:23 jongfoster
192 * Now uses action +image-blocker{} rather than config->tinygif
194 * Revision 1.16 2001/06/01 18:49:17 jongfoster
195 * Replaced "list_share" with "list" - the tiny memory gain was not
196 * worth the extra complexity.
198 * Revision 1.15 2001/05/31 21:24:47 jongfoster
199 * Changed "permission" to "action" throughout.
200 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
201 * Moved vanilla wafer check into chat(), since we must now
202 * decide whether or not to add it based on the URL.
204 * Revision 1.14 2001/05/29 20:14:01 joergs
205 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
208 * Revision 1.13 2001/05/29 09:50:24 jongfoster
209 * Unified blocklist/imagelist/permissionslist.
210 * File format is still under discussion, but the internal changes
213 * Also modified interceptor behaviour:
214 * - We now intercept all URLs beginning with one of the following
215 * prefixes (and *only* these prefixes):
217 * * http://ijbswa.sf.net/config/
218 * * http://ijbswa.sourceforge.net/config/
219 * - New interceptors "home page" - go to http://i.j.b/ to see it.
220 * - Internal changes so that intercepted and fast redirect pages
221 * are not replaced with an image.
222 * - Interceptors now have the option to send a binary page direct
223 * to the client. (i.e. ijb-send-banner uses this)
224 * - Implemented show-url-info interceptor. (Which is why I needed
225 * the above interceptors changes - a typical URL is
226 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
227 * The previous mechanism would not have intercepted that, and
228 * if it had been intercepted then it then it would have replaced
231 * Revision 1.12 2001/05/27 22:17:04 oes
233 * - re_process_buffer no longer writes the modified buffer
234 * to the client, which was very ugly. It now returns the
235 * buffer, which it is then written by chat.
237 * - content_length now adjusts the Content-Length: header
238 * for modified documents rather than crunch()ing it.
239 * (Length info in csp->content_length, which is 0 for
240 * unmodified documents)
242 * - For this to work, sed() is called twice when filtering.
244 * Revision 1.11 2001/05/26 17:27:53 jongfoster
245 * Added support for CLF and fixed LOG_LEVEL_LOG.
246 * Also did CRLF->LF fix of my previous patch.
248 * Revision 1.10 2001/05/26 15:26:15 jongfoster
249 * ACL feature now provides more security by immediately dropping
250 * connections from untrusted hosts.
252 * Revision 1.9 2001/05/26 00:28:36 jongfoster
253 * Automatic reloading of config file.
254 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
255 * Most of the global variables have been moved to a new
256 * struct configuration_spec, accessed through csp->config->globalname
257 * Most of the globals remaining are used by the Win32 GUI.
259 * Revision 1.8 2001/05/25 22:43:18 jongfoster
260 * Fixing minor memory leak and buffer overflow.
262 * Revision 1.7 2001/05/25 22:34:30 jongfoster
265 * Revision 1.6 2001/05/23 00:13:58 joergs
266 * AmigaOS support fixed.
268 * Revision 1.5 2001/05/22 18:46:04 oes
270 * - Enabled filtering banners by size rather than URL
271 * by adding patterns that replace all standard banner
272 * sizes with the "Junkbuster" gif to the re_filterfile
274 * - Enabled filtering WebBugs by providing a pattern
275 * which kills all 1x1 images
277 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
278 * which is selected by the (nonstandard and therefore
279 * capital) letter 'U' in the option string.
280 * It causes the quantifiers to be ungreedy by default.
281 * Appending a ? turns back to greedy (!).
283 * - Added a new interceptor ijb-send-banner, which
284 * sends back the "Junkbuster" gif. Without imagelist or
285 * MSIE detection support, or if tinygif = 1, or the
286 * URL isn't recognized as an imageurl, a lame HTML
287 * explanation is sent instead.
289 * - Added new feature, which permits blocking remote
290 * script redirects and firing back a local redirect
292 * The feature is conditionally compiled, i.e. it
293 * can be disabled with --disable-fast-redirects,
294 * plus it must be activated by a "fast-redirects"
295 * line in the config file, has its own log level
296 * and of course wants to be displayed by show-proxy-args
297 * Note: Boy, all the #ifdefs in 1001 locations and
298 * all the fumbling with configure.in and acconfig.h
299 * were *way* more work than the feature itself :-(
301 * - Because a generic redirect template was needed for
302 * this, tinygif = 3 now uses the same.
304 * - Moved GIFs, and other static HTTP response templates
309 * - Removed some >400 CRs again (Jon, you really worked
312 * Revision 1.4 2001/05/21 19:34:01 jongfoster
313 * Made failure to bind() a fatal error.
315 * Revision 1.3 2001/05/20 01:21:20 jongfoster
316 * Version 2.9.4 checkin.
317 * - Merged popupfile and cookiefile, and added control over PCRS
318 * filtering, in new "permissionsfile".
319 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
320 * file error you now get a message box (in the Win32 GUI) rather
321 * than the program exiting with no explanation.
322 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
324 * - Removed tabs from "config"
325 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
326 * - Bumped up version number.
328 * Revision 1.2 2001/05/17 22:34:44 oes
329 * - Added hint on GIF char array generation to jcc.c
330 * - Cleaned CRLF's from the sources and related files
331 * - Repaired logging for REF and FRC
333 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
334 * Initial import of version 2.9.3 source tree
337 *********************************************************************/
343 #include <sys/types.h>
350 #ifdef FEATURE_PTHREAD
352 #endif /* def FEATURE_PTHREAD */
355 # ifndef FEATURE_PTHREAD
356 # include <windows.h>
357 # include <process.h>
358 # endif /* ndef FEATURE_PTHREAD */
361 # ifndef _WIN_CONSOLE
363 # endif /* ndef _WIN_CONSOLE */
365 #else /* ifndef _WIN32 */
367 # if !defined (__OS2__)
369 # include <sys/wait.h>
370 # endif /* ndef __OS2__ */
371 # include <sys/time.h>
372 # include <sys/stat.h>
376 # include <socket.h> /* BeOS has select() for sockets only. */
377 # include <OS.h> /* declarations for threads and stuff. */
380 # if defined(__EMX__) || defined(__OS2__)
381 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
386 #define bzero(B,N) memset(B,0x00,n)
401 #include "killpopup.h"
402 #include "miscutil.h"
404 #include "jbsockets.h"
410 const char jcc_h_rcs[] = JCC_H_VERSION;
411 const char project_h_rcs[] = PROJECT_H_VERSION;
413 struct client_state clients[1];
414 struct file_list files[1];
416 #ifdef FEATURE_STATISTICS
417 int urls_read = 0; /* total nr of urls read inc rejected */
418 int urls_rejected = 0; /* total nr of urls rejected */
419 #endif /* def FEATURE_STATISTICS */
422 static void listen_loop(void);
423 static void chat(struct client_state *csp);
425 void serve(struct client_state *csp);
426 #else /* ifndef AMIGA */
427 static void serve(struct client_state *csp);
428 #endif /* def AMIGA */
431 static int32 server_thread(void *data);
432 #endif /* def __BEOS__ */
435 #define sleep(N) Sleep(((N) * 1000))
439 #define sleep(N) DosSleep(((N) * 100))
443 /* The vanilla wafer. */
444 static const char VANILLA_WAFER[] =
445 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
446 "Do_not_send_me_any_copyrighted_information_other_than_the_"
447 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
448 "In_particular_do_not_send_me_any_cookies_that_"
449 "are_subject_to_a_claim_of_copyright_by_anybody._"
450 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
451 "(copyright_or_otherwise)_applying_to_any_cookie._";
454 /*********************************************************************
458 * Description : Once a connection to the client has been accepted,
459 * this function is called (via serve()) to handle the
460 * main business of the communication. When this
461 * function returns, the caller must close the client
465 * 1 : csp = Current client state (buffers, headers, etc...)
467 * Returns : On success, the number of bytes written are returned (zero
468 * indicates nothing was written). On error, -1 is returned,
469 * and errno is set appropriately. If count is zero and the
470 * file descriptor refers to a regular file, 0 will be
471 * returned without causing any other effect. For a special
472 * file, the results are not portable.
474 *********************************************************************/
475 static void chat(struct client_state *csp)
478 * This next lines are a little ugly, but they simplifies the if statements
479 * below. Basically if TOGGLE, then we want the if to test if the
480 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
481 * then we want the if to test for CSP_FLAG_FORCED , else we don't
483 #ifdef FEATURE_TOGGLE
484 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
485 #else /* ifndef FEATURE_TOGGLE */
486 # define IS_TOGGLED_ON_AND
487 #endif /* ndef FEATURE_TOGGLE */
488 #ifdef FEATURE_FORCE_LOAD
489 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
490 #else /* ifndef FEATURE_FORCE_LOAD */
491 # define IS_NOT_FORCED_AND
492 #endif /* def FEATURE_FORCE_LOAD */
494 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
496 char buf[BUFFER_SIZE];
499 int n, maxfd, server_body;
500 int ms_iis5_hack = 0;
502 const struct forward_spec * fwd;
503 struct http_request *http;
504 #ifdef FEATURE_KILL_POPUPS
505 int block_popups; /* bool, 1==will block popups */
506 int block_popups_now = 0; /* bool, 1==currently blocking popups */
507 #endif /* def FEATURE_KILL_POPUPS */
509 int pcrs_filter; /* bool, 1==will filter through pcrs */
510 int gif_deanimate; /* bool, 1==will deanimate gifs */
512 /* Function that does the content filtering for the current request */
513 char *(*content_filter)() = NULL;
515 /* Skeleton for HTTP response, if we should intercept the request */
516 struct http_response *rsp;
521 * Read the client's request. Note that since we're not using select() we
522 * could get blocked here if a client connected, then didn't say anything!
527 n = read_socket(csp->cfd, buf, sizeof(buf));
529 if (n <= 0) break; /* error! */
531 add_to_iob(csp, buf, n);
533 req = get_header(csp);
537 break; /* no HTTP request! */
542 continue; /* more to come! */
545 #ifdef FEATURE_FORCE_LOAD
546 /* If this request contains the FORCE_PREFIX,
547 * better get rid of it now and set the force flag --oes
550 if (strstr(req, FORCE_PREFIX))
552 strclean(req, FORCE_PREFIX);
553 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
554 csp->flags |= CSP_FLAG_FORCED;
557 #endif /* def FEATURE_FORCE_LOAD */
559 parse_http_request(req, http, csp);
564 if (http->cmd == NULL)
566 strcpy(buf, CHEADER);
567 write_socket(csp->cfd, buf, strlen(buf));
569 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
574 /* decide how to route the HTTP request */
576 if ((fwd = forward_url(http, csp)) == NULL)
578 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
579 /* Never get here - LOG_LEVEL_FATAL causes program exit */
582 /* build the http request to send to the server
583 * we have to do one of the following:
585 * create = use the original HTTP request to create a new
586 * HTTP request that has either the path component
587 * without the http://domainspec (w/path) or the
588 * full orininal URL (w/url)
589 * Note that the path and/or the HTTP version may
590 * have been altered by now.
592 * connect = Open a socket to the host:port of the server
593 * and short-circuit server and client socket.
595 * pass = Pass the request unchanged if forwarding a CONNECT
596 * request to a parent proxy. Note that we'll be sending
597 * the CFAIL message ourselves if connecting to the parent
598 * fails, but we won't send a CSUCCEED message if it works,
599 * since that would result in a double message (ours and the
600 * parent's). After sending the request to the parent, we simply
606 * +--------+--------+
608 * 0 | create | connect|
610 * Forwarding +--------+--------+
612 * 1 | create | pass |
614 * +--------+--------+
619 * Determine the actions for this URL
621 #ifdef FEATURE_TOGGLE
622 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
624 /* Most compatible set of actions (i.e. none) */
625 init_current_action(csp->action);
628 #endif /* ndef FEATURE_TOGGLE */
630 url_actions(http, csp);
635 * Check if a CONNECT request is allowable:
636 * In the absence of a +limit-connect action, allow only port 443.
637 * If there is an action, allow whatever matches the specificaton.
641 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
642 || (csp->action->flags & ACTION_LIMIT_CONNECT
643 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
645 strcpy(buf, CFORBIDDEN);
646 write_socket(csp->cfd, buf, strlen(buf));
648 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
649 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
657 * Downgrade http version from 1.1 to 1.0 if +downgrade
660 if (!strcmpic(http->ver, "HTTP/1.1") && csp->action->flags & ACTION_DOWNGRADE)
663 http->ver = strdup("HTTP/1.0");
667 * (Re)build the HTTP request for non-SSL requests.
668 * If forwarding, use the whole URL, else, use only the path.
674 http->cmd = strsav(http->cmd, http->gpc);
675 http->cmd = strsav(http->cmd, " ");
677 if (fwd->forward_host)
679 http->cmd = strsav(http->cmd, http->url);
683 http->cmd = strsav(http->cmd, http->path);
686 http->cmd = strsav(http->cmd, " ");
687 http->cmd = strsav(http->cmd, http->ver);
690 enlist(csp->headers, http->cmd);
693 #ifdef FEATURE_COOKIE_JAR
695 * If we're logging cookies in a cookie jar, and the user has not
696 * supplied any wafers, and the user has not told us to suppress the
697 * vanilla wafer, then send the vanilla wafer.
699 if ((csp->config->jarfile != NULL)
700 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
701 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
703 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
705 #endif /* def FEATURE_COOKIE_JAR */
708 #ifdef FEATURE_KILL_POPUPS
709 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
710 #endif /* def FEATURE_KILL_POPUPS */
712 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
713 ((csp->action->flags & ACTION_FILTER) != 0);
715 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
717 /* grab the rest of the client's headers */
721 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
723 n = read_socket(csp->cfd, buf, sizeof(buf));
726 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
729 add_to_iob(csp, buf, n);
733 if (p == NULL) break;
735 enlist(csp->headers, p);
739 /* We have a request. */
742 * Now, check to see if we need to intercept it, i.e.
747 /* a CGI call was detected and answered */
748 (NULL != (rsp = dispatch_cgi(csp)))
750 /* or we are enabled and... */
753 /* ..the request was blocked */
754 ( NULL != (rsp = block_url(csp)))
758 || ( NULL != (rsp = trust_url(csp)))
759 #endif /* def FEATURE_TRUST */
761 /* ..or a fast redirect kicked in */
762 #ifdef FEATURE_FAST_REDIRECTS
763 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
764 (NULL != (rsp = redirect_url(csp))))
765 #endif /* def FEATURE_FAST_REDIRECTS */
769 /* Write the answer to the client */
770 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
771 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
773 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
776 #ifdef FEATURE_STATISTICS
777 /* Count as a rejected request */
778 csp->flags |= CSP_FLAG_REJECTED;
779 #endif /* def FEATURE_STATISTICS */
781 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
782 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
783 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
785 /* Clean up and return */
786 free_http_response(rsp);
790 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
792 if (fwd->forward_host)
794 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
795 fwd->forward_host, fwd->forward_port, http->hostport);
799 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
802 /* here we connect to the server, gateway, or the forwarder */
804 csp->sfd = forwarded_connect(fwd, http, csp);
808 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
813 rsp = error_response(csp, "no-such-domain", errno);
815 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
816 csp->ip_addr_str, http->cmd);
820 rsp = error_response(csp, "connect-failed", errno);
822 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
823 csp->ip_addr_str, http->cmd);
826 /* Write the answer to the client */
829 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
830 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
832 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
836 free_http_response(rsp);
840 log_error(LOG_LEVEL_CONNECT, "OK");
842 hdr = sed(client_patterns, add_client_headers, csp);
843 list_remove_all(csp->headers);
845 if (fwd->forward_host || (http->ssl == 0))
847 /* write the client's (modified) header to the server
848 * (along with anything else that may be in the buffer)
853 if ((write_socket(csp->sfd, hdr, n) != n)
854 || (flush_socket(csp->sfd, csp ) < 0))
856 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
859 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
860 csp->ip_addr_str, http->cmd);
862 rsp = error_response(csp, "connect-failed", errno);
866 if ((write_socket(csp->cfd, rsp->head, n) != n)
867 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
869 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
873 free_http_response(rsp);
881 * We're running an SSL tunnel and we're not forwarding,
882 * so just send the "connect succeeded" message to the
883 * client, flush the rest, and get out of the way.
885 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
886 csp->ip_addr_str, http->cmd);
888 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
896 /* we're finished with the client's header */
899 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
901 /* pass data between the client and server
902 * until one or the other shuts down the connection.
911 FD_SET(csp->cfd, &rfds);
912 FD_SET(csp->sfd, &rfds);
914 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
918 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
922 /* this is the body of the browser's request
923 * just read it and write it.
926 if (FD_ISSET(csp->cfd, &rfds))
928 n = read_socket(csp->cfd, buf, sizeof(buf));
932 break; /* "game over, man" */
935 if (write_socket(csp->sfd, buf, n) != n)
937 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
944 * The server wants to talk. It could be the header or the body.
945 * If `hdr' is null, then it's the header otherwise it's the body.
946 * FIXME: Does `hdr' really mean `host'? No.
950 if (FD_ISSET(csp->sfd, &rfds))
953 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
957 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
959 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
960 csp->ip_addr_str, http->cmd);
962 rsp = error_response(csp, "connect-failed", errno);
966 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
967 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
969 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
973 free_http_response(rsp);
977 /* Add a trailing zero. This lets filter_popups
978 * use string operations.
982 #ifdef FEATURE_KILL_POPUPS
983 /* Filter the popups on this read. */
984 if (block_popups_now)
986 filter_popups(buf, csp);
988 #endif /* def FEATURE_KILL_POPUPS */
990 /* Normally, this would indicate that we've read
991 * as much as the server has sent us and we can
992 * close the client connection. However, Microsoft
993 * in its wisdom has released IIS/5 with a bug that
994 * prevents it from sending the trailing \r\n in
995 * a 302 redirect header (and possibly other headers).
996 * To work around this if we've haven't parsed
997 * a full header we'll append a trailing \r\n
998 * and see if this now generates a valid one.
1000 * This hack shouldn't have any impacts. If we've
1001 * already transmitted the header or if this is a
1002 * SSL connection, then we won't bother with this
1003 * hack. So we only work on partially received
1004 * headers. If we append a \r\n and this still
1005 * doesn't generate a valid header, then we won't
1006 * transmit anything to the client.
1011 if (server_body || http->ssl)
1014 * If we have been buffering up the document,
1015 * now is the time to apply content modification
1016 * and send the result to the client.
1021 * If the content filter fails, use the original
1022 * buffer and length.
1023 * (see p != NULL ? p : csp->iob->cur below)
1025 if (NULL == (p = (*content_filter)(csp)))
1027 csp->content_length = csp->iob->eod - csp->iob->cur;
1030 hdr = sed(server_patterns, add_server_headers, csp);
1033 if ((write_socket(csp->cfd, hdr, n) != n)
1034 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1036 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1046 break; /* "game over, man" */
1050 * This is NOT the body, so
1051 * Let's pretend the server just sent us a blank line.
1053 n = sprintf(buf, "\r\n");
1056 * Now, let the normal header parsing algorithm below do its
1057 * job. If it fails, we'll exit instead of continuing.
1064 * If this is an SSL connection or we're in the body
1065 * of the server document, just write it to the client,
1066 * unless we need to buffer the body for later content-filtering
1069 if (server_body || http->ssl)
1073 add_to_iob(csp, buf, n);
1076 * If the buffer limit will be reached on the next read,
1077 * switch to non-filtering mode, i.e. make & write the
1078 * header, flush the socket and get out of the way.
1080 if (csp->iob->eod - csp->iob->buf + BUFFER_SIZE > csp->config->buffer_limit)
1082 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1084 hdr = sed(server_patterns, add_server_headers, csp);
1088 if (((write_socket(csp->cfd, hdr, n) != n)
1089 || (n = flush_socket(csp->cfd, csp) < 0)))
1091 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1100 content_filter = NULL;
1107 if (write_socket(csp->cfd, buf, n) != n)
1109 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1118 /* we're still looking for the end of the
1119 * server's header ... (does that make header
1120 * parsing an "out of body experience" ?
1123 /* buffer up the data we just read */
1124 add_to_iob(csp, buf, n);
1126 /* get header lines from the iob */
1128 while ((p = get_header(csp)))
1132 /* see following note */
1135 enlist(csp->headers, p);
1139 /* NOTE: there are no "empty" headers so
1140 * if the pointer `p' is not NULL we must
1141 * assume that we reached the end of the
1142 * buffer before we hit the end of the header.
1149 /* Well, we tried our MS IIS/5
1150 * hack and it didn't work.
1151 * The header is incomplete
1152 * and there isn't anything
1153 * we can do about it.
1159 /* Since we have to wait for
1160 * more from the server before
1161 * we can parse the headers
1162 * we just continue here.
1168 /* we have now received the entire header.
1169 * filter it and send the result to the client
1172 hdr = sed(server_patterns, add_server_headers, csp);
1175 /* write the server's (modified) header to
1176 * the client (along with anything else that
1177 * may be in the buffer)
1180 #ifdef FEATURE_KILL_POPUPS
1181 /* Start blocking popups if appropriate. */
1183 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1184 !http->ssl && /* We talk plaintext */
1185 block_popups) /* Policy allows */
1187 block_popups_now = 1;
1189 * Filter the part of the body that came in the same read
1190 * as the last headers:
1192 filter_popups(csp->iob->cur, csp);
1195 #endif /* def FEATURE_KILL_POPUPS */
1197 /* Buffer and pcrs filter this if appropriate. */
1199 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1200 !http->ssl && /* We talk plaintext */
1201 pcrs_filter) /* Policy allows */
1203 content_filter = pcrs_filter_response;
1206 /* Buffer and gif_deanimate this if appropriate. */
1208 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1209 !http->ssl && /* We talk plaintext */
1210 gif_deanimate) /* Policy allows */
1212 content_filter = gif_deanimate_response;
1217 * Only write if we're not buffering for content modification
1219 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1220 || (n = flush_socket(csp->cfd, csp) < 0)))
1222 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1224 /* the write failed, so don't bother
1225 * mentioning it to the client...
1226 * it probably can't hear us anyway.
1232 if(!content_filter) byte_count += n;
1234 /* we're finished with the server's header */
1239 /* If this was a MS IIS/5 hack then it means
1240 * the server has already closed the
1241 * connection. Nothing more to read. Time
1252 return; /* huh? we should never get here */
1255 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1256 csp->ip_addr_str, http->cmd, byte_count);
1260 /*********************************************************************
1264 * Description : This is little more than chat. We only "serve" to
1265 * to close any socket that chat may have opened.
1268 * 1 : csp = Current client state (buffers, headers, etc...)
1272 *********************************************************************/
1274 void serve(struct client_state *csp)
1275 #else /* ifndef AMIGA */
1276 static void serve(struct client_state *csp)
1277 #endif /* def AMIGA */
1280 close_socket(csp->cfd);
1284 close_socket(csp->sfd);
1287 csp->flags &= ~CSP_FLAG_ACTIVE;
1293 /*********************************************************************
1295 * Function : server_thread
1297 * Description : We only exist to call `serve' in a threaded environment.
1300 * 1 : data = Current client state (buffers, headers, etc...)
1302 * Returns : Always 0.
1304 *********************************************************************/
1305 static int32 server_thread(void *data)
1307 serve((struct client_state *) data);
1314 /*********************************************************************
1318 * Description : Load the config file and start the listen loop.
1319 * This function is a lot more *sane* with the `load_config'
1320 * and `listen_loop' functions; although it stills does
1321 * a *little* too much for my taste.
1324 * 1 : argc = Number of parameters (including $0).
1325 * 2 : argv = Array of (char *)'s to the parameters.
1327 * Returns : 1 if : can't open config file, unrecognized directive,
1328 * stats requested in multi-thread mode, can't open the
1329 * log file, can't open the jar file, listen port is invalid,
1330 * any load fails, and can't bind port.
1332 * Else main never returns, the process must be signaled
1333 * to terminate execution. Or, on Windows, use the
1334 * "File", "Exit" menu option.
1336 *********************************************************************/
1338 int real_main(int argc, const char *argv[])
1340 int main(int argc, const char *argv[])
1345 "AmiTCP:db/junkbuster/config"
1346 #elif !defined(_WIN32)
1353 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1354 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1356 printf("JunkBuster proxy version " VERSION ".\n\n"
1357 "Usage: %s [configfile]\n\n"
1358 "See " HOME_PAGE_URL " for details.\n"
1359 "This program is distributed under the GNU GPL, version 2 or later.\n",
1363 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1365 printf(VERSION "\n");
1368 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1375 configfile = argv[1];
1382 #elif defined(_WIN32)
1387 #if !defined(_WIN32) && !defined(__OS2__)
1388 signal(SIGPIPE, SIG_IGN);
1389 signal(SIGCHLD, SIG_IGN);
1391 #else /* ifdef _WIN32 */
1392 # ifdef _WIN_CONSOLE
1394 * We *are* in a windows console app.
1395 * Print a verbose messages about FAQ's and such
1397 printf(win32_blurb);
1398 # endif /* def _WIN_CONSOLE */
1399 #endif /* def _WIN32 */
1402 /* Initialize the CGI subsystem */
1403 cgi_init_error_messages();
1413 /*********************************************************************
1415 * Function : listen_loop
1417 * Description : bind the listen port and enter a "FOREVER" listening loop.
1423 *********************************************************************/
1424 static void listen_loop(void)
1426 struct client_state *csp = NULL;
1428 struct configuration_spec * config;
1430 config = load_config();
1432 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1433 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1435 bfd = bind_port(config->haddr, config->hport);
1439 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1440 "- There may be another junkbuster or some other "
1441 "proxy running on port %d",
1442 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1443 config->hport, config->hport
1445 /* shouldn't get here */
1449 config->need_bind = 0;
1454 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1455 while (waitpid(-1, NULL, WNOHANG) > 0)
1457 /* zombie children */
1459 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1462 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1464 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1468 csp->flags |= CSP_FLAG_ACTIVE;
1471 csp->config = config = load_config();
1473 if ( config->need_bind )
1476 * Since we were listening to the "old port", we will not see
1477 * a "listen" param change until the next IJB request. So, at
1478 * least 1 more request must be made for us to find the new
1479 * setting. I am simply closing the old socket and binding the
1482 * Which-ever is correct, we will serve 1 more page via the
1483 * old settings. This should probably be a "show-proxy-args"
1484 * request. This should not be a so common of an operation
1485 * that this will hurt people's feelings.
1490 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1491 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1492 bfd = bind_port(config->haddr, config->hport);
1496 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1497 "- There may be another junkbuster or some other "
1498 "proxy running on port %d",
1499 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1500 config->hport, config->hport
1502 /* shouldn't get here */
1506 config->need_bind = 0;
1509 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1511 if (!accept_connection(csp, bfd))
1513 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1526 log_error(LOG_LEVEL_CONNECT, "OK");
1529 #ifdef FEATURE_TOGGLE
1532 csp->flags |= CSP_FLAG_TOGGLED_ON;
1534 #endif /* def FEATURE_TOGGLE */
1536 if (run_loader(csp))
1538 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1539 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1543 if (block_acl(NULL,csp))
1545 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1546 close_socket(csp->cfd);
1550 #endif /* def FEATURE_ACL */
1552 /* add it to the list of clients */
1553 csp->next = clients->next;
1554 clients->next = csp;
1556 if (config->multi_threaded)
1560 /* this is a switch () statment in the C preprocessor - ugh */
1561 #undef SELECTED_ONE_OPTION
1563 /* Use Pthreads in preference to native code */
1564 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1565 #define SELECTED_ONE_OPTION
1567 pthread_t the_thread;
1568 pthread_attr_t attrs;
1570 pthread_attr_init(&attrs);
1571 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1572 child_id = (pthread_create(&the_thread, &attrs,
1573 (void*)serve, csp) ? -1 : 0);
1574 pthread_attr_destroy(&attrs);
1578 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1579 #define SELECTED_ONE_OPTION
1580 child_id = _beginthread(
1586 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1587 #define SELECTED_ONE_OPTION
1588 child_id = _beginthread(
1595 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1596 #define SELECTED_ONE_OPTION
1598 thread_id tid = spawn_thread
1599 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1601 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1603 child_id = (int) tid;
1612 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1613 #define SELECTED_ONE_OPTION
1614 csp->cfd = ReleaseSocket(csp->cfd, -1);
1615 if((child_id = (int)CreateNewProcTags(
1616 NP_Entry, (ULONG)server_thread,
1617 NP_Output, Output(),
1618 NP_CloseOutput, FALSE,
1619 NP_Name, (ULONG)"junkbuster child",
1620 NP_StackSize, 200*1024,
1624 ((struct Task *)child_id)->tc_UserData = csp;
1625 Signal((struct Task *)child_id, SIGF_SINGLE);
1630 #if !defined(SELECTED_ONE_OPTION)
1633 /* This block is only needed when using fork().
1634 * When using threads, the server thread was
1635 * created and run by the call to _beginthread().
1637 if (child_id == 0) /* child */
1643 else if (child_id > 0) /* parent */
1645 /* in a fork()'d environment, the parent's
1646 * copy of the client socket and the CSP
1650 #if !defined(_WIN32) && defined(__CYGWIN__)
1652 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1653 close_socket(csp->cfd);
1654 csp->flags &= ~CSP_FLAG_ACTIVE;
1658 #undef SELECTED_ONE_OPTION
1659 /* end of cpp switch () */
1661 if (child_id < 0) /* failed */
1663 char buf[BUFFER_SIZE];
1665 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1667 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1669 write_socket(csp->cfd, buf, strlen(buf));
1670 close_socket(csp->cfd);
1671 csp->flags &= ~CSP_FLAG_ACTIVE;