1 const char jcc_rcs[] = "$Id: jcc.c,v 1.91 2002/04/08 20:35:58 swa Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001 the SourceForge
10 * 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.91 2002/04/08 20:35:58 swa
39 * Revision 1.90 2002/04/02 14:57:28 oes
40 * Made sending wafers independent of FEATURE_COOKIE_JAR
42 * Revision 1.89 2002/03/31 17:18:59 jongfoster
43 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
45 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
46 * More compiler warning message maintenance
48 * Revision 1.87 2002/03/26 22:29:54 swa
49 * we have a new homepage!
51 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
52 * Workaround for closing the jarfile before load_config() comes around again
54 * Revision 1.85 2002/03/24 15:23:33 jongfoster
57 * Revision 1.84 2002/03/24 13:25:43 swa
58 * name change related issues
60 * Revision 1.83 2002/03/16 23:54:06 jongfoster
61 * Adding graceful termination feature, to help look for memory leaks.
62 * If you enable this (which, by design, has to be done by hand
63 * editing config.h) and then go to http://i.j.b/die, then the program
64 * will exit cleanly after the *next* request. It should free all the
65 * memory that was used.
67 * Revision 1.82 2002/03/13 00:27:05 jongfoster
70 * Revision 1.81 2002/03/12 01:42:50 oes
71 * Introduced modular filters
73 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
74 * OS/2 port maintenance:
75 * - Fixed EMX build - it had decayed a little
76 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
77 * substituted a memset for now.
79 * Revision 1.79 2002/03/09 20:03:52 jongfoster
80 * - Making various functions return int rather than size_t.
81 * (Undoing a recent change). Since size_t is unsigned on
82 * Windows, functions like read_socket that return -1 on
83 * error cannot return a size_t.
85 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
86 * crashes, and also frequently caused JB to jump to 100%
87 * CPU and stay there. (Because it thought it had just
88 * read ((unsigned)-1) == 4Gb of data...)
90 * - The signature of write_socket has changed, it now simply
91 * returns success=0/failure=nonzero.
93 * - Trying to get rid of a few warnings --with-debug on
94 * Windows, I've introduced a new type "jb_socket". This is
95 * used for the socket file descriptors. On Windows, this
96 * is SOCKET (a typedef for unsigned). Everywhere else, it's
97 * an int. The error value can't be -1 any more, so it's
98 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
99 * Windows it maps to the #define INVALID_SOCKET.)
101 * - The signature of bind_port has changed.
103 * Revision 1.78 2002/03/08 21:35:04 oes
104 * Added optional group supplement to --user option. Will now use default group of user if no group given
106 * Revision 1.77 2002/03/07 03:52:06 oes
107 * - Fixed compiler warnings etc
108 * - Improved handling of failed DNS lookups
110 * Revision 1.76 2002/03/06 22:54:35 jongfoster
111 * Automated function-comment nitpicking.
113 * Revision 1.75 2002/03/06 10:02:19 oes
114 * Fixed stupid bug when --user was not given
116 * Revision 1.74 2002/03/06 00:49:31 jongfoster
117 * Fixing warning on Windows
118 * Making #ifdefs that refer to the same variable consistently
119 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
121 * Revision 1.73 2002/03/05 23:57:30 hal9
122 * Stray character 's' on line 1618 was breaking build.
124 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
125 * - Re-enable OS/2 building after new parms were added
126 * - Fix false out of memory report when resolving CGI templates when no IP
127 * address is available of failed attempt (a la no such domain)
129 * Revision 1.71 2002/03/05 18:13:56 oes
130 * Added --user option
132 * Revision 1.70 2002/03/05 04:52:42 oes
133 * Deleted non-errlog debugging code
135 * Revision 1.69 2002/03/04 23:50:00 jongfoster
136 * Splitting off bind_port() call into bind_port_helper(), with
139 * Revision 1.68 2002/03/04 20:17:32 oes
142 * Revision 1.67 2002/03/04 18:18:57 oes
143 * - Removed _DEBUG mode
144 * - Cleand up cmdline parsing
145 * - Introduced --no-daemon, --pidfile options
146 * - Cleaned up signal handling:
147 * - Terminate cleanly on INT, TERM and ABRT
148 * - Schedule logfile for re-opening on HUP
149 * - Ignore CHLD and PIPE
150 * - Leave the rest with their default handlers
151 * - Uniform handler registration
152 * - Added usage() function
153 * - Played styleguide police
155 * Revision 1.66 2002/03/03 15:06:55 oes
156 * Re-enabled automatic config reloading
158 * Revision 1.65 2002/03/03 14:49:11 oes
159 * Fixed CLF logging: Now uses client's original HTTP request
161 * Revision 1.64 2002/03/03 09:18:03 joergs
162 * Made jumbjuster work on AmigaOS again.
164 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
165 * Clean up a little CRLF unpleasantness that suddenly appeared
167 * Revision 1.62 2002/02/20 23:17:23 jongfoster
168 * Detecting some out-of memory conditions and exiting with a log message.
170 * Revision 1.61 2002/01/17 21:01:52 jongfoster
171 * Moving all our URL and URL pattern parsing code to urlmatch.c.
173 * Revision 1.60 2001/12/30 14:07:32 steudten
174 * - Add signal handling (unix)
175 * - Add SIGHUP handler (unix)
176 * - Add creation of pidfile (unix)
177 * - Add action 'top' in rc file (RH)
178 * - Add entry 'SIGNALS' to manpage
179 * - Add exit message to logfile (unix)
181 * Revision 1.59 2001/12/13 14:07:18 oes
182 * Fixed Bug: 503 error page now sent OK
184 * Revision 1.58 2001/11/30 23:37:24 jongfoster
185 * Renaming the Win32 config file to config.txt - this is almost the
186 * same as the corresponding UNIX name "config"
188 * Revision 1.57 2001/11/16 00:47:43 jongfoster
189 * Changing the tty-disconnection code to use setsid().
191 * Revision 1.56 2001/11/13 20:20:54 jongfoster
192 * Tabs->spaces, fixing a bug with missing {} around an if()
194 * Revision 1.55 2001/11/13 20:14:53 jongfoster
195 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
197 * Revision 1.54 2001/11/07 00:03:14 steudten
198 * Give reliable return value if an error
199 * occurs not just 0 with new daemon mode.
201 * Revision 1.53 2001/11/05 21:41:43 steudten
202 * Add changes to be a real daemon just for unix os.
203 * (change cwd to /, detach from controlling tty, set
204 * process group and session leader to the own process.
206 * Add some fatal-error log message for failed malloc().
207 * Add '-d' if compiled with 'configure --with-debug' to
208 * enable debug output.
210 * Revision 1.52 2001/10/26 20:11:20 jongfoster
211 * Fixing type mismatch
213 * Revision 1.51 2001/10/26 17:38:28 oes
216 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
217 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
218 * threads to call select() simultaneously. So, it's time to do a real, live,
219 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
220 * (native). Both versions will work, but using __OS2__ offers multi-threading.
222 * Revision 1.49 2001/10/23 21:41:35 jongfoster
223 * Added call to initialize the (statically-allocated of course)
224 * "out of memory" CGI response.
226 * Revision 1.48 2001/10/10 19:56:46 jongfoster
227 * Moving some code that wasn't cookie-related out of an #ifdef
230 * Revision 1.47 2001/10/10 16:44:36 oes
231 * Added CONNECT destination port limitation check
233 * Revision 1.46 2001/10/08 15:17:41 oes
234 * Re-enabled SSL forwarding
236 * Revision 1.45 2001/10/07 15:42:11 oes
237 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
239 * Moved downgrading of the HTTP version from parse_http_request to
240 * chat(), since we can't decide if it is necessary before we have
241 * determined the actions for the URL. The HTTP command is now
242 * *always* re-built so the repairs need no longer be special-cased.
244 * filter_popups now gets a csp pointer so it can raise the new
245 * CSP_FLAG_MODIFIED flag.
249 * Added configurable size limit for the IOB. If the IOB grows so
250 * large that the next read would exceed the limit, the header
251 * is generated, and the header & unfiltered buffer are flushed
252 * to the client. Chat then continues in non-buffering,
253 * non-filtering body mode.
255 * Revision 1.44 2001/10/02 18:13:57 oes
258 * Revision 1.43 2001/10/02 15:32:13 oes
259 * Moved generation of hdr
261 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
262 * Cleaning up 2 compiler warnings on OS/2.
264 * Revision 1.41 2001/09/16 17:05:14 jongfoster
265 * Removing unused #include showarg.h
267 * Revision 1.40 2001/09/16 15:41:45 jongfoster
268 * Fixing signed/unsigned comparison warning.
270 * Revision 1.39 2001/09/16 13:21:27 jongfoster
271 * Changes to use new list functions.
273 * Revision 1.38 2001/09/16 13:01:46 jongfoster
274 * Removing redundant function call that zeroed zalloc()'d memory.
276 * Revision 1.37 2001/09/10 11:12:24 oes
277 * Deleted unused variable
279 * Revision 1.36 2001/09/10 10:56:15 oes
280 * Silenced compiler warnings
282 * Revision 1.35 2001/07/31 14:44:22 oes
283 * Deleted unused size parameter from filter_popups()
285 * Revision 1.34 2001/07/30 22:08:36 jongfoster
286 * Tidying up #defines:
287 * - All feature #defines are now of the form FEATURE_xxx
288 * - Permanently turned off WIN_GUI_EDIT
289 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
291 * Revision 1.33 2001/07/29 19:32:00 jongfoster
292 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
294 * Revision 1.32 2001/07/29 18:47:05 jongfoster
295 * Adding missing #include "loadcfg.h"
297 * Revision 1.31 2001/07/29 12:17:48 oes
298 * Applied pthread fix by Paul Lieverse
300 * Revision 1.30 2001/07/25 22:57:13 jongfoster
301 * __BEOS__ no longer overrides FEATURE_PTHREAD.
302 * This is because FEATURE_PTHREAD will soon be widely used, so I
303 * want to keep it simple.
305 * Revision 1.29 2001/07/24 12:47:06 oes
306 * Applied BeOS support update by Eugenia
308 * Revision 1.28 2001/07/23 13:26:12 oes
309 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
311 * Revision 1.27 2001/07/19 19:09:47 haroon
312 * - Added code to take care of the situation where while processing the first
313 * server response (which includes the server header), after finding the end
314 * of the headers we were not looking past the end of the headers for
315 * content modification. I enabled it for filter_popups.
316 * Someone else should look to see if other similar operations should be
317 * done to the discarded portion of the buffer.
319 * Note 2001/07/20: No, the other content modification mechanisms will process
320 * the whole iob later anyway. --oes
322 * Revision 1.26 2001/07/18 12:31:36 oes
325 * Revision 1.25 2001/07/15 19:43:49 jongfoster
326 * Supports POSIX threads.
327 * Also removed some unused #includes.
329 * Revision 1.24 2001/07/13 14:00:40 oes
330 * - Generic content modification scheme:
331 * Each feature has its own applicability flag that is set
332 * from csp->action->flags.
333 * Replaced the "filtering" int flag , by a function pointer
334 * "content_filter" to the function that will do the content
335 * modification. If it is != NULL, the document will be buffered
336 * and processed through *content_filter, which must set
337 * csp->content_length and return a modified copy of the body
338 * or return NULL (on failiure).
339 * - Changed csp->is_text to the more generic bitmap csp->content_type
340 * which can currently take the valued CT_TEXT or CT_GIF
342 * - Removed all #ifdef PCRS
344 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
345 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
346 * the `block_acl' call. This prevents a compilation error when the user
347 * does not wish to use the "ACL" feature.
349 * Revision 1.22 2001/06/29 21:45:41 oes
350 * Indentation, CRLF->LF, Tab-> Space
352 * Revision 1.21 2001/06/29 13:29:36 oes
353 * - Cleaned up, improved comments
354 * - Unified all possible interceptors (CGI,
355 * block, trust, fast_redirect) in one
356 * place, with one (CGI) answer generation
357 * mechansim. Much clearer now.
358 * - Removed the GIF image generation, which
359 * is now done in filters.c:block_url()
360 * - Made error conditions like domain lookup
361 * failiure or (various) problems while talking
362 * to the server use cgi.c:error_response()
363 * instead of generating HTML/HTTP in chat() (yuck!)
364 * - Removed logentry from cancelled commit
366 * Revision 1.20 2001/06/09 10:55:28 jongfoster
367 * Changing BUFSIZ ==> BUFFER_SIZE
369 * Revision 1.19 2001/06/07 23:12:52 jongfoster
370 * Replacing function pointer in struct gateway with a directly
371 * called function forwarded_connect().
372 * Replacing struct gateway with struct forward_spec
374 * Revision 1.18 2001/06/03 19:12:16 oes
375 * introduced new cgi handling
377 * Revision 1.17 2001/06/01 20:07:23 jongfoster
378 * Now uses action +image-blocker{} rather than config->tinygif
380 * Revision 1.16 2001/06/01 18:49:17 jongfoster
381 * Replaced "list_share" with "list" - the tiny memory gain was not
382 * worth the extra complexity.
384 * Revision 1.15 2001/05/31 21:24:47 jongfoster
385 * Changed "permission" to "action" throughout.
386 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
387 * Moved vanilla wafer check into chat(), since we must now
388 * decide whether or not to add it based on the URL.
390 * Revision 1.14 2001/05/29 20:14:01 joergs
391 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
394 * Revision 1.13 2001/05/29 09:50:24 jongfoster
395 * Unified blocklist/imagelist/permissionslist.
396 * File format is still under discussion, but the internal changes
399 * Also modified interceptor behaviour:
400 * - We now intercept all URLs beginning with one of the following
401 * prefixes (and *only* these prefixes):
403 * * http://ijbswa.sf.net/config/
404 * * http://ijbswa.sourceforge.net/config/
405 * - New interceptors "home page" - go to http://i.j.b/ to see it.
406 * - Internal changes so that intercepted and fast redirect pages
407 * are not replaced with an image.
408 * - Interceptors now have the option to send a binary page direct
409 * to the client. (i.e. ijb-send-banner uses this)
410 * - Implemented show-url-info interceptor. (Which is why I needed
411 * the above interceptors changes - a typical URL is
412 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
413 * The previous mechanism would not have intercepted that, and
414 * if it had been intercepted then it then it would have replaced
417 * Revision 1.12 2001/05/27 22:17:04 oes
419 * - re_process_buffer no longer writes the modified buffer
420 * to the client, which was very ugly. It now returns the
421 * buffer, which it is then written by chat.
423 * - content_length now adjusts the Content-Length: header
424 * for modified documents rather than crunch()ing it.
425 * (Length info in csp->content_length, which is 0 for
426 * unmodified documents)
428 * - For this to work, sed() is called twice when filtering.
430 * Revision 1.11 2001/05/26 17:27:53 jongfoster
431 * Added support for CLF and fixed LOG_LEVEL_LOG.
432 * Also did CRLF->LF fix of my previous patch.
434 * Revision 1.10 2001/05/26 15:26:15 jongfoster
435 * ACL feature now provides more security by immediately dropping
436 * connections from untrusted hosts.
438 * Revision 1.9 2001/05/26 00:28:36 jongfoster
439 * Automatic reloading of config file.
440 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
441 * Most of the global variables have been moved to a new
442 * struct configuration_spec, accessed through csp->config->globalname
443 * Most of the globals remaining are used by the Win32 GUI.
445 * Revision 1.8 2001/05/25 22:43:18 jongfoster
446 * Fixing minor memory leak and buffer overflow.
448 * Revision 1.7 2001/05/25 22:34:30 jongfoster
451 * Revision 1.6 2001/05/23 00:13:58 joergs
452 * AmigaOS support fixed.
454 * Revision 1.5 2001/05/22 18:46:04 oes
456 * - Enabled filtering banners by size rather than URL
457 * by adding patterns that replace all standard banner
458 * sizes with the "Junkbuster" gif to the re_filterfile
460 * - Enabled filtering WebBugs by providing a pattern
461 * which kills all 1x1 images
463 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
464 * which is selected by the (nonstandard and therefore
465 * capital) letter 'U' in the option string.
466 * It causes the quantifiers to be ungreedy by default.
467 * Appending a ? turns back to greedy (!).
469 * - Added a new interceptor ijb-send-banner, which
470 * sends back the "Junkbuster" gif. Without imagelist or
471 * MSIE detection support, or if tinygif = 1, or the
472 * URL isn't recognized as an imageurl, a lame HTML
473 * explanation is sent instead.
475 * - Added new feature, which permits blocking remote
476 * script redirects and firing back a local redirect
478 * The feature is conditionally compiled, i.e. it
479 * can be disabled with --disable-fast-redirects,
480 * plus it must be activated by a "fast-redirects"
481 * line in the config file, has its own log level
482 * and of course wants to be displayed by show-proxy-args
483 * Note: Boy, all the #ifdefs in 1001 locations and
484 * all the fumbling with configure.in and acconfig.h
485 * were *way* more work than the feature itself :-(
487 * - Because a generic redirect template was needed for
488 * this, tinygif = 3 now uses the same.
490 * - Moved GIFs, and other static HTTP response templates
495 * - Removed some >400 CRs again (Jon, you really worked
498 * Revision 1.4 2001/05/21 19:34:01 jongfoster
499 * Made failure to bind() a fatal error.
501 * Revision 1.3 2001/05/20 01:21:20 jongfoster
502 * Version 2.9.4 checkin.
503 * - Merged popupfile and cookiefile, and added control over PCRS
504 * filtering, in new "permissionsfile".
505 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
506 * file error you now get a message box (in the Win32 GUI) rather
507 * than the program exiting with no explanation.
508 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
510 * - Removed tabs from "config"
511 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
512 * - Bumped up version number.
514 * Revision 1.2 2001/05/17 22:34:44 oes
515 * - Added hint on GIF char array generation to jcc.c
516 * - Cleaned CRLF's from the sources and related files
517 * - Repaired logging for REF and FRC
519 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
520 * Initial import of version 2.9.3 source tree
523 *********************************************************************/
529 #include <sys/types.h>
536 #ifdef FEATURE_PTHREAD
538 #endif /* def FEATURE_PTHREAD */
541 # ifndef FEATURE_PTHREAD
545 # include <windows.h>
546 # include <process.h>
547 # endif /* ndef FEATURE_PTHREAD */
550 # ifndef _WIN_CONSOLE
552 # endif /* ndef _WIN_CONSOLE */
554 #else /* ifndef _WIN32 */
556 # if !defined (__OS2__)
558 # include <sys/wait.h>
559 # endif /* ndef __OS2__ */
560 # include <sys/time.h>
561 # include <sys/stat.h>
562 # include <sys/ioctl.h>
565 #include <sys/termios.h>
576 # include <socket.h> /* BeOS has select() for sockets only. */
577 # include <OS.h> /* declarations for threads and stuff. */
580 # if defined(__EMX__) || defined(__OS2__)
581 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
586 #define bzero(B,N) memset(B,0x00,n)
601 #include "killpopup.h"
602 #include "miscutil.h"
604 #include "jbsockets.h"
609 #include "urlmatch.h"
611 const char jcc_h_rcs[] = JCC_H_VERSION;
612 const char project_h_rcs[] = PROJECT_H_VERSION;
615 struct client_state clients[1];
616 struct file_list files[1];
618 #ifdef FEATURE_STATISTICS
619 int urls_read = 0; /* total nr of urls read inc rejected */
620 int urls_rejected = 0; /* total nr of urls rejected */
621 #endif /* def FEATURE_STATISTICS */
623 #ifdef FEATURE_GRACEFUL_TERMINATION
627 static void listen_loop(void);
628 static void chat(struct client_state *csp);
630 void serve(struct client_state *csp);
631 #else /* ifndef AMIGA */
632 static void serve(struct client_state *csp);
633 #endif /* def AMIGA */
636 static int32 server_thread(void *data);
637 #endif /* def __BEOS__ */
640 #define sleep(N) Sleep(((N) * 1000))
644 #define sleep(N) DosSleep(((N) * 100))
647 #if defined(unix) || defined(__EMX__)
649 const char *pidfile = NULL;
650 int received_hup_signal = 0;
651 #endif /* defined unix */
653 /* The vanilla wafer. */
654 static const char VANILLA_WAFER[] =
655 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
656 "Do_not_send_me_any_copyrighted_information_other_than_the_"
657 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
658 "In_particular_do_not_send_me_any_cookies_that_"
659 "are_subject_to_a_claim_of_copyright_by_anybody._"
660 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
661 "(copyright_or_otherwise)_applying_to_any_cookie._";
664 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
665 /*********************************************************************
667 * Function : sig_handler
669 * Description : Signal handler for different signals.
670 * Exit gracefully on ABRT, TERM and INT
671 * or set a flag that will cause the errlog
672 * to be reopened by the main thread on HUP.
675 * 1 : the_signal = the signal cause this function to call
679 *********************************************************************/
680 static void sig_handler(int the_signal)
687 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
695 received_hup_signal = 1;
700 * We shouldn't be here, unless we catch signals
701 * in main() that we can't handle here!
703 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
711 /*********************************************************************
715 * Description : Once a connection to the client has been accepted,
716 * this function is called (via serve()) to handle the
717 * main business of the communication. When this
718 * function returns, the caller must close the client
722 * 1 : csp = Current client state (buffers, headers, etc...)
724 * Returns : On success, the number of bytes written are returned (zero
725 * indicates nothing was written). On error, -1 is returned,
726 * and errno is set appropriately. If count is zero and the
727 * file descriptor refers to a regular file, 0 will be
728 * returned without causing any other effect. For a special
729 * file, the results are not portable.
731 *********************************************************************/
732 static void chat(struct client_state *csp)
735 * This next lines are a little ugly, but they simplifies the if statements
736 * below. Basically if TOGGLE, then we want the if to test if the
737 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
738 * then we want the if to test for CSP_FLAG_FORCED , else we don't
740 #ifdef FEATURE_TOGGLE
741 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
742 #else /* ifndef FEATURE_TOGGLE */
743 # define IS_TOGGLED_ON_AND
744 #endif /* ndef FEATURE_TOGGLE */
745 #ifdef FEATURE_FORCE_LOAD
746 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
747 #else /* ifndef FEATURE_FORCE_LOAD */
748 # define IS_NOT_FORCED_AND
749 #endif /* def FEATURE_FORCE_LOAD */
751 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
753 char buf[BUFFER_SIZE];
761 int ms_iis5_hack = 0;
763 const struct forward_spec * fwd;
764 struct http_request *http;
765 int len; /* for buffer sizes */
766 #ifdef FEATURE_KILL_POPUPS
767 int block_popups; /* bool, 1==will block popups */
768 int block_popups_now = 0; /* bool, 1==currently blocking popups */
769 #endif /* def FEATURE_KILL_POPUPS */
771 int pcrs_filter; /* bool, 1==will filter through pcrs */
772 int gif_deanimate; /* bool, 1==will deanimate gifs */
774 /* Function that does the content filtering for the current request */
775 char *(*content_filter)() = NULL;
777 /* Skeleton for HTTP response, if we should intercept the request */
778 struct http_response *rsp;
783 * Read the client's request. Note that since we're not using select() we
784 * could get blocked here if a client connected, then didn't say anything!
789 len = read_socket(csp->cfd, buf, sizeof(buf));
791 if (len <= 0) break; /* error! */
794 * If there is no memory left for buffering the
795 * request, there is nothing we can do but hang up
797 if (add_to_iob(csp, buf, len))
802 req = get_header(csp);
806 break; /* no HTTP request! */
811 continue; /* more to come! */
814 #ifdef FEATURE_FORCE_LOAD
815 /* If this request contains the FORCE_PREFIX,
816 * better get rid of it now and set the force flag --oes
819 if (strstr(req, FORCE_PREFIX))
821 strclean(req, FORCE_PREFIX);
822 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
823 csp->flags |= CSP_FLAG_FORCED;
826 #endif /* def FEATURE_FORCE_LOAD */
828 parse_http_request(req, http, csp);
833 if (http->cmd == NULL)
835 strcpy(buf, CHEADER);
836 write_socket(csp->cfd, buf, strlen(buf));
838 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
843 /* decide how to route the HTTP request */
845 if ((fwd = forward_url(http, csp)) == NULL)
847 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
848 /* Never get here - LOG_LEVEL_FATAL causes program exit */
851 /* build the http request to send to the server
852 * we have to do one of the following:
854 * create = use the original HTTP request to create a new
855 * HTTP request that has either the path component
856 * without the http://domainspec (w/path) or the
857 * full orininal URL (w/url)
858 * Note that the path and/or the HTTP version may
859 * have been altered by now.
861 * connect = Open a socket to the host:port of the server
862 * and short-circuit server and client socket.
864 * pass = Pass the request unchanged if forwarding a CONNECT
865 * request to a parent proxy. Note that we'll be sending
866 * the CFAIL message ourselves if connecting to the parent
867 * fails, but we won't send a CSUCCEED message if it works,
868 * since that would result in a double message (ours and the
869 * parent's). After sending the request to the parent, we simply
875 * +--------+--------+
877 * 0 | create | connect|
879 * Forwarding +--------+--------+
881 * 1 | create | pass |
883 * +--------+--------+
888 * Determine the actions for this URL
890 #ifdef FEATURE_TOGGLE
891 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
893 /* Most compatible set of actions (i.e. none) */
894 init_current_action(csp->action);
897 #endif /* ndef FEATURE_TOGGLE */
899 url_actions(http, csp);
904 * Check if a CONNECT request is allowable:
905 * In the absence of a +limit-connect action, allow only port 443.
906 * If there is an action, allow whatever matches the specificaton.
910 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
911 || (csp->action->flags & ACTION_LIMIT_CONNECT
912 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
914 strcpy(buf, CFORBIDDEN);
915 write_socket(csp->cfd, buf, strlen(buf));
917 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
918 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
926 * Downgrade http version from 1.1 to 1.0 if +downgrade
929 if ( (http->ssl == 0)
930 && (!strcmpic(http->ver, "HTTP/1.1"))
931 && (csp->action->flags & ACTION_DOWNGRADE))
934 http->ver = strdup("HTTP/1.0");
936 if (http->ver == NULL)
938 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
943 * Save a copy of the original request for logging
945 http->ocmd = strdup(http->cmd);
947 if (http->ocmd == NULL)
949 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
953 * (Re)build the HTTP request for non-SSL requests.
954 * If forwarding, use the whole URL, else, use only the path.
960 http->cmd = strdup(http->gpc);
961 string_append(&http->cmd, " ");
963 if (fwd->forward_host)
965 string_append(&http->cmd, http->url);
969 string_append(&http->cmd, http->path);
972 string_append(&http->cmd, " ");
973 string_append(&http->cmd, http->ver);
975 if (http->cmd == NULL)
977 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
980 enlist(csp->headers, http->cmd);
984 * If the user has not supplied any wafers, and the user has not
985 * told us to suppress the vanilla wafer, then send the vanilla wafer.
987 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
988 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
990 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
994 #ifdef FEATURE_KILL_POPUPS
995 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
996 #endif /* def FEATURE_KILL_POPUPS */
998 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
999 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1001 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1003 /* grab the rest of the client's headers */
1007 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
1009 len = read_socket(csp->cfd, buf, sizeof(buf));
1012 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1017 * If there is no memory left for buffering the
1018 * request, there is nothing we can do but hang up
1020 if (add_to_iob(csp, buf, len))
1027 if (p == NULL) break;
1029 enlist(csp->headers, p);
1033 * We have a request. Now, check to see if we need to
1034 * intercept it, i.e. If ..
1038 /* a CGI call was detected and answered */
1039 (NULL != (rsp = dispatch_cgi(csp)))
1041 /* or we are enabled and... */
1042 || (IS_ENABLED_AND (
1044 /* ..the request was blocked */
1045 ( NULL != (rsp = block_url(csp)))
1047 /* ..or untrusted */
1048 #ifdef FEATURE_TRUST
1049 || ( NULL != (rsp = trust_url(csp)))
1050 #endif /* def FEATURE_TRUST */
1052 /* ..or a fast redirect kicked in */
1053 #ifdef FEATURE_FAST_REDIRECTS
1054 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
1055 (NULL != (rsp = redirect_url(csp))))
1056 #endif /* def FEATURE_FAST_REDIRECTS */
1060 /* Write the answer to the client */
1061 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1062 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1064 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1067 #ifdef FEATURE_STATISTICS
1068 /* Count as a rejected request */
1069 csp->flags |= CSP_FLAG_REJECTED;
1070 #endif /* def FEATURE_STATISTICS */
1072 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
1073 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1074 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1076 /* Clean up and return */
1077 free_http_response(rsp);
1081 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1083 if (fwd->forward_host)
1085 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1086 fwd->forward_host, fwd->forward_port, http->hostport);
1090 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1093 /* here we connect to the server, gateway, or the forwarder */
1095 csp->sfd = forwarded_connect(fwd, http, csp);
1097 if (csp->sfd == JB_INVALID_SOCKET)
1099 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1102 if (errno == EINVAL)
1104 rsp = error_response(csp, "no-such-domain", errno);
1106 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1107 csp->ip_addr_str, http->ocmd);
1111 rsp = error_response(csp, "connect-failed", errno);
1113 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1114 csp->ip_addr_str, http->ocmd);
1118 /* Write the answer to the client */
1121 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1122 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1124 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1128 free_http_response(rsp);
1132 log_error(LOG_LEVEL_CONNECT, "OK");
1134 hdr = sed(client_patterns, add_client_headers, csp);
1137 /* FIXME Should handle error properly */
1138 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1141 list_remove_all(csp->headers);
1143 if (fwd->forward_host || (http->ssl == 0))
1145 /* write the client's (modified) header to the server
1146 * (along with anything else that may be in the buffer)
1149 if (write_socket(csp->sfd, hdr, strlen(hdr))
1150 || (flush_socket(csp->sfd, csp) < 0))
1152 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1155 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1156 csp->ip_addr_str, http->ocmd);
1158 rsp = error_response(csp, "connect-failed", errno);
1162 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1163 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1165 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1169 free_http_response(rsp);
1177 * We're running an SSL tunnel and we're not forwarding,
1178 * so just send the "connect succeeded" message to the
1179 * client, flush the rest, and get out of the way.
1181 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1182 csp->ip_addr_str, http->ocmd);
1184 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1192 /* we're finished with the client's header */
1195 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1197 /* pass data between the client and server
1198 * until one or the other shuts down the connection.
1207 * FD_ZERO here seems to point to an errant macro which crashes.
1208 * So do this by hand for now...
1210 memset(&rfds,0x00,sizeof(fd_set));
1214 FD_SET(csp->cfd, &rfds);
1215 FD_SET(csp->sfd, &rfds);
1217 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1221 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1225 /* this is the body of the browser's request
1226 * just read it and write it.
1229 if (FD_ISSET(csp->cfd, &rfds))
1231 len = read_socket(csp->cfd, buf, sizeof(buf));
1235 break; /* "game over, man" */
1238 if (write_socket(csp->sfd, buf, (size_t)len))
1240 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1247 * The server wants to talk. It could be the header or the body.
1248 * If `hdr' is null, then it's the header otherwise it's the body.
1249 * FIXME: Does `hdr' really mean `host'? No.
1253 if (FD_ISSET(csp->sfd, &rfds))
1256 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1260 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1262 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1263 csp->ip_addr_str, http->ocmd);
1265 rsp = error_response(csp, "connect-failed", errno);
1269 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1270 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1272 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1276 free_http_response(rsp);
1280 /* Add a trailing zero. This lets filter_popups
1281 * use string operations.
1285 #ifdef FEATURE_KILL_POPUPS
1286 /* Filter the popups on this read. */
1287 if (block_popups_now)
1289 filter_popups(buf, csp);
1291 #endif /* def FEATURE_KILL_POPUPS */
1293 /* Normally, this would indicate that we've read
1294 * as much as the server has sent us and we can
1295 * close the client connection. However, Microsoft
1296 * in its wisdom has released IIS/5 with a bug that
1297 * prevents it from sending the trailing \r\n in
1298 * a 302 redirect header (and possibly other headers).
1299 * To work around this if we've haven't parsed
1300 * a full header we'll append a trailing \r\n
1301 * and see if this now generates a valid one.
1303 * This hack shouldn't have any impacts. If we've
1304 * already transmitted the header or if this is a
1305 * SSL connection, then we won't bother with this
1306 * hack. So we only work on partially received
1307 * headers. If we append a \r\n and this still
1308 * doesn't generate a valid header, then we won't
1309 * transmit anything to the client.
1314 if (server_body || http->ssl)
1317 * If we have been buffering up the document,
1318 * now is the time to apply content modification
1319 * and send the result to the client.
1324 * If the content filter fails, use the original
1325 * buffer and length.
1326 * (see p != NULL ? p : csp->iob->cur below)
1328 if (NULL == (p = (*content_filter)(csp)))
1330 csp->content_length = csp->iob->eod - csp->iob->cur;
1333 hdr = sed(server_patterns, add_server_headers, csp);
1336 /* FIXME Should handle error properly */
1337 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1340 if (write_socket(csp->cfd, hdr, strlen(hdr))
1341 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1343 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1353 break; /* "game over, man" */
1357 * This is NOT the body, so
1358 * Let's pretend the server just sent us a blank line.
1360 len = sprintf(buf, "\r\n");
1363 * Now, let the normal header parsing algorithm below do its
1364 * job. If it fails, we'll exit instead of continuing.
1371 * If this is an SSL connection or we're in the body
1372 * of the server document, just write it to the client,
1373 * unless we need to buffer the body for later content-filtering
1376 if (server_body || http->ssl)
1381 * If there is no memory left for buffering the content, or the buffer limit
1382 * has been reached, switch to non-filtering mode, i.e. make & write the
1383 * header, flush the iob and buf, and get out of the way.
1385 if (add_to_iob(csp, buf, len))
1390 log_error(LOG_LEVEL_ERROR, "Flushing header and buffers. Stepping back from filtering.");
1392 hdr = sed(server_patterns, add_server_headers, csp);
1396 * Memory is too tight to even generate the header.
1397 * Send our static "Out-of-memory" page.
1399 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
1400 rsp = cgi_error_memory();
1402 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1403 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1405 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1410 hdrlen = strlen(hdr);
1412 if (write_socket(csp->cfd, hdr, hdrlen)
1413 || ((flushed = flush_socket(csp->cfd, csp)) < 0)
1414 || (write_socket(csp->cfd, buf, len)))
1416 log_error(LOG_LEVEL_CONNECT, "Flush header and buffers to client failed: %E");
1422 byte_count += hdrlen + flushed + len;
1424 content_filter = NULL;
1431 if (write_socket(csp->cfd, buf, (size_t)len))
1433 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1442 /* we're still looking for the end of the
1443 * server's header ... (does that make header
1444 * parsing an "out of body experience" ?
1448 * buffer up the data we just read. If that fails,
1449 * there's little we can do but send our static
1450 * out-of-memory page.
1452 if (add_to_iob(csp, buf, len))
1454 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
1455 rsp = cgi_error_memory();
1457 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1458 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1460 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1465 /* get header lines from the iob */
1467 while ((p = get_header(csp)) != NULL)
1471 /* see following note */
1474 enlist(csp->headers, p);
1478 /* NOTE: there are no "empty" headers so
1479 * if the pointer `p' is not NULL we must
1480 * assume that we reached the end of the
1481 * buffer before we hit the end of the header.
1488 /* Well, we tried our MS IIS/5
1489 * hack and it didn't work.
1490 * The header is incomplete
1491 * and there isn't anything
1492 * we can do about it.
1498 /* Since we have to wait for
1499 * more from the server before
1500 * we can parse the headers
1501 * we just continue here.
1507 /* we have now received the entire header.
1508 * filter it and send the result to the client
1511 hdr = sed(server_patterns, add_server_headers, csp);
1514 /* FIXME Should handle error properly */
1515 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1518 #ifdef FEATURE_KILL_POPUPS
1519 /* Start blocking popups if appropriate. */
1521 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1522 !http->ssl && /* We talk plaintext */
1523 block_popups) /* Policy allows */
1525 block_popups_now = 1;
1527 * Filter the part of the body that came in the same read
1528 * as the last headers:
1530 filter_popups(csp->iob->cur, csp);
1533 #endif /* def FEATURE_KILL_POPUPS */
1535 /* Buffer and pcrs filter this if appropriate. */
1537 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1538 !http->ssl && /* We talk plaintext */
1539 pcrs_filter) /* Policy allows */
1541 content_filter = pcrs_filter_response;
1544 /* Buffer and gif_deanimate this if appropriate. */
1546 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1547 !http->ssl && /* We talk plaintext */
1548 gif_deanimate) /* Policy allows */
1550 content_filter = gif_deanimate_response;
1554 * Only write if we're not buffering for content modification
1556 if (!content_filter)
1558 /* write the server's (modified) header to
1559 * the client (along with anything else that
1560 * may be in the buffer)
1563 if (write_socket(csp->cfd, hdr, strlen(hdr))
1564 || ((len = flush_socket(csp->cfd, csp)) < 0))
1566 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1568 /* the write failed, so don't bother
1569 * mentioning it to the client...
1570 * it probably can't hear us anyway.
1579 /* we're finished with the server's header */
1584 /* If this was a MS IIS/5 hack then it means
1585 * the server has already closed the
1586 * connection. Nothing more to read. Time
1597 return; /* huh? we should never get here */
1600 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1601 csp->ip_addr_str, http->ocmd, byte_count);
1605 /*********************************************************************
1609 * Description : This is little more than chat. We only "serve" to
1610 * to close any socket that chat may have opened.
1613 * 1 : csp = Current client state (buffers, headers, etc...)
1617 *********************************************************************/
1619 void serve(struct client_state *csp)
1620 #else /* ifndef AMIGA */
1621 static void serve(struct client_state *csp)
1622 #endif /* def AMIGA */
1625 close_socket(csp->cfd);
1627 if (csp->sfd != JB_INVALID_SOCKET)
1629 close_socket(csp->sfd);
1632 csp->flags &= ~CSP_FLAG_ACTIVE;
1638 /*********************************************************************
1640 * Function : server_thread
1642 * Description : We only exist to call `serve' in a threaded environment.
1645 * 1 : data = Current client state (buffers, headers, etc...)
1647 * Returns : Always 0.
1649 *********************************************************************/
1650 static int32 server_thread(void *data)
1652 serve((struct client_state *) data);
1659 /*********************************************************************
1663 * Description : Print usage info & exit.
1665 * Parameters : Pointer to argv[0] for identifying ourselves
1669 *********************************************************************/
1670 void usage(const char *myname)
1672 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
1673 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1674 "Aborting.\n", myname);
1681 /*********************************************************************
1685 * Description : Load the config file and start the listen loop.
1686 * This function is a lot more *sane* with the `load_config'
1687 * and `listen_loop' functions; although it stills does
1688 * a *little* too much for my taste.
1691 * 1 : argc = Number of parameters (including $0).
1692 * 2 : argv = Array of (char *)'s to the parameters.
1694 * Returns : 1 if : can't open config file, unrecognized directive,
1695 * stats requested in multi-thread mode, can't open the
1696 * log file, can't open the jar file, listen port is invalid,
1697 * any load fails, and can't bind port.
1699 * Else main never returns, the process must be signaled
1700 * to terminate execution. Or, on Windows, use the
1701 * "File", "Exit" menu option.
1703 *********************************************************************/
1705 int real_main(int argc, const char *argv[])
1707 int main(int argc, const char *argv[])
1712 struct passwd *pw = NULL;
1713 struct group *grp = NULL;
1721 #if !defined(_WIN32)
1729 * Parse the command line arguments
1731 while (++argc_pos < argc)
1733 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1735 if (strcmp(argv[argc_pos], "--help") == 0)
1740 else if(strcmp(argv[argc_pos], "--version") == 0)
1742 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1746 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1751 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1753 if (++argc_pos == argc) usage(argv[0]);
1754 pidfile = strdup(argv[argc_pos]);
1757 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1759 if (++argc_pos == argc) usage(argv[argc_pos]);
1761 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1764 if (NULL == (grp = getgrnam(p)))
1766 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1770 if (NULL == (pw = getpwnam(argv[argc_pos])))
1772 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1775 if (p != NULL) *--p = '\0';
1777 #endif /* defined(unix) */
1779 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1781 configfile = argv[argc_pos];
1784 } /* -END- while (more arguments) */
1787 if ( *configfile != '/' )
1791 /* make config-filename absolute here */
1792 if ( !(basedir = getcwd( NULL, 1024 )))
1794 perror("get working dir failed");
1798 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1800 perror("malloc failed");
1803 strcpy( abs_file, basedir );
1804 strcat( abs_file, "/" );
1805 strcat( abs_file, configfile );
1806 configfile = abs_file;
1808 #endif /* defined unix */
1815 #elif defined(_WIN32)
1820 * Unix signal handling
1822 * Catch the abort, interrupt and terminate signals for a graceful exit
1823 * Catch the hangup signal so the errlog can be reopened.
1824 * Ignore the broken pipe and child signals
1825 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1827 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1830 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1831 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1833 for (idx = 0; catched_signals[idx] != 0; idx++)
1835 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1837 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1841 for (idx = 0; ignored_signals[idx] != 0; idx++)
1843 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1845 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1850 #else /* ifdef _WIN32 */
1851 # ifdef _WIN_CONSOLE
1853 * We *are* in a windows console app.
1854 * Print a verbose messages about FAQ's and such
1856 printf(win32_blurb);
1857 # endif /* def _WIN_CONSOLE */
1858 #endif /* def _WIN32 */
1861 /* Initialize the CGI subsystem */
1862 cgi_init_error_messages();
1865 * If runnig on unix and without the --nodaemon
1866 * option, become a daemon. I.e. fork, detach
1867 * from tty and get process group leadership
1880 if ( pid < 0 ) /* error */
1885 else if ( pid != 0 ) /* parent */
1890 * must check for errors
1891 * child died due to missing files aso
1894 wpid = waitpid( pid, &status, WNOHANG );
1903 /* Should be more portable, but not as well tested */
1908 #else /* ndef __FreeBSD__ */
1910 #endif /* ndef __FreeBSD__ */
1911 fd = open("/dev/tty", O_RDONLY);
1914 /* no error check here */
1915 ioctl( fd, TIOCNOTTY,0 );
1919 /* FIXME: should close stderr (fd 2) here too, but the test
1921 * and load config file is done in listen_loop() and puts
1922 * some messages on stderr there.
1929 } /* -END- if (!no_daemon) */
1932 * As soon as we have written the PID file, we can switch
1933 * to the user and group ID indicated by the --user option
1939 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1941 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1943 if (setuid(pw->pw_uid))
1945 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1949 #endif /* defined unix */
1959 /*********************************************************************
1961 * Function : bind_port_helper
1963 * Description : Bind the listen port. Handles logging, and aborts
1967 * 1 : config = Privoxy configuration. Specifies port
1970 * Returns : Port that was opened.
1972 *********************************************************************/
1973 static jb_socket bind_port_helper(struct configuration_spec * config)
1978 if ( (config->haddr != NULL)
1979 && (config->haddr[0] == '1')
1980 && (config->haddr[1] == '2')
1981 && (config->haddr[2] == '7')
1982 && (config->haddr[3] == '.') )
1984 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1987 else if (config->haddr == NULL)
1989 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1994 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1995 config->hport, config->haddr);
1998 result = bind_port(config->haddr, config->hport, &bfd);
2005 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2006 "There may be another Privoxy or some other "
2007 "proxy running on port %d",
2008 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
2009 config->hport, config->hport);
2012 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2013 "The hostname is not resolvable",
2014 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2017 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
2018 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2021 /* shouldn't get here */
2022 return JB_INVALID_SOCKET;
2025 config->need_bind = 0;
2031 /*********************************************************************
2033 * Function : listen_loop
2035 * Description : bind the listen port and enter a "FOREVER" listening loop.
2041 *********************************************************************/
2042 static void listen_loop(void)
2044 struct client_state *csp = NULL;
2046 struct configuration_spec * config;
2048 config = load_config();
2050 bfd = bind_port_helper(config);
2052 #ifdef FEATURE_GRACEFUL_TERMINATION
2053 while (!g_terminate)
2058 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
2059 while (waitpid(-1, NULL, WNOHANG) > 0)
2061 /* zombie children */
2063 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2066 * Free data that was used by died threads
2072 * Re-open the errlog after HUP signal
2074 if (received_hup_signal)
2076 init_error_log(Argv[0], config->logfile, config->debug);
2077 received_hup_signal = 0;
2082 #ifdef FEATURE_COOKIE_JAR
2084 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
2085 * already open. I think unload_configfile() is not being run, which should do
2086 * this work. Until that can get resolved, we'll use this workaround.
2090 if (csp->config->jar)
2092 fclose(csp->config->jar);
2093 csp->config->jar = NULL;
2095 #endif /* FEATURE_COOKIE_JAR */
2096 #endif /* __OS2__ */
2098 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2100 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2104 csp->flags |= CSP_FLAG_ACTIVE;
2105 csp->sfd = JB_INVALID_SOCKET;
2107 csp->config = config = load_config();
2109 if ( config->need_bind )
2112 * Since we were listening to the "old port", we will not see
2113 * a "listen" param change until the next IJB request. So, at
2114 * least 1 more request must be made for us to find the new
2115 * setting. I am simply closing the old socket and binding the
2118 * Which-ever is correct, we will serve 1 more page via the
2119 * old settings. This should probably be a "show-proxy-args"
2120 * request. This should not be a so common of an operation
2121 * that this will hurt people's feelings.
2126 bfd = bind_port_helper(config);
2129 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2131 if (!accept_connection(csp, bfd))
2133 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2146 log_error(LOG_LEVEL_CONNECT, "OK");
2149 #ifdef FEATURE_TOGGLE
2152 csp->flags |= CSP_FLAG_TOGGLED_ON;
2154 #endif /* def FEATURE_TOGGLE */
2156 if (run_loader(csp))
2158 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2159 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2163 if (block_acl(NULL,csp))
2165 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2166 close_socket(csp->cfd);
2170 #endif /* def FEATURE_ACL */
2172 /* add it to the list of clients */
2173 csp->next = clients->next;
2174 clients->next = csp;
2176 if (config->multi_threaded)
2180 /* this is a switch () statment in the C preprocessor - ugh */
2181 #undef SELECTED_ONE_OPTION
2183 /* Use Pthreads in preference to native code */
2184 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2185 #define SELECTED_ONE_OPTION
2187 pthread_t the_thread;
2188 pthread_attr_t attrs;
2190 pthread_attr_init(&attrs);
2191 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2192 child_id = (pthread_create(&the_thread, &attrs,
2193 (void*)serve, csp) ? -1 : 0);
2194 pthread_attr_destroy(&attrs);
2198 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2199 #define SELECTED_ONE_OPTION
2200 child_id = _beginthread(
2201 (void (*)(void *))serve,
2206 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2207 #define SELECTED_ONE_OPTION
2208 child_id = _beginthread(
2209 (void(* _Optlink)(void*))serve,
2215 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2216 #define SELECTED_ONE_OPTION
2218 thread_id tid = spawn_thread
2219 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2221 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2223 child_id = (int) tid;
2232 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2233 #define SELECTED_ONE_OPTION
2234 csp->cfd = ReleaseSocket(csp->cfd, -1);
2235 if((child_id = (int)CreateNewProcTags(
2236 NP_Entry, (ULONG)server_thread,
2237 NP_Output, Output(),
2238 NP_CloseOutput, FALSE,
2239 NP_Name, (ULONG)"privoxy child",
2240 NP_StackSize, 200*1024,
2244 ((struct Task *)child_id)->tc_UserData = csp;
2245 Signal((struct Task *)child_id, SIGF_SINGLE);
2250 #if !defined(SELECTED_ONE_OPTION)
2253 /* This block is only needed when using fork().
2254 * When using threads, the server thread was
2255 * created and run by the call to _beginthread().
2257 if (child_id == 0) /* child */
2263 else if (child_id > 0) /* parent */
2265 /* in a fork()'d environment, the parent's
2266 * copy of the client socket and the CSP
2270 #if !defined(_WIN32) && defined(__CYGWIN__)
2272 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2273 close_socket(csp->cfd);
2274 csp->flags &= ~CSP_FLAG_ACTIVE;
2278 #undef SELECTED_ONE_OPTION
2279 /* end of cpp switch () */
2281 if (child_id < 0) /* failed */
2283 char buf[BUFFER_SIZE];
2285 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2287 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
2289 write_socket(csp->cfd, buf, strlen(buf));
2290 close_socket(csp->cfd);
2291 csp->flags &= ~CSP_FLAG_ACTIVE;
2302 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2304 /* Clean up. Aim: free all memory (no leaks) */
2305 #ifdef FEATURE_GRACEFUL_TERMINATION
2307 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2309 unload_current_config_file();
2310 unload_current_actions_file();
2311 unload_current_re_filterfile();
2312 #ifdef FEATURE_TRUST
2313 unload_current_trust_file();
2316 if (config->multi_threaded)
2323 } while ((clients->next != NULL) && (--i > 0));
2327 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2336 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2337 /* Cleanup - remove taskbar icon etc. */
2342 #endif /* FEATURE_GRACEFUL_TERMINATION */