1 const char jcc_rcs[] = "$Id: jcc.c,v 2.5 2003/01/26 20:24:26 david__schmidt 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.5 2003/01/26 20:24:26 david__schmidt
37 * Updated activity console instrumentation locations
39 * Revision 2.4 2002/12/28 03:58:19 david__schmidt
40 * Initial drop of dashboard instrumentation - enabled with
41 * --enable-activity-console
43 * Revision 2.3 2002/07/18 22:06:12 jongfoster
44 * Trivial formatting changes
46 * Revision 2.2 2002/07/12 04:26:17 agotneja
47 * Re-factored 'chat()' to become understandable and maintainable as
48 * a first step in adding Transparent Proxy functionality.
50 * Added several new static functions in jcc.c, and moved some data
51 * parameters up into project.h to allow them to be passed between
54 * Revision 1.91 2002/04/08 20:35:58 swa
57 * Revision 1.90 2002/04/02 14:57:28 oes
58 * Made sending wafers independent of FEATURE_COOKIE_JAR
60 * Revision 1.89 2002/03/31 17:18:59 jongfoster
61 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
63 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
64 * More compiler warning message maintenance
66 * Revision 1.87 2002/03/26 22:29:54 swa
67 * we have a new homepage!
69 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
70 * Workaround for closing the jarfile before load_config() comes around again
72 * Revision 1.85 2002/03/24 15:23:33 jongfoster
75 * Revision 1.84 2002/03/24 13:25:43 swa
76 * name change related issues
78 * Revision 1.83 2002/03/16 23:54:06 jongfoster
79 * Adding graceful termination feature, to help look for memory leaks.
80 * If you enable this (which, by design, has to be done by hand
81 * editing config.h) and then go to http://i.j.b/die, then the program
82 * will exit cleanly after the *next* request. It should free all the
83 * memory that was used.
85 * Revision 1.82 2002/03/13 00:27:05 jongfoster
88 * Revision 1.81 2002/03/12 01:42:50 oes
89 * Introduced modular filters
91 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
92 * OS/2 port maintenance:
93 * - Fixed EMX build - it had decayed a little
94 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
95 * substituted a memset for now.
97 * Revision 1.79 2002/03/09 20:03:52 jongfoster
98 * - Making various functions return int rather than size_t.
99 * (Undoing a recent change). Since size_t is unsigned on
100 * Windows, functions like read_socket that return -1 on
101 * error cannot return a size_t.
103 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
104 * crashes, and also frequently caused JB to jump to 100%
105 * CPU and stay there. (Because it thought it had just
106 * read ((unsigned)-1) == 4Gb of data...)
108 * - The signature of write_socket has changed, it now simply
109 * returns success=0/failure=nonzero.
111 * - Trying to get rid of a few warnings --with-debug on
112 * Windows, I've introduced a new type "jb_socket". This is
113 * used for the socket file descriptors. On Windows, this
114 * is SOCKET (a typedef for unsigned). Everywhere else, it's
115 * an int. The error value can't be -1 any more, so it's
116 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
117 * Windows it maps to the #define INVALID_SOCKET.)
119 * - The signature of bind_port has changed.
121 * Revision 1.78 2002/03/08 21:35:04 oes
122 * Added optional group supplement to --user option. Will now use default group of user if no group given
124 * Revision 1.77 2002/03/07 03:52:06 oes
125 * - Fixed compiler warnings etc
126 * - Improved handling of failed DNS lookups
128 * Revision 1.76 2002/03/06 22:54:35 jongfoster
129 * Automated function-comment nitpicking.
131 * Revision 1.75 2002/03/06 10:02:19 oes
132 * Fixed stupid bug when --user was not given
134 * Revision 1.74 2002/03/06 00:49:31 jongfoster
135 * Fixing warning on Windows
136 * Making #ifdefs that refer to the same variable consistently
137 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
139 * Revision 1.73 2002/03/05 23:57:30 hal9
140 * Stray character 's' on line 1618 was breaking build.
142 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
143 * - Re-enable OS/2 building after new parms were added
144 * - Fix false out of memory report when resolving CGI templates when no IP
145 * address is available of failed attempt (a la no such domain)
147 * Revision 1.71 2002/03/05 18:13:56 oes
148 * Added --user option
150 * Revision 1.70 2002/03/05 04:52:42 oes
151 * Deleted non-errlog debugging code
153 * Revision 1.69 2002/03/04 23:50:00 jongfoster
154 * Splitting off bind_port() call into bind_port_helper(), with
157 * Revision 1.68 2002/03/04 20:17:32 oes
160 * Revision 1.67 2002/03/04 18:18:57 oes
161 * - Removed _DEBUG mode
162 * - Cleand up cmdline parsing
163 * - Introduced --no-daemon, --pidfile options
164 * - Cleaned up signal handling:
165 * - Terminate cleanly on INT, TERM and ABRT
166 * - Schedule logfile for re-opening on HUP
167 * - Ignore CHLD and PIPE
168 * - Leave the rest with their default handlers
169 * - Uniform handler registration
170 * - Added usage() function
171 * - Played styleguide police
173 * Revision 1.66 2002/03/03 15:06:55 oes
174 * Re-enabled automatic config reloading
176 * Revision 1.65 2002/03/03 14:49:11 oes
177 * Fixed CLF logging: Now uses client's original HTTP request
179 * Revision 1.64 2002/03/03 09:18:03 joergs
180 * Made jumbjuster work on AmigaOS again.
182 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
183 * Clean up a little CRLF unpleasantness that suddenly appeared
185 * Revision 1.62 2002/02/20 23:17:23 jongfoster
186 * Detecting some out-of memory conditions and exiting with a log message.
188 * Revision 1.61 2002/01/17 21:01:52 jongfoster
189 * Moving all our URL and URL pattern parsing code to urlmatch.c.
191 * Revision 1.60 2001/12/30 14:07:32 steudten
192 * - Add signal handling (unix)
193 * - Add SIGHUP handler (unix)
194 * - Add creation of pidfile (unix)
195 * - Add action 'top' in rc file (RH)
196 * - Add entry 'SIGNALS' to manpage
197 * - Add exit message to logfile (unix)
199 * Revision 1.59 2001/12/13 14:07:18 oes
200 * Fixed Bug: 503 error page now sent OK
202 * Revision 1.58 2001/11/30 23:37:24 jongfoster
203 * Renaming the Win32 config file to config.txt - this is almost the
204 * same as the corresponding UNIX name "config"
206 * Revision 1.57 2001/11/16 00:47:43 jongfoster
207 * Changing the tty-disconnection code to use setsid().
209 * Revision 1.56 2001/11/13 20:20:54 jongfoster
210 * Tabs->spaces, fixing a bug with missing {} around an if()
212 * Revision 1.55 2001/11/13 20:14:53 jongfoster
213 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
215 * Revision 1.54 2001/11/07 00:03:14 steudten
216 * Give reliable return value if an error
217 * occurs not just 0 with new daemon mode.
219 * Revision 1.53 2001/11/05 21:41:43 steudten
220 * Add changes to be a real daemon just for unix os.
221 * (change cwd to /, detach from controlling tty, set
222 * process group and session leader to the own process.
224 * Add some fatal-error log message for failed malloc().
225 * Add '-d' if compiled with 'configure --with-debug' to
226 * enable debug output.
228 * Revision 1.52 2001/10/26 20:11:20 jongfoster
229 * Fixing type mismatch
231 * Revision 1.51 2001/10/26 17:38:28 oes
234 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
235 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
236 * threads to call select() simultaneously. So, it's time to do a real, live,
237 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
238 * (native). Both versions will work, but using __OS2__ offers multi-threading.
240 * Revision 1.49 2001/10/23 21:41:35 jongfoster
241 * Added call to initialize the (statically-allocated of course)
242 * "out of memory" CGI response.
244 * Revision 1.48 2001/10/10 19:56:46 jongfoster
245 * Moving some code that wasn't cookie-related out of an #ifdef
248 * Revision 1.47 2001/10/10 16:44:36 oes
249 * Added CONNECT destination port limitation check
251 * Revision 1.46 2001/10/08 15:17:41 oes
252 * Re-enabled SSL forwarding
254 * Revision 1.45 2001/10/07 15:42:11 oes
255 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
257 * Moved downgrading of the HTTP version from parse_http_request to
258 * chat(), since we can't decide if it is necessary before we have
259 * determined the actions for the URL. The HTTP command is now
260 * *always* re-built so the repairs need no longer be special-cased.
262 * filter_popups now gets a csp pointer so it can raise the new
263 * CSP_FLAG_MODIFIED flag.
267 * Added configurable size limit for the IOB. If the IOB grows so
268 * large that the next read would exceed the limit, the header
269 * is generated, and the header & unfiltered buffer are flushed
270 * to the client. Chat then continues in non-buffering,
271 * non-filtering body mode.
273 * Revision 1.44 2001/10/02 18:13:57 oes
276 * Revision 1.43 2001/10/02 15:32:13 oes
277 * Moved generation of hdr
279 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
280 * Cleaning up 2 compiler warnings on OS/2.
282 * Revision 1.41 2001/09/16 17:05:14 jongfoster
283 * Removing unused #include showarg.h
285 * Revision 1.40 2001/09/16 15:41:45 jongfoster
286 * Fixing signed/unsigned comparison warning.
288 * Revision 1.39 2001/09/16 13:21:27 jongfoster
289 * Changes to use new list functions.
291 * Revision 1.38 2001/09/16 13:01:46 jongfoster
292 * Removing redundant function call that zeroed zalloc()'d memory.
294 * Revision 1.37 2001/09/10 11:12:24 oes
295 * Deleted unused variable
297 * Revision 1.36 2001/09/10 10:56:15 oes
298 * Silenced compiler warnings
300 * Revision 1.35 2001/07/31 14:44:22 oes
301 * Deleted unused size parameter from filter_popups()
303 * Revision 1.34 2001/07/30 22:08:36 jongfoster
304 * Tidying up #defines:
305 * - All feature #defines are now of the form FEATURE_xxx
306 * - Permanently turned off WIN_GUI_EDIT
307 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
309 * Revision 1.33 2001/07/29 19:32:00 jongfoster
310 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
312 * Revision 1.32 2001/07/29 18:47:05 jongfoster
313 * Adding missing #include "loadcfg.h"
315 * Revision 1.31 2001/07/29 12:17:48 oes
316 * Applied pthread fix by Paul Lieverse
318 * Revision 1.30 2001/07/25 22:57:13 jongfoster
319 * __BEOS__ no longer overrides FEATURE_PTHREAD.
320 * This is because FEATURE_PTHREAD will soon be widely used, so I
321 * want to keep it simple.
323 * Revision 1.29 2001/07/24 12:47:06 oes
324 * Applied BeOS support update by Eugenia
326 * Revision 1.28 2001/07/23 13:26:12 oes
327 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
329 * Revision 1.27 2001/07/19 19:09:47 haroon
330 * - Added code to take care of the situation where while processing the first
331 * server response (which includes the server header), after finding the end
332 * of the headers we were not looking past the end of the headers for
333 * content modification. I enabled it for filter_popups.
334 * Someone else should look to see if other similar operations should be
335 * done to the discarded portion of the buffer.
337 * Note 2001/07/20: No, the other content modification mechanisms will process
338 * the whole iob later anyway. --oes
340 * Revision 1.26 2001/07/18 12:31:36 oes
343 * Revision 1.25 2001/07/15 19:43:49 jongfoster
344 * Supports POSIX threads.
345 * Also removed some unused #includes.
347 * Revision 1.24 2001/07/13 14:00:40 oes
348 * - Generic content modification scheme:
349 * Each feature has its own applicability flag that is set
350 * from csp->action->flags.
351 * Replaced the "filtering" int flag , by a function pointer
352 * "content_filter" to the function that will do the content
353 * modification. If it is != NULL, the document will be buffered
354 * and processed through *content_filter, which must set
355 * csp->content_length and return a modified copy of the body
356 * or return NULL (on failiure).
357 * - Changed csp->is_text to the more generic bitmap csp->content_type
358 * which can currently take the valued CT_TEXT or CT_GIF
360 * - Removed all #ifdef PCRS
362 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
363 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
364 * the `block_acl' call. This prevents a compilation error when the user
365 * does not wish to use the "ACL" feature.
367 * Revision 1.22 2001/06/29 21:45:41 oes
368 * Indentation, CRLF->LF, Tab-> Space
370 * Revision 1.21 2001/06/29 13:29:36 oes
371 * - Cleaned up, improved comments
372 * - Unified all possible interceptors (CGI,
373 * block, trust, fast_redirect) in one
374 * place, with one (CGI) answer generation
375 * mechansim. Much clearer now.
376 * - Removed the GIF image generation, which
377 * is now done in filters.c:block_url()
378 * - Made error conditions like domain lookup
379 * failiure or (various) problems while talking
380 * to the server use cgi.c:error_response()
381 * instead of generating HTML/HTTP in chat() (yuck!)
382 * - Removed logentry from cancelled commit
384 * Revision 1.20 2001/06/09 10:55:28 jongfoster
385 * Changing BUFSIZ ==> BUFFER_SIZE
387 * Revision 1.19 2001/06/07 23:12:52 jongfoster
388 * Replacing function pointer in struct gateway with a directly
389 * called function forwarded_connect().
390 * Replacing struct gateway with struct forward_spec
392 * Revision 1.18 2001/06/03 19:12:16 oes
393 * introduced new cgi handling
395 * Revision 1.17 2001/06/01 20:07:23 jongfoster
396 * Now uses action +image-blocker{} rather than config->tinygif
398 * Revision 1.16 2001/06/01 18:49:17 jongfoster
399 * Replaced "list_share" with "list" - the tiny memory gain was not
400 * worth the extra complexity.
402 * Revision 1.15 2001/05/31 21:24:47 jongfoster
403 * Changed "permission" to "action" throughout.
404 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
405 * Moved vanilla wafer check into chat(), since we must now
406 * decide whether or not to add it based on the URL.
408 * Revision 1.14 2001/05/29 20:14:01 joergs
409 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
412 * Revision 1.13 2001/05/29 09:50:24 jongfoster
413 * Unified blocklist/imagelist/permissionslist.
414 * File format is still under discussion, but the internal changes
417 * Also modified interceptor behaviour:
418 * - We now intercept all URLs beginning with one of the following
419 * prefixes (and *only* these prefixes):
421 * * http://ijbswa.sf.net/config/
422 * * http://ijbswa.sourceforge.net/config/
423 * - New interceptors "home page" - go to http://i.j.b/ to see it.
424 * - Internal changes so that intercepted and fast redirect pages
425 * are not replaced with an image.
426 * - Interceptors now have the option to send a binary page direct
427 * to the client. (i.e. ijb-send-banner uses this)
428 * - Implemented show-url-info interceptor. (Which is why I needed
429 * the above interceptors changes - a typical URL is
430 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
431 * The previous mechanism would not have intercepted that, and
432 * if it had been intercepted then it then it would have replaced
435 * Revision 1.12 2001/05/27 22:17:04 oes
437 * - re_process_buffer no longer writes the modified buffer
438 * to the client, which was very ugly. It now returns the
439 * buffer, which it is then written by chat.
441 * - content_length now adjusts the Content-Length: header
442 * for modified documents rather than crunch()ing it.
443 * (Length info in csp->content_length, which is 0 for
444 * unmodified documents)
446 * - For this to work, sed() is called twice when filtering.
448 * Revision 1.11 2001/05/26 17:27:53 jongfoster
449 * Added support for CLF and fixed LOG_LEVEL_LOG.
450 * Also did CRLF->LF fix of my previous patch.
452 * Revision 1.10 2001/05/26 15:26:15 jongfoster
453 * ACL feature now provides more security by immediately dropping
454 * connections from untrusted hosts.
456 * Revision 1.9 2001/05/26 00:28:36 jongfoster
457 * Automatic reloading of config file.
458 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
459 * Most of the global variables have been moved to a new
460 * struct configuration_spec, accessed through csp->config->globalname
461 * Most of the globals remaining are used by the Win32 GUI.
463 * Revision 1.8 2001/05/25 22:43:18 jongfoster
464 * Fixing minor memory leak and buffer overflow.
466 * Revision 1.7 2001/05/25 22:34:30 jongfoster
469 * Revision 1.6 2001/05/23 00:13:58 joergs
470 * AmigaOS support fixed.
472 * Revision 1.5 2001/05/22 18:46:04 oes
474 * - Enabled filtering banners by size rather than URL
475 * by adding patterns that replace all standard banner
476 * sizes with the "Junkbuster" gif to the re_filterfile
478 * - Enabled filtering WebBugs by providing a pattern
479 * which kills all 1x1 images
481 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
482 * which is selected by the (nonstandard and therefore
483 * capital) letter 'U' in the option string.
484 * It causes the quantifiers to be ungreedy by default.
485 * Appending a ? turns back to greedy (!).
487 * - Added a new interceptor ijb-send-banner, which
488 * sends back the "Junkbuster" gif. Without imagelist or
489 * MSIE detection support, or if tinygif = 1, or the
490 * URL isn't recognized as an imageurl, a lame HTML
491 * explanation is sent instead.
493 * - Added new feature, which permits blocking remote
494 * script redirects and firing back a local redirect
496 * The feature is conditionally compiled, i.e. it
497 * can be disabled with --disable-fast-redirects,
498 * plus it must be activated by a "fast-redirects"
499 * line in the config file, has its own log level
500 * and of course wants to be displayed by show-proxy-args
501 * Note: Boy, all the #ifdefs in 1001 locations and
502 * all the fumbling with configure.in and acconfig.h
503 * were *way* more work than the feature itself :-(
505 * - Because a generic redirect template was needed for
506 * this, tinygif = 3 now uses the same.
508 * - Moved GIFs, and other static HTTP response templates
513 * - Removed some >400 CRs again (Jon, you really worked
516 * Revision 1.4 2001/05/21 19:34:01 jongfoster
517 * Made failure to bind() a fatal error.
519 * Revision 1.3 2001/05/20 01:21:20 jongfoster
520 * Version 2.9.4 checkin.
521 * - Merged popupfile and cookiefile, and added control over PCRS
522 * filtering, in new "permissionsfile".
523 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
524 * file error you now get a message box (in the Win32 GUI) rather
525 * than the program exiting with no explanation.
526 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
528 * - Removed tabs from "config"
529 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
530 * - Bumped up version number.
532 * Revision 1.2 2001/05/17 22:34:44 oes
533 * - Added hint on GIF char array generation to jcc.c
534 * - Cleaned CRLF's from the sources and related files
535 * - Repaired logging for REF and FRC
537 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
538 * Initial import of version 2.9.3 source tree
541 *********************************************************************/
547 #include <sys/types.h>
554 #ifdef FEATURE_PTHREAD
556 #endif /* def FEATURE_PTHREAD */
559 # ifndef FEATURE_PTHREAD
563 # include <windows.h>
564 # include <process.h>
565 # endif /* ndef FEATURE_PTHREAD */
568 # ifndef _WIN_CONSOLE
570 # endif /* ndef _WIN_CONSOLE */
572 #else /* ifndef _WIN32 */
574 # if !defined (__OS2__)
576 # include <sys/wait.h>
577 # endif /* ndef __OS2__ */
578 # include <sys/time.h>
579 # include <sys/stat.h>
580 # include <sys/ioctl.h>
583 #include <sys/termios.h>
594 # include <socket.h> /* BeOS has select() for sockets only. */
595 # include <OS.h> /* declarations for threads and stuff. */
598 # if defined(__EMX__) || defined(__OS2__)
599 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
604 #define bzero(B,N) memset(B,0x00,n)
619 #include "killpopup.h"
620 #include "miscutil.h"
622 #include "jbsockets.h"
627 #include "urlmatch.h"
628 #ifdef FEATURE_ACTIVITY_CONSOLE
630 #endif /* def FEATURE_ACTIVITY_CONSOLE */
632 const char jcc_h_rcs[] = JCC_H_VERSION;
633 const char project_h_rcs[] = PROJECT_H_VERSION;
636 struct client_state clients[1];
637 struct file_list files[1];
639 #ifdef FEATURE_STATISTICS
640 int urls_read = 0; /* total nr of urls read inc rejected */
641 int urls_rejected = 0; /* total nr of urls rejected */
642 #endif /* def FEATURE_STATISTICS */
644 #ifdef FEATURE_GRACEFUL_TERMINATION
648 static void listen_loop(void);
649 static void chat(struct client_state *csp);
650 static jb_err relay_server_traffic( struct client_state *csp ) ;
651 static jb_err read_client_headers( struct client_state *csp, struct http_request *http ) ;
652 static jb_err process_client_headers( struct client_state *csp, struct http_request *http ) ;
653 static jb_err intercept_page( struct client_state *csp, struct http_request *http );
654 static jb_err open_forwarding_connection( struct client_state *csp );
655 static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http, char* hdr );
656 static jb_err is_connect_request_allowed( struct client_state *csp ) ;
660 void serve(struct client_state *csp);
661 #else /* ifndef AMIGA */
662 static void serve(struct client_state *csp);
663 #endif /* def AMIGA */
666 static int32 server_thread(void *data);
667 #endif /* def __BEOS__ */
670 #define sleep(N) Sleep(((N) * 1000))
674 #define sleep(N) DosSleep(((N) * 100))
677 #if defined(unix) || defined(__EMX__)
679 const char *pidfile = NULL;
680 int received_hup_signal = 0;
681 #endif /* defined unix */
683 /* The vanilla wafer. */
684 static const char VANILLA_WAFER[] =
685 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
686 "Do_not_send_me_any_copyrighted_information_other_than_the_"
687 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
688 "In_particular_do_not_send_me_any_cookies_that_"
689 "are_subject_to_a_claim_of_copyright_by_anybody._"
690 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
691 "(copyright_or_otherwise)_applying_to_any_cookie._";
694 * HTTP header sent when doing HTTPS tunnelling ("CONNECT" method).
696 static const char CSUCCEED[] =
697 "HTTP/1.0 200 Connection established\n"
698 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
702 * HTTP reply sent when the browser sends something unintelligible.
704 static const char CHEADER[] =
705 "HTTP/1.0 400 Invalid header received from browser\r\n\r\n";
709 * HTTP reply sent when the browser tries to tunnel ("CONNECT") to something
710 * other than a HTTPS port (as defined by +limit-connect).
712 static const char CFORBIDDEN[] =
713 "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";
715 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
716 /*********************************************************************
718 * Function : sig_handler
720 * Description : Signal handler for different signals.
721 * Exit gracefully on ABRT, TERM and INT
722 * or set a flag that will cause the errlog
723 * to be reopened by the main thread on HUP.
726 * 1 : the_signal = the signal cause this function to call
730 *********************************************************************/
731 static void sig_handler(int the_signal)
738 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
746 received_hup_signal = 1;
751 * We shouldn't be here, unless we catch signals
752 * in main() that we can't handle here!
754 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
762 /*********************************************************************
766 * Description : Once a connection to the client has been accepted,
767 * this function is called (via serve()) to handle the
768 * main business of the communication. When this
769 * function returns, the caller must close the client
773 * 1 : csp = Current client state (buffers, headers, etc...)
777 *********************************************************************/
778 static void chat(struct client_state *csp)
782 char buf[BUFFER_SIZE];
783 int len; /* for buffer sizes */
789 struct http_request *http;
793 if (read_client_headers(csp, http ) != JB_ERR_OK )
797 /* Process the client headers */
798 if (process_client_headers(csp, http) != JB_ERR_OK)
802 /* Check if this connection request is permitted */
803 if (is_connect_request_allowed(csp) != JB_ERR_OK)
807 * We have a valid and legit request. Now, check to see if we need to
810 if (intercept_page(csp, http) != JB_ERR_OK)
814 * The page passed the intercept routine, so open a forwarding
815 * connection for conversation
817 if (open_forwarding_connection(csp) != JB_ERR_OK )
822 hdr = sed(client_patterns, add_client_headers, csp);
825 /* FIXME Should handle error properly */
826 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
829 /* FIXME - where should this go, logically ? */
830 list_remove_all(csp->headers);
833 if (send_client_headers_to_server(csp, http, hdr) != JB_ERR_OK)
837 /* we're finished with the client's header */
840 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
842 /* pass data between the client and server
843 * until one or the other shuts down the connection.
846 /* Set the flag for reading headers to False */
847 /* This is used in relay_server_traffic */
848 csp->all_headers_read = 0 ;
852 jb_err tmp_ret_val = JB_ERR_GENERIC ;
856 * FD_ZERO here seems to point to an errant macro which crashes.
857 * So do this by hand for now...
859 memset(&rfds,0x00,sizeof(fd_set));
863 FD_SET(csp->cfd, &rfds);
864 FD_SET(csp->sfd, &rfds);
866 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
870 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
875 * This is the body of the browser's request.
876 * Just read it and write it.
879 if (FD_ISSET(csp->cfd, &rfds))
881 len = read_socket(csp->cfd, buf, sizeof(buf));
885 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
886 csp->ip_addr_str, http->ocmd, byte_count);
890 if (write_socket(csp->sfd, buf, (size_t)len))
892 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
899 * Check if the server wants to talk, and if so, converse.
902 if (FD_ISSET(csp->sfd, &rfds))
903 tmp_ret_val = relay_server_traffic(csp) ;
906 if (tmp_ret_val == JB_ERR_OK)
911 /* We should never get here! */
912 log_error(LOG_LEVEL_FATAL, "chat() : logic error in for() loop" ) ;
916 /*********************************************************************
920 * Description : This is little more than chat. We only "serve" to
921 * to close any socket that chat may have opened.
924 * 1 : csp = Current client state (buffers, headers, etc...)
928 *********************************************************************/
930 void serve(struct client_state *csp)
931 #else /* ifndef AMIGA */
932 static void serve(struct client_state *csp)
933 #endif /* def AMIGA */
936 close_socket(csp->cfd);
938 if (csp->sfd != JB_INVALID_SOCKET)
940 close_socket(csp->sfd);
943 csp->flags &= ~CSP_FLAG_ACTIVE;
949 /*********************************************************************
951 * Function : server_thread
953 * Description : We only exist to call `serve' in a threaded environment.
956 * 1 : data = Current client state (buffers, headers, etc...)
958 * Returns : Always 0.
960 *********************************************************************/
961 static int32 server_thread(void *data)
963 serve((struct client_state *) data);
970 /*********************************************************************
974 * Description : Print usage info & exit.
976 * Parameters : Pointer to argv[0] for identifying ourselves
980 *********************************************************************/
981 void usage(const char *myname)
983 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
984 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
985 "Aborting.\n", myname);
992 /*********************************************************************
996 * Description : Load the config file and start the listen loop.
997 * This function is a lot more *sane* with the `load_config'
998 * and `listen_loop' functions; although it stills does
999 * a *little* too much for my taste.
1002 * 1 : argc = Number of parameters (including $0).
1003 * 2 : argv = Array of (char *)'s to the parameters.
1005 * Returns : 1 if : can't open config file, unrecognized directive,
1006 * stats requested in multi-thread mode, can't open the
1007 * log file, can't open the jar file, listen port is invalid,
1008 * any load fails, and can't bind port.
1010 * Else main never returns, the process must be signaled
1011 * to terminate execution. Or, on Windows, use the
1012 * "File", "Exit" menu option.
1014 *********************************************************************/
1016 int real_main(int argc, const char *argv[])
1018 int main(int argc, const char *argv[])
1023 struct passwd *pw = NULL;
1024 struct group *grp = NULL;
1032 #if !defined(_WIN32)
1040 * Parse the command line arguments
1042 while (++argc_pos < argc)
1044 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1046 if (strcmp(argv[argc_pos], "--help") == 0)
1051 else if(strcmp(argv[argc_pos], "--version") == 0)
1053 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1057 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1062 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1064 if (++argc_pos == argc) usage(argv[0]);
1065 pidfile = strdup(argv[argc_pos]);
1068 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1070 if (++argc_pos == argc) usage(argv[argc_pos]);
1072 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1075 if (NULL == (grp = getgrnam(p)))
1077 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1081 if (NULL == (pw = getpwnam(argv[argc_pos])))
1083 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1086 if (p != NULL) *--p = '\0';
1088 #endif /* defined(unix) */
1090 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1092 configfile = argv[argc_pos];
1095 } /* -END- while (more arguments) */
1098 if ( *configfile != '/' )
1102 /* make config-filename absolute here */
1103 if ( !(basedir = getcwd( NULL, 1024 )))
1105 perror("get working dir failed");
1109 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1111 perror("malloc failed");
1114 strcpy( abs_file, basedir );
1115 strcat( abs_file, "/" );
1116 strcat( abs_file, configfile );
1117 configfile = abs_file;
1119 #endif /* defined unix */
1126 #elif defined(_WIN32)
1131 * Unix signal handling
1133 * Catch the abort, interrupt and terminate signals for a graceful exit
1134 * Catch the hangup signal so the errlog can be reopened.
1135 * Ignore the broken pipe and child signals
1136 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1138 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1141 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1142 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1144 for (idx = 0; catched_signals[idx] != 0; idx++)
1146 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1148 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1152 for (idx = 0; ignored_signals[idx] != 0; idx++)
1154 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1156 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1161 #else /* ifdef _WIN32 */
1162 # ifdef _WIN_CONSOLE
1164 * We *are* in a windows console app.
1165 * Print a verbose messages about FAQ's and such
1167 printf(win32_blurb);
1168 # endif /* def _WIN_CONSOLE */
1169 #endif /* def _WIN32 */
1172 /* Initialize the CGI subsystem */
1173 cgi_init_error_messages();
1176 * If runnig on unix and without the --nodaemon
1177 * option, become a daemon. I.e. fork, detach
1178 * from tty and get process group leadership
1191 if ( pid < 0 ) /* error */
1196 else if ( pid != 0 ) /* parent */
1201 * must check for errors
1202 * child died due to missing files aso
1205 wpid = waitpid( pid, &status, WNOHANG );
1214 /* Should be more portable, but not as well tested */
1219 #else /* ndef __FreeBSD__ */
1221 #endif /* ndef __FreeBSD__ */
1222 fd = open("/dev/tty", O_RDONLY);
1225 /* no error check here */
1226 ioctl( fd, TIOCNOTTY,0 );
1230 /* FIXME: should close stderr (fd 2) here too, but the test
1232 * and load config file is done in listen_loop() and puts
1233 * some messages on stderr there.
1240 } /* -END- if (!no_daemon) */
1243 * As soon as we have written the PID file, we can switch
1244 * to the user and group ID indicated by the --user option
1250 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1252 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1254 if (setuid(pw->pw_uid))
1256 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1260 #endif /* defined unix */
1270 /*********************************************************************
1272 * Function : bind_port_helper
1274 * Description : Bind the listen port. Handles logging, and aborts
1278 * 1 : config = Privoxy configuration. Specifies port
1281 * Returns : Port that was opened.
1283 *********************************************************************/
1284 static jb_socket bind_port_helper(struct configuration_spec * config)
1289 if ( (config->haddr != NULL)
1290 && (config->haddr[0] == '1')
1291 && (config->haddr[1] == '2')
1292 && (config->haddr[2] == '7')
1293 && (config->haddr[3] == '.') )
1295 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1298 else if (config->haddr == NULL)
1300 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1305 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1306 config->hport, config->haddr);
1309 result = bind_port(config->haddr, config->hport, &bfd);
1316 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1317 "There may be another Privoxy or some other "
1318 "proxy running on port %d",
1319 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1320 config->hport, config->hport);
1323 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1324 "The hostname is not resolvable",
1325 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1328 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
1329 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1332 /* shouldn't get here */
1333 return JB_INVALID_SOCKET;
1336 config->need_bind = 0;
1342 /*********************************************************************
1344 * Function : listen_loop
1346 * Description : bind the listen port and enter a "FOREVER" listening loop.
1352 *********************************************************************/
1353 static void listen_loop(void)
1355 struct client_state *csp = NULL;
1357 struct configuration_spec * config;
1359 config = load_config();
1361 bfd = bind_port_helper(config);
1363 #ifdef FEATURE_ACTIVITY_CONSOLE
1364 init_stats_config(config);
1365 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1367 #ifdef FEATURE_GRACEFUL_TERMINATION
1368 while (!g_terminate)
1373 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1374 while (waitpid(-1, NULL, WNOHANG) > 0)
1376 /* zombie children */
1378 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1381 * Free data that was used by died threads
1387 * Re-open the errlog after HUP signal
1389 if (received_hup_signal)
1391 init_error_log(Argv[0], config->logfile, config->debug);
1392 received_hup_signal = 0;
1397 #ifdef FEATURE_COOKIE_JAR
1399 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
1400 * already open. I think unload_configfile() is not being run, which should do
1401 * this work. Until that can get resolved, we'll use this workaround.
1403 * [Note from Jon: We don't unload_configfile() until all existing threads have
1404 * exited - they're likely to hang aroung transferring data to the browser.]
1408 if (csp->config->jar)
1410 fclose(csp->config->jar);
1411 csp->config->jar = NULL;
1413 #endif /* FEATURE_COOKIE_JAR */
1414 #endif /* __OS2__ */
1416 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1418 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1422 csp->flags |= CSP_FLAG_ACTIVE;
1423 csp->sfd = JB_INVALID_SOCKET;
1425 csp->config = config = load_config();
1427 if ( config->need_bind )
1430 * Since we were listening to the "old port", we will not see
1431 * a "listen" param change until the next IJB request. So, at
1432 * least 1 more request must be made for us to find the new
1433 * setting. I am simply closing the old socket and binding the
1436 * Which-ever is correct, we will serve 1 more page via the
1437 * old settings. This should probably be a "show-proxy-args"
1438 * request. This should not be a so common of an operation
1439 * that this will hurt people's feelings.
1444 bfd = bind_port_helper(config);
1447 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1449 if (!accept_connection(csp, bfd))
1451 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1464 log_error(LOG_LEVEL_CONNECT, "OK");
1467 #ifdef FEATURE_TOGGLE
1470 csp->flags |= CSP_FLAG_TOGGLED_ON;
1472 #endif /* def FEATURE_TOGGLE */
1474 #ifdef FEATURE_ACTIVITY_CONSOLE
1475 update_stats_config(config);
1476 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1478 if (run_loader(csp))
1480 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1481 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1485 if (block_acl(NULL,csp))
1487 #ifdef FEATURE_ACTIVITY_CONSOLE
1488 accumulate_stats(STATS_ACL_RESTRICT,1);
1489 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1490 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1491 close_socket(csp->cfd);
1495 #endif /* def FEATURE_ACL */
1497 /* add it to the list of clients */
1498 csp->next = clients->next;
1499 clients->next = csp;
1501 if (config->multi_threaded)
1505 /* this is a switch () statment in the C preprocessor - ugh */
1506 #undef SELECTED_ONE_OPTION
1508 /* Use Pthreads in preference to native code */
1509 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1510 #define SELECTED_ONE_OPTION
1512 pthread_t the_thread;
1513 pthread_attr_t attrs;
1515 pthread_attr_init(&attrs);
1516 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1517 child_id = (pthread_create(&the_thread, &attrs,
1518 (void*)serve, csp) ? -1 : 0);
1519 pthread_attr_destroy(&attrs);
1523 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1524 #define SELECTED_ONE_OPTION
1525 child_id = _beginthread(
1526 (void (*)(void *))serve,
1531 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1532 #define SELECTED_ONE_OPTION
1533 child_id = _beginthread(
1534 (void(* _Optlink)(void*))serve,
1540 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1541 #define SELECTED_ONE_OPTION
1543 thread_id tid = spawn_thread
1544 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1546 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1548 child_id = (int) tid;
1557 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1558 #define SELECTED_ONE_OPTION
1559 csp->cfd = ReleaseSocket(csp->cfd, -1);
1560 if((child_id = (int)CreateNewProcTags(
1561 NP_Entry, (ULONG)server_thread,
1562 NP_Output, Output(),
1563 NP_CloseOutput, FALSE,
1564 NP_Name, (ULONG)"privoxy child",
1565 NP_StackSize, 200*1024,
1569 ((struct Task *)child_id)->tc_UserData = csp;
1570 Signal((struct Task *)child_id, SIGF_SINGLE);
1575 #if !defined(SELECTED_ONE_OPTION)
1578 /* This block is only needed when using fork().
1579 * When using threads, the server thread was
1580 * created and run by the call to _beginthread().
1582 if (child_id == 0) /* child */
1588 else if (child_id > 0) /* parent */
1590 /* in a fork()'d environment, the parent's
1591 * copy of the client socket and the CSP
1595 #if !defined(_WIN32) && defined(__CYGWIN__)
1597 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1598 close_socket(csp->cfd);
1599 csp->flags &= ~CSP_FLAG_ACTIVE;
1603 #undef SELECTED_ONE_OPTION
1604 /* end of cpp switch () */
1606 if (child_id < 0) /* failed */
1608 char buf[BUFFER_SIZE];
1610 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1612 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
1614 write_socket(csp->cfd, buf, strlen(buf));
1615 close_socket(csp->cfd);
1616 csp->flags &= ~CSP_FLAG_ACTIVE;
1627 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
1629 /* Clean up. Aim: free all memory (no leaks) */
1630 #ifdef FEATURE_GRACEFUL_TERMINATION
1632 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
1634 unload_current_config_file();
1635 unload_current_actions_file();
1636 unload_current_re_filterfile();
1637 #ifdef FEATURE_TRUST
1638 unload_current_trust_file();
1641 if (config->multi_threaded)
1648 } while ((clients->next != NULL) && (--i > 0));
1652 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
1661 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
1662 /* Cleanup - remove taskbar icon etc. */
1667 #endif /* FEATURE_GRACEFUL_TERMINATION */
1671 /*********************************************************************
1673 * Function : relay_server_traffic
1675 * Description : receive traffic from the server and relay it
1676 * to the client, with some processing
1679 * 1 : client_state structure
1682 * Returns : JB_ERR_OK if there may be more work
1683 * : other values for errors
1685 **********************************************************************/
1687 static jb_err relay_server_traffic( struct client_state *csp )
1689 #ifdef FEATURE_KILL_POPUPS
1690 int block_popups; /* bool, 1==will block popups */
1691 int block_popups_now = 0; /* bool, 1==currently blocking popups */
1692 #endif /* def FEATURE_KILL_POPUPS */
1694 char buf[BUFFER_SIZE];
1695 int len; /* for buffer sizes */
1696 int ms_iis5_hack = 0;
1701 /* Skeleton for HTTP response, if we should intercept the request */
1702 struct http_response *rsp;
1704 int pcrs_filter; /* bool, 1==will filter through pcrs */
1705 int gif_deanimate; /* bool, 1==will deanimate gifs */
1707 #ifdef FEATURE_KILL_POPUPS
1708 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1709 #endif /* def FEATURE_KILL_POPUPS */
1711 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
1712 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1714 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1718 len = read_socket (csp->sfd, buf, sizeof (buf) - 1);
1722 log_error (LOG_LEVEL_ERROR, "read from: %s failed: %E", csp->http->host);
1724 log_error (LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1725 csp->ip_addr_str, csp->http->ocmd);
1727 rsp = error_response (csp, "connect-failed", errno);
1731 if (write_socket (csp->cfd, rsp->head, rsp->head_length)
1732 || write_socket (csp->cfd, rsp->body, rsp->content_length))
1734 log_error (LOG_LEVEL_ERROR, "write to: %s failed: %E",
1739 free_http_response (rsp);
1740 return JB_ERR_GENERIC;
1743 /* Add a trailing zero. This lets filter_popups
1744 * use string operations.
1748 #ifdef FEATURE_KILL_POPUPS
1749 /* Filter the popups on this read. */
1750 if (block_popups_now)
1752 filter_popups (buf, csp);
1754 #endif /* def FEATURE_KILL_POPUPS */
1757 /* Normally, this would indicate that we've read
1758 * as much as the server has sent us and we can
1759 * close the client connection. However, Microsoft
1760 * in its wisdom has released IIS/5 with a bug that
1761 * prevents it from sending the trailing \r\n in
1762 * a 302 redirect header (and possibly other headers).
1763 * To work around this if we've haven't parsed
1764 * a full header we'll append a trailing \r\n
1765 * and see if this now generates a valid one.
1767 * This hack shouldn't have any impacts. If we've
1768 * already transmitted the header or if this is a
1769 * SSL connection, then we won't bother with this
1770 * hack. So we only work on partially received
1771 * headers. If we append a \r\n and this still
1772 * doesn't generate a valid header, then we won't
1773 * transmit anything to the client.
1778 if (csp->all_headers_read || csp->http->ssl)
1781 * If we have been buffering up the document,
1782 * now is the time to apply content modification
1783 * and send the result to the client.
1785 if (csp->content_filter)
1788 * If the content filter fails, use the original
1789 * buffer and length.
1790 * (see p != NULL ? p : csp->iob->cur below)
1792 if (NULL == (p = (*csp->content_filter) (csp)))
1794 csp->content_length = csp->iob->eod - csp->iob->cur;
1797 hdr = sed (server_patterns, add_server_headers, csp);
1800 /* FIXME Should handle error properly */
1801 log_error (LOG_LEVEL_FATAL,
1802 "Out of memory parsing server header");
1806 if (write_socket (csp->cfd, hdr, strlen (hdr))
1807 || write_socket (csp->cfd, p != NULL ? p : csp->iob->cur,
1808 csp->content_length))
1810 log_error (LOG_LEVEL_ERROR,
1811 "write modified content to client failed: %E");
1812 return JB_ERR_GENERIC;
1821 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1822 csp->ip_addr_str, csp->http->ocmd, byte_count);
1823 return JB_ERR_GENERIC;
1827 * This is NOT the body, so
1828 * Let's pretend the server just sent us a blank line.
1830 len = sprintf (buf, "\r\n");
1833 * Now, let the normal header parsing algorithm below do its
1834 * job. If it fails, we'll exit instead of continuing.
1841 * If this is an SSL connection or we're in the body
1842 * of the server document, just write it to the client,
1843 * unless we need to buffer the body for later content-filtering
1846 if (csp->all_headers_read || csp->http->ssl)
1848 if (csp->content_filter)
1850 add_to_iob (csp, buf, len);
1853 * If the buffer limit will be reached on the next read,
1854 * switch to non-filtering mode, i.e. make & write the
1855 * header, flush the socket and get out of the way.
1857 if (((size_t) (csp->iob->eod - csp->iob->buf)) +
1858 (size_t) BUFFER_SIZE > csp->config->buffer_limit)
1862 log_error (LOG_LEVEL_ERROR,
1863 "Buffer size limit reached! Flushing and stepping back.");
1865 hdr = sed (server_patterns, add_server_headers, csp);
1868 /* FIXME Should handle error properly */
1869 log_error (LOG_LEVEL_FATAL,
1870 "Out of memory parsing server header");
1873 hdrlen = strlen (hdr);
1874 byte_count += hdrlen;
1876 if (write_socket (csp->cfd, hdr, hdrlen)
1877 || ((len = flush_socket (csp->cfd, csp)) < 0))
1879 log_error (LOG_LEVEL_CONNECT,
1880 "write header to client failed: %E");
1883 return JB_ERR_GENERIC;
1889 csp->content_filter = NULL;
1890 csp->all_headers_read = 1;
1896 if (write_socket (csp->cfd, buf, (size_t) len))
1898 log_error (LOG_LEVEL_ERROR, "write to client failed: %E");
1899 return JB_ERR_GENERIC;
1908 * we're still looking for the end of the
1909 * server's header ... (does that make header
1910 * parsing an "out of body experience" ?
1913 /* buffer up the data we just read */
1914 add_to_iob (csp, buf, len);
1916 /* get header lines from the iob */
1918 while ((p = get_header (csp)) != NULL)
1922 /* see following note */
1923 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1924 csp->ip_addr_str, csp->http->ocmd, byte_count);
1925 return JB_ERR_GENERIC;
1927 enlist (csp->headers, p);
1931 /* NOTE: there are no "empty" headers so
1932 * if the pointer `p' is not NULL we must
1933 * assume that we reached the end of the
1934 * buffer before we hit the end of the header.
1941 /* Well, we tried our MS IIS/5
1942 * hack and it didn't work.
1943 * The header is incomplete
1944 * and there isn't anything
1945 * we can do about it.
1947 log_error(LOG_LEVEL_CLF, "Incomplete Server Header: %s - - [%T] \"%s\" 200 %d",
1948 csp->ip_addr_str, csp->http->ocmd, byte_count);
1949 return JB_ERR_GENERIC;
1953 /* Since we have to wait for
1954 * more from the server before
1955 * we can parse the headers
1956 * we just continue here.
1962 /* we have now received the entire header.
1963 * filter it and send the result to the client
1966 hdr = sed (server_patterns, add_server_headers, csp);
1969 /* FIXME Should handle error properly */
1970 log_error (LOG_LEVEL_FATAL, "Out of memory parsing server header");
1975 #ifdef FEATURE_KILL_POPUPS
1976 /* Start blocking popups if appropriate. */
1978 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1979 !csp->http->ssl && /* We talk plaintext */
1980 block_popups) /* Policy allows */
1982 block_popups_now = 1;
1984 * Filter the part of the body that came in the same read
1985 * as the last headers:
1987 filter_popups (csp->iob->cur, csp);
1990 #endif /* def FEATURE_KILL_POPUPS */
1992 /* Buffer and pcrs filter this if appropriate. */
1994 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1995 !csp->http->ssl && /* We talk plaintext */
1996 pcrs_filter) /* Policy allows */
1998 csp->content_filter = pcrs_filter_response;
2001 /* Buffer and gif_deanimate this if appropriate. */
2003 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
2004 !csp->http->ssl && /* We talk plaintext */
2005 gif_deanimate) /* Policy allows */
2007 csp->content_filter = gif_deanimate_response;
2010 * Only write if we're not buffering for content modification
2012 if (!csp->content_filter)
2014 /* write the server's (modified) header to
2015 * the client (along with anything else that
2016 * may be in the buffer)
2018 if (write_socket (csp->cfd, hdr, strlen (hdr))
2019 || ((len = flush_socket (csp->cfd, csp)) < 0))
2021 log_error (LOG_LEVEL_CONNECT,
2022 "write header to client failed: %E");
2024 /* the write failed, so don't bother
2025 * mentioning it to the client...
2026 * it probably can't hear us anyway.
2029 return JB_ERR_GENERIC;
2035 /* we're finished with the server's header */
2038 csp->all_headers_read = 1;
2040 /* If this was a MS IIS/5 hack then it means
2041 * the server has already closed the
2042 * connection. Nothing more to read. Time
2047 return JB_ERR_GENERIC ;
2051 } /* END relay_server_traffic() */
2054 /*********************************************************************
2056 * Function : read_client_headers
2058 * Description : read all the client headers, and fill in the
2062 * 1 : client_state structure
2063 * 2 : http_request structure
2066 * Returns : JB_ERR_OK - headers read and parsed ok
2067 * : other values - an error occurred.
2068 *********************************************************************/
2070 static jb_err read_client_headers( struct client_state *csp, struct http_request *http )
2075 char buf[BUFFER_SIZE];
2076 int len; /* for buffer sizes */
2079 * Read the client's request. Note that since we're not using select() we
2080 * could get blocked here if a client connected, then didn't say anything!
2082 * This will read all the client headers.
2088 len = read_socket(csp->cfd, buf, sizeof(buf));
2090 if (len <= 0) break; /* error! */
2092 add_to_iob(csp, buf, len);
2094 req = get_header(csp);
2098 break; /* no HTTP request! */
2103 continue; /* more to come! */
2106 /* When we get here we have read one header which is enough */
2107 /* to check whether the connection is allowed */
2115 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
2117 len = read_socket(csp->cfd, buf, sizeof(buf));
2120 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
2121 return JB_ERR_GENERIC;
2123 add_to_iob(csp, buf, len);
2127 if (p == NULL) break;
2129 enlist(csp->headers, p);
2134 parse_http_request(req, http, csp);
2137 if (http->cmd == NULL)
2139 strcpy(buf, CHEADER);
2140 write_socket(csp->cfd, buf, strlen(buf));
2142 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
2144 return JB_ERR_GENERIC;
2150 } /* END read_client_headers */
2153 /*********************************************************************
2155 * Function : process_client_headers
2157 * Description : Process client headers
2158 * FIXME: Add description of what we do here!
2161 * 1 : client_state structure
2162 * 2 : http_request structure
2165 * Returns : JB_ERR_OK - headers processed ok
2166 * : other values - an error occurred.
2167 *********************************************************************/
2169 static jb_err process_client_headers( struct client_state *csp, struct http_request *http )
2173 #ifdef FEATURE_FORCE_LOAD
2174 /* If this request contains the FORCE_PREFIX,
2175 * better get rid of it now and set the force flag --oes
2176 * Changed to use the http structure rather than the req field --jaa
2177 * FIXME: This isn't enough -- there is the path and referrer etc! *
2180 if (strstr(http->url, FORCE_PREFIX))
2182 strclean(http->url, FORCE_PREFIX);
2183 strclean(http->path, FORCE_PREFIX);
2184 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", http->url);
2185 csp->flags |= CSP_FLAG_FORCED;
2188 #endif /* def FEATURE_FORCE_LOAD */
2191 /* decide how to route the HTTP request */
2193 if ((http->fwd = forward_url(http, csp)) == NULL)
2195 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2196 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2199 /* build the http request to send to the server
2200 * we have to do one of the following:
2202 * create = use the original HTTP request to create a new
2203 * HTTP request that has either the path component
2204 * without the http://domainspec (w/path) or the
2205 * full orininal URL (w/url)
2206 * Note that the path and/or the HTTP version may
2207 * have been altered by now.
2209 * connect = Open a socket to the host:port of the server
2210 * and short-circuit server and client socket.
2212 * pass = Pass the request unchanged if forwarding a CONNECT
2213 * request to a parent proxy. Note that we'll be sending
2214 * the CFAIL message ourselves if connecting to the parent
2215 * fails, but we won't send a CSUCCEED message if it works,
2216 * since that would result in a double message (ours and the
2217 * parent's). After sending the request to the parent, we simply
2220 * here's the matrix:
2223 * +--------+--------+
2225 * 0 | create | connect|
2227 * Forwarding +--------+--------+
2229 * 1 | create | pass |
2231 * +--------+--------+
2236 * Determine the actions for this URL
2238 #ifdef FEATURE_TOGGLE
2239 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
2241 /* Most compatible set of actions (i.e. none) */
2242 init_current_action(csp->action);
2245 #endif /* ndef FEATURE_TOGGLE */
2247 url_actions(http, csp);
2255 * Downgrade http version from 1.1 to 1.0 if +downgrade
2258 if ( (http->ssl == 0)
2259 && (!strcmpic(http->ver, "HTTP/1.1"))
2260 && (csp->action->flags & ACTION_DOWNGRADE))
2263 http->ver = strdup("HTTP/1.0");
2265 if (http->ver == NULL)
2267 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
2272 * Save a copy of the original request for logging
2274 http->ocmd = strdup(http->cmd);
2276 if (http->ocmd == NULL)
2278 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
2282 * (Re)build the HTTP request for non-SSL requests.
2283 * If forwarding, use the whole URL, else, use only the path.
2289 http->cmd = strdup(http->gpc);
2290 string_append(&http->cmd, " ");
2292 if (http->fwd->forward_host)
2294 string_append(&http->cmd, http->url);
2298 string_append(&http->cmd, http->path);
2301 string_append(&http->cmd, " ");
2302 string_append(&http->cmd, http->ver);
2304 if (http->cmd == NULL)
2306 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
2309 enlist_first(csp->headers, http->cmd);
2313 * If the user has not supplied any wafers, and the user has not
2314 * told us to suppress the vanilla wafer, then send the vanilla wafer.
2316 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
2317 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
2319 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
2323 } /* process_client_headers */
2325 /*********************************************************************
2327 * Function : intercept_page
2329 * Description : Check whether to intercept page
2332 * 1 : client_state structure
2333 * 2 : http_request structure
2336 * Returns : JB_ERR_OK - Do NOT intercept this page
2337 * : JB_ERR_INTERCEPT - intercept this page
2338 * : all other values - an error occurred.
2339 *********************************************************************/
2340 static jb_err intercept_page( struct client_state *csp, struct http_request *http )
2343 /* Skeleton for HTTP response, if we should intercept the request */
2344 struct http_response *rsp;
2348 * These next lines are a little ugly, but they simplifies the if statements
2349 * below. Basically if TOGGLE, then we want the if to test if the
2350 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
2351 * then we want the if to test for CSP_FLAG_FORCED , else we don't
2353 #ifdef FEATURE_TOGGLE
2354 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
2355 #else /* ifndef FEATURE_TOGGLE */
2356 # define IS_TOGGLED_ON_AND
2357 #endif /* ndef FEATURE_TOGGLE */
2358 #ifdef FEATURE_FORCE_LOAD
2359 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
2360 #else /* ifndef FEATURE_FORCE_LOAD */
2361 # define IS_NOT_FORCED_AND
2362 #endif /* def FEATURE_FORCE_LOAD */
2364 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
2367 /* a CGI call was detected and answered */
2368 (NULL != (rsp = dispatch_cgi(csp)))
2370 /* or we are enabled and... */
2371 || (IS_ENABLED_AND (
2373 /* ..the request was blocked */
2374 ( NULL != (rsp = block_url(csp)))
2376 /* ..or untrusted */
2377 #ifdef FEATURE_TRUST
2378 || ( NULL != (rsp = trust_url(csp)))
2379 #endif /* def FEATURE_TRUST */
2381 /* ..or a fast redirect kicked in */
2382 #ifdef FEATURE_FAST_REDIRECTS
2383 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
2384 (NULL != (rsp = redirect_url(csp))))
2385 #endif /* def FEATURE_FAST_REDIRECTS */
2389 /* Write the answer to the client */
2390 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2391 || write_socket(csp->cfd, rsp->body, rsp->content_length))
2393 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2396 #ifdef FEATURE_STATISTICS
2397 /* Count as a rejected request */
2398 csp->flags |= CSP_FLAG_REJECTED;
2399 #endif /* def FEATURE_STATISTICS */
2401 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
2402 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
2403 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
2405 /* Clean up and return */
2406 free_http_response(rsp);
2407 return JB_ERR_INTERCEPT;
2410 /* When we get here the request doesn't need to be intercepted */
2414 /*********************************************************************
2416 * Function : open_forwarding_connection
2418 * Description : Check whether to intercept page
2421 * 1 : client_state structure
2422 * 2 : http_request structure
2424 * Returns : JB_ERR_OK - Connection opened ok
2425 * : all other values - an error occurred.
2426 *********************************************************************/
2427 static jb_err open_forwarding_connection(struct client_state *csp )
2429 struct http_response *rsp;
2431 #ifdef FEATURE_ACTIVITY_CONSOLE
2432 accumulate_stats(STATS_REQUEST, 1);
2433 #endif /* def FEATURE_ACTIVITY_CONSOLE */
2434 log_error(LOG_LEVEL_GPC, "%s%s", csp->http->hostport, csp->http->path);
2436 if (csp->http->fwd->forward_host)
2438 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
2439 csp->http->fwd->forward_host, csp->http->fwd->forward_port,
2440 csp->http->hostport);
2444 log_error(LOG_LEVEL_CONNECT, "to %s", csp->http->hostport);
2447 /* here we connect to the server, gateway, or the forwarder */
2449 csp->sfd = forwarded_connect(csp->http->fwd, csp->http, csp);
2451 if (csp->sfd == JB_INVALID_SOCKET)
2453 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
2454 csp->http->hostport);
2456 if (errno == EINVAL)
2458 rsp = error_response(csp, "no-such-domain", errno);
2460 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
2461 csp->ip_addr_str, csp->http->ocmd);
2465 rsp = error_response(csp, "connect-failed", errno);
2467 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
2468 csp->ip_addr_str, csp->http->ocmd);
2472 /* Write the answer to the client */
2475 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2476 || write_socket(csp->cfd, rsp->body, rsp->content_length))
2478 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
2482 free_http_response(rsp);
2483 return JB_ERR_GENERIC;
2486 log_error(LOG_LEVEL_CONNECT, "OK");
2489 } /* END open_forwarding_connection() */
2492 /*********************************************************************
2494 * Function : send_client_headers_to_server
2496 * Description : send the client headers (possibly modified) to the server
2499 * 1 : client_state structure
2500 * 2 : http_request structure
2503 * Returns : JB_ERR_OK - headers sent ok
2504 * : other values - an error occurred.
2505 *********************************************************************/
2507 static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http, char *hdr )
2510 struct http_response *rsp;
2512 if (http->fwd->forward_host || (http->ssl == 0))
2514 /* write the client's (modified) header to the server
2515 * (along with anything else that may be in the buffer)
2518 if (write_socket(csp->sfd, hdr, strlen(hdr))
2519 || (flush_socket(csp->sfd, csp) < 0))
2521 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
2524 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
2525 csp->ip_addr_str, http->ocmd);
2527 rsp = error_response(csp, "connect-failed", errno);
2531 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2532 || write_socket(csp->cfd, rsp->body, rsp->content_length))
2534 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2538 free_http_response(rsp);
2539 return JB_ERR_GENERIC;
2545 * We're running an SSL tunnel and we're not forwarding,
2546 * so just send the "connect succeeded" message to the
2547 * client, flush the rest, and get out of the way.
2549 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
2550 csp->ip_addr_str, http->ocmd);
2552 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
2560 } /* END send_client_headers_to_server */
2563 /*********************************************************************
2565 * Function : is_connect_request_allowed
2567 * Description : send the client headers (possibly modified) to the server
2570 * 1 : client_state structure
2574 * Returns : JB_ERR_OK - connect request allowed
2575 * : other values - connect request not allowed
2576 *********************************************************************/
2577 static jb_err is_connect_request_allowed( struct client_state *csp )
2580 * Check if a CONNECT request is allowable:
2581 * In the absence of a +limit-connect action, allow only port 443.
2582 * If there is an action, allow whatever matches the specificaton.
2587 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
2588 || (csp->action->flags & ACTION_LIMIT_CONNECT
2589 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
2591 char buf[BUFFER_SIZE];
2592 strcpy(buf, CFORBIDDEN);
2593 write_socket(csp->cfd, buf, strlen(buf));
2595 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
2596 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
2598 return JB_ERR_GENERIC;
2603 } /* END is_connect_request_allowed */