1 const char jcc_rcs[] = "$Id: jcc.c,v 2.3 2002/07/18 22:06:12 jongfoster Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/src/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 2.3 2002/07/18 22:06:12 jongfoster
37 * Trivial formatting changes
39 * Revision 2.2 2002/07/12 04:26:17 agotneja
40 * Re-factored 'chat()' to become understandable and maintainable as
41 * a first step in adding Transparent Proxy functionality.
43 * Added several new static functions in jcc.c, and moved some data
44 * parameters up into project.h to allow them to be passed between
47 * Revision 1.91 2002/04/08 20:35:58 swa
50 * Revision 1.90 2002/04/02 14:57:28 oes
51 * Made sending wafers independent of FEATURE_COOKIE_JAR
53 * Revision 1.89 2002/03/31 17:18:59 jongfoster
54 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
56 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
57 * More compiler warning message maintenance
59 * Revision 1.87 2002/03/26 22:29:54 swa
60 * we have a new homepage!
62 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
63 * Workaround for closing the jarfile before load_config() comes around again
65 * Revision 1.85 2002/03/24 15:23:33 jongfoster
68 * Revision 1.84 2002/03/24 13:25:43 swa
69 * name change related issues
71 * Revision 1.83 2002/03/16 23:54:06 jongfoster
72 * Adding graceful termination feature, to help look for memory leaks.
73 * If you enable this (which, by design, has to be done by hand
74 * editing config.h) and then go to http://i.j.b/die, then the program
75 * will exit cleanly after the *next* request. It should free all the
76 * memory that was used.
78 * Revision 1.82 2002/03/13 00:27:05 jongfoster
81 * Revision 1.81 2002/03/12 01:42:50 oes
82 * Introduced modular filters
84 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
85 * OS/2 port maintenance:
86 * - Fixed EMX build - it had decayed a little
87 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
88 * substituted a memset for now.
90 * Revision 1.79 2002/03/09 20:03:52 jongfoster
91 * - Making various functions return int rather than size_t.
92 * (Undoing a recent change). Since size_t is unsigned on
93 * Windows, functions like read_socket that return -1 on
94 * error cannot return a size_t.
96 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
97 * crashes, and also frequently caused JB to jump to 100%
98 * CPU and stay there. (Because it thought it had just
99 * read ((unsigned)-1) == 4Gb of data...)
101 * - The signature of write_socket has changed, it now simply
102 * returns success=0/failure=nonzero.
104 * - Trying to get rid of a few warnings --with-debug on
105 * Windows, I've introduced a new type "jb_socket". This is
106 * used for the socket file descriptors. On Windows, this
107 * is SOCKET (a typedef for unsigned). Everywhere else, it's
108 * an int. The error value can't be -1 any more, so it's
109 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
110 * Windows it maps to the #define INVALID_SOCKET.)
112 * - The signature of bind_port has changed.
114 * Revision 1.78 2002/03/08 21:35:04 oes
115 * Added optional group supplement to --user option. Will now use default group of user if no group given
117 * Revision 1.77 2002/03/07 03:52:06 oes
118 * - Fixed compiler warnings etc
119 * - Improved handling of failed DNS lookups
121 * Revision 1.76 2002/03/06 22:54:35 jongfoster
122 * Automated function-comment nitpicking.
124 * Revision 1.75 2002/03/06 10:02:19 oes
125 * Fixed stupid bug when --user was not given
127 * Revision 1.74 2002/03/06 00:49:31 jongfoster
128 * Fixing warning on Windows
129 * Making #ifdefs that refer to the same variable consistently
130 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
132 * Revision 1.73 2002/03/05 23:57:30 hal9
133 * Stray character 's' on line 1618 was breaking build.
135 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
136 * - Re-enable OS/2 building after new parms were added
137 * - Fix false out of memory report when resolving CGI templates when no IP
138 * address is available of failed attempt (a la no such domain)
140 * Revision 1.71 2002/03/05 18:13:56 oes
141 * Added --user option
143 * Revision 1.70 2002/03/05 04:52:42 oes
144 * Deleted non-errlog debugging code
146 * Revision 1.69 2002/03/04 23:50:00 jongfoster
147 * Splitting off bind_port() call into bind_port_helper(), with
150 * Revision 1.68 2002/03/04 20:17:32 oes
153 * Revision 1.67 2002/03/04 18:18:57 oes
154 * - Removed _DEBUG mode
155 * - Cleand up cmdline parsing
156 * - Introduced --no-daemon, --pidfile options
157 * - Cleaned up signal handling:
158 * - Terminate cleanly on INT, TERM and ABRT
159 * - Schedule logfile for re-opening on HUP
160 * - Ignore CHLD and PIPE
161 * - Leave the rest with their default handlers
162 * - Uniform handler registration
163 * - Added usage() function
164 * - Played styleguide police
166 * Revision 1.66 2002/03/03 15:06:55 oes
167 * Re-enabled automatic config reloading
169 * Revision 1.65 2002/03/03 14:49:11 oes
170 * Fixed CLF logging: Now uses client's original HTTP request
172 * Revision 1.64 2002/03/03 09:18:03 joergs
173 * Made jumbjuster work on AmigaOS again.
175 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
176 * Clean up a little CRLF unpleasantness that suddenly appeared
178 * Revision 1.62 2002/02/20 23:17:23 jongfoster
179 * Detecting some out-of memory conditions and exiting with a log message.
181 * Revision 1.61 2002/01/17 21:01:52 jongfoster
182 * Moving all our URL and URL pattern parsing code to urlmatch.c.
184 * Revision 1.60 2001/12/30 14:07:32 steudten
185 * - Add signal handling (unix)
186 * - Add SIGHUP handler (unix)
187 * - Add creation of pidfile (unix)
188 * - Add action 'top' in rc file (RH)
189 * - Add entry 'SIGNALS' to manpage
190 * - Add exit message to logfile (unix)
192 * Revision 1.59 2001/12/13 14:07:18 oes
193 * Fixed Bug: 503 error page now sent OK
195 * Revision 1.58 2001/11/30 23:37:24 jongfoster
196 * Renaming the Win32 config file to config.txt - this is almost the
197 * same as the corresponding UNIX name "config"
199 * Revision 1.57 2001/11/16 00:47:43 jongfoster
200 * Changing the tty-disconnection code to use setsid().
202 * Revision 1.56 2001/11/13 20:20:54 jongfoster
203 * Tabs->spaces, fixing a bug with missing {} around an if()
205 * Revision 1.55 2001/11/13 20:14:53 jongfoster
206 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
208 * Revision 1.54 2001/11/07 00:03:14 steudten
209 * Give reliable return value if an error
210 * occurs not just 0 with new daemon mode.
212 * Revision 1.53 2001/11/05 21:41:43 steudten
213 * Add changes to be a real daemon just for unix os.
214 * (change cwd to /, detach from controlling tty, set
215 * process group and session leader to the own process.
217 * Add some fatal-error log message for failed malloc().
218 * Add '-d' if compiled with 'configure --with-debug' to
219 * enable debug output.
221 * Revision 1.52 2001/10/26 20:11:20 jongfoster
222 * Fixing type mismatch
224 * Revision 1.51 2001/10/26 17:38:28 oes
227 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
228 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
229 * threads to call select() simultaneously. So, it's time to do a real, live,
230 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
231 * (native). Both versions will work, but using __OS2__ offers multi-threading.
233 * Revision 1.49 2001/10/23 21:41:35 jongfoster
234 * Added call to initialize the (statically-allocated of course)
235 * "out of memory" CGI response.
237 * Revision 1.48 2001/10/10 19:56:46 jongfoster
238 * Moving some code that wasn't cookie-related out of an #ifdef
241 * Revision 1.47 2001/10/10 16:44:36 oes
242 * Added CONNECT destination port limitation check
244 * Revision 1.46 2001/10/08 15:17:41 oes
245 * Re-enabled SSL forwarding
247 * Revision 1.45 2001/10/07 15:42:11 oes
248 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
250 * Moved downgrading of the HTTP version from parse_http_request to
251 * chat(), since we can't decide if it is necessary before we have
252 * determined the actions for the URL. The HTTP command is now
253 * *always* re-built so the repairs need no longer be special-cased.
255 * filter_popups now gets a csp pointer so it can raise the new
256 * CSP_FLAG_MODIFIED flag.
260 * Added configurable size limit for the IOB. If the IOB grows so
261 * large that the next read would exceed the limit, the header
262 * is generated, and the header & unfiltered buffer are flushed
263 * to the client. Chat then continues in non-buffering,
264 * non-filtering body mode.
266 * Revision 1.44 2001/10/02 18:13:57 oes
269 * Revision 1.43 2001/10/02 15:32:13 oes
270 * Moved generation of hdr
272 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
273 * Cleaning up 2 compiler warnings on OS/2.
275 * Revision 1.41 2001/09/16 17:05:14 jongfoster
276 * Removing unused #include showarg.h
278 * Revision 1.40 2001/09/16 15:41:45 jongfoster
279 * Fixing signed/unsigned comparison warning.
281 * Revision 1.39 2001/09/16 13:21:27 jongfoster
282 * Changes to use new list functions.
284 * Revision 1.38 2001/09/16 13:01:46 jongfoster
285 * Removing redundant function call that zeroed zalloc()'d memory.
287 * Revision 1.37 2001/09/10 11:12:24 oes
288 * Deleted unused variable
290 * Revision 1.36 2001/09/10 10:56:15 oes
291 * Silenced compiler warnings
293 * Revision 1.35 2001/07/31 14:44:22 oes
294 * Deleted unused size parameter from filter_popups()
296 * Revision 1.34 2001/07/30 22:08:36 jongfoster
297 * Tidying up #defines:
298 * - All feature #defines are now of the form FEATURE_xxx
299 * - Permanently turned off WIN_GUI_EDIT
300 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
302 * Revision 1.33 2001/07/29 19:32:00 jongfoster
303 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
305 * Revision 1.32 2001/07/29 18:47:05 jongfoster
306 * Adding missing #include "loadcfg.h"
308 * Revision 1.31 2001/07/29 12:17:48 oes
309 * Applied pthread fix by Paul Lieverse
311 * Revision 1.30 2001/07/25 22:57:13 jongfoster
312 * __BEOS__ no longer overrides FEATURE_PTHREAD.
313 * This is because FEATURE_PTHREAD will soon be widely used, so I
314 * want to keep it simple.
316 * Revision 1.29 2001/07/24 12:47:06 oes
317 * Applied BeOS support update by Eugenia
319 * Revision 1.28 2001/07/23 13:26:12 oes
320 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
322 * Revision 1.27 2001/07/19 19:09:47 haroon
323 * - Added code to take care of the situation where while processing the first
324 * server response (which includes the server header), after finding the end
325 * of the headers we were not looking past the end of the headers for
326 * content modification. I enabled it for filter_popups.
327 * Someone else should look to see if other similar operations should be
328 * done to the discarded portion of the buffer.
330 * Note 2001/07/20: No, the other content modification mechanisms will process
331 * the whole iob later anyway. --oes
333 * Revision 1.26 2001/07/18 12:31:36 oes
336 * Revision 1.25 2001/07/15 19:43:49 jongfoster
337 * Supports POSIX threads.
338 * Also removed some unused #includes.
340 * Revision 1.24 2001/07/13 14:00:40 oes
341 * - Generic content modification scheme:
342 * Each feature has its own applicability flag that is set
343 * from csp->action->flags.
344 * Replaced the "filtering" int flag , by a function pointer
345 * "content_filter" to the function that will do the content
346 * modification. If it is != NULL, the document will be buffered
347 * and processed through *content_filter, which must set
348 * csp->content_length and return a modified copy of the body
349 * or return NULL (on failiure).
350 * - Changed csp->is_text to the more generic bitmap csp->content_type
351 * which can currently take the valued CT_TEXT or CT_GIF
353 * - Removed all #ifdef PCRS
355 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
356 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
357 * the `block_acl' call. This prevents a compilation error when the user
358 * does not wish to use the "ACL" feature.
360 * Revision 1.22 2001/06/29 21:45:41 oes
361 * Indentation, CRLF->LF, Tab-> Space
363 * Revision 1.21 2001/06/29 13:29:36 oes
364 * - Cleaned up, improved comments
365 * - Unified all possible interceptors (CGI,
366 * block, trust, fast_redirect) in one
367 * place, with one (CGI) answer generation
368 * mechansim. Much clearer now.
369 * - Removed the GIF image generation, which
370 * is now done in filters.c:block_url()
371 * - Made error conditions like domain lookup
372 * failiure or (various) problems while talking
373 * to the server use cgi.c:error_response()
374 * instead of generating HTML/HTTP in chat() (yuck!)
375 * - Removed logentry from cancelled commit
377 * Revision 1.20 2001/06/09 10:55:28 jongfoster
378 * Changing BUFSIZ ==> BUFFER_SIZE
380 * Revision 1.19 2001/06/07 23:12:52 jongfoster
381 * Replacing function pointer in struct gateway with a directly
382 * called function forwarded_connect().
383 * Replacing struct gateway with struct forward_spec
385 * Revision 1.18 2001/06/03 19:12:16 oes
386 * introduced new cgi handling
388 * Revision 1.17 2001/06/01 20:07:23 jongfoster
389 * Now uses action +image-blocker{} rather than config->tinygif
391 * Revision 1.16 2001/06/01 18:49:17 jongfoster
392 * Replaced "list_share" with "list" - the tiny memory gain was not
393 * worth the extra complexity.
395 * Revision 1.15 2001/05/31 21:24:47 jongfoster
396 * Changed "permission" to "action" throughout.
397 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
398 * Moved vanilla wafer check into chat(), since we must now
399 * decide whether or not to add it based on the URL.
401 * Revision 1.14 2001/05/29 20:14:01 joergs
402 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
405 * Revision 1.13 2001/05/29 09:50:24 jongfoster
406 * Unified blocklist/imagelist/permissionslist.
407 * File format is still under discussion, but the internal changes
410 * Also modified interceptor behaviour:
411 * - We now intercept all URLs beginning with one of the following
412 * prefixes (and *only* these prefixes):
414 * * http://ijbswa.sf.net/config/
415 * * http://ijbswa.sourceforge.net/config/
416 * - New interceptors "home page" - go to http://i.j.b/ to see it.
417 * - Internal changes so that intercepted and fast redirect pages
418 * are not replaced with an image.
419 * - Interceptors now have the option to send a binary page direct
420 * to the client. (i.e. ijb-send-banner uses this)
421 * - Implemented show-url-info interceptor. (Which is why I needed
422 * the above interceptors changes - a typical URL is
423 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
424 * The previous mechanism would not have intercepted that, and
425 * if it had been intercepted then it then it would have replaced
428 * Revision 1.12 2001/05/27 22:17:04 oes
430 * - re_process_buffer no longer writes the modified buffer
431 * to the client, which was very ugly. It now returns the
432 * buffer, which it is then written by chat.
434 * - content_length now adjusts the Content-Length: header
435 * for modified documents rather than crunch()ing it.
436 * (Length info in csp->content_length, which is 0 for
437 * unmodified documents)
439 * - For this to work, sed() is called twice when filtering.
441 * Revision 1.11 2001/05/26 17:27:53 jongfoster
442 * Added support for CLF and fixed LOG_LEVEL_LOG.
443 * Also did CRLF->LF fix of my previous patch.
445 * Revision 1.10 2001/05/26 15:26:15 jongfoster
446 * ACL feature now provides more security by immediately dropping
447 * connections from untrusted hosts.
449 * Revision 1.9 2001/05/26 00:28:36 jongfoster
450 * Automatic reloading of config file.
451 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
452 * Most of the global variables have been moved to a new
453 * struct configuration_spec, accessed through csp->config->globalname
454 * Most of the globals remaining are used by the Win32 GUI.
456 * Revision 1.8 2001/05/25 22:43:18 jongfoster
457 * Fixing minor memory leak and buffer overflow.
459 * Revision 1.7 2001/05/25 22:34:30 jongfoster
462 * Revision 1.6 2001/05/23 00:13:58 joergs
463 * AmigaOS support fixed.
465 * Revision 1.5 2001/05/22 18:46:04 oes
467 * - Enabled filtering banners by size rather than URL
468 * by adding patterns that replace all standard banner
469 * sizes with the "Junkbuster" gif to the re_filterfile
471 * - Enabled filtering WebBugs by providing a pattern
472 * which kills all 1x1 images
474 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
475 * which is selected by the (nonstandard and therefore
476 * capital) letter 'U' in the option string.
477 * It causes the quantifiers to be ungreedy by default.
478 * Appending a ? turns back to greedy (!).
480 * - Added a new interceptor ijb-send-banner, which
481 * sends back the "Junkbuster" gif. Without imagelist or
482 * MSIE detection support, or if tinygif = 1, or the
483 * URL isn't recognized as an imageurl, a lame HTML
484 * explanation is sent instead.
486 * - Added new feature, which permits blocking remote
487 * script redirects and firing back a local redirect
489 * The feature is conditionally compiled, i.e. it
490 * can be disabled with --disable-fast-redirects,
491 * plus it must be activated by a "fast-redirects"
492 * line in the config file, has its own log level
493 * and of course wants to be displayed by show-proxy-args
494 * Note: Boy, all the #ifdefs in 1001 locations and
495 * all the fumbling with configure.in and acconfig.h
496 * were *way* more work than the feature itself :-(
498 * - Because a generic redirect template was needed for
499 * this, tinygif = 3 now uses the same.
501 * - Moved GIFs, and other static HTTP response templates
506 * - Removed some >400 CRs again (Jon, you really worked
509 * Revision 1.4 2001/05/21 19:34:01 jongfoster
510 * Made failure to bind() a fatal error.
512 * Revision 1.3 2001/05/20 01:21:20 jongfoster
513 * Version 2.9.4 checkin.
514 * - Merged popupfile and cookiefile, and added control over PCRS
515 * filtering, in new "permissionsfile".
516 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
517 * file error you now get a message box (in the Win32 GUI) rather
518 * than the program exiting with no explanation.
519 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
521 * - Removed tabs from "config"
522 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
523 * - Bumped up version number.
525 * Revision 1.2 2001/05/17 22:34:44 oes
526 * - Added hint on GIF char array generation to jcc.c
527 * - Cleaned CRLF's from the sources and related files
528 * - Repaired logging for REF and FRC
530 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
531 * Initial import of version 2.9.3 source tree
534 *********************************************************************/
540 #include <sys/types.h>
547 #ifdef FEATURE_PTHREAD
549 #endif /* def FEATURE_PTHREAD */
552 # ifndef FEATURE_PTHREAD
556 # include <windows.h>
557 # include <process.h>
558 # endif /* ndef FEATURE_PTHREAD */
561 # ifndef _WIN_CONSOLE
563 # endif /* ndef _WIN_CONSOLE */
565 #else /* ifndef _WIN32 */
567 # if !defined (__OS2__)
569 # include <sys/wait.h>
570 # endif /* ndef __OS2__ */
571 # include <sys/time.h>
572 # include <sys/stat.h>
573 # include <sys/ioctl.h>
576 #include <sys/termios.h>
587 # include <socket.h> /* BeOS has select() for sockets only. */
588 # include <OS.h> /* declarations for threads and stuff. */
591 # if defined(__EMX__) || defined(__OS2__)
592 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
597 #define bzero(B,N) memset(B,0x00,n)
612 #include "killpopup.h"
613 #include "miscutil.h"
615 #include "jbsockets.h"
620 #include "urlmatch.h"
621 #ifdef FEATURE_ACTIVITY_CONSOLE
623 #endif /* def FEATURE_ACTIVITY_CONSOLE */
625 const char jcc_h_rcs[] = JCC_H_VERSION;
626 const char project_h_rcs[] = PROJECT_H_VERSION;
629 struct client_state clients[1];
630 struct file_list files[1];
632 #ifdef FEATURE_STATISTICS
633 int urls_read = 0; /* total nr of urls read inc rejected */
634 int urls_rejected = 0; /* total nr of urls rejected */
635 #endif /* def FEATURE_STATISTICS */
637 #ifdef FEATURE_GRACEFUL_TERMINATION
641 static void listen_loop(void);
642 static void chat(struct client_state *csp);
643 static jb_err relay_server_traffic( struct client_state *csp ) ;
644 static jb_err read_client_headers( struct client_state *csp, struct http_request *http ) ;
645 static jb_err process_client_headers( struct client_state *csp, struct http_request *http ) ;
646 static jb_err intercept_page( struct client_state *csp, struct http_request *http );
647 static jb_err open_forwarding_connection( struct client_state *csp );
648 static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http, char* hdr );
649 static jb_err is_connect_request_allowed( struct client_state *csp ) ;
653 void serve(struct client_state *csp);
654 #else /* ifndef AMIGA */
655 static void serve(struct client_state *csp);
656 #endif /* def AMIGA */
659 static int32 server_thread(void *data);
660 #endif /* def __BEOS__ */
663 #define sleep(N) Sleep(((N) * 1000))
667 #define sleep(N) DosSleep(((N) * 100))
670 #if defined(unix) || defined(__EMX__)
672 const char *pidfile = NULL;
673 int received_hup_signal = 0;
674 #endif /* defined unix */
676 /* The vanilla wafer. */
677 static const char VANILLA_WAFER[] =
678 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
679 "Do_not_send_me_any_copyrighted_information_other_than_the_"
680 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
681 "In_particular_do_not_send_me_any_cookies_that_"
682 "are_subject_to_a_claim_of_copyright_by_anybody._"
683 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
684 "(copyright_or_otherwise)_applying_to_any_cookie._";
687 * HTTP header sent when doing HTTPS tunnelling ("CONNECT" method).
689 static const char CSUCCEED[] =
690 "HTTP/1.0 200 Connection established\n"
691 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
695 * HTTP reply sent when the browser sends something unintelligible.
697 static const char CHEADER[] =
698 "HTTP/1.0 400 Invalid header received from browser\r\n\r\n";
702 * HTTP reply sent when the browser tries to tunnel ("CONNECT") to something
703 * other than a HTTPS port (as defined by +limit-connect).
705 static const char CFORBIDDEN[] =
706 "HTTP/1.0 403 Connection not allowable\r\nX-Hint: If you read this message interactively, then you know why this happens ,-)\r\n\r\n";
708 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
709 /*********************************************************************
711 * Function : sig_handler
713 * Description : Signal handler for different signals.
714 * Exit gracefully on ABRT, TERM and INT
715 * or set a flag that will cause the errlog
716 * to be reopened by the main thread on HUP.
719 * 1 : the_signal = the signal cause this function to call
723 *********************************************************************/
724 static void sig_handler(int the_signal)
731 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
739 received_hup_signal = 1;
744 * We shouldn't be here, unless we catch signals
745 * in main() that we can't handle here!
747 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
755 /*********************************************************************
759 * Description : Once a connection to the client has been accepted,
760 * this function is called (via serve()) to handle the
761 * main business of the communication. When this
762 * function returns, the caller must close the client
766 * 1 : csp = Current client state (buffers, headers, etc...)
770 *********************************************************************/
771 static void chat(struct client_state *csp)
775 char buf[BUFFER_SIZE];
776 int len; /* for buffer sizes */
782 struct http_request *http;
786 if (read_client_headers(csp, http ) != JB_ERR_OK )
790 /* Process the client headers */
791 if (process_client_headers(csp, http) != JB_ERR_OK)
795 /* Check if this connection request is permitted */
796 if (is_connect_request_allowed(csp) != JB_ERR_OK)
800 * We have a valid and legit request. Now, check to see if we need to
803 if (intercept_page(csp, http) != JB_ERR_OK)
807 * The page passed the intercept routine, so open a forwarding
808 * connection for conversation
810 if (open_forwarding_connection(csp) != JB_ERR_OK )
815 hdr = sed(client_patterns, add_client_headers, csp);
818 /* FIXME Should handle error properly */
819 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
822 /* FIXME - where should this go, logically ? */
823 list_remove_all(csp->headers);
826 if (send_client_headers_to_server(csp, http, hdr) != JB_ERR_OK)
830 /* we're finished with the client's header */
833 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
835 /* pass data between the client and server
836 * until one or the other shuts down the connection.
839 /* Set the flag for reading headers to False */
840 /* This is used in relay_server_traffic */
841 csp->all_headers_read = 0 ;
845 jb_err tmp_ret_val = JB_ERR_GENERIC ;
849 * FD_ZERO here seems to point to an errant macro which crashes.
850 * So do this by hand for now...
852 memset(&rfds,0x00,sizeof(fd_set));
856 FD_SET(csp->cfd, &rfds);
857 FD_SET(csp->sfd, &rfds);
859 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
863 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
868 * This is the body of the browser's request.
869 * Just read it and write it.
872 if (FD_ISSET(csp->cfd, &rfds))
874 len = read_socket(csp->cfd, buf, sizeof(buf));
878 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
879 csp->ip_addr_str, http->ocmd, byte_count);
883 if (write_socket(csp->sfd, buf, (size_t)len))
885 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
892 * Check if the server wants to talk, and if so, converse.
895 if (FD_ISSET(csp->sfd, &rfds))
896 tmp_ret_val = relay_server_traffic(csp) ;
899 if (tmp_ret_val == JB_ERR_OK)
904 /* We should never get here! */
905 log_error(LOG_LEVEL_FATAL, "chat() : logic error in for() loop" ) ;
909 /*********************************************************************
913 * Description : This is little more than chat. We only "serve" to
914 * to close any socket that chat may have opened.
917 * 1 : csp = Current client state (buffers, headers, etc...)
921 *********************************************************************/
923 void serve(struct client_state *csp)
924 #else /* ifndef AMIGA */
925 static void serve(struct client_state *csp)
926 #endif /* def AMIGA */
929 close_socket(csp->cfd);
931 if (csp->sfd != JB_INVALID_SOCKET)
933 close_socket(csp->sfd);
936 csp->flags &= ~CSP_FLAG_ACTIVE;
942 /*********************************************************************
944 * Function : server_thread
946 * Description : We only exist to call `serve' in a threaded environment.
949 * 1 : data = Current client state (buffers, headers, etc...)
951 * Returns : Always 0.
953 *********************************************************************/
954 static int32 server_thread(void *data)
956 serve((struct client_state *) data);
963 /*********************************************************************
967 * Description : Print usage info & exit.
969 * Parameters : Pointer to argv[0] for identifying ourselves
973 *********************************************************************/
974 void usage(const char *myname)
976 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
977 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
978 "Aborting.\n", myname);
985 /*********************************************************************
989 * Description : Load the config file and start the listen loop.
990 * This function is a lot more *sane* with the `load_config'
991 * and `listen_loop' functions; although it stills does
992 * a *little* too much for my taste.
995 * 1 : argc = Number of parameters (including $0).
996 * 2 : argv = Array of (char *)'s to the parameters.
998 * Returns : 1 if : can't open config file, unrecognized directive,
999 * stats requested in multi-thread mode, can't open the
1000 * log file, can't open the jar file, listen port is invalid,
1001 * any load fails, and can't bind port.
1003 * Else main never returns, the process must be signaled
1004 * to terminate execution. Or, on Windows, use the
1005 * "File", "Exit" menu option.
1007 *********************************************************************/
1009 int real_main(int argc, const char *argv[])
1011 int main(int argc, const char *argv[])
1016 struct passwd *pw = NULL;
1017 struct group *grp = NULL;
1025 #if !defined(_WIN32)
1033 * Parse the command line arguments
1035 while (++argc_pos < argc)
1037 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1039 if (strcmp(argv[argc_pos], "--help") == 0)
1044 else if(strcmp(argv[argc_pos], "--version") == 0)
1046 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1050 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1055 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1057 if (++argc_pos == argc) usage(argv[0]);
1058 pidfile = strdup(argv[argc_pos]);
1061 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1063 if (++argc_pos == argc) usage(argv[argc_pos]);
1065 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1068 if (NULL == (grp = getgrnam(p)))
1070 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1074 if (NULL == (pw = getpwnam(argv[argc_pos])))
1076 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1079 if (p != NULL) *--p = '\0';
1081 #endif /* defined(unix) */
1083 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1085 configfile = argv[argc_pos];
1088 } /* -END- while (more arguments) */
1091 if ( *configfile != '/' )
1095 /* make config-filename absolute here */
1096 if ( !(basedir = getcwd( NULL, 1024 )))
1098 perror("get working dir failed");
1102 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1104 perror("malloc failed");
1107 strcpy( abs_file, basedir );
1108 strcat( abs_file, "/" );
1109 strcat( abs_file, configfile );
1110 configfile = abs_file;
1112 #endif /* defined unix */
1119 #elif defined(_WIN32)
1124 * Unix signal handling
1126 * Catch the abort, interrupt and terminate signals for a graceful exit
1127 * Catch the hangup signal so the errlog can be reopened.
1128 * Ignore the broken pipe and child signals
1129 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1131 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1134 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1135 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1137 for (idx = 0; catched_signals[idx] != 0; idx++)
1139 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1141 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1145 for (idx = 0; ignored_signals[idx] != 0; idx++)
1147 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1149 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1154 #else /* ifdef _WIN32 */
1155 # ifdef _WIN_CONSOLE
1157 * We *are* in a windows console app.
1158 * Print a verbose messages about FAQ's and such
1160 printf(win32_blurb);
1161 # endif /* def _WIN_CONSOLE */
1162 #endif /* def _WIN32 */
1165 /* Initialize the CGI subsystem */
1166 cgi_init_error_messages();
1169 * If runnig on unix and without the --nodaemon
1170 * option, become a daemon. I.e. fork, detach
1171 * from tty and get process group leadership
1184 if ( pid < 0 ) /* error */
1189 else if ( pid != 0 ) /* parent */
1194 * must check for errors
1195 * child died due to missing files aso
1198 wpid = waitpid( pid, &status, WNOHANG );
1207 /* Should be more portable, but not as well tested */
1212 #else /* ndef __FreeBSD__ */
1214 #endif /* ndef __FreeBSD__ */
1215 fd = open("/dev/tty", O_RDONLY);
1218 /* no error check here */
1219 ioctl( fd, TIOCNOTTY,0 );
1223 /* FIXME: should close stderr (fd 2) here too, but the test
1225 * and load config file is done in listen_loop() and puts
1226 * some messages on stderr there.
1233 } /* -END- if (!no_daemon) */
1236 * As soon as we have written the PID file, we can switch
1237 * to the user and group ID indicated by the --user option
1243 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1245 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1247 if (setuid(pw->pw_uid))
1249 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1253 #endif /* defined unix */
1263 /*********************************************************************
1265 * Function : bind_port_helper
1267 * Description : Bind the listen port. Handles logging, and aborts
1271 * 1 : config = Privoxy configuration. Specifies port
1274 * Returns : Port that was opened.
1276 *********************************************************************/
1277 static jb_socket bind_port_helper(struct configuration_spec * config)
1282 if ( (config->haddr != NULL)
1283 && (config->haddr[0] == '1')
1284 && (config->haddr[1] == '2')
1285 && (config->haddr[2] == '7')
1286 && (config->haddr[3] == '.') )
1288 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1291 else if (config->haddr == NULL)
1293 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1298 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1299 config->hport, config->haddr);
1302 result = bind_port(config->haddr, config->hport, &bfd);
1309 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1310 "There may be another Privoxy or some other "
1311 "proxy running on port %d",
1312 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1313 config->hport, config->hport);
1316 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1317 "The hostname is not resolvable",
1318 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1321 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
1322 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1325 /* shouldn't get here */
1326 return JB_INVALID_SOCKET;
1329 config->need_bind = 0;
1335 /*********************************************************************
1337 * Function : listen_loop
1339 * Description : bind the listen port and enter a "FOREVER" listening loop.
1345 *********************************************************************/
1346 static void listen_loop(void)
1348 struct client_state *csp = NULL;
1350 struct configuration_spec * config;
1352 config = load_config();
1354 bfd = bind_port_helper(config);
1356 #ifdef FEATURE_ACTIVITY_CONSOLE
1357 init_stats_config(config);
1358 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1360 #ifdef FEATURE_GRACEFUL_TERMINATION
1361 while (!g_terminate)
1366 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1367 while (waitpid(-1, NULL, WNOHANG) > 0)
1369 /* zombie children */
1371 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1374 * Free data that was used by died threads
1380 * Re-open the errlog after HUP signal
1382 if (received_hup_signal)
1384 init_error_log(Argv[0], config->logfile, config->debug);
1385 received_hup_signal = 0;
1390 #ifdef FEATURE_COOKIE_JAR
1392 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
1393 * already open. I think unload_configfile() is not being run, which should do
1394 * this work. Until that can get resolved, we'll use this workaround.
1396 * [Note from Jon: We don't unload_configfile() until all existing threads have
1397 * exited - they're likely to hang aroung transferring data to the browser.]
1401 if (csp->config->jar)
1403 fclose(csp->config->jar);
1404 csp->config->jar = NULL;
1406 #endif /* FEATURE_COOKIE_JAR */
1407 #endif /* __OS2__ */
1409 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1411 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1415 csp->flags |= CSP_FLAG_ACTIVE;
1416 csp->sfd = JB_INVALID_SOCKET;
1418 csp->config = config = load_config();
1420 if ( config->need_bind )
1423 * Since we were listening to the "old port", we will not see
1424 * a "listen" param change until the next IJB request. So, at
1425 * least 1 more request must be made for us to find the new
1426 * setting. I am simply closing the old socket and binding the
1429 * Which-ever is correct, we will serve 1 more page via the
1430 * old settings. This should probably be a "show-proxy-args"
1431 * request. This should not be a so common of an operation
1432 * that this will hurt people's feelings.
1437 bfd = bind_port_helper(config);
1440 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1442 if (!accept_connection(csp, bfd))
1444 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1457 log_error(LOG_LEVEL_CONNECT, "OK");
1460 #ifdef FEATURE_TOGGLE
1463 csp->flags |= CSP_FLAG_TOGGLED_ON;
1465 #endif /* def FEATURE_TOGGLE */
1467 #ifdef FEATURE_ACTIVITY_CONSOLE
1468 update_stats_config(config);
1469 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1471 if (run_loader(csp))
1473 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1474 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1478 if (block_acl(NULL,csp))
1480 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1481 close_socket(csp->cfd);
1485 #endif /* def FEATURE_ACL */
1487 /* add it to the list of clients */
1488 csp->next = clients->next;
1489 clients->next = csp;
1491 if (config->multi_threaded)
1495 /* this is a switch () statment in the C preprocessor - ugh */
1496 #undef SELECTED_ONE_OPTION
1498 /* Use Pthreads in preference to native code */
1499 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1500 #define SELECTED_ONE_OPTION
1502 pthread_t the_thread;
1503 pthread_attr_t attrs;
1505 pthread_attr_init(&attrs);
1506 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1507 child_id = (pthread_create(&the_thread, &attrs,
1508 (void*)serve, csp) ? -1 : 0);
1509 pthread_attr_destroy(&attrs);
1513 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1514 #define SELECTED_ONE_OPTION
1515 child_id = _beginthread(
1516 (void (*)(void *))serve,
1521 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1522 #define SELECTED_ONE_OPTION
1523 child_id = _beginthread(
1524 (void(* _Optlink)(void*))serve,
1530 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1531 #define SELECTED_ONE_OPTION
1533 thread_id tid = spawn_thread
1534 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1536 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1538 child_id = (int) tid;
1547 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1548 #define SELECTED_ONE_OPTION
1549 csp->cfd = ReleaseSocket(csp->cfd, -1);
1550 if((child_id = (int)CreateNewProcTags(
1551 NP_Entry, (ULONG)server_thread,
1552 NP_Output, Output(),
1553 NP_CloseOutput, FALSE,
1554 NP_Name, (ULONG)"privoxy child",
1555 NP_StackSize, 200*1024,
1559 ((struct Task *)child_id)->tc_UserData = csp;
1560 Signal((struct Task *)child_id, SIGF_SINGLE);
1565 #if !defined(SELECTED_ONE_OPTION)
1568 /* This block is only needed when using fork().
1569 * When using threads, the server thread was
1570 * created and run by the call to _beginthread().
1572 if (child_id == 0) /* child */
1578 else if (child_id > 0) /* parent */
1580 /* in a fork()'d environment, the parent's
1581 * copy of the client socket and the CSP
1585 #if !defined(_WIN32) && defined(__CYGWIN__)
1587 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1588 close_socket(csp->cfd);
1589 csp->flags &= ~CSP_FLAG_ACTIVE;
1593 #undef SELECTED_ONE_OPTION
1594 /* end of cpp switch () */
1596 if (child_id < 0) /* failed */
1598 char buf[BUFFER_SIZE];
1600 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1602 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
1604 write_socket(csp->cfd, buf, strlen(buf));
1605 close_socket(csp->cfd);
1606 csp->flags &= ~CSP_FLAG_ACTIVE;
1617 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
1619 /* Clean up. Aim: free all memory (no leaks) */
1620 #ifdef FEATURE_GRACEFUL_TERMINATION
1622 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
1624 unload_current_config_file();
1625 unload_current_actions_file();
1626 unload_current_re_filterfile();
1627 #ifdef FEATURE_TRUST
1628 unload_current_trust_file();
1631 if (config->multi_threaded)
1638 } while ((clients->next != NULL) && (--i > 0));
1642 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
1651 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
1652 /* Cleanup - remove taskbar icon etc. */
1657 #endif /* FEATURE_GRACEFUL_TERMINATION */
1661 /*********************************************************************
1663 * Function : relay_server_traffic
1665 * Description : receive traffic from the server and relay it
1666 * to the client, with some processing
1669 * 1 : client_state structure
1672 * Returns : JB_ERR_OK if there may be more work
1673 * : other values for errors
1675 **********************************************************************/
1677 static jb_err relay_server_traffic( struct client_state *csp )
1679 #ifdef FEATURE_KILL_POPUPS
1680 int block_popups; /* bool, 1==will block popups */
1681 int block_popups_now = 0; /* bool, 1==currently blocking popups */
1682 #endif /* def FEATURE_KILL_POPUPS */
1684 char buf[BUFFER_SIZE];
1685 int len; /* for buffer sizes */
1686 int ms_iis5_hack = 0;
1691 /* Skeleton for HTTP response, if we should intercept the request */
1692 struct http_response *rsp;
1694 int pcrs_filter; /* bool, 1==will filter through pcrs */
1695 int gif_deanimate; /* bool, 1==will deanimate gifs */
1697 #ifdef FEATURE_KILL_POPUPS
1698 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1699 #endif /* def FEATURE_KILL_POPUPS */
1701 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
1702 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1704 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1708 len = read_socket (csp->sfd, buf, sizeof (buf) - 1);
1712 log_error (LOG_LEVEL_ERROR, "read from: %s failed: %E", csp->http->host);
1714 log_error (LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1715 csp->ip_addr_str, csp->http->ocmd);
1717 rsp = error_response (csp, "connect-failed", errno);
1721 if (write_socket (csp->cfd, rsp->head, rsp->head_length)
1722 || write_socket (csp->cfd, rsp->body, rsp->content_length))
1724 log_error (LOG_LEVEL_ERROR, "write to: %s failed: %E",
1729 free_http_response (rsp);
1730 return JB_ERR_GENERIC;
1733 /* Add a trailing zero. This lets filter_popups
1734 * use string operations.
1738 #ifdef FEATURE_KILL_POPUPS
1739 /* Filter the popups on this read. */
1740 if (block_popups_now)
1742 filter_popups (buf, csp);
1744 #endif /* def FEATURE_KILL_POPUPS */
1747 /* Normally, this would indicate that we've read
1748 * as much as the server has sent us and we can
1749 * close the client connection. However, Microsoft
1750 * in its wisdom has released IIS/5 with a bug that
1751 * prevents it from sending the trailing \r\n in
1752 * a 302 redirect header (and possibly other headers).
1753 * To work around this if we've haven't parsed
1754 * a full header we'll append a trailing \r\n
1755 * and see if this now generates a valid one.
1757 * This hack shouldn't have any impacts. If we've
1758 * already transmitted the header or if this is a
1759 * SSL connection, then we won't bother with this
1760 * hack. So we only work on partially received
1761 * headers. If we append a \r\n and this still
1762 * doesn't generate a valid header, then we won't
1763 * transmit anything to the client.
1768 if (csp->all_headers_read || csp->http->ssl)
1771 * If we have been buffering up the document,
1772 * now is the time to apply content modification
1773 * and send the result to the client.
1775 if (csp->content_filter)
1778 * If the content filter fails, use the original
1779 * buffer and length.
1780 * (see p != NULL ? p : csp->iob->cur below)
1782 if (NULL == (p = (*csp->content_filter) (csp)))
1784 csp->content_length = csp->iob->eod - csp->iob->cur;
1787 hdr = sed (server_patterns, add_server_headers, csp);
1790 /* FIXME Should handle error properly */
1791 log_error (LOG_LEVEL_FATAL,
1792 "Out of memory parsing server header");
1796 if (write_socket (csp->cfd, hdr, strlen (hdr))
1797 || write_socket (csp->cfd, p != NULL ? p : csp->iob->cur,
1798 csp->content_length))
1800 log_error (LOG_LEVEL_ERROR,
1801 "write modified content to client failed: %E");
1802 return JB_ERR_GENERIC;
1811 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1812 csp->ip_addr_str, csp->http->ocmd, byte_count);
1813 return JB_ERR_GENERIC;
1817 * This is NOT the body, so
1818 * Let's pretend the server just sent us a blank line.
1820 len = sprintf (buf, "\r\n");
1823 * Now, let the normal header parsing algorithm below do its
1824 * job. If it fails, we'll exit instead of continuing.
1831 * If this is an SSL connection or we're in the body
1832 * of the server document, just write it to the client,
1833 * unless we need to buffer the body for later content-filtering
1836 if (csp->all_headers_read || csp->http->ssl)
1838 if (csp->content_filter)
1840 add_to_iob (csp, buf, len);
1843 * If the buffer limit will be reached on the next read,
1844 * switch to non-filtering mode, i.e. make & write the
1845 * header, flush the socket and get out of the way.
1847 if (((size_t) (csp->iob->eod - csp->iob->buf)) +
1848 (size_t) BUFFER_SIZE > csp->config->buffer_limit)
1852 log_error (LOG_LEVEL_ERROR,
1853 "Buffer size limit reached! Flushing and stepping back.");
1855 hdr = sed (server_patterns, add_server_headers, csp);
1858 /* FIXME Should handle error properly */
1859 log_error (LOG_LEVEL_FATAL,
1860 "Out of memory parsing server header");
1863 hdrlen = strlen (hdr);
1864 byte_count += hdrlen;
1866 if (write_socket (csp->cfd, hdr, hdrlen)
1867 || ((len = flush_socket (csp->cfd, csp)) < 0))
1869 log_error (LOG_LEVEL_CONNECT,
1870 "write header to client failed: %E");
1873 return JB_ERR_GENERIC;
1879 csp->content_filter = NULL;
1880 csp->all_headers_read = 1;
1886 if (write_socket (csp->cfd, buf, (size_t) len))
1888 log_error (LOG_LEVEL_ERROR, "write to client failed: %E");
1889 return JB_ERR_GENERIC;
1898 * we're still looking for the end of the
1899 * server's header ... (does that make header
1900 * parsing an "out of body experience" ?
1903 /* buffer up the data we just read */
1904 add_to_iob (csp, buf, len);
1906 /* get header lines from the iob */
1908 while ((p = get_header (csp)) != NULL)
1912 /* see following note */
1913 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1914 csp->ip_addr_str, csp->http->ocmd, byte_count);
1915 return JB_ERR_GENERIC;
1917 enlist (csp->headers, p);
1921 /* NOTE: there are no "empty" headers so
1922 * if the pointer `p' is not NULL we must
1923 * assume that we reached the end of the
1924 * buffer before we hit the end of the header.
1931 /* Well, we tried our MS IIS/5
1932 * hack and it didn't work.
1933 * The header is incomplete
1934 * and there isn't anything
1935 * we can do about it.
1937 log_error(LOG_LEVEL_CLF, "Incomplete Server Header: %s - - [%T] \"%s\" 200 %d",
1938 csp->ip_addr_str, csp->http->ocmd, byte_count);
1939 return JB_ERR_GENERIC;
1943 /* Since we have to wait for
1944 * more from the server before
1945 * we can parse the headers
1946 * we just continue here.
1952 /* we have now received the entire header.
1953 * filter it and send the result to the client
1956 hdr = sed (server_patterns, add_server_headers, csp);
1959 /* FIXME Should handle error properly */
1960 log_error (LOG_LEVEL_FATAL, "Out of memory parsing server header");
1965 #ifdef FEATURE_KILL_POPUPS
1966 /* Start blocking popups if appropriate. */
1968 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1969 !csp->http->ssl && /* We talk plaintext */
1970 block_popups) /* Policy allows */
1972 block_popups_now = 1;
1974 * Filter the part of the body that came in the same read
1975 * as the last headers:
1977 filter_popups (csp->iob->cur, csp);
1980 #endif /* def FEATURE_KILL_POPUPS */
1982 /* Buffer and pcrs filter this if appropriate. */
1984 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1985 !csp->http->ssl && /* We talk plaintext */
1986 pcrs_filter) /* Policy allows */
1988 csp->content_filter = pcrs_filter_response;
1991 /* Buffer and gif_deanimate this if appropriate. */
1993 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
1994 !csp->http->ssl && /* We talk plaintext */
1995 gif_deanimate) /* Policy allows */
1997 csp->content_filter = gif_deanimate_response;
2000 * Only write if we're not buffering for content modification
2002 if (!csp->content_filter)
2004 /* write the server's (modified) header to
2005 * the client (along with anything else that
2006 * may be in the buffer)
2008 if (write_socket (csp->cfd, hdr, strlen (hdr))
2009 || ((len = flush_socket (csp->cfd, csp)) < 0))
2011 log_error (LOG_LEVEL_CONNECT,
2012 "write header to client failed: %E");
2014 /* the write failed, so don't bother
2015 * mentioning it to the client...
2016 * it probably can't hear us anyway.
2019 return JB_ERR_GENERIC;
2025 /* we're finished with the server's header */
2028 csp->all_headers_read = 1;
2030 /* If this was a MS IIS/5 hack then it means
2031 * the server has already closed the
2032 * connection. Nothing more to read. Time
2037 return JB_ERR_GENERIC ;
2041 } /* END relay_server_traffic() */
2044 /*********************************************************************
2046 * Function : read_client_headers
2048 * Description : read all the client headers, and fill in the
2052 * 1 : client_state structure
2053 * 2 : http_request structure
2056 * Returns : JB_ERR_OK - headers read and parsed ok
2057 * : other values - an error occurred.
2058 *********************************************************************/
2060 static jb_err read_client_headers( struct client_state *csp, struct http_request *http )
2065 char buf[BUFFER_SIZE];
2066 int len; /* for buffer sizes */
2069 * Read the client's request. Note that since we're not using select() we
2070 * could get blocked here if a client connected, then didn't say anything!
2072 * This will read all the client headers.
2078 len = read_socket(csp->cfd, buf, sizeof(buf));
2080 if (len <= 0) break; /* error! */
2082 add_to_iob(csp, buf, len);
2084 req = get_header(csp);
2088 break; /* no HTTP request! */
2093 continue; /* more to come! */
2096 /* When we get here we have read one header which is enough */
2097 /* to check whether the connection is allowed */
2105 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
2107 len = read_socket(csp->cfd, buf, sizeof(buf));
2110 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
2111 return JB_ERR_GENERIC;
2113 add_to_iob(csp, buf, len);
2117 if (p == NULL) break;
2119 enlist(csp->headers, p);
2124 parse_http_request(req, http, csp);
2127 if (http->cmd == NULL)
2129 strcpy(buf, CHEADER);
2130 write_socket(csp->cfd, buf, strlen(buf));
2132 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
2134 return JB_ERR_GENERIC;
2140 } /* END read_client_headers */
2143 /*********************************************************************
2145 * Function : process_client_headers
2147 * Description : Process client headers
2148 * FIXME: Add description of what we do here!
2151 * 1 : client_state structure
2152 * 2 : http_request structure
2155 * Returns : JB_ERR_OK - headers processed ok
2156 * : other values - an error occurred.
2157 *********************************************************************/
2159 static jb_err process_client_headers( struct client_state *csp, struct http_request *http )
2163 #ifdef FEATURE_FORCE_LOAD
2164 /* If this request contains the FORCE_PREFIX,
2165 * better get rid of it now and set the force flag --oes
2166 * Changed to use the http structure rather than the req field --jaa
2169 if (strstr(http->url, FORCE_PREFIX))
2171 strclean(http->url, FORCE_PREFIX);
2172 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", http->url);
2173 csp->flags |= CSP_FLAG_FORCED;
2176 #endif /* def FEATURE_FORCE_LOAD */
2179 /* decide how to route the HTTP request */
2181 if ((http->fwd = forward_url(http, csp)) == NULL)
2183 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2184 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2187 /* build the http request to send to the server
2188 * we have to do one of the following:
2190 * create = use the original HTTP request to create a new
2191 * HTTP request that has either the path component
2192 * without the http://domainspec (w/path) or the
2193 * full orininal URL (w/url)
2194 * Note that the path and/or the HTTP version may
2195 * have been altered by now.
2197 * connect = Open a socket to the host:port of the server
2198 * and short-circuit server and client socket.
2200 * pass = Pass the request unchanged if forwarding a CONNECT
2201 * request to a parent proxy. Note that we'll be sending
2202 * the CFAIL message ourselves if connecting to the parent
2203 * fails, but we won't send a CSUCCEED message if it works,
2204 * since that would result in a double message (ours and the
2205 * parent's). After sending the request to the parent, we simply
2208 * here's the matrix:
2211 * +--------+--------+
2213 * 0 | create | connect|
2215 * Forwarding +--------+--------+
2217 * 1 | create | pass |
2219 * +--------+--------+
2224 * Determine the actions for this URL
2226 #ifdef FEATURE_TOGGLE
2227 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
2229 /* Most compatible set of actions (i.e. none) */
2230 init_current_action(csp->action);
2233 #endif /* ndef FEATURE_TOGGLE */
2235 url_actions(http, csp);
2243 * Downgrade http version from 1.1 to 1.0 if +downgrade
2246 if ( (http->ssl == 0)
2247 && (!strcmpic(http->ver, "HTTP/1.1"))
2248 && (csp->action->flags & ACTION_DOWNGRADE))
2251 http->ver = strdup("HTTP/1.0");
2253 if (http->ver == NULL)
2255 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
2260 * Save a copy of the original request for logging
2262 http->ocmd = strdup(http->cmd);
2264 if (http->ocmd == NULL)
2266 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
2270 * (Re)build the HTTP request for non-SSL requests.
2271 * If forwarding, use the whole URL, else, use only the path.
2277 http->cmd = strdup(http->gpc);
2278 string_append(&http->cmd, " ");
2280 if (http->fwd->forward_host)
2282 string_append(&http->cmd, http->url);
2286 string_append(&http->cmd, http->path);
2289 string_append(&http->cmd, " ");
2290 string_append(&http->cmd, http->ver);
2292 if (http->cmd == NULL)
2294 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
2297 enlist_first(csp->headers, http->cmd);
2301 * If the user has not supplied any wafers, and the user has not
2302 * told us to suppress the vanilla wafer, then send the vanilla wafer.
2304 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
2305 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
2307 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
2311 } /* process_client_headers */
2313 /*********************************************************************
2315 * Function : intercept_page
2317 * Description : Check whether to intercept page
2320 * 1 : client_state structure
2321 * 2 : http_request structure
2324 * Returns : JB_ERR_OK - Do NOT intercept this page
2325 * : JB_ERR_INTERCEPT - intercept this page
2326 * : all other values - an error occurred.
2327 *********************************************************************/
2328 static jb_err intercept_page( struct client_state *csp, struct http_request *http )
2331 /* Skeleton for HTTP response, if we should intercept the request */
2332 struct http_response *rsp;
2336 * These next lines are a little ugly, but they simplifies the if statements
2337 * below. Basically if TOGGLE, then we want the if to test if the
2338 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
2339 * then we want the if to test for CSP_FLAG_FORCED , else we don't
2341 #ifdef FEATURE_TOGGLE
2342 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
2343 #else /* ifndef FEATURE_TOGGLE */
2344 # define IS_TOGGLED_ON_AND
2345 #endif /* ndef FEATURE_TOGGLE */
2346 #ifdef FEATURE_FORCE_LOAD
2347 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
2348 #else /* ifndef FEATURE_FORCE_LOAD */
2349 # define IS_NOT_FORCED_AND
2350 #endif /* def FEATURE_FORCE_LOAD */
2352 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
2355 /* a CGI call was detected and answered */
2356 (NULL != (rsp = dispatch_cgi(csp)))
2358 /* or we are enabled and... */
2359 || (IS_ENABLED_AND (
2361 /* ..the request was blocked */
2362 ( NULL != (rsp = block_url(csp)))
2364 /* ..or untrusted */
2365 #ifdef FEATURE_TRUST
2366 || ( NULL != (rsp = trust_url(csp)))
2367 #endif /* def FEATURE_TRUST */
2369 /* ..or a fast redirect kicked in */
2370 #ifdef FEATURE_FAST_REDIRECTS
2371 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
2372 (NULL != (rsp = redirect_url(csp))))
2373 #endif /* def FEATURE_FAST_REDIRECTS */
2377 /* Write the answer to the client */
2378 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2379 || write_socket(csp->cfd, rsp->body, rsp->content_length))
2381 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2384 #ifdef FEATURE_STATISTICS
2385 /* Count as a rejected request */
2386 csp->flags |= CSP_FLAG_REJECTED;
2387 #endif /* def FEATURE_STATISTICS */
2389 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
2390 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
2391 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
2393 /* Clean up and return */
2394 free_http_response(rsp);
2395 return JB_ERR_INTERCEPT;
2398 /* When we get here the request doesn't need to be intercepted */
2402 /*********************************************************************
2404 * Function : open_forwarding_connection
2406 * Description : Check whether to intercept page
2409 * 1 : client_state structure
2410 * 2 : http_request structure
2412 * Returns : JB_ERR_OK - Connection opened ok
2413 * : all other values - an error occurred.
2414 *********************************************************************/
2415 static jb_err open_forwarding_connection(struct client_state *csp )
2417 struct http_response *rsp;
2419 #ifdef FEATURE_ACTIVITY_CONSOLE
2420 accumulate_stats(STATS_REQUEST, 1);
2421 #endif /* def FEATURE_ACTIVITY_CONSOLE */
2422 log_error(LOG_LEVEL_GPC, "%s%s", csp->http->hostport, csp->http->path);
2424 if (csp->http->fwd->forward_host)
2426 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
2427 csp->http->fwd->forward_host, csp->http->fwd->forward_port,
2428 csp->http->hostport);
2432 log_error(LOG_LEVEL_CONNECT, "to %s", csp->http->hostport);
2435 /* here we connect to the server, gateway, or the forwarder */
2437 csp->sfd = forwarded_connect(csp->http->fwd, csp->http, csp);
2439 if (csp->sfd == JB_INVALID_SOCKET)
2441 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
2442 csp->http->hostport);
2444 if (errno == EINVAL)
2446 rsp = error_response(csp, "no-such-domain", errno);
2448 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
2449 csp->ip_addr_str, csp->http->ocmd);
2453 rsp = error_response(csp, "connect-failed", errno);
2455 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
2456 csp->ip_addr_str, csp->http->ocmd);
2460 /* Write the answer to the client */
2463 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2464 || write_socket(csp->cfd, rsp->body, rsp->content_length))
2466 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
2470 free_http_response(rsp);
2471 return JB_ERR_GENERIC;
2474 log_error(LOG_LEVEL_CONNECT, "OK");
2477 } /* END open_forwarding_connection() */
2480 /*********************************************************************
2482 * Function : send_client_headers_to_server
2484 * Description : send the client headers (possibly modified) to the server
2487 * 1 : client_state structure
2488 * 2 : http_request structure
2491 * Returns : JB_ERR_OK - headers sent ok
2492 * : other values - an error occurred.
2493 *********************************************************************/
2495 static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http, char *hdr )
2498 struct http_response *rsp;
2500 if (http->fwd->forward_host || (http->ssl == 0))
2502 /* write the client's (modified) header to the server
2503 * (along with anything else that may be in the buffer)
2506 if (write_socket(csp->sfd, hdr, strlen(hdr))
2507 || (flush_socket(csp->sfd, csp) < 0))
2509 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
2512 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
2513 csp->ip_addr_str, http->ocmd);
2515 rsp = error_response(csp, "connect-failed", errno);
2519 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2520 || write_socket(csp->cfd, rsp->body, rsp->content_length))
2522 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2526 free_http_response(rsp);
2527 return JB_ERR_GENERIC;
2533 * We're running an SSL tunnel and we're not forwarding,
2534 * so just send the "connect succeeded" message to the
2535 * client, flush the rest, and get out of the way.
2537 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
2538 csp->ip_addr_str, http->ocmd);
2540 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
2548 } /* END send_client_headers_to_server */
2551 /*********************************************************************
2553 * Function : is_connect_request_allowed
2555 * Description : send the client headers (possibly modified) to the server
2558 * 1 : client_state structure
2562 * Returns : JB_ERR_OK - connect request allowed
2563 * : other values - connect request not allowed
2564 *********************************************************************/
2565 static jb_err is_connect_request_allowed( struct client_state *csp )
2568 * Check if a CONNECT request is allowable:
2569 * In the absence of a +limit-connect action, allow only port 443.
2570 * If there is an action, allow whatever matches the specificaton.
2575 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
2576 || (csp->action->flags & ACTION_LIMIT_CONNECT
2577 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
2579 char buf[BUFFER_SIZE];
2580 strcpy(buf, CFORBIDDEN);
2581 write_socket(csp->cfd, buf, strlen(buf));
2583 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
2584 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
2586 return JB_ERR_GENERIC;
2591 } /* END is_connect_request_allowed */