1 const char jcc_rcs[] = "$Id: jcc.c,v 1.56 2001/11/13 20:20:54 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.56 2001/11/13 20:20:54 jongfoster
37 * Tabs->spaces, fixing a bug with missing {} around an if()
39 * Revision 1.55 2001/11/13 20:14:53 jongfoster
40 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
42 * Revision 1.54 2001/11/07 00:03:14 steudten
43 * Give reliable return value if an error
44 * occurs not just 0 with new daemon mode.
46 * Revision 1.53 2001/11/05 21:41:43 steudten
47 * Add changes to be a real daemon just for unix os.
48 * (change cwd to /, detach from controlling tty, set
49 * process group and session leader to the own process.
51 * Add some fatal-error log message for failed malloc().
52 * Add '-d' if compiled with 'configure --with-debug' to
53 * enable debug output.
55 * Revision 1.52 2001/10/26 20:11:20 jongfoster
56 * Fixing type mismatch
58 * Revision 1.51 2001/10/26 17:38:28 oes
61 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
62 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
63 * threads to call select() simultaneously. So, it's time to do a real, live,
64 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
65 * (native). Both versions will work, but using __OS2__ offers multi-threading.
67 * Revision 1.49 2001/10/23 21:41:35 jongfoster
68 * Added call to initialize the (statically-allocated of course)
69 * "out of memory" CGI response.
71 * Revision 1.48 2001/10/10 19:56:46 jongfoster
72 * Moving some code that wasn't cookie-related out of an #ifdef
75 * Revision 1.47 2001/10/10 16:44:36 oes
76 * Added CONNECT destination port limitation check
78 * Revision 1.46 2001/10/08 15:17:41 oes
79 * Re-enabled SSL forwarding
81 * Revision 1.45 2001/10/07 15:42:11 oes
82 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
84 * Moved downgrading of the HTTP version from parse_http_request to
85 * chat(), since we can't decide if it is necessary before we have
86 * determined the actions for the URL. The HTTP command is now
87 * *always* re-built so the repairs need no longer be special-cased.
89 * filter_popups now gets a csp pointer so it can raise the new
90 * CSP_FLAG_MODIFIED flag.
94 * Added configurable size limit for the IOB. If the IOB grows so
95 * large that the next read would exceed the limit, the header
96 * is generated, and the header & unfiltered buffer are flushed
97 * to the client. Chat then continues in non-buffering,
98 * non-filtering body mode.
100 * Revision 1.44 2001/10/02 18:13:57 oes
103 * Revision 1.43 2001/10/02 15:32:13 oes
104 * Moved generation of hdr
106 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
107 * Cleaning up 2 compiler warnings on OS/2.
109 * Revision 1.41 2001/09/16 17:05:14 jongfoster
110 * Removing unused #include showarg.h
112 * Revision 1.40 2001/09/16 15:41:45 jongfoster
113 * Fixing signed/unsigned comparison warning.
115 * Revision 1.39 2001/09/16 13:21:27 jongfoster
116 * Changes to use new list functions.
118 * Revision 1.38 2001/09/16 13:01:46 jongfoster
119 * Removing redundant function call that zeroed zalloc()'d memory.
121 * Revision 1.37 2001/09/10 11:12:24 oes
122 * Deleted unused variable
124 * Revision 1.36 2001/09/10 10:56:15 oes
125 * Silenced compiler warnings
127 * Revision 1.35 2001/07/31 14:44:22 oes
128 * Deleted unused size parameter from filter_popups()
130 * Revision 1.34 2001/07/30 22:08:36 jongfoster
131 * Tidying up #defines:
132 * - All feature #defines are now of the form FEATURE_xxx
133 * - Permanently turned off WIN_GUI_EDIT
134 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
136 * Revision 1.33 2001/07/29 19:32:00 jongfoster
137 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
139 * Revision 1.32 2001/07/29 18:47:05 jongfoster
140 * Adding missing #include "loadcfg.h"
142 * Revision 1.31 2001/07/29 12:17:48 oes
143 * Applied pthread fix by Paul Lieverse
145 * Revision 1.30 2001/07/25 22:57:13 jongfoster
146 * __BEOS__ no longer overrides FEATURE_PTHREAD.
147 * This is because FEATURE_PTHREAD will soon be widely used, so I
148 * want to keep it simple.
150 * Revision 1.29 2001/07/24 12:47:06 oes
151 * Applied BeOS support update by Eugenia
153 * Revision 1.28 2001/07/23 13:26:12 oes
154 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
156 * Revision 1.27 2001/07/19 19:09:47 haroon
157 * - Added code to take care of the situation where while processing the first
158 * server response (which includes the server header), after finding the end
159 * of the headers we were not looking past the end of the headers for
160 * content modification. I enabled it for filter_popups.
161 * Someone else should look to see if other similar operations should be
162 * done to the discarded portion of the buffer.
164 * Note 2001/07/20: No, the other content modification mechanisms will process
165 * the whole iob later anyway. --oes
167 * Revision 1.26 2001/07/18 12:31:36 oes
170 * Revision 1.25 2001/07/15 19:43:49 jongfoster
171 * Supports POSIX threads.
172 * Also removed some unused #includes.
174 * Revision 1.24 2001/07/13 14:00:40 oes
175 * - Generic content modification scheme:
176 * Each feature has its own applicability flag that is set
177 * from csp->action->flags.
178 * Replaced the "filtering" int flag , by a function pointer
179 * "content_filter" to the function that will do the content
180 * modification. If it is != NULL, the document will be buffered
181 * and processed through *content_filter, which must set
182 * csp->content_length and return a modified copy of the body
183 * or return NULL (on failiure).
184 * - Changed csp->is_text to the more generic bitmap csp->content_type
185 * which can currently take the valued CT_TEXT or CT_GIF
187 * - Removed all #ifdef PCRS
189 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
190 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
191 * the `block_acl' call. This prevents a compilation error when the user
192 * does not wish to use the "ACL" feature.
194 * Revision 1.22 2001/06/29 21:45:41 oes
195 * Indentation, CRLF->LF, Tab-> Space
197 * Revision 1.21 2001/06/29 13:29:36 oes
198 * - Cleaned up, improved comments
199 * - Unified all possible interceptors (CGI,
200 * block, trust, fast_redirect) in one
201 * place, with one (CGI) answer generation
202 * mechansim. Much clearer now.
203 * - Removed the GIF image generation, which
204 * is now done in filters.c:block_url()
205 * - Made error conditions like domain lookup
206 * failiure or (various) problems while talking
207 * to the server use cgi.c:error_response()
208 * instead of generating HTML/HTTP in chat() (yuck!)
209 * - Removed logentry from cancelled commit
211 * Revision 1.20 2001/06/09 10:55:28 jongfoster
212 * Changing BUFSIZ ==> BUFFER_SIZE
214 * Revision 1.19 2001/06/07 23:12:52 jongfoster
215 * Replacing function pointer in struct gateway with a directly
216 * called function forwarded_connect().
217 * Replacing struct gateway with struct forward_spec
219 * Revision 1.18 2001/06/03 19:12:16 oes
220 * introduced new cgi handling
222 * Revision 1.17 2001/06/01 20:07:23 jongfoster
223 * Now uses action +image-blocker{} rather than config->tinygif
225 * Revision 1.16 2001/06/01 18:49:17 jongfoster
226 * Replaced "list_share" with "list" - the tiny memory gain was not
227 * worth the extra complexity.
229 * Revision 1.15 2001/05/31 21:24:47 jongfoster
230 * Changed "permission" to "action" throughout.
231 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
232 * Moved vanilla wafer check into chat(), since we must now
233 * decide whether or not to add it based on the URL.
235 * Revision 1.14 2001/05/29 20:14:01 joergs
236 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
239 * Revision 1.13 2001/05/29 09:50:24 jongfoster
240 * Unified blocklist/imagelist/permissionslist.
241 * File format is still under discussion, but the internal changes
244 * Also modified interceptor behaviour:
245 * - We now intercept all URLs beginning with one of the following
246 * prefixes (and *only* these prefixes):
248 * * http://ijbswa.sf.net/config/
249 * * http://ijbswa.sourceforge.net/config/
250 * - New interceptors "home page" - go to http://i.j.b/ to see it.
251 * - Internal changes so that intercepted and fast redirect pages
252 * are not replaced with an image.
253 * - Interceptors now have the option to send a binary page direct
254 * to the client. (i.e. ijb-send-banner uses this)
255 * - Implemented show-url-info interceptor. (Which is why I needed
256 * the above interceptors changes - a typical URL is
257 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
258 * The previous mechanism would not have intercepted that, and
259 * if it had been intercepted then it then it would have replaced
262 * Revision 1.12 2001/05/27 22:17:04 oes
264 * - re_process_buffer no longer writes the modified buffer
265 * to the client, which was very ugly. It now returns the
266 * buffer, which it is then written by chat.
268 * - content_length now adjusts the Content-Length: header
269 * for modified documents rather than crunch()ing it.
270 * (Length info in csp->content_length, which is 0 for
271 * unmodified documents)
273 * - For this to work, sed() is called twice when filtering.
275 * Revision 1.11 2001/05/26 17:27:53 jongfoster
276 * Added support for CLF and fixed LOG_LEVEL_LOG.
277 * Also did CRLF->LF fix of my previous patch.
279 * Revision 1.10 2001/05/26 15:26:15 jongfoster
280 * ACL feature now provides more security by immediately dropping
281 * connections from untrusted hosts.
283 * Revision 1.9 2001/05/26 00:28:36 jongfoster
284 * Automatic reloading of config file.
285 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
286 * Most of the global variables have been moved to a new
287 * struct configuration_spec, accessed through csp->config->globalname
288 * Most of the globals remaining are used by the Win32 GUI.
290 * Revision 1.8 2001/05/25 22:43:18 jongfoster
291 * Fixing minor memory leak and buffer overflow.
293 * Revision 1.7 2001/05/25 22:34:30 jongfoster
296 * Revision 1.6 2001/05/23 00:13:58 joergs
297 * AmigaOS support fixed.
299 * Revision 1.5 2001/05/22 18:46:04 oes
301 * - Enabled filtering banners by size rather than URL
302 * by adding patterns that replace all standard banner
303 * sizes with the "Junkbuster" gif to the re_filterfile
305 * - Enabled filtering WebBugs by providing a pattern
306 * which kills all 1x1 images
308 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
309 * which is selected by the (nonstandard and therefore
310 * capital) letter 'U' in the option string.
311 * It causes the quantifiers to be ungreedy by default.
312 * Appending a ? turns back to greedy (!).
314 * - Added a new interceptor ijb-send-banner, which
315 * sends back the "Junkbuster" gif. Without imagelist or
316 * MSIE detection support, or if tinygif = 1, or the
317 * URL isn't recognized as an imageurl, a lame HTML
318 * explanation is sent instead.
320 * - Added new feature, which permits blocking remote
321 * script redirects and firing back a local redirect
323 * The feature is conditionally compiled, i.e. it
324 * can be disabled with --disable-fast-redirects,
325 * plus it must be activated by a "fast-redirects"
326 * line in the config file, has its own log level
327 * and of course wants to be displayed by show-proxy-args
328 * Note: Boy, all the #ifdefs in 1001 locations and
329 * all the fumbling with configure.in and acconfig.h
330 * were *way* more work than the feature itself :-(
332 * - Because a generic redirect template was needed for
333 * this, tinygif = 3 now uses the same.
335 * - Moved GIFs, and other static HTTP response templates
340 * - Removed some >400 CRs again (Jon, you really worked
343 * Revision 1.4 2001/05/21 19:34:01 jongfoster
344 * Made failure to bind() a fatal error.
346 * Revision 1.3 2001/05/20 01:21:20 jongfoster
347 * Version 2.9.4 checkin.
348 * - Merged popupfile and cookiefile, and added control over PCRS
349 * filtering, in new "permissionsfile".
350 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
351 * file error you now get a message box (in the Win32 GUI) rather
352 * than the program exiting with no explanation.
353 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
355 * - Removed tabs from "config"
356 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
357 * - Bumped up version number.
359 * Revision 1.2 2001/05/17 22:34:44 oes
360 * - Added hint on GIF char array generation to jcc.c
361 * - Cleaned CRLF's from the sources and related files
362 * - Repaired logging for REF and FRC
364 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
365 * Initial import of version 2.9.3 source tree
368 *********************************************************************/
374 #include <sys/types.h>
381 #ifdef FEATURE_PTHREAD
383 #endif /* def FEATURE_PTHREAD */
386 # ifndef FEATURE_PTHREAD
387 # include <windows.h>
388 # include <process.h>
389 # endif /* ndef FEATURE_PTHREAD */
392 # ifndef _WIN_CONSOLE
394 # endif /* ndef _WIN_CONSOLE */
396 #else /* ifndef _WIN32 */
398 # if !defined (__OS2__)
400 # include <sys/wait.h>
401 # endif /* ndef __OS2__ */
402 # include <sys/time.h>
403 # include <sys/stat.h>
404 # include <sys/ioctl.h>
407 #include <sys/termios.h>
413 # include <socket.h> /* BeOS has select() for sockets only. */
414 # include <OS.h> /* declarations for threads and stuff. */
417 # if defined(__EMX__) || defined(__OS2__)
418 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
423 #define bzero(B,N) memset(B,0x00,n)
442 #include "killpopup.h"
443 #include "miscutil.h"
445 #include "jbsockets.h"
451 const char jcc_h_rcs[] = JCC_H_VERSION;
452 const char project_h_rcs[] = PROJECT_H_VERSION;
454 struct client_state clients[1];
455 struct file_list files[1];
457 #ifdef FEATURE_STATISTICS
458 int urls_read = 0; /* total nr of urls read inc rejected */
459 int urls_rejected = 0; /* total nr of urls rejected */
460 #endif /* def FEATURE_STATISTICS */
463 static void listen_loop(void);
464 static void chat(struct client_state *csp);
466 void serve(struct client_state *csp);
467 #else /* ifndef AMIGA */
468 static void serve(struct client_state *csp);
469 #endif /* def AMIGA */
472 static int32 server_thread(void *data);
473 #endif /* def __BEOS__ */
476 #define sleep(N) Sleep(((N) * 1000))
480 #define sleep(N) DosSleep(((N) * 100))
485 #endif /* defined unix */
487 /* The vanilla wafer. */
488 static const char VANILLA_WAFER[] =
489 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
490 "Do_not_send_me_any_copyrighted_information_other_than_the_"
491 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
492 "In_particular_do_not_send_me_any_cookies_that_"
493 "are_subject_to_a_claim_of_copyright_by_anybody._"
494 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
495 "(copyright_or_otherwise)_applying_to_any_cookie._";
498 /*********************************************************************
502 * Description : Once a connection to the client has been accepted,
503 * this function is called (via serve()) to handle the
504 * main business of the communication. When this
505 * function returns, the caller must close the client
509 * 1 : csp = Current client state (buffers, headers, etc...)
511 * Returns : On success, the number of bytes written are returned (zero
512 * indicates nothing was written). On error, -1 is returned,
513 * and errno is set appropriately. If count is zero and the
514 * file descriptor refers to a regular file, 0 will be
515 * returned without causing any other effect. For a special
516 * file, the results are not portable.
518 *********************************************************************/
519 static void chat(struct client_state *csp)
522 * This next lines are a little ugly, but they simplifies the if statements
523 * below. Basically if TOGGLE, then we want the if to test if the
524 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
525 * then we want the if to test for CSP_FLAG_FORCED , else we don't
527 #ifdef FEATURE_TOGGLE
528 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
529 #else /* ifndef FEATURE_TOGGLE */
530 # define IS_TOGGLED_ON_AND
531 #endif /* ndef FEATURE_TOGGLE */
532 #ifdef FEATURE_FORCE_LOAD
533 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
534 #else /* ifndef FEATURE_FORCE_LOAD */
535 # define IS_NOT_FORCED_AND
536 #endif /* def FEATURE_FORCE_LOAD */
538 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
540 char buf[BUFFER_SIZE];
543 int n, maxfd, server_body;
544 int ms_iis5_hack = 0;
546 const struct forward_spec * fwd;
547 struct http_request *http;
548 #ifdef FEATURE_KILL_POPUPS
549 int block_popups; /* bool, 1==will block popups */
550 int block_popups_now = 0; /* bool, 1==currently blocking popups */
551 #endif /* def FEATURE_KILL_POPUPS */
553 int pcrs_filter; /* bool, 1==will filter through pcrs */
554 int gif_deanimate; /* bool, 1==will deanimate gifs */
556 /* Function that does the content filtering for the current request */
557 char *(*content_filter)() = NULL;
559 /* Skeleton for HTTP response, if we should intercept the request */
560 struct http_response *rsp;
565 * Read the client's request. Note that since we're not using select() we
566 * could get blocked here if a client connected, then didn't say anything!
571 n = read_socket(csp->cfd, buf, sizeof(buf));
573 if (n <= 0) break; /* error! */
575 add_to_iob(csp, buf, n);
577 req = get_header(csp);
581 break; /* no HTTP request! */
586 continue; /* more to come! */
589 #ifdef FEATURE_FORCE_LOAD
590 /* If this request contains the FORCE_PREFIX,
591 * better get rid of it now and set the force flag --oes
594 if (strstr(req, FORCE_PREFIX))
596 strclean(req, FORCE_PREFIX);
597 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
598 csp->flags |= CSP_FLAG_FORCED;
601 #endif /* def FEATURE_FORCE_LOAD */
603 parse_http_request(req, http, csp);
608 if (http->cmd == NULL)
610 strcpy(buf, CHEADER);
611 write_socket(csp->cfd, buf, strlen(buf));
613 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
618 /* decide how to route the HTTP request */
620 if ((fwd = forward_url(http, csp)) == NULL)
622 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
623 /* Never get here - LOG_LEVEL_FATAL causes program exit */
626 /* build the http request to send to the server
627 * we have to do one of the following:
629 * create = use the original HTTP request to create a new
630 * HTTP request that has either the path component
631 * without the http://domainspec (w/path) or the
632 * full orininal URL (w/url)
633 * Note that the path and/or the HTTP version may
634 * have been altered by now.
636 * connect = Open a socket to the host:port of the server
637 * and short-circuit server and client socket.
639 * pass = Pass the request unchanged if forwarding a CONNECT
640 * request to a parent proxy. Note that we'll be sending
641 * the CFAIL message ourselves if connecting to the parent
642 * fails, but we won't send a CSUCCEED message if it works,
643 * since that would result in a double message (ours and the
644 * parent's). After sending the request to the parent, we simply
650 * +--------+--------+
652 * 0 | create | connect|
654 * Forwarding +--------+--------+
656 * 1 | create | pass |
658 * +--------+--------+
663 * Determine the actions for this URL
665 #ifdef FEATURE_TOGGLE
666 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
668 /* Most compatible set of actions (i.e. none) */
669 init_current_action(csp->action);
672 #endif /* ndef FEATURE_TOGGLE */
674 url_actions(http, csp);
679 * Check if a CONNECT request is allowable:
680 * In the absence of a +limit-connect action, allow only port 443.
681 * If there is an action, allow whatever matches the specificaton.
685 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
686 || (csp->action->flags & ACTION_LIMIT_CONNECT
687 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
689 strcpy(buf, CFORBIDDEN);
690 write_socket(csp->cfd, buf, strlen(buf));
692 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
693 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
701 * Downgrade http version from 1.1 to 1.0 if +downgrade
704 if (!strcmpic(http->ver, "HTTP/1.1") && csp->action->flags & ACTION_DOWNGRADE)
707 http->ver = strdup("HTTP/1.0");
711 * (Re)build the HTTP request for non-SSL requests.
712 * If forwarding, use the whole URL, else, use only the path.
718 http->cmd = strsav(http->cmd, http->gpc);
719 http->cmd = strsav(http->cmd, " ");
721 if (fwd->forward_host)
723 http->cmd = strsav(http->cmd, http->url);
727 http->cmd = strsav(http->cmd, http->path);
730 http->cmd = strsav(http->cmd, " ");
731 http->cmd = strsav(http->cmd, http->ver);
734 enlist(csp->headers, http->cmd);
737 #ifdef FEATURE_COOKIE_JAR
739 * If we're logging cookies in a cookie jar, and the user has not
740 * supplied any wafers, and the user has not told us to suppress the
741 * vanilla wafer, then send the vanilla wafer.
743 if ((csp->config->jarfile != NULL)
744 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
745 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
747 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
749 #endif /* def FEATURE_COOKIE_JAR */
752 #ifdef FEATURE_KILL_POPUPS
753 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
754 #endif /* def FEATURE_KILL_POPUPS */
756 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
757 ((csp->action->flags & ACTION_FILTER) != 0);
759 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
761 /* grab the rest of the client's headers */
765 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
767 n = read_socket(csp->cfd, buf, sizeof(buf));
770 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
773 add_to_iob(csp, buf, n);
777 if (p == NULL) break;
779 enlist(csp->headers, p);
783 * We have a request. Now, check to see if we need to
784 * intercept it, i.e. If ..
788 /* a CGI call was detected and answered */
789 (NULL != (rsp = dispatch_cgi(csp)))
791 /* or we are enabled and... */
794 /* ..the request was blocked */
795 ( NULL != (rsp = block_url(csp)))
799 || ( NULL != (rsp = trust_url(csp)))
800 #endif /* def FEATURE_TRUST */
802 /* ..or a fast redirect kicked in */
803 #ifdef FEATURE_FAST_REDIRECTS
804 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
805 (NULL != (rsp = redirect_url(csp))))
806 #endif /* def FEATURE_FAST_REDIRECTS */
810 /* Write the answer to the client */
811 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
812 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
814 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
817 #ifdef FEATURE_STATISTICS
818 /* Count as a rejected request */
819 csp->flags |= CSP_FLAG_REJECTED;
820 #endif /* def FEATURE_STATISTICS */
822 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
823 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
824 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
826 /* Clean up and return */
827 free_http_response(rsp);
831 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
833 if (fwd->forward_host)
835 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
836 fwd->forward_host, fwd->forward_port, http->hostport);
840 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
843 /* here we connect to the server, gateway, or the forwarder */
845 csp->sfd = forwarded_connect(fwd, http, csp);
849 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
854 rsp = error_response(csp, "no-such-domain", errno);
856 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
857 csp->ip_addr_str, http->cmd);
861 rsp = error_response(csp, "connect-failed", errno);
863 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
864 csp->ip_addr_str, http->cmd);
867 /* Write the answer to the client */
870 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
871 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
873 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
877 free_http_response(rsp);
881 log_error(LOG_LEVEL_CONNECT, "OK");
883 hdr = sed(client_patterns, add_client_headers, csp);
884 list_remove_all(csp->headers);
886 if (fwd->forward_host || (http->ssl == 0))
888 /* write the client's (modified) header to the server
889 * (along with anything else that may be in the buffer)
894 if ((write_socket(csp->sfd, hdr, n) != n)
895 || (flush_socket(csp->sfd, csp ) < 0))
897 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
900 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
901 csp->ip_addr_str, http->cmd);
903 rsp = error_response(csp, "connect-failed", errno);
907 if ((write_socket(csp->cfd, rsp->head, n) != n)
908 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
910 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
914 free_http_response(rsp);
922 * We're running an SSL tunnel and we're not forwarding,
923 * so just send the "connect succeeded" message to the
924 * client, flush the rest, and get out of the way.
926 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
927 csp->ip_addr_str, http->cmd);
929 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
937 /* we're finished with the client's header */
940 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
942 /* pass data between the client and server
943 * until one or the other shuts down the connection.
952 FD_SET(csp->cfd, &rfds);
953 FD_SET(csp->sfd, &rfds);
955 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
959 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
963 /* this is the body of the browser's request
964 * just read it and write it.
967 if (FD_ISSET(csp->cfd, &rfds))
969 n = read_socket(csp->cfd, buf, sizeof(buf));
973 break; /* "game over, man" */
976 if (write_socket(csp->sfd, buf, n) != n)
978 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
985 * The server wants to talk. It could be the header or the body.
986 * If `hdr' is null, then it's the header otherwise it's the body.
987 * FIXME: Does `hdr' really mean `host'? No.
991 if (FD_ISSET(csp->sfd, &rfds))
994 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
998 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1000 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1001 csp->ip_addr_str, http->cmd);
1003 rsp = error_response(csp, "connect-failed", errno);
1007 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1008 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1010 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1014 free_http_response(rsp);
1018 /* Add a trailing zero. This lets filter_popups
1019 * use string operations.
1023 #ifdef FEATURE_KILL_POPUPS
1024 /* Filter the popups on this read. */
1025 if (block_popups_now)
1027 filter_popups(buf, csp);
1029 #endif /* def FEATURE_KILL_POPUPS */
1031 /* Normally, this would indicate that we've read
1032 * as much as the server has sent us and we can
1033 * close the client connection. However, Microsoft
1034 * in its wisdom has released IIS/5 with a bug that
1035 * prevents it from sending the trailing \r\n in
1036 * a 302 redirect header (and possibly other headers).
1037 * To work around this if we've haven't parsed
1038 * a full header we'll append a trailing \r\n
1039 * and see if this now generates a valid one.
1041 * This hack shouldn't have any impacts. If we've
1042 * already transmitted the header or if this is a
1043 * SSL connection, then we won't bother with this
1044 * hack. So we only work on partially received
1045 * headers. If we append a \r\n and this still
1046 * doesn't generate a valid header, then we won't
1047 * transmit anything to the client.
1052 if (server_body || http->ssl)
1055 * If we have been buffering up the document,
1056 * now is the time to apply content modification
1057 * and send the result to the client.
1062 * If the content filter fails, use the original
1063 * buffer and length.
1064 * (see p != NULL ? p : csp->iob->cur below)
1066 if (NULL == (p = (*content_filter)(csp)))
1068 csp->content_length = csp->iob->eod - csp->iob->cur;
1071 hdr = sed(server_patterns, add_server_headers, csp);
1074 if ((write_socket(csp->cfd, hdr, n) != n)
1075 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1077 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1087 break; /* "game over, man" */
1091 * This is NOT the body, so
1092 * Let's pretend the server just sent us a blank line.
1094 n = sprintf(buf, "\r\n");
1097 * Now, let the normal header parsing algorithm below do its
1098 * job. If it fails, we'll exit instead of continuing.
1105 * If this is an SSL connection or we're in the body
1106 * of the server document, just write it to the client,
1107 * unless we need to buffer the body for later content-filtering
1110 if (server_body || http->ssl)
1114 add_to_iob(csp, buf, n);
1117 * If the buffer limit will be reached on the next read,
1118 * switch to non-filtering mode, i.e. make & write the
1119 * header, flush the socket and get out of the way.
1121 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1123 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1125 hdr = sed(server_patterns, add_server_headers, csp);
1129 if (((write_socket(csp->cfd, hdr, n) != n)
1130 || (n = flush_socket(csp->cfd, csp) < 0)))
1132 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1141 content_filter = NULL;
1148 if (write_socket(csp->cfd, buf, n) != n)
1150 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1159 /* we're still looking for the end of the
1160 * server's header ... (does that make header
1161 * parsing an "out of body experience" ?
1164 /* buffer up the data we just read */
1165 add_to_iob(csp, buf, n);
1167 /* get header lines from the iob */
1169 while ((p = get_header(csp)))
1173 /* see following note */
1176 enlist(csp->headers, p);
1180 /* NOTE: there are no "empty" headers so
1181 * if the pointer `p' is not NULL we must
1182 * assume that we reached the end of the
1183 * buffer before we hit the end of the header.
1190 /* Well, we tried our MS IIS/5
1191 * hack and it didn't work.
1192 * The header is incomplete
1193 * and there isn't anything
1194 * we can do about it.
1200 /* Since we have to wait for
1201 * more from the server before
1202 * we can parse the headers
1203 * we just continue here.
1209 /* we have now received the entire header.
1210 * filter it and send the result to the client
1213 hdr = sed(server_patterns, add_server_headers, csp);
1216 /* write the server's (modified) header to
1217 * the client (along with anything else that
1218 * may be in the buffer)
1221 #ifdef FEATURE_KILL_POPUPS
1222 /* Start blocking popups if appropriate. */
1224 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1225 !http->ssl && /* We talk plaintext */
1226 block_popups) /* Policy allows */
1228 block_popups_now = 1;
1230 * Filter the part of the body that came in the same read
1231 * as the last headers:
1233 filter_popups(csp->iob->cur, csp);
1236 #endif /* def FEATURE_KILL_POPUPS */
1238 /* Buffer and pcrs filter this if appropriate. */
1240 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1241 !http->ssl && /* We talk plaintext */
1242 pcrs_filter) /* Policy allows */
1244 content_filter = pcrs_filter_response;
1247 /* Buffer and gif_deanimate this if appropriate. */
1249 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1250 !http->ssl && /* We talk plaintext */
1251 gif_deanimate) /* Policy allows */
1253 content_filter = gif_deanimate_response;
1258 * Only write if we're not buffering for content modification
1260 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1261 || (n = flush_socket(csp->cfd, csp) < 0)))
1263 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1265 /* the write failed, so don't bother
1266 * mentioning it to the client...
1267 * it probably can't hear us anyway.
1273 if(!content_filter) byte_count += n;
1275 /* we're finished with the server's header */
1280 /* If this was a MS IIS/5 hack then it means
1281 * the server has already closed the
1282 * connection. Nothing more to read. Time
1293 return; /* huh? we should never get here */
1296 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1297 csp->ip_addr_str, http->cmd, byte_count);
1301 /*********************************************************************
1305 * Description : This is little more than chat. We only "serve" to
1306 * to close any socket that chat may have opened.
1309 * 1 : csp = Current client state (buffers, headers, etc...)
1313 *********************************************************************/
1315 void serve(struct client_state *csp)
1316 #else /* ifndef AMIGA */
1317 static void serve(struct client_state *csp)
1318 #endif /* def AMIGA */
1321 close_socket(csp->cfd);
1325 close_socket(csp->sfd);
1328 csp->flags &= ~CSP_FLAG_ACTIVE;
1334 /*********************************************************************
1336 * Function : server_thread
1338 * Description : We only exist to call `serve' in a threaded environment.
1341 * 1 : data = Current client state (buffers, headers, etc...)
1343 * Returns : Always 0.
1345 *********************************************************************/
1346 static int32 server_thread(void *data)
1348 serve((struct client_state *) data);
1355 /*********************************************************************
1359 * Description : Load the config file and start the listen loop.
1360 * This function is a lot more *sane* with the `load_config'
1361 * and `listen_loop' functions; although it stills does
1362 * a *little* too much for my taste.
1365 * 1 : argc = Number of parameters (including $0).
1366 * 2 : argv = Array of (char *)'s to the parameters.
1368 * Returns : 1 if : can't open config file, unrecognized directive,
1369 * stats requested in multi-thread mode, can't open the
1370 * log file, can't open the jar file, listen port is invalid,
1371 * any load fails, and can't bind port.
1373 * Else main never returns, the process must be signaled
1374 * to terminate execution. Or, on Windows, use the
1375 * "File", "Exit" menu option.
1377 *********************************************************************/
1379 int real_main(int argc, const char *argv[])
1381 int main(int argc, const char *argv[])
1388 "AmiTCP:db/junkbuster/config"
1389 #elif !defined(_WIN32)
1396 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1397 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1399 printf("JunkBuster proxy version " VERSION ".\n\n"
1400 "Usage: %s [configfile]\n\n"
1401 "See " HOME_PAGE_URL " for details.\n"
1402 "This program is distributed under the GNU GPL, version 2 or later.\n",
1406 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1408 printf(VERSION "\n");
1412 if ((argc >= 2) && (strcmp(argv[1], "-d")==0))
1416 fprintf(stderr,"debugging enabled..\n");
1419 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1424 if (argc > argc_pos )
1426 configfile = argv[argc_pos];
1430 if ( *configfile != '/' )
1434 DBG(1, ("configfile before '%s'\n",configfile) );
1436 /* make config-filename absolute here */
1437 if ( !(basedir = getcwd( NULL, 1024 )))
1439 perror("get working dir failed");
1442 DBG(1, ("working dir '%s'\n",basedir) );
1443 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1445 perror("malloc failed");
1448 strcpy( abs_file, basedir );
1449 strcat( abs_file, "/" );
1450 strcat( abs_file, configfile );
1451 configfile = abs_file;
1452 DBG(1, ("configfile after '%s'\n",configfile) );
1454 #endif /* defined unix */
1461 #elif defined(_WIN32)
1466 #if !defined(_WIN32) && !defined(__OS2__)
1467 signal(SIGPIPE, SIG_IGN);
1468 signal(SIGCHLD, SIG_IGN);
1470 #else /* ifdef _WIN32 */
1471 # ifdef _WIN_CONSOLE
1473 * We *are* in a windows console app.
1474 * Print a verbose messages about FAQ's and such
1476 printf(win32_blurb);
1477 # endif /* def _WIN_CONSOLE */
1478 #endif /* def _WIN32 */
1481 /* Initialize the CGI subsystem */
1482 cgi_init_error_messages();
1492 * we make us a real daemon
1498 if ( pid < 0 ) /* error */
1503 else if ( pid != 0 ) /* parent */
1508 * must check for errors
1509 * child died due to missing files aso
1512 wpid = waitpid( pid, &status, WNOHANG );
1521 /* Should be more portable, but not as well tested */
1526 #else /* ndef __FreeBSD__ */
1528 #endif /* ndef __FreeBSD__ */
1529 fd = open("/dev/tty", O_RDONLY);
1532 /* no error check here */
1533 ioctl( fd, TIOCNOTTY,0 );
1537 /* should close stderr (fd 2) here too, but the test for existence
1538 ** and load config file is done in listen_loop() and puts
1539 ** some messages on stderr there.
1554 #endif /* defined unix */
1556 DBG(1, ("call listen_loop() \n") );
1565 /*********************************************************************
1567 * Function : listen_loop
1569 * Description : bind the listen port and enter a "FOREVER" listening loop.
1575 *********************************************************************/
1576 static void listen_loop(void)
1578 struct client_state *csp = NULL;
1580 struct configuration_spec * config;
1582 config = load_config();
1584 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1585 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1587 bfd = bind_port(config->haddr, config->hport);
1591 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1592 "- There may be another junkbuster or some other "
1593 "proxy running on port %d",
1594 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1595 config->hport, config->hport
1597 /* shouldn't get here */
1601 config->need_bind = 0;
1605 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1606 while (waitpid(-1, NULL, WNOHANG) > 0)
1608 /* zombie children */
1610 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1613 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1615 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1619 csp->flags |= CSP_FLAG_ACTIVE;
1622 csp->config = config = load_config();
1624 if ( config->need_bind )
1627 * Since we were listening to the "old port", we will not see
1628 * a "listen" param change until the next IJB request. So, at
1629 * least 1 more request must be made for us to find the new
1630 * setting. I am simply closing the old socket and binding the
1633 * Which-ever is correct, we will serve 1 more page via the
1634 * old settings. This should probably be a "show-proxy-args"
1635 * request. This should not be a so common of an operation
1636 * that this will hurt people's feelings.
1641 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1642 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1643 bfd = bind_port(config->haddr, config->hport);
1647 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1648 "- There may be another junkbuster or some other "
1649 "proxy running on port %d",
1650 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1651 config->hport, config->hport
1653 /* shouldn't get here */
1657 config->need_bind = 0;
1660 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1662 if (!accept_connection(csp, bfd))
1664 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1677 log_error(LOG_LEVEL_CONNECT, "OK");
1680 #ifdef FEATURE_TOGGLE
1683 csp->flags |= CSP_FLAG_TOGGLED_ON;
1685 #endif /* def FEATURE_TOGGLE */
1687 if (run_loader(csp))
1689 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1690 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1694 if (block_acl(NULL,csp))
1696 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1697 close_socket(csp->cfd);
1701 #endif /* def FEATURE_ACL */
1703 /* add it to the list of clients */
1704 csp->next = clients->next;
1705 clients->next = csp;
1707 if (config->multi_threaded)
1711 /* this is a switch () statment in the C preprocessor - ugh */
1712 #undef SELECTED_ONE_OPTION
1714 /* Use Pthreads in preference to native code */
1715 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1716 #define SELECTED_ONE_OPTION
1718 pthread_t the_thread;
1719 pthread_attr_t attrs;
1721 pthread_attr_init(&attrs);
1722 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1723 child_id = (pthread_create(&the_thread, &attrs,
1724 (void*)serve, csp) ? -1 : 0);
1725 pthread_attr_destroy(&attrs);
1729 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1730 #define SELECTED_ONE_OPTION
1731 child_id = _beginthread(
1737 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1738 #define SELECTED_ONE_OPTION
1739 child_id = _beginthread(
1746 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1747 #define SELECTED_ONE_OPTION
1749 thread_id tid = spawn_thread
1750 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1752 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1754 child_id = (int) tid;
1763 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1764 #define SELECTED_ONE_OPTION
1765 csp->cfd = ReleaseSocket(csp->cfd, -1);
1766 if((child_id = (int)CreateNewProcTags(
1767 NP_Entry, (ULONG)server_thread,
1768 NP_Output, Output(),
1769 NP_CloseOutput, FALSE,
1770 NP_Name, (ULONG)"junkbuster child",
1771 NP_StackSize, 200*1024,
1775 ((struct Task *)child_id)->tc_UserData = csp;
1776 Signal((struct Task *)child_id, SIGF_SINGLE);
1781 #if !defined(SELECTED_ONE_OPTION)
1784 /* This block is only needed when using fork().
1785 * When using threads, the server thread was
1786 * created and run by the call to _beginthread().
1788 if (child_id == 0) /* child */
1794 else if (child_id > 0) /* parent */
1796 /* in a fork()'d environment, the parent's
1797 * copy of the client socket and the CSP
1801 #if !defined(_WIN32) && defined(__CYGWIN__)
1803 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1804 close_socket(csp->cfd);
1805 csp->flags &= ~CSP_FLAG_ACTIVE;
1809 #undef SELECTED_ONE_OPTION
1810 /* end of cpp switch () */
1812 if (child_id < 0) /* failed */
1814 char buf[BUFFER_SIZE];
1816 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1818 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1820 write_socket(csp->cfd, buf, strlen(buf));
1821 close_socket(csp->cfd);
1822 csp->flags &= ~CSP_FLAG_ACTIVE;