1 const char jcc_rcs[] = "$Id: jcc.c,v 2.6 2003/06/24 12:24:24 oes 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.6 2003/06/24 12:24:24 oes
37 * Added a line plus Fix-me as a reminder to fix broken force handling in trunk. Thanks to lionel for the hint
39 * Revision 2.5 2003/01/26 20:24:26 david__schmidt
40 * Updated activity console instrumentation locations
42 * Revision 2.4 2002/12/28 03:58:19 david__schmidt
43 * Initial drop of dashboard instrumentation - enabled with
44 * --enable-activity-console
46 * Revision 2.3 2002/07/18 22:06:12 jongfoster
47 * Trivial formatting changes
49 * Revision 2.2 2002/07/12 04:26:17 agotneja
50 * Re-factored 'chat()' to become understandable and maintainable as
51 * a first step in adding Transparent Proxy functionality.
53 * Added several new static functions in jcc.c, and moved some data
54 * parameters up into project.h to allow them to be passed between
57 * Revision 1.91 2002/04/08 20:35:58 swa
60 * Revision 1.90 2002/04/02 14:57:28 oes
61 * Made sending wafers independent of FEATURE_COOKIE_JAR
63 * Revision 1.89 2002/03/31 17:18:59 jongfoster
64 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
66 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
67 * More compiler warning message maintenance
69 * Revision 1.87 2002/03/26 22:29:54 swa
70 * we have a new homepage!
72 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
73 * Workaround for closing the jarfile before load_config() comes around again
75 * Revision 1.85 2002/03/24 15:23:33 jongfoster
78 * Revision 1.84 2002/03/24 13:25:43 swa
79 * name change related issues
81 * Revision 1.83 2002/03/16 23:54:06 jongfoster
82 * Adding graceful termination feature, to help look for memory leaks.
83 * If you enable this (which, by design, has to be done by hand
84 * editing config.h) and then go to http://i.j.b/die, then the program
85 * will exit cleanly after the *next* request. It should free all the
86 * memory that was used.
88 * Revision 1.82 2002/03/13 00:27:05 jongfoster
91 * Revision 1.81 2002/03/12 01:42:50 oes
92 * Introduced modular filters
94 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
95 * OS/2 port maintenance:
96 * - Fixed EMX build - it had decayed a little
97 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
98 * substituted a memset for now.
100 * Revision 1.79 2002/03/09 20:03:52 jongfoster
101 * - Making various functions return int rather than size_t.
102 * (Undoing a recent change). Since size_t is unsigned on
103 * Windows, functions like read_socket that return -1 on
104 * error cannot return a size_t.
106 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
107 * crashes, and also frequently caused JB to jump to 100%
108 * CPU and stay there. (Because it thought it had just
109 * read ((unsigned)-1) == 4Gb of data...)
111 * - The signature of write_socket has changed, it now simply
112 * returns success=0/failure=nonzero.
114 * - Trying to get rid of a few warnings --with-debug on
115 * Windows, I've introduced a new type "jb_socket". This is
116 * used for the socket file descriptors. On Windows, this
117 * is SOCKET (a typedef for unsigned). Everywhere else, it's
118 * an int. The error value can't be -1 any more, so it's
119 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
120 * Windows it maps to the #define INVALID_SOCKET.)
122 * - The signature of bind_port has changed.
124 * Revision 1.78 2002/03/08 21:35:04 oes
125 * Added optional group supplement to --user option. Will now use default group of user if no group given
127 * Revision 1.77 2002/03/07 03:52:06 oes
128 * - Fixed compiler warnings etc
129 * - Improved handling of failed DNS lookups
131 * Revision 1.76 2002/03/06 22:54:35 jongfoster
132 * Automated function-comment nitpicking.
134 * Revision 1.75 2002/03/06 10:02:19 oes
135 * Fixed stupid bug when --user was not given
137 * Revision 1.74 2002/03/06 00:49:31 jongfoster
138 * Fixing warning on Windows
139 * Making #ifdefs that refer to the same variable consistently
140 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
142 * Revision 1.73 2002/03/05 23:57:30 hal9
143 * Stray character 's' on line 1618 was breaking build.
145 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
146 * - Re-enable OS/2 building after new parms were added
147 * - Fix false out of memory report when resolving CGI templates when no IP
148 * address is available of failed attempt (a la no such domain)
150 * Revision 1.71 2002/03/05 18:13:56 oes
151 * Added --user option
153 * Revision 1.70 2002/03/05 04:52:42 oes
154 * Deleted non-errlog debugging code
156 * Revision 1.69 2002/03/04 23:50:00 jongfoster
157 * Splitting off bind_port() call into bind_port_helper(), with
160 * Revision 1.68 2002/03/04 20:17:32 oes
163 * Revision 1.67 2002/03/04 18:18:57 oes
164 * - Removed _DEBUG mode
165 * - Cleand up cmdline parsing
166 * - Introduced --no-daemon, --pidfile options
167 * - Cleaned up signal handling:
168 * - Terminate cleanly on INT, TERM and ABRT
169 * - Schedule logfile for re-opening on HUP
170 * - Ignore CHLD and PIPE
171 * - Leave the rest with their default handlers
172 * - Uniform handler registration
173 * - Added usage() function
174 * - Played styleguide police
176 * Revision 1.66 2002/03/03 15:06:55 oes
177 * Re-enabled automatic config reloading
179 * Revision 1.65 2002/03/03 14:49:11 oes
180 * Fixed CLF logging: Now uses client's original HTTP request
182 * Revision 1.64 2002/03/03 09:18:03 joergs
183 * Made jumbjuster work on AmigaOS again.
185 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
186 * Clean up a little CRLF unpleasantness that suddenly appeared
188 * Revision 1.62 2002/02/20 23:17:23 jongfoster
189 * Detecting some out-of memory conditions and exiting with a log message.
191 * Revision 1.61 2002/01/17 21:01:52 jongfoster
192 * Moving all our URL and URL pattern parsing code to urlmatch.c.
194 * Revision 1.60 2001/12/30 14:07:32 steudten
195 * - Add signal handling (unix)
196 * - Add SIGHUP handler (unix)
197 * - Add creation of pidfile (unix)
198 * - Add action 'top' in rc file (RH)
199 * - Add entry 'SIGNALS' to manpage
200 * - Add exit message to logfile (unix)
202 * Revision 1.59 2001/12/13 14:07:18 oes
203 * Fixed Bug: 503 error page now sent OK
205 * Revision 1.58 2001/11/30 23:37:24 jongfoster
206 * Renaming the Win32 config file to config.txt - this is almost the
207 * same as the corresponding UNIX name "config"
209 * Revision 1.57 2001/11/16 00:47:43 jongfoster
210 * Changing the tty-disconnection code to use setsid().
212 * Revision 1.56 2001/11/13 20:20:54 jongfoster
213 * Tabs->spaces, fixing a bug with missing {} around an if()
215 * Revision 1.55 2001/11/13 20:14:53 jongfoster
216 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
218 * Revision 1.54 2001/11/07 00:03:14 steudten
219 * Give reliable return value if an error
220 * occurs not just 0 with new daemon mode.
222 * Revision 1.53 2001/11/05 21:41:43 steudten
223 * Add changes to be a real daemon just for unix os.
224 * (change cwd to /, detach from controlling tty, set
225 * process group and session leader to the own process.
227 * Add some fatal-error log message for failed malloc().
228 * Add '-d' if compiled with 'configure --with-debug' to
229 * enable debug output.
231 * Revision 1.52 2001/10/26 20:11:20 jongfoster
232 * Fixing type mismatch
234 * Revision 1.51 2001/10/26 17:38:28 oes
237 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
238 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
239 * threads to call select() simultaneously. So, it's time to do a real, live,
240 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
241 * (native). Both versions will work, but using __OS2__ offers multi-threading.
243 * Revision 1.49 2001/10/23 21:41:35 jongfoster
244 * Added call to initialize the (statically-allocated of course)
245 * "out of memory" CGI response.
247 * Revision 1.48 2001/10/10 19:56:46 jongfoster
248 * Moving some code that wasn't cookie-related out of an #ifdef
251 * Revision 1.47 2001/10/10 16:44:36 oes
252 * Added CONNECT destination port limitation check
254 * Revision 1.46 2001/10/08 15:17:41 oes
255 * Re-enabled SSL forwarding
257 * Revision 1.45 2001/10/07 15:42:11 oes
258 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
260 * Moved downgrading of the HTTP version from parse_http_request to
261 * chat(), since we can't decide if it is necessary before we have
262 * determined the actions for the URL. The HTTP command is now
263 * *always* re-built so the repairs need no longer be special-cased.
265 * filter_popups now gets a csp pointer so it can raise the new
266 * CSP_FLAG_MODIFIED flag.
270 * Added configurable size limit for the IOB. If the IOB grows so
271 * large that the next read would exceed the limit, the header
272 * is generated, and the header & unfiltered buffer are flushed
273 * to the client. Chat then continues in non-buffering,
274 * non-filtering body mode.
276 * Revision 1.44 2001/10/02 18:13:57 oes
279 * Revision 1.43 2001/10/02 15:32:13 oes
280 * Moved generation of hdr
282 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
283 * Cleaning up 2 compiler warnings on OS/2.
285 * Revision 1.41 2001/09/16 17:05:14 jongfoster
286 * Removing unused #include showarg.h
288 * Revision 1.40 2001/09/16 15:41:45 jongfoster
289 * Fixing signed/unsigned comparison warning.
291 * Revision 1.39 2001/09/16 13:21:27 jongfoster
292 * Changes to use new list functions.
294 * Revision 1.38 2001/09/16 13:01:46 jongfoster
295 * Removing redundant function call that zeroed zalloc()'d memory.
297 * Revision 1.37 2001/09/10 11:12:24 oes
298 * Deleted unused variable
300 * Revision 1.36 2001/09/10 10:56:15 oes
301 * Silenced compiler warnings
303 * Revision 1.35 2001/07/31 14:44:22 oes
304 * Deleted unused size parameter from filter_popups()
306 * Revision 1.34 2001/07/30 22:08:36 jongfoster
307 * Tidying up #defines:
308 * - All feature #defines are now of the form FEATURE_xxx
309 * - Permanently turned off WIN_GUI_EDIT
310 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
312 * Revision 1.33 2001/07/29 19:32:00 jongfoster
313 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
315 * Revision 1.32 2001/07/29 18:47:05 jongfoster
316 * Adding missing #include "loadcfg.h"
318 * Revision 1.31 2001/07/29 12:17:48 oes
319 * Applied pthread fix by Paul Lieverse
321 * Revision 1.30 2001/07/25 22:57:13 jongfoster
322 * __BEOS__ no longer overrides FEATURE_PTHREAD.
323 * This is because FEATURE_PTHREAD will soon be widely used, so I
324 * want to keep it simple.
326 * Revision 1.29 2001/07/24 12:47:06 oes
327 * Applied BeOS support update by Eugenia
329 * Revision 1.28 2001/07/23 13:26:12 oes
330 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
332 * Revision 1.27 2001/07/19 19:09:47 haroon
333 * - Added code to take care of the situation where while processing the first
334 * server response (which includes the server header), after finding the end
335 * of the headers we were not looking past the end of the headers for
336 * content modification. I enabled it for filter_popups.
337 * Someone else should look to see if other similar operations should be
338 * done to the discarded portion of the buffer.
340 * Note 2001/07/20: No, the other content modification mechanisms will process
341 * the whole iob later anyway. --oes
343 * Revision 1.26 2001/07/18 12:31:36 oes
346 * Revision 1.25 2001/07/15 19:43:49 jongfoster
347 * Supports POSIX threads.
348 * Also removed some unused #includes.
350 * Revision 1.24 2001/07/13 14:00:40 oes
351 * - Generic content modification scheme:
352 * Each feature has its own applicability flag that is set
353 * from csp->action->flags.
354 * Replaced the "filtering" int flag , by a function pointer
355 * "content_filter" to the function that will do the content
356 * modification. If it is != NULL, the document will be buffered
357 * and processed through *content_filter, which must set
358 * csp->content_length and return a modified copy of the body
359 * or return NULL (on failiure).
360 * - Changed csp->is_text to the more generic bitmap csp->content_type
361 * which can currently take the valued CT_TEXT or CT_GIF
363 * - Removed all #ifdef PCRS
365 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
366 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
367 * the `block_acl' call. This prevents a compilation error when the user
368 * does not wish to use the "ACL" feature.
370 * Revision 1.22 2001/06/29 21:45:41 oes
371 * Indentation, CRLF->LF, Tab-> Space
373 * Revision 1.21 2001/06/29 13:29:36 oes
374 * - Cleaned up, improved comments
375 * - Unified all possible interceptors (CGI,
376 * block, trust, fast_redirect) in one
377 * place, with one (CGI) answer generation
378 * mechansim. Much clearer now.
379 * - Removed the GIF image generation, which
380 * is now done in filters.c:block_url()
381 * - Made error conditions like domain lookup
382 * failiure or (various) problems while talking
383 * to the server use cgi.c:error_response()
384 * instead of generating HTML/HTTP in chat() (yuck!)
385 * - Removed logentry from cancelled commit
387 * Revision 1.20 2001/06/09 10:55:28 jongfoster
388 * Changing BUFSIZ ==> BUFFER_SIZE
390 * Revision 1.19 2001/06/07 23:12:52 jongfoster
391 * Replacing function pointer in struct gateway with a directly
392 * called function forwarded_connect().
393 * Replacing struct gateway with struct forward_spec
395 * Revision 1.18 2001/06/03 19:12:16 oes
396 * introduced new cgi handling
398 * Revision 1.17 2001/06/01 20:07:23 jongfoster
399 * Now uses action +image-blocker{} rather than config->tinygif
401 * Revision 1.16 2001/06/01 18:49:17 jongfoster
402 * Replaced "list_share" with "list" - the tiny memory gain was not
403 * worth the extra complexity.
405 * Revision 1.15 2001/05/31 21:24:47 jongfoster
406 * Changed "permission" to "action" throughout.
407 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
408 * Moved vanilla wafer check into chat(), since we must now
409 * decide whether or not to add it based on the URL.
411 * Revision 1.14 2001/05/29 20:14:01 joergs
412 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
415 * Revision 1.13 2001/05/29 09:50:24 jongfoster
416 * Unified blocklist/imagelist/permissionslist.
417 * File format is still under discussion, but the internal changes
420 * Also modified interceptor behaviour:
421 * - We now intercept all URLs beginning with one of the following
422 * prefixes (and *only* these prefixes):
424 * * http://ijbswa.sf.net/config/
425 * * http://ijbswa.sourceforge.net/config/
426 * - New interceptors "home page" - go to http://i.j.b/ to see it.
427 * - Internal changes so that intercepted and fast redirect pages
428 * are not replaced with an image.
429 * - Interceptors now have the option to send a binary page direct
430 * to the client. (i.e. ijb-send-banner uses this)
431 * - Implemented show-url-info interceptor. (Which is why I needed
432 * the above interceptors changes - a typical URL is
433 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
434 * The previous mechanism would not have intercepted that, and
435 * if it had been intercepted then it then it would have replaced
438 * Revision 1.12 2001/05/27 22:17:04 oes
440 * - re_process_buffer no longer writes the modified buffer
441 * to the client, which was very ugly. It now returns the
442 * buffer, which it is then written by chat.
444 * - content_length now adjusts the Content-Length: header
445 * for modified documents rather than crunch()ing it.
446 * (Length info in csp->content_length, which is 0 for
447 * unmodified documents)
449 * - For this to work, sed() is called twice when filtering.
451 * Revision 1.11 2001/05/26 17:27:53 jongfoster
452 * Added support for CLF and fixed LOG_LEVEL_LOG.
453 * Also did CRLF->LF fix of my previous patch.
455 * Revision 1.10 2001/05/26 15:26:15 jongfoster
456 * ACL feature now provides more security by immediately dropping
457 * connections from untrusted hosts.
459 * Revision 1.9 2001/05/26 00:28:36 jongfoster
460 * Automatic reloading of config file.
461 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
462 * Most of the global variables have been moved to a new
463 * struct configuration_spec, accessed through csp->config->globalname
464 * Most of the globals remaining are used by the Win32 GUI.
466 * Revision 1.8 2001/05/25 22:43:18 jongfoster
467 * Fixing minor memory leak and buffer overflow.
469 * Revision 1.7 2001/05/25 22:34:30 jongfoster
472 * Revision 1.6 2001/05/23 00:13:58 joergs
473 * AmigaOS support fixed.
475 * Revision 1.5 2001/05/22 18:46:04 oes
477 * - Enabled filtering banners by size rather than URL
478 * by adding patterns that replace all standard banner
479 * sizes with the "Junkbuster" gif to the re_filterfile
481 * - Enabled filtering WebBugs by providing a pattern
482 * which kills all 1x1 images
484 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
485 * which is selected by the (nonstandard and therefore
486 * capital) letter 'U' in the option string.
487 * It causes the quantifiers to be ungreedy by default.
488 * Appending a ? turns back to greedy (!).
490 * - Added a new interceptor ijb-send-banner, which
491 * sends back the "Junkbuster" gif. Without imagelist or
492 * MSIE detection support, or if tinygif = 1, or the
493 * URL isn't recognized as an imageurl, a lame HTML
494 * explanation is sent instead.
496 * - Added new feature, which permits blocking remote
497 * script redirects and firing back a local redirect
499 * The feature is conditionally compiled, i.e. it
500 * can be disabled with --disable-fast-redirects,
501 * plus it must be activated by a "fast-redirects"
502 * line in the config file, has its own log level
503 * and of course wants to be displayed by show-proxy-args
504 * Note: Boy, all the #ifdefs in 1001 locations and
505 * all the fumbling with configure.in and acconfig.h
506 * were *way* more work than the feature itself :-(
508 * - Because a generic redirect template was needed for
509 * this, tinygif = 3 now uses the same.
511 * - Moved GIFs, and other static HTTP response templates
516 * - Removed some >400 CRs again (Jon, you really worked
519 * Revision 1.4 2001/05/21 19:34:01 jongfoster
520 * Made failure to bind() a fatal error.
522 * Revision 1.3 2001/05/20 01:21:20 jongfoster
523 * Version 2.9.4 checkin.
524 * - Merged popupfile and cookiefile, and added control over PCRS
525 * filtering, in new "permissionsfile".
526 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
527 * file error you now get a message box (in the Win32 GUI) rather
528 * than the program exiting with no explanation.
529 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
531 * - Removed tabs from "config"
532 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
533 * - Bumped up version number.
535 * Revision 1.2 2001/05/17 22:34:44 oes
536 * - Added hint on GIF char array generation to jcc.c
537 * - Cleaned CRLF's from the sources and related files
538 * - Repaired logging for REF and FRC
540 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
541 * Initial import of version 2.9.3 source tree
544 *********************************************************************/
550 #include <sys/types.h>
557 #ifdef FEATURE_PTHREAD
559 #endif /* def FEATURE_PTHREAD */
562 # ifndef FEATURE_PTHREAD
566 # include <windows.h>
567 # include <process.h>
568 # endif /* ndef FEATURE_PTHREAD */
571 # ifndef _WIN_CONSOLE
573 # endif /* ndef _WIN_CONSOLE */
575 #else /* ifndef _WIN32 */
577 # if !defined (__OS2__)
579 # include <sys/wait.h>
580 # endif /* ndef __OS2__ */
581 # include <sys/time.h>
582 # include <sys/stat.h>
583 # include <sys/ioctl.h>
586 #include <sys/termios.h>
597 # include <socket.h> /* BeOS has select() for sockets only. */
598 # include <OS.h> /* declarations for threads and stuff. */
601 # if defined(__EMX__) || defined(__OS2__)
602 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
607 #define bzero(B,N) memset(B,0x00,n)
622 #include "killpopup.h"
623 #include "miscutil.h"
625 #include "jbsockets.h"
630 #include "urlmatch.h"
631 #ifdef FEATURE_ACTIVITY_CONSOLE
633 #endif /* def FEATURE_ACTIVITY_CONSOLE */
635 const char jcc_h_rcs[] = JCC_H_VERSION;
636 const char project_h_rcs[] = PROJECT_H_VERSION;
639 struct client_state clients[1];
640 struct file_list files[1];
642 #ifdef FEATURE_STATISTICS
643 int urls_read = 0; /* total nr of urls read inc rejected */
644 int urls_rejected = 0; /* total nr of urls rejected */
645 #endif /* def FEATURE_STATISTICS */
647 #ifdef FEATURE_GRACEFUL_TERMINATION
651 static void listen_loop(void);
652 static void chat(struct client_state *csp);
653 static jb_err relay_server_traffic( struct client_state *csp ) ;
654 static jb_err read_client_headers( struct client_state *csp, struct http_request *http ) ;
655 static jb_err process_client_headers( struct client_state *csp, struct http_request *http ) ;
656 static jb_err intercept_page( struct client_state *csp, struct http_request *http );
657 static jb_err open_forwarding_connection( struct client_state *csp );
658 static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http, char* hdr );
659 static jb_err is_connect_request_allowed( struct client_state *csp ) ;
663 void serve(struct client_state *csp);
664 #else /* ifndef AMIGA */
665 static void serve(struct client_state *csp);
666 #endif /* def AMIGA */
669 static int32 server_thread(void *data);
670 #endif /* def __BEOS__ */
673 #define sleep(N) Sleep(((N) * 1000))
677 #define sleep(N) DosSleep(((N) * 100))
682 * Hit OSX over the head with a hammer. Protect all *_r functions.
684 pthread_mutex_t gmtime_mutex;
685 pthread_mutex_t localtime_mutex;
686 pthread_mutex_t gethostbyaddr_mutex;
687 pthread_mutex_t gethostbyname_mutex;
688 #endif /* def OSX_DARWIN */
690 #if defined(unix) || defined(__EMX__)
691 const char *basedir = NULL;
692 const char *pidfile = NULL;
693 int received_hup_signal = 0;
694 #endif /* defined unix */
696 /* The vanilla wafer. */
697 static const char VANILLA_WAFER[] =
698 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
699 "Do_not_send_me_any_copyrighted_information_other_than_the_"
700 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
701 "In_particular_do_not_send_me_any_cookies_that_"
702 "are_subject_to_a_claim_of_copyright_by_anybody._"
703 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
704 "(copyright_or_otherwise)_applying_to_any_cookie._";
707 * HTTP header sent when doing HTTPS tunnelling ("CONNECT" method).
709 static const char CSUCCEED[] =
710 "HTTP/1.0 200 Connection established\n"
711 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
715 * HTTP reply sent when the browser sends something unintelligible.
717 static const char CHEADER[] =
718 "HTTP/1.0 400 Invalid header received from browser\r\n\r\n";
722 * HTTP reply sent when the browser tries to tunnel ("CONNECT") to something
723 * other than a HTTPS port (as defined by +limit-connect).
725 static const char CFORBIDDEN[] =
726 "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";
728 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
729 /*********************************************************************
731 * Function : sig_handler
733 * Description : Signal handler for different signals.
734 * Exit gracefully on ABRT, TERM and INT
735 * or set a flag that will cause the errlog
736 * to be reopened by the main thread on HUP.
739 * 1 : the_signal = the signal cause this function to call
743 *********************************************************************/
744 static void sig_handler(int the_signal)
751 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
759 received_hup_signal = 1;
764 * We shouldn't be here, unless we catch signals
765 * in main() that we can't handle here!
767 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
775 /*********************************************************************
779 * Description : Once a connection to the client has been accepted,
780 * this function is called (via serve()) to handle the
781 * main business of the communication. When this
782 * function returns, the caller must close the client
786 * 1 : csp = Current client state (buffers, headers, etc...)
790 *********************************************************************/
791 static void chat(struct client_state *csp)
795 char buf[BUFFER_SIZE];
796 int len; /* for buffer sizes */
802 struct http_request *http;
806 if (read_client_headers(csp, http ) != JB_ERR_OK )
810 /* Process the client headers */
811 if (process_client_headers(csp, http) != JB_ERR_OK)
815 /* Check if this connection request is permitted */
816 if (is_connect_request_allowed(csp) != JB_ERR_OK)
820 * We have a valid and legit request. Now, check to see if we need to
823 if (intercept_page(csp, http) != JB_ERR_OK)
827 * The page passed the intercept routine, so open a forwarding
828 * connection for conversation
830 if (open_forwarding_connection(csp) != JB_ERR_OK )
835 hdr = sed(client_patterns, add_client_headers, csp);
838 /* FIXME Should handle error properly */
839 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
842 /* FIXME - where should this go, logically ? */
843 list_remove_all(csp->headers);
846 if (send_client_headers_to_server(csp, http, hdr) != JB_ERR_OK)
850 /* we're finished with the client's header */
853 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
855 /* pass data between the client and server
856 * until one or the other shuts down the connection.
859 /* Set the flag for reading headers to False */
860 /* This is used in relay_server_traffic */
861 csp->all_headers_read = 0 ;
865 jb_err tmp_ret_val = JB_ERR_GENERIC ;
869 * FD_ZERO here seems to point to an errant macro which crashes.
870 * So do this by hand for now...
872 memset(&rfds,0x00,sizeof(fd_set));
876 FD_SET(csp->cfd, &rfds);
877 FD_SET(csp->sfd, &rfds);
879 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
883 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
888 * This is the body of the browser's request.
889 * Just read it and write it.
892 if (FD_ISSET(csp->cfd, &rfds))
894 len = read_socket(csp->cfd, buf, sizeof(buf));
898 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
899 csp->ip_addr_str, http->ocmd, byte_count);
903 if (write_socket(csp->sfd, buf, (size_t)len))
905 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
912 * Check if the server wants to talk, and if so, converse.
915 if (FD_ISSET(csp->sfd, &rfds))
916 tmp_ret_val = relay_server_traffic(csp) ;
919 if (tmp_ret_val == JB_ERR_OK)
924 /* We should never get here! */
925 log_error(LOG_LEVEL_FATAL, "chat() : logic error in for() loop" ) ;
929 /*********************************************************************
933 * Description : This is little more than chat. We only "serve" to
934 * to close any socket that chat may have opened.
937 * 1 : csp = Current client state (buffers, headers, etc...)
941 *********************************************************************/
943 void serve(struct client_state *csp)
944 #else /* ifndef AMIGA */
945 static void serve(struct client_state *csp)
946 #endif /* def AMIGA */
949 close_socket(csp->cfd);
951 if (csp->sfd != JB_INVALID_SOCKET)
953 close_socket(csp->sfd);
956 csp->flags &= ~CSP_FLAG_ACTIVE;
962 /*********************************************************************
964 * Function : server_thread
966 * Description : We only exist to call `serve' in a threaded environment.
969 * 1 : data = Current client state (buffers, headers, etc...)
971 * Returns : Always 0.
973 *********************************************************************/
974 static int32 server_thread(void *data)
976 serve((struct client_state *) data);
983 /*********************************************************************
987 * Description : Print usage info & exit.
989 * Parameters : Pointer to argv[0] for identifying ourselves
993 *********************************************************************/
994 void usage(const char *myname)
996 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
997 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
998 "Aborting.\n", myname);
1005 /*********************************************************************
1009 * Description : Load the config file and start the listen loop.
1010 * This function is a lot more *sane* with the `load_config'
1011 * and `listen_loop' functions; although it stills does
1012 * a *little* too much for my taste.
1015 * 1 : argc = Number of parameters (including $0).
1016 * 2 : argv = Array of (char *)'s to the parameters.
1018 * Returns : 1 if : can't open config file, unrecognized directive,
1019 * stats requested in multi-thread mode, can't open the
1020 * log file, can't open the jar file, listen port is invalid,
1021 * any load fails, and can't bind port.
1023 * Else main never returns, the process must be signaled
1024 * to terminate execution. Or, on Windows, use the
1025 * "File", "Exit" menu option.
1027 *********************************************************************/
1029 int real_main(int argc, const char *argv[])
1031 int main(int argc, const char *argv[])
1036 struct passwd *pw = NULL;
1037 struct group *grp = NULL;
1045 #if !defined(_WIN32)
1053 * Parse the command line arguments
1055 while (++argc_pos < argc)
1057 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1059 if (strcmp(argv[argc_pos], "--help") == 0)
1064 else if(strcmp(argv[argc_pos], "--version") == 0)
1066 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1070 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1075 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1077 if (++argc_pos == argc) usage(argv[0]);
1078 pidfile = strdup(argv[argc_pos]);
1081 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1083 if (++argc_pos == argc) usage(argv[argc_pos]);
1085 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1088 if (NULL == (grp = getgrnam(p)))
1090 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1094 if (NULL == (pw = getpwnam(argv[argc_pos])))
1096 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1099 if (p != NULL) *--p = '\0';
1101 #endif /* defined(unix) */
1103 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1105 configfile = argv[argc_pos];
1108 } /* -END- while (more arguments) */
1111 if ( *configfile != '/' )
1115 /* make config-filename absolute here */
1116 if ( !(basedir = getcwd( NULL, 1024 )))
1118 perror("get working dir failed");
1122 if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1124 perror("malloc failed");
1127 strcpy( abs_file, basedir );
1128 strcat( abs_file, "/" );
1129 strcat( abs_file, configfile );
1130 configfile = abs_file;
1132 #endif /* defined unix */
1139 #elif defined(_WIN32)
1145 * Prepare global mutex semaphores
1147 pthread_mutex_init(&gmtime_mutex,0);
1148 pthread_mutex_init(&localtime_mutex,0);
1149 pthread_mutex_init(&gethostbyaddr_mutex,0);
1150 pthread_mutex_init(&gethostbyname_mutex,0);
1151 #endif /* def OSX_DARWIN */
1154 * Unix signal handling
1156 * Catch the abort, interrupt and terminate signals for a graceful exit
1157 * Catch the hangup signal so the errlog can be reopened.
1158 * Ignore the broken pipe and child signals
1159 * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
1161 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1164 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1165 const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1167 for (idx = 0; catched_signals[idx] != 0; idx++)
1169 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1171 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1175 for (idx = 0; ignored_signals[idx] != 0; idx++)
1177 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1179 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1184 #else /* ifdef _WIN32 */
1185 # ifdef _WIN_CONSOLE
1187 * We *are* in a windows console app.
1188 * Print a verbose messages about FAQ's and such
1190 printf(win32_blurb);
1191 # endif /* def _WIN_CONSOLE */
1192 #endif /* def _WIN32 */
1195 /* Initialize the CGI subsystem */
1196 cgi_init_error_messages();
1199 * If runnig on unix and without the --nodaemon
1200 * option, become a daemon. I.e. fork, detach
1201 * from tty and get process group leadership
1214 if ( pid < 0 ) /* error */
1219 else if ( pid != 0 ) /* parent */
1224 * must check for errors
1225 * child died due to missing files aso
1228 wpid = waitpid( pid, &status, WNOHANG );
1237 /* Should be more portable, but not as well tested */
1242 #else /* ndef __FreeBSD__ */
1244 #endif /* ndef __FreeBSD__ */
1245 fd = open("/dev/tty", O_RDONLY);
1248 /* no error check here */
1249 ioctl( fd, TIOCNOTTY,0 );
1253 /* FIXME: should close stderr (fd 2) here too, but the test
1255 * and load config file is done in listen_loop() and puts
1256 * some messages on stderr there.
1263 } /* -END- if (!no_daemon) */
1266 * As soon as we have written the PID file, we can switch
1267 * to the user and group ID indicated by the --user option
1273 if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1275 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1277 if (setuid(pw->pw_uid))
1279 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1283 #endif /* defined unix */
1293 /*********************************************************************
1295 * Function : bind_port_helper
1297 * Description : Bind the listen port. Handles logging, and aborts
1301 * 1 : config = Privoxy configuration. Specifies port
1304 * Returns : Port that was opened.
1306 *********************************************************************/
1307 static jb_socket bind_port_helper(struct configuration_spec * config)
1312 if ( (config->haddr != NULL)
1313 && (config->haddr[0] == '1')
1314 && (config->haddr[1] == '2')
1315 && (config->haddr[2] == '7')
1316 && (config->haddr[3] == '.') )
1318 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1321 else if (config->haddr == NULL)
1323 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1328 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1329 config->hport, config->haddr);
1332 result = bind_port(config->haddr, config->hport, &bfd);
1339 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1340 "There may be another Privoxy or some other "
1341 "proxy running on port %d",
1342 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1343 config->hport, config->hport);
1346 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1347 "The hostname is not resolvable",
1348 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1351 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
1352 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1355 /* shouldn't get here */
1356 return JB_INVALID_SOCKET;
1359 config->need_bind = 0;
1365 /*********************************************************************
1367 * Function : listen_loop
1369 * Description : bind the listen port and enter a "FOREVER" listening loop.
1375 *********************************************************************/
1376 static void listen_loop(void)
1378 struct client_state *csp = NULL;
1380 struct configuration_spec * config;
1382 config = load_config();
1384 bfd = bind_port_helper(config);
1386 #ifdef FEATURE_ACTIVITY_CONSOLE
1387 init_stats_config(config);
1388 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1390 #ifdef FEATURE_GRACEFUL_TERMINATION
1391 while (!g_terminate)
1396 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1397 while (waitpid(-1, NULL, WNOHANG) > 0)
1399 /* zombie children */
1401 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1404 * Free data that was used by died threads
1410 * Re-open the errlog after HUP signal
1412 if (received_hup_signal)
1414 init_error_log(Argv[0], config->logfile, config->debug);
1415 received_hup_signal = 0;
1420 #ifdef FEATURE_COOKIE_JAR
1422 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
1423 * already open. I think unload_configfile() is not being run, which should do
1424 * this work. Until that can get resolved, we'll use this workaround.
1426 * [Note from Jon: We don't unload_configfile() until all existing threads have
1427 * exited - they're likely to hang aroung transferring data to the browser.]
1431 if (csp->config->jar)
1433 fclose(csp->config->jar);
1434 csp->config->jar = NULL;
1436 #endif /* FEATURE_COOKIE_JAR */
1437 #endif /* __OS2__ */
1439 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1441 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1445 csp->flags |= CSP_FLAG_ACTIVE;
1446 csp->sfd = JB_INVALID_SOCKET;
1448 csp->config = config = load_config();
1450 if ( config->need_bind )
1453 * Since we were listening to the "old port", we will not see
1454 * a "listen" param change until the next IJB request. So, at
1455 * least 1 more request must be made for us to find the new
1456 * setting. I am simply closing the old socket and binding the
1459 * Which-ever is correct, we will serve 1 more page via the
1460 * old settings. This should probably be a "show-proxy-args"
1461 * request. This should not be a so common of an operation
1462 * that this will hurt people's feelings.
1467 bfd = bind_port_helper(config);
1470 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1472 if (!accept_connection(csp, bfd))
1474 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1487 log_error(LOG_LEVEL_CONNECT, "OK");
1490 #ifdef FEATURE_TOGGLE
1493 csp->flags |= CSP_FLAG_TOGGLED_ON;
1495 #endif /* def FEATURE_TOGGLE */
1497 #ifdef FEATURE_ACTIVITY_CONSOLE
1498 update_stats_config(config);
1499 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1501 if (run_loader(csp))
1503 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1504 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1508 if (block_acl(NULL,csp))
1510 #ifdef FEATURE_ACTIVITY_CONSOLE
1511 accumulate_stats(STATS_ACL_RESTRICT,1);
1512 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1513 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1514 close_socket(csp->cfd);
1518 #endif /* def FEATURE_ACL */
1520 /* add it to the list of clients */
1521 csp->next = clients->next;
1522 clients->next = csp;
1524 if (config->multi_threaded)
1528 /* this is a switch () statment in the C preprocessor - ugh */
1529 #undef SELECTED_ONE_OPTION
1531 /* Use Pthreads in preference to native code */
1532 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1533 #define SELECTED_ONE_OPTION
1535 pthread_t the_thread;
1536 pthread_attr_t attrs;
1538 pthread_attr_init(&attrs);
1539 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1540 child_id = (pthread_create(&the_thread, &attrs,
1541 (void*)serve, csp) ? -1 : 0);
1542 pthread_attr_destroy(&attrs);
1546 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1547 #define SELECTED_ONE_OPTION
1548 child_id = _beginthread(
1549 (void (*)(void *))serve,
1554 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1555 #define SELECTED_ONE_OPTION
1556 child_id = _beginthread(
1557 (void(* _Optlink)(void*))serve,
1563 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1564 #define SELECTED_ONE_OPTION
1566 thread_id tid = spawn_thread
1567 (server_thread, "server", B_NORMAL_PRIORITY, csp);
1569 if ((tid >= 0) && (resume_thread(tid) == B_OK))
1571 child_id = (int) tid;
1580 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1581 #define SELECTED_ONE_OPTION
1582 csp->cfd = ReleaseSocket(csp->cfd, -1);
1583 if((child_id = (int)CreateNewProcTags(
1584 NP_Entry, (ULONG)server_thread,
1585 NP_Output, Output(),
1586 NP_CloseOutput, FALSE,
1587 NP_Name, (ULONG)"privoxy child",
1588 NP_StackSize, 200*1024,
1592 ((struct Task *)child_id)->tc_UserData = csp;
1593 Signal((struct Task *)child_id, SIGF_SINGLE);
1598 #if !defined(SELECTED_ONE_OPTION)
1601 /* This block is only needed when using fork().
1602 * When using threads, the server thread was
1603 * created and run by the call to _beginthread().
1605 if (child_id == 0) /* child */
1611 else if (child_id > 0) /* parent */
1613 /* in a fork()'d environment, the parent's
1614 * copy of the client socket and the CSP
1618 #if !defined(_WIN32) && defined(__CYGWIN__)
1620 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1621 close_socket(csp->cfd);
1622 csp->flags &= ~CSP_FLAG_ACTIVE;
1626 #undef SELECTED_ONE_OPTION
1627 /* end of cpp switch () */
1629 if (child_id < 0) /* failed */
1631 char buf[BUFFER_SIZE];
1633 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1635 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
1637 write_socket(csp->cfd, buf, strlen(buf));
1638 close_socket(csp->cfd);
1639 csp->flags &= ~CSP_FLAG_ACTIVE;
1650 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
1652 /* Clean up. Aim: free all memory (no leaks) */
1653 #ifdef FEATURE_GRACEFUL_TERMINATION
1655 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
1657 unload_current_config_file();
1658 unload_current_actions_file();
1659 unload_current_re_filterfile();
1660 #ifdef FEATURE_TRUST
1661 unload_current_trust_file();
1664 if (config->multi_threaded)
1671 } while ((clients->next != NULL) && (--i > 0));
1675 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
1684 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
1685 /* Cleanup - remove taskbar icon etc. */
1690 #endif /* FEATURE_GRACEFUL_TERMINATION */
1694 /*********************************************************************
1696 * Function : relay_server_traffic
1698 * Description : receive traffic from the server and relay it
1699 * to the client, with some processing
1702 * 1 : client_state structure
1705 * Returns : JB_ERR_OK if there may be more work
1706 * : other values for errors
1708 **********************************************************************/
1710 static jb_err relay_server_traffic( struct client_state *csp )
1712 #ifdef FEATURE_KILL_POPUPS
1713 int block_popups; /* bool, 1==will block popups */
1714 int block_popups_now = 0; /* bool, 1==currently blocking popups */
1715 #endif /* def FEATURE_KILL_POPUPS */
1717 char buf[BUFFER_SIZE];
1718 int len; /* for buffer sizes */
1719 int ms_iis5_hack = 0;
1724 /* Skeleton for HTTP response, if we should intercept the request */
1725 struct http_response *rsp;
1727 int pcrs_filter; /* bool, 1==will filter through pcrs */
1728 int gif_deanimate; /* bool, 1==will deanimate gifs */
1730 #ifdef FEATURE_KILL_POPUPS
1731 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1732 #endif /* def FEATURE_KILL_POPUPS */
1734 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
1735 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1737 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1741 len = read_socket (csp->sfd, buf, sizeof (buf) - 1);
1745 log_error (LOG_LEVEL_ERROR, "read from: %s failed: %E", csp->http->host);
1747 log_error (LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1748 csp->ip_addr_str, csp->http->ocmd);
1750 rsp = error_response (csp, "connect-failed", errno);
1754 if (write_socket (csp->cfd, rsp->head, rsp->head_length)
1755 || write_socket (csp->cfd, rsp->body, rsp->content_length))
1757 log_error (LOG_LEVEL_ERROR, "write to: %s failed: %E",
1762 free_http_response (rsp);
1763 return JB_ERR_GENERIC;
1766 /* Add a trailing zero. This lets filter_popups
1767 * use string operations.
1771 #ifdef FEATURE_KILL_POPUPS
1772 /* Filter the popups on this read. */
1773 if (block_popups_now)
1775 filter_popups (buf, csp);
1777 #endif /* def FEATURE_KILL_POPUPS */
1780 /* Normally, this would indicate that we've read
1781 * as much as the server has sent us and we can
1782 * close the client connection. However, Microsoft
1783 * in its wisdom has released IIS/5 with a bug that
1784 * prevents it from sending the trailing \r\n in
1785 * a 302 redirect header (and possibly other headers).
1786 * To work around this if we've haven't parsed
1787 * a full header we'll append a trailing \r\n
1788 * and see if this now generates a valid one.
1790 * This hack shouldn't have any impacts. If we've
1791 * already transmitted the header or if this is a
1792 * SSL connection, then we won't bother with this
1793 * hack. So we only work on partially received
1794 * headers. If we append a \r\n and this still
1795 * doesn't generate a valid header, then we won't
1796 * transmit anything to the client.
1801 if (csp->all_headers_read || csp->http->ssl)
1804 * If we have been buffering up the document,
1805 * now is the time to apply content modification
1806 * and send the result to the client.
1808 if (csp->content_filter)
1811 * If the content filter fails, use the original
1812 * buffer and length.
1813 * (see p != NULL ? p : csp->iob->cur below)
1815 if (NULL == (p = (*csp->content_filter) (csp)))
1817 csp->content_length = csp->iob->eod - csp->iob->cur;
1820 hdr = sed (server_patterns, add_server_headers, csp);
1823 /* FIXME Should handle error properly */
1824 log_error (LOG_LEVEL_FATAL,
1825 "Out of memory parsing server header");
1829 if (write_socket (csp->cfd, hdr, strlen (hdr))
1830 || write_socket (csp->cfd, p != NULL ? p : csp->iob->cur,
1831 csp->content_length))
1833 log_error (LOG_LEVEL_ERROR,
1834 "write modified content to client failed: %E");
1835 return JB_ERR_GENERIC;
1844 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1845 csp->ip_addr_str, csp->http->ocmd, byte_count);
1846 return JB_ERR_GENERIC;
1850 * This is NOT the body, so
1851 * Let's pretend the server just sent us a blank line.
1853 len = sprintf (buf, "\r\n");
1856 * Now, let the normal header parsing algorithm below do its
1857 * job. If it fails, we'll exit instead of continuing.
1864 * If this is an SSL connection or we're in the body
1865 * of the server document, just write it to the client,
1866 * unless we need to buffer the body for later content-filtering
1869 if (csp->all_headers_read || csp->http->ssl)
1871 if (csp->content_filter)
1873 add_to_iob (csp, buf, len);
1876 * If the buffer limit will be reached on the next read,
1877 * switch to non-filtering mode, i.e. make & write the
1878 * header, flush the socket and get out of the way.
1880 if (((size_t) (csp->iob->eod - csp->iob->buf)) +
1881 (size_t) BUFFER_SIZE > csp->config->buffer_limit)
1885 log_error (LOG_LEVEL_ERROR,
1886 "Buffer size limit reached! Flushing and stepping back.");
1888 hdr = sed (server_patterns, add_server_headers, csp);
1891 /* FIXME Should handle error properly */
1892 log_error (LOG_LEVEL_FATAL,
1893 "Out of memory parsing server header");
1896 hdrlen = strlen (hdr);
1897 byte_count += hdrlen;
1899 if (write_socket (csp->cfd, hdr, hdrlen)
1900 || ((len = flush_socket (csp->cfd, csp)) < 0))
1902 log_error (LOG_LEVEL_CONNECT,
1903 "write header to client failed: %E");
1906 return JB_ERR_GENERIC;
1912 csp->content_filter = NULL;
1913 csp->all_headers_read = 1;
1919 if (write_socket (csp->cfd, buf, (size_t) len))
1921 log_error (LOG_LEVEL_ERROR, "write to client failed: %E");
1922 return JB_ERR_GENERIC;
1931 * we're still looking for the end of the
1932 * server's header ... (does that make header
1933 * parsing an "out of body experience" ?
1936 /* buffer up the data we just read */
1937 add_to_iob (csp, buf, len);
1939 /* get header lines from the iob */
1941 while ((p = get_header (csp)) != NULL)
1945 /* see following note */
1946 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1947 csp->ip_addr_str, csp->http->ocmd, byte_count);
1948 return JB_ERR_GENERIC;
1950 enlist (csp->headers, p);
1954 /* NOTE: there are no "empty" headers so
1955 * if the pointer `p' is not NULL we must
1956 * assume that we reached the end of the
1957 * buffer before we hit the end of the header.
1964 /* Well, we tried our MS IIS/5
1965 * hack and it didn't work.
1966 * The header is incomplete
1967 * and there isn't anything
1968 * we can do about it.
1970 log_error(LOG_LEVEL_CLF, "Incomplete Server Header: %s - - [%T] \"%s\" 200 %d",
1971 csp->ip_addr_str, csp->http->ocmd, byte_count);
1972 return JB_ERR_GENERIC;
1976 /* Since we have to wait for
1977 * more from the server before
1978 * we can parse the headers
1979 * we just continue here.
1985 /* we have now received the entire header.
1986 * filter it and send the result to the client
1989 hdr = sed (server_patterns, add_server_headers, csp);
1992 /* FIXME Should handle error properly */
1993 log_error (LOG_LEVEL_FATAL, "Out of memory parsing server header");
1998 #ifdef FEATURE_KILL_POPUPS
1999 /* Start blocking popups if appropriate. */
2001 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
2002 !csp->http->ssl && /* We talk plaintext */
2003 block_popups) /* Policy allows */
2005 block_popups_now = 1;
2007 * Filter the part of the body that came in the same read
2008 * as the last headers:
2010 filter_popups (csp->iob->cur, csp);
2013 #endif /* def FEATURE_KILL_POPUPS */
2015 /* Buffer and pcrs filter this if appropriate. */
2017 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
2018 !csp->http->ssl && /* We talk plaintext */
2019 pcrs_filter) /* Policy allows */
2021 csp->content_filter = pcrs_filter_response;
2024 /* Buffer and gif_deanimate this if appropriate. */
2026 if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
2027 !csp->http->ssl && /* We talk plaintext */
2028 gif_deanimate) /* Policy allows */
2030 csp->content_filter = gif_deanimate_response;
2033 * Only write if we're not buffering for content modification
2035 if (!csp->content_filter)
2037 /* write the server's (modified) header to
2038 * the client (along with anything else that
2039 * may be in the buffer)
2041 if (write_socket (csp->cfd, hdr, strlen (hdr))
2042 || ((len = flush_socket (csp->cfd, csp)) < 0))
2044 log_error (LOG_LEVEL_CONNECT,
2045 "write header to client failed: %E");
2047 /* the write failed, so don't bother
2048 * mentioning it to the client...
2049 * it probably can't hear us anyway.
2052 return JB_ERR_GENERIC;
2058 /* we're finished with the server's header */
2061 csp->all_headers_read = 1;
2063 /* If this was a MS IIS/5 hack then it means
2064 * the server has already closed the
2065 * connection. Nothing more to read. Time
2070 return JB_ERR_GENERIC ;
2074 } /* END relay_server_traffic() */
2077 /*********************************************************************
2079 * Function : read_client_headers
2081 * Description : read all the client headers, and fill in the
2085 * 1 : client_state structure
2086 * 2 : http_request structure
2089 * Returns : JB_ERR_OK - headers read and parsed ok
2090 * : other values - an error occurred.
2091 *********************************************************************/
2093 static jb_err read_client_headers( struct client_state *csp, struct http_request *http )
2098 char buf[BUFFER_SIZE];
2099 int len; /* for buffer sizes */
2102 * Read the client's request. Note that since we're not using select() we
2103 * could get blocked here if a client connected, then didn't say anything!
2105 * This will read all the client headers.
2111 len = read_socket(csp->cfd, buf, sizeof(buf));
2113 if (len <= 0) break; /* error! */
2115 add_to_iob(csp, buf, len);
2117 req = get_header(csp);
2121 break; /* no HTTP request! */
2126 continue; /* more to come! */
2129 /* When we get here we have read one header which is enough */
2130 /* to check whether the connection is allowed */
2138 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
2140 len = read_socket(csp->cfd, buf, sizeof(buf));
2143 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
2144 return JB_ERR_GENERIC;
2146 add_to_iob(csp, buf, len);
2150 if (p == NULL) break;
2152 enlist(csp->headers, p);
2157 parse_http_request(req, http, csp);
2160 if (http->cmd == NULL)
2162 strcpy(buf, CHEADER);
2163 write_socket(csp->cfd, buf, strlen(buf));
2165 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
2167 return JB_ERR_GENERIC;
2173 } /* END read_client_headers */
2176 /*********************************************************************
2178 * Function : process_client_headers
2180 * Description : Process client headers
2181 * FIXME: Add description of what we do here!
2184 * 1 : client_state structure
2185 * 2 : http_request structure
2188 * Returns : JB_ERR_OK - headers processed ok
2189 * : other values - an error occurred.
2190 *********************************************************************/
2192 static jb_err process_client_headers( struct client_state *csp, struct http_request *http )
2196 #ifdef FEATURE_FORCE_LOAD
2197 /* If this request contains the FORCE_PREFIX,
2198 * better get rid of it now and set the force flag --oes
2199 * Changed to use the http structure rather than the req field --jaa
2200 * FIXME: This isn't enough -- there is the path and referrer etc! *
2203 if (strstr(http->url, FORCE_PREFIX))
2205 strclean(http->url, FORCE_PREFIX);
2206 strclean(http->path, FORCE_PREFIX);
2207 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", http->url);
2208 csp->flags |= CSP_FLAG_FORCED;
2211 #endif /* def FEATURE_FORCE_LOAD */
2214 /* decide how to route the HTTP request */
2216 if ((http->fwd = forward_url(http, csp)) == NULL)
2218 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2219 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2222 /* build the http request to send to the server
2223 * we have to do one of the following:
2225 * create = use the original HTTP request to create a new
2226 * HTTP request that has either the path component
2227 * without the http://domainspec (w/path) or the
2228 * full orininal URL (w/url)
2229 * Note that the path and/or the HTTP version may
2230 * have been altered by now.
2232 * connect = Open a socket to the host:port of the server
2233 * and short-circuit server and client socket.
2235 * pass = Pass the request unchanged if forwarding a CONNECT
2236 * request to a parent proxy. Note that we'll be sending
2237 * the CFAIL message ourselves if connecting to the parent
2238 * fails, but we won't send a CSUCCEED message if it works,
2239 * since that would result in a double message (ours and the
2240 * parent's). After sending the request to the parent, we simply
2243 * here's the matrix:
2246 * +--------+--------+
2248 * 0 | create | connect|
2250 * Forwarding +--------+--------+
2252 * 1 | create | pass |
2254 * +--------+--------+
2259 * Determine the actions for this URL
2261 #ifdef FEATURE_TOGGLE
2262 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
2264 /* Most compatible set of actions (i.e. none) */
2265 init_current_action(csp->action);
2268 #endif /* ndef FEATURE_TOGGLE */
2270 url_actions(http, csp);
2278 * Downgrade http version from 1.1 to 1.0 if +downgrade
2281 if ( (http->ssl == 0)
2282 && (!strcmpic(http->ver, "HTTP/1.1"))
2283 && (csp->action->flags & ACTION_DOWNGRADE))
2286 http->ver = strdup("HTTP/1.0");
2288 if (http->ver == NULL)
2290 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
2295 * Save a copy of the original request for logging
2297 http->ocmd = strdup(http->cmd);
2299 if (http->ocmd == NULL)
2301 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
2305 * (Re)build the HTTP request for non-SSL requests.
2306 * If forwarding, use the whole URL, else, use only the path.
2312 http->cmd = strdup(http->gpc);
2313 string_append(&http->cmd, " ");
2315 if (http->fwd->forward_host)
2317 string_append(&http->cmd, http->url);
2321 string_append(&http->cmd, http->path);
2324 string_append(&http->cmd, " ");
2325 string_append(&http->cmd, http->ver);
2327 if (http->cmd == NULL)
2329 log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
2332 enlist_first(csp->headers, http->cmd);
2336 * If the user has not supplied any wafers, and the user has not
2337 * told us to suppress the vanilla wafer, then send the vanilla wafer.
2339 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
2340 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
2342 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
2346 } /* process_client_headers */
2348 /*********************************************************************
2350 * Function : intercept_page
2352 * Description : Check whether to intercept page
2355 * 1 : client_state structure
2356 * 2 : http_request structure
2359 * Returns : JB_ERR_OK - Do NOT intercept this page
2360 * : JB_ERR_INTERCEPT - intercept this page
2361 * : all other values - an error occurred.
2362 *********************************************************************/
2363 static jb_err intercept_page( struct client_state *csp, struct http_request *http )
2366 /* Skeleton for HTTP response, if we should intercept the request */
2367 struct http_response *rsp;
2371 * These next lines are a little ugly, but they simplifies the if statements
2372 * below. Basically if TOGGLE, then we want the if to test if the
2373 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
2374 * then we want the if to test for CSP_FLAG_FORCED , else we don't
2376 #ifdef FEATURE_TOGGLE
2377 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
2378 #else /* ifndef FEATURE_TOGGLE */
2379 # define IS_TOGGLED_ON_AND
2380 #endif /* ndef FEATURE_TOGGLE */
2381 #ifdef FEATURE_FORCE_LOAD
2382 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
2383 #else /* ifndef FEATURE_FORCE_LOAD */
2384 # define IS_NOT_FORCED_AND
2385 #endif /* def FEATURE_FORCE_LOAD */
2387 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
2390 /* a CGI call was detected and answered */
2391 (NULL != (rsp = dispatch_cgi(csp)))
2393 /* or we are enabled and... */
2394 || (IS_ENABLED_AND (
2396 /* ..the request was blocked */
2397 ( NULL != (rsp = block_url(csp)))
2399 /* ..or untrusted */
2400 #ifdef FEATURE_TRUST
2401 || ( NULL != (rsp = trust_url(csp)))
2402 #endif /* def FEATURE_TRUST */
2404 /* ..or a fast redirect kicked in */
2405 #ifdef FEATURE_FAST_REDIRECTS
2406 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
2407 (NULL != (rsp = redirect_url(csp))))
2408 #endif /* def FEATURE_FAST_REDIRECTS */
2412 /* Write the answer to the client */
2413 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2414 || write_socket(csp->cfd, rsp->body, rsp->content_length))
2416 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2419 #ifdef FEATURE_STATISTICS
2420 /* Count as a rejected request */
2421 csp->flags |= CSP_FLAG_REJECTED;
2422 #endif /* def FEATURE_STATISTICS */
2424 /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
2425 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
2426 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
2428 /* Clean up and return */
2429 free_http_response(rsp);
2430 return JB_ERR_INTERCEPT;
2433 /* When we get here the request doesn't need to be intercepted */
2437 /*********************************************************************
2439 * Function : open_forwarding_connection
2441 * Description : Check whether to intercept page
2444 * 1 : client_state structure
2445 * 2 : http_request structure
2447 * Returns : JB_ERR_OK - Connection opened ok
2448 * : all other values - an error occurred.
2449 *********************************************************************/
2450 static jb_err open_forwarding_connection(struct client_state *csp )
2452 struct http_response *rsp;
2454 #ifdef FEATURE_ACTIVITY_CONSOLE
2455 accumulate_stats(STATS_REQUEST, 1);
2456 #endif /* def FEATURE_ACTIVITY_CONSOLE */
2457 log_error(LOG_LEVEL_GPC, "%s%s", csp->http->hostport, csp->http->path);
2459 if (csp->http->fwd->forward_host)
2461 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
2462 csp->http->fwd->forward_host, csp->http->fwd->forward_port,
2463 csp->http->hostport);
2467 log_error(LOG_LEVEL_CONNECT, "to %s", csp->http->hostport);
2470 /* here we connect to the server, gateway, or the forwarder */
2472 csp->sfd = forwarded_connect(csp->http->fwd, csp->http, csp);
2474 if (csp->sfd == JB_INVALID_SOCKET)
2476 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
2477 csp->http->hostport);
2479 if (errno == EINVAL)
2481 rsp = error_response(csp, "no-such-domain", errno);
2483 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
2484 csp->ip_addr_str, csp->http->ocmd);
2488 rsp = error_response(csp, "connect-failed", errno);
2490 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
2491 csp->ip_addr_str, csp->http->ocmd);
2495 /* Write the answer to the client */
2498 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2499 || write_socket(csp->cfd, rsp->body, rsp->content_length))
2501 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
2505 free_http_response(rsp);
2506 return JB_ERR_GENERIC;
2509 log_error(LOG_LEVEL_CONNECT, "OK");
2512 } /* END open_forwarding_connection() */
2515 /*********************************************************************
2517 * Function : send_client_headers_to_server
2519 * Description : send the client headers (possibly modified) to the server
2522 * 1 : client_state structure
2523 * 2 : http_request structure
2526 * Returns : JB_ERR_OK - headers sent ok
2527 * : other values - an error occurred.
2528 *********************************************************************/
2530 static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http, char *hdr )
2533 struct http_response *rsp;
2535 if (http->fwd->forward_host || (http->ssl == 0))
2537 /* write the client's (modified) header to the server
2538 * (along with anything else that may be in the buffer)
2541 if (write_socket(csp->sfd, hdr, strlen(hdr))
2542 || (flush_socket(csp->sfd, csp) < 0))
2544 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
2547 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
2548 csp->ip_addr_str, http->ocmd);
2550 rsp = error_response(csp, "connect-failed", errno);
2554 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2555 || write_socket(csp->cfd, rsp->body, rsp->content_length))
2557 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2561 free_http_response(rsp);
2562 return JB_ERR_GENERIC;
2568 * We're running an SSL tunnel and we're not forwarding,
2569 * so just send the "connect succeeded" message to the
2570 * client, flush the rest, and get out of the way.
2572 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
2573 csp->ip_addr_str, http->ocmd);
2575 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
2583 } /* END send_client_headers_to_server */
2586 /*********************************************************************
2588 * Function : is_connect_request_allowed
2590 * Description : send the client headers (possibly modified) to the server
2593 * 1 : client_state structure
2597 * Returns : JB_ERR_OK - connect request allowed
2598 * : other values - connect request not allowed
2599 *********************************************************************/
2600 static jb_err is_connect_request_allowed( struct client_state *csp )
2603 * Check if a CONNECT request is allowable:
2604 * In the absence of a +limit-connect action, allow only port 443.
2605 * If there is an action, allow whatever matches the specificaton.
2610 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
2611 || (csp->action->flags & ACTION_LIMIT_CONNECT
2612 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
2614 char buf[BUFFER_SIZE];
2615 strcpy(buf, CFORBIDDEN);
2616 write_socket(csp->cfd, buf, strlen(buf));
2618 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
2619 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
2621 return JB_ERR_GENERIC;
2626 } /* END is_connect_request_allowed */