1 const char jcc_rcs[] = "$Id: jcc.c,v 1.54 2001/11/07 00:03:14 steudten 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.54 2001/11/07 00:03:14 steudten
37 * Give reliable return value if an error
38 * occurs not just 0 with new daemon mode.
40 * Revision 1.53 2001/11/05 21:41:43 steudten
41 * Add changes to be a real daemon just for unix os.
42 * (change cwd to /, detach from controlling tty, set
43 * process group and session leader to the own process.
45 * Add some fatal-error log message for failed malloc().
46 * Add '-d' if compiled with 'configure --with-debug' to
47 * enable debug output.
49 * Revision 1.52 2001/10/26 20:11:20 jongfoster
50 * Fixing type mismatch
52 * Revision 1.51 2001/10/26 17:38:28 oes
55 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
56 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
57 * threads to call select() simultaneously. So, it's time to do a real, live,
58 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
59 * (native). Both versions will work, but using __OS2__ offers multi-threading.
61 * Revision 1.49 2001/10/23 21:41:35 jongfoster
62 * Added call to initialize the (statically-allocated of course)
63 * "out of memory" CGI response.
65 * Revision 1.48 2001/10/10 19:56:46 jongfoster
66 * Moving some code that wasn't cookie-related out of an #ifdef
69 * Revision 1.47 2001/10/10 16:44:36 oes
70 * Added CONNECT destination port limitation check
72 * Revision 1.46 2001/10/08 15:17:41 oes
73 * Re-enabled SSL forwarding
75 * Revision 1.45 2001/10/07 15:42:11 oes
76 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
78 * Moved downgrading of the HTTP version from parse_http_request to
79 * chat(), since we can't decide if it is necessary before we have
80 * determined the actions for the URL. The HTTP command is now
81 * *always* re-built so the repairs need no longer be special-cased.
83 * filter_popups now gets a csp pointer so it can raise the new
84 * CSP_FLAG_MODIFIED flag.
88 * Added configurable size limit for the IOB. If the IOB grows so
89 * large that the next read would exceed the limit, the header
90 * is generated, and the header & unfiltered buffer are flushed
91 * to the client. Chat then continues in non-buffering,
92 * non-filtering body mode.
94 * Revision 1.44 2001/10/02 18:13:57 oes
97 * Revision 1.43 2001/10/02 15:32:13 oes
98 * Moved generation of hdr
100 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
101 * Cleaning up 2 compiler warnings on OS/2.
103 * Revision 1.41 2001/09/16 17:05:14 jongfoster
104 * Removing unused #include showarg.h
106 * Revision 1.40 2001/09/16 15:41:45 jongfoster
107 * Fixing signed/unsigned comparison warning.
109 * Revision 1.39 2001/09/16 13:21:27 jongfoster
110 * Changes to use new list functions.
112 * Revision 1.38 2001/09/16 13:01:46 jongfoster
113 * Removing redundant function call that zeroed zalloc()'d memory.
115 * Revision 1.37 2001/09/10 11:12:24 oes
116 * Deleted unused variable
118 * Revision 1.36 2001/09/10 10:56:15 oes
119 * Silenced compiler warnings
121 * Revision 1.35 2001/07/31 14:44:22 oes
122 * Deleted unused size parameter from filter_popups()
124 * Revision 1.34 2001/07/30 22:08:36 jongfoster
125 * Tidying up #defines:
126 * - All feature #defines are now of the form FEATURE_xxx
127 * - Permanently turned off WIN_GUI_EDIT
128 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
130 * Revision 1.33 2001/07/29 19:32:00 jongfoster
131 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
133 * Revision 1.32 2001/07/29 18:47:05 jongfoster
134 * Adding missing #include "loadcfg.h"
136 * Revision 1.31 2001/07/29 12:17:48 oes
137 * Applied pthread fix by Paul Lieverse
139 * Revision 1.30 2001/07/25 22:57:13 jongfoster
140 * __BEOS__ no longer overrides FEATURE_PTHREAD.
141 * This is because FEATURE_PTHREAD will soon be widely used, so I
142 * want to keep it simple.
144 * Revision 1.29 2001/07/24 12:47:06 oes
145 * Applied BeOS support update by Eugenia
147 * Revision 1.28 2001/07/23 13:26:12 oes
148 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
150 * Revision 1.27 2001/07/19 19:09:47 haroon
151 * - Added code to take care of the situation where while processing the first
152 * server response (which includes the server header), after finding the end
153 * of the headers we were not looking past the end of the headers for
154 * content modification. I enabled it for filter_popups.
155 * Someone else should look to see if other similar operations should be
156 * done to the discarded portion of the buffer.
158 * Note 2001/07/20: No, the other content modification mechanisms will process
159 * the whole iob later anyway. --oes
161 * Revision 1.26 2001/07/18 12:31:36 oes
164 * Revision 1.25 2001/07/15 19:43:49 jongfoster
165 * Supports POSIX threads.
166 * Also removed some unused #includes.
168 * Revision 1.24 2001/07/13 14:00:40 oes
169 * - Generic content modification scheme:
170 * Each feature has its own applicability flag that is set
171 * from csp->action->flags.
172 * Replaced the "filtering" int flag , by a function pointer
173 * "content_filter" to the function that will do the content
174 * modification. If it is != NULL, the document will be buffered
175 * and processed through *content_filter, which must set
176 * csp->content_length and return a modified copy of the body
177 * or return NULL (on failiure).
178 * - Changed csp->is_text to the more generic bitmap csp->content_type
179 * which can currently take the valued CT_TEXT or CT_GIF
181 * - Removed all #ifdef PCRS
183 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
184 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
185 * the `block_acl' call. This prevents a compilation error when the user
186 * does not wish to use the "ACL" feature.
188 * Revision 1.22 2001/06/29 21:45:41 oes
189 * Indentation, CRLF->LF, Tab-> Space
191 * Revision 1.21 2001/06/29 13:29:36 oes
192 * - Cleaned up, improved comments
193 * - Unified all possible interceptors (CGI,
194 * block, trust, fast_redirect) in one
195 * place, with one (CGI) answer generation
196 * mechansim. Much clearer now.
197 * - Removed the GIF image generation, which
198 * is now done in filters.c:block_url()
199 * - Made error conditions like domain lookup
200 * failiure or (various) problems while talking
201 * to the server use cgi.c:error_response()
202 * instead of generating HTML/HTTP in chat() (yuck!)
203 * - Removed logentry from cancelled commit
205 * Revision 1.20 2001/06/09 10:55:28 jongfoster
206 * Changing BUFSIZ ==> BUFFER_SIZE
208 * Revision 1.19 2001/06/07 23:12:52 jongfoster
209 * Replacing function pointer in struct gateway with a directly
210 * called function forwarded_connect().
211 * Replacing struct gateway with struct forward_spec
213 * Revision 1.18 2001/06/03 19:12:16 oes
214 * introduced new cgi handling
216 * Revision 1.17 2001/06/01 20:07:23 jongfoster
217 * Now uses action +image-blocker{} rather than config->tinygif
219 * Revision 1.16 2001/06/01 18:49:17 jongfoster
220 * Replaced "list_share" with "list" - the tiny memory gain was not
221 * worth the extra complexity.
223 * Revision 1.15 2001/05/31 21:24:47 jongfoster
224 * Changed "permission" to "action" throughout.
225 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
226 * Moved vanilla wafer check into chat(), since we must now
227 * decide whether or not to add it based on the URL.
229 * Revision 1.14 2001/05/29 20:14:01 joergs
230 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
233 * Revision 1.13 2001/05/29 09:50:24 jongfoster
234 * Unified blocklist/imagelist/permissionslist.
235 * File format is still under discussion, but the internal changes
238 * Also modified interceptor behaviour:
239 * - We now intercept all URLs beginning with one of the following
240 * prefixes (and *only* these prefixes):
242 * * http://ijbswa.sf.net/config/
243 * * http://ijbswa.sourceforge.net/config/
244 * - New interceptors "home page" - go to http://i.j.b/ to see it.
245 * - Internal changes so that intercepted and fast redirect pages
246 * are not replaced with an image.
247 * - Interceptors now have the option to send a binary page direct
248 * to the client. (i.e. ijb-send-banner uses this)
249 * - Implemented show-url-info interceptor. (Which is why I needed
250 * the above interceptors changes - a typical URL is
251 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
252 * The previous mechanism would not have intercepted that, and
253 * if it had been intercepted then it then it would have replaced
256 * Revision 1.12 2001/05/27 22:17:04 oes
258 * - re_process_buffer no longer writes the modified buffer
259 * to the client, which was very ugly. It now returns the
260 * buffer, which it is then written by chat.
262 * - content_length now adjusts the Content-Length: header
263 * for modified documents rather than crunch()ing it.
264 * (Length info in csp->content_length, which is 0 for
265 * unmodified documents)
267 * - For this to work, sed() is called twice when filtering.
269 * Revision 1.11 2001/05/26 17:27:53 jongfoster
270 * Added support for CLF and fixed LOG_LEVEL_LOG.
271 * Also did CRLF->LF fix of my previous patch.
273 * Revision 1.10 2001/05/26 15:26:15 jongfoster
274 * ACL feature now provides more security by immediately dropping
275 * connections from untrusted hosts.
277 * Revision 1.9 2001/05/26 00:28:36 jongfoster
278 * Automatic reloading of config file.
279 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
280 * Most of the global variables have been moved to a new
281 * struct configuration_spec, accessed through csp->config->globalname
282 * Most of the globals remaining are used by the Win32 GUI.
284 * Revision 1.8 2001/05/25 22:43:18 jongfoster
285 * Fixing minor memory leak and buffer overflow.
287 * Revision 1.7 2001/05/25 22:34:30 jongfoster
290 * Revision 1.6 2001/05/23 00:13:58 joergs
291 * AmigaOS support fixed.
293 * Revision 1.5 2001/05/22 18:46:04 oes
295 * - Enabled filtering banners by size rather than URL
296 * by adding patterns that replace all standard banner
297 * sizes with the "Junkbuster" gif to the re_filterfile
299 * - Enabled filtering WebBugs by providing a pattern
300 * which kills all 1x1 images
302 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
303 * which is selected by the (nonstandard and therefore
304 * capital) letter 'U' in the option string.
305 * It causes the quantifiers to be ungreedy by default.
306 * Appending a ? turns back to greedy (!).
308 * - Added a new interceptor ijb-send-banner, which
309 * sends back the "Junkbuster" gif. Without imagelist or
310 * MSIE detection support, or if tinygif = 1, or the
311 * URL isn't recognized as an imageurl, a lame HTML
312 * explanation is sent instead.
314 * - Added new feature, which permits blocking remote
315 * script redirects and firing back a local redirect
317 * The feature is conditionally compiled, i.e. it
318 * can be disabled with --disable-fast-redirects,
319 * plus it must be activated by a "fast-redirects"
320 * line in the config file, has its own log level
321 * and of course wants to be displayed by show-proxy-args
322 * Note: Boy, all the #ifdefs in 1001 locations and
323 * all the fumbling with configure.in and acconfig.h
324 * were *way* more work than the feature itself :-(
326 * - Because a generic redirect template was needed for
327 * this, tinygif = 3 now uses the same.
329 * - Moved GIFs, and other static HTTP response templates
334 * - Removed some >400 CRs again (Jon, you really worked
337 * Revision 1.4 2001/05/21 19:34:01 jongfoster
338 * Made failure to bind() a fatal error.
340 * Revision 1.3 2001/05/20 01:21:20 jongfoster
341 * Version 2.9.4 checkin.
342 * - Merged popupfile and cookiefile, and added control over PCRS
343 * filtering, in new "permissionsfile".
344 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
345 * file error you now get a message box (in the Win32 GUI) rather
346 * than the program exiting with no explanation.
347 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
349 * - Removed tabs from "config"
350 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
351 * - Bumped up version number.
353 * Revision 1.2 2001/05/17 22:34:44 oes
354 * - Added hint on GIF char array generation to jcc.c
355 * - Cleaned CRLF's from the sources and related files
356 * - Repaired logging for REF and FRC
358 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
359 * Initial import of version 2.9.3 source tree
362 *********************************************************************/
368 #include <sys/types.h>
375 #ifdef FEATURE_PTHREAD
377 #endif /* def FEATURE_PTHREAD */
380 # ifndef FEATURE_PTHREAD
381 # include <windows.h>
382 # include <process.h>
383 # endif /* ndef FEATURE_PTHREAD */
386 # ifndef _WIN_CONSOLE
388 # endif /* ndef _WIN_CONSOLE */
390 #else /* ifndef _WIN32 */
392 # if !defined (__OS2__)
394 # include <sys/wait.h>
395 # endif /* ndef __OS2__ */
396 # include <sys/time.h>
397 # include <sys/stat.h>
398 # include <sys/ioctl.h>
401 #include <sys/termios.h>
407 # include <socket.h> /* BeOS has select() for sockets only. */
408 # include <OS.h> /* declarations for threads and stuff. */
411 # if defined(__EMX__) || defined(__OS2__)
412 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
417 #define bzero(B,N) memset(B,0x00,n)
436 #include "killpopup.h"
437 #include "miscutil.h"
439 #include "jbsockets.h"
445 const char jcc_h_rcs[] = JCC_H_VERSION;
446 const char project_h_rcs[] = PROJECT_H_VERSION;
448 struct client_state clients[1];
449 struct file_list files[1];
451 #ifdef FEATURE_STATISTICS
452 int urls_read = 0; /* total nr of urls read inc rejected */
453 int urls_rejected = 0; /* total nr of urls rejected */
454 #endif /* def FEATURE_STATISTICS */
457 static void listen_loop(void);
458 static void chat(struct client_state *csp);
460 void serve(struct client_state *csp);
461 #else /* ifndef AMIGA */
462 static void serve(struct client_state *csp);
463 #endif /* def AMIGA */
466 static int32 server_thread(void *data);
467 #endif /* def __BEOS__ */
470 #define sleep(N) Sleep(((N) * 1000))
474 #define sleep(N) DosSleep(((N) * 100))
479 #endif /* defined unix */
481 /* The vanilla wafer. */
482 static const char VANILLA_WAFER[] =
483 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
484 "Do_not_send_me_any_copyrighted_information_other_than_the_"
485 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
486 "In_particular_do_not_send_me_any_cookies_that_"
487 "are_subject_to_a_claim_of_copyright_by_anybody._"
488 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
489 "(copyright_or_otherwise)_applying_to_any_cookie._";
492 /*********************************************************************
496 * Description : Once a connection to the client has been accepted,
497 * this function is called (via serve()) to handle the
498 * main business of the communication. When this
499 * function returns, the caller must close the client
503 * 1 : csp = Current client state (buffers, headers, etc...)
505 * Returns : On success, the number of bytes written are returned (zero
506 * indicates nothing was written). On error, -1 is returned,
507 * and errno is set appropriately. If count is zero and the
508 * file descriptor refers to a regular file, 0 will be
509 * returned without causing any other effect. For a special
510 * file, the results are not portable.
512 *********************************************************************/
513 static void chat(struct client_state *csp)
516 * This next lines are a little ugly, but they simplifies the if statements
517 * below. Basically if TOGGLE, then we want the if to test if the
518 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
519 * then we want the if to test for CSP_FLAG_FORCED , else we don't
521 #ifdef FEATURE_TOGGLE
522 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
523 #else /* ifndef FEATURE_TOGGLE */
524 # define IS_TOGGLED_ON_AND
525 #endif /* ndef FEATURE_TOGGLE */
526 #ifdef FEATURE_FORCE_LOAD
527 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
528 #else /* ifndef FEATURE_FORCE_LOAD */
529 # define IS_NOT_FORCED_AND
530 #endif /* def FEATURE_FORCE_LOAD */
532 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
534 char buf[BUFFER_SIZE];
537 int n, maxfd, server_body;
538 int ms_iis5_hack = 0;
540 const struct forward_spec * fwd;
541 struct http_request *http;
542 #ifdef FEATURE_KILL_POPUPS
543 int block_popups; /* bool, 1==will block popups */
544 int block_popups_now = 0; /* bool, 1==currently blocking popups */
545 #endif /* def FEATURE_KILL_POPUPS */
547 int pcrs_filter; /* bool, 1==will filter through pcrs */
548 int gif_deanimate; /* bool, 1==will deanimate gifs */
550 /* Function that does the content filtering for the current request */
551 char *(*content_filter)() = NULL;
553 /* Skeleton for HTTP response, if we should intercept the request */
554 struct http_response *rsp;
559 * Read the client's request. Note that since we're not using select() we
560 * could get blocked here if a client connected, then didn't say anything!
565 n = read_socket(csp->cfd, buf, sizeof(buf));
567 if (n <= 0) break; /* error! */
569 add_to_iob(csp, buf, n);
571 req = get_header(csp);
575 break; /* no HTTP request! */
580 continue; /* more to come! */
583 #ifdef FEATURE_FORCE_LOAD
584 /* If this request contains the FORCE_PREFIX,
585 * better get rid of it now and set the force flag --oes
588 if (strstr(req, FORCE_PREFIX))
590 strclean(req, FORCE_PREFIX);
591 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
592 csp->flags |= CSP_FLAG_FORCED;
595 #endif /* def FEATURE_FORCE_LOAD */
597 parse_http_request(req, http, csp);
602 if (http->cmd == NULL)
604 strcpy(buf, CHEADER);
605 write_socket(csp->cfd, buf, strlen(buf));
607 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
612 /* decide how to route the HTTP request */
614 if ((fwd = forward_url(http, csp)) == NULL)
616 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
617 /* Never get here - LOG_LEVEL_FATAL causes program exit */
620 /* build the http request to send to the server
621 * we have to do one of the following:
623 * create = use the original HTTP request to create a new
624 * HTTP request that has either the path component
625 * without the http://domainspec (w/path) or the
626 * full orininal URL (w/url)
627 * Note that the path and/or the HTTP version may
628 * have been altered by now.
630 * connect = Open a socket to the host:port of the server
631 * and short-circuit server and client socket.
633 * pass = Pass the request unchanged if forwarding a CONNECT
634 * request to a parent proxy. Note that we'll be sending
635 * the CFAIL message ourselves if connecting to the parent
636 * fails, but we won't send a CSUCCEED message if it works,
637 * since that would result in a double message (ours and the
638 * parent's). After sending the request to the parent, we simply
644 * +--------+--------+
646 * 0 | create | connect|
648 * Forwarding +--------+--------+
650 * 1 | create | pass |
652 * +--------+--------+
657 * Determine the actions for this URL
659 #ifdef FEATURE_TOGGLE
660 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
662 /* Most compatible set of actions (i.e. none) */
663 init_current_action(csp->action);
666 #endif /* ndef FEATURE_TOGGLE */
668 url_actions(http, csp);
673 * Check if a CONNECT request is allowable:
674 * In the absence of a +limit-connect action, allow only port 443.
675 * If there is an action, allow whatever matches the specificaton.
679 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
680 || (csp->action->flags & ACTION_LIMIT_CONNECT
681 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
683 strcpy(buf, CFORBIDDEN);
684 write_socket(csp->cfd, buf, strlen(buf));
686 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
687 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
695 * Downgrade http version from 1.1 to 1.0 if +downgrade
698 if (!strcmpic(http->ver, "HTTP/1.1") && csp->action->flags & ACTION_DOWNGRADE)
701 http->ver = strdup("HTTP/1.0");
705 * (Re)build the HTTP request for non-SSL requests.
706 * If forwarding, use the whole URL, else, use only the path.
712 http->cmd = strsav(http->cmd, http->gpc);
713 http->cmd = strsav(http->cmd, " ");
715 if (fwd->forward_host)
717 http->cmd = strsav(http->cmd, http->url);
721 http->cmd = strsav(http->cmd, http->path);
724 http->cmd = strsav(http->cmd, " ");
725 http->cmd = strsav(http->cmd, http->ver);
728 enlist(csp->headers, http->cmd);
731 #ifdef FEATURE_COOKIE_JAR
733 * If we're logging cookies in a cookie jar, and the user has not
734 * supplied any wafers, and the user has not told us to suppress the
735 * vanilla wafer, then send the vanilla wafer.
737 if ((csp->config->jarfile != NULL)
738 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
739 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
741 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
743 #endif /* def FEATURE_COOKIE_JAR */
746 #ifdef FEATURE_KILL_POPUPS
747 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
748 #endif /* def FEATURE_KILL_POPUPS */
750 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
751 ((csp->action->flags & ACTION_FILTER) != 0);
753 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
755 /* grab the rest of the client's headers */
759 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
761 n = read_socket(csp->cfd, buf, sizeof(buf));
764 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
767 add_to_iob(csp, buf, n);
771 if (p == NULL) break;
773 enlist(csp->headers, p);
777 * We have a request. Now, check to see if we need to
778 * intercept it, i.e. If ..
782 /* a CGI call was detected and answered */
783 (NULL != (rsp = dispatch_cgi(csp)))
785 /* or we are enabled and... */
788 /* ..the request was blocked */
789 ( NULL != (rsp = block_url(csp)))
793 || ( NULL != (rsp = trust_url(csp)))
794 #endif /* def FEATURE_TRUST */
796 /* ..or a fast redirect kicked in */
797 #ifdef FEATURE_FAST_REDIRECTS
798 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
799 (NULL != (rsp = redirect_url(csp))))
800 #endif /* def FEATURE_FAST_REDIRECTS */
804 /* Write the answer to the client */
805 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
806 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
808 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
811 #ifdef FEATURE_STATISTICS
812 /* Count as a rejected request */
813 csp->flags |= CSP_FLAG_REJECTED;
814 #endif /* def FEATURE_STATISTICS */
816 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
817 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
818 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
820 /* Clean up and return */
821 free_http_response(rsp);
825 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
827 if (fwd->forward_host)
829 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
830 fwd->forward_host, fwd->forward_port, http->hostport);
834 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
837 /* here we connect to the server, gateway, or the forwarder */
839 csp->sfd = forwarded_connect(fwd, http, csp);
843 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
848 rsp = error_response(csp, "no-such-domain", errno);
850 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
851 csp->ip_addr_str, http->cmd);
855 rsp = error_response(csp, "connect-failed", errno);
857 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
858 csp->ip_addr_str, http->cmd);
861 /* Write the answer to the client */
864 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
865 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
867 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
871 free_http_response(rsp);
875 log_error(LOG_LEVEL_CONNECT, "OK");
877 hdr = sed(client_patterns, add_client_headers, csp);
878 list_remove_all(csp->headers);
880 if (fwd->forward_host || (http->ssl == 0))
882 /* write the client's (modified) header to the server
883 * (along with anything else that may be in the buffer)
888 if ((write_socket(csp->sfd, hdr, n) != n)
889 || (flush_socket(csp->sfd, csp ) < 0))
891 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
894 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
895 csp->ip_addr_str, http->cmd);
897 rsp = error_response(csp, "connect-failed", errno);
901 if ((write_socket(csp->cfd, rsp->head, n) != n)
902 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
904 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
908 free_http_response(rsp);
916 * We're running an SSL tunnel and we're not forwarding,
917 * so just send the "connect succeeded" message to the
918 * client, flush the rest, and get out of the way.
920 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
921 csp->ip_addr_str, http->cmd);
923 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
931 /* we're finished with the client's header */
934 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
936 /* pass data between the client and server
937 * until one or the other shuts down the connection.
946 FD_SET(csp->cfd, &rfds);
947 FD_SET(csp->sfd, &rfds);
949 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
953 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
957 /* this is the body of the browser's request
958 * just read it and write it.
961 if (FD_ISSET(csp->cfd, &rfds))
963 n = read_socket(csp->cfd, buf, sizeof(buf));
967 break; /* "game over, man" */
970 if (write_socket(csp->sfd, buf, n) != n)
972 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
979 * The server wants to talk. It could be the header or the body.
980 * If `hdr' is null, then it's the header otherwise it's the body.
981 * FIXME: Does `hdr' really mean `host'? No.
985 if (FD_ISSET(csp->sfd, &rfds))
988 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
992 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
994 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
995 csp->ip_addr_str, http->cmd);
997 rsp = error_response(csp, "connect-failed", errno);
1001 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
1002 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
1004 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1008 free_http_response(rsp);
1012 /* Add a trailing zero. This lets filter_popups
1013 * use string operations.
1017 #ifdef FEATURE_KILL_POPUPS
1018 /* Filter the popups on this read. */
1019 if (block_popups_now)
1021 filter_popups(buf, csp);
1023 #endif /* def FEATURE_KILL_POPUPS */
1025 /* Normally, this would indicate that we've read
1026 * as much as the server has sent us and we can
1027 * close the client connection. However, Microsoft
1028 * in its wisdom has released IIS/5 with a bug that
1029 * prevents it from sending the trailing \r\n in
1030 * a 302 redirect header (and possibly other headers).
1031 * To work around this if we've haven't parsed
1032 * a full header we'll append a trailing \r\n
1033 * and see if this now generates a valid one.
1035 * This hack shouldn't have any impacts. If we've
1036 * already transmitted the header or if this is a
1037 * SSL connection, then we won't bother with this
1038 * hack. So we only work on partially received
1039 * headers. If we append a \r\n and this still
1040 * doesn't generate a valid header, then we won't
1041 * transmit anything to the client.
1046 if (server_body || http->ssl)
1049 * If we have been buffering up the document,
1050 * now is the time to apply content modification
1051 * and send the result to the client.
1056 * If the content filter fails, use the original
1057 * buffer and length.
1058 * (see p != NULL ? p : csp->iob->cur below)
1060 if (NULL == (p = (*content_filter)(csp)))
1062 csp->content_length = csp->iob->eod - csp->iob->cur;
1065 hdr = sed(server_patterns, add_server_headers, csp);
1068 if ((write_socket(csp->cfd, hdr, n) != n)
1069 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != (int)csp->content_length))
1071 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1081 break; /* "game over, man" */
1085 * This is NOT the body, so
1086 * Let's pretend the server just sent us a blank line.
1088 n = sprintf(buf, "\r\n");
1091 * Now, let the normal header parsing algorithm below do its
1092 * job. If it fails, we'll exit instead of continuing.
1099 * If this is an SSL connection or we're in the body
1100 * of the server document, just write it to the client,
1101 * unless we need to buffer the body for later content-filtering
1104 if (server_body || http->ssl)
1108 add_to_iob(csp, buf, n);
1111 * If the buffer limit will be reached on the next read,
1112 * switch to non-filtering mode, i.e. make & write the
1113 * header, flush the socket and get out of the way.
1115 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1117 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1119 hdr = sed(server_patterns, add_server_headers, csp);
1123 if (((write_socket(csp->cfd, hdr, n) != n)
1124 || (n = flush_socket(csp->cfd, csp) < 0)))
1126 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1135 content_filter = NULL;
1142 if (write_socket(csp->cfd, buf, n) != n)
1144 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1153 /* we're still looking for the end of the
1154 * server's header ... (does that make header
1155 * parsing an "out of body experience" ?
1158 /* buffer up the data we just read */
1159 add_to_iob(csp, buf, n);
1161 /* get header lines from the iob */
1163 while ((p = get_header(csp)))
1167 /* see following note */
1170 enlist(csp->headers, p);
1174 /* NOTE: there are no "empty" headers so
1175 * if the pointer `p' is not NULL we must
1176 * assume that we reached the end of the
1177 * buffer before we hit the end of the header.
1184 /* Well, we tried our MS IIS/5
1185 * hack and it didn't work.
1186 * The header is incomplete
1187 * and there isn't anything
1188 * we can do about it.
1194 /* Since we have to wait for
1195 * more from the server before
1196 * we can parse the headers
1197 * we just continue here.
1203 /* we have now received the entire header.
1204 * filter it and send the result to the client
1207 hdr = sed(server_patterns, add_server_headers, csp);
1210 /* write the server's (modified) header to
1211 * the client (along with anything else that
1212 * may be in the buffer)
1215 #ifdef FEATURE_KILL_POPUPS
1216 /* Start blocking popups if appropriate. */
1218 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1219 !http->ssl && /* We talk plaintext */
1220 block_popups) /* Policy allows */
1222 block_popups_now = 1;
1224 * Filter the part of the body that came in the same read
1225 * as the last headers:
1227 filter_popups(csp->iob->cur, csp);
1230 #endif /* def FEATURE_KILL_POPUPS */
1232 /* Buffer and pcrs filter this if appropriate. */
1234 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1235 !http->ssl && /* We talk plaintext */
1236 pcrs_filter) /* Policy allows */
1238 content_filter = pcrs_filter_response;
1241 /* Buffer and gif_deanimate this if appropriate. */
1243 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1244 !http->ssl && /* We talk plaintext */
1245 gif_deanimate) /* Policy allows */
1247 content_filter = gif_deanimate_response;
1252 * Only write if we're not buffering for content modification
1254 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1255 || (n = flush_socket(csp->cfd, csp) < 0)))
1257 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1259 /* the write failed, so don't bother
1260 * mentioning it to the client...
1261 * it probably can't hear us anyway.
1267 if(!content_filter) byte_count += n;
1269 /* we're finished with the server's header */
1274 /* If this was a MS IIS/5 hack then it means
1275 * the server has already closed the
1276 * connection. Nothing more to read. Time
1287 return; /* huh? we should never get here */
1290 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1291 csp->ip_addr_str, http->cmd, byte_count);
1295 /*********************************************************************
1299 * Description : This is little more than chat. We only "serve" to
1300 * to close any socket that chat may have opened.
1303 * 1 : csp = Current client state (buffers, headers, etc...)
1307 *********************************************************************/
1309 void serve(struct client_state *csp)
1310 #else /* ifndef AMIGA */
1311 static void serve(struct client_state *csp)
1312 #endif /* def AMIGA */
1315 close_socket(csp->cfd);
1319 close_socket(csp->sfd);
1322 csp->flags &= ~CSP_FLAG_ACTIVE;
1328 /*********************************************************************
1330 * Function : server_thread
1332 * Description : We only exist to call `serve' in a threaded environment.
1335 * 1 : data = Current client state (buffers, headers, etc...)
1337 * Returns : Always 0.
1339 *********************************************************************/
1340 static int32 server_thread(void *data)
1342 serve((struct client_state *) data);
1349 /*********************************************************************
1353 * Description : Load the config file and start the listen loop.
1354 * This function is a lot more *sane* with the `load_config'
1355 * and `listen_loop' functions; although it stills does
1356 * a *little* too much for my taste.
1359 * 1 : argc = Number of parameters (including $0).
1360 * 2 : argv = Array of (char *)'s to the parameters.
1362 * Returns : 1 if : can't open config file, unrecognized directive,
1363 * stats requested in multi-thread mode, can't open the
1364 * log file, can't open the jar file, listen port is invalid,
1365 * any load fails, and can't bind port.
1367 * Else main never returns, the process must be signaled
1368 * to terminate execution. Or, on Windows, use the
1369 * "File", "Exit" menu option.
1371 *********************************************************************/
1373 int real_main(int argc, const char *argv[])
1375 int main(int argc, const char *argv[])
1382 "AmiTCP:db/junkbuster/config"
1383 #elif !defined(_WIN32)
1390 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1391 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1393 printf("JunkBuster proxy version " VERSION ".\n\n"
1394 "Usage: %s [configfile]\n\n"
1395 "See " HOME_PAGE_URL " for details.\n"
1396 "This program is distributed under the GNU GPL, version 2 or later.\n",
1400 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1402 printf(VERSION "\n");
1406 if ((argc >= 2) && (strcmp(argv[1], "-d")==0))
1410 fprintf(stderr,"debugging enabled..\n");
1413 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1418 if (argc > argc_pos )
1420 configfile = argv[argc_pos];
1424 if ( *configfile != '/' )
1428 DBG(1, ("configfile before '%s'\n",configfile) );
1430 /* make config-filename absolute here */
1431 if ( !(basedir = getcwd( NULL, 1024 )))
1433 perror("get working dir failed");
1436 DBG(1, ("working dir '%s'\n",basedir) );
1437 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1439 perror("malloc failed");
1442 strcpy( abs_file, basedir );
1443 strcat( abs_file, "/" );
1444 strcat( abs_file, configfile );
1445 configfile = abs_file;
1446 DBG(1, ("configfile after '%s'\n",configfile) );
1448 #endif /* defined unix */
1455 #elif defined(_WIN32)
1460 #if !defined(_WIN32) && !defined(__OS2__)
1461 signal(SIGPIPE, SIG_IGN);
1462 signal(SIGCHLD, SIG_IGN);
1464 #else /* ifdef _WIN32 */
1465 # ifdef _WIN_CONSOLE
1467 * We *are* in a windows console app.
1468 * Print a verbose messages about FAQ's and such
1470 printf(win32_blurb);
1471 # endif /* def _WIN_CONSOLE */
1472 #endif /* def _WIN32 */
1475 /* Initialize the CGI subsystem */
1476 cgi_init_error_messages();
1484 ** we make us a real daemon
1490 if ( pid < 0 ) /* error */
1495 else if ( pid != 0 ) /* parent */
1500 ** must check for errors
1501 ** child died due to missing files aso
1504 wpid = waitpid( pid, &status, WNOHANG );
1517 fd = open("/dev/tty", O_RDONLY);
1520 /* no error check here */
1521 ioctl( fd, TIOCNOTTY,0 );
1524 /* should close stderr (fd 2) here too, but the test for existence
1525 ** and load config file is done in listen_loop() and puts
1526 ** some messages on stderr there.
1530 close( 0 ); close( 1 );
1532 close( 0 ); close( 1 );
1537 #endif /* defined unix */
1539 DBG(1, ("call listen_loop() \n") );
1548 /*********************************************************************
1550 * Function : listen_loop
1552 * Description : bind the listen port and enter a "FOREVER" listening loop.
1558 *********************************************************************/
1559 static void listen_loop(void)
1561 struct client_state *csp = NULL;
1563 struct configuration_spec * config;
1565 config = load_config();
1567 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1568 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1570 bfd = bind_port(config->haddr, config->hport);
1574 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1575 "- There may be another junkbuster or some other "
1576 "proxy running on port %d",
1577 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1578 config->hport, config->hport
1580 /* shouldn't get here */
1584 config->need_bind = 0;
1588 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1589 while (waitpid(-1, NULL, WNOHANG) > 0)
1591 /* zombie children */
1593 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1596 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1598 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1602 csp->flags |= CSP_FLAG_ACTIVE;
1605 csp->config = config = load_config();
1607 if ( config->need_bind )
1610 * Since we were listening to the "old port", we will not see
1611 * a "listen" param change until the next IJB request. So, at
1612 * least 1 more request must be made for us to find the new
1613 * setting. I am simply closing the old socket and binding the
1616 * Which-ever is correct, we will serve 1 more page via the
1617 * old settings. This should probably be a "show-proxy-args"
1618 * request. This should not be a so common of an operation
1619 * that this will hurt people's feelings.
1624 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1625 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1626 bfd = bind_port(config->haddr, config->hport);
1630 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1631 "- There may be another junkbuster or some other "
1632 "proxy running on port %d",
1633 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1634 config->hport, config->hport
1636 /* shouldn't get here */
1640 config->need_bind = 0;
1643 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1645 if (!accept_connection(csp, bfd))
1647 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1660 log_error(LOG_LEVEL_CONNECT, "OK");
1663 #ifdef FEATURE_TOGGLE
1666 csp->flags |= CSP_FLAG_TOGGLED_ON;
1668 #endif /* def FEATURE_TOGGLE */
1670 if (run_loader(csp))
1672 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1673 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1677 if (block_acl(NULL,csp))
1679 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1680 close_socket(csp->cfd);
1684 #endif /* def FEATURE_ACL */
1686 /* add it to the list of clients */
1687 csp->next = clients->next;
1688 clients->next = csp;
1690 if (config->multi_threaded)
1694 /* this is a switch () statment in the C preprocessor - ugh */
1695 #undef SELECTED_ONE_OPTION
1697 /* Use Pthreads in preference to native code */
1698 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1699 #define SELECTED_ONE_OPTION
1701 pthread_t the_thread;
1702 pthread_attr_t attrs;
1704 pthread_attr_init(&attrs);
1705 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1706 child_id = (pthread_create(&the_thread, &attrs,
1707 (void*)serve, csp) ? -1 : 0);
1708 pthread_attr_destroy(&attrs);
1712 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1713 #define SELECTED_ONE_OPTION
1714 child_id = _beginthread(
1720 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1721 #define SELECTED_ONE_OPTION
1722 child_id = _beginthread(
1729 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1730 #define SELECTED_ONE_OPTION
1732 thread_id tid = spawn_thread
1733 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1735 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1737 child_id = (int) tid;
1746 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1747 #define SELECTED_ONE_OPTION
1748 csp->cfd = ReleaseSocket(csp->cfd, -1);
1749 if((child_id = (int)CreateNewProcTags(
1750 NP_Entry, (ULONG)server_thread,
1751 NP_Output, Output(),
1752 NP_CloseOutput, FALSE,
1753 NP_Name, (ULONG)"junkbuster child",
1754 NP_StackSize, 200*1024,
1758 ((struct Task *)child_id)->tc_UserData = csp;
1759 Signal((struct Task *)child_id, SIGF_SINGLE);
1764 #if !defined(SELECTED_ONE_OPTION)
1767 /* This block is only needed when using fork().
1768 * When using threads, the server thread was
1769 * created and run by the call to _beginthread().
1771 if (child_id == 0) /* child */
1777 else if (child_id > 0) /* parent */
1779 /* in a fork()'d environment, the parent's
1780 * copy of the client socket and the CSP
1784 #if !defined(_WIN32) && defined(__CYGWIN__)
1786 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1787 close_socket(csp->cfd);
1788 csp->flags &= ~CSP_FLAG_ACTIVE;
1792 #undef SELECTED_ONE_OPTION
1793 /* end of cpp switch () */
1795 if (child_id < 0) /* failed */
1797 char buf[BUFFER_SIZE];
1799 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1801 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1803 write_socket(csp->cfd, buf, strlen(buf));
1804 close_socket(csp->cfd);
1805 csp->flags &= ~CSP_FLAG_ACTIVE;