1 const char jcc_rcs[] = "$Id: jcc.c,v 1.92.2.4 2003/03/07 03:41:04 david__schmidt 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.4 2003/03/07 03:41:04 david__schmidt
37 * Wrapping all *_r functions (the non-_r versions of them) with mutex semaphores for OSX. Hopefully this will take care of all of those pesky crash reports.
39 * Revision 1.92.2.3 2003/02/28 12:53:06 oes
40 * Fixed two mostly harmless mem leaks
42 * Revision 1.92.2.2 2002/11/20 14:37:47 oes
43 * Fix: Head of global clients list now initialized to NULL
45 * Revision 1.92.2.1 2002/09/25 14:52:24 oes
46 * Added basic support for OPTIONS and TRACE HTTP methods:
47 * - New interceptor direct_response() added in chat().
48 * - sed() moved to earlier in the process, so that the
49 * Host: header is evaluated before actions and forwarding
52 * Revision 1.92 2002/05/08 16:00:46 oes
53 * Chat's buffer handling:
54 * - Fixed bug with unchecked out-of-mem conditions
55 * while reading client request & server headers
56 * - No longer predict if the buffer limit will be exceeded
57 * in the next read -- check add_to_iob's new
58 * return code. If buffer couldn't be extended
59 * (policy or out-of-mem) while
60 * - reading from client: abort
61 * - reading server headers: send error page
62 * - buffering server body for filter: flush,
63 * and if that fails: send error page
65 * Revision 1.91 2002/04/08 20:35:58 swa
68 * Revision 1.90 2002/04/02 14:57:28 oes
69 * Made sending wafers independent of FEATURE_COOKIE_JAR
71 * Revision 1.89 2002/03/31 17:18:59 jongfoster
72 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
74 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
75 * More compiler warning message maintenance
77 * Revision 1.87 2002/03/26 22:29:54 swa
78 * we have a new homepage!
80 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
81 * Workaround for closing the jarfile before load_config() comes around again
83 * Revision 1.85 2002/03/24 15:23:33 jongfoster
86 * Revision 1.84 2002/03/24 13:25:43 swa
87 * name change related issues
89 * Revision 1.83 2002/03/16 23:54:06 jongfoster
90 * Adding graceful termination feature, to help look for memory leaks.
91 * If you enable this (which, by design, has to be done by hand
92 * editing config.h) and then go to http://i.j.b/die, then the program
93 * will exit cleanly after the *next* request. It should free all the
94 * memory that was used.
96 * Revision 1.82 2002/03/13 00:27:05 jongfoster
99 * Revision 1.81 2002/03/12 01:42:50 oes
100 * Introduced modular filters
102 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
103 * OS/2 port maintenance:
104 * - Fixed EMX build - it had decayed a little
105 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
106 * substituted a memset for now.
108 * Revision 1.79 2002/03/09 20:03:52 jongfoster
109 * - Making various functions return int rather than size_t.
110 * (Undoing a recent change). Since size_t is unsigned on
111 * Windows, functions like read_socket that return -1 on
112 * error cannot return a size_t.
114 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
115 * crashes, and also frequently caused JB to jump to 100%
116 * CPU and stay there. (Because it thought it had just
117 * read ((unsigned)-1) == 4Gb of data...)
119 * - The signature of write_socket has changed, it now simply
120 * returns success=0/failure=nonzero.
122 * - Trying to get rid of a few warnings --with-debug on
123 * Windows, I've introduced a new type "jb_socket". This is
124 * used for the socket file descriptors. On Windows, this
125 * is SOCKET (a typedef for unsigned). Everywhere else, it's
126 * an int. The error value can't be -1 any more, so it's
127 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
128 * Windows it maps to the #define INVALID_SOCKET.)
130 * - The signature of bind_port has changed.
132 * Revision 1.78 2002/03/08 21:35:04 oes
133 * Added optional group supplement to --user option. Will now use default group of user if no group given
135 * Revision 1.77 2002/03/07 03:52:06 oes
136 * - Fixed compiler warnings etc
137 * - Improved handling of failed DNS lookups
139 * Revision 1.76 2002/03/06 22:54:35 jongfoster
140 * Automated function-comment nitpicking.
142 * Revision 1.75 2002/03/06 10:02:19 oes
143 * Fixed stupid bug when --user was not given
145 * Revision 1.74 2002/03/06 00:49:31 jongfoster
146 * Fixing warning on Windows
147 * Making #ifdefs that refer to the same variable consistently
148 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
150 * Revision 1.73 2002/03/05 23:57:30 hal9
151 * Stray character 's' on line 1618 was breaking build.
153 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
154 * - Re-enable OS/2 building after new parms were added
155 * - Fix false out of memory report when resolving CGI templates when no IP
156 * address is available of failed attempt (a la no such domain)
158 * Revision 1.71 2002/03/05 18:13:56 oes
159 * Added --user option
161 * Revision 1.70 2002/03/05 04:52:42 oes
162 * Deleted non-errlog debugging code
164 * Revision 1.69 2002/03/04 23:50:00 jongfoster
165 * Splitting off bind_port() call into bind_port_helper(), with
168 * Revision 1.68 2002/03/04 20:17:32 oes
171 * Revision 1.67 2002/03/04 18:18:57 oes
172 * - Removed _DEBUG mode
173 * - Cleand up cmdline parsing
174 * - Introduced --no-daemon, --pidfile options
175 * - Cleaned up signal handling:
176 * - Terminate cleanly on INT, TERM and ABRT
177 * - Schedule logfile for re-opening on HUP
178 * - Ignore CHLD and PIPE
179 * - Leave the rest with their default handlers
180 * - Uniform handler registration
181 * - Added usage() function
182 * - Played styleguide police
184 * Revision 1.66 2002/03/03 15:06:55 oes
185 * Re-enabled automatic config reloading
187 * Revision 1.65 2002/03/03 14:49:11 oes
188 * Fixed CLF logging: Now uses client's original HTTP request
190 * Revision 1.64 2002/03/03 09:18:03 joergs
191 * Made jumbjuster work on AmigaOS again.
193 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
194 * Clean up a little CRLF unpleasantness that suddenly appeared
196 * Revision 1.62 2002/02/20 23:17:23 jongfoster
197 * Detecting some out-of memory conditions and exiting with a log message.
199 * Revision 1.61 2002/01/17 21:01:52 jongfoster
200 * Moving all our URL and URL pattern parsing code to urlmatch.c.
202 * Revision 1.60 2001/12/30 14:07:32 steudten
203 * - Add signal handling (unix)
204 * - Add SIGHUP handler (unix)
205 * - Add creation of pidfile (unix)
206 * - Add action 'top' in rc file (RH)
207 * - Add entry 'SIGNALS' to manpage
208 * - Add exit message to logfile (unix)
210 * Revision 1.59 2001/12/13 14:07:18 oes
211 * Fixed Bug: 503 error page now sent OK
213 * Revision 1.58 2001/11/30 23:37:24 jongfoster
214 * Renaming the Win32 config file to config.txt - this is almost the
215 * same as the corresponding UNIX name "config"
217 * Revision 1.57 2001/11/16 00:47:43 jongfoster
218 * Changing the tty-disconnection code to use setsid().
220 * Revision 1.56 2001/11/13 20:20:54 jongfoster
221 * Tabs->spaces, fixing a bug with missing {} around an if()
223 * Revision 1.55 2001/11/13 20:14:53 jongfoster
224 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
226 * Revision 1.54 2001/11/07 00:03:14 steudten
227 * Give reliable return value if an error
228 * occurs not just 0 with new daemon mode.
230 * Revision 1.53 2001/11/05 21:41:43 steudten
231 * Add changes to be a real daemon just for unix os.
232 * (change cwd to /, detach from controlling tty, set
233 * process group and session leader to the own process.
235 * Add some fatal-error log message for failed malloc().
236 * Add '-d' if compiled with 'configure --with-debug' to
237 * enable debug output.
239 * Revision 1.52 2001/10/26 20:11:20 jongfoster
240 * Fixing type mismatch
242 * Revision 1.51 2001/10/26 17:38:28 oes
245 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
246 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
247 * threads to call select() simultaneously. So, it's time to do a real, live,
248 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
249 * (native). Both versions will work, but using __OS2__ offers multi-threading.
251 * Revision 1.49 2001/10/23 21:41:35 jongfoster
252 * Added call to initialize the (statically-allocated of course)
253 * "out of memory" CGI response.
255 * Revision 1.48 2001/10/10 19:56:46 jongfoster
256 * Moving some code that wasn't cookie-related out of an #ifdef
259 * Revision 1.47 2001/10/10 16:44:36 oes
260 * Added CONNECT destination port limitation check
262 * Revision 1.46 2001/10/08 15:17:41 oes
263 * Re-enabled SSL forwarding
265 * Revision 1.45 2001/10/07 15:42:11 oes
266 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
268 * Moved downgrading of the HTTP version from parse_http_request to
269 * chat(), since we can't decide if it is necessary before we have
270 * determined the actions for the URL. The HTTP command is now
271 * *always* re-built so the repairs need no longer be special-cased.
273 * filter_popups now gets a csp pointer so it can raise the new
274 * CSP_FLAG_MODIFIED flag.
278 * Added configurable size limit for the IOB. If the IOB grows so
279 * large that the next read would exceed the limit, the header
280 * is generated, and the header & unfiltered buffer are flushed
281 * to the client. Chat then continues in non-buffering,
282 * non-filtering body mode.
284 * Revision 1.44 2001/10/02 18:13:57 oes
287 * Revision 1.43 2001/10/02 15:32:13 oes
288 * Moved generation of hdr
290 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
291 * Cleaning up 2 compiler warnings on OS/2.
293 * Revision 1.41 2001/09/16 17:05:14 jongfoster
294 * Removing unused #include showarg.h
296 * Revision 1.40 2001/09/16 15:41:45 jongfoster
297 * Fixing signed/unsigned comparison warning.
299 * Revision 1.39 2001/09/16 13:21:27 jongfoster
300 * Changes to use new list functions.
302 * Revision 1.38 2001/09/16 13:01:46 jongfoster
303 * Removing redundant function call that zeroed zalloc()'d memory.
305 * Revision 1.37 2001/09/10 11:12:24 oes
306 * Deleted unused variable
308 * Revision 1.36 2001/09/10 10:56:15 oes
309 * Silenced compiler warnings
311 * Revision 1.35 2001/07/31 14:44:22 oes
312 * Deleted unused size parameter from filter_popups()
314 * Revision 1.34 2001/07/30 22:08:36 jongfoster
315 * Tidying up #defines:
316 * - All feature #defines are now of the form FEATURE_xxx
317 * - Permanently turned off WIN_GUI_EDIT
318 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
320 * Revision 1.33 2001/07/29 19:32:00 jongfoster
321 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
323 * Revision 1.32 2001/07/29 18:47:05 jongfoster
324 * Adding missing #include "loadcfg.h"
326 * Revision 1.31 2001/07/29 12:17:48 oes
327 * Applied pthread fix by Paul Lieverse
329 * Revision 1.30 2001/07/25 22:57:13 jongfoster
330 * __BEOS__ no longer overrides FEATURE_PTHREAD.
331 * This is because FEATURE_PTHREAD will soon be widely used, so I
332 * want to keep it simple.
334 * Revision 1.29 2001/07/24 12:47:06 oes
335 * Applied BeOS support update by Eugenia
337 * Revision 1.28 2001/07/23 13:26:12 oes
338 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
340 * Revision 1.27 2001/07/19 19:09:47 haroon
341 * - Added code to take care of the situation where while processing the first
342 * server response (which includes the server header), after finding the end
343 * of the headers we were not looking past the end of the headers for
344 * content modification. I enabled it for filter_popups.
345 * Someone else should look to see if other similar operations should be
346 * done to the discarded portion of the buffer.
348 * Note 2001/07/20: No, the other content modification mechanisms will process
349 * the whole iob later anyway. --oes
351 * Revision 1.26 2001/07/18 12:31:36 oes
354 * Revision 1.25 2001/07/15 19:43:49 jongfoster
355 * Supports POSIX threads.
356 * Also removed some unused #includes.
358 * Revision 1.24 2001/07/13 14:00:40 oes
359 * - Generic content modification scheme:
360 * Each feature has its own applicability flag that is set
361 * from csp->action->flags.
362 * Replaced the "filtering" int flag , by a function pointer
363 * "content_filter" to the function that will do the content
364 * modification. If it is != NULL, the document will be buffered
365 * and processed through *content_filter, which must set
366 * csp->content_length and return a modified copy of the body
367 * or return NULL (on failiure).
368 * - Changed csp->is_text to the more generic bitmap csp->content_type
369 * which can currently take the valued CT_TEXT or CT_GIF
371 * - Removed all #ifdef PCRS
373 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
374 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
375 * the `block_acl' call. This prevents a compilation error when the user
376 * does not wish to use the "ACL" feature.
378 * Revision 1.22 2001/06/29 21:45:41 oes
379 * Indentation, CRLF->LF, Tab-> Space
381 * Revision 1.21 2001/06/29 13:29:36 oes
382 * - Cleaned up, improved comments
383 * - Unified all possible interceptors (CGI,
384 * block, trust, fast_redirect) in one
385 * place, with one (CGI) answer generation
386 * mechansim. Much clearer now.
387 * - Removed the GIF image generation, which
388 * is now done in filters.c:block_url()
389 * - Made error conditions like domain lookup
390 * failiure or (various) problems while talking
391 * to the server use cgi.c:error_response()
392 * instead of generating HTML/HTTP in chat() (yuck!)
393 * - Removed logentry from cancelled commit
395 * Revision 1.20 2001/06/09 10:55:28 jongfoster
396 * Changing BUFSIZ ==> BUFFER_SIZE
398 * Revision 1.19 2001/06/07 23:12:52 jongfoster
399 * Replacing function pointer in struct gateway with a directly
400 * called function forwarded_connect().
401 * Replacing struct gateway with struct forward_spec
403 * Revision 1.18 2001/06/03 19:12:16 oes
404 * introduced new cgi handling
406 * Revision 1.17 2001/06/01 20:07:23 jongfoster
407 * Now uses action +image-blocker{} rather than config->tinygif
409 * Revision 1.16 2001/06/01 18:49:17 jongfoster
410 * Replaced "list_share" with "list" - the tiny memory gain was not
411 * worth the extra complexity.
413 * Revision 1.15 2001/05/31 21:24:47 jongfoster
414 * Changed "permission" to "action" throughout.
415 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
416 * Moved vanilla wafer check into chat(), since we must now
417 * decide whether or not to add it based on the URL.
419 * Revision 1.14 2001/05/29 20:14:01 joergs
420 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
423 * Revision 1.13 2001/05/29 09:50:24 jongfoster
424 * Unified blocklist/imagelist/permissionslist.
425 * File format is still under discussion, but the internal changes
428 * Also modified interceptor behaviour:
429 * - We now intercept all URLs beginning with one of the following
430 * prefixes (and *only* these prefixes):
432 * * http://ijbswa.sf.net/config/
433 * * http://ijbswa.sourceforge.net/config/
434 * - New interceptors "home page" - go to http://i.j.b/ to see it.
435 * - Internal changes so that intercepted and fast redirect pages
436 * are not replaced with an image.
437 * - Interceptors now have the option to send a binary page direct
438 * to the client. (i.e. ijb-send-banner uses this)
439 * - Implemented show-url-info interceptor. (Which is why I needed
440 * the above interceptors changes - a typical URL is
441 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
442 * The previous mechanism would not have intercepted that, and
443 * if it had been intercepted then it then it would have replaced
446 * Revision 1.12 2001/05/27 22:17:04 oes
448 * - re_process_buffer no longer writes the modified buffer
449 * to the client, which was very ugly. It now returns the
450 * buffer, which it is then written by chat.
452 * - content_length now adjusts the Content-Length: header
453 * for modified documents rather than crunch()ing it.
454 * (Length info in csp->content_length, which is 0 for
455 * unmodified documents)
457 * - For this to work, sed() is called twice when filtering.
459 * Revision 1.11 2001/05/26 17:27:53 jongfoster
460 * Added support for CLF and fixed LOG_LEVEL_LOG.
461 * Also did CRLF->LF fix of my previous patch.
463 * Revision 1.10 2001/05/26 15:26:15 jongfoster
464 * ACL feature now provides more security by immediately dropping
465 * connections from untrusted hosts.
467 * Revision 1.9 2001/05/26 00:28:36 jongfoster
468 * Automatic reloading of config file.
469 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
470 * Most of the global variables have been moved to a new
471 * struct configuration_spec, accessed through csp->config->globalname
472 * Most of the globals remaining are used by the Win32 GUI.
474 * Revision 1.8 2001/05/25 22:43:18 jongfoster
475 * Fixing minor memory leak and buffer overflow.
477 * Revision 1.7 2001/05/25 22:34:30 jongfoster
480 * Revision 1.6 2001/05/23 00:13:58 joergs
481 * AmigaOS support fixed.
483 * Revision 1.5 2001/05/22 18:46:04 oes
485 * - Enabled filtering banners by size rather than URL
486 * by adding patterns that replace all standard banner
487 * sizes with the "Junkbuster" gif to the re_filterfile
489 * - Enabled filtering WebBugs by providing a pattern
490 * which kills all 1x1 images
492 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
493 * which is selected by the (nonstandard and therefore
494 * capital) letter 'U' in the option string.
495 * It causes the quantifiers to be ungreedy by default.
496 * Appending a ? turns back to greedy (!).
498 * - Added a new interceptor ijb-send-banner, which
499 * sends back the "Junkbuster" gif. Without imagelist or
500 * MSIE detection support, or if tinygif = 1, or the
501 * URL isn't recognized as an imageurl, a lame HTML
502 * explanation is sent instead.
504 * - Added new feature, which permits blocking remote
505 * script redirects and firing back a local redirect
507 * The feature is conditionally compiled, i.e. it
508 * can be disabled with --disable-fast-redirects,
509 * plus it must be activated by a "fast-redirects"
510 * line in the config file, has its own log level
511 * and of course wants to be displayed by show-proxy-args
512 * Note: Boy, all the #ifdefs in 1001 locations and
513 * all the fumbling with configure.in and acconfig.h
514 * were *way* more work than the feature itself :-(
516 * - Because a generic redirect template was needed for
517 * this, tinygif = 3 now uses the same.
519 * - Moved GIFs, and other static HTTP response templates
524 * - Removed some >400 CRs again (Jon, you really worked
527 * Revision 1.4 2001/05/21 19:34:01 jongfoster
528 * Made failure to bind() a fatal error.
530 * Revision 1.3 2001/05/20 01:21:20 jongfoster
531 * Version 2.9.4 checkin.
532 * - Merged popupfile and cookiefile, and added control over PCRS
533 * filtering, in new "permissionsfile".
534 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
535 * file error you now get a message box (in the Win32 GUI) rather
536 * than the program exiting with no explanation.
537 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
539 * - Removed tabs from "config"
540 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
541 * - Bumped up version number.
543 * Revision 1.2 2001/05/17 22:34:44 oes
544 * - Added hint on GIF char array generation to jcc.c
545 * - Cleaned CRLF's from the sources and related files
546 * - Repaired logging for REF and FRC
548 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
549 * Initial import of version 2.9.3 source tree
552 *********************************************************************/
558 #include <sys/types.h>
565 #ifdef FEATURE_PTHREAD
567 #endif /* def FEATURE_PTHREAD */
570 # ifndef FEATURE_PTHREAD
574 # include <windows.h>
575 # include <process.h>
576 # endif /* ndef FEATURE_PTHREAD */
579 # ifndef _WIN_CONSOLE
581 # endif /* ndef _WIN_CONSOLE */
583 #else /* ifndef _WIN32 */
585 # if !defined (__OS2__)
587 # include <sys/wait.h>
588 # endif /* ndef __OS2__ */
589 # include <sys/time.h>
590 # include <sys/stat.h>
591 # include <sys/ioctl.h>
594 #include <sys/termios.h>
605 # include <socket.h> /* BeOS has select() for sockets only. */
606 # include <OS.h> /* declarations for threads and stuff. */
609 # if defined(__EMX__) || defined(__OS2__)
610 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
615 #define bzero(B,N) memset(B,0x00,n)
630 #include "killpopup.h"
631 #include "miscutil.h"
633 #include "jbsockets.h"
638 #include "urlmatch.h"
640 const char jcc_h_rcs[] = JCC_H_VERSION;
641 const char project_h_rcs[] = PROJECT_H_VERSION;
644 struct client_state clients[1];
645 struct file_list files[1];
647 #ifdef FEATURE_STATISTICS
648 int urls_read = 0; /* total nr of urls read inc rejected */
649 int urls_rejected = 0; /* total nr of urls rejected */
650 #endif /* def FEATURE_STATISTICS */
652 #ifdef FEATURE_GRACEFUL_TERMINATION
656 static void listen_loop(void);
657 static void chat(struct client_state *csp);
659 void serve(struct client_state *csp);
660 #else /* ifndef AMIGA */
661 static void serve(struct client_state *csp);
662 #endif /* def AMIGA */
665 static int32 server_thread(void *data);
666 #endif /* def __BEOS__ */
669 #define sleep(N) Sleep(((N) * 1000))
673 #define sleep(N) DosSleep(((N) * 100))
678 * Hit OSX over the head with a hammer. Protect all *_r functions.
680 pthread_mutex_t gmtime_mutex;
681 pthread_mutex_t localtime_mutex;
682 pthread_mutex_t gethostbyaddr_mutex;
683 pthread_mutex_t gethostbyname_mutex;
684 #endif /* def OSX_DARWIN */
686 #if defined(unix) || defined(__EMX__)
688 const char *pidfile = NULL;
689 int received_hup_signal = 0;
690 #endif /* defined unix */
692 /* The vanilla wafer. */
693 static const char VANILLA_WAFER[] =
694 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
695 "Do_not_send_me_any_copyrighted_information_other_than_the_"
696 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
697 "In_particular_do_not_send_me_any_cookies_that_"
698 "are_subject_to_a_claim_of_copyright_by_anybody._"
699 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
700 "(copyright_or_otherwise)_applying_to_any_cookie._";
703 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
704 /*********************************************************************
706 * Function : sig_handler
708 * Description : Signal handler for different signals.
709 * Exit gracefully on ABRT, TERM and INT
710 * or set a flag that will cause the errlog
711 * to be reopened by the main thread on HUP.
714 * 1 : the_signal = the signal cause this function to call
718 *********************************************************************/
719 static void sig_handler(int the_signal)
726 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
734 received_hup_signal = 1;
739 * We shouldn't be here, unless we catch signals
740 * in main() that we can't handle here!
742 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
750 /*********************************************************************
754 * Description : Once a connection to the client has been accepted,
755 * this function is called (via serve()) to handle the
756 * main business of the communication. When this
757 * function returns, the caller must close the client
761 * 1 : csp = Current client state (buffers, headers, etc...)
763 * Returns : On success, the number of bytes written are returned (zero
764 * indicates nothing was written). On error, -1 is returned,
765 * and errno is set appropriately. If count is zero and the
766 * file descriptor refers to a regular file, 0 will be
767 * returned without causing any other effect. For a special
768 * file, the results are not portable.
770 *********************************************************************/
771 static void chat(struct client_state *csp)
774 * This next lines are a little ugly, but they simplifies the if statements
775 * below. Basically if TOGGLE, then we want the if to test if the
776 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
777 * then we want the if to test for CSP_FLAG_FORCED , else we don't
779 #ifdef FEATURE_TOGGLE
780 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
781 #else /* ifndef FEATURE_TOGGLE */
782 # define IS_TOGGLED_ON_AND
783 #endif /* ndef FEATURE_TOGGLE */
784 #ifdef FEATURE_FORCE_LOAD
785 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
786 #else /* ifndef FEATURE_FORCE_LOAD */
787 # define IS_NOT_FORCED_AND
788 #endif /* def FEATURE_FORCE_LOAD */
790 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
792 char buf[BUFFER_SIZE];
800 int ms_iis5_hack = 0;
802 const struct forward_spec * fwd;
803 struct http_request *http;
804 int len; /* for buffer sizes */
805 #ifdef FEATURE_KILL_POPUPS
806 int block_popups; /* bool, 1==will block popups */
807 int block_popups_now = 0; /* bool, 1==currently blocking popups */
808 #endif /* def FEATURE_KILL_POPUPS */
810 int pcrs_filter; /* bool, 1==will filter through pcrs */
811 int gif_deanimate; /* bool, 1==will deanimate gifs */
813 /* Function that does the content filtering for the current request */
814 char *(*content_filter)() = NULL;
816 /* Skeleton for HTTP response, if we should intercept the request */
817 struct http_response *rsp;
822 * Read the client's request. Note that since we're not using select() we
823 * could get blocked here if a client connected, then didn't say anything!
828 len = read_socket(csp->cfd, buf, sizeof(buf));
830 if (len <= 0) break; /* error! */
833 * If there is no memory left for buffering the
834 * request, there is nothing we can do but hang up
836 if (add_to_iob(csp, buf, len))
841 req = get_header(csp);
845 break; /* no HTTP request! */
850 continue; /* more to come! */
853 #ifdef FEATURE_FORCE_LOAD
854 /* If this request contains the FORCE_PREFIX,
855 * better get rid of it now and set the force flag --oes
858 if (strstr(req, FORCE_PREFIX))
860 strclean(req, FORCE_PREFIX);
861 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
862 csp->flags |= CSP_FLAG_FORCED;
865 #endif /* def FEATURE_FORCE_LOAD */
867 parse_http_request(req, http, csp);
872 if (http->cmd == NULL)
874 strcpy(buf, CHEADER);
875 write_socket(csp->cfd, buf, strlen(buf));
877 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
879 free_http_request(http);
883 /* decide how to route the HTTP request */
885 if ((fwd = forward_url(http, csp)) == NULL)
887 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
888 /* Never get here - LOG_LEVEL_FATAL causes program exit */
891 /* build the http request to send to the server
892 * we have to do one of the following:
894 * create = use the original HTTP request to create a new
895 * HTTP request that has either the path component
896 * without the http://domainspec (w/path) or the
897 * full orininal URL (w/url)
898 * Note that the path and/or the HTTP version may
899 * have been altered by now.
901 * connect = Open a socket to the host:port of the server
902 * and short-circuit server and client socket.
904 * pass = Pass the request unchanged if forwarding a CONNECT
905 * request to a parent proxy. Note that we'll be sending
906 * the CFAIL message ourselves if connecting to the parent
907 * fails, but we won't send a CSUCCEED message if it works,
908 * since that would result in a double message (ours and the
909 * parent's). After sending the request to the parent, we simply
915 * +--------+--------+
917 * 0 | create | connect|
919 * Forwarding +--------+--------+
921 * 1 | create | pass |
923 * +--------+--------+
928 * Determine the actions for this URL
930 #ifdef FEATURE_TOGGLE
931 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
933 /* Most compatible set of actions (i.e. none) */
934 init_current_action(csp->action);
937 #endif /* ndef FEATURE_TOGGLE */
939 url_actions(http, csp);
944 * Check if a CONNECT request is allowable:
945 * In the absence of a +limit-connect action, allow only port 443.
946 * If there is an action, allow whatever matches the specificaton.
950 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
951 || (csp->action->flags & ACTION_LIMIT_CONNECT
952 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
954 strcpy(buf, CFORBIDDEN);
955 write_socket(csp->cfd, buf, strlen(buf));
957 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
958 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
966 * Downgrade http version from 1.1 to 1.0 if +downgrade
969 if ( (http->ssl == 0)
970 && (!strcmpic(http->ver, "HTTP/1.1"))
971 && (csp->action->flags & ACTION_DOWNGRADE))
974 http->ver = strdup("HTTP/1.0");
976 if (http->ver == NULL)
978 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
983 * Save a copy of the original request for logging
985 http->ocmd = strdup(http->cmd);
987 if (http->ocmd == NULL)
989 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
993 * (Re)build the HTTP request for non-SSL requests.
994 * If forwarding, use the whole URL, else, use only the path.
1000 http->cmd = strdup(http->gpc);
1001 string_append(&http->cmd, " ");
1003 if (fwd->forward_host)
1005 string_append(&http->cmd, http->url);
1009 string_append(&http->cmd, http->path);
1011 string_append(&http->cmd, " ");
1012 string_append(&http->cmd, http->ver);
1014 if (http->cmd == NULL)
1016 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1018 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", http->cmd);
1020 enlist(csp->headers, http->cmd);
1024 * If the user has not supplied any wafers, and the user has not
1025 * told us to suppress the vanilla wafer, then send the vanilla wafer.
1027 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
1028 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
1030 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
1034 #ifdef FEATURE_KILL_POPUPS
1035 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1036 #endif /* def FEATURE_KILL_POPUPS */
1038 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
1039 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1041 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1043 /* grab the rest of the client's headers */
1047 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
1049 len = read_socket(csp->cfd, buf, sizeof(buf));
1052 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1057 * If there is no memory left for buffering the
1058 * request, there is nothing we can do but hang up
1060 if (add_to_iob(csp, buf, len))
1067 if (p == NULL) break;
1069 enlist(csp->headers, p);
1074 * We have a request. Now, check to see if we need to
1075 * intercept it, i.e. If ..
1079 /* We may not forward the request by rfc2616 sect 14.31 */
1080 (NULL != (rsp = direct_response(csp)))
1082 /* or a CGI call was detected and answered */
1083 || (NULL != (rsp = dispatch_cgi(csp)))
1085 /* or we are enabled and... */
1086 || (IS_ENABLED_AND (
1088 /* ..the request was blocked */
1089 ( NULL != (rsp = block_url(csp)))
1091 /* ..or untrusted */
1092 #ifdef FEATURE_TRUST
1093 || ( NULL != (rsp = trust_url(csp)))
1094 #endif /* def FEATURE_TRUST */
1096 /* ..or a fast redirect kicked in */
1097 #ifdef FEATURE_FAST_REDIRECTS
1098 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
1099 (NULL != (rsp = redirect_url(csp))))
1100 #endif /* def FEATURE_FAST_REDIRECTS */
1104 /* Write the answer to the client */
1105 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1106 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1108 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1111 #ifdef FEATURE_STATISTICS
1112 /* Count as a rejected request */
1113 csp->flags |= CSP_FLAG_REJECTED;
1114 #endif /* def FEATURE_STATISTICS */
1116 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
1117 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1118 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1120 /* Clean up and return */
1121 free_http_response(rsp);
1125 hdr = sed(client_patterns, add_client_headers, csp);
1128 /* FIXME Should handle error properly */
1129 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1132 list_remove_all(csp->headers);
1134 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1136 if (fwd->forward_host)
1138 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1139 fwd->forward_host, fwd->forward_port, http->hostport);
1143 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1146 /* here we connect to the server, gateway, or the forwarder */
1148 csp->sfd = forwarded_connect(fwd, http, csp);
1150 if (csp->sfd == JB_INVALID_SOCKET)
1152 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1155 if (errno == EINVAL)
1157 rsp = error_response(csp, "no-such-domain", errno);
1159 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1160 csp->ip_addr_str, http->ocmd);
1164 rsp = error_response(csp, "connect-failed", errno);
1166 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1167 csp->ip_addr_str, http->ocmd);
1171 /* Write the answer to the client */
1174 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1175 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1177 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1181 free_http_response(rsp);
1186 log_error(LOG_LEVEL_CONNECT, "OK");
1188 if (fwd->forward_host || (http->ssl == 0))
1190 /* write the client's (modified) header to the server
1191 * (along with anything else that may be in the buffer)
1194 if (write_socket(csp->sfd, hdr, strlen(hdr))
1195 || (flush_socket(csp->sfd, csp) < 0))
1197 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1200 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1201 csp->ip_addr_str, http->ocmd);
1203 rsp = error_response(csp, "connect-failed", errno);
1207 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1208 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1210 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1214 free_http_response(rsp);
1222 * We're running an SSL tunnel and we're not forwarding,
1223 * so just send the "connect succeeded" message to the
1224 * client, flush the rest, and get out of the way.
1226 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1227 csp->ip_addr_str, http->ocmd);
1229 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1237 /* we're finished with the client's header */
1240 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1242 /* pass data between the client and server
1243 * until one or the other shuts down the connection.
1252 * FD_ZERO here seems to point to an errant macro which crashes.
1253 * So do this by hand for now...
1255 memset(&rfds,0x00,sizeof(fd_set));
1259 FD_SET(csp->cfd, &rfds);
1260 FD_SET(csp->sfd, &rfds);
1262 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1266 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1270 /* this is the body of the browser's request
1271 * just read it and write it.
1274 if (FD_ISSET(csp->cfd, &rfds))
1276 len = read_socket(csp->cfd, buf, sizeof(buf));
1280 break; /* "game over, man" */
1283 if (write_socket(csp->sfd, buf, (size_t)len))
1285 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1292 * The server wants to talk. It could be the header or the body.
1293 * If `hdr' is null, then it's the header otherwise it's the body.
1294 * FIXME: Does `hdr' really mean `host'? No.
1298 if (FD_ISSET(csp->sfd, &rfds))
1301 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1305 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1307 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1308 csp->ip_addr_str, http->ocmd);
1310 rsp = error_response(csp, "connect-failed", errno);
1314 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1315 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1317 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1321 free_http_response(rsp);
1325 /* Add a trailing zero. This lets filter_popups
1326 * use string operations.
1330 #ifdef FEATURE_KILL_POPUPS
1331 /* Filter the popups on this read. */
1332 if (block_popups_now)
1334 filter_popups(buf, csp);
1336 #endif /* def FEATURE_KILL_POPUPS */
1338 /* Normally, this would indicate that we've read
1339 * as much as the server has sent us and we can
1340 * close the client connection. However, Microsoft
1341 * in its wisdom has released IIS/5 with a bug that
1342 * prevents it from sending the trailing \r\n in
1343 * a 302 redirect header (and possibly other headers).
1344 * To work around this if we've haven't parsed
1345 * a full header we'll append a trailing \r\n
1346 * and see if this now generates a valid one.
1348 * This hack shouldn't have any impacts. If we've
1349 * already transmitted the header or if this is a
1350 * SSL connection, then we won't bother with this
1351 * hack. So we only work on partially received
1352 * headers. If we append a \r\n and this still
1353 * doesn't generate a valid header, then we won't
1354 * transmit anything to the client.
1359 if (server_body || http->ssl)
1362 * If we have been buffering up the document,
1363 * now is the time to apply content modification
1364 * and send the result to the client.
1369 * If the content filter fails, use the original
1370 * buffer and length.
1371 * (see p != NULL ? p : csp->iob->cur below)
1373 if (NULL == (p = (*content_filter)(csp)))
1375 csp->content_length = csp->iob->eod - csp->iob->cur;
1378 hdr = sed(server_patterns, add_server_headers, csp);
1381 /* FIXME Should handle error properly */
1382 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1385 if (write_socket(csp->cfd, hdr, strlen(hdr))
1386 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1388 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1398 break; /* "game over, man" */
1402 * This is NOT the body, so
1403 * Let's pretend the server just sent us a blank line.
1405 len = sprintf(buf, "\r\n");
1408 * Now, let the normal header parsing algorithm below do its
1409 * job. If it fails, we'll exit instead of continuing.
1416 * If this is an SSL connection or we're in the body
1417 * of the server document, just write it to the client,
1418 * unless we need to buffer the body for later content-filtering
1421 if (server_body || http->ssl)
1426 * If there is no memory left for buffering the content, or the buffer limit
1427 * has been reached, switch to non-filtering mode, i.e. make & write the
1428 * header, flush the iob and buf, and get out of the way.
1430 if (add_to_iob(csp, buf, len))
1435 log_error(LOG_LEVEL_ERROR, "Flushing header and buffers. Stepping back from filtering.");
1437 hdr = sed(server_patterns, add_server_headers, csp);
1441 * Memory is too tight to even generate the header.
1442 * Send our static "Out-of-memory" page.
1444 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
1445 rsp = cgi_error_memory();
1447 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1448 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1450 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1455 hdrlen = strlen(hdr);
1457 if (write_socket(csp->cfd, hdr, hdrlen)
1458 || ((flushed = flush_socket(csp->cfd, csp)) < 0)
1459 || (write_socket(csp->cfd, buf, len)))
1461 log_error(LOG_LEVEL_CONNECT, "Flush header and buffers to client failed: %E");
1467 byte_count += hdrlen + flushed + len;
1469 content_filter = NULL;
1476 if (write_socket(csp->cfd, buf, (size_t)len))
1478 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1487 /* we're still looking for the end of the
1488 * server's header ... (does that make header
1489 * parsing an "out of body experience" ?
1493 * buffer up the data we just read. If that fails,
1494 * there's little we can do but send our static
1495 * out-of-memory page.
1497 if (add_to_iob(csp, buf, len))
1499 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
1500 rsp = cgi_error_memory();
1502 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1503 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1505 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1510 /* get header lines from the iob */
1512 while ((p = get_header(csp)) != NULL)
1516 /* see following note */
1519 enlist(csp->headers, p);
1523 /* NOTE: there are no "empty" headers so
1524 * if the pointer `p' is not NULL we must
1525 * assume that we reached the end of the
1526 * buffer before we hit the end of the header.
1533 /* Well, we tried our MS IIS/5
1534 * hack and it didn't work.
1535 * The header is incomplete
1536 * and there isn't anything
1537 * we can do about it.
1543 /* Since we have to wait for
1544 * more from the server before
1545 * we can parse the headers
1546 * we just continue here.
1552 /* we have now received the entire header.
1553 * filter it and send the result to the client
1556 hdr = sed(server_patterns, add_server_headers, csp);
1559 /* FIXME Should handle error properly */
1560 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1563 #ifdef FEATURE_KILL_POPUPS
1564 /* Start blocking popups if appropriate. */
1566 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1567 !http->ssl && /* We talk plaintext */
1568 block_popups) /* Policy allows */
1570 block_popups_now = 1;
1572 * Filter the part of the body that came in the same read
1573 * as the last headers:
1575 filter_popups(csp->iob->cur, csp);
1578 #endif /* def FEATURE_KILL_POPUPS */
1580 /* Buffer and pcrs filter this if appropriate. */
1582 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1583 !http->ssl && /* We talk plaintext */
1584 pcrs_filter) /* Policy allows */
1586 content_filter = pcrs_filter_response;
1589 /* Buffer and gif_deanimate this if appropriate. */
1591 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1592 !http->ssl && /* We talk plaintext */
1593 gif_deanimate) /* Policy allows */
1595 content_filter = gif_deanimate_response;
1599 * Only write if we're not buffering for content modification
1601 if (!content_filter)
1603 /* write the server's (modified) header to
1604 * the client (along with anything else that
1605 * may be in the buffer)
1608 if (write_socket(csp->cfd, hdr, strlen(hdr))
1609 || ((len = flush_socket(csp->cfd, csp)) < 0))
1611 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1613 /* the write failed, so don't bother
1614 * mentioning it to the client...
1615 * it probably can't hear us anyway.
1624 /* we're finished with the server's header */
1629 /* If this was a MS IIS/5 hack then it means
1630 * the server has already closed the
1631 * connection. Nothing more to read. Time
1642 return; /* huh? we should never get here */
1645 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1646 csp->ip_addr_str, http->ocmd, byte_count);
1650 /*********************************************************************
1654 * Description : This is little more than chat. We only "serve" to
1655 * to close any socket that chat may have opened.
1658 * 1 : csp = Current client state (buffers, headers, etc...)
1662 *********************************************************************/
1664 void serve(struct client_state *csp)
1665 #else /* ifndef AMIGA */
1666 static void serve(struct client_state *csp)
1667 #endif /* def AMIGA */
1670 close_socket(csp->cfd);
1672 if (csp->sfd != JB_INVALID_SOCKET)
1674 close_socket(csp->sfd);
1677 csp->flags &= ~CSP_FLAG_ACTIVE;
1683 /*********************************************************************
1685 * Function : server_thread
1687 * Description : We only exist to call `serve' in a threaded environment.
1690 * 1 : data = Current client state (buffers, headers, etc...)
1692 * Returns : Always 0.
1694 *********************************************************************/
1695 static int32 server_thread(void *data)
1697 serve((struct client_state *) data);
1704 /*********************************************************************
1708 * Description : Print usage info & exit.
1710 * Parameters : Pointer to argv[0] for identifying ourselves
1714 *********************************************************************/
1715 void usage(const char *myname)
1717 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
1718 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1719 "Aborting.\n", myname);
1726 /*********************************************************************
1730 * Description : Load the config file and start the listen loop.
1731 * This function is a lot more *sane* with the `load_config'
1732 * and `listen_loop' functions; although it stills does
1733 * a *little* too much for my taste.
1736 * 1 : argc = Number of parameters (including $0).
1737 * 2 : argv = Array of (char *)'s to the parameters.
1739 * Returns : 1 if : can't open config file, unrecognized directive,
1740 * stats requested in multi-thread mode, can't open the
1741 * log file, can't open the jar file, listen port is invalid,
1742 * any load fails, and can't bind port.
1744 * Else main never returns, the process must be signaled
1745 * to terminate execution. Or, on Windows, use the
1746 * "File", "Exit" menu option.
1748 *********************************************************************/
1750 int real_main(int argc, const char *argv[])
1752 int main(int argc, const char *argv[])
1757 struct passwd *pw = NULL;
1758 struct group *grp = NULL;
1766 #if !defined(_WIN32)
1774 * Parse the command line arguments
1776 while (++argc_pos < argc)
1778 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1780 if (strcmp(argv[argc_pos], "--help") == 0)
1785 else if(strcmp(argv[argc_pos], "--version") == 0)
1787 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1791 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1796 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1798 if (++argc_pos == argc) usage(argv[0]);
1799 pidfile = strdup(argv[argc_pos]);
1802 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1804 if (++argc_pos == argc) usage(argv[argc_pos]);
1806 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1809 if (NULL == (grp = getgrnam(p)))
1811 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1815 if (NULL == (pw = getpwnam(argv[argc_pos])))
1817 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1820 if (p != NULL) *--p = '\0';
1822 #endif /* defined(unix) */
1824 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1826 configfile = argv[argc_pos];
1829 } /* -END- while (more arguments) */
1832 if ( *configfile != '/' )
1836 /* make config-filename absolute here */
1837 if ( !(basedir = getcwd( NULL, 1024 )))
1839 perror("get working dir failed");
1843 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1845 perror("malloc failed");
1848 strcpy( abs_file, basedir );
1849 strcat( abs_file, "/" );
1850 strcat( abs_file, configfile );
1851 configfile = abs_file;
1853 #endif /* defined unix */
1857 clients->next = NULL;
1861 #elif defined(_WIN32)
1867 * Prepare global mutex semaphores
1869 pthread_mutex_init(&gmtime_mutex,0);
1870 pthread_mutex_init(&localtime_mutex,0);
1871 pthread_mutex_init(&gethostbyaddr_mutex,0);
1872 pthread_mutex_init(&gethostbyname_mutex,0);
1873 #endif /* def OSX_DARWIN */
1876 * Unix signal handling
1878 * Catch the abort, interrupt and terminate signals for a graceful exit
1879 * Catch the hangup signal so the errlog can be reopened.
1880 * Ignore the broken pipe and child signals
1881 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1883 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1886 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1887 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1889 for (idx = 0; catched_signals[idx] != 0; idx++)
1891 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1893 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1897 for (idx = 0; ignored_signals[idx] != 0; idx++)
1899 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1901 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1906 #else /* ifdef _WIN32 */
1907 # ifdef _WIN_CONSOLE
1909 * We *are* in a windows console app.
1910 * Print a verbose messages about FAQ's and such
1912 printf(win32_blurb);
1913 # endif /* def _WIN_CONSOLE */
1914 #endif /* def _WIN32 */
1917 /* Initialize the CGI subsystem */
1918 cgi_init_error_messages();
1921 * If runnig on unix and without the --nodaemon
1922 * option, become a daemon. I.e. fork, detach
1923 * from tty and get process group leadership
1936 if ( pid < 0 ) /* error */
1941 else if ( pid != 0 ) /* parent */
1946 * must check for errors
1947 * child died due to missing files aso
1950 wpid = waitpid( pid, &status, WNOHANG );
1959 /* Should be more portable, but not as well tested */
1964 #else /* ndef __FreeBSD__ */
1966 #endif /* ndef __FreeBSD__ */
1967 fd = open("/dev/tty", O_RDONLY);
1970 /* no error check here */
1971 ioctl( fd, TIOCNOTTY,0 );
1975 /* FIXME: should close stderr (fd 2) here too, but the test
1977 * and load config file is done in listen_loop() and puts
1978 * some messages on stderr there.
1985 } /* -END- if (!no_daemon) */
1988 * As soon as we have written the PID file, we can switch
1989 * to the user and group ID indicated by the --user option
1995 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1997 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1999 if (setuid(pw->pw_uid))
2001 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
2005 #endif /* defined unix */
2015 /*********************************************************************
2017 * Function : bind_port_helper
2019 * Description : Bind the listen port. Handles logging, and aborts
2023 * 1 : config = Privoxy configuration. Specifies port
2026 * Returns : Port that was opened.
2028 *********************************************************************/
2029 static jb_socket bind_port_helper(struct configuration_spec * config)
2034 if ( (config->haddr != NULL)
2035 && (config->haddr[0] == '1')
2036 && (config->haddr[1] == '2')
2037 && (config->haddr[2] == '7')
2038 && (config->haddr[3] == '.') )
2040 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
2043 else if (config->haddr == NULL)
2045 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
2050 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
2051 config->hport, config->haddr);
2054 result = bind_port(config->haddr, config->hport, &bfd);
2061 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2062 "There may be another Privoxy or some other "
2063 "proxy running on port %d",
2064 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
2065 config->hport, config->hport);
2068 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2069 "The hostname is not resolvable",
2070 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2073 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
2074 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2077 /* shouldn't get here */
2078 return JB_INVALID_SOCKET;
2081 config->need_bind = 0;
2087 /*********************************************************************
2089 * Function : listen_loop
2091 * Description : bind the listen port and enter a "FOREVER" listening loop.
2097 *********************************************************************/
2098 static void listen_loop(void)
2100 struct client_state *csp = NULL;
2102 struct configuration_spec * config;
2104 config = load_config();
2106 bfd = bind_port_helper(config);
2108 #ifdef FEATURE_GRACEFUL_TERMINATION
2109 while (!g_terminate)
2114 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
2115 while (waitpid(-1, NULL, WNOHANG) > 0)
2117 /* zombie children */
2119 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2122 * Free data that was used by died threads
2128 * Re-open the errlog after HUP signal
2130 if (received_hup_signal)
2132 init_error_log(Argv[0], config->logfile, config->debug);
2133 received_hup_signal = 0;
2138 #ifdef FEATURE_COOKIE_JAR
2140 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
2141 * already open. I think unload_configfile() is not being run, which should do
2142 * this work. Until that can get resolved, we'll use this workaround.
2146 if (csp->config->jar)
2148 fclose(csp->config->jar);
2149 csp->config->jar = NULL;
2151 #endif /* FEATURE_COOKIE_JAR */
2152 #endif /* __OS2__ */
2154 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2156 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2160 csp->flags |= CSP_FLAG_ACTIVE;
2161 csp->sfd = JB_INVALID_SOCKET;
2163 csp->config = config = load_config();
2165 if ( config->need_bind )
2168 * Since we were listening to the "old port", we will not see
2169 * a "listen" param change until the next IJB request. So, at
2170 * least 1 more request must be made for us to find the new
2171 * setting. I am simply closing the old socket and binding the
2174 * Which-ever is correct, we will serve 1 more page via the
2175 * old settings. This should probably be a "show-proxy-args"
2176 * request. This should not be a so common of an operation
2177 * that this will hurt people's feelings.
2182 bfd = bind_port_helper(config);
2185 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2187 if (!accept_connection(csp, bfd))
2189 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2202 log_error(LOG_LEVEL_CONNECT, "OK");
2205 #ifdef FEATURE_TOGGLE
2208 csp->flags |= CSP_FLAG_TOGGLED_ON;
2210 #endif /* def FEATURE_TOGGLE */
2212 if (run_loader(csp))
2214 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2215 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2219 if (block_acl(NULL,csp))
2221 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2222 close_socket(csp->cfd);
2226 #endif /* def FEATURE_ACL */
2228 /* add it to the list of clients */
2229 csp->next = clients->next;
2230 clients->next = csp;
2232 if (config->multi_threaded)
2236 /* this is a switch () statment in the C preprocessor - ugh */
2237 #undef SELECTED_ONE_OPTION
2239 /* Use Pthreads in preference to native code */
2240 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2241 #define SELECTED_ONE_OPTION
2243 pthread_t the_thread;
2244 pthread_attr_t attrs;
2246 pthread_attr_init(&attrs);
2247 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2248 child_id = (pthread_create(&the_thread, &attrs,
2249 (void*)serve, csp) ? -1 : 0);
2250 pthread_attr_destroy(&attrs);
2254 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2255 #define SELECTED_ONE_OPTION
2256 child_id = _beginthread(
2257 (void (*)(void *))serve,
2262 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2263 #define SELECTED_ONE_OPTION
2264 child_id = _beginthread(
2265 (void(* _Optlink)(void*))serve,
2271 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2272 #define SELECTED_ONE_OPTION
2274 thread_id tid = spawn_thread
2275 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2277 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2279 child_id = (int) tid;
2288 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2289 #define SELECTED_ONE_OPTION
2290 csp->cfd = ReleaseSocket(csp->cfd, -1);
2291 if((child_id = (int)CreateNewProcTags(
2292 NP_Entry, (ULONG)server_thread,
2293 NP_Output, Output(),
2294 NP_CloseOutput, FALSE,
2295 NP_Name, (ULONG)"privoxy child",
2296 NP_StackSize, 200*1024,
2300 ((struct Task *)child_id)->tc_UserData = csp;
2301 Signal((struct Task *)child_id, SIGF_SINGLE);
2306 #if !defined(SELECTED_ONE_OPTION)
2309 /* This block is only needed when using fork().
2310 * When using threads, the server thread was
2311 * created and run by the call to _beginthread().
2313 if (child_id == 0) /* child */
2315 int inherited_toggle_state = g_bToggleIJB;
2319 * If we've been toggled, tell Mom
2321 if (inherited_toggle_state != g_bToggleIJB)
2330 else if (child_id > 0) /* parent */
2332 /* in a fork()'d environment, the parent's
2333 * copy of the client socket and the CSP
2337 #if !defined(_WIN32) && !defined(__CYGWIN__)
2338 wait( &child_status );
2340 * If the child has been toggled (return code 17), toggle ourselves
2342 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) == 17))
2344 g_bToggleIJB = !g_bToggleIJB;
2346 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2347 close_socket(csp->cfd);
2348 csp->flags &= ~CSP_FLAG_ACTIVE;
2352 #undef SELECTED_ONE_OPTION
2353 /* end of cpp switch () */
2355 if (child_id < 0) /* failed */
2357 char buf[BUFFER_SIZE];
2359 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2361 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
2363 write_socket(csp->cfd, buf, strlen(buf));
2364 close_socket(csp->cfd);
2365 csp->flags &= ~CSP_FLAG_ACTIVE;
2376 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2378 /* Clean up. Aim: free all memory (no leaks) */
2379 #ifdef FEATURE_GRACEFUL_TERMINATION
2381 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2383 unload_current_config_file();
2384 unload_current_actions_file();
2385 unload_current_re_filterfile();
2386 #ifdef FEATURE_TRUST
2387 unload_current_trust_file();
2390 if (config->multi_threaded)
2397 } while ((clients->next != NULL) && (--i > 0));
2401 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2410 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2411 /* Cleanup - remove taskbar icon etc. */
2416 #endif /* FEATURE_GRACEFUL_TERMINATION */