1 const char jcc_rcs[] = "$Id: jcc.c,v 1.30 2001/07/25 22:57:13 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.30 2001/07/25 22:57:13 jongfoster
37 * __BEOS__ no longer overrides FEATURE_PTHREAD.
38 * This is because FEATURE_PTHREAD will soon be widely used, so I
39 * want to keep it simple.
41 * Revision 1.29 2001/07/24 12:47:06 oes
42 * Applied BeOS support update by Eugenia
44 * Revision 1.28 2001/07/23 13:26:12 oes
45 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
47 * Revision 1.27 2001/07/19 19:09:47 haroon
48 * - Added code to take care of the situation where while processing the first
49 * server response (which includes the server header), after finding the end
50 * of the headers we were not looking past the end of the headers for
51 * content modification. I enabled it for filter_popups.
52 * Someone else should look to see if other similar operations should be
53 * done to the discarded portion of the buffer.
55 * Note 2001/07/20: No, the other content modification mechanisms will process
56 * the whole iob later anyway. --oes
58 * Revision 1.26 2001/07/18 12:31:36 oes
61 * Revision 1.25 2001/07/15 19:43:49 jongfoster
62 * Supports POSIX threads.
63 * Also removed some unused #includes.
65 * Revision 1.24 2001/07/13 14:00:40 oes
66 * - Generic content modification scheme:
67 * Each feature has its own applicability flag that is set
68 * from csp->action->flags.
69 * Replaced the "filtering" int flag , by a function pointer
70 * "content_filter" to the function that will do the content
71 * modification. If it is != NULL, the document will be buffered
72 * and processed through *content_filter, which must set
73 * csp->content_length and return a modified copy of the body
74 * or return NULL (on failiure).
75 * - Changed csp->is_text to the more generic bitmap csp->content_type
76 * which can currently take the valued CT_TEXT or CT_GIF
78 * - Removed all #ifdef PCRS
80 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
81 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
82 * the `block_acl' call. This prevents a compilation error when the user
83 * does not wish to use the "ACL" feature.
85 * Revision 1.22 2001/06/29 21:45:41 oes
86 * Indentation, CRLF->LF, Tab-> Space
88 * Revision 1.21 2001/06/29 13:29:36 oes
89 * - Cleaned up, improved comments
90 * - Unified all possible interceptors (CGI,
91 * block, trust, fast_redirect) in one
92 * place, with one (CGI) answer generation
93 * mechansim. Much clearer now.
94 * - Removed the GIF image generation, which
95 * is now done in filters.c:block_url()
96 * - Made error conditions like domain lookup
97 * failiure or (various) problems while talking
98 * to the server use cgi.c:error_response()
99 * instead of generating HTML/HTTP in chat() (yuck!)
100 * - Removed logentry from cancelled commit
102 * Revision 1.20 2001/06/09 10:55:28 jongfoster
103 * Changing BUFSIZ ==> BUFFER_SIZE
105 * Revision 1.19 2001/06/07 23:12:52 jongfoster
106 * Replacing function pointer in struct gateway with a directly
107 * called function forwarded_connect().
108 * Replacing struct gateway with struct forward_spec
110 * Revision 1.18 2001/06/03 19:12:16 oes
111 * introduced new cgi handling
113 * Revision 1.17 2001/06/01 20:07:23 jongfoster
114 * Now uses action +image-blocker{} rather than config->tinygif
116 * Revision 1.16 2001/06/01 18:49:17 jongfoster
117 * Replaced "list_share" with "list" - the tiny memory gain was not
118 * worth the extra complexity.
120 * Revision 1.15 2001/05/31 21:24:47 jongfoster
121 * Changed "permission" to "action" throughout.
122 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
123 * Moved vanilla wafer check into chat(), since we must now
124 * decide whether or not to add it based on the URL.
126 * Revision 1.14 2001/05/29 20:14:01 joergs
127 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
130 * Revision 1.13 2001/05/29 09:50:24 jongfoster
131 * Unified blocklist/imagelist/permissionslist.
132 * File format is still under discussion, but the internal changes
135 * Also modified interceptor behaviour:
136 * - We now intercept all URLs beginning with one of the following
137 * prefixes (and *only* these prefixes):
139 * * http://ijbswa.sf.net/config/
140 * * http://ijbswa.sourceforge.net/config/
141 * - New interceptors "home page" - go to http://i.j.b/ to see it.
142 * - Internal changes so that intercepted and fast redirect pages
143 * are not replaced with an image.
144 * - Interceptors now have the option to send a binary page direct
145 * to the client. (i.e. ijb-send-banner uses this)
146 * - Implemented show-url-info interceptor. (Which is why I needed
147 * the above interceptors changes - a typical URL is
148 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
149 * The previous mechanism would not have intercepted that, and
150 * if it had been intercepted then it then it would have replaced
153 * Revision 1.12 2001/05/27 22:17:04 oes
155 * - re_process_buffer no longer writes the modified buffer
156 * to the client, which was very ugly. It now returns the
157 * buffer, which it is then written by chat.
159 * - content_length now adjusts the Content-Length: header
160 * for modified documents rather than crunch()ing it.
161 * (Length info in csp->content_length, which is 0 for
162 * unmodified documents)
164 * - For this to work, sed() is called twice when filtering.
166 * Revision 1.11 2001/05/26 17:27:53 jongfoster
167 * Added support for CLF and fixed LOG_LEVEL_LOG.
168 * Also did CRLF->LF fix of my previous patch.
170 * Revision 1.10 2001/05/26 15:26:15 jongfoster
171 * ACL feature now provides more security by immediately dropping
172 * connections from untrusted hosts.
174 * Revision 1.9 2001/05/26 00:28:36 jongfoster
175 * Automatic reloading of config file.
176 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
177 * Most of the global variables have been moved to a new
178 * struct configuration_spec, accessed through csp->config->globalname
179 * Most of the globals remaining are used by the Win32 GUI.
181 * Revision 1.8 2001/05/25 22:43:18 jongfoster
182 * Fixing minor memory leak and buffer overflow.
184 * Revision 1.7 2001/05/25 22:34:30 jongfoster
187 * Revision 1.6 2001/05/23 00:13:58 joergs
188 * AmigaOS support fixed.
190 * Revision 1.5 2001/05/22 18:46:04 oes
192 * - Enabled filtering banners by size rather than URL
193 * by adding patterns that replace all standard banner
194 * sizes with the "Junkbuster" gif to the re_filterfile
196 * - Enabled filtering WebBugs by providing a pattern
197 * which kills all 1x1 images
199 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
200 * which is selected by the (nonstandard and therefore
201 * capital) letter 'U' in the option string.
202 * It causes the quantifiers to be ungreedy by default.
203 * Appending a ? turns back to greedy (!).
205 * - Added a new interceptor ijb-send-banner, which
206 * sends back the "Junkbuster" gif. Without imagelist or
207 * MSIE detection support, or if tinygif = 1, or the
208 * URL isn't recognized as an imageurl, a lame HTML
209 * explanation is sent instead.
211 * - Added new feature, which permits blocking remote
212 * script redirects and firing back a local redirect
214 * The feature is conditionally compiled, i.e. it
215 * can be disabled with --disable-fast-redirects,
216 * plus it must be activated by a "fast-redirects"
217 * line in the config file, has its own log level
218 * and of course wants to be displayed by show-proxy-args
219 * Note: Boy, all the #ifdefs in 1001 locations and
220 * all the fumbling with configure.in and acconfig.h
221 * were *way* more work than the feature itself :-(
223 * - Because a generic redirect template was needed for
224 * this, tinygif = 3 now uses the same.
226 * - Moved GIFs, and other static HTTP response templates
231 * - Removed some >400 CRs again (Jon, you really worked
234 * Revision 1.4 2001/05/21 19:34:01 jongfoster
235 * Made failure to bind() a fatal error.
237 * Revision 1.3 2001/05/20 01:21:20 jongfoster
238 * Version 2.9.4 checkin.
239 * - Merged popupfile and cookiefile, and added control over PCRS
240 * filtering, in new "permissionsfile".
241 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
242 * file error you now get a message box (in the Win32 GUI) rather
243 * than the program exiting with no explanation.
244 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
246 * - Removed tabs from "config"
247 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
248 * - Bumped up version number.
250 * Revision 1.2 2001/05/17 22:34:44 oes
251 * - Added hint on GIF char array generation to jcc.c
252 * - Cleaned CRLF's from the sources and related files
253 * - Repaired logging for REF and FRC
255 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
256 * Initial import of version 2.9.3 source tree
259 *********************************************************************/
265 #include <sys/types.h>
272 #ifdef FEATURE_PTHREAD
274 #endif /* def FEATURE_PTHREAD */
277 # ifndef FEATURE_PTHREAD
278 # include <windows.h>
279 # include <process.h>
280 # endif /* ndef FEATURE_PTHREAD */
283 # ifndef _WIN_CONSOLE
285 # endif /* ndef _WIN_CONSOLE */
287 #else /* ifndef _WIN32 */
290 # include <sys/time.h>
291 # include <sys/wait.h>
292 # include <sys/stat.h>
296 # include <socket.h> /* BeOS has select() for sockets only. */
297 # include <OS.h> /* declarations for threads and stuff. */
311 #include "showargs.h"
313 #include "killpopup.h"
314 #include "miscutil.h"
316 #include "jbsockets.h"
321 const char jcc_h_rcs[] = JCC_H_VERSION;
322 const char project_h_rcs[] = PROJECT_H_VERSION;
324 struct client_state clients[1];
325 struct file_list files[1];
328 int urls_read = 0; /* total nr of urls read inc rejected */
329 int urls_rejected = 0; /* total nr of urls rejected */
330 #endif /* def STATISTICS */
333 static void listen_loop(void);
334 static void chat(struct client_state *csp);
336 void serve(struct client_state *csp);
337 #else /* ifndef AMIGA */
338 static void serve(struct client_state *csp);
339 #endif /* def AMIGA */
342 static int32 server_thread(void *data);
343 #endif /* def __BEOS__ */
346 #define sleep(N) Sleep(((N) * 1000))
350 /* The vanilla wafer. */
351 static const char VANILLA_WAFER[] =
352 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
353 "Do_not_send_me_any_copyrighted_information_other_than_the_"
354 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
355 "In_particular_do_not_send_me_any_cookies_that_"
356 "are_subject_to_a_claim_of_copyright_by_anybody._"
357 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
358 "(copyright_or_otherwise)_applying_to_any_cookie._";
361 /*********************************************************************
365 * Description : Once a connection to the client has been accepted,
366 * this function is called (via serve()) to handle the
367 * main business of the communication. When this
368 * function returns, the caller must close the client
372 * 1 : csp = Current client state (buffers, headers, etc...)
374 * Returns : On success, the number of bytes written are returned (zero
375 * indicates nothing was written). On error, -1 is returned,
376 * and errno is set appropriately. If count is zero and the
377 * file descriptor refers to a regular file, 0 will be
378 * returned without causing any other effect. For a special
379 * file, the results are not portable.
381 *********************************************************************/
382 static void chat(struct client_state *csp)
385 * This next lines are a little ugly, but they simplifies the if statements below.
386 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
387 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
390 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
391 #else /* ifndef TOGGLE */
392 # define IS_TOGGLED_ON_AND
393 #endif /* ndef TOGGLE */
395 # define IS_NOT_FORCED_AND (!csp->force) &&
396 #else /* ifndef FORCE_LOAD */
397 # define IS_NOT_FORCED_AND
398 #endif /* def FORCE_LOAD */
400 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
402 char buf[BUFFER_SIZE];
406 int n, maxfd, server_body;
407 int ms_iis5_hack = 0;
409 const struct forward_spec * fwd;
410 struct http_request *http;
412 int block_popups; /* bool, 1==will block popups */
413 int block_popups_now = 0; /* bool, 1==currently blocking popups */
414 #endif /* def KILLPOPUPS */
416 int pcrs_filter; /* bool, 1==will filter through pcrs */
417 int gif_deanimate; /* bool, 1==will deanimate gifs */
419 /* Function that does the content filtering for the current request */
420 char *(*content_filter)() = NULL;
422 /* Skeleton for HTTP response, if we should intercept the request */
423 struct http_response *rsp;
428 * Read the client's request. Note that since we're not using select() we
429 * could get blocked here if a client connected, then didn't say anything!
434 n = read_socket(csp->cfd, buf, sizeof(buf));
436 if (n <= 0) break; /* error! */
438 add_to_iob(csp, buf, n);
440 req = get_header(csp);
444 break; /* no HTTP request! */
449 continue; /* more to come! */
453 /* If this request contains the FORCE_PREFIX,
454 * better get rid of it now and set the force flag --oes
457 if (strstr(req, FORCE_PREFIX))
459 strclean(req, FORCE_PREFIX);
460 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
467 #endif /* def FORCE_LOAD */
469 parse_http_request(req, http, csp);
474 if (http->cmd == NULL)
476 strcpy(buf, CHEADER);
477 write_socket(csp->cfd, buf, strlen(buf));
479 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
484 /* decide how to route the HTTP request */
486 if ((fwd = forward_url(http, csp)) == NULL)
488 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
489 /* Never get here - LOG_LEVEL_FATAL causes program exit */
492 /* build the http request to send to the server
493 * we have to do one of the following:
495 * create = use the original HTTP request to create a new
496 * HTTP request that has only the path component
497 * without the http://domainspec
498 * pass = pass the original HTTP request unchanged
500 * drop = drop the HTTP request
505 * +--------+--------+
507 * 0 | create | drop |
509 * Forwarding +--------+--------+
513 * +--------+--------+
517 if (fwd->forward_host)
519 /* if forwarding, just pass the request as is */
520 enlist(csp->headers, http->cmd);
526 /* otherwise elide the host information from the url */
528 p = strsav(p, http->gpc);
530 p = strsav(p, http->path);
532 p = strsav(p, http->ver);
533 enlist(csp->headers, p);
538 /* decide what we're to do with cookies */
541 if (!csp->toggled_on)
543 /* Most compatible set of actions (i.e. none) */
544 init_current_action(csp->action);
547 #endif /* ndef TOGGLE */
549 url_actions(http, csp);
554 * If we're logging cookies in a cookie jar, and the user has not
555 * supplied any wafers, and the user has not told us to suppress the
556 * vanilla wafer, then send the vanilla wafer.
558 if ((csp->config->jarfile != NULL)
559 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
560 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
562 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
564 #endif /* def JAR_FILES */
567 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
568 #endif /* def KILLPOPUPS */
570 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
571 ((csp->action->flags & ACTION_FILTER) != 0);
573 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
575 /* grab the rest of the client's headers */
579 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
581 n = read_socket(csp->cfd, buf, sizeof(buf));
584 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
587 add_to_iob(csp, buf, n);
591 if (p == NULL) break;
593 enlist(csp->headers, p);
597 /* We have a request. */
599 hdr = sed(client_patterns, add_client_headers, csp);
600 destroy_list(csp->headers);
603 * Now, check to see if we need to intercept it, i.e.
608 /* a CGI call was detected and answered */
609 (NULL != (rsp = dispatch_cgi(csp)))
611 /* or we are enabled and... */
614 /* ..the request was blocked */
615 ( NULL != (rsp = block_url(csp)))
619 || ( NULL != (rsp = trust_url(csp)))
622 /* ..or a fast redirect kicked in */
623 #ifdef FAST_REDIRECTS
624 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
625 (NULL != (rsp = redirect_url(csp))))
626 #endif /* def FAST_REDIRECTS */
630 /* Write the answer to the client */
631 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
632 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
634 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
638 /* Count as a rejected request */
640 #endif /* def STATISTICS */
642 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
643 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
644 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
646 /* Clean up and return */
647 free_http_response(rsp);
652 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
654 if (fwd->forward_host)
656 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
657 fwd->forward_host, fwd->forward_port, http->hostport);
661 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
664 /* here we connect to the server, gateway, or the forwarder */
666 csp->sfd = forwarded_connect(fwd, http, csp);
670 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
675 rsp = error_response(csp, "no-such-domain", errno);
677 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
678 csp->ip_addr_str, http->cmd);
682 rsp = error_response(csp, "connect-failed", errno);
684 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
685 csp->ip_addr_str, http->cmd);
688 /* Write the answer to the client */
691 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
692 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
694 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
698 free_http_response(rsp);
703 log_error(LOG_LEVEL_CONNECT, "OK");
705 if (fwd->forward_host || (http->ssl == 0))
707 /* write the client's (modified) header to the server
708 * (along with anything else that may be in the buffer)
713 if ((write_socket(csp->sfd, hdr, n) != n)
714 || (flush_socket(csp->sfd, csp ) < 0))
716 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
719 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
720 csp->ip_addr_str, http->cmd);
722 rsp = error_response(csp, "connect-failed", errno);
726 if ((write_socket(csp->cfd, rsp->head, n) != n)
727 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
729 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
733 free_http_response(rsp);
741 * We're running an SSL tunnel and we're not forwarding,
742 * so just send the "connect succeeded" message to the
743 * client, flush the rest, and get out of the way.
745 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
746 csp->ip_addr_str, http->cmd);
748 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
756 /* we're finished with the client's header */
759 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
761 /* pass data between the client and server
762 * until one or the other shuts down the connection.
771 FD_SET(csp->cfd, &rfds);
772 FD_SET(csp->sfd, &rfds);
774 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
778 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
782 /* this is the body of the browser's request
783 * just read it and write it.
786 if (FD_ISSET(csp->cfd, &rfds))
788 n = read_socket(csp->cfd, buf, sizeof(buf));
792 break; /* "game over, man" */
795 if (write_socket(csp->sfd, buf, n) != n)
797 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
804 * The server wants to talk. It could be the header or the body.
805 * If `hdr' is null, then it's the header otherwise it's the body.
806 * FIXME: Does `hdr' really mean `host'? No.
810 if (FD_ISSET(csp->sfd, &rfds))
813 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
817 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
819 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
820 csp->ip_addr_str, http->cmd);
822 rsp = error_response(csp, "connect-failed", errno);
826 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
827 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
829 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
833 free_http_response(rsp);
837 /* Add a trailing zero. This lets filter_popups
838 * use string operations.
843 /* Filter the popups on this read. */
844 if (block_popups_now)
846 filter_popups(buf, n);
848 #endif /* def KILLPOPUPS */
850 /* Normally, this would indicate that we've read
851 * as much as the server has sent us and we can
852 * close the client connection. However, Microsoft
853 * in its wisdom has released IIS/5 with a bug that
854 * prevents it from sending the trailing \r\n in
855 * a 302 redirect header (and possibly other headers).
856 * To work around this if we've haven't parsed
857 * a full header we'll append a trailing \r\n
858 * and see if this now generates a valid one.
860 * This hack shouldn't have any impacts. If we've
861 * already transmitted the header or if this is a
862 * SSL connection, then we won't bother with this
863 * hack. So we only work on partially received
864 * headers. If we append a \r\n and this still
865 * doesn't generate a valid header, then we won't
866 * transmit anything to the client.
871 if (server_body || http->ssl)
874 * If we have been buffering up the document,
875 * now is the time to apply content modification
876 * and send the result to the client.
881 * If the content filter fails, use the original
883 * (see p != NULL ? p : csp->iob->cur below)
885 if (NULL == (p = (*content_filter)(csp)))
887 csp->content_length = csp->iob->eod - csp->iob->cur;
890 hdr = sed(server_patterns, add_server_headers, csp);
893 if ((write_socket(csp->cfd, hdr, n) != n)
894 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != csp->content_length))
896 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
904 break; /* "game over, man" */
908 * This is NOT the body, so
909 * Let's pretend the server just sent us a blank line.
911 n = sprintf(buf, "\r\n");
914 * Now, let the normal header parsing algorithm below do its
915 * job. If it fails, we'll exit instead of continuing.
922 * If this is an SSL connection or we're in the body
923 * of the server document, just write it to the client,
924 * unless we need to buffer the body for later content-filtering
927 if (server_body || http->ssl)
931 add_to_iob(csp, buf, n);
935 if (write_socket(csp->cfd, buf, n) != n)
937 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
946 /* we're still looking for the end of the
947 * server's header ... (does that make header
948 * parsing an "out of body experience" ?
951 /* buffer up the data we just read */
952 add_to_iob(csp, buf, n);
954 /* get header lines from the iob */
956 while ((p = get_header(csp)))
960 /* see following note */
963 enlist(csp->headers, p);
967 /* NOTE: there are no "empty" headers so
968 * if the pointer `p' is not NULL we must
969 * assume that we reached the end of the
970 * buffer before we hit the end of the header.
977 /* Well, we tried our MS IIS/5
978 * hack and it didn't work.
979 * The header is incomplete
980 * and there isn't anything
981 * we can do about it.
987 /* Since we have to wait for
988 * more from the server before
989 * we can parse the headers
990 * we just continue here.
996 /* we have now received the entire header.
997 * filter it and send the result to the client
1000 hdr = sed(server_patterns, add_server_headers, csp);
1003 /* write the server's (modified) header to
1004 * the client (along with anything else that
1005 * may be in the buffer)
1009 /* Start blocking popups if appropriate. */
1011 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1012 !http->ssl && /* We talk plaintext */
1013 block_popups) /* Policy allows */
1015 block_popups_now = 1;
1017 * Filter the part of the body that came in the same read
1018 * as the last headers:
1020 filter_popups(csp->iob->cur, csp->iob->eod - csp->iob->cur);
1023 #endif /* def KILLPOPUPS */
1025 /* Buffer and pcrs filter this if appropriate. */
1027 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1028 !http->ssl && /* We talk plaintext */
1029 pcrs_filter) /* Policy allows */
1031 content_filter = pcrs_filter_response;
1034 /* Buffer and gif_deanimate this if appropriate. */
1036 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1037 !http->ssl && /* We talk plaintext */
1038 gif_deanimate) /* Policy allows */
1040 content_filter = gif_deanimate_response;
1045 * Only write if we're not buffering for content modification
1047 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1048 || (n = flush_socket(csp->cfd, csp) < 0)))
1050 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1052 /* the write failed, so don't bother
1053 * mentioning it to the client...
1054 * it probably can't hear us anyway.
1060 !content_filter && (byte_count += n);
1062 /* we're finished with the server's header */
1067 /* If this was a MS IIS/5 hack then it means
1068 * the server has already closed the
1069 * connection. Nothing more to read. Time
1080 return; /* huh? we should never get here */
1083 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1084 csp->ip_addr_str, http->cmd, byte_count);
1088 /*********************************************************************
1092 * Description : This is little more than chat. We only "serve" to
1093 * to close any socket that chat may have opened.
1096 * 1 : csp = Current client state (buffers, headers, etc...)
1100 *********************************************************************/
1102 void serve(struct client_state *csp)
1103 #else /* ifndef AMIGA */
1104 static void serve(struct client_state *csp)
1105 #endif /* def AMIGA */
1108 close_socket(csp->cfd);
1112 close_socket(csp->sfd);
1121 /*********************************************************************
1123 * Function : server_thread
1125 * Description : We only exist to call `serve' in a threaded environment.
1128 * 1 : data = Current client state (buffers, headers, etc...)
1130 * Returns : Always 0.
1132 *********************************************************************/
1133 static int32 server_thread(void *data)
1135 serve((struct client_state *) data);
1142 /*********************************************************************
1146 * Description : Load the config file and start the listen loop.
1147 * This function is a lot more *sane* with the `load_config'
1148 * and `listen_loop' functions; although it stills does
1149 * a *little* too much for my taste.
1152 * 1 : argc = Number of parameters (including $0).
1153 * 2 : argv = Array of (char *)'s to the parameters.
1155 * Returns : 1 if : can't open config file, unrecognized directive,
1156 * stats requested in multi-thread mode, can't open the
1157 * log file, can't open the jar file, listen port is invalid,
1158 * any load fails, and can't bind port.
1160 * Else main never returns, the process must be signaled
1161 * to terminate execution. Or, on Windows, use the
1162 * "File", "Exit" menu option.
1164 *********************************************************************/
1166 int _main(int argc, const char *argv[])
1168 int main(int argc, const char *argv[])
1173 "AmiTCP:db/junkbuster/config"
1174 #elif !defined(_WIN32)
1181 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1182 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1184 printf("JunkBuster proxy version " VERSION ".\n\n"
1185 "Usage: %s [configfile]\n\n"
1186 "See " HOME_PAGE_URL " for details.\n"
1187 "This program is distributed under the GNU GPL, version 2 or later.\n",
1191 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1193 printf(VERSION "\n");
1196 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1203 configfile = argv[1];
1210 #elif defined(_WIN32)
1216 signal(SIGPIPE, SIG_IGN);
1217 signal(SIGCHLD, SIG_IGN);
1219 #else /* ifdef _WIN32 */
1220 # ifdef _WIN_CONSOLE
1222 * We *are* in a windows console app.
1223 * Print a verbose messages about FAQ's and such
1225 printf(win32_blurb);
1226 # endif /* def _WIN_CONSOLE */
1227 #endif /* def _WIN32 */
1238 /*********************************************************************
1240 * Function : listen_loop
1242 * Description : bind the listen port and enter a "FOREVER" listening loop.
1248 *********************************************************************/
1249 static void listen_loop(void)
1251 struct client_state *csp = NULL;
1253 struct configuration_spec * config;
1255 config = load_config();
1257 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1258 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1260 bfd = bind_port(config->haddr, config->hport);
1264 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1265 "- There may be another junkbuster or some other "
1266 "proxy running on port %d",
1267 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1268 config->hport, config->hport
1270 /* shouldn't get here */
1274 config->need_bind = 0;
1279 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1280 while (waitpid(-1, NULL, WNOHANG) > 0)
1282 /* zombie children */
1284 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1287 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1289 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1293 memset(csp, '\0', sizeof(*csp));
1298 csp->config = config = load_config();
1300 if ( config->need_bind )
1303 * Since we were listening to the "old port", we will not see
1304 * a "listen" param change until the next IJB request. So, at
1305 * least 1 more request must be made for us to find the new
1306 * setting. I am simply closing the old socket and binding the
1309 * Which-ever is correct, we will serve 1 more page via the
1310 * old settings. This should probably be a "show-proxy-args"
1311 * request. This should not be a so common of an operation
1312 * that this will hurt people's feelings.
1317 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1318 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1319 bfd = bind_port(config->haddr, config->hport);
1323 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1324 "- There may be another junkbuster or some other "
1325 "proxy running on port %d",
1326 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1327 config->hport, config->hport
1329 /* shouldn't get here */
1333 config->need_bind = 0;
1336 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1338 if (!accept_connection(csp, bfd))
1340 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1353 log_error(LOG_LEVEL_CONNECT, "OK");
1357 /* by haroon - most of credit to srt19170 */
1358 csp->toggled_on = g_bToggleIJB;
1361 if (run_loader(csp))
1363 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1364 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1368 if (block_acl(NULL,csp))
1370 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1371 close_socket(csp->cfd);
1375 #endif /* def ACL_FILES */
1377 /* add it to the list of clients */
1378 csp->next = clients->next;
1379 clients->next = csp;
1381 if (config->multi_threaded)
1385 /* this is a switch () statment in the C preprocessor - ugh */
1386 #undef SELECTED_ONE_OPTION
1388 /* Use Pthreads in preference to native code */
1389 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1390 #define SELECTED_ONE_OPTION
1392 pthread_t the_thread;
1393 pthread_attr_t attrs;
1395 pthread_attr_init(&attrs);
1396 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1397 child_id = (pthread_create(&the_thread, &attrs,
1398 (void*)serve, csp) ? -1 : 0);
1399 pthread_attr_destroy(&attrs);
1403 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1404 #define SELECTED_ONE_OPTION
1405 child_id = _beginthread(
1411 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1412 #define SELECTED_ONE_OPTION
1414 thread_id tid = spawn_thread
1415 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1417 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1419 child_id = (int) tid;
1428 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1429 #define SELECTED_ONE_OPTION
1430 csp->cfd = ReleaseSocket(csp->cfd, -1);
1431 if((child_id = (int)CreateNewProcTags(
1432 NP_Entry, (ULONG)server_thread,
1433 NP_Output, Output(),
1434 NP_CloseOutput, FALSE,
1435 NP_Name, (ULONG)"junkbuster child",
1436 NP_StackSize, 200*1024,
1440 ((struct Task *)child_id)->tc_UserData = csp;
1441 Signal((struct Task *)child_id, SIGF_SINGLE);
1446 #if !defined(SELECTED_ONE_OPTION)
1449 /* This block is only needed when using fork().
1450 * When using threads, the server thread was
1451 * created and run by the call to _beginthread().
1453 if (child_id == 0) /* child */
1459 else if (child_id > 0) /* parent */
1461 /* in a fork()'d environment, the parent's
1462 * copy of the client socket and the CSP
1466 #if !defined(_WIN32) && defined(__CYGWIN__)
1468 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1469 close_socket(csp->cfd);
1474 #undef SELECTED_ONE_OPTION
1475 /* end of cpp switch () */
1477 if (child_id < 0) /* failed */
1479 char buf[BUFFER_SIZE];
1481 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1483 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1485 write_socket(csp->cfd, buf, strlen(buf));
1486 close_socket(csp->cfd);