1 const char jcc_rcs[] = "$Id: jcc.c,v 1.25 2001/07/15 19:43:49 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.25 2001/07/15 19:43:49 jongfoster
37 * Supports POSIX threads.
38 * Also removed some unused #includes.
40 * Revision 1.24 2001/07/13 14:00:40 oes
41 * - Generic content modification scheme:
42 * Each feature has its own applicability flag that is set
43 * from csp->action->flags.
44 * Replaced the "filtering" int flag , by a function pointer
45 * "content_filter" to the function that will do the content
46 * modification. If it is != NULL, the document will be buffered
47 * and processed through *content_filter, which must set
48 * csp->content_length and return a modified copy of the body
49 * or return NULL (on failiure).
50 * - Changed csp->is_text to the more generic bitmap csp->content_type
51 * which can currently take the valued CT_TEXT or CT_GIF
53 * - Removed all #ifdef PCRS
55 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
56 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
57 * the `block_acl' call. This prevents a compilation error when the user
58 * does not wish to use the "ACL" feature.
60 * Revision 1.22 2001/06/29 21:45:41 oes
61 * Indentation, CRLF->LF, Tab-> Space
63 * Revision 1.21 2001/06/29 13:29:36 oes
64 * - Cleaned up, improved comments
65 * - Unified all possible interceptors (CGI,
66 * block, trust, fast_redirect) in one
67 * place, with one (CGI) answer generation
68 * mechansim. Much clearer now.
69 * - Removed the GIF image generation, which
70 * is now done in filters.c:block_url()
71 * - Made error conditions like domain lookup
72 * failiure or (various) problems while talking
73 * to the server use cgi.c:error_response()
74 * instead of generating HTML/HTTP in chat() (yuck!)
75 * - Removed logentry from cancelled commit
77 * Revision 1.20 2001/06/09 10:55:28 jongfoster
78 * Changing BUFSIZ ==> BUFFER_SIZE
80 * Revision 1.19 2001/06/07 23:12:52 jongfoster
81 * Replacing function pointer in struct gateway with a directly
82 * called function forwarded_connect().
83 * Replacing struct gateway with struct forward_spec
85 * Revision 1.18 2001/06/03 19:12:16 oes
86 * introduced new cgi handling
88 * Revision 1.17 2001/06/01 20:07:23 jongfoster
89 * Now uses action +image-blocker{} rather than config->tinygif
91 * Revision 1.16 2001/06/01 18:49:17 jongfoster
92 * Replaced "list_share" with "list" - the tiny memory gain was not
93 * worth the extra complexity.
95 * Revision 1.15 2001/05/31 21:24:47 jongfoster
96 * Changed "permission" to "action" throughout.
97 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
98 * Moved vanilla wafer check into chat(), since we must now
99 * decide whether or not to add it based on the URL.
101 * Revision 1.14 2001/05/29 20:14:01 joergs
102 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
105 * Revision 1.13 2001/05/29 09:50:24 jongfoster
106 * Unified blocklist/imagelist/permissionslist.
107 * File format is still under discussion, but the internal changes
110 * Also modified interceptor behaviour:
111 * - We now intercept all URLs beginning with one of the following
112 * prefixes (and *only* these prefixes):
114 * * http://ijbswa.sf.net/config/
115 * * http://ijbswa.sourceforge.net/config/
116 * - New interceptors "home page" - go to http://i.j.b/ to see it.
117 * - Internal changes so that intercepted and fast redirect pages
118 * are not replaced with an image.
119 * - Interceptors now have the option to send a binary page direct
120 * to the client. (i.e. ijb-send-banner uses this)
121 * - Implemented show-url-info interceptor. (Which is why I needed
122 * the above interceptors changes - a typical URL is
123 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
124 * The previous mechanism would not have intercepted that, and
125 * if it had been intercepted then it then it would have replaced
128 * Revision 1.12 2001/05/27 22:17:04 oes
130 * - re_process_buffer no longer writes the modified buffer
131 * to the client, which was very ugly. It now returns the
132 * buffer, which it is then written by chat.
134 * - content_length now adjusts the Content-Length: header
135 * for modified documents rather than crunch()ing it.
136 * (Length info in csp->content_length, which is 0 for
137 * unmodified documents)
139 * - For this to work, sed() is called twice when filtering.
141 * Revision 1.11 2001/05/26 17:27:53 jongfoster
142 * Added support for CLF and fixed LOG_LEVEL_LOG.
143 * Also did CRLF->LF fix of my previous patch.
145 * Revision 1.10 2001/05/26 15:26:15 jongfoster
146 * ACL feature now provides more security by immediately dropping
147 * connections from untrusted hosts.
149 * Revision 1.9 2001/05/26 00:28:36 jongfoster
150 * Automatic reloading of config file.
151 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
152 * Most of the global variables have been moved to a new
153 * struct configuration_spec, accessed through csp->config->globalname
154 * Most of the globals remaining are used by the Win32 GUI.
156 * Revision 1.8 2001/05/25 22:43:18 jongfoster
157 * Fixing minor memory leak and buffer overflow.
159 * Revision 1.7 2001/05/25 22:34:30 jongfoster
162 * Revision 1.6 2001/05/23 00:13:58 joergs
163 * AmigaOS support fixed.
165 * Revision 1.5 2001/05/22 18:46:04 oes
167 * - Enabled filtering banners by size rather than URL
168 * by adding patterns that replace all standard banner
169 * sizes with the "Junkbuster" gif to the re_filterfile
171 * - Enabled filtering WebBugs by providing a pattern
172 * which kills all 1x1 images
174 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
175 * which is selected by the (nonstandard and therefore
176 * capital) letter 'U' in the option string.
177 * It causes the quantifiers to be ungreedy by default.
178 * Appending a ? turns back to greedy (!).
180 * - Added a new interceptor ijb-send-banner, which
181 * sends back the "Junkbuster" gif. Without imagelist or
182 * MSIE detection support, or if tinygif = 1, or the
183 * URL isn't recognized as an imageurl, a lame HTML
184 * explanation is sent instead.
186 * - Added new feature, which permits blocking remote
187 * script redirects and firing back a local redirect
189 * The feature is conditionally compiled, i.e. it
190 * can be disabled with --disable-fast-redirects,
191 * plus it must be activated by a "fast-redirects"
192 * line in the config file, has its own log level
193 * and of course wants to be displayed by show-proxy-args
194 * Note: Boy, all the #ifdefs in 1001 locations and
195 * all the fumbling with configure.in and acconfig.h
196 * were *way* more work than the feature itself :-(
198 * - Because a generic redirect template was needed for
199 * this, tinygif = 3 now uses the same.
201 * - Moved GIFs, and other static HTTP response templates
206 * - Removed some >400 CRs again (Jon, you really worked
209 * Revision 1.4 2001/05/21 19:34:01 jongfoster
210 * Made failure to bind() a fatal error.
212 * Revision 1.3 2001/05/20 01:21:20 jongfoster
213 * Version 2.9.4 checkin.
214 * - Merged popupfile and cookiefile, and added control over PCRS
215 * filtering, in new "permissionsfile".
216 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
217 * file error you now get a message box (in the Win32 GUI) rather
218 * than the program exiting with no explanation.
219 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
221 * - Removed tabs from "config"
222 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
223 * - Bumped up version number.
225 * Revision 1.2 2001/05/17 22:34:44 oes
226 * - Added hint on GIF char array generation to jcc.c
227 * - Cleaned CRLF's from the sources and related files
228 * - Repaired logging for REF and FRC
230 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
231 * Initial import of version 2.9.3 source tree
234 *********************************************************************/
240 #include <sys/types.h>
247 #ifdef FEATURE_PTHREAD
249 #endif /* def FEATURE_PTHREAD */
252 # ifndef FEATURE_PTHREAD
253 # include <windows.h>
254 # include <process.h>
255 # endif /* ndef FEATURE_PTHREAD */
258 # ifndef _WIN_CONSOLE
260 # endif /* ndef _WIN_CONSOLE */
262 #else /* ifndef _WIN32 */
265 # include <sys/time.h>
266 # include <sys/wait.h>
267 # include <sys/stat.h>
271 # include <socket.h> /* BeOS has select() for sockets only. */
272 # include <OS.h> /* declarations for threads and stuff. */
286 #include "showargs.h"
288 #include "killpopup.h"
289 #include "miscutil.h"
291 #include "jbsockets.h"
296 const char jcc_h_rcs[] = JCC_H_VERSION;
297 const char project_h_rcs[] = PROJECT_H_VERSION;
299 struct client_state clients[1];
300 struct file_list files[1];
303 int urls_read = 0; /* total nr of urls read inc rejected */
304 int urls_rejected = 0; /* total nr of urls rejected */
305 #endif /* def STATISTICS */
308 static void listen_loop(void);
309 static void chat(struct client_state *csp);
311 void serve(struct client_state *csp);
312 #else /* ifndef AMIGA */
313 static void serve(struct client_state *csp);
314 #endif /* def AMIGA */
317 static int32 server_thread(void *data);
318 #endif /* def __BEOS__ */
321 #define sleep(N) Sleep(((N) * 1000))
325 /* The vanilla wafer. */
326 static const char VANILLA_WAFER[] =
327 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
328 "Do_not_send_me_any_copyrighted_information_other_than_the_"
329 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
330 "In_particular_do_not_send_me_any_cookies_that_"
331 "are_subject_to_a_claim_of_copyright_by_anybody._"
332 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
333 "(copyright_or_otherwise)_applying_to_any_cookie._";
336 /*********************************************************************
340 * Description : Once a connection to the client has been accepted,
341 * this function is called (via serve()) to handle the
342 * main business of the communication. When this
343 * function returns, the caller must close the client
347 * 1 : csp = Current client state (buffers, headers, etc...)
349 * Returns : On success, the number of bytes written are returned (zero
350 * indicates nothing was written). On error, -1 is returned,
351 * and errno is set appropriately. If count is zero and the
352 * file descriptor refers to a regular file, 0 will be
353 * returned without causing any other effect. For a special
354 * file, the results are not portable.
356 *********************************************************************/
357 static void chat(struct client_state *csp)
360 * This next lines are a little ugly, but they simplifies the if statements below.
361 * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
362 * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
365 # define IS_TOGGLED_ON_AND (csp->toggled_on) &&
366 #else /* ifndef TOGGLE */
367 # define IS_TOGGLED_ON_AND
368 #endif /* ndef TOGGLE */
370 # define IS_NOT_FORCED_AND (!csp->force) &&
371 #else /* ifndef FORCE_LOAD */
372 # define IS_NOT_FORCED_AND
373 #endif /* def FORCE_LOAD */
375 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
377 char buf[BUFFER_SIZE];
381 int n, maxfd, server_body;
382 int ms_iis5_hack = 0;
384 const struct forward_spec * fwd;
385 struct http_request *http;
387 int block_popups; /* bool, 1==will block popups */
388 int block_popups_now = 0; /* bool, 1==currently blocking popups */
389 #endif /* def KILLPOPUPS */
391 int pcrs_filter; /* bool, 1==will filter through pcrs */
392 int gif_deanimate; /* bool, 1==will deanimate gifs */
394 /* Function that does the content filtering for the current request */
395 char *(*content_filter)() = NULL;
397 /* Skeleton for HTTP response, if we should intercept the request */
398 struct http_response *rsp;
403 * Read the client's request. Note that since we're not using select() we
404 * could get blocked here if a client connected, then didn't say anything!
409 n = read_socket(csp->cfd, buf, sizeof(buf));
411 if (n <= 0) break; /* error! */
413 add_to_iob(csp, buf, n);
415 req = get_header(csp);
419 break; /* no HTTP request! */
424 continue; /* more to come! */
428 /* If this request contains the FORCE_PREFIX,
429 * better get rid of it now and set the force flag --oes
432 if (strstr(req, FORCE_PREFIX))
434 strclean(req, FORCE_PREFIX);
435 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
442 #endif /* def FORCE_LOAD */
444 parse_http_request(req, http, csp);
449 if (http->cmd == NULL)
451 strcpy(buf, CHEADER);
452 write_socket(csp->cfd, buf, strlen(buf));
454 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
459 /* decide how to route the HTTP request */
461 if ((fwd = forward_url(http, csp)) == NULL)
463 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
464 /* Never get here - LOG_LEVEL_FATAL causes program exit */
467 /* build the http request to send to the server
468 * we have to do one of the following:
470 * create = use the original HTTP request to create a new
471 * HTTP request that has only the path component
472 * without the http://domainspec
473 * pass = pass the original HTTP request unchanged
475 * drop = drop the HTTP request
480 * +--------+--------+
482 * 0 | create | drop |
484 * Forwarding +--------+--------+
488 * +--------+--------+
492 if (fwd->forward_host)
494 /* if forwarding, just pass the request as is */
495 enlist(csp->headers, http->cmd);
501 /* otherwise elide the host information from the url */
503 p = strsav(p, http->gpc);
505 p = strsav(p, http->path);
507 p = strsav(p, http->ver);
508 enlist(csp->headers, p);
513 /* decide what we're to do with cookies */
516 if (!csp->toggled_on)
518 /* Most compatible set of actions (i.e. none) */
519 init_current_action(csp->action);
522 #endif /* ndef TOGGLE */
524 url_actions(http, csp);
529 * If we're logging cookies in a cookie jar, and the user has not
530 * supplied any wafers, and the user has not told us to suppress the
531 * vanilla wafer, then send the vanilla wafer.
533 if ((csp->config->jarfile != NULL)
534 && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
535 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
537 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
539 #endif /* def JAR_FILES */
542 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
543 #endif /* def KILLPOPUPS */
545 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
546 ((csp->action->flags & ACTION_FILTER) != 0);
548 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
550 /* grab the rest of the client's headers */
554 if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
556 n = read_socket(csp->cfd, buf, sizeof(buf));
559 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
562 add_to_iob(csp, buf, n);
566 if (p == NULL) break;
568 enlist(csp->headers, p);
572 /* We have a request. */
574 hdr = sed(client_patterns, add_client_headers, csp);
575 destroy_list(csp->headers);
578 * Now, check to see if we need to intercept it, i.e.
583 /* a CGI call was detected and answered */
584 (NULL != (rsp = dispatch_cgi(csp)))
586 /* or we are enabled and... */
589 /* ..the request was blocked */
590 ( NULL != (rsp = block_url(csp)))
594 || ( NULL != (rsp = trust_url(csp)))
597 /* ..or a fast redirect kicked in */
598 #ifdef FAST_REDIRECTS
599 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
600 (NULL != (rsp = redirect_url(csp))))
601 #endif /* def FAST_REDIRECTS */
605 /* Write the answer to the client */
606 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
607 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
609 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
613 /* Count as a rejected request */
615 #endif /* def STATISTICS */
617 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
618 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
619 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd);
621 /* Clean up and return */
622 free_http_response(rsp);
627 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
629 if (fwd->forward_host)
631 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
632 fwd->forward_host, fwd->forward_port, http->hostport);
636 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
639 /* here we connect to the server, gateway, or the forwarder */
641 csp->sfd = forwarded_connect(fwd, http, csp);
645 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
650 rsp = error_response(csp, "no-such-domain", errno);
652 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
653 csp->ip_addr_str, http->cmd);
657 rsp = error_response(csp, "connect-failed", errno);
659 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
660 csp->ip_addr_str, http->cmd);
663 /* Write the answer to the client */
666 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
667 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
669 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
673 free_http_response(rsp);
678 log_error(LOG_LEVEL_CONNECT, "OK");
680 if (fwd->forward_host || (http->ssl == 0))
682 /* write the client's (modified) header to the server
683 * (along with anything else that may be in the buffer)
688 if ((write_socket(csp->sfd, hdr, n) != n)
689 || (flush_socket(csp->sfd, csp ) < 0))
691 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
694 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
695 csp->ip_addr_str, http->cmd);
697 rsp = error_response(csp, "connect-failed", errno);
701 if ((write_socket(csp->cfd, rsp->head, n) != n)
702 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
704 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
708 free_http_response(rsp);
716 * We're running an SSL tunnel and we're not forwarding,
717 * so just send the "connect succeeded" message to the
718 * client, flush the rest, and get out of the way.
720 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
721 csp->ip_addr_str, http->cmd);
723 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
731 /* we're finished with the client's header */
734 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
736 /* pass data between the client and server
737 * until one or the other shuts down the connection.
746 FD_SET(csp->cfd, &rfds);
747 FD_SET(csp->sfd, &rfds);
749 n = select(maxfd+1, &rfds, NULL, NULL, NULL);
753 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
757 /* this is the body of the browser's request
758 * just read it and write it.
761 if (FD_ISSET(csp->cfd, &rfds))
763 n = read_socket(csp->cfd, buf, sizeof(buf));
767 break; /* "game over, man" */
770 if (write_socket(csp->sfd, buf, n) != n)
772 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
779 * The server wants to talk. It could be the header or the body.
780 * If `hdr' is null, then it's the header otherwise it's the body.
781 * FIXME: Does `hdr' really mean `host'? No.
785 if (FD_ISSET(csp->sfd, &rfds))
788 n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
792 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
794 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
795 csp->ip_addr_str, http->cmd);
797 rsp = error_response(csp, "connect-failed", errno);
801 if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
802 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
804 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
808 free_http_response(rsp);
812 /* Add a trailing zero. This lets filter_popups
813 * use string operations.
818 /* Filter the popups on this read. */
819 if (block_popups_now)
821 filter_popups(buf, n);
823 #endif /* def KILLPOPUPS */
825 /* Normally, this would indicate that we've read
826 * as much as the server has sent us and we can
827 * close the client connection. However, Microsoft
828 * in its wisdom has released IIS/5 with a bug that
829 * prevents it from sending the trailing \r\n in
830 * a 302 redirect header (and possibly other headers).
831 * To work around this if we've haven't parsed
832 * a full header we'll append a trailing \r\n
833 * and see if this now generates a valid one.
835 * This hack shouldn't have any impacts. If we've
836 * already transmitted the header or if this is a
837 * SSL connection, then we won't bother with this
838 * hack. So we only work on partially received
839 * headers. If we append a \r\n and this still
840 * doesn't generate a valid header, then we won't
841 * transmit anything to the client.
846 if (server_body || http->ssl)
849 * If we have been buffering up the document,
850 * now is the time to apply content modification
851 * and send the result to the client.
856 * If the content filter fails, use the original
858 * (see p != NULL ? p : csp->iob->cur below)
860 if (NULL == (p = (*content_filter)(csp)))
862 csp->content_length = csp->iob->eod - csp->iob->cur;
865 hdr = sed(server_patterns, add_server_headers, csp);
868 if ((write_socket(csp->cfd, hdr, n) != n)
869 || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != csp->content_length))
871 log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
879 break; /* "game over, man" */
883 * This is NOT the body, so
884 * Let's pretend the server just sent us a blank line.
886 n = sprintf(buf, "\r\n");
889 * Now, let the normal header parsing algorithm below do its
890 * job. If it fails, we'll exit instead of continuing.
897 * If this is an SSL connection or we're in the body
898 * of the server document, just write it to the client,
899 * unless we need to buffer the body for later content-filtering
902 if (server_body || http->ssl)
906 add_to_iob(csp, buf, n);
910 if (write_socket(csp->cfd, buf, n) != n)
912 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
921 /* we're still looking for the end of the
922 * server's header ... (does that make header
923 * parsing an "out of body experience" ?
926 /* buffer up the data we just read */
927 add_to_iob(csp, buf, n);
929 /* get header lines from the iob */
931 while ((p = get_header(csp)))
935 /* see following note */
938 enlist(csp->headers, p);
942 /* NOTE: there are no "empty" headers so
943 * if the pointer `p' is not NULL we must
944 * assume that we reached the end of the
945 * buffer before we hit the end of the header.
952 /* Well, we tried our MS IIS/5
953 * hack and it didn't work.
954 * The header is incomplete
955 * and there isn't anything
956 * we can do about it.
962 /* Since we have to wait for
963 * more from the server before
964 * we can parse the headers
965 * we just continue here.
971 /* we have now received the entire header.
972 * filter it and send the result to the client
975 hdr = sed(server_patterns, add_server_headers, csp);
978 /* write the server's (modified) header to
979 * the client (along with anything else that
980 * may be in the buffer)
984 /* Start blocking popups if appropriate. */
986 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
987 !http->ssl && /* We talk plaintext */
988 block_popups) /* Policy allows */
990 block_popups_now = 1;
993 #endif /* def KILLPOPUPS */
995 /* Buffer and pcrs filter this if appropriate. */
997 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
998 !http->ssl && /* We talk plaintext */
999 pcrs_filter) /* Policy allows */
1001 content_filter = pcrs_filter_response;
1004 /* Buffer and gif_deanimate this if appropriate. */
1006 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1007 !http->ssl && /* We talk plaintext */
1008 gif_deanimate) /* Policy allows */
1010 content_filter = gif_deanimate_response;
1015 * Only write if we're not buffering for content modification
1017 if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1018 || (n = flush_socket(csp->cfd, csp) < 0)))
1020 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1022 /* the write failed, so don't bother
1023 * mentioning it to the client...
1024 * it probably can't hear us anyway.
1030 !content_filter && (byte_count += n);
1032 /* we're finished with the server's header */
1037 /* If this was a MS IIS/5 hack then it means
1038 * the server has already closed the
1039 * connection. Nothing more to read. Time
1050 return; /* huh? we should never get here */
1053 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1054 csp->ip_addr_str, http->cmd, byte_count);
1058 /*********************************************************************
1062 * Description : This is little more than chat. We only "serve" to
1063 * to close any socket that chat may have opened.
1066 * 1 : csp = Current client state (buffers, headers, etc...)
1070 *********************************************************************/
1072 void serve(struct client_state *csp)
1073 #else /* ifndef AMIGA */
1074 static void serve(struct client_state *csp)
1075 #endif /* def AMIGA */
1078 close_socket(csp->cfd);
1082 close_socket(csp->sfd);
1091 /*********************************************************************
1093 * Function : server_thread
1095 * Description : We only exist to call `serve' in a threaded environment.
1098 * 1 : data = Current client state (buffers, headers, etc...)
1100 * Returns : Always 0.
1102 *********************************************************************/
1103 static int32 server_thread(void *data)
1105 serve((struct client_state *) data);
1112 /*********************************************************************
1116 * Description : Load the config file and start the listen loop.
1117 * This function is a lot more *sane* with the `load_config'
1118 * and `listen_loop' functions; although it stills does
1119 * a *little* too much for my taste.
1122 * 1 : argc = Number of parameters (including $0).
1123 * 2 : argv = Array of (char *)'s to the parameters.
1125 * Returns : 1 if : can't open config file, unrecognized directive,
1126 * stats requested in multi-thread mode, can't open the
1127 * log file, can't open the jar file, listen port is invalid,
1128 * any load fails, and can't bind port.
1130 * Else main never returns, the process must be signaled
1131 * to terminate execution. Or, on Windows, use the
1132 * "File", "Exit" menu option.
1134 *********************************************************************/
1136 int _main(int argc, const char *argv[])
1138 int main(int argc, const char *argv[])
1143 "AmiTCP:db/junkbuster/config"
1144 #elif !defined(_WIN32)
1151 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1152 if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1154 printf("JunkBuster proxy version " VERSION ".\n\n"
1155 "Usage: %s [configfile]\n\n"
1156 "See " HOME_PAGE_URL " for details.\n"
1157 "This program is distributed under the GNU GPL, version 2 or later.\n",
1161 if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1163 printf(VERSION "\n");
1166 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1173 configfile = argv[1];
1180 #elif defined(_WIN32)
1186 signal(SIGPIPE, SIG_IGN);
1187 signal(SIGCHLD, SIG_IGN);
1189 #else /* ifdef _WIN32 */
1190 # ifdef _WIN_CONSOLE
1192 * We *are* in a windows console app.
1193 * Print a verbose messages about FAQ's and such
1195 printf(win32_blurb);
1196 # endif /* def _WIN_CONSOLE */
1197 #endif /* def _WIN32 */
1208 /*********************************************************************
1210 * Function : listen_loop
1212 * Description : bind the listen port and enter a "FOREVER" listening loop.
1218 *********************************************************************/
1219 static void listen_loop(void)
1221 struct client_state *csp = NULL;
1223 struct configuration_spec * config;
1225 config = load_config();
1227 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1228 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1230 bfd = bind_port(config->haddr, config->hport);
1234 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1235 "- There may be another junkbuster or some other "
1236 "proxy running on port %d",
1237 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1238 config->hport, config->hport
1240 /* shouldn't get here */
1244 config->need_bind = 0;
1249 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1250 while (waitpid(-1, NULL, WNOHANG) > 0)
1252 /* zombie children */
1254 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1257 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1259 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1263 memset(csp, '\0', sizeof(*csp));
1268 csp->config = config = load_config();
1270 if ( config->need_bind )
1273 * Since we were listening to the "old port", we will not see
1274 * a "listen" param change until the next IJB request. So, at
1275 * least 1 more request must be made for us to find the new
1276 * setting. I am simply closing the old socket and binding the
1279 * Which-ever is correct, we will serve 1 more page via the
1280 * old settings. This should probably be a "show-proxy-args"
1281 * request. This should not be a so common of an operation
1282 * that this will hurt people's feelings.
1287 log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1288 config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1289 bfd = bind_port(config->haddr, config->hport);
1293 log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1294 "- There may be another junkbuster or some other "
1295 "proxy running on port %d",
1296 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1297 config->hport, config->hport
1299 /* shouldn't get here */
1303 config->need_bind = 0;
1306 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1308 if (!accept_connection(csp, bfd))
1310 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1323 log_error(LOG_LEVEL_CONNECT, "OK");
1327 /* by haroon - most of credit to srt19170 */
1328 csp->toggled_on = g_bToggleIJB;
1331 if (run_loader(csp))
1333 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1334 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1338 if (block_acl(NULL,csp))
1340 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1341 close_socket(csp->cfd);
1345 #endif /* def ACL_FILES */
1347 /* add it to the list of clients */
1348 csp->next = clients->next;
1349 clients->next = csp;
1351 if (config->multi_threaded)
1355 /* this is a switch () statment in the C preprocessor - ugh */
1356 #undef SELECTED_ONE_OPTION
1358 /* Use Pthreads in preference to native code */
1359 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1360 #define SELECTED_ONE_OPTION
1362 pthread_t the_thread;
1363 pthread_attr_t attrs;
1365 pthread_attr_init(&attrs);
1366 child_id = (pthread_create(&the_thread, &attrs,
1367 (void*)serve, csp) ? -1 : 0);
1368 pthread_attr_destroy(&attrs);
1372 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1373 #define SELECTED_ONE_OPTION
1374 child_id = _beginthread(
1380 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1381 #define SELECTED_ONE_OPTION
1383 thread_id tid = spawn_thread
1384 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1386 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1388 child_id = (int) tid;
1397 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1398 #define SELECTED_ONE_OPTION
1399 csp->cfd = ReleaseSocket(csp->cfd, -1);
1400 if((child_id = (int)CreateNewProcTags(
1401 NP_Entry, (ULONG)server_thread,
1402 NP_Output, Output(),
1403 NP_CloseOutput, FALSE,
1404 NP_Name, (ULONG)"junkbuster child",
1405 NP_StackSize, 200*1024,
1409 ((struct Task *)child_id)->tc_UserData = csp;
1410 Signal((struct Task *)child_id, SIGF_SINGLE);
1415 #if !defined(SELECTED_ONE_OPTION)
1418 /* This block is only needed when using fork().
1419 * When using threads, the server thread was
1420 * created and run by the call to _beginthread().
1422 if (child_id == 0) /* child */
1428 else if (child_id > 0) /* parent */
1430 /* in a fork()'d environment, the parent's
1431 * copy of the client socket and the CSP
1435 #if !defined(_WIN32) && defined(__CYGWIN__)
1437 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1438 close_socket(csp->cfd);
1443 #undef SELECTED_ONE_OPTION
1444 /* end of cpp switch () */
1446 if (child_id < 0) /* failed */
1448 char buf[BUFFER_SIZE];
1450 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1452 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1454 write_socket(csp->cfd, buf, strlen(buf));
1455 close_socket(csp->cfd);