1 const char jcc_rcs[] = "$Id: jcc.c,v 1.92.2.5 2003/03/10 23:45:32 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.5 2003/03/10 23:45:32 oes
37 * Fixed bug #700381: Non-Threaded version now capable of being toggled.
38 * Children now report having been toggled through _exit(17), parents
39 * watch for that code and toggle themselves if found.
41 * Revision 1.92.2.4 2003/03/07 03:41:04 david__schmidt
42 * 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.
44 * Revision 1.92.2.3 2003/02/28 12:53:06 oes
45 * Fixed two mostly harmless mem leaks
47 * Revision 1.92.2.2 2002/11/20 14:37:47 oes
48 * Fix: Head of global clients list now initialized to NULL
50 * Revision 1.92.2.1 2002/09/25 14:52:24 oes
51 * Added basic support for OPTIONS and TRACE HTTP methods:
52 * - New interceptor direct_response() added in chat().
53 * - sed() moved to earlier in the process, so that the
54 * Host: header is evaluated before actions and forwarding
57 * Revision 1.92 2002/05/08 16:00:46 oes
58 * Chat's buffer handling:
59 * - Fixed bug with unchecked out-of-mem conditions
60 * while reading client request & server headers
61 * - No longer predict if the buffer limit will be exceeded
62 * in the next read -- check add_to_iob's new
63 * return code. If buffer couldn't be extended
64 * (policy or out-of-mem) while
65 * - reading from client: abort
66 * - reading server headers: send error page
67 * - buffering server body for filter: flush,
68 * and if that fails: send error page
70 * Revision 1.91 2002/04/08 20:35:58 swa
73 * Revision 1.90 2002/04/02 14:57:28 oes
74 * Made sending wafers independent of FEATURE_COOKIE_JAR
76 * Revision 1.89 2002/03/31 17:18:59 jongfoster
77 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
79 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
80 * More compiler warning message maintenance
82 * Revision 1.87 2002/03/26 22:29:54 swa
83 * we have a new homepage!
85 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
86 * Workaround for closing the jarfile before load_config() comes around again
88 * Revision 1.85 2002/03/24 15:23:33 jongfoster
91 * Revision 1.84 2002/03/24 13:25:43 swa
92 * name change related issues
94 * Revision 1.83 2002/03/16 23:54:06 jongfoster
95 * Adding graceful termination feature, to help look for memory leaks.
96 * If you enable this (which, by design, has to be done by hand
97 * editing config.h) and then go to http://i.j.b/die, then the program
98 * will exit cleanly after the *next* request. It should free all the
99 * memory that was used.
101 * Revision 1.82 2002/03/13 00:27:05 jongfoster
104 * Revision 1.81 2002/03/12 01:42:50 oes
105 * Introduced modular filters
107 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
108 * OS/2 port maintenance:
109 * - Fixed EMX build - it had decayed a little
110 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
111 * substituted a memset for now.
113 * Revision 1.79 2002/03/09 20:03:52 jongfoster
114 * - Making various functions return int rather than size_t.
115 * (Undoing a recent change). Since size_t is unsigned on
116 * Windows, functions like read_socket that return -1 on
117 * error cannot return a size_t.
119 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
120 * crashes, and also frequently caused JB to jump to 100%
121 * CPU and stay there. (Because it thought it had just
122 * read ((unsigned)-1) == 4Gb of data...)
124 * - The signature of write_socket has changed, it now simply
125 * returns success=0/failure=nonzero.
127 * - Trying to get rid of a few warnings --with-debug on
128 * Windows, I've introduced a new type "jb_socket". This is
129 * used for the socket file descriptors. On Windows, this
130 * is SOCKET (a typedef for unsigned). Everywhere else, it's
131 * an int. The error value can't be -1 any more, so it's
132 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
133 * Windows it maps to the #define INVALID_SOCKET.)
135 * - The signature of bind_port has changed.
137 * Revision 1.78 2002/03/08 21:35:04 oes
138 * Added optional group supplement to --user option. Will now use default group of user if no group given
140 * Revision 1.77 2002/03/07 03:52:06 oes
141 * - Fixed compiler warnings etc
142 * - Improved handling of failed DNS lookups
144 * Revision 1.76 2002/03/06 22:54:35 jongfoster
145 * Automated function-comment nitpicking.
147 * Revision 1.75 2002/03/06 10:02:19 oes
148 * Fixed stupid bug when --user was not given
150 * Revision 1.74 2002/03/06 00:49:31 jongfoster
151 * Fixing warning on Windows
152 * Making #ifdefs that refer to the same variable consistently
153 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
155 * Revision 1.73 2002/03/05 23:57:30 hal9
156 * Stray character 's' on line 1618 was breaking build.
158 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
159 * - Re-enable OS/2 building after new parms were added
160 * - Fix false out of memory report when resolving CGI templates when no IP
161 * address is available of failed attempt (a la no such domain)
163 * Revision 1.71 2002/03/05 18:13:56 oes
164 * Added --user option
166 * Revision 1.70 2002/03/05 04:52:42 oes
167 * Deleted non-errlog debugging code
169 * Revision 1.69 2002/03/04 23:50:00 jongfoster
170 * Splitting off bind_port() call into bind_port_helper(), with
173 * Revision 1.68 2002/03/04 20:17:32 oes
176 * Revision 1.67 2002/03/04 18:18:57 oes
177 * - Removed _DEBUG mode
178 * - Cleand up cmdline parsing
179 * - Introduced --no-daemon, --pidfile options
180 * - Cleaned up signal handling:
181 * - Terminate cleanly on INT, TERM and ABRT
182 * - Schedule logfile for re-opening on HUP
183 * - Ignore CHLD and PIPE
184 * - Leave the rest with their default handlers
185 * - Uniform handler registration
186 * - Added usage() function
187 * - Played styleguide police
189 * Revision 1.66 2002/03/03 15:06:55 oes
190 * Re-enabled automatic config reloading
192 * Revision 1.65 2002/03/03 14:49:11 oes
193 * Fixed CLF logging: Now uses client's original HTTP request
195 * Revision 1.64 2002/03/03 09:18:03 joergs
196 * Made jumbjuster work on AmigaOS again.
198 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
199 * Clean up a little CRLF unpleasantness that suddenly appeared
201 * Revision 1.62 2002/02/20 23:17:23 jongfoster
202 * Detecting some out-of memory conditions and exiting with a log message.
204 * Revision 1.61 2002/01/17 21:01:52 jongfoster
205 * Moving all our URL and URL pattern parsing code to urlmatch.c.
207 * Revision 1.60 2001/12/30 14:07:32 steudten
208 * - Add signal handling (unix)
209 * - Add SIGHUP handler (unix)
210 * - Add creation of pidfile (unix)
211 * - Add action 'top' in rc file (RH)
212 * - Add entry 'SIGNALS' to manpage
213 * - Add exit message to logfile (unix)
215 * Revision 1.59 2001/12/13 14:07:18 oes
216 * Fixed Bug: 503 error page now sent OK
218 * Revision 1.58 2001/11/30 23:37:24 jongfoster
219 * Renaming the Win32 config file to config.txt - this is almost the
220 * same as the corresponding UNIX name "config"
222 * Revision 1.57 2001/11/16 00:47:43 jongfoster
223 * Changing the tty-disconnection code to use setsid().
225 * Revision 1.56 2001/11/13 20:20:54 jongfoster
226 * Tabs->spaces, fixing a bug with missing {} around an if()
228 * Revision 1.55 2001/11/13 20:14:53 jongfoster
229 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
231 * Revision 1.54 2001/11/07 00:03:14 steudten
232 * Give reliable return value if an error
233 * occurs not just 0 with new daemon mode.
235 * Revision 1.53 2001/11/05 21:41:43 steudten
236 * Add changes to be a real daemon just for unix os.
237 * (change cwd to /, detach from controlling tty, set
238 * process group and session leader to the own process.
240 * Add some fatal-error log message for failed malloc().
241 * Add '-d' if compiled with 'configure --with-debug' to
242 * enable debug output.
244 * Revision 1.52 2001/10/26 20:11:20 jongfoster
245 * Fixing type mismatch
247 * Revision 1.51 2001/10/26 17:38:28 oes
250 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
251 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
252 * threads to call select() simultaneously. So, it's time to do a real, live,
253 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
254 * (native). Both versions will work, but using __OS2__ offers multi-threading.
256 * Revision 1.49 2001/10/23 21:41:35 jongfoster
257 * Added call to initialize the (statically-allocated of course)
258 * "out of memory" CGI response.
260 * Revision 1.48 2001/10/10 19:56:46 jongfoster
261 * Moving some code that wasn't cookie-related out of an #ifdef
264 * Revision 1.47 2001/10/10 16:44:36 oes
265 * Added CONNECT destination port limitation check
267 * Revision 1.46 2001/10/08 15:17:41 oes
268 * Re-enabled SSL forwarding
270 * Revision 1.45 2001/10/07 15:42:11 oes
271 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
273 * Moved downgrading of the HTTP version from parse_http_request to
274 * chat(), since we can't decide if it is necessary before we have
275 * determined the actions for the URL. The HTTP command is now
276 * *always* re-built so the repairs need no longer be special-cased.
278 * filter_popups now gets a csp pointer so it can raise the new
279 * CSP_FLAG_MODIFIED flag.
283 * Added configurable size limit for the IOB. If the IOB grows so
284 * large that the next read would exceed the limit, the header
285 * is generated, and the header & unfiltered buffer are flushed
286 * to the client. Chat then continues in non-buffering,
287 * non-filtering body mode.
289 * Revision 1.44 2001/10/02 18:13:57 oes
292 * Revision 1.43 2001/10/02 15:32:13 oes
293 * Moved generation of hdr
295 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
296 * Cleaning up 2 compiler warnings on OS/2.
298 * Revision 1.41 2001/09/16 17:05:14 jongfoster
299 * Removing unused #include showarg.h
301 * Revision 1.40 2001/09/16 15:41:45 jongfoster
302 * Fixing signed/unsigned comparison warning.
304 * Revision 1.39 2001/09/16 13:21:27 jongfoster
305 * Changes to use new list functions.
307 * Revision 1.38 2001/09/16 13:01:46 jongfoster
308 * Removing redundant function call that zeroed zalloc()'d memory.
310 * Revision 1.37 2001/09/10 11:12:24 oes
311 * Deleted unused variable
313 * Revision 1.36 2001/09/10 10:56:15 oes
314 * Silenced compiler warnings
316 * Revision 1.35 2001/07/31 14:44:22 oes
317 * Deleted unused size parameter from filter_popups()
319 * Revision 1.34 2001/07/30 22:08:36 jongfoster
320 * Tidying up #defines:
321 * - All feature #defines are now of the form FEATURE_xxx
322 * - Permanently turned off WIN_GUI_EDIT
323 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
325 * Revision 1.33 2001/07/29 19:32:00 jongfoster
326 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
328 * Revision 1.32 2001/07/29 18:47:05 jongfoster
329 * Adding missing #include "loadcfg.h"
331 * Revision 1.31 2001/07/29 12:17:48 oes
332 * Applied pthread fix by Paul Lieverse
334 * Revision 1.30 2001/07/25 22:57:13 jongfoster
335 * __BEOS__ no longer overrides FEATURE_PTHREAD.
336 * This is because FEATURE_PTHREAD will soon be widely used, so I
337 * want to keep it simple.
339 * Revision 1.29 2001/07/24 12:47:06 oes
340 * Applied BeOS support update by Eugenia
342 * Revision 1.28 2001/07/23 13:26:12 oes
343 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
345 * Revision 1.27 2001/07/19 19:09:47 haroon
346 * - Added code to take care of the situation where while processing the first
347 * server response (which includes the server header), after finding the end
348 * of the headers we were not looking past the end of the headers for
349 * content modification. I enabled it for filter_popups.
350 * Someone else should look to see if other similar operations should be
351 * done to the discarded portion of the buffer.
353 * Note 2001/07/20: No, the other content modification mechanisms will process
354 * the whole iob later anyway. --oes
356 * Revision 1.26 2001/07/18 12:31:36 oes
359 * Revision 1.25 2001/07/15 19:43:49 jongfoster
360 * Supports POSIX threads.
361 * Also removed some unused #includes.
363 * Revision 1.24 2001/07/13 14:00:40 oes
364 * - Generic content modification scheme:
365 * Each feature has its own applicability flag that is set
366 * from csp->action->flags.
367 * Replaced the "filtering" int flag , by a function pointer
368 * "content_filter" to the function that will do the content
369 * modification. If it is != NULL, the document will be buffered
370 * and processed through *content_filter, which must set
371 * csp->content_length and return a modified copy of the body
372 * or return NULL (on failiure).
373 * - Changed csp->is_text to the more generic bitmap csp->content_type
374 * which can currently take the valued CT_TEXT or CT_GIF
376 * - Removed all #ifdef PCRS
378 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
379 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
380 * the `block_acl' call. This prevents a compilation error when the user
381 * does not wish to use the "ACL" feature.
383 * Revision 1.22 2001/06/29 21:45:41 oes
384 * Indentation, CRLF->LF, Tab-> Space
386 * Revision 1.21 2001/06/29 13:29:36 oes
387 * - Cleaned up, improved comments
388 * - Unified all possible interceptors (CGI,
389 * block, trust, fast_redirect) in one
390 * place, with one (CGI) answer generation
391 * mechansim. Much clearer now.
392 * - Removed the GIF image generation, which
393 * is now done in filters.c:block_url()
394 * - Made error conditions like domain lookup
395 * failiure or (various) problems while talking
396 * to the server use cgi.c:error_response()
397 * instead of generating HTML/HTTP in chat() (yuck!)
398 * - Removed logentry from cancelled commit
400 * Revision 1.20 2001/06/09 10:55:28 jongfoster
401 * Changing BUFSIZ ==> BUFFER_SIZE
403 * Revision 1.19 2001/06/07 23:12:52 jongfoster
404 * Replacing function pointer in struct gateway with a directly
405 * called function forwarded_connect().
406 * Replacing struct gateway with struct forward_spec
408 * Revision 1.18 2001/06/03 19:12:16 oes
409 * introduced new cgi handling
411 * Revision 1.17 2001/06/01 20:07:23 jongfoster
412 * Now uses action +image-blocker{} rather than config->tinygif
414 * Revision 1.16 2001/06/01 18:49:17 jongfoster
415 * Replaced "list_share" with "list" - the tiny memory gain was not
416 * worth the extra complexity.
418 * Revision 1.15 2001/05/31 21:24:47 jongfoster
419 * Changed "permission" to "action" throughout.
420 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
421 * Moved vanilla wafer check into chat(), since we must now
422 * decide whether or not to add it based on the URL.
424 * Revision 1.14 2001/05/29 20:14:01 joergs
425 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
428 * Revision 1.13 2001/05/29 09:50:24 jongfoster
429 * Unified blocklist/imagelist/permissionslist.
430 * File format is still under discussion, but the internal changes
433 * Also modified interceptor behaviour:
434 * - We now intercept all URLs beginning with one of the following
435 * prefixes (and *only* these prefixes):
437 * * http://ijbswa.sf.net/config/
438 * * http://ijbswa.sourceforge.net/config/
439 * - New interceptors "home page" - go to http://i.j.b/ to see it.
440 * - Internal changes so that intercepted and fast redirect pages
441 * are not replaced with an image.
442 * - Interceptors now have the option to send a binary page direct
443 * to the client. (i.e. ijb-send-banner uses this)
444 * - Implemented show-url-info interceptor. (Which is why I needed
445 * the above interceptors changes - a typical URL is
446 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
447 * The previous mechanism would not have intercepted that, and
448 * if it had been intercepted then it then it would have replaced
451 * Revision 1.12 2001/05/27 22:17:04 oes
453 * - re_process_buffer no longer writes the modified buffer
454 * to the client, which was very ugly. It now returns the
455 * buffer, which it is then written by chat.
457 * - content_length now adjusts the Content-Length: header
458 * for modified documents rather than crunch()ing it.
459 * (Length info in csp->content_length, which is 0 for
460 * unmodified documents)
462 * - For this to work, sed() is called twice when filtering.
464 * Revision 1.11 2001/05/26 17:27:53 jongfoster
465 * Added support for CLF and fixed LOG_LEVEL_LOG.
466 * Also did CRLF->LF fix of my previous patch.
468 * Revision 1.10 2001/05/26 15:26:15 jongfoster
469 * ACL feature now provides more security by immediately dropping
470 * connections from untrusted hosts.
472 * Revision 1.9 2001/05/26 00:28:36 jongfoster
473 * Automatic reloading of config file.
474 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
475 * Most of the global variables have been moved to a new
476 * struct configuration_spec, accessed through csp->config->globalname
477 * Most of the globals remaining are used by the Win32 GUI.
479 * Revision 1.8 2001/05/25 22:43:18 jongfoster
480 * Fixing minor memory leak and buffer overflow.
482 * Revision 1.7 2001/05/25 22:34:30 jongfoster
485 * Revision 1.6 2001/05/23 00:13:58 joergs
486 * AmigaOS support fixed.
488 * Revision 1.5 2001/05/22 18:46:04 oes
490 * - Enabled filtering banners by size rather than URL
491 * by adding patterns that replace all standard banner
492 * sizes with the "Junkbuster" gif to the re_filterfile
494 * - Enabled filtering WebBugs by providing a pattern
495 * which kills all 1x1 images
497 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
498 * which is selected by the (nonstandard and therefore
499 * capital) letter 'U' in the option string.
500 * It causes the quantifiers to be ungreedy by default.
501 * Appending a ? turns back to greedy (!).
503 * - Added a new interceptor ijb-send-banner, which
504 * sends back the "Junkbuster" gif. Without imagelist or
505 * MSIE detection support, or if tinygif = 1, or the
506 * URL isn't recognized as an imageurl, a lame HTML
507 * explanation is sent instead.
509 * - Added new feature, which permits blocking remote
510 * script redirects and firing back a local redirect
512 * The feature is conditionally compiled, i.e. it
513 * can be disabled with --disable-fast-redirects,
514 * plus it must be activated by a "fast-redirects"
515 * line in the config file, has its own log level
516 * and of course wants to be displayed by show-proxy-args
517 * Note: Boy, all the #ifdefs in 1001 locations and
518 * all the fumbling with configure.in and acconfig.h
519 * were *way* more work than the feature itself :-(
521 * - Because a generic redirect template was needed for
522 * this, tinygif = 3 now uses the same.
524 * - Moved GIFs, and other static HTTP response templates
529 * - Removed some >400 CRs again (Jon, you really worked
532 * Revision 1.4 2001/05/21 19:34:01 jongfoster
533 * Made failure to bind() a fatal error.
535 * Revision 1.3 2001/05/20 01:21:20 jongfoster
536 * Version 2.9.4 checkin.
537 * - Merged popupfile and cookiefile, and added control over PCRS
538 * filtering, in new "permissionsfile".
539 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
540 * file error you now get a message box (in the Win32 GUI) rather
541 * than the program exiting with no explanation.
542 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
544 * - Removed tabs from "config"
545 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
546 * - Bumped up version number.
548 * Revision 1.2 2001/05/17 22:34:44 oes
549 * - Added hint on GIF char array generation to jcc.c
550 * - Cleaned CRLF's from the sources and related files
551 * - Repaired logging for REF and FRC
553 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
554 * Initial import of version 2.9.3 source tree
557 *********************************************************************/
563 #include <sys/types.h>
570 #ifdef FEATURE_PTHREAD
572 #endif /* def FEATURE_PTHREAD */
575 # ifndef FEATURE_PTHREAD
579 # include <windows.h>
580 # include <process.h>
581 # endif /* ndef FEATURE_PTHREAD */
584 # ifndef _WIN_CONSOLE
586 # endif /* ndef _WIN_CONSOLE */
588 #else /* ifndef _WIN32 */
590 # if !defined (__OS2__)
592 # include <sys/wait.h>
593 # endif /* ndef __OS2__ */
594 # include <sys/time.h>
595 # include <sys/stat.h>
596 # include <sys/ioctl.h>
599 #include <sys/termios.h>
610 # include <socket.h> /* BeOS has select() for sockets only. */
611 # include <OS.h> /* declarations for threads and stuff. */
614 # if defined(__EMX__) || defined(__OS2__)
615 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
620 #define bzero(B,N) memset(B,0x00,n)
635 #include "killpopup.h"
636 #include "miscutil.h"
638 #include "jbsockets.h"
643 #include "urlmatch.h"
645 const char jcc_h_rcs[] = JCC_H_VERSION;
646 const char project_h_rcs[] = PROJECT_H_VERSION;
649 struct client_state clients[1];
650 struct file_list files[1];
652 #ifdef FEATURE_STATISTICS
653 int urls_read = 0; /* total nr of urls read inc rejected */
654 int urls_rejected = 0; /* total nr of urls rejected */
655 #endif /* def FEATURE_STATISTICS */
657 #ifdef FEATURE_GRACEFUL_TERMINATION
661 static void listen_loop(void);
662 static void chat(struct client_state *csp);
664 void serve(struct client_state *csp);
665 #else /* ifndef AMIGA */
666 static void serve(struct client_state *csp);
667 #endif /* def AMIGA */
670 static int32 server_thread(void *data);
671 #endif /* def __BEOS__ */
674 #define sleep(N) Sleep(((N) * 1000))
678 #define sleep(N) DosSleep(((N) * 100))
683 * Hit OSX over the head with a hammer. Protect all *_r functions.
685 pthread_mutex_t gmtime_mutex;
686 pthread_mutex_t localtime_mutex;
687 pthread_mutex_t gethostbyaddr_mutex;
688 pthread_mutex_t gethostbyname_mutex;
689 #endif /* def OSX_DARWIN */
691 #if defined(unix) || defined(__EMX__)
693 const char *pidfile = NULL;
694 int received_hup_signal = 0;
695 #endif /* defined unix */
697 /* The vanilla wafer. */
698 static const char VANILLA_WAFER[] =
699 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
700 "Do_not_send_me_any_copyrighted_information_other_than_the_"
701 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
702 "In_particular_do_not_send_me_any_cookies_that_"
703 "are_subject_to_a_claim_of_copyright_by_anybody._"
704 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
705 "(copyright_or_otherwise)_applying_to_any_cookie._";
708 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
709 /*********************************************************************
711 * Function : sig_handler
713 * Description : Signal handler for different signals.
714 * Exit gracefully on ABRT, TERM and INT
715 * or set a flag that will cause the errlog
716 * to be reopened by the main thread on HUP.
719 * 1 : the_signal = the signal cause this function to call
723 *********************************************************************/
724 static void sig_handler(int the_signal)
731 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
739 received_hup_signal = 1;
744 * We shouldn't be here, unless we catch signals
745 * in main() that we can't handle here!
747 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
755 /*********************************************************************
759 * Description : Once a connection to the client has been accepted,
760 * this function is called (via serve()) to handle the
761 * main business of the communication. When this
762 * function returns, the caller must close the client
766 * 1 : csp = Current client state (buffers, headers, etc...)
768 * Returns : On success, the number of bytes written are returned (zero
769 * indicates nothing was written). On error, -1 is returned,
770 * and errno is set appropriately. If count is zero and the
771 * file descriptor refers to a regular file, 0 will be
772 * returned without causing any other effect. For a special
773 * file, the results are not portable.
775 *********************************************************************/
776 static void chat(struct client_state *csp)
779 * This next lines are a little ugly, but they simplifies the if statements
780 * below. Basically if TOGGLE, then we want the if to test if the
781 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
782 * then we want the if to test for CSP_FLAG_FORCED , else we don't
784 #ifdef FEATURE_TOGGLE
785 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
786 #else /* ifndef FEATURE_TOGGLE */
787 # define IS_TOGGLED_ON_AND
788 #endif /* ndef FEATURE_TOGGLE */
789 #ifdef FEATURE_FORCE_LOAD
790 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
791 #else /* ifndef FEATURE_FORCE_LOAD */
792 # define IS_NOT_FORCED_AND
793 #endif /* def FEATURE_FORCE_LOAD */
795 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
797 char buf[BUFFER_SIZE];
805 int ms_iis5_hack = 0;
807 const struct forward_spec * fwd;
808 struct http_request *http;
809 int len; /* for buffer sizes */
810 #ifdef FEATURE_KILL_POPUPS
811 int block_popups; /* bool, 1==will block popups */
812 int block_popups_now = 0; /* bool, 1==currently blocking popups */
813 #endif /* def FEATURE_KILL_POPUPS */
815 int pcrs_filter; /* bool, 1==will filter through pcrs */
816 int gif_deanimate; /* bool, 1==will deanimate gifs */
818 /* Function that does the content filtering for the current request */
819 char *(*content_filter)() = NULL;
821 /* Skeleton for HTTP response, if we should intercept the request */
822 struct http_response *rsp;
827 * Read the client's request. Note that since we're not using select() we
828 * could get blocked here if a client connected, then didn't say anything!
833 len = read_socket(csp->cfd, buf, sizeof(buf));
835 if (len <= 0) break; /* error! */
838 * If there is no memory left for buffering the
839 * request, there is nothing we can do but hang up
841 if (add_to_iob(csp, buf, len))
846 req = get_header(csp);
850 break; /* no HTTP request! */
855 continue; /* more to come! */
858 #ifdef FEATURE_FORCE_LOAD
859 /* If this request contains the FORCE_PREFIX,
860 * better get rid of it now and set the force flag --oes
863 if (strstr(req, FORCE_PREFIX))
865 strclean(req, FORCE_PREFIX);
866 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
867 csp->flags |= CSP_FLAG_FORCED;
870 #endif /* def FEATURE_FORCE_LOAD */
872 parse_http_request(req, http, csp);
877 if (http->cmd == NULL)
879 strcpy(buf, CHEADER);
880 write_socket(csp->cfd, buf, strlen(buf));
882 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
884 free_http_request(http);
888 /* decide how to route the HTTP request */
890 if ((fwd = forward_url(http, csp)) == NULL)
892 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
893 /* Never get here - LOG_LEVEL_FATAL causes program exit */
896 /* build the http request to send to the server
897 * we have to do one of the following:
899 * create = use the original HTTP request to create a new
900 * HTTP request that has either the path component
901 * without the http://domainspec (w/path) or the
902 * full orininal URL (w/url)
903 * Note that the path and/or the HTTP version may
904 * have been altered by now.
906 * connect = Open a socket to the host:port of the server
907 * and short-circuit server and client socket.
909 * pass = Pass the request unchanged if forwarding a CONNECT
910 * request to a parent proxy. Note that we'll be sending
911 * the CFAIL message ourselves if connecting to the parent
912 * fails, but we won't send a CSUCCEED message if it works,
913 * since that would result in a double message (ours and the
914 * parent's). After sending the request to the parent, we simply
920 * +--------+--------+
922 * 0 | create | connect|
924 * Forwarding +--------+--------+
926 * 1 | create | pass |
928 * +--------+--------+
933 * Determine the actions for this URL
935 #ifdef FEATURE_TOGGLE
936 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
938 /* Most compatible set of actions (i.e. none) */
939 init_current_action(csp->action);
942 #endif /* ndef FEATURE_TOGGLE */
944 url_actions(http, csp);
949 * Check if a CONNECT request is allowable:
950 * In the absence of a +limit-connect action, allow only port 443.
951 * If there is an action, allow whatever matches the specificaton.
955 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
956 || (csp->action->flags & ACTION_LIMIT_CONNECT
957 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
959 strcpy(buf, CFORBIDDEN);
960 write_socket(csp->cfd, buf, strlen(buf));
962 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
963 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
971 * Downgrade http version from 1.1 to 1.0 if +downgrade
974 if ( (http->ssl == 0)
975 && (!strcmpic(http->ver, "HTTP/1.1"))
976 && (csp->action->flags & ACTION_DOWNGRADE))
979 http->ver = strdup("HTTP/1.0");
981 if (http->ver == NULL)
983 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
988 * Save a copy of the original request for logging
990 http->ocmd = strdup(http->cmd);
992 if (http->ocmd == NULL)
994 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
998 * (Re)build the HTTP request for non-SSL requests.
999 * If forwarding, use the whole URL, else, use only the path.
1005 http->cmd = strdup(http->gpc);
1006 string_append(&http->cmd, " ");
1008 if (fwd->forward_host)
1010 string_append(&http->cmd, http->url);
1014 string_append(&http->cmd, http->path);
1016 string_append(&http->cmd, " ");
1017 string_append(&http->cmd, http->ver);
1019 if (http->cmd == NULL)
1021 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1023 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", http->cmd);
1025 enlist(csp->headers, http->cmd);
1029 * If the user has not supplied any wafers, and the user has not
1030 * told us to suppress the vanilla wafer, then send the vanilla wafer.
1032 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
1033 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
1035 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
1039 #ifdef FEATURE_KILL_POPUPS
1040 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1041 #endif /* def FEATURE_KILL_POPUPS */
1043 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
1044 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1046 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1048 /* grab the rest of the client's headers */
1052 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
1054 len = read_socket(csp->cfd, buf, sizeof(buf));
1057 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1062 * If there is no memory left for buffering the
1063 * request, there is nothing we can do but hang up
1065 if (add_to_iob(csp, buf, len))
1072 if (p == NULL) break;
1074 enlist(csp->headers, p);
1079 * We have a request. Now, check to see if we need to
1080 * intercept it, i.e. If ..
1084 /* We may not forward the request by rfc2616 sect 14.31 */
1085 (NULL != (rsp = direct_response(csp)))
1087 /* or a CGI call was detected and answered */
1088 || (NULL != (rsp = dispatch_cgi(csp)))
1090 /* or we are enabled and... */
1091 || (IS_ENABLED_AND (
1093 /* ..the request was blocked */
1094 ( NULL != (rsp = block_url(csp)))
1096 /* ..or untrusted */
1097 #ifdef FEATURE_TRUST
1098 || ( NULL != (rsp = trust_url(csp)))
1099 #endif /* def FEATURE_TRUST */
1101 /* ..or a fast redirect kicked in */
1102 #ifdef FEATURE_FAST_REDIRECTS
1103 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
1104 (NULL != (rsp = redirect_url(csp))))
1105 #endif /* def FEATURE_FAST_REDIRECTS */
1109 /* Write the answer to the client */
1110 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1111 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1113 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1116 #ifdef FEATURE_STATISTICS
1117 /* Count as a rejected request */
1118 csp->flags |= CSP_FLAG_REJECTED;
1119 #endif /* def FEATURE_STATISTICS */
1121 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
1122 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1123 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1125 /* Clean up and return */
1126 free_http_response(rsp);
1130 hdr = sed(client_patterns, add_client_headers, csp);
1133 /* FIXME Should handle error properly */
1134 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1137 list_remove_all(csp->headers);
1139 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1141 if (fwd->forward_host)
1143 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1144 fwd->forward_host, fwd->forward_port, http->hostport);
1148 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1151 /* here we connect to the server, gateway, or the forwarder */
1153 csp->sfd = forwarded_connect(fwd, http, csp);
1155 if (csp->sfd == JB_INVALID_SOCKET)
1157 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1160 if (errno == EINVAL)
1162 rsp = error_response(csp, "no-such-domain", errno);
1164 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1165 csp->ip_addr_str, http->ocmd);
1169 rsp = error_response(csp, "connect-failed", errno);
1171 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1172 csp->ip_addr_str, http->ocmd);
1176 /* Write the answer to the client */
1179 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1180 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1182 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1186 free_http_response(rsp);
1191 log_error(LOG_LEVEL_CONNECT, "OK");
1193 if (fwd->forward_host || (http->ssl == 0))
1195 /* write the client's (modified) header to the server
1196 * (along with anything else that may be in the buffer)
1199 if (write_socket(csp->sfd, hdr, strlen(hdr))
1200 || (flush_socket(csp->sfd, csp) < 0))
1202 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1205 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1206 csp->ip_addr_str, http->ocmd);
1208 rsp = error_response(csp, "connect-failed", errno);
1212 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1213 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1215 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1219 free_http_response(rsp);
1227 * We're running an SSL tunnel and we're not forwarding,
1228 * so just send the "connect succeeded" message to the
1229 * client, flush the rest, and get out of the way.
1231 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1232 csp->ip_addr_str, http->ocmd);
1234 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1242 /* we're finished with the client's header */
1245 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1247 /* pass data between the client and server
1248 * until one or the other shuts down the connection.
1257 * FD_ZERO here seems to point to an errant macro which crashes.
1258 * So do this by hand for now...
1260 memset(&rfds,0x00,sizeof(fd_set));
1264 FD_SET(csp->cfd, &rfds);
1265 FD_SET(csp->sfd, &rfds);
1267 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1271 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1275 /* this is the body of the browser's request
1276 * just read it and write it.
1279 if (FD_ISSET(csp->cfd, &rfds))
1281 len = read_socket(csp->cfd, buf, sizeof(buf));
1285 break; /* "game over, man" */
1288 if (write_socket(csp->sfd, buf, (size_t)len))
1290 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1297 * The server wants to talk. It could be the header or the body.
1298 * If `hdr' is null, then it's the header otherwise it's the body.
1299 * FIXME: Does `hdr' really mean `host'? No.
1303 if (FD_ISSET(csp->sfd, &rfds))
1306 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1310 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1312 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1313 csp->ip_addr_str, http->ocmd);
1315 rsp = error_response(csp, "connect-failed", errno);
1319 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1320 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1322 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1326 free_http_response(rsp);
1330 /* Add a trailing zero. This lets filter_popups
1331 * use string operations.
1335 #ifdef FEATURE_KILL_POPUPS
1336 /* Filter the popups on this read. */
1337 if (block_popups_now)
1339 filter_popups(buf, csp);
1341 #endif /* def FEATURE_KILL_POPUPS */
1343 /* Normally, this would indicate that we've read
1344 * as much as the server has sent us and we can
1345 * close the client connection. However, Microsoft
1346 * in its wisdom has released IIS/5 with a bug that
1347 * prevents it from sending the trailing \r\n in
1348 * a 302 redirect header (and possibly other headers).
1349 * To work around this if we've haven't parsed
1350 * a full header we'll append a trailing \r\n
1351 * and see if this now generates a valid one.
1353 * This hack shouldn't have any impacts. If we've
1354 * already transmitted the header or if this is a
1355 * SSL connection, then we won't bother with this
1356 * hack. So we only work on partially received
1357 * headers. If we append a \r\n and this still
1358 * doesn't generate a valid header, then we won't
1359 * transmit anything to the client.
1364 if (server_body || http->ssl)
1367 * If we have been buffering up the document,
1368 * now is the time to apply content modification
1369 * and send the result to the client.
1374 * If the content filter fails, use the original
1375 * buffer and length.
1376 * (see p != NULL ? p : csp->iob->cur below)
1378 if (NULL == (p = (*content_filter)(csp)))
1380 csp->content_length = csp->iob->eod - csp->iob->cur;
1383 hdr = sed(server_patterns, add_server_headers, csp);
1386 /* FIXME Should handle error properly */
1387 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1390 if (write_socket(csp->cfd, hdr, strlen(hdr))
1391 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1393 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1403 break; /* "game over, man" */
1407 * This is NOT the body, so
1408 * Let's pretend the server just sent us a blank line.
1410 len = sprintf(buf, "\r\n");
1413 * Now, let the normal header parsing algorithm below do its
1414 * job. If it fails, we'll exit instead of continuing.
1421 * If this is an SSL connection or we're in the body
1422 * of the server document, just write it to the client,
1423 * unless we need to buffer the body for later content-filtering
1426 if (server_body || http->ssl)
1431 * If there is no memory left for buffering the content, or the buffer limit
1432 * has been reached, switch to non-filtering mode, i.e. make & write the
1433 * header, flush the iob and buf, and get out of the way.
1435 if (add_to_iob(csp, buf, len))
1440 log_error(LOG_LEVEL_ERROR, "Flushing header and buffers. Stepping back from filtering.");
1442 hdr = sed(server_patterns, add_server_headers, csp);
1446 * Memory is too tight to even generate the header.
1447 * Send our static "Out-of-memory" page.
1449 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
1450 rsp = cgi_error_memory();
1452 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1453 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1455 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1460 hdrlen = strlen(hdr);
1462 if (write_socket(csp->cfd, hdr, hdrlen)
1463 || ((flushed = flush_socket(csp->cfd, csp)) < 0)
1464 || (write_socket(csp->cfd, buf, len)))
1466 log_error(LOG_LEVEL_CONNECT, "Flush header and buffers to client failed: %E");
1472 byte_count += hdrlen + flushed + len;
1474 content_filter = NULL;
1481 if (write_socket(csp->cfd, buf, (size_t)len))
1483 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1492 /* we're still looking for the end of the
1493 * server's header ... (does that make header
1494 * parsing an "out of body experience" ?
1498 * buffer up the data we just read. If that fails,
1499 * there's little we can do but send our static
1500 * out-of-memory page.
1502 if (add_to_iob(csp, buf, len))
1504 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
1505 rsp = cgi_error_memory();
1507 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1508 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1510 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1515 /* get header lines from the iob */
1517 while ((p = get_header(csp)) != NULL)
1521 /* see following note */
1524 enlist(csp->headers, p);
1528 /* NOTE: there are no "empty" headers so
1529 * if the pointer `p' is not NULL we must
1530 * assume that we reached the end of the
1531 * buffer before we hit the end of the header.
1538 /* Well, we tried our MS IIS/5
1539 * hack and it didn't work.
1540 * The header is incomplete
1541 * and there isn't anything
1542 * we can do about it.
1548 /* Since we have to wait for
1549 * more from the server before
1550 * we can parse the headers
1551 * we just continue here.
1557 /* we have now received the entire header.
1558 * filter it and send the result to the client
1561 hdr = sed(server_patterns, add_server_headers, csp);
1564 /* FIXME Should handle error properly */
1565 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1568 #ifdef FEATURE_KILL_POPUPS
1569 /* Start blocking popups if appropriate. */
1571 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1572 !http->ssl && /* We talk plaintext */
1573 block_popups) /* Policy allows */
1575 block_popups_now = 1;
1577 * Filter the part of the body that came in the same read
1578 * as the last headers:
1580 filter_popups(csp->iob->cur, csp);
1583 #endif /* def FEATURE_KILL_POPUPS */
1585 /* Buffer and pcrs filter this if appropriate. */
1587 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1588 !http->ssl && /* We talk plaintext */
1589 pcrs_filter) /* Policy allows */
1591 content_filter = pcrs_filter_response;
1594 /* Buffer and gif_deanimate this if appropriate. */
1596 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1597 !http->ssl && /* We talk plaintext */
1598 gif_deanimate) /* Policy allows */
1600 content_filter = gif_deanimate_response;
1604 * Only write if we're not buffering for content modification
1606 if (!content_filter)
1608 /* write the server's (modified) header to
1609 * the client (along with anything else that
1610 * may be in the buffer)
1613 if (write_socket(csp->cfd, hdr, strlen(hdr))
1614 || ((len = flush_socket(csp->cfd, csp)) < 0))
1616 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1618 /* the write failed, so don't bother
1619 * mentioning it to the client...
1620 * it probably can't hear us anyway.
1629 /* we're finished with the server's header */
1634 /* If this was a MS IIS/5 hack then it means
1635 * the server has already closed the
1636 * connection. Nothing more to read. Time
1647 return; /* huh? we should never get here */
1650 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1651 csp->ip_addr_str, http->ocmd, byte_count);
1655 /*********************************************************************
1659 * Description : This is little more than chat. We only "serve" to
1660 * to close any socket that chat may have opened.
1663 * 1 : csp = Current client state (buffers, headers, etc...)
1667 *********************************************************************/
1669 void serve(struct client_state *csp)
1670 #else /* ifndef AMIGA */
1671 static void serve(struct client_state *csp)
1672 #endif /* def AMIGA */
1675 close_socket(csp->cfd);
1677 if (csp->sfd != JB_INVALID_SOCKET)
1679 close_socket(csp->sfd);
1682 csp->flags &= ~CSP_FLAG_ACTIVE;
1688 /*********************************************************************
1690 * Function : server_thread
1692 * Description : We only exist to call `serve' in a threaded environment.
1695 * 1 : data = Current client state (buffers, headers, etc...)
1697 * Returns : Always 0.
1699 *********************************************************************/
1700 static int32 server_thread(void *data)
1702 serve((struct client_state *) data);
1709 /*********************************************************************
1713 * Description : Print usage info & exit.
1715 * Parameters : Pointer to argv[0] for identifying ourselves
1719 *********************************************************************/
1720 void usage(const char *myname)
1722 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
1723 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1724 "Aborting.\n", myname);
1731 /*********************************************************************
1735 * Description : Load the config file and start the listen loop.
1736 * This function is a lot more *sane* with the `load_config'
1737 * and `listen_loop' functions; although it stills does
1738 * a *little* too much for my taste.
1741 * 1 : argc = Number of parameters (including $0).
1742 * 2 : argv = Array of (char *)'s to the parameters.
1744 * Returns : 1 if : can't open config file, unrecognized directive,
1745 * stats requested in multi-thread mode, can't open the
1746 * log file, can't open the jar file, listen port is invalid,
1747 * any load fails, and can't bind port.
1749 * Else main never returns, the process must be signaled
1750 * to terminate execution. Or, on Windows, use the
1751 * "File", "Exit" menu option.
1753 *********************************************************************/
1755 int real_main(int argc, const char *argv[])
1757 int main(int argc, const char *argv[])
1762 struct passwd *pw = NULL;
1763 struct group *grp = NULL;
1771 #if !defined(_WIN32)
1779 * Parse the command line arguments
1781 while (++argc_pos < argc)
1783 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1785 if (strcmp(argv[argc_pos], "--help") == 0)
1790 else if(strcmp(argv[argc_pos], "--version") == 0)
1792 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1796 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1801 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1803 if (++argc_pos == argc) usage(argv[0]);
1804 pidfile = strdup(argv[argc_pos]);
1807 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1809 if (++argc_pos == argc) usage(argv[argc_pos]);
1811 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1814 if (NULL == (grp = getgrnam(p)))
1816 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1820 if (NULL == (pw = getpwnam(argv[argc_pos])))
1822 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1825 if (p != NULL) *--p = '\0';
1827 #endif /* defined(unix) */
1829 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1831 configfile = argv[argc_pos];
1834 } /* -END- while (more arguments) */
1837 if ( *configfile != '/' )
1841 /* make config-filename absolute here */
1842 if ( !(basedir = getcwd( NULL, 1024 )))
1844 perror("get working dir failed");
1848 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1850 perror("malloc failed");
1853 strcpy( abs_file, basedir );
1854 strcat( abs_file, "/" );
1855 strcat( abs_file, configfile );
1856 configfile = abs_file;
1858 #endif /* defined unix */
1862 clients->next = NULL;
1866 #elif defined(_WIN32)
1872 * Prepare global mutex semaphores
1874 pthread_mutex_init(&gmtime_mutex,0);
1875 pthread_mutex_init(&localtime_mutex,0);
1876 pthread_mutex_init(&gethostbyaddr_mutex,0);
1877 pthread_mutex_init(&gethostbyname_mutex,0);
1878 #endif /* def OSX_DARWIN */
1881 * Unix signal handling
1883 * Catch the abort, interrupt and terminate signals for a graceful exit
1884 * Catch the hangup signal so the errlog can be reopened.
1885 * Ignore the broken pipe and child signals
1886 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1888 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1891 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1892 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1894 for (idx = 0; catched_signals[idx] != 0; idx++)
1896 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1898 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1902 for (idx = 0; ignored_signals[idx] != 0; idx++)
1904 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1906 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1911 #else /* ifdef _WIN32 */
1912 # ifdef _WIN_CONSOLE
1914 * We *are* in a windows console app.
1915 * Print a verbose messages about FAQ's and such
1917 printf(win32_blurb);
1918 # endif /* def _WIN_CONSOLE */
1919 #endif /* def _WIN32 */
1922 /* Initialize the CGI subsystem */
1923 cgi_init_error_messages();
1926 * If runnig on unix and without the --nodaemon
1927 * option, become a daemon. I.e. fork, detach
1928 * from tty and get process group leadership
1941 if ( pid < 0 ) /* error */
1946 else if ( pid != 0 ) /* parent */
1951 * must check for errors
1952 * child died due to missing files aso
1955 wpid = waitpid( pid, &status, WNOHANG );
1964 /* Should be more portable, but not as well tested */
1969 #else /* ndef __FreeBSD__ */
1971 #endif /* ndef __FreeBSD__ */
1972 fd = open("/dev/tty", O_RDONLY);
1975 /* no error check here */
1976 ioctl( fd, TIOCNOTTY,0 );
1980 /* FIXME: should close stderr (fd 2) here too, but the test
1982 * and load config file is done in listen_loop() and puts
1983 * some messages on stderr there.
1990 } /* -END- if (!no_daemon) */
1993 * As soon as we have written the PID file, we can switch
1994 * to the user and group ID indicated by the --user option
2000 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
2002 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
2004 if (setuid(pw->pw_uid))
2006 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
2010 #endif /* defined unix */
2020 /*********************************************************************
2022 * Function : bind_port_helper
2024 * Description : Bind the listen port. Handles logging, and aborts
2028 * 1 : config = Privoxy configuration. Specifies port
2031 * Returns : Port that was opened.
2033 *********************************************************************/
2034 static jb_socket bind_port_helper(struct configuration_spec * config)
2039 if ( (config->haddr != NULL)
2040 && (config->haddr[0] == '1')
2041 && (config->haddr[1] == '2')
2042 && (config->haddr[2] == '7')
2043 && (config->haddr[3] == '.') )
2045 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
2048 else if (config->haddr == NULL)
2050 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
2055 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
2056 config->hport, config->haddr);
2059 result = bind_port(config->haddr, config->hport, &bfd);
2066 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2067 "There may be another Privoxy or some other "
2068 "proxy running on port %d",
2069 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
2070 config->hport, config->hport);
2073 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2074 "The hostname is not resolvable",
2075 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2078 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
2079 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2082 /* shouldn't get here */
2083 return JB_INVALID_SOCKET;
2086 config->need_bind = 0;
2092 /*********************************************************************
2094 * Function : listen_loop
2096 * Description : bind the listen port and enter a "FOREVER" listening loop.
2102 *********************************************************************/
2103 static void listen_loop(void)
2105 struct client_state *csp = NULL;
2107 struct configuration_spec * config;
2109 config = load_config();
2111 bfd = bind_port_helper(config);
2113 #ifdef FEATURE_GRACEFUL_TERMINATION
2114 while (!g_terminate)
2119 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
2120 while (waitpid(-1, NULL, WNOHANG) > 0)
2122 /* zombie children */
2124 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2127 * Free data that was used by died threads
2133 * Re-open the errlog after HUP signal
2135 if (received_hup_signal)
2137 init_error_log(Argv[0], config->logfile, config->debug);
2138 received_hup_signal = 0;
2143 #ifdef FEATURE_COOKIE_JAR
2145 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
2146 * already open. I think unload_configfile() is not being run, which should do
2147 * this work. Until that can get resolved, we'll use this workaround.
2151 if (csp->config->jar)
2153 fclose(csp->config->jar);
2154 csp->config->jar = NULL;
2156 #endif /* FEATURE_COOKIE_JAR */
2157 #endif /* __OS2__ */
2159 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2161 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2165 csp->flags |= CSP_FLAG_ACTIVE;
2166 csp->sfd = JB_INVALID_SOCKET;
2168 csp->config = config = load_config();
2170 if ( config->need_bind )
2173 * Since we were listening to the "old port", we will not see
2174 * a "listen" param change until the next IJB request. So, at
2175 * least 1 more request must be made for us to find the new
2176 * setting. I am simply closing the old socket and binding the
2179 * Which-ever is correct, we will serve 1 more page via the
2180 * old settings. This should probably be a "show-proxy-args"
2181 * request. This should not be a so common of an operation
2182 * that this will hurt people's feelings.
2187 bfd = bind_port_helper(config);
2190 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2192 if (!accept_connection(csp, bfd))
2194 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2207 log_error(LOG_LEVEL_CONNECT, "OK");
2210 #ifdef FEATURE_TOGGLE
2211 if (global_toggle_state)
2213 csp->flags |= CSP_FLAG_TOGGLED_ON;
2215 #endif /* def FEATURE_TOGGLE */
2217 if (run_loader(csp))
2219 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2220 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2224 if (block_acl(NULL,csp))
2226 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2227 close_socket(csp->cfd);
2231 #endif /* def FEATURE_ACL */
2233 /* add it to the list of clients */
2234 csp->next = clients->next;
2235 clients->next = csp;
2237 if (config->multi_threaded)
2241 /* this is a switch () statment in the C preprocessor - ugh */
2242 #undef SELECTED_ONE_OPTION
2244 /* Use Pthreads in preference to native code */
2245 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2246 #define SELECTED_ONE_OPTION
2248 pthread_t the_thread;
2249 pthread_attr_t attrs;
2251 pthread_attr_init(&attrs);
2252 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2253 child_id = (pthread_create(&the_thread, &attrs,
2254 (void*)serve, csp) ? -1 : 0);
2255 pthread_attr_destroy(&attrs);
2259 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2260 #define SELECTED_ONE_OPTION
2261 child_id = _beginthread(
2262 (void (*)(void *))serve,
2267 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2268 #define SELECTED_ONE_OPTION
2269 child_id = _beginthread(
2270 (void(* _Optlink)(void*))serve,
2276 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2277 #define SELECTED_ONE_OPTION
2279 thread_id tid = spawn_thread
2280 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2282 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2284 child_id = (int) tid;
2293 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2294 #define SELECTED_ONE_OPTION
2295 csp->cfd = ReleaseSocket(csp->cfd, -1);
2297 if((child_id = (int)CreateNewProcTags(
2298 NP_Entry, (ULONG)server_thread,
2299 NP_Output, Output(),
2300 NP_CloseOutput, FALSE,
2301 NP_Name, (ULONG)"privoxy child",
2302 NP_StackSize, 200*1024,
2306 ((struct Task *)child_id)->tc_UserData = csp;
2307 Signal((struct Task *)child_id, SIGF_SINGLE);
2312 #if !defined(SELECTED_ONE_OPTION)
2315 /* This block is only needed when using fork().
2316 * When using threads, the server thread was
2317 * created and run by the call to _beginthread().
2319 if (child_id == 0) /* child */
2322 #ifdef FEATURE_TOGGLE
2323 int inherited_toggle_state = global_toggle_state;
2324 #endif /* def FEATURE_TOGGLE */
2329 * If we've been toggled or we'be blocked the request, tell Mom
2332 #ifdef FEATURE_TOGGLE
2333 if (inherited_toggle_state != global_toggle_state)
2335 rc |= RC_FLAG_TOGGLED;
2337 #endif /* def FEATURE_TOGGLE */
2339 #ifdef FEATURE_STATISTICS
2340 if (csp->flags & CSP_FLAG_REJECTED)
2342 rc |= RC_FLAG_BLOCKED;
2344 #endif /* ndef FEATURE_STATISTICS */
2348 else if (child_id > 0) /* parent */
2350 /* in a fork()'d environment, the parent's
2351 * copy of the client socket and the CSP
2355 #if !defined(_WIN32) && !defined(__CYGWIN__)
2357 wait( &child_status );
2360 * Evaluate child's return code: If the child has
2361 * - been toggled, toggle ourselves
2362 * - blocked its request, bump up the stats counter
2365 #ifdef FEATURE_TOGGLE
2366 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
2368 global_toggle_state = !global_toggle_state;
2370 #endif /* def FEATURE_TOGGLE */
2372 #ifdef FEATURE_STATISTICS
2374 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
2378 #endif /* def FEATURE_STATISTICS */
2380 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2381 close_socket(csp->cfd);
2382 csp->flags &= ~CSP_FLAG_ACTIVE;
2386 #undef SELECTED_ONE_OPTION
2387 /* end of cpp switch () */
2389 if (child_id < 0) /* failed */
2391 char buf[BUFFER_SIZE];
2393 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2395 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
2397 write_socket(csp->cfd, buf, strlen(buf));
2398 close_socket(csp->cfd);
2399 csp->flags &= ~CSP_FLAG_ACTIVE;
2410 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2412 /* Clean up. Aim: free all memory (no leaks) */
2413 #ifdef FEATURE_GRACEFUL_TERMINATION
2415 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2417 unload_current_config_file();
2418 unload_current_actions_file();
2419 unload_current_re_filterfile();
2420 #ifdef FEATURE_TRUST
2421 unload_current_trust_file();
2424 if (config->multi_threaded)
2431 } while ((clients->next != NULL) && (--i > 0));
2435 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2444 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2445 /* Cleanup - remove taskbar icon etc. */
2450 #endif /* FEATURE_GRACEFUL_TERMINATION */