1 const char jcc_rcs[] = "$Id: jcc.c,v 1.89 2002/03/31 17:18:59 jongfoster Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001 the SourceForge
10 * 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.89 2002/03/31 17:18:59 jongfoster
37 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
39 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
40 * More compiler warning message maintenance
42 * Revision 1.87 2002/03/26 22:29:54 swa
43 * we have a new homepage!
45 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
46 * Workaround for closing the jarfile before load_config() comes around again
48 * Revision 1.85 2002/03/24 15:23:33 jongfoster
51 * Revision 1.84 2002/03/24 13:25:43 swa
52 * name change related issues
54 * Revision 1.83 2002/03/16 23:54:06 jongfoster
55 * Adding graceful termination feature, to help look for memory leaks.
56 * If you enable this (which, by design, has to be done by hand
57 * editing config.h) and then go to http://i.j.b/die, then the program
58 * will exit cleanly after the *next* request. It should free all the
59 * memory that was used.
61 * Revision 1.82 2002/03/13 00:27:05 jongfoster
64 * Revision 1.81 2002/03/12 01:42:50 oes
65 * Introduced modular filters
67 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
68 * OS/2 port maintenance:
69 * - Fixed EMX build - it had decayed a little
70 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
71 * substituted a memset for now.
73 * Revision 1.79 2002/03/09 20:03:52 jongfoster
74 * - Making various functions return int rather than size_t.
75 * (Undoing a recent change). Since size_t is unsigned on
76 * Windows, functions like read_socket that return -1 on
77 * error cannot return a size_t.
79 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
80 * crashes, and also frequently caused JB to jump to 100%
81 * CPU and stay there. (Because it thought it had just
82 * read ((unsigned)-1) == 4Gb of data...)
84 * - The signature of write_socket has changed, it now simply
85 * returns success=0/failure=nonzero.
87 * - Trying to get rid of a few warnings --with-debug on
88 * Windows, I've introduced a new type "jb_socket". This is
89 * used for the socket file descriptors. On Windows, this
90 * is SOCKET (a typedef for unsigned). Everywhere else, it's
91 * an int. The error value can't be -1 any more, so it's
92 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
93 * Windows it maps to the #define INVALID_SOCKET.)
95 * - The signature of bind_port has changed.
97 * Revision 1.78 2002/03/08 21:35:04 oes
98 * Added optional group supplement to --user option. Will now use default group of user if no group given
100 * Revision 1.77 2002/03/07 03:52:06 oes
101 * - Fixed compiler warnings etc
102 * - Improved handling of failed DNS lookups
104 * Revision 1.76 2002/03/06 22:54:35 jongfoster
105 * Automated function-comment nitpicking.
107 * Revision 1.75 2002/03/06 10:02:19 oes
108 * Fixed stupid bug when --user was not given
110 * Revision 1.74 2002/03/06 00:49:31 jongfoster
111 * Fixing warning on Windows
112 * Making #ifdefs that refer to the same variable consistently
113 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
115 * Revision 1.73 2002/03/05 23:57:30 hal9
116 * Stray character 's' on line 1618 was breaking build.
118 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
119 * - Re-enable OS/2 building after new parms were added
120 * - Fix false out of memory report when resolving CGI templates when no IP
121 * address is available of failed attempt (a la no such domain)
123 * Revision 1.71 2002/03/05 18:13:56 oes
124 * Added --user option
126 * Revision 1.70 2002/03/05 04:52:42 oes
127 * Deleted non-errlog debugging code
129 * Revision 1.69 2002/03/04 23:50:00 jongfoster
130 * Splitting off bind_port() call into bind_port_helper(), with
133 * Revision 1.68 2002/03/04 20:17:32 oes
136 * Revision 1.67 2002/03/04 18:18:57 oes
137 * - Removed _DEBUG mode
138 * - Cleand up cmdline parsing
139 * - Introduced --no-daemon, --pidfile options
140 * - Cleaned up signal handling:
141 * - Terminate cleanly on INT, TERM and ABRT
142 * - Schedule logfile for re-opening on HUP
143 * - Ignore CHLD and PIPE
144 * - Leave the rest with their default handlers
145 * - Uniform handler registration
146 * - Added usage() function
147 * - Played styleguide police
149 * Revision 1.66 2002/03/03 15:06:55 oes
150 * Re-enabled automatic config reloading
152 * Revision 1.65 2002/03/03 14:49:11 oes
153 * Fixed CLF logging: Now uses client's original HTTP request
155 * Revision 1.64 2002/03/03 09:18:03 joergs
156 * Made jumbjuster work on AmigaOS again.
158 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
159 * Clean up a little CRLF unpleasantness that suddenly appeared
161 * Revision 1.62 2002/02/20 23:17:23 jongfoster
162 * Detecting some out-of memory conditions and exiting with a log message.
164 * Revision 1.61 2002/01/17 21:01:52 jongfoster
165 * Moving all our URL and URL pattern parsing code to urlmatch.c.
167 * Revision 1.60 2001/12/30 14:07:32 steudten
168 * - Add signal handling (unix)
169 * - Add SIGHUP handler (unix)
170 * - Add creation of pidfile (unix)
171 * - Add action 'top' in rc file (RH)
172 * - Add entry 'SIGNALS' to manpage
173 * - Add exit message to logfile (unix)
175 * Revision 1.59 2001/12/13 14:07:18 oes
176 * Fixed Bug: 503 error page now sent OK
178 * Revision 1.58 2001/11/30 23:37:24 jongfoster
179 * Renaming the Win32 config file to config.txt - this is almost the
180 * same as the corresponding UNIX name "config"
182 * Revision 1.57 2001/11/16 00:47:43 jongfoster
183 * Changing the tty-disconnection code to use setsid().
185 * Revision 1.56 2001/11/13 20:20:54 jongfoster
186 * Tabs->spaces, fixing a bug with missing {} around an if()
188 * Revision 1.55 2001/11/13 20:14:53 jongfoster
189 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
191 * Revision 1.54 2001/11/07 00:03:14 steudten
192 * Give reliable return value if an error
193 * occurs not just 0 with new daemon mode.
195 * Revision 1.53 2001/11/05 21:41:43 steudten
196 * Add changes to be a real daemon just for unix os.
197 * (change cwd to /, detach from controlling tty, set
198 * process group and session leader to the own process.
200 * Add some fatal-error log message for failed malloc().
201 * Add '-d' if compiled with 'configure --with-debug' to
202 * enable debug output.
204 * Revision 1.52 2001/10/26 20:11:20 jongfoster
205 * Fixing type mismatch
207 * Revision 1.51 2001/10/26 17:38:28 oes
210 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
211 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
212 * threads to call select() simultaneously. So, it's time to do a real, live,
213 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
214 * (native). Both versions will work, but using __OS2__ offers multi-threading.
216 * Revision 1.49 2001/10/23 21:41:35 jongfoster
217 * Added call to initialize the (statically-allocated of course)
218 * "out of memory" CGI response.
220 * Revision 1.48 2001/10/10 19:56:46 jongfoster
221 * Moving some code that wasn't cookie-related out of an #ifdef
224 * Revision 1.47 2001/10/10 16:44:36 oes
225 * Added CONNECT destination port limitation check
227 * Revision 1.46 2001/10/08 15:17:41 oes
228 * Re-enabled SSL forwarding
230 * Revision 1.45 2001/10/07 15:42:11 oes
231 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
233 * Moved downgrading of the HTTP version from parse_http_request to
234 * chat(), since we can't decide if it is necessary before we have
235 * determined the actions for the URL. The HTTP command is now
236 * *always* re-built so the repairs need no longer be special-cased.
238 * filter_popups now gets a csp pointer so it can raise the new
239 * CSP_FLAG_MODIFIED flag.
243 * Added configurable size limit for the IOB. If the IOB grows so
244 * large that the next read would exceed the limit, the header
245 * is generated, and the header & unfiltered buffer are flushed
246 * to the client. Chat then continues in non-buffering,
247 * non-filtering body mode.
249 * Revision 1.44 2001/10/02 18:13:57 oes
252 * Revision 1.43 2001/10/02 15:32:13 oes
253 * Moved generation of hdr
255 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
256 * Cleaning up 2 compiler warnings on OS/2.
258 * Revision 1.41 2001/09/16 17:05:14 jongfoster
259 * Removing unused #include showarg.h
261 * Revision 1.40 2001/09/16 15:41:45 jongfoster
262 * Fixing signed/unsigned comparison warning.
264 * Revision 1.39 2001/09/16 13:21:27 jongfoster
265 * Changes to use new list functions.
267 * Revision 1.38 2001/09/16 13:01:46 jongfoster
268 * Removing redundant function call that zeroed zalloc()'d memory.
270 * Revision 1.37 2001/09/10 11:12:24 oes
271 * Deleted unused variable
273 * Revision 1.36 2001/09/10 10:56:15 oes
274 * Silenced compiler warnings
276 * Revision 1.35 2001/07/31 14:44:22 oes
277 * Deleted unused size parameter from filter_popups()
279 * Revision 1.34 2001/07/30 22:08:36 jongfoster
280 * Tidying up #defines:
281 * - All feature #defines are now of the form FEATURE_xxx
282 * - Permanently turned off WIN_GUI_EDIT
283 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
285 * Revision 1.33 2001/07/29 19:32:00 jongfoster
286 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
288 * Revision 1.32 2001/07/29 18:47:05 jongfoster
289 * Adding missing #include "loadcfg.h"
291 * Revision 1.31 2001/07/29 12:17:48 oes
292 * Applied pthread fix by Paul Lieverse
294 * Revision 1.30 2001/07/25 22:57:13 jongfoster
295 * __BEOS__ no longer overrides FEATURE_PTHREAD.
296 * This is because FEATURE_PTHREAD will soon be widely used, so I
297 * want to keep it simple.
299 * Revision 1.29 2001/07/24 12:47:06 oes
300 * Applied BeOS support update by Eugenia
302 * Revision 1.28 2001/07/23 13:26:12 oes
303 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
305 * Revision 1.27 2001/07/19 19:09:47 haroon
306 * - Added code to take care of the situation where while processing the first
307 * server response (which includes the server header), after finding the end
308 * of the headers we were not looking past the end of the headers for
309 * content modification. I enabled it for filter_popups.
310 * Someone else should look to see if other similar operations should be
311 * done to the discarded portion of the buffer.
313 * Note 2001/07/20: No, the other content modification mechanisms will process
314 * the whole iob later anyway. --oes
316 * Revision 1.26 2001/07/18 12:31:36 oes
319 * Revision 1.25 2001/07/15 19:43:49 jongfoster
320 * Supports POSIX threads.
321 * Also removed some unused #includes.
323 * Revision 1.24 2001/07/13 14:00:40 oes
324 * - Generic content modification scheme:
325 * Each feature has its own applicability flag that is set
326 * from csp->action->flags.
327 * Replaced the "filtering" int flag , by a function pointer
328 * "content_filter" to the function that will do the content
329 * modification. If it is != NULL, the document will be buffered
330 * and processed through *content_filter, which must set
331 * csp->content_length and return a modified copy of the body
332 * or return NULL (on failiure).
333 * - Changed csp->is_text to the more generic bitmap csp->content_type
334 * which can currently take the valued CT_TEXT or CT_GIF
336 * - Removed all #ifdef PCRS
338 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
339 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
340 * the `block_acl' call. This prevents a compilation error when the user
341 * does not wish to use the "ACL" feature.
343 * Revision 1.22 2001/06/29 21:45:41 oes
344 * Indentation, CRLF->LF, Tab-> Space
346 * Revision 1.21 2001/06/29 13:29:36 oes
347 * - Cleaned up, improved comments
348 * - Unified all possible interceptors (CGI,
349 * block, trust, fast_redirect) in one
350 * place, with one (CGI) answer generation
351 * mechansim. Much clearer now.
352 * - Removed the GIF image generation, which
353 * is now done in filters.c:block_url()
354 * - Made error conditions like domain lookup
355 * failiure or (various) problems while talking
356 * to the server use cgi.c:error_response()
357 * instead of generating HTML/HTTP in chat() (yuck!)
358 * - Removed logentry from cancelled commit
360 * Revision 1.20 2001/06/09 10:55:28 jongfoster
361 * Changing BUFSIZ ==> BUFFER_SIZE
363 * Revision 1.19 2001/06/07 23:12:52 jongfoster
364 * Replacing function pointer in struct gateway with a directly
365 * called function forwarded_connect().
366 * Replacing struct gateway with struct forward_spec
368 * Revision 1.18 2001/06/03 19:12:16 oes
369 * introduced new cgi handling
371 * Revision 1.17 2001/06/01 20:07:23 jongfoster
372 * Now uses action +image-blocker{} rather than config->tinygif
374 * Revision 1.16 2001/06/01 18:49:17 jongfoster
375 * Replaced "list_share" with "list" - the tiny memory gain was not
376 * worth the extra complexity.
378 * Revision 1.15 2001/05/31 21:24:47 jongfoster
379 * Changed "permission" to "action" throughout.
380 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
381 * Moved vanilla wafer check into chat(), since we must now
382 * decide whether or not to add it based on the URL.
384 * Revision 1.14 2001/05/29 20:14:01 joergs
385 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
388 * Revision 1.13 2001/05/29 09:50:24 jongfoster
389 * Unified blocklist/imagelist/permissionslist.
390 * File format is still under discussion, but the internal changes
393 * Also modified interceptor behaviour:
394 * - We now intercept all URLs beginning with one of the following
395 * prefixes (and *only* these prefixes):
397 * * http://ijbswa.sf.net/config/
398 * * http://ijbswa.sourceforge.net/config/
399 * - New interceptors "home page" - go to http://i.j.b/ to see it.
400 * - Internal changes so that intercepted and fast redirect pages
401 * are not replaced with an image.
402 * - Interceptors now have the option to send a binary page direct
403 * to the client. (i.e. ijb-send-banner uses this)
404 * - Implemented show-url-info interceptor. (Which is why I needed
405 * the above interceptors changes - a typical URL is
406 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
407 * The previous mechanism would not have intercepted that, and
408 * if it had been intercepted then it then it would have replaced
411 * Revision 1.12 2001/05/27 22:17:04 oes
413 * - re_process_buffer no longer writes the modified buffer
414 * to the client, which was very ugly. It now returns the
415 * buffer, which it is then written by chat.
417 * - content_length now adjusts the Content-Length: header
418 * for modified documents rather than crunch()ing it.
419 * (Length info in csp->content_length, which is 0 for
420 * unmodified documents)
422 * - For this to work, sed() is called twice when filtering.
424 * Revision 1.11 2001/05/26 17:27:53 jongfoster
425 * Added support for CLF and fixed LOG_LEVEL_LOG.
426 * Also did CRLF->LF fix of my previous patch.
428 * Revision 1.10 2001/05/26 15:26:15 jongfoster
429 * ACL feature now provides more security by immediately dropping
430 * connections from untrusted hosts.
432 * Revision 1.9 2001/05/26 00:28:36 jongfoster
433 * Automatic reloading of config file.
434 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
435 * Most of the global variables have been moved to a new
436 * struct configuration_spec, accessed through csp->config->globalname
437 * Most of the globals remaining are used by the Win32 GUI.
439 * Revision 1.8 2001/05/25 22:43:18 jongfoster
440 * Fixing minor memory leak and buffer overflow.
442 * Revision 1.7 2001/05/25 22:34:30 jongfoster
445 * Revision 1.6 2001/05/23 00:13:58 joergs
446 * AmigaOS support fixed.
448 * Revision 1.5 2001/05/22 18:46:04 oes
450 * - Enabled filtering banners by size rather than URL
451 * by adding patterns that replace all standard banner
452 * sizes with the "Junkbuster" gif to the re_filterfile
454 * - Enabled filtering WebBugs by providing a pattern
455 * which kills all 1x1 images
457 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
458 * which is selected by the (nonstandard and therefore
459 * capital) letter 'U' in the option string.
460 * It causes the quantifiers to be ungreedy by default.
461 * Appending a ? turns back to greedy (!).
463 * - Added a new interceptor ijb-send-banner, which
464 * sends back the "Junkbuster" gif. Without imagelist or
465 * MSIE detection support, or if tinygif = 1, or the
466 * URL isn't recognized as an imageurl, a lame HTML
467 * explanation is sent instead.
469 * - Added new feature, which permits blocking remote
470 * script redirects and firing back a local redirect
472 * The feature is conditionally compiled, i.e. it
473 * can be disabled with --disable-fast-redirects,
474 * plus it must be activated by a "fast-redirects"
475 * line in the config file, has its own log level
476 * and of course wants to be displayed by show-proxy-args
477 * Note: Boy, all the #ifdefs in 1001 locations and
478 * all the fumbling with configure.in and acconfig.h
479 * were *way* more work than the feature itself :-(
481 * - Because a generic redirect template was needed for
482 * this, tinygif = 3 now uses the same.
484 * - Moved GIFs, and other static HTTP response templates
489 * - Removed some >400 CRs again (Jon, you really worked
492 * Revision 1.4 2001/05/21 19:34:01 jongfoster
493 * Made failure to bind() a fatal error.
495 * Revision 1.3 2001/05/20 01:21:20 jongfoster
496 * Version 2.9.4 checkin.
497 * - Merged popupfile and cookiefile, and added control over PCRS
498 * filtering, in new "permissionsfile".
499 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
500 * file error you now get a message box (in the Win32 GUI) rather
501 * than the program exiting with no explanation.
502 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
504 * - Removed tabs from "config"
505 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
506 * - Bumped up version number.
508 * Revision 1.2 2001/05/17 22:34:44 oes
509 * - Added hint on GIF char array generation to jcc.c
510 * - Cleaned CRLF's from the sources and related files
511 * - Repaired logging for REF and FRC
513 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
514 * Initial import of version 2.9.3 source tree
517 *********************************************************************/
523 #include <sys/types.h>
530 #ifdef FEATURE_PTHREAD
532 #endif /* def FEATURE_PTHREAD */
535 # ifndef FEATURE_PTHREAD
539 # include <windows.h>
540 # include <process.h>
541 # endif /* ndef FEATURE_PTHREAD */
544 # ifndef _WIN_CONSOLE
546 # endif /* ndef _WIN_CONSOLE */
548 #else /* ifndef _WIN32 */
550 # if !defined (__OS2__)
552 # include <sys/wait.h>
553 # endif /* ndef __OS2__ */
554 # include <sys/time.h>
555 # include <sys/stat.h>
556 # include <sys/ioctl.h>
559 #include <sys/termios.h>
570 # include <socket.h> /* BeOS has select() for sockets only. */
571 # include <OS.h> /* declarations for threads and stuff. */
574 # if defined(__EMX__) || defined(__OS2__)
575 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
580 #define bzero(B,N) memset(B,0x00,n)
595 #include "killpopup.h"
596 #include "miscutil.h"
598 #include "jbsockets.h"
603 #include "urlmatch.h"
605 const char jcc_h_rcs[] = JCC_H_VERSION;
606 const char project_h_rcs[] = PROJECT_H_VERSION;
609 struct client_state clients[1];
610 struct file_list files[1];
612 #ifdef FEATURE_STATISTICS
613 int urls_read = 0; /* total nr of urls read inc rejected */
614 int urls_rejected = 0; /* total nr of urls rejected */
615 #endif /* def FEATURE_STATISTICS */
617 #ifdef FEATURE_GRACEFUL_TERMINATION
621 static void listen_loop(void);
622 static void chat(struct client_state *csp);
624 void serve(struct client_state *csp);
625 #else /* ifndef AMIGA */
626 static void serve(struct client_state *csp);
627 #endif /* def AMIGA */
630 static int32 server_thread(void *data);
631 #endif /* def __BEOS__ */
634 #define sleep(N) Sleep(((N) * 1000))
638 #define sleep(N) DosSleep(((N) * 100))
641 #if defined(unix) || defined(__EMX__)
643 const char *pidfile = NULL;
644 int received_hup_signal = 0;
645 #endif /* defined unix */
647 /* The vanilla wafer. */
648 static const char VANILLA_WAFER[] =
649 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
650 "Do_not_send_me_any_copyrighted_information_other_than_the_"
651 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
652 "In_particular_do_not_send_me_any_cookies_that_"
653 "are_subject_to_a_claim_of_copyright_by_anybody._"
654 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
655 "(copyright_or_otherwise)_applying_to_any_cookie._";
658 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
659 /*********************************************************************
661 * Function : sig_handler
663 * Description : Signal handler for different signals.
664 * Exit gracefully on ABRT, TERM and INT
665 * or set a flag that will cause the errlog
666 * to be reopened by the main thread on HUP.
669 * 1 : the_signal = the signal cause this function to call
673 *********************************************************************/
674 static void sig_handler(int the_signal)
681 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
689 received_hup_signal = 1;
694 * We shouldn't be here, unless we catch signals
695 * in main() that we can't handle here!
697 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
705 /*********************************************************************
709 * Description : Once a connection to the client has been accepted,
710 * this function is called (via serve()) to handle the
711 * main business of the communication. When this
712 * function returns, the caller must close the client
716 * 1 : csp = Current client state (buffers, headers, etc...)
718 * Returns : On success, the number of bytes written are returned (zero
719 * indicates nothing was written). On error, -1 is returned,
720 * and errno is set appropriately. If count is zero and the
721 * file descriptor refers to a regular file, 0 will be
722 * returned without causing any other effect. For a special
723 * file, the results are not portable.
725 *********************************************************************/
726 static void chat(struct client_state *csp)
729 * This next lines are a little ugly, but they simplifies the if statements
730 * below. Basically if TOGGLE, then we want the if to test if the
731 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
732 * then we want the if to test for CSP_FLAG_FORCED , else we don't
734 #ifdef FEATURE_TOGGLE
735 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
736 #else /* ifndef FEATURE_TOGGLE */
737 # define IS_TOGGLED_ON_AND
738 #endif /* ndef FEATURE_TOGGLE */
739 #ifdef FEATURE_FORCE_LOAD
740 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
741 #else /* ifndef FEATURE_FORCE_LOAD */
742 # define IS_NOT_FORCED_AND
743 #endif /* def FEATURE_FORCE_LOAD */
745 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
747 char buf[BUFFER_SIZE];
755 int ms_iis5_hack = 0;
757 const struct forward_spec * fwd;
758 struct http_request *http;
759 int len; /* for buffer sizes */
760 #ifdef FEATURE_KILL_POPUPS
761 int block_popups; /* bool, 1==will block popups */
762 int block_popups_now = 0; /* bool, 1==currently blocking popups */
763 #endif /* def FEATURE_KILL_POPUPS */
765 int pcrs_filter; /* bool, 1==will filter through pcrs */
766 int gif_deanimate; /* bool, 1==will deanimate gifs */
768 /* Function that does the content filtering for the current request */
769 char *(*content_filter)() = NULL;
771 /* Skeleton for HTTP response, if we should intercept the request */
772 struct http_response *rsp;
777 * Read the client's request. Note that since we're not using select() we
778 * could get blocked here if a client connected, then didn't say anything!
783 len = read_socket(csp->cfd, buf, sizeof(buf));
785 if (len <= 0) break; /* error! */
787 add_to_iob(csp, buf, len);
789 req = get_header(csp);
793 break; /* no HTTP request! */
798 continue; /* more to come! */
801 #ifdef FEATURE_FORCE_LOAD
802 /* If this request contains the FORCE_PREFIX,
803 * better get rid of it now and set the force flag --oes
806 if (strstr(req, FORCE_PREFIX))
808 strclean(req, FORCE_PREFIX);
809 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
810 csp->flags |= CSP_FLAG_FORCED;
813 #endif /* def FEATURE_FORCE_LOAD */
815 parse_http_request(req, http, csp);
820 if (http->cmd == NULL)
822 strcpy(buf, CHEADER);
823 write_socket(csp->cfd, buf, strlen(buf));
825 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
830 /* decide how to route the HTTP request */
832 if ((fwd = forward_url(http, csp)) == NULL)
834 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
835 /* Never get here - LOG_LEVEL_FATAL causes program exit */
838 /* build the http request to send to the server
839 * we have to do one of the following:
841 * create = use the original HTTP request to create a new
842 * HTTP request that has either the path component
843 * without the http://domainspec (w/path) or the
844 * full orininal URL (w/url)
845 * Note that the path and/or the HTTP version may
846 * have been altered by now.
848 * connect = Open a socket to the host:port of the server
849 * and short-circuit server and client socket.
851 * pass = Pass the request unchanged if forwarding a CONNECT
852 * request to a parent proxy. Note that we'll be sending
853 * the CFAIL message ourselves if connecting to the parent
854 * fails, but we won't send a CSUCCEED message if it works,
855 * since that would result in a double message (ours and the
856 * parent's). After sending the request to the parent, we simply
862 * +--------+--------+
864 * 0 | create | connect|
866 * Forwarding +--------+--------+
868 * 1 | create | pass |
870 * +--------+--------+
875 * Determine the actions for this URL
877 #ifdef FEATURE_TOGGLE
878 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
880 /* Most compatible set of actions (i.e. none) */
881 init_current_action(csp->action);
884 #endif /* ndef FEATURE_TOGGLE */
886 url_actions(http, csp);
891 * Check if a CONNECT request is allowable:
892 * In the absence of a +limit-connect action, allow only port 443.
893 * If there is an action, allow whatever matches the specificaton.
897 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
898 || (csp->action->flags & ACTION_LIMIT_CONNECT
899 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
901 strcpy(buf, CFORBIDDEN);
902 write_socket(csp->cfd, buf, strlen(buf));
904 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
905 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
913 * Downgrade http version from 1.1 to 1.0 if +downgrade
916 if ( (http->ssl == 0)
917 && (!strcmpic(http->ver, "HTTP/1.1"))
918 && (csp->action->flags & ACTION_DOWNGRADE))
921 http->ver = strdup("HTTP/1.0");
923 if (http->ver == NULL)
925 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
930 * Save a copy of the original request for logging
932 http->ocmd = strdup(http->cmd);
934 if (http->ocmd == NULL)
936 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
940 * (Re)build the HTTP request for non-SSL requests.
941 * If forwarding, use the whole URL, else, use only the path.
947 http->cmd = strdup(http->gpc);
948 string_append(&http->cmd, " ");
950 if (fwd->forward_host)
952 string_append(&http->cmd, http->url);
956 string_append(&http->cmd, http->path);
959 string_append(&http->cmd, " ");
960 string_append(&http->cmd, http->ver);
962 if (http->cmd == NULL)
964 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
967 enlist(csp->headers, http->cmd);
971 * If the user has not supplied any wafers, and the user has not
972 * told us to suppress the vanilla wafer, then send the vanilla wafer.
974 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
975 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
977 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
981 #ifdef FEATURE_KILL_POPUPS
982 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
983 #endif /* def FEATURE_KILL_POPUPS */
985 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
986 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
988 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
990 /* grab the rest of the client's headers */
994 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
996 len = read_socket(csp->cfd, buf, sizeof(buf));
999 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1002 add_to_iob(csp, buf, len);
1006 if (p == NULL) break;
1008 enlist(csp->headers, p);
1012 * We have a request. Now, check to see if we need to
1013 * intercept it, i.e. If ..
1017 /* a CGI call was detected and answered */
1018 (NULL != (rsp = dispatch_cgi(csp)))
1020 /* or we are enabled and... */
1021 || (IS_ENABLED_AND (
1023 /* ..the request was blocked */
1024 ( NULL != (rsp = block_url(csp)))
1026 /* ..or untrusted */
1027 #ifdef FEATURE_TRUST
1028 || ( NULL != (rsp = trust_url(csp)))
1029 #endif /* def FEATURE_TRUST */
1031 /* ..or a fast redirect kicked in */
1032 #ifdef FEATURE_FAST_REDIRECTS
1033 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
1034 (NULL != (rsp = redirect_url(csp))))
1035 #endif /* def FEATURE_FAST_REDIRECTS */
1039 /* Write the answer to the client */
1040 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1041 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1043 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1046 #ifdef FEATURE_STATISTICS
1047 /* Count as a rejected request */
1048 csp->flags |= CSP_FLAG_REJECTED;
1049 #endif /* def FEATURE_STATISTICS */
1051 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
1052 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1053 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1055 /* Clean up and return */
1056 free_http_response(rsp);
1060 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1062 if (fwd->forward_host)
1064 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1065 fwd->forward_host, fwd->forward_port, http->hostport);
1069 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1072 /* here we connect to the server, gateway, or the forwarder */
1074 csp->sfd = forwarded_connect(fwd, http, csp);
1076 if (csp->sfd == JB_INVALID_SOCKET)
1078 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1081 if (errno == EINVAL)
1083 rsp = error_response(csp, "no-such-domain", errno);
1085 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1086 csp->ip_addr_str, http->ocmd);
1090 rsp = error_response(csp, "connect-failed", errno);
1092 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1093 csp->ip_addr_str, http->ocmd);
1097 /* Write the answer to the client */
1100 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1101 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1103 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1107 free_http_response(rsp);
1111 log_error(LOG_LEVEL_CONNECT, "OK");
1113 hdr = sed(client_patterns, add_client_headers, csp);
1116 /* FIXME Should handle error properly */
1117 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1120 list_remove_all(csp->headers);
1122 if (fwd->forward_host || (http->ssl == 0))
1124 /* write the client's (modified) header to the server
1125 * (along with anything else that may be in the buffer)
1128 if (write_socket(csp->sfd, hdr, strlen(hdr))
1129 || (flush_socket(csp->sfd, csp) < 0))
1131 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1134 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1135 csp->ip_addr_str, http->ocmd);
1137 rsp = error_response(csp, "connect-failed", errno);
1141 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1142 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1144 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1148 free_http_response(rsp);
1156 * We're running an SSL tunnel and we're not forwarding,
1157 * so just send the "connect succeeded" message to the
1158 * client, flush the rest, and get out of the way.
1160 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1161 csp->ip_addr_str, http->ocmd);
1163 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1171 /* we're finished with the client's header */
1174 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1176 /* pass data between the client and server
1177 * until one or the other shuts down the connection.
1186 * FD_ZERO here seems to point to an errant macro which crashes.
1187 * So do this by hand for now...
1189 memset(&rfds,0x00,sizeof(fd_set));
1193 FD_SET(csp->cfd, &rfds);
1194 FD_SET(csp->sfd, &rfds);
1196 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1200 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1204 /* this is the body of the browser's request
1205 * just read it and write it.
1208 if (FD_ISSET(csp->cfd, &rfds))
1210 len = read_socket(csp->cfd, buf, sizeof(buf));
1214 break; /* "game over, man" */
1217 if (write_socket(csp->sfd, buf, (size_t)len))
1219 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1226 * The server wants to talk. It could be the header or the body.
1227 * If `hdr' is null, then it's the header otherwise it's the body.
1228 * FIXME: Does `hdr' really mean `host'? No.
1232 if (FD_ISSET(csp->sfd, &rfds))
1235 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1239 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1241 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1242 csp->ip_addr_str, http->ocmd);
1244 rsp = error_response(csp, "connect-failed", errno);
1248 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1249 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1251 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1255 free_http_response(rsp);
1259 /* Add a trailing zero. This lets filter_popups
1260 * use string operations.
1264 #ifdef FEATURE_KILL_POPUPS
1265 /* Filter the popups on this read. */
1266 if (block_popups_now)
1268 filter_popups(buf, csp);
1270 #endif /* def FEATURE_KILL_POPUPS */
1272 /* Normally, this would indicate that we've read
1273 * as much as the server has sent us and we can
1274 * close the client connection. However, Microsoft
1275 * in its wisdom has released IIS/5 with a bug that
1276 * prevents it from sending the trailing \r\n in
1277 * a 302 redirect header (and possibly other headers).
1278 * To work around this if we've haven't parsed
1279 * a full header we'll append a trailing \r\n
1280 * and see if this now generates a valid one.
1282 * This hack shouldn't have any impacts. If we've
1283 * already transmitted the header or if this is a
1284 * SSL connection, then we won't bother with this
1285 * hack. So we only work on partially received
1286 * headers. If we append a \r\n and this still
1287 * doesn't generate a valid header, then we won't
1288 * transmit anything to the client.
1293 if (server_body || http->ssl)
1296 * If we have been buffering up the document,
1297 * now is the time to apply content modification
1298 * and send the result to the client.
1303 * If the content filter fails, use the original
1304 * buffer and length.
1305 * (see p != NULL ? p : csp->iob->cur below)
1307 if (NULL == (p = (*content_filter)(csp)))
1309 csp->content_length = csp->iob->eod - csp->iob->cur;
1312 hdr = sed(server_patterns, add_server_headers, csp);
1315 /* FIXME Should handle error properly */
1316 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1319 if (write_socket(csp->cfd, hdr, strlen(hdr))
1320 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1322 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1332 break; /* "game over, man" */
1336 * This is NOT the body, so
1337 * Let's pretend the server just sent us a blank line.
1339 len = sprintf(buf, "\r\n");
1342 * Now, let the normal header parsing algorithm below do its
1343 * job. If it fails, we'll exit instead of continuing.
1350 * If this is an SSL connection or we're in the body
1351 * of the server document, just write it to the client,
1352 * unless we need to buffer the body for later content-filtering
1355 if (server_body || http->ssl)
1359 add_to_iob(csp, buf, len);
1362 * If the buffer limit will be reached on the next read,
1363 * switch to non-filtering mode, i.e. make & write the
1364 * header, flush the socket and get out of the way.
1366 if (((size_t)(csp->iob->eod - csp->iob->buf)) + (size_t)BUFFER_SIZE > csp->config->buffer_limit)
1370 log_error(LOG_LEVEL_ERROR, "Buffer size limit reached! Flushing and stepping back.");
1372 hdr = sed(server_patterns, add_server_headers, csp);
1375 /* FIXME Should handle error properly */
1376 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1379 hdrlen = strlen(hdr);
1380 byte_count += hdrlen;
1382 if (write_socket(csp->cfd, hdr, hdrlen)
1383 || ((len = flush_socket(csp->cfd, csp)) < 0))
1385 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1394 content_filter = NULL;
1401 if (write_socket(csp->cfd, buf, (size_t)len))
1403 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1412 /* we're still looking for the end of the
1413 * server's header ... (does that make header
1414 * parsing an "out of body experience" ?
1417 /* buffer up the data we just read */
1418 add_to_iob(csp, buf, len);
1420 /* get header lines from the iob */
1422 while ((p = get_header(csp)) != NULL)
1426 /* see following note */
1429 enlist(csp->headers, p);
1433 /* NOTE: there are no "empty" headers so
1434 * if the pointer `p' is not NULL we must
1435 * assume that we reached the end of the
1436 * buffer before we hit the end of the header.
1443 /* Well, we tried our MS IIS/5
1444 * hack and it didn't work.
1445 * The header is incomplete
1446 * and there isn't anything
1447 * we can do about it.
1453 /* Since we have to wait for
1454 * more from the server before
1455 * we can parse the headers
1456 * we just continue here.
1462 /* we have now received the entire header.
1463 * filter it and send the result to the client
1466 hdr = sed(server_patterns, add_server_headers, csp);
1469 /* FIXME Should handle error properly */
1470 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1473 #ifdef FEATURE_KILL_POPUPS
1474 /* Start blocking popups if appropriate. */
1476 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1477 !http->ssl && /* We talk plaintext */
1478 block_popups) /* Policy allows */
1480 block_popups_now = 1;
1482 * Filter the part of the body that came in the same read
1483 * as the last headers:
1485 filter_popups(csp->iob->cur, csp);
1488 #endif /* def FEATURE_KILL_POPUPS */
1490 /* Buffer and pcrs filter this if appropriate. */
1492 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1493 !http->ssl && /* We talk plaintext */
1494 pcrs_filter) /* Policy allows */
1496 content_filter = pcrs_filter_response;
1499 /* Buffer and gif_deanimate this if appropriate. */
1501 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1502 !http->ssl && /* We talk plaintext */
1503 gif_deanimate) /* Policy allows */
1505 content_filter = gif_deanimate_response;
1509 * Only write if we're not buffering for content modification
1511 if (!content_filter)
1513 /* write the server's (modified) header to
1514 * the client (along with anything else that
1515 * may be in the buffer)
1518 if (write_socket(csp->cfd, hdr, strlen(hdr))
1519 || ((len = flush_socket(csp->cfd, csp)) < 0))
1521 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1523 /* the write failed, so don't bother
1524 * mentioning it to the client...
1525 * it probably can't hear us anyway.
1534 /* we're finished with the server's header */
1539 /* If this was a MS IIS/5 hack then it means
1540 * the server has already closed the
1541 * connection. Nothing more to read. Time
1552 return; /* huh? we should never get here */
1555 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1556 csp->ip_addr_str, http->ocmd, byte_count);
1560 /*********************************************************************
1564 * Description : This is little more than chat. We only "serve" to
1565 * to close any socket that chat may have opened.
1568 * 1 : csp = Current client state (buffers, headers, etc...)
1572 *********************************************************************/
1574 void serve(struct client_state *csp)
1575 #else /* ifndef AMIGA */
1576 static void serve(struct client_state *csp)
1577 #endif /* def AMIGA */
1580 close_socket(csp->cfd);
1582 if (csp->sfd != JB_INVALID_SOCKET)
1584 close_socket(csp->sfd);
1587 csp->flags &= ~CSP_FLAG_ACTIVE;
1593 /*********************************************************************
1595 * Function : server_thread
1597 * Description : We only exist to call `serve' in a threaded environment.
1600 * 1 : data = Current client state (buffers, headers, etc...)
1602 * Returns : Always 0.
1604 *********************************************************************/
1605 static int32 server_thread(void *data)
1607 serve((struct client_state *) data);
1614 /*********************************************************************
1618 * Description : Print usage info & exit.
1620 * Parameters : Pointer to argv[0] for identifying ourselves
1624 *********************************************************************/
1625 void usage(const char *myname)
1627 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
1628 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1629 "Aborting.\n", myname);
1636 /*********************************************************************
1640 * Description : Load the config file and start the listen loop.
1641 * This function is a lot more *sane* with the `load_config'
1642 * and `listen_loop' functions; although it stills does
1643 * a *little* too much for my taste.
1646 * 1 : argc = Number of parameters (including $0).
1647 * 2 : argv = Array of (char *)'s to the parameters.
1649 * Returns : 1 if : can't open config file, unrecognized directive,
1650 * stats requested in multi-thread mode, can't open the
1651 * log file, can't open the jar file, listen port is invalid,
1652 * any load fails, and can't bind port.
1654 * Else main never returns, the process must be signaled
1655 * to terminate execution. Or, on Windows, use the
1656 * "File", "Exit" menu option.
1658 *********************************************************************/
1660 int real_main(int argc, const char *argv[])
1662 int main(int argc, const char *argv[])
1667 struct passwd *pw = NULL;
1668 struct group *grp = NULL;
1676 #if !defined(_WIN32)
1684 * Parse the command line arguments
1686 while (++argc_pos < argc)
1688 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1690 if (strcmp(argv[argc_pos], "--help") == 0)
1695 else if(strcmp(argv[argc_pos], "--version") == 0)
1697 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1701 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1706 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1708 if (++argc_pos == argc) usage(argv[0]);
1709 pidfile = strdup(argv[argc_pos]);
1712 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1714 if (++argc_pos == argc) usage(argv[argc_pos]);
1716 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1719 if (NULL == (grp = getgrnam(p)))
1721 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1725 if (NULL == (pw = getpwnam(argv[argc_pos])))
1727 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1730 if (p != NULL) *--p = '\0';
1732 #endif /* defined(unix) */
1734 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1736 configfile = argv[argc_pos];
1739 } /* -END- while (more arguments) */
1742 if ( *configfile != '/' )
1746 /* make config-filename absolute here */
1747 if ( !(basedir = getcwd( NULL, 1024 )))
1749 perror("get working dir failed");
1753 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1755 perror("malloc failed");
1758 strcpy( abs_file, basedir );
1759 strcat( abs_file, "/" );
1760 strcat( abs_file, configfile );
1761 configfile = abs_file;
1763 #endif /* defined unix */
1770 #elif defined(_WIN32)
1775 * Unix signal handling
1777 * Catch the abort, interrupt and terminate signals for a graceful exit
1778 * Catch the hangup signal so the errlog can be reopened.
1779 * Ignore the broken pipe and child signals
1780 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1782 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1785 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1786 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1788 for (idx = 0; catched_signals[idx] != 0; idx++)
1790 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1792 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1796 for (idx = 0; ignored_signals[idx] != 0; idx++)
1798 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1800 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1805 #else /* ifdef _WIN32 */
1806 # ifdef _WIN_CONSOLE
1808 * We *are* in a windows console app.
1809 * Print a verbose messages about FAQ's and such
1811 printf(win32_blurb);
1812 # endif /* def _WIN_CONSOLE */
1813 #endif /* def _WIN32 */
1816 /* Initialize the CGI subsystem */
1817 cgi_init_error_messages();
1820 * If runnig on unix and without the --nodaemon
1821 * option, become a daemon. I.e. fork, detach
1822 * from tty and get process group leadership
1835 if ( pid < 0 ) /* error */
1840 else if ( pid != 0 ) /* parent */
1845 * must check for errors
1846 * child died due to missing files aso
1849 wpid = waitpid( pid, &status, WNOHANG );
1858 /* Should be more portable, but not as well tested */
1863 #else /* ndef __FreeBSD__ */
1865 #endif /* ndef __FreeBSD__ */
1866 fd = open("/dev/tty", O_RDONLY);
1869 /* no error check here */
1870 ioctl( fd, TIOCNOTTY,0 );
1874 /* FIXME: should close stderr (fd 2) here too, but the test
1876 * and load config file is done in listen_loop() and puts
1877 * some messages on stderr there.
1884 } /* -END- if (!no_daemon) */
1887 * As soon as we have written the PID file, we can switch
1888 * to the user and group ID indicated by the --user option
1894 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1896 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1898 if (setuid(pw->pw_uid))
1900 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1904 #endif /* defined unix */
1914 /*********************************************************************
1916 * Function : bind_port_helper
1918 * Description : Bind the listen port. Handles logging, and aborts
1922 * 1 : config = Privoxy configuration. Specifies port
1925 * Returns : Port that was opened.
1927 *********************************************************************/
1928 static jb_socket bind_port_helper(struct configuration_spec * config)
1933 if ( (config->haddr != NULL)
1934 && (config->haddr[0] == '1')
1935 && (config->haddr[1] == '2')
1936 && (config->haddr[2] == '7')
1937 && (config->haddr[3] == '.') )
1939 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1942 else if (config->haddr == NULL)
1944 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1949 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1950 config->hport, config->haddr);
1953 result = bind_port(config->haddr, config->hport, &bfd);
1960 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1961 "There may be another Privoxy or some other "
1962 "proxy running on port %d",
1963 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1964 config->hport, config->hport);
1967 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1968 "The hostname is not resolvable",
1969 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1972 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
1973 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1976 /* shouldn't get here */
1977 return JB_INVALID_SOCKET;
1980 config->need_bind = 0;
1986 /*********************************************************************
1988 * Function : listen_loop
1990 * Description : bind the listen port and enter a "FOREVER" listening loop.
1996 *********************************************************************/
1997 static void listen_loop(void)
1999 struct client_state *csp = NULL;
2001 struct configuration_spec * config;
2003 config = load_config();
2005 bfd = bind_port_helper(config);
2007 #ifdef FEATURE_GRACEFUL_TERMINATION
2008 while (!g_terminate)
2013 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
2014 while (waitpid(-1, NULL, WNOHANG) > 0)
2016 /* zombie children */
2018 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2021 * Free data that was used by died threads
2027 * Re-open the errlog after HUP signal
2029 if (received_hup_signal)
2031 init_error_log(Argv[0], config->logfile, config->debug);
2032 received_hup_signal = 0;
2037 #ifdef FEATURE_COOKIE_JAR
2039 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
2040 * already open. I think unload_configfile() is not being run, which should do
2041 * this work. Until that can get resolved, we'll use this workaround.
2045 if (csp->config->jar)
2047 fclose(csp->config->jar);
2048 csp->config->jar = NULL;
2050 #endif /* FEATURE_COOKIE_JAR */
2051 #endif /* __OS2__ */
2053 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2055 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2059 csp->flags |= CSP_FLAG_ACTIVE;
2060 csp->sfd = JB_INVALID_SOCKET;
2062 csp->config = config = load_config();
2064 if ( config->need_bind )
2067 * Since we were listening to the "old port", we will not see
2068 * a "listen" param change until the next IJB request. So, at
2069 * least 1 more request must be made for us to find the new
2070 * setting. I am simply closing the old socket and binding the
2073 * Which-ever is correct, we will serve 1 more page via the
2074 * old settings. This should probably be a "show-proxy-args"
2075 * request. This should not be a so common of an operation
2076 * that this will hurt people's feelings.
2081 bfd = bind_port_helper(config);
2084 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2086 if (!accept_connection(csp, bfd))
2088 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2101 log_error(LOG_LEVEL_CONNECT, "OK");
2104 #ifdef FEATURE_TOGGLE
2107 csp->flags |= CSP_FLAG_TOGGLED_ON;
2109 #endif /* def FEATURE_TOGGLE */
2111 if (run_loader(csp))
2113 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2114 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2118 if (block_acl(NULL,csp))
2120 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2121 close_socket(csp->cfd);
2125 #endif /* def FEATURE_ACL */
2127 /* add it to the list of clients */
2128 csp->next = clients->next;
2129 clients->next = csp;
2131 if (config->multi_threaded)
2135 /* this is a switch () statment in the C preprocessor - ugh */
2136 #undef SELECTED_ONE_OPTION
2138 /* Use Pthreads in preference to native code */
2139 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2140 #define SELECTED_ONE_OPTION
2142 pthread_t the_thread;
2143 pthread_attr_t attrs;
2145 pthread_attr_init(&attrs);
2146 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2147 child_id = (pthread_create(&the_thread, &attrs,
2148 (void*)serve, csp) ? -1 : 0);
2149 pthread_attr_destroy(&attrs);
2153 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2154 #define SELECTED_ONE_OPTION
2155 child_id = _beginthread(
2156 (void (*)(void *))serve,
2161 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2162 #define SELECTED_ONE_OPTION
2163 child_id = _beginthread(
2164 (void(* _Optlink)(void*))serve,
2170 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2171 #define SELECTED_ONE_OPTION
2173 thread_id tid = spawn_thread
2174 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2176 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2178 child_id = (int) tid;
2187 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2188 #define SELECTED_ONE_OPTION
2189 csp->cfd = ReleaseSocket(csp->cfd, -1);
2190 if((child_id = (int)CreateNewProcTags(
2191 NP_Entry, (ULONG)server_thread,
2192 NP_Output, Output(),
2193 NP_CloseOutput, FALSE,
2194 NP_Name, (ULONG)"privoxy child",
2195 NP_StackSize, 200*1024,
2199 ((struct Task *)child_id)->tc_UserData = csp;
2200 Signal((struct Task *)child_id, SIGF_SINGLE);
2205 #if !defined(SELECTED_ONE_OPTION)
2208 /* This block is only needed when using fork().
2209 * When using threads, the server thread was
2210 * created and run by the call to _beginthread().
2212 if (child_id == 0) /* child */
2218 else if (child_id > 0) /* parent */
2220 /* in a fork()'d environment, the parent's
2221 * copy of the client socket and the CSP
2225 #if !defined(_WIN32) && defined(__CYGWIN__)
2227 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2228 close_socket(csp->cfd);
2229 csp->flags &= ~CSP_FLAG_ACTIVE;
2233 #undef SELECTED_ONE_OPTION
2234 /* end of cpp switch () */
2236 if (child_id < 0) /* failed */
2238 char buf[BUFFER_SIZE];
2240 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2242 sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
2244 write_socket(csp->cfd, buf, strlen(buf));
2245 close_socket(csp->cfd);
2246 csp->flags &= ~CSP_FLAG_ACTIVE;
2257 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2259 /* Clean up. Aim: free all memory (no leaks) */
2260 #ifdef FEATURE_GRACEFUL_TERMINATION
2262 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2264 unload_current_config_file();
2265 unload_current_actions_file();
2266 unload_current_re_filterfile();
2267 #ifdef FEATURE_TRUST
2268 unload_current_trust_file();
2271 if (config->multi_threaded)
2278 } while ((clients->next != NULL) && (--i > 0));
2282 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2291 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2292 /* Cleanup - remove taskbar icon etc. */
2297 #endif /* FEATURE_GRACEFUL_TERMINATION */