1 const char jcc_rcs[] = "$Id: jcc.c,v 2.7 2003/09/25 01:44:33 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.7 2003/09/25 01:44:33 david__schmidt
37 * Resyncing HEAD with v_3_0_branch for two OSX fixes:
38 * Making thread IDs look sane in the logfile for Mach kernels,
39 * and fixing multithreading crashes due to thread-unsafe
43 * Revision 2.6 2003/06/24 12:24:24 oes
44 * Added a line plus Fix-me as a reminder to fix broken force handling in trunk. Thanks to lionel for the hint
46 * Revision 2.5 2003/01/26 20:24:26 david__schmidt
47 * Updated activity console instrumentation locations
49 * Revision 2.4 2002/12/28 03:58:19 david__schmidt
50 * Initial drop of dashboard instrumentation - enabled with
51 * --enable-activity-console
53 * Revision 2.3 2002/07/18 22:06:12 jongfoster
54 * Trivial formatting changes
56 * Revision 2.2 2002/07/12 04:26:17 agotneja
57 * Re-factored 'chat()' to become understandable and maintainable as
58 * a first step in adding Transparent Proxy functionality.
60 * Added several new static functions in jcc.c, and moved some data
61 * parameters up into project.h to allow them to be passed between
64 * Revision 1.91 2002/04/08 20:35:58 swa
67 * Revision 1.90 2002/04/02 14:57:28 oes
68 * Made sending wafers independent of FEATURE_COOKIE_JAR
70 * Revision 1.89 2002/03/31 17:18:59 jongfoster
71 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
73 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
74 * More compiler warning message maintenance
76 * Revision 1.87 2002/03/26 22:29:54 swa
77 * we have a new homepage!
79 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
80 * Workaround for closing the jarfile before load_config() comes around again
82 * Revision 1.85 2002/03/24 15:23:33 jongfoster
85 * Revision 1.84 2002/03/24 13:25:43 swa
86 * name change related issues
88 * Revision 1.83 2002/03/16 23:54:06 jongfoster
89 * Adding graceful termination feature, to help look for memory leaks.
90 * If you enable this (which, by design, has to be done by hand
91 * editing config.h) and then go to http://i.j.b/die, then the program
92 * will exit cleanly after the *next* request. It should free all the
93 * memory that was used.
95 * Revision 1.82 2002/03/13 00:27:05 jongfoster
98 * Revision 1.81 2002/03/12 01:42:50 oes
99 * Introduced modular filters
101 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
102 * OS/2 port maintenance:
103 * - Fixed EMX build - it had decayed a little
104 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
105 * substituted a memset for now.
107 * Revision 1.79 2002/03/09 20:03:52 jongfoster
108 * - Making various functions return int rather than size_t.
109 * (Undoing a recent change). Since size_t is unsigned on
110 * Windows, functions like read_socket that return -1 on
111 * error cannot return a size_t.
113 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
114 * crashes, and also frequently caused JB to jump to 100%
115 * CPU and stay there. (Because it thought it had just
116 * read ((unsigned)-1) == 4Gb of data...)
118 * - The signature of write_socket has changed, it now simply
119 * returns success=0/failure=nonzero.
121 * - Trying to get rid of a few warnings --with-debug on
122 * Windows, I've introduced a new type "jb_socket". This is
123 * used for the socket file descriptors. On Windows, this
124 * is SOCKET (a typedef for unsigned). Everywhere else, it's
125 * an int. The error value can't be -1 any more, so it's
126 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
127 * Windows it maps to the #define INVALID_SOCKET.)
129 * - The signature of bind_port has changed.
131 * Revision 1.78 2002/03/08 21:35:04 oes
132 * Added optional group supplement to --user option. Will now use default group of user if no group given
134 * Revision 1.77 2002/03/07 03:52:06 oes
135 * - Fixed compiler warnings etc
136 * - Improved handling of failed DNS lookups
138 * Revision 1.76 2002/03/06 22:54:35 jongfoster
139 * Automated function-comment nitpicking.
141 * Revision 1.75 2002/03/06 10:02:19 oes
142 * Fixed stupid bug when --user was not given
144 * Revision 1.74 2002/03/06 00:49:31 jongfoster
145 * Fixing warning on Windows
146 * Making #ifdefs that refer to the same variable consistently
147 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
149 * Revision 1.73 2002/03/05 23:57:30 hal9
150 * Stray character 's' on line 1618 was breaking build.
152 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
153 * - Re-enable OS/2 building after new parms were added
154 * - Fix false out of memory report when resolving CGI templates when no IP
155 * address is available of failed attempt (a la no such domain)
157 * Revision 1.71 2002/03/05 18:13:56 oes
158 * Added --user option
160 * Revision 1.70 2002/03/05 04:52:42 oes
161 * Deleted non-errlog debugging code
163 * Revision 1.69 2002/03/04 23:50:00 jongfoster
164 * Splitting off bind_port() call into bind_port_helper(), with
167 * Revision 1.68 2002/03/04 20:17:32 oes
170 * Revision 1.67 2002/03/04 18:18:57 oes
171 * - Removed _DEBUG mode
172 * - Cleand up cmdline parsing
173 * - Introduced --no-daemon, --pidfile options
174 * - Cleaned up signal handling:
175 * - Terminate cleanly on INT, TERM and ABRT
176 * - Schedule logfile for re-opening on HUP
177 * - Ignore CHLD and PIPE
178 * - Leave the rest with their default handlers
179 * - Uniform handler registration
180 * - Added usage() function
181 * - Played styleguide police
183 * Revision 1.66 2002/03/03 15:06:55 oes
184 * Re-enabled automatic config reloading
186 * Revision 1.65 2002/03/03 14:49:11 oes
187 * Fixed CLF logging: Now uses client's original HTTP request
189 * Revision 1.64 2002/03/03 09:18:03 joergs
190 * Made jumbjuster work on AmigaOS again.
192 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
193 * Clean up a little CRLF unpleasantness that suddenly appeared
195 * Revision 1.62 2002/02/20 23:17:23 jongfoster
196 * Detecting some out-of memory conditions and exiting with a log message.
198 * Revision 1.61 2002/01/17 21:01:52 jongfoster
199 * Moving all our URL and URL pattern parsing code to urlmatch.c.
201 * Revision 1.60 2001/12/30 14:07:32 steudten
202 * - Add signal handling (unix)
203 * - Add SIGHUP handler (unix)
204 * - Add creation of pidfile (unix)
205 * - Add action 'top' in rc file (RH)
206 * - Add entry 'SIGNALS' to manpage
207 * - Add exit message to logfile (unix)
209 * Revision 1.59 2001/12/13 14:07:18 oes
210 * Fixed Bug: 503 error page now sent OK
212 * Revision 1.58 2001/11/30 23:37:24 jongfoster
213 * Renaming the Win32 config file to config.txt - this is almost the
214 * same as the corresponding UNIX name "config"
216 * Revision 1.57 2001/11/16 00:47:43 jongfoster
217 * Changing the tty-disconnection code to use setsid().
219 * Revision 1.56 2001/11/13 20:20:54 jongfoster
220 * Tabs->spaces, fixing a bug with missing {} around an if()
222 * Revision 1.55 2001/11/13 20:14:53 jongfoster
223 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
225 * Revision 1.54 2001/11/07 00:03:14 steudten
226 * Give reliable return value if an error
227 * occurs not just 0 with new daemon mode.
229 * Revision 1.53 2001/11/05 21:41:43 steudten
230 * Add changes to be a real daemon just for unix os.
231 * (change cwd to /, detach from controlling tty, set
232 * process group and session leader to the own process.
234 * Add some fatal-error log message for failed malloc().
235 * Add '-d' if compiled with 'configure --with-debug' to
236 * enable debug output.
238 * Revision 1.52 2001/10/26 20:11:20 jongfoster
239 * Fixing type mismatch
241 * Revision 1.51 2001/10/26 17:38:28 oes
244 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
245 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
246 * threads to call select() simultaneously. So, it's time to do a real, live,
247 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
248 * (native). Both versions will work, but using __OS2__ offers multi-threading.
250 * Revision 1.49 2001/10/23 21:41:35 jongfoster
251 * Added call to initialize the (statically-allocated of course)
252 * "out of memory" CGI response.
254 * Revision 1.48 2001/10/10 19:56:46 jongfoster
255 * Moving some code that wasn't cookie-related out of an #ifdef
258 * Revision 1.47 2001/10/10 16:44:36 oes
259 * Added CONNECT destination port limitation check
261 * Revision 1.46 2001/10/08 15:17:41 oes
262 * Re-enabled SSL forwarding
264 * Revision 1.45 2001/10/07 15:42:11 oes
265 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
267 * Moved downgrading of the HTTP version from parse_http_request to
268 * chat(), since we can't decide if it is necessary before we have
269 * determined the actions for the URL. The HTTP command is now
270 * *always* re-built so the repairs need no longer be special-cased.
272 * filter_popups now gets a csp pointer so it can raise the new
273 * CSP_FLAG_MODIFIED flag.
277 * Added configurable size limit for the IOB. If the IOB grows so
278 * large that the next read would exceed the limit, the header
279 * is generated, and the header & unfiltered buffer are flushed
280 * to the client. Chat then continues in non-buffering,
281 * non-filtering body mode.
283 * Revision 1.44 2001/10/02 18:13:57 oes
286 * Revision 1.43 2001/10/02 15:32:13 oes
287 * Moved generation of hdr
289 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
290 * Cleaning up 2 compiler warnings on OS/2.
292 * Revision 1.41 2001/09/16 17:05:14 jongfoster
293 * Removing unused #include showarg.h
295 * Revision 1.40 2001/09/16 15:41:45 jongfoster
296 * Fixing signed/unsigned comparison warning.
298 * Revision 1.39 2001/09/16 13:21:27 jongfoster
299 * Changes to use new list functions.
301 * Revision 1.38 2001/09/16 13:01:46 jongfoster
302 * Removing redundant function call that zeroed zalloc()'d memory.
304 * Revision 1.37 2001/09/10 11:12:24 oes
305 * Deleted unused variable
307 * Revision 1.36 2001/09/10 10:56:15 oes
308 * Silenced compiler warnings
310 * Revision 1.35 2001/07/31 14:44:22 oes
311 * Deleted unused size parameter from filter_popups()
313 * Revision 1.34 2001/07/30 22:08:36 jongfoster
314 * Tidying up #defines:
315 * - All feature #defines are now of the form FEATURE_xxx
316 * - Permanently turned off WIN_GUI_EDIT
317 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
319 * Revision 1.33 2001/07/29 19:32:00 jongfoster
320 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
322 * Revision 1.32 2001/07/29 18:47:05 jongfoster
323 * Adding missing #include "loadcfg.h"
325 * Revision 1.31 2001/07/29 12:17:48 oes
326 * Applied pthread fix by Paul Lieverse
328 * Revision 1.30 2001/07/25 22:57:13 jongfoster
329 * __BEOS__ no longer overrides FEATURE_PTHREAD.
330 * This is because FEATURE_PTHREAD will soon be widely used, so I
331 * want to keep it simple.
333 * Revision 1.29 2001/07/24 12:47:06 oes
334 * Applied BeOS support update by Eugenia
336 * Revision 1.28 2001/07/23 13:26:12 oes
337 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
339 * Revision 1.27 2001/07/19 19:09:47 haroon
340 * - Added code to take care of the situation where while processing the first
341 * server response (which includes the server header), after finding the end
342 * of the headers we were not looking past the end of the headers for
343 * content modification. I enabled it for filter_popups.
344 * Someone else should look to see if other similar operations should be
345 * done to the discarded portion of the buffer.
347 * Note 2001/07/20: No, the other content modification mechanisms will process
348 * the whole iob later anyway. --oes
350 * Revision 1.26 2001/07/18 12:31:36 oes
353 * Revision 1.25 2001/07/15 19:43:49 jongfoster
354 * Supports POSIX threads.
355 * Also removed some unused #includes.
357 * Revision 1.24 2001/07/13 14:00:40 oes
358 * - Generic content modification scheme:
359 * Each feature has its own applicability flag that is set
360 * from csp->action->flags.
361 * Replaced the "filtering" int flag , by a function pointer
362 * "content_filter" to the function that will do the content
363 * modification. If it is != NULL, the document will be buffered
364 * and processed through *content_filter, which must set
365 * csp->content_length and return a modified copy of the body
366 * or return NULL (on failiure).
367 * - Changed csp->is_text to the more generic bitmap csp->content_type
368 * which can currently take the valued CT_TEXT or CT_GIF
370 * - Removed all #ifdef PCRS
372 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
373 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
374 * the `block_acl' call. This prevents a compilation error when the user
375 * does not wish to use the "ACL" feature.
377 * Revision 1.22 2001/06/29 21:45:41 oes
378 * Indentation, CRLF->LF, Tab-> Space
380 * Revision 1.21 2001/06/29 13:29:36 oes
381 * - Cleaned up, improved comments
382 * - Unified all possible interceptors (CGI,
383 * block, trust, fast_redirect) in one
384 * place, with one (CGI) answer generation
385 * mechansim. Much clearer now.
386 * - Removed the GIF image generation, which
387 * is now done in filters.c:block_url()
388 * - Made error conditions like domain lookup
389 * failiure or (various) problems while talking
390 * to the server use cgi.c:error_response()
391 * instead of generating HTML/HTTP in chat() (yuck!)
392 * - Removed logentry from cancelled commit
394 * Revision 1.20 2001/06/09 10:55:28 jongfoster
395 * Changing BUFSIZ ==> BUFFER_SIZE
397 * Revision 1.19 2001/06/07 23:12:52 jongfoster
398 * Replacing function pointer in struct gateway with a directly
399 * called function forwarded_connect().
400 * Replacing struct gateway with struct forward_spec
402 * Revision 1.18 2001/06/03 19:12:16 oes
403 * introduced new cgi handling
405 * Revision 1.17 2001/06/01 20:07:23 jongfoster
406 * Now uses action +image-blocker{} rather than config->tinygif
408 * Revision 1.16 2001/06/01 18:49:17 jongfoster
409 * Replaced "list_share" with "list" - the tiny memory gain was not
410 * worth the extra complexity.
412 * Revision 1.15 2001/05/31 21:24:47 jongfoster
413 * Changed "permission" to "action" throughout.
414 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
415 * Moved vanilla wafer check into chat(), since we must now
416 * decide whether or not to add it based on the URL.
418 * Revision 1.14 2001/05/29 20:14:01 joergs
419 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
422 * Revision 1.13 2001/05/29 09:50:24 jongfoster
423 * Unified blocklist/imagelist/permissionslist.
424 * File format is still under discussion, but the internal changes
427 * Also modified interceptor behaviour:
428 * - We now intercept all URLs beginning with one of the following
429 * prefixes (and *only* these prefixes):
431 * * http://ijbswa.sf.net/config/
432 * * http://ijbswa.sourceforge.net/config/
433 * - New interceptors "home page" - go to http://i.j.b/ to see it.
434 * - Internal changes so that intercepted and fast redirect pages
435 * are not replaced with an image.
436 * - Interceptors now have the option to send a binary page direct
437 * to the client. (i.e. ijb-send-banner uses this)
438 * - Implemented show-url-info interceptor. (Which is why I needed
439 * the above interceptors changes - a typical URL is
440 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
441 * The previous mechanism would not have intercepted that, and
442 * if it had been intercepted then it then it would have replaced
445 * Revision 1.12 2001/05/27 22:17:04 oes
447 * - re_process_buffer no longer writes the modified buffer
448 * to the client, which was very ugly. It now returns the
449 * buffer, which it is then written by chat.
451 * - content_length now adjusts the Content-Length: header
452 * for modified documents rather than crunch()ing it.
453 * (Length info in csp->content_length, which is 0 for
454 * unmodified documents)
456 * - For this to work, sed() is called twice when filtering.
458 * Revision 1.11 2001/05/26 17:27:53 jongfoster
459 * Added support for CLF and fixed LOG_LEVEL_LOG.
460 * Also did CRLF->LF fix of my previous patch.
462 * Revision 1.10 2001/05/26 15:26:15 jongfoster
463 * ACL feature now provides more security by immediately dropping
464 * connections from untrusted hosts.
466 * Revision 1.9 2001/05/26 00:28:36 jongfoster
467 * Automatic reloading of config file.
468 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
469 * Most of the global variables have been moved to a new
470 * struct configuration_spec, accessed through csp->config->globalname
471 * Most of the globals remaining are used by the Win32 GUI.
473 * Revision 1.8 2001/05/25 22:43:18 jongfoster
474 * Fixing minor memory leak and buffer overflow.
476 * Revision 1.7 2001/05/25 22:34:30 jongfoster
479 * Revision 1.6 2001/05/23 00:13:58 joergs
480 * AmigaOS support fixed.
482 * Revision 1.5 2001/05/22 18:46:04 oes
484 * - Enabled filtering banners by size rather than URL
485 * by adding patterns that replace all standard banner
486 * sizes with the "Junkbuster" gif to the re_filterfile
488 * - Enabled filtering WebBugs by providing a pattern
489 * which kills all 1x1 images
491 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
492 * which is selected by the (nonstandard and therefore
493 * capital) letter 'U' in the option string.
494 * It causes the quantifiers to be ungreedy by default.
495 * Appending a ? turns back to greedy (!).
497 * - Added a new interceptor ijb-send-banner, which
498 * sends back the "Junkbuster" gif. Without imagelist or
499 * MSIE detection support, or if tinygif = 1, or the
500 * URL isn't recognized as an imageurl, a lame HTML
501 * explanation is sent instead.
503 * - Added new feature, which permits blocking remote
504 * script redirects and firing back a local redirect
506 * The feature is conditionally compiled, i.e. it
507 * can be disabled with --disable-fast-redirects,
508 * plus it must be activated by a "fast-redirects"
509 * line in the config file, has its own log level
510 * and of course wants to be displayed by show-proxy-args
511 * Note: Boy, all the #ifdefs in 1001 locations and
512 * all the fumbling with configure.in and acconfig.h
513 * were *way* more work than the feature itself :-(
515 * - Because a generic redirect template was needed for
516 * this, tinygif = 3 now uses the same.
518 * - Moved GIFs, and other static HTTP response templates
523 * - Removed some >400 CRs again (Jon, you really worked
526 * Revision 1.4 2001/05/21 19:34:01 jongfoster
527 * Made failure to bind() a fatal error.
529 * Revision 1.3 2001/05/20 01:21:20 jongfoster
530 * Version 2.9.4 checkin.
531 * - Merged popupfile and cookiefile, and added control over PCRS
532 * filtering, in new "permissionsfile".
533 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
534 * file error you now get a message box (in the Win32 GUI) rather
535 * than the program exiting with no explanation.
536 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
538 * - Removed tabs from "config"
539 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
540 * - Bumped up version number.
542 * Revision 1.2 2001/05/17 22:34:44 oes
543 * - Added hint on GIF char array generation to jcc.c
544 * - Cleaned CRLF's from the sources and related files
545 * - Repaired logging for REF and FRC
547 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
548 * Initial import of version 2.9.3 source tree
551 *********************************************************************/
557 #include <sys/types.h>
564 #ifdef FEATURE_PTHREAD
566 #endif /* def FEATURE_PTHREAD */
569 # ifndef FEATURE_PTHREAD
573 # include <windows.h>
574 # include <process.h>
575 # endif /* ndef FEATURE_PTHREAD */
578 # ifndef _WIN_CONSOLE
580 # endif /* ndef _WIN_CONSOLE */
582 #else /* ifndef _WIN32 */
584 # if !defined (__OS2__)
586 # include <sys/wait.h>
587 # endif /* ndef __OS2__ */
588 # include <sys/time.h>
589 # include <sys/stat.h>
590 # include <sys/ioctl.h>
593 #include <sys/termios.h>
604 # include <socket.h> /* BeOS has select() for sockets only. */
605 # include <OS.h> /* declarations for threads and stuff. */
608 # if defined(__EMX__) || defined(__OS2__)
609 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
614 #define bzero(B,N) memset(B,0x00,n)
629 #include "killpopup.h"
630 #include "miscutil.h"
632 #include "jbsockets.h"
637 #include "urlmatch.h"
638 #ifdef FEATURE_ACTIVITY_CONSOLE
640 #endif /* def FEATURE_ACTIVITY_CONSOLE */
642 const char jcc_h_rcs[] = JCC_H_VERSION;
643 const char project_h_rcs[] = PROJECT_H_VERSION;
646 struct client_state clients[1];
647 struct file_list files[1];
649 #ifdef FEATURE_STATISTICS
650 int urls_read = 0; /* total nr of urls read inc rejected */
651 int urls_rejected = 0; /* total nr of urls rejected */
652 #endif /* def FEATURE_STATISTICS */
654 #ifdef FEATURE_GRACEFUL_TERMINATION
658 static void listen_loop(void);
659 static void chat(struct client_state *csp);
660 static jb_err relay_server_traffic( struct client_state *csp ) ;
661 static jb_err read_client_headers( struct client_state *csp, struct http_request *http ) ;
662 static jb_err process_client_headers( struct client_state *csp, struct http_request *http ) ;
663 static jb_err intercept_page( struct client_state *csp, struct http_request *http );
664 static jb_err open_forwarding_connection( struct client_state *csp );
665 static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http, char* hdr );
666 static jb_err is_connect_request_allowed( struct client_state *csp ) ;
670 void serve(struct client_state *csp);
671 #else /* ifndef AMIGA */
672 static void serve(struct client_state *csp);
673 #endif /* def AMIGA */
676 static int32 server_thread(void *data);
677 #endif /* def __BEOS__ */
680 #define sleep(N) Sleep(((N) * 1000))
684 #define sleep(N) DosSleep(((N) * 100))
689 * Hit OSX over the head with a hammer. Protect all *_r functions.
691 pthread_mutex_t gmtime_mutex;
692 pthread_mutex_t localtime_mutex;
693 pthread_mutex_t gethostbyaddr_mutex;
694 pthread_mutex_t gethostbyname_mutex;
695 #endif /* def OSX_DARWIN */
697 #if defined(unix) || defined(__EMX__)
698 const char *basedir = NULL;
699 const char *pidfile = NULL;
700 int received_hup_signal = 0;
701 #endif /* defined unix */
703 /* The vanilla wafer. */
704 static const char VANILLA_WAFER[] =
705 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
706 "Do_not_send_me_any_copyrighted_information_other_than_the_"
707 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
708 "In_particular_do_not_send_me_any_cookies_that_"
709 "are_subject_to_a_claim_of_copyright_by_anybody._"
710 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
711 "(copyright_or_otherwise)_applying_to_any_cookie._";
714 * HTTP header sent when doing HTTPS tunnelling ("CONNECT" method).
716 static const char CSUCCEED[] =
717 "HTTP/1.0 200 Connection established\n"
718 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
722 * HTTP reply sent when the browser sends something unintelligible.
724 static const char CHEADER[] =
725 "HTTP/1.0 400 Invalid header received from browser\r\n\r\n";
729 * HTTP reply sent when the browser tries to tunnel ("CONNECT") to something
730 * other than a HTTPS port (as defined by +limit-connect).
732 static const char CFORBIDDEN[] =
733 "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";
735 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
736 /*********************************************************************
738 * Function : sig_handler
740 * Description : Signal handler for different signals.
741 * Exit gracefully on ABRT, TERM and INT
742 * or set a flag that will cause the errlog
743 * to be reopened by the main thread on HUP.
746 * 1 : the_signal = the signal cause this function to call
750 *********************************************************************/
751 static void sig_handler(int the_signal)
758 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
766 received_hup_signal = 1;
771 * We shouldn't be here, unless we catch signals
772 * in main() that we can't handle here!
774 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
782 /*********************************************************************
786 * Description : Once a connection to the client has been accepted,
787 * this function is called (via serve()) to handle the
788 * main business of the communication. When this
789 * function returns, the caller must close the client
793 * 1 : csp = Current client state (buffers, headers, etc...)
797 *********************************************************************/
798 static void chat(struct client_state *csp)
802 char buf[BUFFER_SIZE];
803 int len; /* for buffer sizes */
809 struct http_request *http;
813 if (read_client_headers(csp, http ) != JB_ERR_OK )
817 /* Process the client headers */
818 if (process_client_headers(csp, http) != JB_ERR_OK)
822 /* Check if this connection request is permitted */
823 if (is_connect_request_allowed(csp) != JB_ERR_OK)
827 * We have a valid and legit request. Now, check to see if we need to
830 if (intercept_page(csp, http) != JB_ERR_OK)
834 * The page passed the intercept routine, so open a forwarding
835 * connection for conversation
837 if (open_forwarding_connection(csp) != JB_ERR_OK )
842 hdr = sed(client_patterns, add_client_headers, csp);
845 /* FIXME Should handle error properly */
846 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
849 /* FIXME - where should this go, logically ? */
850 list_remove_all(csp->headers);
853 if (send_client_headers_to_server(csp, http, hdr) != JB_ERR_OK)
857 /* we're finished with the client's header */
860 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
862 /* pass data between the client and server
863 * until one or the other shuts down the connection.
866 /* Set the flag for reading headers to False */
867 /* This is used in relay_server_traffic */
868 csp->all_headers_read = 0 ;
872 jb_err tmp_ret_val = JB_ERR_GENERIC ;
876 * FD_ZERO here seems to point to an errant macro which crashes.
877 * So do this by hand for now...
879 memset(&rfds,0x00,sizeof(fd_set));
883 FD_SET(csp->cfd, &rfds);
884 FD_SET(csp->sfd, &rfds);
886 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
890 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
895 * This is the body of the browser's request.
896 * Just read it and write it.
899 if (FD_ISSET(csp->cfd, &rfds))
901 len = read_socket(csp->cfd, buf, sizeof(buf));
905 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
906 csp->ip_addr_str, http->ocmd, byte_count);
910 if (write_socket(csp->sfd, buf, (size_t)len))
912 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
919 * Check if the server wants to talk, and if so, converse.
922 if (FD_ISSET(csp->sfd, &rfds))
923 tmp_ret_val = relay_server_traffic(csp) ;
926 if (tmp_ret_val == JB_ERR_OK)
931 /* We should never get here! */
932 log_error(LOG_LEVEL_FATAL, "chat() : logic error in for() loop" ) ;
936 /*********************************************************************
940 * Description : This is little more than chat. We only "serve" to
941 * to close any socket that chat may have opened.
944 * 1 : csp = Current client state (buffers, headers, etc...)
948 *********************************************************************/
950 void serve(struct client_state *csp)
951 #else /* ifndef AMIGA */
952 static void serve(struct client_state *csp)
953 #endif /* def AMIGA */
956 close_socket(csp->cfd);
958 if (csp->sfd != JB_INVALID_SOCKET)
960 close_socket(csp->sfd);
963 csp->flags &= ~CSP_FLAG_ACTIVE;
969 /*********************************************************************
971 * Function : server_thread
973 * Description : We only exist to call `serve' in a threaded environment.
976 * 1 : data = Current client state (buffers, headers, etc...)
978 * Returns : Always 0.
980 *********************************************************************/
981 static int32 server_thread(void *data)
983 serve((struct client_state *) data);
990 /*********************************************************************
994 * Description : Print usage info & exit.
996 * Parameters : Pointer to argv[0] for identifying ourselves
1000 *********************************************************************/
1001 void usage(const char *myname)
1003 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
1004 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1005 "Aborting.\n", myname);
1012 /*********************************************************************
1016 * Description : Load the config file and start the listen loop.
1017 * This function is a lot more *sane* with the `load_config'
1018 * and `listen_loop' functions; although it stills does
1019 * a *little* too much for my taste.
1022 * 1 : argc = Number of parameters (including $0).
1023 * 2 : argv = Array of (char *)'s to the parameters.
1025 * Returns : 1 if : can't open config file, unrecognized directive,
1026 * stats requested in multi-thread mode, can't open the
1027 * log file, can't open the jar file, listen port is invalid,
1028 * any load fails, and can't bind port.
1030 * Else main never returns, the process must be signaled
1031 * to terminate execution. Or, on Windows, use the
1032 * "File", "Exit" menu option.
1034 *********************************************************************/
1036 int real_main(int argc, const char *argv[])
1038 int main(int argc, const char *argv[])
1043 struct passwd *pw = NULL;
1044 struct group *grp = NULL;
1052 #if !defined(_WIN32)
1060 * Parse the command line arguments
1062 while (++argc_pos < argc)
1064 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1066 if (strcmp(argv[argc_pos], "--help") == 0)
1071 else if(strcmp(argv[argc_pos], "--version") == 0)
1073 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1077 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1082 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1084 if (++argc_pos == argc) usage(argv[0]);
1085 pidfile = strdup(argv[argc_pos]);
1088 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1090 if (++argc_pos == argc) usage(argv[argc_pos]);
1092 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1095 if (NULL == (grp = getgrnam(p)))
1097 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1101 if (NULL == (pw = getpwnam(argv[argc_pos])))
1103 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1106 if (p != NULL) *--p = '\0';
1108 #endif /* defined(unix) */
1110 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1112 configfile = argv[argc_pos];
1115 } /* -END- while (more arguments) */
1118 if ( *configfile != '/' )
1122 /* make config-filename absolute here */
1123 if ( !(basedir = getcwd( NULL, 1024 )))
1125 perror("get working dir failed");
1129 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1131 perror("malloc failed");
1134 strcpy( abs_file, basedir );
1135 strcat( abs_file, "/" );
1136 strcat( abs_file, configfile );
1137 configfile = abs_file;
1139 #endif /* defined unix */
1146 #elif defined(_WIN32)
1152 * Prepare global mutex semaphores
1154 pthread_mutex_init(&gmtime_mutex,0);
1155 pthread_mutex_init(&localtime_mutex,0);
1156 pthread_mutex_init(&gethostbyaddr_mutex,0);
1157 pthread_mutex_init(&gethostbyname_mutex,0);
1158 #endif /* def OSX_DARWIN */
1161 * Unix signal handling
1163 * Catch the abort, interrupt and terminate signals for a graceful exit
1164 * Catch the hangup signal so the errlog can be reopened.
1165 * Ignore the broken pipe and child signals
1166 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1168 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1171 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1172 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1174 for (idx = 0; catched_signals[idx] != 0; idx++)
1176 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1178 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1182 for (idx = 0; ignored_signals[idx] != 0; idx++)
1184 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1186 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1191 #else /* ifdef _WIN32 */
1192 # ifdef _WIN_CONSOLE
1194 * We *are* in a windows console app.
1195 * Print a verbose messages about FAQ's and such
1197 printf(win32_blurb);
1198 # endif /* def _WIN_CONSOLE */
1199 #endif /* def _WIN32 */
1202 /* Initialize the CGI subsystem */
1203 cgi_init_error_messages();
1206 * If runnig on unix and without the --nodaemon
1207 * option, become a daemon. I.e. fork, detach
1208 * from tty and get process group leadership
1221 if ( pid < 0 ) /* error */
1226 else if ( pid != 0 ) /* parent */
1231 * must check for errors
1232 * child died due to missing files aso
1235 wpid = waitpid( pid, &status, WNOHANG );
1244 /* Should be more portable, but not as well tested */
1249 #else /* ndef __FreeBSD__ */
1251 #endif /* ndef __FreeBSD__ */
1252 fd = open("/dev/tty", O_RDONLY);
1255 /* no error check here */
1256 ioctl( fd, TIOCNOTTY,0 );
1260 /* FIXME: should close stderr (fd 2) here too, but the test
1262 * and load config file is done in listen_loop() and puts
1263 * some messages on stderr there.
1270 } /* -END- if (!no_daemon) */
1273 * As soon as we have written the PID file, we can switch
1274 * to the user and group ID indicated by the --user option
1280 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1282 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1284 if (setuid(pw->pw_uid))
1286 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1290 #endif /* defined unix */
1300 /*********************************************************************
1302 * Function : bind_port_helper
1304 * Description : Bind the listen port. Handles logging, and aborts
1308 * 1 : config = Privoxy configuration. Specifies port
1311 * Returns : Port that was opened.
1313 *********************************************************************/
1314 static jb_socket bind_port_helper(struct configuration_spec * config)
1319 if ( (config->haddr != NULL)
1320 && (config->haddr[0] == '1')
1321 && (config->haddr[1] == '2')
1322 && (config->haddr[2] == '7')
1323 && (config->haddr[3] == '.') )
1325 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1328 else if (config->haddr == NULL)
1330 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1335 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1336 config->hport, config->haddr);
1339 result = bind_port(config->haddr, config->hport, &bfd);
1346 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1347 "There may be another Privoxy or some other "
1348 "proxy running on port %d",
1349 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1350 config->hport, config->hport);
1353 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1354 "The hostname is not resolvable",
1355 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1358 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
1359 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1362 /* shouldn't get here */
1363 return JB_INVALID_SOCKET;
1366 config->need_bind = 0;
1372 /*********************************************************************
1374 * Function : listen_loop
1376 * Description : bind the listen port and enter a "FOREVER" listening loop.
1382 *********************************************************************/
1383 static void listen_loop(void)
1385 struct client_state *csp = NULL;
1387 struct configuration_spec * config;
1389 config = load_config();
1391 bfd = bind_port_helper(config);
1393 #ifdef FEATURE_ACTIVITY_CONSOLE
1394 init_stats_config(config);
1395 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1397 #ifdef FEATURE_GRACEFUL_TERMINATION
1398 while (!g_terminate)
1403 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1404 while (waitpid(-1, NULL, WNOHANG) > 0)
1406 /* zombie children */
1408 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1411 * Free data that was used by died threads
1417 * Re-open the errlog after HUP signal
1419 if (received_hup_signal)
1421 init_error_log(Argv[0], config->logfile, config->debug);
1422 received_hup_signal = 0;
1427 #ifdef FEATURE_COOKIE_JAR
1429 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
1430 * already open. I think unload_configfile() is not being run, which should do
1431 * this work. Until that can get resolved, we'll use this workaround.
1433 * [Note from Jon: We don't unload_configfile() until all existing threads have
1434 * exited - they're likely to hang aroung transferring data to the browser.]
1438 if (csp->config->jar)
1440 fclose(csp->config->jar);
1441 csp->config->jar = NULL;
1443 #endif /* FEATURE_COOKIE_JAR */
1444 #endif /* __OS2__ */
1446 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1448 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1452 csp->flags |= CSP_FLAG_ACTIVE;
1453 csp->sfd = JB_INVALID_SOCKET;
1455 csp->config = config = load_config();
1457 if ( config->need_bind )
1460 * Since we were listening to the "old port", we will not see
1461 * a "listen" param change until the next IJB request. So, at
1462 * least 1 more request must be made for us to find the new
1463 * setting. I am simply closing the old socket and binding the
1466 * Which-ever is correct, we will serve 1 more page via the
1467 * old settings. This should probably be a "show-proxy-args"
1468 * request. This should not be a so common of an operation
1469 * that this will hurt people's feelings.
1474 bfd = bind_port_helper(config);
1477 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1479 if (!accept_connection(csp, bfd))
1481 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1494 log_error(LOG_LEVEL_CONNECT, "OK");
1497 #ifdef FEATURE_TOGGLE
1500 csp->flags |= CSP_FLAG_TOGGLED_ON;
1502 #endif /* def FEATURE_TOGGLE */
1504 #ifdef FEATURE_ACTIVITY_CONSOLE
1505 update_stats_config(config);
1506 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1508 if (run_loader(csp))
1510 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1511 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1515 if (block_acl(NULL,csp))
1517 #ifdef FEATURE_ACTIVITY_CONSOLE
1518 accumulate_stats(STATS_ACL_RESTRICT,1);
1519 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1520 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1521 close_socket(csp->cfd);
1525 #endif /* def FEATURE_ACL */
1527 /* add it to the list of clients */
1528 csp->next = clients->next;
1529 clients->next = csp;
1531 if (config->multi_threaded)
1535 /* this is a switch () statment in the C preprocessor - ugh */
1536 #undef SELECTED_ONE_OPTION
1538 /* Use Pthreads in preference to native code */
1539 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1540 #define SELECTED_ONE_OPTION
1542 pthread_t the_thread;
1543 pthread_attr_t attrs;
1545 pthread_attr_init(&attrs);
1546 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1547 child_id = (pthread_create(&the_thread, &attrs,
1548 (void*)serve, csp) ? -1 : 0);
1549 pthread_attr_destroy(&attrs);
1553 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1554 #define SELECTED_ONE_OPTION
1555 child_id = _beginthread(
1556 (void (*)(void *))serve,
1561 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1562 #define SELECTED_ONE_OPTION
1563 child_id = _beginthread(
1564 (void(* _Optlink)(void*))serve,
1570 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1571 #define SELECTED_ONE_OPTION
1573 thread_id tid = spawn_thread
1574 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1576 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1578 child_id = (int) tid;
1587 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1588 #define SELECTED_ONE_OPTION
1589 csp->cfd = ReleaseSocket(csp->cfd, -1);
1590 if((child_id = (int)CreateNewProcTags(
1591 NP_Entry, (ULONG)server_thread,
1592 NP_Output, Output(),
1593 NP_CloseOutput, FALSE,
1594 NP_Name, (ULONG)"privoxy child",
1595 NP_StackSize, 200*1024,
1599 ((struct Task *)child_id)->tc_UserData = csp;
1600 Signal((struct Task *)child_id, SIGF_SINGLE);
1605 #if !defined(SELECTED_ONE_OPTION)
1608 /* This block is only needed when using fork().
1609 * When using threads, the server thread was
1610 * created and run by the call to _beginthread().
1612 if (child_id == 0) /* child */
1618 else if (child_id > 0) /* parent */
1620 /* in a fork()'d environment, the parent's
1621 * copy of the client socket and the CSP
1625 #if !defined(_WIN32) && defined(__CYGWIN__)
1627 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1628 close_socket(csp->cfd);
1629 csp->flags &= ~CSP_FLAG_ACTIVE;
1633 #undef SELECTED_ONE_OPTION
1634 /* end of cpp switch () */
1636 if (child_id < 0) /* failed */
1638 char buf[BUFFER_SIZE];
1640 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1642 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
1644 write_socket(csp->cfd, buf, strlen(buf));
1645 close_socket(csp->cfd);
1646 csp->flags &= ~CSP_FLAG_ACTIVE;
1657 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
1659 /* Clean up. Aim: free all memory (no leaks) */
1660 #ifdef FEATURE_GRACEFUL_TERMINATION
1662 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
1664 unload_current_config_file();
1665 unload_current_actions_file();
1666 unload_current_re_filterfile();
1667 #ifdef FEATURE_TRUST
1668 unload_current_trust_file();
1671 if (config->multi_threaded)
1678 } while ((clients->next != NULL) && (--i > 0));
1682 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
1691 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
1692 /* Cleanup - remove taskbar icon etc. */
1697 #endif /* FEATURE_GRACEFUL_TERMINATION */
1701 /*********************************************************************
1703 * Function : relay_server_traffic
1705 * Description : receive traffic from the server and relay it
1706 * to the client, with some processing
1709 * 1 : client_state structure
1712 * Returns : JB_ERR_OK if there may be more work
1713 * : other values for errors
1715 **********************************************************************/
1717 static jb_err relay_server_traffic( struct client_state *csp )
1719 #ifdef FEATURE_KILL_POPUPS
1720 int block_popups; /* bool, 1==will block popups */
1721 int block_popups_now = 0; /* bool, 1==currently blocking popups */
1722 #endif /* def FEATURE_KILL_POPUPS */
1724 char buf[BUFFER_SIZE];
1725 int len; /* for buffer sizes */
1726 int ms_iis5_hack = 0;
1731 /* Skeleton for HTTP response, if we should intercept the request */
1732 struct http_response *rsp;
1734 int pcrs_filter; /* bool, 1==will filter through pcrs */
1735 int gif_deanimate; /* bool, 1==will deanimate gifs */
1736 int jpeg_inspect; /* bool, 1==will inspect jpegs */
1738 #ifdef FEATURE_KILL_POPUPS
1739 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1740 #endif /* def FEATURE_KILL_POPUPS */
1742 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
1743 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1745 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1747 jpeg_inspect = ((csp->action->flags & ACTION_JPEG_INSPECT) != 0);
1750 len = read_socket (csp->sfd, buf, sizeof (buf) - 1);
1754 log_error (LOG_LEVEL_ERROR, "read from: %s failed: %E", csp->http->host);
1756 log_error (LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1757 csp->ip_addr_str, csp->http->ocmd);
1759 rsp = error_response (csp, "connect-failed", errno);
1763 if (write_socket (csp->cfd, rsp->head, rsp->head_length)
1764 || write_socket (csp->cfd, rsp->body, rsp->content_length))
1766 log_error (LOG_LEVEL_ERROR, "write to: %s failed: %E",
1771 free_http_response (rsp);
1772 return JB_ERR_GENERIC;
1775 /* Add a trailing zero. This lets filter_popups
1776 * use string operations.
1780 #ifdef FEATURE_KILL_POPUPS
1781 /* Filter the popups on this read. */
1782 if (block_popups_now)
1784 filter_popups (buf, csp);
1786 #endif /* def FEATURE_KILL_POPUPS */
1789 /* Normally, this would indicate that we've read
1790 * as much as the server has sent us and we can
1791 * close the client connection. However, Microsoft
1792 * in its wisdom has released IIS/5 with a bug that
1793 * prevents it from sending the trailing \r\n in
1794 * a 302 redirect header (and possibly other headers).
1795 * To work around this if we've haven't parsed
1796 * a full header we'll append a trailing \r\n
1797 * and see if this now generates a valid one.
1799 * This hack shouldn't have any impacts. If we've
1800 * already transmitted the header or if this is a
1801 * SSL connection, then we won't bother with this
1802 * hack. So we only work on partially received
1803 * headers. If we append a \r\n and this still
1804 * doesn't generate a valid header, then we won't
1805 * transmit anything to the client.
1810 if (csp->all_headers_read || csp->http->ssl)
1813 * If we have been buffering up the document,
1814 * now is the time to apply content modification
1815 * and send the result to the client.
1817 if (csp->content_filter)
1820 * If the content filter fails, use the original
1821 * buffer and length.
1822 * (see p != NULL ? p : csp->iob->cur below)
1824 if (NULL == (p = (*csp->content_filter) (csp)))
1826 csp->content_length = csp->iob->eod - csp->iob->cur;
1829 hdr = sed (server_patterns, add_server_headers, csp);
1832 /* FIXME Should handle error properly */
1833 log_error (LOG_LEVEL_FATAL,
1834 "Out of memory parsing server header");
1838 if (write_socket (csp->cfd, hdr, strlen (hdr))
1839 || write_socket (csp->cfd, p != NULL ? p : csp->iob->cur,
1840 csp->content_length))
1842 log_error (LOG_LEVEL_ERROR,
1843 "write modified content to client failed: %E");
1844 return JB_ERR_GENERIC;
1853 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1854 csp->ip_addr_str, csp->http->ocmd, byte_count);
1855 return JB_ERR_GENERIC;
1859 * This is NOT the body, so
1860 * Let's pretend the server just sent us a blank line.
1862 len = sprintf (buf, "\r\n");
1865 * Now, let the normal header parsing algorithm below do its
1866 * job. If it fails, we'll exit instead of continuing.
1873 * If this is an SSL connection or we're in the body
1874 * of the server document, just write it to the client,
1875 * unless we need to buffer the body for later content-filtering
1878 if (csp->all_headers_read || csp->http->ssl)
1880 if (csp->content_filter)
1882 add_to_iob (csp, buf, len);
1885 * If the buffer limit will be reached on the next read,
1886 * switch to non-filtering mode, i.e. make & write the
1887 * header, flush the socket and get out of the way.
1889 if (((size_t) (csp->iob->eod - csp->iob->buf)) +
1890 (size_t) BUFFER_SIZE > csp->config->buffer_limit)
1894 log_error (LOG_LEVEL_ERROR,
1895 "Buffer size limit reached! Flushing and stepping back.");
1897 hdr = sed (server_patterns, add_server_headers, csp);
1900 /* FIXME Should handle error properly */
1901 log_error (LOG_LEVEL_FATAL,
1902 "Out of memory parsing server header");
1905 hdrlen = strlen (hdr);
1906 byte_count += hdrlen;
1908 if (write_socket (csp->cfd, hdr, hdrlen)
1909 || ((len = flush_socket (csp->cfd, csp)) < 0))
1911 log_error (LOG_LEVEL_CONNECT,
1912 "write header to client failed: %E");
1915 return JB_ERR_GENERIC;
1921 csp->content_filter = NULL;
1922 csp->all_headers_read = 1;
1928 if (write_socket (csp->cfd, buf, (size_t) len))
1930 log_error (LOG_LEVEL_ERROR, "write to client failed: %E");
1931 return JB_ERR_GENERIC;
1940 * we're still looking for the end of the
1941 * server's header ... (does that make header
1942 * parsing an "out of body experience" ?
1945 /* buffer up the data we just read */
1946 add_to_iob (csp, buf, len);
1948 /* get header lines from the iob */
1950 while ((p = get_header (csp)) != NULL)
1954 /* see following note */
1955 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1956 csp->ip_addr_str, csp->http->ocmd, byte_count);
1957 return JB_ERR_GENERIC;
1959 enlist (csp->headers, p);
1963 /* NOTE: there are no "empty" headers so
1964 * if the pointer `p' is not NULL we must
1965 * assume that we reached the end of the
1966 * buffer before we hit the end of the header.
1973 /* Well, we tried our MS IIS/5
1974 * hack and it didn't work.
1975 * The header is incomplete
1976 * and there isn't anything
1977 * we can do about it.
1979 log_error(LOG_LEVEL_CLF, "Incomplete Server Header: %s - - [%T] \"%s\" 200 %d",
1980 csp->ip_addr_str, csp->http->ocmd, byte_count);
1981 return JB_ERR_GENERIC;
1985 /* Since we have to wait for
1986 * more from the server before
1987 * we can parse the headers
1988 * we just continue here.
1994 /* we have now received the entire header.
1995 * filter it and send the result to the client
1998 hdr = sed (server_patterns, add_server_headers, csp);
2001 /* FIXME Should handle error properly */
2002 log_error (LOG_LEVEL_FATAL, "Out of memory parsing server header");
2007 #ifdef FEATURE_KILL_POPUPS
2008 /* Start blocking popups if appropriate. */
2010 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
2011 !csp->http->ssl && /* We talk plaintext */
2012 block_popups) /* Policy allows */
2014 block_popups_now = 1;
2016 * Filter the part of the body that came in the same read
2017 * as the last headers:
2019 filter_popups (csp->iob->cur, csp);
2022 #endif /* def FEATURE_KILL_POPUPS */
2024 /* Buffer and pcrs filter this if appropriate. */
2026 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
2027 !csp->http->ssl && /* We talk plaintext */
2028 pcrs_filter) /* Policy allows */
2030 csp->content_filter = pcrs_filter_response;
2033 /* Buffer and gif_deanimate this if appropriate. */
2035 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
2036 !csp->http->ssl && /* We talk plaintext */
2037 gif_deanimate) /* Policy allows */
2039 csp->content_filter = gif_deanimate_response;
2042 /* Buffer and jpg_inspect this if appropriate. */
2044 if ((csp->content_type & CT_JPEG) && /* It's an image/jpeg MIME-Type */
2045 !csp->http->ssl && /* We talk plaintext */
2046 jpeg_inspect) /* Policy allows */
2048 csp->content_filter = jpeg_inspect_response;
2052 * Only write if we're not buffering for content modification
2054 if (!csp->content_filter)
2056 /* write the server's (modified) header to
2057 * the client (along with anything else that
2058 * may be in the buffer)
2060 if (write_socket (csp->cfd, hdr, strlen (hdr))
2061 || ((len = flush_socket (csp->cfd, csp)) < 0))
2063 log_error (LOG_LEVEL_CONNECT,
2064 "write header to client failed: %E");
2066 /* the write failed, so don't bother
2067 * mentioning it to the client...
2068 * it probably can't hear us anyway.
2071 return JB_ERR_GENERIC;
2077 /* we're finished with the server's header */
2080 csp->all_headers_read = 1;
2082 /* If this was a MS IIS/5 hack then it means
2083 * the server has already closed the
2084 * connection. Nothing more to read. Time
2089 return JB_ERR_GENERIC ;
2093 } /* END relay_server_traffic() */
2096 /*********************************************************************
2098 * Function : read_client_headers
2100 * Description : read all the client headers, and fill in the
2104 * 1 : client_state structure
2105 * 2 : http_request structure
2108 * Returns : JB_ERR_OK - headers read and parsed ok
2109 * : other values - an error occurred.
2110 *********************************************************************/
2112 static jb_err read_client_headers( struct client_state *csp, struct http_request *http )
2117 char buf[BUFFER_SIZE];
2118 int len; /* for buffer sizes */
2121 * Read the client's request. Note that since we're not using select() we
2122 * could get blocked here if a client connected, then didn't say anything!
2124 * This will read all the client headers.
2130 len = read_socket(csp->cfd, buf, sizeof(buf));
2132 if (len <= 0) break; /* error! */
2134 add_to_iob(csp, buf, len);
2136 req = get_header(csp);
2140 break; /* no HTTP request! */
2145 continue; /* more to come! */
2148 /* When we get here we have read one header which is enough */
2149 /* to check whether the connection is allowed */
2157 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
2159 len = read_socket(csp->cfd, buf, sizeof(buf));
2162 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
2163 return JB_ERR_GENERIC;
2165 add_to_iob(csp, buf, len);
2169 if (p == NULL) break;
2171 enlist(csp->headers, p);
2176 parse_http_request(req, http, csp);
2179 if (http->cmd == NULL)
2181 strcpy(buf, CHEADER);
2182 write_socket(csp->cfd, buf, strlen(buf));
2184 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
2186 return JB_ERR_GENERIC;
2192 } /* END read_client_headers */
2195 /*********************************************************************
2197 * Function : process_client_headers
2199 * Description : Process client headers
2200 * FIXME: Add description of what we do here!
2203 * 1 : client_state structure
2204 * 2 : http_request structure
2207 * Returns : JB_ERR_OK - headers processed ok
2208 * : other values - an error occurred.
2209 *********************************************************************/
2211 static jb_err process_client_headers( struct client_state *csp, struct http_request *http )
2215 #ifdef FEATURE_FORCE_LOAD
2216 /* If this request contains the FORCE_PREFIX,
2217 * better get rid of it now and set the force flag --oes
2218 * Changed to use the http structure rather than the req field --jaa
2219 * FIXME: This isn't enough -- there is the path and referrer etc! *
2222 if (strstr(http->url, FORCE_PREFIX))
2224 strclean(http->url, FORCE_PREFIX);
2225 strclean(http->path, FORCE_PREFIX);
2226 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", http->url);
2227 csp->flags |= CSP_FLAG_FORCED;
2230 #endif /* def FEATURE_FORCE_LOAD */
2233 /* decide how to route the HTTP request */
2235 if ((http->fwd = forward_url(http, csp)) == NULL)
2237 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2238 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2241 /* build the http request to send to the server
2242 * we have to do one of the following:
2244 * create = use the original HTTP request to create a new
2245 * HTTP request that has either the path component
2246 * without the http://domainspec (w/path) or the
2247 * full orininal URL (w/url)
2248 * Note that the path and/or the HTTP version may
2249 * have been altered by now.
2251 * connect = Open a socket to the host:port of the server
2252 * and short-circuit server and client socket.
2254 * pass = Pass the request unchanged if forwarding a CONNECT
2255 * request to a parent proxy. Note that we'll be sending
2256 * the CFAIL message ourselves if connecting to the parent
2257 * fails, but we won't send a CSUCCEED message if it works,
2258 * since that would result in a double message (ours and the
2259 * parent's). After sending the request to the parent, we simply
2262 * here's the matrix:
2265 * +--------+--------+
2267 * 0 | create | connect|
2269 * Forwarding +--------+--------+
2271 * 1 | create | pass |
2273 * +--------+--------+
2278 * Determine the actions for this URL
2280 #ifdef FEATURE_TOGGLE
2281 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
2283 /* Most compatible set of actions (i.e. none) */
2284 init_current_action(csp->action);
2287 #endif /* ndef FEATURE_TOGGLE */
2289 url_actions(http, csp);
2297 * Downgrade http version from 1.1 to 1.0 if +downgrade
2300 if ( (http->ssl == 0)
2301 && (!strcmpic(http->ver, "HTTP/1.1"))
2302 && (csp->action->flags & ACTION_DOWNGRADE))
2305 http->ver = strdup("HTTP/1.0");
2307 if (http->ver == NULL)
2309 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
2314 * Save a copy of the original request for logging
2316 http->ocmd = strdup(http->cmd);
2318 if (http->ocmd == NULL)
2320 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
2324 * (Re)build the HTTP request for non-SSL requests.
2325 * If forwarding, use the whole URL, else, use only the path.
2331 http->cmd = strdup(http->gpc);
2332 string_append(&http->cmd, " ");
2334 if (http->fwd->forward_host)
2336 string_append(&http->cmd, http->url);
2340 string_append(&http->cmd, http->path);
2343 string_append(&http->cmd, " ");
2344 string_append(&http->cmd, http->ver);
2346 if (http->cmd == NULL)
2348 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
2351 enlist_first(csp->headers, http->cmd);
2355 * If the user has not supplied any wafers, and the user has not
2356 * told us to suppress the vanilla wafer, then send the vanilla wafer.
2358 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
2359 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
2361 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
2365 } /* process_client_headers */
2367 /*********************************************************************
2369 * Function : intercept_page
2371 * Description : Check whether to intercept page
2374 * 1 : client_state structure
2375 * 2 : http_request structure
2378 * Returns : JB_ERR_OK - Do NOT intercept this page
2379 * : JB_ERR_INTERCEPT - intercept this page
2380 * : all other values - an error occurred.
2381 *********************************************************************/
2382 static jb_err intercept_page( struct client_state *csp, struct http_request *http )
2385 /* Skeleton for HTTP response, if we should intercept the request */
2386 struct http_response *rsp;
2390 * These next lines are a little ugly, but they simplifies the if statements
2391 * below. Basically if TOGGLE, then we want the if to test if the
2392 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
2393 * then we want the if to test for CSP_FLAG_FORCED , else we don't
2395 #ifdef FEATURE_TOGGLE
2396 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
2397 #else /* ifndef FEATURE_TOGGLE */
2398 # define IS_TOGGLED_ON_AND
2399 #endif /* ndef FEATURE_TOGGLE */
2400 #ifdef FEATURE_FORCE_LOAD
2401 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
2402 #else /* ifndef FEATURE_FORCE_LOAD */
2403 # define IS_NOT_FORCED_AND
2404 #endif /* def FEATURE_FORCE_LOAD */
2406 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
2409 /* a CGI call was detected and answered */
2410 (NULL != (rsp = dispatch_cgi(csp)))
2412 /* or we are enabled and... */
2413 || (IS_ENABLED_AND (
2415 /* ..the request was blocked */
2416 ( NULL != (rsp = block_url(csp)))
2418 /* ..or untrusted */
2419 #ifdef FEATURE_TRUST
2420 || ( NULL != (rsp = trust_url(csp)))
2421 #endif /* def FEATURE_TRUST */
2423 /* ..or a fast redirect kicked in */
2424 #ifdef FEATURE_FAST_REDIRECTS
2425 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
2426 (NULL != (rsp = redirect_url(csp))))
2427 #endif /* def FEATURE_FAST_REDIRECTS */
2431 /* Write the answer to the client */
2432 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2433 || write_socket(csp->cfd, rsp->body, rsp->content_length))
2435 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2438 #ifdef FEATURE_STATISTICS
2439 /* Count as a rejected request */
2440 csp->flags |= CSP_FLAG_REJECTED;
2441 #endif /* def FEATURE_STATISTICS */
2443 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
2444 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
2445 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
2447 /* Clean up and return */
2448 free_http_response(rsp);
2449 return JB_ERR_INTERCEPT;
2452 /* When we get here the request doesn't need to be intercepted */
2456 /*********************************************************************
2458 * Function : open_forwarding_connection
2460 * Description : Check whether to intercept page
2463 * 1 : client_state structure
2464 * 2 : http_request structure
2466 * Returns : JB_ERR_OK - Connection opened ok
2467 * : all other values - an error occurred.
2468 *********************************************************************/
2469 static jb_err open_forwarding_connection(struct client_state *csp )
2471 struct http_response *rsp;
2473 #ifdef FEATURE_ACTIVITY_CONSOLE
2474 accumulate_stats(STATS_REQUEST, 1);
2475 #endif /* def FEATURE_ACTIVITY_CONSOLE */
2476 log_error(LOG_LEVEL_GPC, "%s%s", csp->http->hostport, csp->http->path);
2478 if (csp->http->fwd->forward_host)
2480 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
2481 csp->http->fwd->forward_host, csp->http->fwd->forward_port,
2482 csp->http->hostport);
2486 log_error(LOG_LEVEL_CONNECT, "to %s", csp->http->hostport);
2489 /* here we connect to the server, gateway, or the forwarder */
2491 csp->sfd = forwarded_connect(csp->http->fwd, csp->http, csp);
2493 if (csp->sfd == JB_INVALID_SOCKET)
2495 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
2496 csp->http->hostport);
2498 if (errno == EINVAL)
2500 rsp = error_response(csp, "no-such-domain", errno);
2502 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
2503 csp->ip_addr_str, csp->http->ocmd);
2507 rsp = error_response(csp, "connect-failed", errno);
2509 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
2510 csp->ip_addr_str, csp->http->ocmd);
2514 /* Write the answer to the client */
2517 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2518 || write_socket(csp->cfd, rsp->body, rsp->content_length))
2520 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
2524 free_http_response(rsp);
2525 return JB_ERR_GENERIC;
2528 log_error(LOG_LEVEL_CONNECT, "OK");
2531 } /* END open_forwarding_connection() */
2534 /*********************************************************************
2536 * Function : send_client_headers_to_server
2538 * Description : send the client headers (possibly modified) to the server
2541 * 1 : client_state structure
2542 * 2 : http_request structure
2545 * Returns : JB_ERR_OK - headers sent ok
2546 * : other values - an error occurred.
2547 *********************************************************************/
2549 static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http, char *hdr )
2552 struct http_response *rsp;
2554 if (http->fwd->forward_host || (http->ssl == 0))
2556 /* write the client's (modified) header to the server
2557 * (along with anything else that may be in the buffer)
2560 if (write_socket(csp->sfd, hdr, strlen(hdr))
2561 || (flush_socket(csp->sfd, csp) < 0))
2563 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
2566 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
2567 csp->ip_addr_str, http->ocmd);
2569 rsp = error_response(csp, "connect-failed", errno);
2573 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2574 || write_socket(csp->cfd, rsp->body, rsp->content_length))
2576 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2580 free_http_response(rsp);
2581 return JB_ERR_GENERIC;
2587 * We're running an SSL tunnel and we're not forwarding,
2588 * so just send the "connect succeeded" message to the
2589 * client, flush the rest, and get out of the way.
2591 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
2592 csp->ip_addr_str, http->ocmd);
2594 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
2602 } /* END send_client_headers_to_server */
2605 /*********************************************************************
2607 * Function : is_connect_request_allowed
2609 * Description : send the client headers (possibly modified) to the server
2612 * 1 : client_state structure
2616 * Returns : JB_ERR_OK - connect request allowed
2617 * : other values - connect request not allowed
2618 *********************************************************************/
2619 static jb_err is_connect_request_allowed( struct client_state *csp )
2622 * Check if a CONNECT request is allowable:
2623 * In the absence of a +limit-connect action, allow only port 443.
2624 * If there is an action, allow whatever matches the specificaton.
2629 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
2630 || (csp->action->flags & ACTION_LIMIT_CONNECT
2631 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
2633 char buf[BUFFER_SIZE];
2634 strcpy(buf, CFORBIDDEN);
2635 write_socket(csp->cfd, buf, strlen(buf));
2637 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
2638 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
2640 return JB_ERR_GENERIC;
2645 } /* END is_connect_request_allowed */