1 const char jcc_rcs[] = "$Id: jcc.c,v 1.92.2.3 2003/02/28 12:53:06 oes Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/Attic/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 * Privoxy team. http://www.privoxy.org/
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.92.2.3 2003/02/28 12:53:06 oes
37 * Fixed two mostly harmless mem leaks
39 * Revision 1.92.2.2 2002/11/20 14:37:47 oes
40 * Fix: Head of global clients list now initialized to NULL
42 * Revision 1.92.2.1 2002/09/25 14:52:24 oes
43 * Added basic support for OPTIONS and TRACE HTTP methods:
44 * - New interceptor direct_response() added in chat().
45 * - sed() moved to earlier in the process, so that the
46 * Host: header is evaluated before actions and forwarding
49 * Revision 1.92 2002/05/08 16:00:46 oes
50 * Chat's buffer handling:
51 * - Fixed bug with unchecked out-of-mem conditions
52 * while reading client request & server headers
53 * - No longer predict if the buffer limit will be exceeded
54 * in the next read -- check add_to_iob's new
55 * return code. If buffer couldn't be extended
56 * (policy or out-of-mem) while
57 * - reading from client: abort
58 * - reading server headers: send error page
59 * - buffering server body for filter: flush,
60 * and if that fails: send error page
62 * Revision 1.91 2002/04/08 20:35:58 swa
65 * Revision 1.90 2002/04/02 14:57:28 oes
66 * Made sending wafers independent of FEATURE_COOKIE_JAR
68 * Revision 1.89 2002/03/31 17:18:59 jongfoster
69 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
71 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
72 * More compiler warning message maintenance
74 * Revision 1.87 2002/03/26 22:29:54 swa
75 * we have a new homepage!
77 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
78 * Workaround for closing the jarfile before load_config() comes around again
80 * Revision 1.85 2002/03/24 15:23:33 jongfoster
83 * Revision 1.84 2002/03/24 13:25:43 swa
84 * name change related issues
86 * Revision 1.83 2002/03/16 23:54:06 jongfoster
87 * Adding graceful termination feature, to help look for memory leaks.
88 * If you enable this (which, by design, has to be done by hand
89 * editing config.h) and then go to http://i.j.b/die, then the program
90 * will exit cleanly after the *next* request. It should free all the
91 * memory that was used.
93 * Revision 1.82 2002/03/13 00:27:05 jongfoster
96 * Revision 1.81 2002/03/12 01:42:50 oes
97 * Introduced modular filters
99 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
100 * OS/2 port maintenance:
101 * - Fixed EMX build - it had decayed a little
102 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
103 * substituted a memset for now.
105 * Revision 1.79 2002/03/09 20:03:52 jongfoster
106 * - Making various functions return int rather than size_t.
107 * (Undoing a recent change). Since size_t is unsigned on
108 * Windows, functions like read_socket that return -1 on
109 * error cannot return a size_t.
111 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
112 * crashes, and also frequently caused JB to jump to 100%
113 * CPU and stay there. (Because it thought it had just
114 * read ((unsigned)-1) == 4Gb of data...)
116 * - The signature of write_socket has changed, it now simply
117 * returns success=0/failure=nonzero.
119 * - Trying to get rid of a few warnings --with-debug on
120 * Windows, I've introduced a new type "jb_socket". This is
121 * used for the socket file descriptors. On Windows, this
122 * is SOCKET (a typedef for unsigned). Everywhere else, it's
123 * an int. The error value can't be -1 any more, so it's
124 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
125 * Windows it maps to the #define INVALID_SOCKET.)
127 * - The signature of bind_port has changed.
129 * Revision 1.78 2002/03/08 21:35:04 oes
130 * Added optional group supplement to --user option. Will now use default group of user if no group given
132 * Revision 1.77 2002/03/07 03:52:06 oes
133 * - Fixed compiler warnings etc
134 * - Improved handling of failed DNS lookups
136 * Revision 1.76 2002/03/06 22:54:35 jongfoster
137 * Automated function-comment nitpicking.
139 * Revision 1.75 2002/03/06 10:02:19 oes
140 * Fixed stupid bug when --user was not given
142 * Revision 1.74 2002/03/06 00:49:31 jongfoster
143 * Fixing warning on Windows
144 * Making #ifdefs that refer to the same variable consistently
145 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
147 * Revision 1.73 2002/03/05 23:57:30 hal9
148 * Stray character 's' on line 1618 was breaking build.
150 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
151 * - Re-enable OS/2 building after new parms were added
152 * - Fix false out of memory report when resolving CGI templates when no IP
153 * address is available of failed attempt (a la no such domain)
155 * Revision 1.71 2002/03/05 18:13:56 oes
156 * Added --user option
158 * Revision 1.70 2002/03/05 04:52:42 oes
159 * Deleted non-errlog debugging code
161 * Revision 1.69 2002/03/04 23:50:00 jongfoster
162 * Splitting off bind_port() call into bind_port_helper(), with
165 * Revision 1.68 2002/03/04 20:17:32 oes
168 * Revision 1.67 2002/03/04 18:18:57 oes
169 * - Removed _DEBUG mode
170 * - Cleand up cmdline parsing
171 * - Introduced --no-daemon, --pidfile options
172 * - Cleaned up signal handling:
173 * - Terminate cleanly on INT, TERM and ABRT
174 * - Schedule logfile for re-opening on HUP
175 * - Ignore CHLD and PIPE
176 * - Leave the rest with their default handlers
177 * - Uniform handler registration
178 * - Added usage() function
179 * - Played styleguide police
181 * Revision 1.66 2002/03/03 15:06:55 oes
182 * Re-enabled automatic config reloading
184 * Revision 1.65 2002/03/03 14:49:11 oes
185 * Fixed CLF logging: Now uses client's original HTTP request
187 * Revision 1.64 2002/03/03 09:18:03 joergs
188 * Made jumbjuster work on AmigaOS again.
190 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
191 * Clean up a little CRLF unpleasantness that suddenly appeared
193 * Revision 1.62 2002/02/20 23:17:23 jongfoster
194 * Detecting some out-of memory conditions and exiting with a log message.
196 * Revision 1.61 2002/01/17 21:01:52 jongfoster
197 * Moving all our URL and URL pattern parsing code to urlmatch.c.
199 * Revision 1.60 2001/12/30 14:07:32 steudten
200 * - Add signal handling (unix)
201 * - Add SIGHUP handler (unix)
202 * - Add creation of pidfile (unix)
203 * - Add action 'top' in rc file (RH)
204 * - Add entry 'SIGNALS' to manpage
205 * - Add exit message to logfile (unix)
207 * Revision 1.59 2001/12/13 14:07:18 oes
208 * Fixed Bug: 503 error page now sent OK
210 * Revision 1.58 2001/11/30 23:37:24 jongfoster
211 * Renaming the Win32 config file to config.txt - this is almost the
212 * same as the corresponding UNIX name "config"
214 * Revision 1.57 2001/11/16 00:47:43 jongfoster
215 * Changing the tty-disconnection code to use setsid().
217 * Revision 1.56 2001/11/13 20:20:54 jongfoster
218 * Tabs->spaces, fixing a bug with missing {} around an if()
220 * Revision 1.55 2001/11/13 20:14:53 jongfoster
221 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
223 * Revision 1.54 2001/11/07 00:03:14 steudten
224 * Give reliable return value if an error
225 * occurs not just 0 with new daemon mode.
227 * Revision 1.53 2001/11/05 21:41:43 steudten
228 * Add changes to be a real daemon just for unix os.
229 * (change cwd to /, detach from controlling tty, set
230 * process group and session leader to the own process.
232 * Add some fatal-error log message for failed malloc().
233 * Add '-d' if compiled with 'configure --with-debug' to
234 * enable debug output.
236 * Revision 1.52 2001/10/26 20:11:20 jongfoster
237 * Fixing type mismatch
239 * Revision 1.51 2001/10/26 17:38:28 oes
242 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
243 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
244 * threads to call select() simultaneously. So, it's time to do a real, live,
245 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
246 * (native). Both versions will work, but using __OS2__ offers multi-threading.
248 * Revision 1.49 2001/10/23 21:41:35 jongfoster
249 * Added call to initialize the (statically-allocated of course)
250 * "out of memory" CGI response.
252 * Revision 1.48 2001/10/10 19:56:46 jongfoster
253 * Moving some code that wasn't cookie-related out of an #ifdef
256 * Revision 1.47 2001/10/10 16:44:36 oes
257 * Added CONNECT destination port limitation check
259 * Revision 1.46 2001/10/08 15:17:41 oes
260 * Re-enabled SSL forwarding
262 * Revision 1.45 2001/10/07 15:42:11 oes
263 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
265 * Moved downgrading of the HTTP version from parse_http_request to
266 * chat(), since we can't decide if it is necessary before we have
267 * determined the actions for the URL. The HTTP command is now
268 * *always* re-built so the repairs need no longer be special-cased.
270 * filter_popups now gets a csp pointer so it can raise the new
271 * CSP_FLAG_MODIFIED flag.
275 * Added configurable size limit for the IOB. If the IOB grows so
276 * large that the next read would exceed the limit, the header
277 * is generated, and the header & unfiltered buffer are flushed
278 * to the client. Chat then continues in non-buffering,
279 * non-filtering body mode.
281 * Revision 1.44 2001/10/02 18:13:57 oes
284 * Revision 1.43 2001/10/02 15:32:13 oes
285 * Moved generation of hdr
287 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
288 * Cleaning up 2 compiler warnings on OS/2.
290 * Revision 1.41 2001/09/16 17:05:14 jongfoster
291 * Removing unused #include showarg.h
293 * Revision 1.40 2001/09/16 15:41:45 jongfoster
294 * Fixing signed/unsigned comparison warning.
296 * Revision 1.39 2001/09/16 13:21:27 jongfoster
297 * Changes to use new list functions.
299 * Revision 1.38 2001/09/16 13:01:46 jongfoster
300 * Removing redundant function call that zeroed zalloc()'d memory.
302 * Revision 1.37 2001/09/10 11:12:24 oes
303 * Deleted unused variable
305 * Revision 1.36 2001/09/10 10:56:15 oes
306 * Silenced compiler warnings
308 * Revision 1.35 2001/07/31 14:44:22 oes
309 * Deleted unused size parameter from filter_popups()
311 * Revision 1.34 2001/07/30 22:08:36 jongfoster
312 * Tidying up #defines:
313 * - All feature #defines are now of the form FEATURE_xxx
314 * - Permanently turned off WIN_GUI_EDIT
315 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
317 * Revision 1.33 2001/07/29 19:32:00 jongfoster
318 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
320 * Revision 1.32 2001/07/29 18:47:05 jongfoster
321 * Adding missing #include "loadcfg.h"
323 * Revision 1.31 2001/07/29 12:17:48 oes
324 * Applied pthread fix by Paul Lieverse
326 * Revision 1.30 2001/07/25 22:57:13 jongfoster
327 * __BEOS__ no longer overrides FEATURE_PTHREAD.
328 * This is because FEATURE_PTHREAD will soon be widely used, so I
329 * want to keep it simple.
331 * Revision 1.29 2001/07/24 12:47:06 oes
332 * Applied BeOS support update by Eugenia
334 * Revision 1.28 2001/07/23 13:26:12 oes
335 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
337 * Revision 1.27 2001/07/19 19:09:47 haroon
338 * - Added code to take care of the situation where while processing the first
339 * server response (which includes the server header), after finding the end
340 * of the headers we were not looking past the end of the headers for
341 * content modification. I enabled it for filter_popups.
342 * Someone else should look to see if other similar operations should be
343 * done to the discarded portion of the buffer.
345 * Note 2001/07/20: No, the other content modification mechanisms will process
346 * the whole iob later anyway. --oes
348 * Revision 1.26 2001/07/18 12:31:36 oes
351 * Revision 1.25 2001/07/15 19:43:49 jongfoster
352 * Supports POSIX threads.
353 * Also removed some unused #includes.
355 * Revision 1.24 2001/07/13 14:00:40 oes
356 * - Generic content modification scheme:
357 * Each feature has its own applicability flag that is set
358 * from csp->action->flags.
359 * Replaced the "filtering" int flag , by a function pointer
360 * "content_filter" to the function that will do the content
361 * modification. If it is != NULL, the document will be buffered
362 * and processed through *content_filter, which must set
363 * csp->content_length and return a modified copy of the body
364 * or return NULL (on failiure).
365 * - Changed csp->is_text to the more generic bitmap csp->content_type
366 * which can currently take the valued CT_TEXT or CT_GIF
368 * - Removed all #ifdef PCRS
370 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
371 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
372 * the `block_acl' call. This prevents a compilation error when the user
373 * does not wish to use the "ACL" feature.
375 * Revision 1.22 2001/06/29 21:45:41 oes
376 * Indentation, CRLF->LF, Tab-> Space
378 * Revision 1.21 2001/06/29 13:29:36 oes
379 * - Cleaned up, improved comments
380 * - Unified all possible interceptors (CGI,
381 * block, trust, fast_redirect) in one
382 * place, with one (CGI) answer generation
383 * mechansim. Much clearer now.
384 * - Removed the GIF image generation, which
385 * is now done in filters.c:block_url()
386 * - Made error conditions like domain lookup
387 * failiure or (various) problems while talking
388 * to the server use cgi.c:error_response()
389 * instead of generating HTML/HTTP in chat() (yuck!)
390 * - Removed logentry from cancelled commit
392 * Revision 1.20 2001/06/09 10:55:28 jongfoster
393 * Changing BUFSIZ ==> BUFFER_SIZE
395 * Revision 1.19 2001/06/07 23:12:52 jongfoster
396 * Replacing function pointer in struct gateway with a directly
397 * called function forwarded_connect().
398 * Replacing struct gateway with struct forward_spec
400 * Revision 1.18 2001/06/03 19:12:16 oes
401 * introduced new cgi handling
403 * Revision 1.17 2001/06/01 20:07:23 jongfoster
404 * Now uses action +image-blocker{} rather than config->tinygif
406 * Revision 1.16 2001/06/01 18:49:17 jongfoster
407 * Replaced "list_share" with "list" - the tiny memory gain was not
408 * worth the extra complexity.
410 * Revision 1.15 2001/05/31 21:24:47 jongfoster
411 * Changed "permission" to "action" throughout.
412 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
413 * Moved vanilla wafer check into chat(), since we must now
414 * decide whether or not to add it based on the URL.
416 * Revision 1.14 2001/05/29 20:14:01 joergs
417 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
420 * Revision 1.13 2001/05/29 09:50:24 jongfoster
421 * Unified blocklist/imagelist/permissionslist.
422 * File format is still under discussion, but the internal changes
425 * Also modified interceptor behaviour:
426 * - We now intercept all URLs beginning with one of the following
427 * prefixes (and *only* these prefixes):
429 * * http://ijbswa.sf.net/config/
430 * * http://ijbswa.sourceforge.net/config/
431 * - New interceptors "home page" - go to http://i.j.b/ to see it.
432 * - Internal changes so that intercepted and fast redirect pages
433 * are not replaced with an image.
434 * - Interceptors now have the option to send a binary page direct
435 * to the client. (i.e. ijb-send-banner uses this)
436 * - Implemented show-url-info interceptor. (Which is why I needed
437 * the above interceptors changes - a typical URL is
438 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
439 * The previous mechanism would not have intercepted that, and
440 * if it had been intercepted then it then it would have replaced
443 * Revision 1.12 2001/05/27 22:17:04 oes
445 * - re_process_buffer no longer writes the modified buffer
446 * to the client, which was very ugly. It now returns the
447 * buffer, which it is then written by chat.
449 * - content_length now adjusts the Content-Length: header
450 * for modified documents rather than crunch()ing it.
451 * (Length info in csp->content_length, which is 0 for
452 * unmodified documents)
454 * - For this to work, sed() is called twice when filtering.
456 * Revision 1.11 2001/05/26 17:27:53 jongfoster
457 * Added support for CLF and fixed LOG_LEVEL_LOG.
458 * Also did CRLF->LF fix of my previous patch.
460 * Revision 1.10 2001/05/26 15:26:15 jongfoster
461 * ACL feature now provides more security by immediately dropping
462 * connections from untrusted hosts.
464 * Revision 1.9 2001/05/26 00:28:36 jongfoster
465 * Automatic reloading of config file.
466 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
467 * Most of the global variables have been moved to a new
468 * struct configuration_spec, accessed through csp->config->globalname
469 * Most of the globals remaining are used by the Win32 GUI.
471 * Revision 1.8 2001/05/25 22:43:18 jongfoster
472 * Fixing minor memory leak and buffer overflow.
474 * Revision 1.7 2001/05/25 22:34:30 jongfoster
477 * Revision 1.6 2001/05/23 00:13:58 joergs
478 * AmigaOS support fixed.
480 * Revision 1.5 2001/05/22 18:46:04 oes
482 * - Enabled filtering banners by size rather than URL
483 * by adding patterns that replace all standard banner
484 * sizes with the "Junkbuster" gif to the re_filterfile
486 * - Enabled filtering WebBugs by providing a pattern
487 * which kills all 1x1 images
489 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
490 * which is selected by the (nonstandard and therefore
491 * capital) letter 'U' in the option string.
492 * It causes the quantifiers to be ungreedy by default.
493 * Appending a ? turns back to greedy (!).
495 * - Added a new interceptor ijb-send-banner, which
496 * sends back the "Junkbuster" gif. Without imagelist or
497 * MSIE detection support, or if tinygif = 1, or the
498 * URL isn't recognized as an imageurl, a lame HTML
499 * explanation is sent instead.
501 * - Added new feature, which permits blocking remote
502 * script redirects and firing back a local redirect
504 * The feature is conditionally compiled, i.e. it
505 * can be disabled with --disable-fast-redirects,
506 * plus it must be activated by a "fast-redirects"
507 * line in the config file, has its own log level
508 * and of course wants to be displayed by show-proxy-args
509 * Note: Boy, all the #ifdefs in 1001 locations and
510 * all the fumbling with configure.in and acconfig.h
511 * were *way* more work than the feature itself :-(
513 * - Because a generic redirect template was needed for
514 * this, tinygif = 3 now uses the same.
516 * - Moved GIFs, and other static HTTP response templates
521 * - Removed some >400 CRs again (Jon, you really worked
524 * Revision 1.4 2001/05/21 19:34:01 jongfoster
525 * Made failure to bind() a fatal error.
527 * Revision 1.3 2001/05/20 01:21:20 jongfoster
528 * Version 2.9.4 checkin.
529 * - Merged popupfile and cookiefile, and added control over PCRS
530 * filtering, in new "permissionsfile".
531 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
532 * file error you now get a message box (in the Win32 GUI) rather
533 * than the program exiting with no explanation.
534 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
536 * - Removed tabs from "config"
537 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
538 * - Bumped up version number.
540 * Revision 1.2 2001/05/17 22:34:44 oes
541 * - Added hint on GIF char array generation to jcc.c
542 * - Cleaned CRLF's from the sources and related files
543 * - Repaired logging for REF and FRC
545 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
546 * Initial import of version 2.9.3 source tree
549 *********************************************************************/
555 #include <sys/types.h>
562 #ifdef FEATURE_PTHREAD
564 #endif /* def FEATURE_PTHREAD */
567 # ifndef FEATURE_PTHREAD
571 # include <windows.h>
572 # include <process.h>
573 # endif /* ndef FEATURE_PTHREAD */
576 # ifndef _WIN_CONSOLE
578 # endif /* ndef _WIN_CONSOLE */
580 #else /* ifndef _WIN32 */
582 # if !defined (__OS2__)
584 # include <sys/wait.h>
585 # endif /* ndef __OS2__ */
586 # include <sys/time.h>
587 # include <sys/stat.h>
588 # include <sys/ioctl.h>
591 #include <sys/termios.h>
602 # include <socket.h> /* BeOS has select() for sockets only. */
603 # include <OS.h> /* declarations for threads and stuff. */
606 # if defined(__EMX__) || defined(__OS2__)
607 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
612 #define bzero(B,N) memset(B,0x00,n)
627 #include "killpopup.h"
628 #include "miscutil.h"
630 #include "jbsockets.h"
635 #include "urlmatch.h"
637 const char jcc_h_rcs[] = JCC_H_VERSION;
638 const char project_h_rcs[] = PROJECT_H_VERSION;
641 struct client_state clients[1];
642 struct file_list files[1];
644 #ifdef FEATURE_STATISTICS
645 int urls_read = 0; /* total nr of urls read inc rejected */
646 int urls_rejected = 0; /* total nr of urls rejected */
647 #endif /* def FEATURE_STATISTICS */
649 #ifdef FEATURE_GRACEFUL_TERMINATION
653 static void listen_loop(void);
654 static void chat(struct client_state *csp);
656 void serve(struct client_state *csp);
657 #else /* ifndef AMIGA */
658 static void serve(struct client_state *csp);
659 #endif /* def AMIGA */
662 static int32 server_thread(void *data);
663 #endif /* def __BEOS__ */
666 #define sleep(N) Sleep(((N) * 1000))
670 #define sleep(N) DosSleep(((N) * 100))
675 * Hit OSX over the head with a hammer. Protect all *_r functions.
677 pthread_mutex_t gmtime_mutex;
678 pthread_mutex_t localtime_mutex;
679 pthread_mutex_t gethostbyaddr_mutex;
680 pthread_mutex_t gethostbyname_mutex;
681 #endif /* def OSX_DARWIN */
683 #if defined(unix) || defined(__EMX__)
685 const char *pidfile = NULL;
686 int received_hup_signal = 0;
687 #endif /* defined unix */
689 /* The vanilla wafer. */
690 static const char VANILLA_WAFER[] =
691 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
692 "Do_not_send_me_any_copyrighted_information_other_than_the_"
693 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
694 "In_particular_do_not_send_me_any_cookies_that_"
695 "are_subject_to_a_claim_of_copyright_by_anybody._"
696 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
697 "(copyright_or_otherwise)_applying_to_any_cookie._";
700 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
701 /*********************************************************************
703 * Function : sig_handler
705 * Description : Signal handler for different signals.
706 * Exit gracefully on ABRT, TERM and INT
707 * or set a flag that will cause the errlog
708 * to be reopened by the main thread on HUP.
711 * 1 : the_signal = the signal cause this function to call
715 *********************************************************************/
716 static void sig_handler(int the_signal)
723 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
731 received_hup_signal = 1;
736 * We shouldn't be here, unless we catch signals
737 * in main() that we can't handle here!
739 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
747 /*********************************************************************
751 * Description : Once a connection to the client has been accepted,
752 * this function is called (via serve()) to handle the
753 * main business of the communication. When this
754 * function returns, the caller must close the client
758 * 1 : csp = Current client state (buffers, headers, etc...)
760 * Returns : On success, the number of bytes written are returned (zero
761 * indicates nothing was written). On error, -1 is returned,
762 * and errno is set appropriately. If count is zero and the
763 * file descriptor refers to a regular file, 0 will be
764 * returned without causing any other effect. For a special
765 * file, the results are not portable.
767 *********************************************************************/
768 static void chat(struct client_state *csp)
771 * This next lines are a little ugly, but they simplifies the if statements
772 * below. Basically if TOGGLE, then we want the if to test if the
773 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
774 * then we want the if to test for CSP_FLAG_FORCED , else we don't
776 #ifdef FEATURE_TOGGLE
777 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
778 #else /* ifndef FEATURE_TOGGLE */
779 # define IS_TOGGLED_ON_AND
780 #endif /* ndef FEATURE_TOGGLE */
781 #ifdef FEATURE_FORCE_LOAD
782 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
783 #else /* ifndef FEATURE_FORCE_LOAD */
784 # define IS_NOT_FORCED_AND
785 #endif /* def FEATURE_FORCE_LOAD */
787 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
789 char buf[BUFFER_SIZE];
797 int ms_iis5_hack = 0;
799 const struct forward_spec * fwd;
800 struct http_request *http;
801 int len; /* for buffer sizes */
802 #ifdef FEATURE_KILL_POPUPS
803 int block_popups; /* bool, 1==will block popups */
804 int block_popups_now = 0; /* bool, 1==currently blocking popups */
805 #endif /* def FEATURE_KILL_POPUPS */
807 int pcrs_filter; /* bool, 1==will filter through pcrs */
808 int gif_deanimate; /* bool, 1==will deanimate gifs */
810 /* Function that does the content filtering for the current request */
811 char *(*content_filter)() = NULL;
813 /* Skeleton for HTTP response, if we should intercept the request */
814 struct http_response *rsp;
819 * Read the client's request. Note that since we're not using select() we
820 * could get blocked here if a client connected, then didn't say anything!
825 len = read_socket(csp->cfd, buf, sizeof(buf));
827 if (len <= 0) break; /* error! */
830 * If there is no memory left for buffering the
831 * request, there is nothing we can do but hang up
833 if (add_to_iob(csp, buf, len))
838 req = get_header(csp);
842 break; /* no HTTP request! */
847 continue; /* more to come! */
850 #ifdef FEATURE_FORCE_LOAD
851 /* If this request contains the FORCE_PREFIX,
852 * better get rid of it now and set the force flag --oes
855 if (strstr(req, FORCE_PREFIX))
857 strclean(req, FORCE_PREFIX);
858 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
859 csp->flags |= CSP_FLAG_FORCED;
862 #endif /* def FEATURE_FORCE_LOAD */
864 parse_http_request(req, http, csp);
869 if (http->cmd == NULL)
871 strcpy(buf, CHEADER);
872 write_socket(csp->cfd, buf, strlen(buf));
874 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
876 free_http_request(http);
880 /* decide how to route the HTTP request */
882 if ((fwd = forward_url(http, csp)) == NULL)
884 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
885 /* Never get here - LOG_LEVEL_FATAL causes program exit */
888 /* build the http request to send to the server
889 * we have to do one of the following:
891 * create = use the original HTTP request to create a new
892 * HTTP request that has either the path component
893 * without the http://domainspec (w/path) or the
894 * full orininal URL (w/url)
895 * Note that the path and/or the HTTP version may
896 * have been altered by now.
898 * connect = Open a socket to the host:port of the server
899 * and short-circuit server and client socket.
901 * pass = Pass the request unchanged if forwarding a CONNECT
902 * request to a parent proxy. Note that we'll be sending
903 * the CFAIL message ourselves if connecting to the parent
904 * fails, but we won't send a CSUCCEED message if it works,
905 * since that would result in a double message (ours and the
906 * parent's). After sending the request to the parent, we simply
912 * +--------+--------+
914 * 0 | create | connect|
916 * Forwarding +--------+--------+
918 * 1 | create | pass |
920 * +--------+--------+
925 * Determine the actions for this URL
927 #ifdef FEATURE_TOGGLE
928 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
930 /* Most compatible set of actions (i.e. none) */
931 init_current_action(csp->action);
934 #endif /* ndef FEATURE_TOGGLE */
936 url_actions(http, csp);
941 * Check if a CONNECT request is allowable:
942 * In the absence of a +limit-connect action, allow only port 443.
943 * If there is an action, allow whatever matches the specificaton.
947 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
948 || (csp->action->flags & ACTION_LIMIT_CONNECT
949 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
951 strcpy(buf, CFORBIDDEN);
952 write_socket(csp->cfd, buf, strlen(buf));
954 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
955 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
963 * Downgrade http version from 1.1 to 1.0 if +downgrade
966 if ( (http->ssl == 0)
967 && (!strcmpic(http->ver, "HTTP/1.1"))
968 && (csp->action->flags & ACTION_DOWNGRADE))
971 http->ver = strdup("HTTP/1.0");
973 if (http->ver == NULL)
975 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
980 * Save a copy of the original request for logging
982 http->ocmd = strdup(http->cmd);
984 if (http->ocmd == NULL)
986 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
990 * (Re)build the HTTP request for non-SSL requests.
991 * If forwarding, use the whole URL, else, use only the path.
997 http->cmd = strdup(http->gpc);
998 string_append(&http->cmd, " ");
1000 if (fwd->forward_host)
1002 string_append(&http->cmd, http->url);
1006 string_append(&http->cmd, http->path);
1008 string_append(&http->cmd, " ");
1009 string_append(&http->cmd, http->ver);
1011 if (http->cmd == NULL)
1013 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1015 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", http->cmd);
1017 enlist(csp->headers, http->cmd);
1021 * If the user has not supplied any wafers, and the user has not
1022 * told us to suppress the vanilla wafer, then send the vanilla wafer.
1024 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
1025 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
1027 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
1031 #ifdef FEATURE_KILL_POPUPS
1032 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1033 #endif /* def FEATURE_KILL_POPUPS */
1035 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
1036 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1038 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1040 /* grab the rest of the client's headers */
1044 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
1046 len = read_socket(csp->cfd, buf, sizeof(buf));
1049 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1054 * If there is no memory left for buffering the
1055 * request, there is nothing we can do but hang up
1057 if (add_to_iob(csp, buf, len))
1064 if (p == NULL) break;
1066 enlist(csp->headers, p);
1071 * We have a request. Now, check to see if we need to
1072 * intercept it, i.e. If ..
1076 /* We may not forward the request by rfc2616 sect 14.31 */
1077 (NULL != (rsp = direct_response(csp)))
1079 /* or a CGI call was detected and answered */
1080 || (NULL != (rsp = dispatch_cgi(csp)))
1082 /* or we are enabled and... */
1083 || (IS_ENABLED_AND (
1085 /* ..the request was blocked */
1086 ( NULL != (rsp = block_url(csp)))
1088 /* ..or untrusted */
1089 #ifdef FEATURE_TRUST
1090 || ( NULL != (rsp = trust_url(csp)))
1091 #endif /* def FEATURE_TRUST */
1093 /* ..or a fast redirect kicked in */
1094 #ifdef FEATURE_FAST_REDIRECTS
1095 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
1096 (NULL != (rsp = redirect_url(csp))))
1097 #endif /* def FEATURE_FAST_REDIRECTS */
1101 /* Write the answer to the client */
1102 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1103 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1105 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1108 #ifdef FEATURE_STATISTICS
1109 /* Count as a rejected request */
1110 csp->flags |= CSP_FLAG_REJECTED;
1111 #endif /* def FEATURE_STATISTICS */
1113 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
1114 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1115 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1117 /* Clean up and return */
1118 free_http_response(rsp);
1122 hdr = sed(client_patterns, add_client_headers, csp);
1125 /* FIXME Should handle error properly */
1126 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1129 list_remove_all(csp->headers);
1131 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1133 if (fwd->forward_host)
1135 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1136 fwd->forward_host, fwd->forward_port, http->hostport);
1140 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1143 /* here we connect to the server, gateway, or the forwarder */
1145 csp->sfd = forwarded_connect(fwd, http, csp);
1147 if (csp->sfd == JB_INVALID_SOCKET)
1149 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1152 if (errno == EINVAL)
1154 rsp = error_response(csp, "no-such-domain", errno);
1156 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1157 csp->ip_addr_str, http->ocmd);
1161 rsp = error_response(csp, "connect-failed", errno);
1163 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1164 csp->ip_addr_str, http->ocmd);
1168 /* Write the answer to the client */
1171 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1172 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1174 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1178 free_http_response(rsp);
1183 log_error(LOG_LEVEL_CONNECT, "OK");
1185 if (fwd->forward_host || (http->ssl == 0))
1187 /* write the client's (modified) header to the server
1188 * (along with anything else that may be in the buffer)
1191 if (write_socket(csp->sfd, hdr, strlen(hdr))
1192 || (flush_socket(csp->sfd, csp) < 0))
1194 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1197 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1198 csp->ip_addr_str, http->ocmd);
1200 rsp = error_response(csp, "connect-failed", errno);
1204 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1205 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1207 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1211 free_http_response(rsp);
1219 * We're running an SSL tunnel and we're not forwarding,
1220 * so just send the "connect succeeded" message to the
1221 * client, flush the rest, and get out of the way.
1223 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1224 csp->ip_addr_str, http->ocmd);
1226 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1234 /* we're finished with the client's header */
1237 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1239 /* pass data between the client and server
1240 * until one or the other shuts down the connection.
1249 * FD_ZERO here seems to point to an errant macro which crashes.
1250 * So do this by hand for now...
1252 memset(&rfds,0x00,sizeof(fd_set));
1256 FD_SET(csp->cfd, &rfds);
1257 FD_SET(csp->sfd, &rfds);
1259 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1263 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1267 /* this is the body of the browser's request
1268 * just read it and write it.
1271 if (FD_ISSET(csp->cfd, &rfds))
1273 len = read_socket(csp->cfd, buf, sizeof(buf));
1277 break; /* "game over, man" */
1280 if (write_socket(csp->sfd, buf, (size_t)len))
1282 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1289 * The server wants to talk. It could be the header or the body.
1290 * If `hdr' is null, then it's the header otherwise it's the body.
1291 * FIXME: Does `hdr' really mean `host'? No.
1295 if (FD_ISSET(csp->sfd, &rfds))
1298 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1302 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1304 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1305 csp->ip_addr_str, http->ocmd);
1307 rsp = error_response(csp, "connect-failed", errno);
1311 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1312 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1314 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1318 free_http_response(rsp);
1322 /* Add a trailing zero. This lets filter_popups
1323 * use string operations.
1327 #ifdef FEATURE_KILL_POPUPS
1328 /* Filter the popups on this read. */
1329 if (block_popups_now)
1331 filter_popups(buf, csp);
1333 #endif /* def FEATURE_KILL_POPUPS */
1335 /* Normally, this would indicate that we've read
1336 * as much as the server has sent us and we can
1337 * close the client connection. However, Microsoft
1338 * in its wisdom has released IIS/5 with a bug that
1339 * prevents it from sending the trailing \r\n in
1340 * a 302 redirect header (and possibly other headers).
1341 * To work around this if we've haven't parsed
1342 * a full header we'll append a trailing \r\n
1343 * and see if this now generates a valid one.
1345 * This hack shouldn't have any impacts. If we've
1346 * already transmitted the header or if this is a
1347 * SSL connection, then we won't bother with this
1348 * hack. So we only work on partially received
1349 * headers. If we append a \r\n and this still
1350 * doesn't generate a valid header, then we won't
1351 * transmit anything to the client.
1356 if (server_body || http->ssl)
1359 * If we have been buffering up the document,
1360 * now is the time to apply content modification
1361 * and send the result to the client.
1366 * If the content filter fails, use the original
1367 * buffer and length.
1368 * (see p != NULL ? p : csp->iob->cur below)
1370 if (NULL == (p = (*content_filter)(csp)))
1372 csp->content_length = csp->iob->eod - csp->iob->cur;
1375 hdr = sed(server_patterns, add_server_headers, csp);
1378 /* FIXME Should handle error properly */
1379 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1382 if (write_socket(csp->cfd, hdr, strlen(hdr))
1383 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1385 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1395 break; /* "game over, man" */
1399 * This is NOT the body, so
1400 * Let's pretend the server just sent us a blank line.
1402 len = sprintf(buf, "\r\n");
1405 * Now, let the normal header parsing algorithm below do its
1406 * job. If it fails, we'll exit instead of continuing.
1413 * If this is an SSL connection or we're in the body
1414 * of the server document, just write it to the client,
1415 * unless we need to buffer the body for later content-filtering
1418 if (server_body || http->ssl)
1423 * If there is no memory left for buffering the content, or the buffer limit
1424 * has been reached, switch to non-filtering mode, i.e. make & write the
1425 * header, flush the iob and buf, and get out of the way.
1427 if (add_to_iob(csp, buf, len))
1432 log_error(LOG_LEVEL_ERROR, "Flushing header and buffers. Stepping back from filtering.");
1434 hdr = sed(server_patterns, add_server_headers, csp);
1438 * Memory is too tight to even generate the header.
1439 * Send our static "Out-of-memory" page.
1441 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
1442 rsp = cgi_error_memory();
1444 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1445 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1447 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1452 hdrlen = strlen(hdr);
1454 if (write_socket(csp->cfd, hdr, hdrlen)
1455 || ((flushed = flush_socket(csp->cfd, csp)) < 0)
1456 || (write_socket(csp->cfd, buf, len)))
1458 log_error(LOG_LEVEL_CONNECT, "Flush header and buffers to client failed: %E");
1464 byte_count += hdrlen + flushed + len;
1466 content_filter = NULL;
1473 if (write_socket(csp->cfd, buf, (size_t)len))
1475 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1484 /* we're still looking for the end of the
1485 * server's header ... (does that make header
1486 * parsing an "out of body experience" ?
1490 * buffer up the data we just read. If that fails,
1491 * there's little we can do but send our static
1492 * out-of-memory page.
1494 if (add_to_iob(csp, buf, len))
1496 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
1497 rsp = cgi_error_memory();
1499 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1500 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1502 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1507 /* get header lines from the iob */
1509 while ((p = get_header(csp)) != NULL)
1513 /* see following note */
1516 enlist(csp->headers, p);
1520 /* NOTE: there are no "empty" headers so
1521 * if the pointer `p' is not NULL we must
1522 * assume that we reached the end of the
1523 * buffer before we hit the end of the header.
1530 /* Well, we tried our MS IIS/5
1531 * hack and it didn't work.
1532 * The header is incomplete
1533 * and there isn't anything
1534 * we can do about it.
1540 /* Since we have to wait for
1541 * more from the server before
1542 * we can parse the headers
1543 * we just continue here.
1549 /* we have now received the entire header.
1550 * filter it and send the result to the client
1553 hdr = sed(server_patterns, add_server_headers, csp);
1556 /* FIXME Should handle error properly */
1557 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1560 #ifdef FEATURE_KILL_POPUPS
1561 /* Start blocking popups if appropriate. */
1563 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1564 !http->ssl && /* We talk plaintext */
1565 block_popups) /* Policy allows */
1567 block_popups_now = 1;
1569 * Filter the part of the body that came in the same read
1570 * as the last headers:
1572 filter_popups(csp->iob->cur, csp);
1575 #endif /* def FEATURE_KILL_POPUPS */
1577 /* Buffer and pcrs filter this if appropriate. */
1579 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1580 !http->ssl && /* We talk plaintext */
1581 pcrs_filter) /* Policy allows */
1583 content_filter = pcrs_filter_response;
1586 /* Buffer and gif_deanimate this if appropriate. */
1588 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1589 !http->ssl && /* We talk plaintext */
1590 gif_deanimate) /* Policy allows */
1592 content_filter = gif_deanimate_response;
1596 * Only write if we're not buffering for content modification
1598 if (!content_filter)
1600 /* write the server's (modified) header to
1601 * the client (along with anything else that
1602 * may be in the buffer)
1605 if (write_socket(csp->cfd, hdr, strlen(hdr))
1606 || ((len = flush_socket(csp->cfd, csp)) < 0))
1608 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1610 /* the write failed, so don't bother
1611 * mentioning it to the client...
1612 * it probably can't hear us anyway.
1621 /* we're finished with the server's header */
1626 /* If this was a MS IIS/5 hack then it means
1627 * the server has already closed the
1628 * connection. Nothing more to read. Time
1639 return; /* huh? we should never get here */
1642 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1643 csp->ip_addr_str, http->ocmd, byte_count);
1647 /*********************************************************************
1651 * Description : This is little more than chat. We only "serve" to
1652 * to close any socket that chat may have opened.
1655 * 1 : csp = Current client state (buffers, headers, etc...)
1659 *********************************************************************/
1661 void serve(struct client_state *csp)
1662 #else /* ifndef AMIGA */
1663 static void serve(struct client_state *csp)
1664 #endif /* def AMIGA */
1667 close_socket(csp->cfd);
1669 if (csp->sfd != JB_INVALID_SOCKET)
1671 close_socket(csp->sfd);
1674 csp->flags &= ~CSP_FLAG_ACTIVE;
1680 /*********************************************************************
1682 * Function : server_thread
1684 * Description : We only exist to call `serve' in a threaded environment.
1687 * 1 : data = Current client state (buffers, headers, etc...)
1689 * Returns : Always 0.
1691 *********************************************************************/
1692 static int32 server_thread(void *data)
1694 serve((struct client_state *) data);
1701 /*********************************************************************
1705 * Description : Print usage info & exit.
1707 * Parameters : Pointer to argv[0] for identifying ourselves
1711 *********************************************************************/
1712 void usage(const char *myname)
1714 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
1715 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1716 "Aborting.\n", myname);
1723 /*********************************************************************
1727 * Description : Load the config file and start the listen loop.
1728 * This function is a lot more *sane* with the `load_config'
1729 * and `listen_loop' functions; although it stills does
1730 * a *little* too much for my taste.
1733 * 1 : argc = Number of parameters (including $0).
1734 * 2 : argv = Array of (char *)'s to the parameters.
1736 * Returns : 1 if : can't open config file, unrecognized directive,
1737 * stats requested in multi-thread mode, can't open the
1738 * log file, can't open the jar file, listen port is invalid,
1739 * any load fails, and can't bind port.
1741 * Else main never returns, the process must be signaled
1742 * to terminate execution. Or, on Windows, use the
1743 * "File", "Exit" menu option.
1745 *********************************************************************/
1747 int real_main(int argc, const char *argv[])
1749 int main(int argc, const char *argv[])
1754 struct passwd *pw = NULL;
1755 struct group *grp = NULL;
1763 #if !defined(_WIN32)
1771 * Parse the command line arguments
1773 while (++argc_pos < argc)
1775 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1777 if (strcmp(argv[argc_pos], "--help") == 0)
1782 else if(strcmp(argv[argc_pos], "--version") == 0)
1784 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1788 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1793 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1795 if (++argc_pos == argc) usage(argv[0]);
1796 pidfile = strdup(argv[argc_pos]);
1799 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1801 if (++argc_pos == argc) usage(argv[argc_pos]);
1803 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1806 if (NULL == (grp = getgrnam(p)))
1808 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1812 if (NULL == (pw = getpwnam(argv[argc_pos])))
1814 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1817 if (p != NULL) *--p = '\0';
1819 #endif /* defined(unix) */
1821 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1823 configfile = argv[argc_pos];
1826 } /* -END- while (more arguments) */
1829 if ( *configfile != '/' )
1833 /* make config-filename absolute here */
1834 if ( !(basedir = getcwd( NULL, 1024 )))
1836 perror("get working dir failed");
1840 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1842 perror("malloc failed");
1845 strcpy( abs_file, basedir );
1846 strcat( abs_file, "/" );
1847 strcat( abs_file, configfile );
1848 configfile = abs_file;
1850 #endif /* defined unix */
1854 clients->next = NULL;
1858 #elif defined(_WIN32)
1864 * Prepare global mutex semaphores
1866 pthread_mutex_init(&gmtime_mutex,0);
1867 pthread_mutex_init(&localtime_mutex,0);
1868 pthread_mutex_init(&gethostbyaddr_mutex,0);
1869 pthread_mutex_init(&gethostbyname_mutex,0);
1870 #endif /* def OSX_DARWIN */
1873 * Unix signal handling
1875 * Catch the abort, interrupt and terminate signals for a graceful exit
1876 * Catch the hangup signal so the errlog can be reopened.
1877 * Ignore the broken pipe and child signals
1878 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1880 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1883 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1884 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1886 for (idx = 0; catched_signals[idx] != 0; idx++)
1888 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1890 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1894 for (idx = 0; ignored_signals[idx] != 0; idx++)
1896 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1898 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1903 #else /* ifdef _WIN32 */
1904 # ifdef _WIN_CONSOLE
1906 * We *are* in a windows console app.
1907 * Print a verbose messages about FAQ's and such
1909 printf(win32_blurb);
1910 # endif /* def _WIN_CONSOLE */
1911 #endif /* def _WIN32 */
1914 /* Initialize the CGI subsystem */
1915 cgi_init_error_messages();
1918 * If runnig on unix and without the --nodaemon
1919 * option, become a daemon. I.e. fork, detach
1920 * from tty and get process group leadership
1933 if ( pid < 0 ) /* error */
1938 else if ( pid != 0 ) /* parent */
1943 * must check for errors
1944 * child died due to missing files aso
1947 wpid = waitpid( pid, &status, WNOHANG );
1956 /* Should be more portable, but not as well tested */
1961 #else /* ndef __FreeBSD__ */
1963 #endif /* ndef __FreeBSD__ */
1964 fd = open("/dev/tty", O_RDONLY);
1967 /* no error check here */
1968 ioctl( fd, TIOCNOTTY,0 );
1972 /* FIXME: should close stderr (fd 2) here too, but the test
1974 * and load config file is done in listen_loop() and puts
1975 * some messages on stderr there.
1982 } /* -END- if (!no_daemon) */
1985 * As soon as we have written the PID file, we can switch
1986 * to the user and group ID indicated by the --user option
1992 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1994 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1996 if (setuid(pw->pw_uid))
1998 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
2002 #endif /* defined unix */
2012 /*********************************************************************
2014 * Function : bind_port_helper
2016 * Description : Bind the listen port. Handles logging, and aborts
2020 * 1 : config = Privoxy configuration. Specifies port
2023 * Returns : Port that was opened.
2025 *********************************************************************/
2026 static jb_socket bind_port_helper(struct configuration_spec * config)
2031 if ( (config->haddr != NULL)
2032 && (config->haddr[0] == '1')
2033 && (config->haddr[1] == '2')
2034 && (config->haddr[2] == '7')
2035 && (config->haddr[3] == '.') )
2037 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
2040 else if (config->haddr == NULL)
2042 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
2047 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
2048 config->hport, config->haddr);
2051 result = bind_port(config->haddr, config->hport, &bfd);
2058 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2059 "There may be another Privoxy or some other "
2060 "proxy running on port %d",
2061 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
2062 config->hport, config->hport);
2065 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2066 "The hostname is not resolvable",
2067 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2070 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
2071 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2074 /* shouldn't get here */
2075 return JB_INVALID_SOCKET;
2078 config->need_bind = 0;
2084 /*********************************************************************
2086 * Function : listen_loop
2088 * Description : bind the listen port and enter a "FOREVER" listening loop.
2094 *********************************************************************/
2095 static void listen_loop(void)
2097 struct client_state *csp = NULL;
2099 struct configuration_spec * config;
2101 config = load_config();
2103 bfd = bind_port_helper(config);
2105 #ifdef FEATURE_GRACEFUL_TERMINATION
2106 while (!g_terminate)
2111 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
2112 while (waitpid(-1, NULL, WNOHANG) > 0)
2114 /* zombie children */
2116 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2119 * Free data that was used by died threads
2125 * Re-open the errlog after HUP signal
2127 if (received_hup_signal)
2129 init_error_log(Argv[0], config->logfile, config->debug);
2130 received_hup_signal = 0;
2135 #ifdef FEATURE_COOKIE_JAR
2137 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
2138 * already open. I think unload_configfile() is not being run, which should do
2139 * this work. Until that can get resolved, we'll use this workaround.
2143 if (csp->config->jar)
2145 fclose(csp->config->jar);
2146 csp->config->jar = NULL;
2148 #endif /* FEATURE_COOKIE_JAR */
2149 #endif /* __OS2__ */
2151 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2153 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2157 csp->flags |= CSP_FLAG_ACTIVE;
2158 csp->sfd = JB_INVALID_SOCKET;
2160 csp->config = config = load_config();
2162 if ( config->need_bind )
2165 * Since we were listening to the "old port", we will not see
2166 * a "listen" param change until the next IJB request. So, at
2167 * least 1 more request must be made for us to find the new
2168 * setting. I am simply closing the old socket and binding the
2171 * Which-ever is correct, we will serve 1 more page via the
2172 * old settings. This should probably be a "show-proxy-args"
2173 * request. This should not be a so common of an operation
2174 * that this will hurt people's feelings.
2179 bfd = bind_port_helper(config);
2182 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2184 if (!accept_connection(csp, bfd))
2186 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2199 log_error(LOG_LEVEL_CONNECT, "OK");
2202 #ifdef FEATURE_TOGGLE
2205 csp->flags |= CSP_FLAG_TOGGLED_ON;
2207 #endif /* def FEATURE_TOGGLE */
2209 if (run_loader(csp))
2211 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2212 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2216 if (block_acl(NULL,csp))
2218 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2219 close_socket(csp->cfd);
2223 #endif /* def FEATURE_ACL */
2225 /* add it to the list of clients */
2226 csp->next = clients->next;
2227 clients->next = csp;
2229 if (config->multi_threaded)
2233 /* this is a switch () statment in the C preprocessor - ugh */
2234 #undef SELECTED_ONE_OPTION
2236 /* Use Pthreads in preference to native code */
2237 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2238 #define SELECTED_ONE_OPTION
2240 pthread_t the_thread;
2241 pthread_attr_t attrs;
2243 pthread_attr_init(&attrs);
2244 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2245 child_id = (pthread_create(&the_thread, &attrs,
2246 (void*)serve, csp) ? -1 : 0);
2247 pthread_attr_destroy(&attrs);
2251 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2252 #define SELECTED_ONE_OPTION
2253 child_id = _beginthread(
2254 (void (*)(void *))serve,
2259 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2260 #define SELECTED_ONE_OPTION
2261 child_id = _beginthread(
2262 (void(* _Optlink)(void*))serve,
2268 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2269 #define SELECTED_ONE_OPTION
2271 thread_id tid = spawn_thread
2272 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2274 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2276 child_id = (int) tid;
2285 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2286 #define SELECTED_ONE_OPTION
2287 csp->cfd = ReleaseSocket(csp->cfd, -1);
2288 if((child_id = (int)CreateNewProcTags(
2289 NP_Entry, (ULONG)server_thread,
2290 NP_Output, Output(),
2291 NP_CloseOutput, FALSE,
2292 NP_Name, (ULONG)"privoxy child",
2293 NP_StackSize, 200*1024,
2297 ((struct Task *)child_id)->tc_UserData = csp;
2298 Signal((struct Task *)child_id, SIGF_SINGLE);
2303 #if !defined(SELECTED_ONE_OPTION)
2306 /* This block is only needed when using fork().
2307 * When using threads, the server thread was
2308 * created and run by the call to _beginthread().
2310 if (child_id == 0) /* child */
2316 else if (child_id > 0) /* parent */
2318 /* in a fork()'d environment, the parent's
2319 * copy of the client socket and the CSP
2323 #if !defined(_WIN32) && defined(__CYGWIN__)
2325 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2326 close_socket(csp->cfd);
2327 csp->flags &= ~CSP_FLAG_ACTIVE;
2331 #undef SELECTED_ONE_OPTION
2332 /* end of cpp switch () */
2334 if (child_id < 0) /* failed */
2336 char buf[BUFFER_SIZE];
2338 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2340 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
2342 write_socket(csp->cfd, buf, strlen(buf));
2343 close_socket(csp->cfd);
2344 csp->flags &= ~CSP_FLAG_ACTIVE;
2355 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2357 /* Clean up. Aim: free all memory (no leaks) */
2358 #ifdef FEATURE_GRACEFUL_TERMINATION
2360 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2362 unload_current_config_file();
2363 unload_current_actions_file();
2364 unload_current_re_filterfile();
2365 #ifdef FEATURE_TRUST
2366 unload_current_trust_file();
2369 if (config->multi_threaded)
2376 } while ((clients->next != NULL) && (--i > 0));
2380 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2389 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2390 /* Cleanup - remove taskbar icon etc. */
2395 #endif /* FEATURE_GRACEFUL_TERMINATION */