-const char jcc_rcs[] = "$Id: jcc.c,v 2.7 2003/09/25 01:44:33 david__schmidt Exp $";
+const char jcc_rcs[] = "$Id: jcc.c,v 1.92.2.16 2005/04/03 20:10:50 david__schmidt Exp $";
/*********************************************************************
*
- * File : $Source: /cvsroot/ijbswa/current/src/jcc.c,v $
+ * File : $Source: /cvsroot/ijbswa/current/Attic/jcc.c,v $
*
* Purpose : Main file. Contains main() method, main loop, and
* the main connection-handling function.
*
* Revisions :
* $Log: jcc.c,v $
- * Revision 2.7 2003/09/25 01:44:33 david__schmidt
- * Resyncing HEAD with v_3_0_branch for two OSX fixes:
- * Making thread IDs look sane in the logfile for Mach kernels,
- * and fixing multithreading crashes due to thread-unsafe
- * system calls.
- * and
- *
- * Revision 2.6 2003/06/24 12:24:24 oes
- * Added a line plus Fix-me as a reminder to fix broken force handling in trunk. Thanks to lionel for the hint
- *
- * Revision 2.5 2003/01/26 20:24:26 david__schmidt
- * Updated activity console instrumentation locations
- *
- * Revision 2.4 2002/12/28 03:58:19 david__schmidt
- * Initial drop of dashboard instrumentation - enabled with
- * --enable-activity-console
- *
- * Revision 2.3 2002/07/18 22:06:12 jongfoster
- * Trivial formatting changes
- *
- * Revision 2.2 2002/07/12 04:26:17 agotneja
- * Re-factored 'chat()' to become understandable and maintainable as
- * a first step in adding Transparent Proxy functionality.
- *
- * Added several new static functions in jcc.c, and moved some data
- * parameters up into project.h to allow them to be passed between
- * the new functions.
+ * Revision 1.92.2.16 2005/04/03 20:10:50 david__schmidt
+ * Thanks to Jindrich Makovicka for a race condition fix for the log
+ * file. The race condition remains for non-pthread implementations.
+ * Reference patch #1175720.
+ *
+ * Revision 1.92.2.15 2004/10/03 12:53:32 david__schmidt
+ * Add the ability to check jpeg images for invalid
+ * lengths of comment blocks. Defensive strategy
+ * against the exploit:
+ * Microsoft Security Bulletin MS04-028
+ * Buffer Overrun in JPEG Processing (GDI+) Could
+ * Allow Code Execution (833987)
+ * Enabled with +inspect-jpegs in actions files.
+ *
+ * Revision 1.92.2.14 2003/12/12 12:52:53 oes
+ * - Fixed usage info for non-unix platforms
+ * - Fixed small cmdline parsing bug
+ *
+ * Revision 1.92.2.13 2003/11/27 19:20:27 oes
+ * Diagnostics: Now preserve the returncode of pthread_create
+ * in errno. Closes BR #775721. Thanks to Geoffrey Hausheer.
+ *
+ * Revision 1.92.2.12 2003/07/11 11:34:19 oes
+ * No longer ignore SIGCHLD. Fixes bug #769381
+ *
+ * Revision 1.92.2.11 2003/05/14 12:32:02 oes
+ * Close jarfile on graceful exit, remove stray line
+ *
+ * Revision 1.92.2.10 2003/05/08 15:13:46 oes
+ * Cosmetics: Killed a warning, a typo and an allocation left at exit
+ *
+ * Revision 1.92.2.9 2003/04/03 15:08:42 oes
+ * No longer rely on non-POSIX.1 extensions of getcwd().
+ * Fixes bug #711001
+ *
+ * Revision 1.92.2.8 2003/03/31 13:12:32 oes
+ * Replaced setenv() by posix-compliant putenv()
+ * Thanks to Neil McCalden (nmcc AT users.sf.net).
+ *
+ * Revision 1.92.2.7 2003/03/17 16:48:59 oes
+ * Added chroot ability, thanks to patch by Sviatoslav Sviridov
+ *
+ * Revision 1.92.2.6 2003/03/11 11:55:00 oes
+ * Clean-up and extension of improvements for forked mode:
+ * - Child's return code now consists of flags RC_FLAG_*
+ * - Reporting toggle to parent now properly #ifdef'ed
+ * - Children now report blocking to parent. This enables
+ * statistics in forked mode
+ *
+ * Revision 1.92.2.5 2003/03/10 23:45:32 oes
+ * Fixed bug #700381: Non-Threaded version now capable of being toggled.
+ * Children now report having been toggled through _exit(17), parents
+ * watch for that code and toggle themselves if found.
+ *
+ * Revision 1.92.2.4 2003/03/07 03:41:04 david__schmidt
+ * Wrapping all *_r functions (the non-_r versions of them) with
+ * mutex semaphores for OSX. Hopefully this will take care of all
+ * of those pesky crash reports.
+ *
+ * Revision 1.92.2.3 2003/02/28 12:53:06 oes
+ * Fixed two mostly harmless mem leaks
+ *
+ * Revision 1.92.2.2 2002/11/20 14:37:47 oes
+ * Fix: Head of global clients list now initialized to NULL
+ *
+ * Revision 1.92.2.1 2002/09/25 14:52:24 oes
+ * Added basic support for OPTIONS and TRACE HTTP methods:
+ * - New interceptor direct_response() added in chat().
+ * - sed() moved to earlier in the process, so that the
+ * Host: header is evaluated before actions and forwarding
+ * are decided on.
+ *
+ * Revision 1.92 2002/05/08 16:00:46 oes
+ * Chat's buffer handling:
+ * - Fixed bug with unchecked out-of-mem conditions
+ * while reading client request & server headers
+ * - No longer predict if the buffer limit will be exceeded
+ * in the next read -- check add_to_iob's new
+ * return code. If buffer couldn't be extended
+ * (policy or out-of-mem) while
+ * - reading from client: abort
+ * - reading server headers: send error page
+ * - buffering server body for filter: flush,
+ * and if that fails: send error page
*
* Revision 1.91 2002/04/08 20:35:58 swa
* fixed JB spelling
#include "cgi.h"
#include "loadcfg.h"
#include "urlmatch.h"
-#ifdef FEATURE_ACTIVITY_CONSOLE
-#include "stats.h"
-#endif /* def FEATURE_ACTIVITY_CONSOLE */
const char jcc_h_rcs[] = JCC_H_VERSION;
const char project_h_rcs[] = PROJECT_H_VERSION;
static void listen_loop(void);
static void chat(struct client_state *csp);
-static jb_err relay_server_traffic( struct client_state *csp ) ;
-static jb_err read_client_headers( struct client_state *csp, struct http_request *http ) ;
-static jb_err process_client_headers( struct client_state *csp, struct http_request *http ) ;
-static jb_err intercept_page( struct client_state *csp, struct http_request *http );
-static jb_err open_forwarding_connection( struct client_state *csp );
-static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http, char* hdr );
-static jb_err is_connect_request_allowed( struct client_state *csp ) ;
-
-
#ifdef AMIGA
void serve(struct client_state *csp);
#else /* ifndef AMIGA */
pthread_mutex_t gethostbyname_mutex;
#endif /* def OSX_DARWIN */
+#ifdef FEATURE_PTHREAD
+pthread_mutex_t log_mutex;
+pthread_mutex_t log_init_mutex;
+#endif /* FEATURE_PTHREAD */
+
#if defined(unix) || defined(__EMX__)
const char *basedir = NULL;
const char *pidfile = NULL;
"Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
"(copyright_or_otherwise)_applying_to_any_cookie._";
-/**
- * HTTP header sent when doing HTTPS tunnelling ("CONNECT" method).
- */
-static const char CSUCCEED[] =
- "HTTP/1.0 200 Connection established\n"
- "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
-
-
-/**
- * HTTP reply sent when the browser sends something unintelligible.
- */
-static const char CHEADER[] =
- "HTTP/1.0 400 Invalid header received from browser\r\n\r\n";
-
-
-/**
- * HTTP reply sent when the browser tries to tunnel ("CONNECT") to something
- * other than a HTTPS port (as defined by +limit-connect).
- */
-static const char CFORBIDDEN[] =
- "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";
#if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
/*********************************************************************
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
*
- * Returns : void
+ * Returns : On success, the number of bytes written are returned (zero
+ * indicates nothing was written). On error, -1 is returned,
+ * and errno is set appropriately. If count is zero and the
+ * file descriptor refers to a regular file, 0 will be
+ * returned without causing any other effect. For a special
+ * file, the results are not portable.
*
*********************************************************************/
static void chat(struct client_state *csp)
{
+/*
+ * This next lines are a little ugly, but they simplifies the if statements
+ * below. Basically if TOGGLE, then we want the if to test if the
+ * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
+ * then we want the if to test for CSP_FLAG_FORCED , else we don't
+ */
+#ifdef FEATURE_TOGGLE
+# define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
+#else /* ifndef FEATURE_TOGGLE */
+# define IS_TOGGLED_ON_AND
+#endif /* ndef FEATURE_TOGGLE */
+#ifdef FEATURE_FORCE_LOAD
+# define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
+#else /* ifndef FEATURE_FORCE_LOAD */
+# define IS_NOT_FORCED_AND
+#endif /* def FEATURE_FORCE_LOAD */
+#define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
char buf[BUFFER_SIZE];
- int len; /* for buffer sizes */
- char *hdr;
+ char *hdr;
+ char *p;
+ char *req;
fd_set rfds;
int n;
jb_socket maxfd;
+ int server_body;
+ int ms_iis5_hack = 0;
int byte_count = 0;
+ const struct forward_spec * fwd;
struct http_request *http;
+ int len; /* for buffer sizes */
+#ifdef FEATURE_KILL_POPUPS
+ int block_popups; /* bool, 1==will block popups */
+ int block_popups_now = 0; /* bool, 1==currently blocking popups */
+#endif /* def FEATURE_KILL_POPUPS */
- http = csp->http;
+ int pcrs_filter; /* bool, 1==will filter through pcrs */
+ int gif_deanimate; /* bool, 1==will deanimate gifs */
+ int jpeg_inspect; /* bool, 1==will inspect jpegs */
- if (read_client_headers(csp, http ) != JB_ERR_OK )
- return;
-
+ /* Function that does the content filtering for the current request */
+ char *(*content_filter)() = NULL;
- /* Process the client headers */
- if (process_client_headers(csp, http) != JB_ERR_OK)
- return;
-
+ /* Skeleton for HTTP response, if we should intercept the request */
+ struct http_response *rsp;
- /* Check if this connection request is permitted */
- if (is_connect_request_allowed(csp) != JB_ERR_OK)
- return ;
+ http = csp->http;
/*
- * We have a valid and legit request. Now, check to see if we need to
- * intercept it.
- */
- if (intercept_page(csp, http) != JB_ERR_OK)
- return;
-
- /*
- * The page passed the intercept routine, so open a forwarding
- * connection for conversation
- */
- if (open_forwarding_connection(csp) != JB_ERR_OK )
- return ;
-
-
-
- hdr = sed(client_patterns, add_client_headers, csp);
- if (hdr == NULL)
- {
- /* FIXME Should handle error properly */
- log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
- }
-
- /* FIXME - where should this go, logically ? */
- list_remove_all(csp->headers);
-
-
- if (send_client_headers_to_server(csp, http, hdr) != JB_ERR_OK)
- return ;
-
-
- /* we're finished with the client's header */
- freez(hdr);
-
- maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
-
- /* pass data between the client and server
- * until one or the other shuts down the connection.
+ * Read the client's request. Note that since we're not using select() we
+ * could get blocked here if a client connected, then didn't say anything!
*/
- /* Set the flag for reading headers to False */
- /* This is used in relay_server_traffic */
- csp->all_headers_read = 0 ;
-
for (;;)
{
- jb_err tmp_ret_val = JB_ERR_GENERIC ;
+ len = read_socket(csp->cfd, buf, sizeof(buf));
-#ifdef __OS2__
+ if (len <= 0) break; /* error! */
+
/*
- * FD_ZERO here seems to point to an errant macro which crashes.
- * So do this by hand for now...
+ * If there is no memory left for buffering the
+ * request, there is nothing we can do but hang up
*/
- memset(&rfds,0x00,sizeof(fd_set));
-#else
- FD_ZERO(&rfds);
-#endif
- FD_SET(csp->cfd, &rfds);
- FD_SET(csp->sfd, &rfds);
-
- n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
-
- if (n < 0)
+ if (add_to_iob(csp, buf, len))
{
- log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
return;
}
- /*
- * This is the body of the browser's request.
- * Just read it and write it.
- */
+ req = get_header(csp);
- if (FD_ISSET(csp->cfd, &rfds))
+ if (req == NULL)
{
- len = read_socket(csp->cfd, buf, sizeof(buf));
-
- if (len <= 0)
- {
- log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
- csp->ip_addr_str, http->ocmd, byte_count);
- return ;
- }
+ break; /* no HTTP request! */
+ }
- if (write_socket(csp->sfd, buf, (size_t)len))
- {
- log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
- return;
- }
- continue;
+ if (*req == '\0')
+ {
+ continue; /* more to come! */
}
- /*
- * Check if the server wants to talk, and if so, converse.
+#ifdef FEATURE_FORCE_LOAD
+ /* If this request contains the FORCE_PREFIX,
+ * better get rid of it now and set the force flag --oes
*/
- if (FD_ISSET(csp->sfd, &rfds))
- tmp_ret_val = relay_server_traffic(csp) ;
+ if (strstr(req, FORCE_PREFIX))
+ {
+ strclean(req, FORCE_PREFIX);
+ log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
+ csp->flags |= CSP_FLAG_FORCED;
+ }
+#endif /* def FEATURE_FORCE_LOAD */
- if (tmp_ret_val == JB_ERR_OK)
- continue ;
- else
- return;
+ parse_http_request(req, http, csp);
+ freez(req);
+ break;
}
- /* We should never get here! */
- log_error(LOG_LEVEL_FATAL, "chat() : logic error in for() loop" ) ;
-} /* END chat() */
+ if (http->cmd == NULL)
+ {
+ strcpy(buf, CHEADER);
+ write_socket(csp->cfd, buf, strlen(buf));
-/*********************************************************************
- *
- * Function : serve
- *
- * Description : This is little more than chat. We only "serve" to
- * to close any socket that chat may have opened.
- *
- * Parameters :
- * 1 : csp = Current client state (buffers, headers, etc...)
- *
- * Returns : N/A
- *
- *********************************************************************/
-#ifdef AMIGA
-void serve(struct client_state *csp)
-#else /* ifndef AMIGA */
-static void serve(struct client_state *csp)
-#endif /* def AMIGA */
-{
- chat(csp);
- close_socket(csp->cfd);
+ log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
- if (csp->sfd != JB_INVALID_SOCKET)
+ free_http_request(http);
+ return;
+ }
+
+ /* decide how to route the HTTP request */
+
+ if ((fwd = forward_url(http, csp)) == NULL)
{
- close_socket(csp->sfd);
+ log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
+ /* Never get here - LOG_LEVEL_FATAL causes program exit */
}
- csp->flags &= ~CSP_FLAG_ACTIVE;
+ /* build the http request to send to the server
+ * we have to do one of the following:
+ *
+ * create = use the original HTTP request to create a new
+ * HTTP request that has either the path component
+ * without the http://domainspec (w/path) or the
+ * full orininal URL (w/url)
+ * Note that the path and/or the HTTP version may
+ * have been altered by now.
+ *
+ * connect = Open a socket to the host:port of the server
+ * and short-circuit server and client socket.
+ *
+ * pass = Pass the request unchanged if forwarding a CONNECT
+ * request to a parent proxy. Note that we'll be sending
+ * the CFAIL message ourselves if connecting to the parent
+ * fails, but we won't send a CSUCCEED message if it works,
+ * since that would result in a double message (ours and the
+ * parent's). After sending the request to the parent, we simply
+ * tunnel.
+ *
+ * here's the matrix:
+ * SSL
+ * 0 1
+ * +--------+--------+
+ * | | |
+ * 0 | create | connect|
+ * | w/path | |
+ * Forwarding +--------+--------+
+ * | | |
+ * 1 | create | pass |
+ * | w/url | |
+ * +--------+--------+
+ *
+ */
-}
+ /*
+ * Determine the actions for this URL
+ */
+#ifdef FEATURE_TOGGLE
+ if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
+ {
+ /* Most compatible set of actions (i.e. none) */
+ init_current_action(csp->action);
+ }
+ else
+#endif /* ndef FEATURE_TOGGLE */
+ {
+ url_actions(http, csp);
+ }
-#ifdef __BEOS__
-/*********************************************************************
- *
- * Function : server_thread
- *
- * Description : We only exist to call `serve' in a threaded environment.
- *
- * Parameters :
- * 1 : data = Current client state (buffers, headers, etc...)
- *
- * Returns : Always 0.
- *
- *********************************************************************/
-static int32 server_thread(void *data)
-{
- serve((struct client_state *) data);
- return 0;
+ /*
+ * Check if a CONNECT request is allowable:
+ * In the absence of a +limit-connect action, allow only port 443.
+ * If there is an action, allow whatever matches the specificaton.
+ */
+ if(http->ssl)
+ {
+ if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
+ || (csp->action->flags & ACTION_LIMIT_CONNECT
+ && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
+ {
+ strcpy(buf, CFORBIDDEN);
+ write_socket(csp->cfd, buf, strlen(buf));
-}
-#endif
+ log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
+ log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
+ return;
+ }
+ }
-/*********************************************************************
- *
- * Function : usage
- *
- * Description : Print usage info & exit.
- *
- * Parameters : Pointer to argv[0] for identifying ourselves
- *
- * Returns : No. ,-)
- *
- *********************************************************************/
-void usage(const char *myname)
-{
- printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
- "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
- "Aborting.\n", myname);
-
- exit(2);
-
-}
-
-
-/*********************************************************************
- *
- * Function : main
- *
- * Description : Load the config file and start the listen loop.
- * This function is a lot more *sane* with the `load_config'
- * and `listen_loop' functions; although it stills does
- * a *little* too much for my taste.
- *
- * Parameters :
- * 1 : argc = Number of parameters (including $0).
- * 2 : argv = Array of (char *)'s to the parameters.
- *
- * Returns : 1 if : can't open config file, unrecognized directive,
- * stats requested in multi-thread mode, can't open the
- * log file, can't open the jar file, listen port is invalid,
- * any load fails, and can't bind port.
- *
- * Else main never returns, the process must be signaled
- * to terminate execution. Or, on Windows, use the
- * "File", "Exit" menu option.
- *
- *********************************************************************/
-#ifdef __MINGW32__
-int real_main(int argc, const char *argv[])
-#else
-int main(int argc, const char *argv[])
-#endif
-{
- int argc_pos = 0;
-#ifdef unix
- struct passwd *pw = NULL;
- struct group *grp = NULL;
- char *p;
-#endif
-
- Argc = argc;
- Argv = argv;
-
- configfile =
-#if !defined(_WIN32)
- "config"
-#else
- "config.txt"
-#endif
- ;
/*
- * Parse the command line arguments
+ * Downgrade http version from 1.1 to 1.0 if +downgrade
+ * action applies
*/
- while (++argc_pos < argc)
+ if ( (http->ssl == 0)
+ && (!strcmpic(http->ver, "HTTP/1.1"))
+ && (csp->action->flags & ACTION_DOWNGRADE))
{
-#if !defined(_WIN32) || defined(_WIN_CONSOLE)
-
- if (strcmp(argv[argc_pos], "--help") == 0)
- {
- usage(argv[0]);
- }
+ freez(http->ver);
+ http->ver = strdup("HTTP/1.0");
- else if(strcmp(argv[argc_pos], "--version") == 0)
+ if (http->ver == NULL)
{
- printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
- exit(0);
+ log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
}
+ }
- else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
- {
- no_daemon = 1;
- }
-#if defined(unix)
- else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
- {
- if (++argc_pos == argc) usage(argv[0]);
- pidfile = strdup(argv[argc_pos]);
- }
+ /*
+ * Save a copy of the original request for logging
+ */
+ http->ocmd = strdup(http->cmd);
- else if (strcmp(argv[argc_pos], "--user" ) == 0)
- {
- if (++argc_pos == argc) usage(argv[argc_pos]);
+ if (http->ocmd == NULL)
+ {
+ log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
+ }
- if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
- {
- *p++ = '\0';
- if (NULL == (grp = getgrnam(p)))
- {
- log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
- }
- }
+ /*
+ * (Re)build the HTTP request for non-SSL requests.
+ * If forwarding, use the whole URL, else, use only the path.
+ */
+ if (http->ssl == 0)
+ {
+ freez(http->cmd);
- if (NULL == (pw = getpwnam(argv[argc_pos])))
- {
- log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
- }
+ http->cmd = strdup(http->gpc);
+ string_append(&http->cmd, " ");
- if (p != NULL) *--p = '\0';
+ if (fwd->forward_host)
+ {
+ string_append(&http->cmd, http->url);
}
-#endif /* defined(unix) */
else
-#endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
{
- configfile = argv[argc_pos];
+ string_append(&http->cmd, http->path);
}
+ string_append(&http->cmd, " ");
+ string_append(&http->cmd, http->ver);
- } /* -END- while (more arguments) */
-
-#if defined(unix)
- if ( *configfile != '/' )
- {
- char *abs_file;
-
- /* make config-filename absolute here */
- if ( !(basedir = getcwd( NULL, 1024 )))
+ if (http->cmd == NULL)
{
- perror("get working dir failed");
- exit( 1 );
+ log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
}
+ log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", http->cmd);
+ }
+ enlist(csp->headers, http->cmd);
- if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
- {
- perror("malloc failed");
- exit( 1 );
- }
- strcpy( abs_file, basedir );
- strcat( abs_file, "/" );
- strcat( abs_file, configfile );
- configfile = abs_file;
+
+ /*
+ * If the user has not supplied any wafers, and the user has not
+ * told us to suppress the vanilla wafer, then send the vanilla wafer.
+ */
+ if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
+ && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
+ {
+ enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
}
-#endif /* defined unix */
- files->next = NULL;
+#ifdef FEATURE_KILL_POPUPS
+ block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
+#endif /* def FEATURE_KILL_POPUPS */
-#ifdef AMIGA
- InitAmiga();
-#elif defined(_WIN32)
- InitWin32();
-#endif
+ pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
+ (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
-#ifdef OSX_DARWIN
- /*
- * Prepare global mutex semaphores
- */
- pthread_mutex_init(&gmtime_mutex,0);
- pthread_mutex_init(&localtime_mutex,0);
- pthread_mutex_init(&gethostbyaddr_mutex,0);
- pthread_mutex_init(&gethostbyname_mutex,0);
-#endif /* def OSX_DARWIN */
+ gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
- /*
- * Unix signal handling
- *
- * Catch the abort, interrupt and terminate signals for a graceful exit
- * Catch the hangup signal so the errlog can be reopened.
- * Ignore the broken pipe and child signals
- * FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE?
- */
-#if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
-{
- int idx;
- const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
- const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
+ jpeg_inspect = ((csp->action->flags & ACTION_JPEG_INSPECT) != 0);
- for (idx = 0; catched_signals[idx] != 0; idx++)
- {
- if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
- {
- log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
- }
- }
+ /* grab the rest of the client's headers */
- for (idx = 0; ignored_signals[idx] != 0; idx++)
+ for (;;)
{
- if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
+ if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
{
- log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
+ len = read_socket(csp->cfd, buf, sizeof(buf));
+ if (len <= 0)
+ {
+ log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
+ return;
+ }
+
+ /*
+ * If there is no memory left for buffering the
+ * request, there is nothing we can do but hang up
+ */
+ if (add_to_iob(csp, buf, len))
+ {
+ return;
+ }
+ continue;
}
+
+ if (p == NULL) break;
+
+ enlist(csp->headers, p);
+ freez(p);
}
-}
-#else /* ifdef _WIN32 */
-# ifdef _WIN_CONSOLE
/*
- * We *are* in a windows console app.
- * Print a verbose messages about FAQ's and such
+ * We have a request. Now, check to see if we need to
+ * intercept it, i.e. If ..
*/
- printf(win32_blurb);
-# endif /* def _WIN_CONSOLE */
-#endif /* def _WIN32 */
+ if (
+ /* We may not forward the request by rfc2616 sect 14.31 */
+ (NULL != (rsp = direct_response(csp)))
- /* Initialize the CGI subsystem */
- cgi_init_error_messages();
+ /* or a CGI call was detected and answered */
+ || (NULL != (rsp = dispatch_cgi(csp)))
- /*
- * If runnig on unix and without the --nodaemon
- * option, become a daemon. I.e. fork, detach
- * from tty and get process group leadership
- */
-#if defined(unix)
- {
- pid_t pid = 0;
-#if 0
- int fd;
-#endif
+ /* or we are enabled and... */
+ || (IS_ENABLED_AND (
- if (!no_daemon)
- {
- pid = fork();
+ /* ..the request was blocked */
+ ( NULL != (rsp = block_url(csp)))
- if ( pid < 0 ) /* error */
- {
- perror("fork");
- exit( 3 );
- }
- else if ( pid != 0 ) /* parent */
- {
- int status;
- pid_t wpid;
- /*
- * must check for errors
- * child died due to missing files aso
- */
- sleep( 1 );
- wpid = waitpid( pid, &status, WNOHANG );
- if ( wpid != 0 )
- {
- exit( 1 );
- }
- exit( 0 );
- }
- /* child */
-#if 1
- /* Should be more portable, but not as well tested */
- setsid();
-#else /* !1 */
-#ifdef __FreeBSD__
- setpgrp(0,0);
-#else /* ndef __FreeBSD__ */
- setpgrp();
-#endif /* ndef __FreeBSD__ */
- fd = open("/dev/tty", O_RDONLY);
- if ( fd )
- {
- /* no error check here */
- ioctl( fd, TIOCNOTTY,0 );
- close ( fd );
- }
-#endif /* 1 */
- /* FIXME: should close stderr (fd 2) here too, but the test
- * for existence
- * and load config file is done in listen_loop() and puts
- * some messages on stderr there.
- */
-
- close( 0 );
- close( 1 );
- chdir("/");
-
- } /* -END- if (!no_daemon) */
+ /* ..or untrusted */
+#ifdef FEATURE_TRUST
+ || ( NULL != (rsp = trust_url(csp)))
+#endif /* def FEATURE_TRUST */
- /*
- * As soon as we have written the PID file, we can switch
- * to the user and group ID indicated by the --user option
- */
- write_pid_file();
-
- if (NULL != pw)
+ /* ..or a fast redirect kicked in */
+#ifdef FEATURE_FAST_REDIRECTS
+ || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
+ (NULL != (rsp = redirect_url(csp))))
+#endif /* def FEATURE_FAST_REDIRECTS */
+ ))
+ )
+ {
+ /* Write the answer to the client */
+ if (write_socket(csp->cfd, rsp->head, rsp->head_length)
+ || write_socket(csp->cfd, rsp->body, rsp->content_length))
{
- if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
- {
- log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
- }
- if (setuid(pw->pw_uid))
- {
- log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
- }
+ log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
}
- }
-#endif /* defined unix */
-
- listen_loop();
-
- /* NOTREACHED */
- return(-1);
-}
+#ifdef FEATURE_STATISTICS
+ /* Count as a rejected request */
+ csp->flags |= CSP_FLAG_REJECTED;
+#endif /* def FEATURE_STATISTICS */
+ /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
+ log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
+ log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
-/*********************************************************************
- *
- * Function : bind_port_helper
- *
- * Description : Bind the listen port. Handles logging, and aborts
- * on failure.
- *
- * Parameters :
- * 1 : config = Privoxy configuration. Specifies port
- * to bind to.
- *
- * Returns : Port that was opened.
- *
- *********************************************************************/
-static jb_socket bind_port_helper(struct configuration_spec * config)
-{
- int result;
- jb_socket bfd;
+ /* Clean up and return */
+ free_http_response(rsp);
+ return;
+ }
- if ( (config->haddr != NULL)
- && (config->haddr[0] == '1')
- && (config->haddr[1] == '2')
- && (config->haddr[2] == '7')
- && (config->haddr[3] == '.') )
+ hdr = sed(client_patterns, add_client_headers, csp);
+ if (hdr == NULL)
{
- log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
- config->hport);
+ /* FIXME Should handle error properly */
+ log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
}
- else if (config->haddr == NULL)
+
+ list_remove_all(csp->headers);
+
+ log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
+
+ if (fwd->forward_host)
{
- log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
- config->hport);
+ log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
+ fwd->forward_host, fwd->forward_port, http->hostport);
}
else
{
- log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
- config->hport, config->haddr);
- }
-
- result = bind_port(config->haddr, config->hport, &bfd);
-
- if (result < 0)
- {
- switch(result)
- {
- case -3 :
- log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
- "There may be another Privoxy or some other "
- "proxy running on port %d",
- (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
- config->hport, config->hport);
-
- case -2 :
- log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
- "The hostname is not resolvable",
- (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
-
- default :
- log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
- (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
- }
-
- /* shouldn't get here */
- return JB_INVALID_SOCKET;
+ log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
}
- config->need_bind = 0;
-
- return bfd;
-}
-
-
-/*********************************************************************
- *
- * Function : listen_loop
- *
- * Description : bind the listen port and enter a "FOREVER" listening loop.
- *
- * Parameters : N/A
- *
- * Returns : Never.
- *
- *********************************************************************/
-static void listen_loop(void)
-{
- struct client_state *csp = NULL;
- jb_socket bfd;
- struct configuration_spec * config;
-
- config = load_config();
-
- bfd = bind_port_helper(config);
+ /* here we connect to the server, gateway, or the forwarder */
-#ifdef FEATURE_ACTIVITY_CONSOLE
- init_stats_config(config);
-#endif /* def FEATURE_ACTIVITY_CONSOLE */
+ csp->sfd = forwarded_connect(fwd, http, csp);
-#ifdef FEATURE_GRACEFUL_TERMINATION
- while (!g_terminate)
-#else
- for (;;)
-#endif
+ if (csp->sfd == JB_INVALID_SOCKET)
{
-#if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
- while (waitpid(-1, NULL, WNOHANG) > 0)
- {
- /* zombie children */
- }
-#endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
-
- /*
- * Free data that was used by died threads
- */
- sweep();
+ log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
+ http->hostport);
-#if defined(unix)
- /*
- * Re-open the errlog after HUP signal
- */
- if (received_hup_signal)
+ if (errno == EINVAL)
{
- init_error_log(Argv[0], config->logfile, config->debug);
- received_hup_signal = 0;
- }
-#endif
-
-#ifdef __OS2__
-#ifdef FEATURE_COOKIE_JAR
- /*
- * Need a workaround here: we have to fclose() the jarfile, or we die because it's
- * already open. I think unload_configfile() is not being run, which should do
- * this work. Until that can get resolved, we'll use this workaround.
- *
- * [Note from Jon: We don't unload_configfile() until all existing threads have
- * exited - they're likely to hang aroung transferring data to the browser.]
- */
- if (csp)
- if(csp->config)
- if (csp->config->jar)
- {
- fclose(csp->config->jar);
- csp->config->jar = NULL;
- }
-#endif /* FEATURE_COOKIE_JAR */
-#endif /* __OS2__ */
+ rsp = error_response(csp, "no-such-domain", errno);
- if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
- {
- log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
- continue;
+ log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
+ csp->ip_addr_str, http->ocmd);
}
-
- csp->flags |= CSP_FLAG_ACTIVE;
- csp->sfd = JB_INVALID_SOCKET;
-
- csp->config = config = load_config();
-
- if ( config->need_bind )
+ else
{
- /*
- * Since we were listening to the "old port", we will not see
- * a "listen" param change until the next IJB request. So, at
- * least 1 more request must be made for us to find the new
- * setting. I am simply closing the old socket and binding the
- * new one.
- *
- * Which-ever is correct, we will serve 1 more page via the
- * old settings. This should probably be a "show-proxy-args"
- * request. This should not be a so common of an operation
- * that this will hurt people's feelings.
- */
-
- close_socket(bfd);
+ rsp = error_response(csp, "connect-failed", errno);
- bfd = bind_port_helper(config);
+ log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
+ csp->ip_addr_str, http->ocmd);
}
- log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
- if (!accept_connection(csp, bfd))
+ /* Write the answer to the client */
+ if(rsp)
{
- log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
-
-#ifdef AMIGA
- if(!childs)
+ if (write_socket(csp->cfd, rsp->head, rsp->head_length)
+ || write_socket(csp->cfd, rsp->body, rsp->content_length))
{
- exit(1);
+ log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
}
-#endif
- freez(csp);
- continue;
- }
- else
- {
- log_error(LOG_LEVEL_CONNECT, "OK");
}
-#ifdef FEATURE_TOGGLE
- if (g_bToggleIJB)
- {
- csp->flags |= CSP_FLAG_TOGGLED_ON;
- }
-#endif /* def FEATURE_TOGGLE */
-
-#ifdef FEATURE_ACTIVITY_CONSOLE
- update_stats_config(config);
-#endif /* def FEATURE_ACTIVITY_CONSOLE */
-
- if (run_loader(csp))
- {
- log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
- /* Never get here - LOG_LEVEL_FATAL causes program exit */
- }
+ free_http_response(rsp);
+ freez(hdr);
+ return;
+ }
-#ifdef FEATURE_ACL
- if (block_acl(NULL,csp))
- {
-#ifdef FEATURE_ACTIVITY_CONSOLE
- accumulate_stats(STATS_ACL_RESTRICT,1);
-#endif /* def FEATURE_ACTIVITY_CONSOLE */
- log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
- close_socket(csp->cfd);
- freez(csp);
- continue;
- }
-#endif /* def FEATURE_ACL */
+ log_error(LOG_LEVEL_CONNECT, "OK");
- /* add it to the list of clients */
- csp->next = clients->next;
- clients->next = csp;
+ if (fwd->forward_host || (http->ssl == 0))
+ {
+ /* write the client's (modified) header to the server
+ * (along with anything else that may be in the buffer)
+ */
- if (config->multi_threaded)
+ if (write_socket(csp->sfd, hdr, strlen(hdr))
+ || (flush_socket(csp->sfd, csp) < 0))
{
- int child_id;
-
-/* this is a switch () statment in the C preprocessor - ugh */
-#undef SELECTED_ONE_OPTION
-
-/* Use Pthreads in preference to native code */
-#if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
-#define SELECTED_ONE_OPTION
- {
- pthread_t the_thread;
- pthread_attr_t attrs;
-
- pthread_attr_init(&attrs);
- pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
- child_id = (pthread_create(&the_thread, &attrs,
- (void*)serve, csp) ? -1 : 0);
- pthread_attr_destroy(&attrs);
- }
-#endif
+ log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
+ http->hostport);
-#if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
-#define SELECTED_ONE_OPTION
- child_id = _beginthread(
- (void (*)(void *))serve,
- 64 * 1024,
- csp);
-#endif
+ log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
+ csp->ip_addr_str, http->ocmd);
-#if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
-#define SELECTED_ONE_OPTION
- child_id = _beginthread(
- (void(* _Optlink)(void*))serve,
- NULL,
- 64 * 1024,
- csp);
-#endif
+ rsp = error_response(csp, "connect-failed", errno);
-#if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
-#define SELECTED_ONE_OPTION
+ if(rsp)
{
- thread_id tid = spawn_thread
- (server_thread, "server", B_NORMAL_PRIORITY, csp);
-
- if ((tid >= 0) && (resume_thread(tid) == B_OK))
- {
- child_id = (int) tid;
- }
- else
+ if (write_socket(csp->cfd, rsp->head, rsp->head_length)
+ || write_socket(csp->cfd, rsp->body, rsp->content_length))
{
- child_id = -1;
+ log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
}
}
-#endif
-
-#if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
-#define SELECTED_ONE_OPTION
- csp->cfd = ReleaseSocket(csp->cfd, -1);
- if((child_id = (int)CreateNewProcTags(
- NP_Entry, (ULONG)server_thread,
- NP_Output, Output(),
- NP_CloseOutput, FALSE,
- NP_Name, (ULONG)"privoxy child",
- NP_StackSize, 200*1024,
- TAG_DONE)))
- {
- childs++;
- ((struct Task *)child_id)->tc_UserData = csp;
- Signal((struct Task *)child_id, SIGF_SINGLE);
- Wait(SIGF_SINGLE);
- }
-#endif
-
-#if !defined(SELECTED_ONE_OPTION)
- child_id = fork();
-
- /* This block is only needed when using fork().
- * When using threads, the server thread was
- * created and run by the call to _beginthread().
- */
- if (child_id == 0) /* child */
- {
- serve(csp);
- _exit(0);
-
- }
- else if (child_id > 0) /* parent */
- {
- /* in a fork()'d environment, the parent's
- * copy of the client socket and the CSP
- * are not used.
- */
-
-#if !defined(_WIN32) && defined(__CYGWIN__)
- wait( NULL );
-#endif /* !defined(_WIN32) && defined(__CYGWIN__) */
- close_socket(csp->cfd);
- csp->flags &= ~CSP_FLAG_ACTIVE;
- }
-#endif
-
-#undef SELECTED_ONE_OPTION
-/* end of cpp switch () */
-
- if (child_id < 0) /* failed */
- {
- char buf[BUFFER_SIZE];
- log_error(LOG_LEVEL_ERROR, "can't fork: %E");
-
- sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
-
- write_socket(csp->cfd, buf, strlen(buf));
- close_socket(csp->cfd);
- csp->flags &= ~CSP_FLAG_ACTIVE;
- sleep(5);
- continue;
- }
+ free_http_response(rsp);
+ freez(hdr);
+ return;
}
- else
+ }
+ else
+ {
+ /*
+ * We're running an SSL tunnel and we're not forwarding,
+ * so just send the "connect succeeded" message to the
+ * client, flush the rest, and get out of the way.
+ */
+ log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
+ csp->ip_addr_str, http->ocmd);
+
+ if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
{
- serve(csp);
+ freez(hdr);
+ return;
}
+ IOB_RESET(csp);
}
- /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
+ /* we're finished with the client's header */
+ freez(hdr);
- /* Clean up. Aim: free all memory (no leaks) */
-#ifdef FEATURE_GRACEFUL_TERMINATION
+ maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
- log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
+ /* pass data between the client and server
+ * until one or the other shuts down the connection.
+ */
- unload_current_config_file();
- unload_current_actions_file();
- unload_current_re_filterfile();
-#ifdef FEATURE_TRUST
- unload_current_trust_file();
-#endif
+ server_body = 0;
- if (config->multi_threaded)
+ for (;;)
{
- int i = 60;
- do
- {
- sleep(1);
- sweep();
- } while ((clients->next != NULL) && (--i > 0));
+#ifdef __OS2__
+ /*
+ * FD_ZERO here seems to point to an errant macro which crashes.
+ * So do this by hand for now...
+ */
+ memset(&rfds,0x00,sizeof(fd_set));
+#else
+ FD_ZERO(&rfds);
+#endif
+ FD_SET(csp->cfd, &rfds);
+ FD_SET(csp->sfd, &rfds);
- if (i <= 0)
+ n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
+
+ if (n < 0)
{
- log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
+ log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
+ return;
}
- }
- sweep();
- sweep();
-
-#if defined(unix)
- free(basedir);
-#endif
-#if defined(_WIN32) && !defined(_WIN_CONSOLE)
- /* Cleanup - remove taskbar icon etc. */
- TermLogWindow();
-#endif
- exit(0);
-#endif /* FEATURE_GRACEFUL_TERMINATION */
-
-}
+ /* this is the body of the browser's request
+ * just read it and write it.
+ */
-/*********************************************************************
- *
- * Function : relay_server_traffic
- *
- * Description : receive traffic from the server and relay it
- * to the client, with some processing
- *
- * Parameters :
- * 1 : client_state structure
- *
- *
- * Returns : JB_ERR_OK if there may be more work
- * : other values for errors
- *
- **********************************************************************/
+ if (FD_ISSET(csp->cfd, &rfds))
+ {
+ len = read_socket(csp->cfd, buf, sizeof(buf));
-static jb_err relay_server_traffic( struct client_state *csp )
-{
-#ifdef FEATURE_KILL_POPUPS
- int block_popups; /* bool, 1==will block popups */
- int block_popups_now = 0; /* bool, 1==currently blocking popups */
-#endif /* def FEATURE_KILL_POPUPS */
-
- char buf[BUFFER_SIZE];
- int len; /* for buffer sizes */
- int ms_iis5_hack = 0;
- int byte_count = 0;
- char *hdr;
- char *p;
+ if (len <= 0)
+ {
+ break; /* "game over, man" */
+ }
- /* Skeleton for HTTP response, if we should intercept the request */
- struct http_response *rsp;
+ if (write_socket(csp->sfd, buf, (size_t)len))
+ {
+ log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
+ return;
+ }
+ continue;
+ }
- int pcrs_filter; /* bool, 1==will filter through pcrs */
- int gif_deanimate; /* bool, 1==will deanimate gifs */
- int jpeg_inspect; /* bool, 1==will inspect jpegs */
+ /*
+ * The server wants to talk. It could be the header or the body.
+ * If `hdr' is null, then it's the header otherwise it's the body.
+ * FIXME: Does `hdr' really mean `host'? No.
+ */
-#ifdef FEATURE_KILL_POPUPS
- block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
-#endif /* def FEATURE_KILL_POPUPS */
- pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
- (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
+ if (FD_ISSET(csp->sfd, &rfds))
+ {
+ fflush( 0 );
+ len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
- gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
+ if (len < 0)
+ {
+ log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
- jpeg_inspect = ((csp->action->flags & ACTION_JPEG_INSPECT) != 0);
+ log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
+ csp->ip_addr_str, http->ocmd);
- fflush (0);
- len = read_socket (csp->sfd, buf, sizeof (buf) - 1);
+ rsp = error_response(csp, "connect-failed", errno);
- if (len < 0)
- {
- log_error (LOG_LEVEL_ERROR, "read from: %s failed: %E", csp->http->host);
+ if(rsp)
+ {
+ if (write_socket(csp->cfd, rsp->head, rsp->head_length)
+ || write_socket(csp->cfd, rsp->body, rsp->content_length))
+ {
+ log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
+ }
+ }
- log_error (LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
- csp->ip_addr_str, csp->http->ocmd);
+ free_http_response(rsp);
+ return;
+ }
- rsp = error_response (csp, "connect-failed", errno);
+ /* Add a trailing zero. This lets filter_popups
+ * use string operations.
+ */
+ buf[len] = '\0';
- if (rsp)
- {
- if (write_socket (csp->cfd, rsp->head, rsp->head_length)
- || write_socket (csp->cfd, rsp->body, rsp->content_length))
+#ifdef FEATURE_KILL_POPUPS
+ /* Filter the popups on this read. */
+ if (block_popups_now)
{
- log_error (LOG_LEVEL_ERROR, "write to: %s failed: %E",
- csp->http->host);
+ filter_popups(buf, csp);
}
- }
+#endif /* def FEATURE_KILL_POPUPS */
- free_http_response (rsp);
- return JB_ERR_GENERIC;
- }
+ /* Normally, this would indicate that we've read
+ * as much as the server has sent us and we can
+ * close the client connection. However, Microsoft
+ * in its wisdom has released IIS/5 with a bug that
+ * prevents it from sending the trailing \r\n in
+ * a 302 redirect header (and possibly other headers).
+ * To work around this if we've haven't parsed
+ * a full header we'll append a trailing \r\n
+ * and see if this now generates a valid one.
+ *
+ * This hack shouldn't have any impacts. If we've
+ * already transmitted the header or if this is a
+ * SSL connection, then we won't bother with this
+ * hack. So we only work on partially received
+ * headers. If we append a \r\n and this still
+ * doesn't generate a valid header, then we won't
+ * transmit anything to the client.
+ */
+ if (len == 0)
+ {
- /* Add a trailing zero. This lets filter_popups
- * use string operations.
- */
- buf[len] = '\0';
+ if (server_body || http->ssl)
+ {
+ /*
+ * If we have been buffering up the document,
+ * now is the time to apply content modification
+ * and send the result to the client.
+ */
+ if (content_filter)
+ {
+ /*
+ * If the content filter fails, use the original
+ * buffer and length.
+ * (see p != NULL ? p : csp->iob->cur below)
+ */
+ if (NULL == (p = (*content_filter)(csp)))
+ {
+ csp->content_length = csp->iob->eod - csp->iob->cur;
+ }
+
+ hdr = sed(server_patterns, add_server_headers, csp);
+ if (hdr == NULL)
+ {
+ /* FIXME Should handle error properly */
+ log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
+ }
+
+ if (write_socket(csp->cfd, hdr, strlen(hdr))
+ || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
+ {
+ log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
+ freez(hdr);
+ freez(p);
+ return;
+ }
+
+ freez(hdr);
+ freez(p);
+ }
+
+ break; /* "game over, man" */
+ }
-#ifdef FEATURE_KILL_POPUPS
- /* Filter the popups on this read. */
- if (block_popups_now)
- {
- filter_popups (buf, csp);
- }
-#endif /* def FEATURE_KILL_POPUPS */
+ /*
+ * This is NOT the body, so
+ * Let's pretend the server just sent us a blank line.
+ */
+ len = sprintf(buf, "\r\n");
+ /*
+ * Now, let the normal header parsing algorithm below do its
+ * job. If it fails, we'll exit instead of continuing.
+ */
- /* Normally, this would indicate that we've read
- * as much as the server has sent us and we can
- * close the client connection. However, Microsoft
- * in its wisdom has released IIS/5 with a bug that
- * prevents it from sending the trailing \r\n in
- * a 302 redirect header (and possibly other headers).
- * To work around this if we've haven't parsed
- * a full header we'll append a trailing \r\n
- * and see if this now generates a valid one.
- *
- * This hack shouldn't have any impacts. If we've
- * already transmitted the header or if this is a
- * SSL connection, then we won't bother with this
- * hack. So we only work on partially received
- * headers. If we append a \r\n and this still
- * doesn't generate a valid header, then we won't
- * transmit anything to the client.
- */
- if (len == 0)
- {
+ ms_iis5_hack = 1;
+ }
- if (csp->all_headers_read || csp->http->ssl)
- {
/*
- * If we have been buffering up the document,
- * now is the time to apply content modification
- * and send the result to the client.
+ * If this is an SSL connection or we're in the body
+ * of the server document, just write it to the client,
+ * unless we need to buffer the body for later content-filtering
*/
- if (csp->content_filter)
+
+ if (server_body || http->ssl)
{
- /*
- * If the content filter fails, use the original
- * buffer and length.
- * (see p != NULL ? p : csp->iob->cur below)
- */
- if (NULL == (p = (*csp->content_filter) (csp)))
+ if (content_filter)
{
- csp->content_length = csp->iob->eod - csp->iob->cur;
+ /*
+ * If there is no memory left for buffering the content, or the buffer limit
+ * has been reached, switch to non-filtering mode, i.e. make & write the
+ * header, flush the iob and buf, and get out of the way.
+ */
+ if (add_to_iob(csp, buf, len))
+ {
+ size_t hdrlen;
+ int flushed;
+
+ log_error(LOG_LEVEL_ERROR, "Flushing header and buffers. Stepping back from filtering.");
+
+ hdr = sed(server_patterns, add_server_headers, csp);
+ if (hdr == NULL)
+ {
+ /*
+ * Memory is too tight to even generate the header.
+ * Send our static "Out-of-memory" page.
+ */
+ log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
+ rsp = cgi_error_memory();
+
+ if (write_socket(csp->cfd, rsp->head, rsp->head_length)
+ || write_socket(csp->cfd, rsp->body, rsp->content_length))
+ {
+ log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
+ }
+ return;
+ }
+
+ hdrlen = strlen(hdr);
+
+ if (write_socket(csp->cfd, hdr, hdrlen)
+ || ((flushed = flush_socket(csp->cfd, csp)) < 0)
+ || (write_socket(csp->cfd, buf, (size_t) len)))
+ {
+ log_error(LOG_LEVEL_CONNECT, "Flush header and buffers to client failed: %E");
+
+ freez(hdr);
+ return;
+ }
+
+ byte_count += hdrlen + flushed + len;
+ freez(hdr);
+ content_filter = NULL;
+ server_body = 1;
+
+ }
}
-
- hdr = sed (server_patterns, add_server_headers, csp);
- if (hdr == NULL)
+ else
{
- /* FIXME Should handle error properly */
- log_error (LOG_LEVEL_FATAL,
- "Out of memory parsing server header");
-
+ if (write_socket(csp->cfd, buf, (size_t)len))
+ {
+ log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
+ return;
+ }
}
+ byte_count += len;
+ continue;
+ }
+ else
+ {
+ /* we're still looking for the end of the
+ * server's header ... (does that make header
+ * parsing an "out of body experience" ?
+ */
- if (write_socket (csp->cfd, hdr, strlen (hdr))
- || write_socket (csp->cfd, p != NULL ? p : csp->iob->cur,
- csp->content_length))
+ /*
+ * buffer up the data we just read. If that fails,
+ * there's little we can do but send our static
+ * out-of-memory page.
+ */
+ if (add_to_iob(csp, buf, len))
{
- log_error (LOG_LEVEL_ERROR,
- "write modified content to client failed: %E");
- return JB_ERR_GENERIC;
+ log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
+ rsp = cgi_error_memory();
+
+ if (write_socket(csp->cfd, rsp->head, rsp->head_length)
+ || write_socket(csp->cfd, rsp->body, rsp->content_length))
+ {
+ log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
+ }
+ return;
}
- freez (hdr);
- if (NULL != p)
+ /* get header lines from the iob */
+
+ while ((p = get_header(csp)) != NULL)
{
- freez (p);
+ if (*p == '\0')
+ {
+ /* see following note */
+ break;
+ }
+ enlist(csp->headers, p);
+ freez(p);
}
- }
- log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
- csp->ip_addr_str, csp->http->ocmd, byte_count);
- return JB_ERR_GENERIC;
- }
-
- /*
- * This is NOT the body, so
- * Let's pretend the server just sent us a blank line.
- */
- len = sprintf (buf, "\r\n");
-
- /*
- * Now, let the normal header parsing algorithm below do its
- * job. If it fails, we'll exit instead of continuing.
- */
-
- ms_iis5_hack = 1;
- }
-
- /*
- * If this is an SSL connection or we're in the body
- * of the server document, just write it to the client,
- * unless we need to buffer the body for later content-filtering
- */
- if (csp->all_headers_read || csp->http->ssl)
- {
- if (csp->content_filter)
- {
- add_to_iob (csp, buf, len);
+ /* NOTE: there are no "empty" headers so
+ * if the pointer `p' is not NULL we must
+ * assume that we reached the end of the
+ * buffer before we hit the end of the header.
+ */
- /*
- * If the buffer limit will be reached on the next read,
- * switch to non-filtering mode, i.e. make & write the
- * header, flush the socket and get out of the way.
- */
- if (((size_t) (csp->iob->eod - csp->iob->buf)) +
- (size_t) BUFFER_SIZE > csp->config->buffer_limit)
- {
- size_t hdrlen;
+ if (p)
+ {
+ if (ms_iis5_hack)
+ {
+ /* Well, we tried our MS IIS/5
+ * hack and it didn't work.
+ * The header is incomplete
+ * and there isn't anything
+ * we can do about it.
+ */
+ break;
+ }
+ else
+ {
+ /* Since we have to wait for
+ * more from the server before
+ * we can parse the headers
+ * we just continue here.
+ */
+ continue;
+ }
+ }
- log_error (LOG_LEVEL_ERROR,
- "Buffer size limit reached! Flushing and stepping back.");
+ /* we have now received the entire header.
+ * filter it and send the result to the client
+ */
- hdr = sed (server_patterns, add_server_headers, csp);
+ hdr = sed(server_patterns, add_server_headers, csp);
if (hdr == NULL)
{
/* FIXME Should handle error properly */
- log_error (LOG_LEVEL_FATAL,
- "Out of memory parsing server header");
+ log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
}
- hdrlen = strlen (hdr);
- byte_count += hdrlen;
+#ifdef FEATURE_KILL_POPUPS
+ /* Start blocking popups if appropriate. */
- if (write_socket (csp->cfd, hdr, hdrlen)
- || ((len = flush_socket (csp->cfd, csp)) < 0))
+ if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
+ !http->ssl && /* We talk plaintext */
+ block_popups) /* Policy allows */
{
- log_error (LOG_LEVEL_CONNECT,
- "write header to client failed: %E");
-
- freez (hdr);
- return JB_ERR_GENERIC;
+ block_popups_now = 1;
+ /*
+ * Filter the part of the body that came in the same read
+ * as the last headers:
+ */
+ filter_popups(csp->iob->cur, csp);
}
- freez (hdr);
- byte_count += len;
+#endif /* def FEATURE_KILL_POPUPS */
- csp->content_filter = NULL;
- csp->all_headers_read = 1;
+ /* Buffer and pcrs filter this if appropriate. */
- }
- }
- else
- {
- if (write_socket (csp->cfd, buf, (size_t) len))
- {
- log_error (LOG_LEVEL_ERROR, "write to client failed: %E");
- return JB_ERR_GENERIC;
- }
- }
- byte_count += len;
- return JB_ERR_OK ;
- }
- else
- {
- /*
- * we're still looking for the end of the
- * server's header ... (does that make header
- * parsing an "out of body experience" ?
- */
+ if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
+ !http->ssl && /* We talk plaintext */
+ pcrs_filter) /* Policy allows */
+ {
+ content_filter = pcrs_filter_response;
+ }
- /* buffer up the data we just read */
- add_to_iob (csp, buf, len);
+ /* Buffer and gif_deanimate this if appropriate. */
- /* get header lines from the iob */
+ if ((csp->content_type & CT_GIF) && /* It's an image/gif MIME-Type */
+ !http->ssl && /* We talk plaintext */
+ gif_deanimate) /* Policy allows */
+ {
+ content_filter = gif_deanimate_response;
+ }
- while ((p = get_header (csp)) != NULL)
- {
- if (*p == '\0')
- {
- /* see following note */
- log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
- csp->ip_addr_str, csp->http->ocmd, byte_count);
- return JB_ERR_GENERIC;
- }
- enlist (csp->headers, p);
- freez (p);
- }
+ /* Buffer and jpg_inspect this if appropriate. */
- /* NOTE: there are no "empty" headers so
- * if the pointer `p' is not NULL we must
- * assume that we reached the end of the
- * buffer before we hit the end of the header.
- */
+ if ((csp->content_type & CT_JPEG) && /* It's an image/jpeg MIME-Type */
+ !http->ssl && /* We talk plaintext */
+ jpeg_inspect) /* Policy allows */
+ {
+ content_filter = jpeg_inspect_response;
+ }
- if (p)
- {
- if (ms_iis5_hack)
- {
- /* Well, we tried our MS IIS/5
- * hack and it didn't work.
- * The header is incomplete
- * and there isn't anything
- * we can do about it.
- */
- log_error(LOG_LEVEL_CLF, "Incomplete Server Header: %s - - [%T] \"%s\" 200 %d",
- csp->ip_addr_str, csp->http->ocmd, byte_count);
- return JB_ERR_GENERIC;
- }
- else
- {
- /* Since we have to wait for
- * more from the server before
- * we can parse the headers
- * we just continue here.
+ /*
+ * Only write if we're not buffering for content modification
*/
- return JB_ERR_OK;
- }
- }
-
- /* we have now received the entire header.
- * filter it and send the result to the client
- */
-
- hdr = sed (server_patterns, add_server_headers, csp);
- if (hdr == NULL)
- {
- /* FIXME Should handle error properly */
- log_error (LOG_LEVEL_FATAL, "Out of memory parsing server header");
- }
+ if (!content_filter)
+ {
+ /* write the server's (modified) header to
+ * the client (along with anything else that
+ * may be in the buffer)
+ */
+
+ if (write_socket(csp->cfd, hdr, strlen(hdr))
+ || ((len = flush_socket(csp->cfd, csp)) < 0))
+ {
+ log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
+
+ /* the write failed, so don't bother
+ * mentioning it to the client...
+ * it probably can't hear us anyway.
+ */
+ freez(hdr);
+ return;
+ }
+
+ byte_count += len;
+ }
-
+ /* we're finished with the server's header */
-#ifdef FEATURE_KILL_POPUPS
- /* Start blocking popups if appropriate. */
+ freez(hdr);
+ server_body = 1;
- if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
- !csp->http->ssl && /* We talk plaintext */
- block_popups) /* Policy allows */
- {
- block_popups_now = 1;
- /*
- * Filter the part of the body that came in the same read
- * as the last headers:
- */
- filter_popups (csp->iob->cur, csp);
+ /* If this was a MS IIS/5 hack then it means
+ * the server has already closed the
+ * connection. Nothing more to read. Time
+ * to bail.
+ */
+ if (ms_iis5_hack)
+ {
+ break;
+ }
+ }
+ continue;
}
-#endif /* def FEATURE_KILL_POPUPS */
+ return; /* huh? we should never get here */
+ }
- /* Buffer and pcrs filter this if appropriate. */
+ log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
+ csp->ip_addr_str, http->ocmd, byte_count);
+}
- if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
- !csp->http->ssl && /* We talk plaintext */
- pcrs_filter) /* Policy allows */
- {
- csp->content_filter = pcrs_filter_response;
- }
- /* Buffer and gif_deanimate this if appropriate. */
+/*********************************************************************
+ *
+ * Function : serve
+ *
+ * Description : This is little more than chat. We only "serve" to
+ * to close any socket that chat may have opened.
+ *
+ * Parameters :
+ * 1 : csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns : N/A
+ *
+ *********************************************************************/
+#ifdef AMIGA
+void serve(struct client_state *csp)
+#else /* ifndef AMIGA */
+static void serve(struct client_state *csp)
+#endif /* def AMIGA */
+{
+ chat(csp);
+ close_socket(csp->cfd);
- if ((csp->content_type & CT_GIF) && /* It's a image/gif MIME-Type */
- !csp->http->ssl && /* We talk plaintext */
- gif_deanimate) /* Policy allows */
- {
- csp->content_filter = gif_deanimate_response;
- }
+ if (csp->sfd != JB_INVALID_SOCKET)
+ {
+ close_socket(csp->sfd);
+ }
- /* Buffer and jpg_inspect this if appropriate. */
+ csp->flags &= ~CSP_FLAG_ACTIVE;
- if ((csp->content_type & CT_JPEG) && /* It's an image/jpeg MIME-Type */
- !csp->http->ssl && /* We talk plaintext */
- jpeg_inspect) /* Policy allows */
- {
- csp->content_filter = jpeg_inspect_response;
- }
+}
- /*
- * Only write if we're not buffering for content modification
- */
- if (!csp->content_filter)
- {
- /* write the server's (modified) header to
- * the client (along with anything else that
- * may be in the buffer)
- */
- if (write_socket (csp->cfd, hdr, strlen (hdr))
- || ((len = flush_socket (csp->cfd, csp)) < 0))
- {
- log_error (LOG_LEVEL_CONNECT,
- "write header to client failed: %E");
- /* the write failed, so don't bother
- * mentioning it to the client...
- * it probably can't hear us anyway.
- */
- freez (hdr);
- return JB_ERR_GENERIC;
- }
+#ifdef __BEOS__
+/*********************************************************************
+ *
+ * Function : server_thread
+ *
+ * Description : We only exist to call `serve' in a threaded environment.
+ *
+ * Parameters :
+ * 1 : data = Current client state (buffers, headers, etc...)
+ *
+ * Returns : Always 0.
+ *
+ *********************************************************************/
+static int32 server_thread(void *data)
+{
+ serve((struct client_state *) data);
+ return 0;
- byte_count += len;
- }
+}
+#endif
- /* we're finished with the server's header */
- freez (hdr);
- csp->all_headers_read = 1;
+/*********************************************************************
+ *
+ * Function : usage
+ *
+ * Description : Print usage info & exit.
+ *
+ * Parameters : Pointer to argv[0] for identifying ourselves
+ *
+ * Returns : No. ,-)
+ *
+ *********************************************************************/
+void usage(const char *myname)
+{
+ printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
+#if !defined(unix)
+ "Usage: %s [--help] [--version] [configfile]\n"
+#else
+ "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
+#endif
+ "Aborting.\n", myname);
+
+ exit(2);
- /* If this was a MS IIS/5 hack then it means
- * the server has already closed the
- * connection. Nothing more to read. Time
- * to bail.
- */
- if (ms_iis5_hack)
- {
- return JB_ERR_GENERIC ;
- }
- }
- return JB_ERR_OK ;
-} /* END relay_server_traffic() */
+}
/*********************************************************************
*
- * Function : read_client_headers
+ * Function : main
*
- * Description : read all the client headers, and fill in the
- * http* structure
+ * Description : Load the config file and start the listen loop.
+ * This function is a lot more *sane* with the `load_config'
+ * and `listen_loop' functions; although it stills does
+ * a *little* too much for my taste.
*
* Parameters :
- * 1 : client_state structure
- * 2 : http_request structure
- *
+ * 1 : argc = Number of parameters (including $0).
+ * 2 : argv = Array of (char *)'s to the parameters.
+ *
+ * Returns : 1 if : can't open config file, unrecognized directive,
+ * stats requested in multi-thread mode, can't open the
+ * log file, can't open the jar file, listen port is invalid,
+ * any load fails, and can't bind port.
+ *
+ * Else main never returns, the process must be signaled
+ * to terminate execution. Or, on Windows, use the
+ * "File", "Exit" menu option.
*
- * Returns : JB_ERR_OK - headers read and parsed ok
- * : other values - an error occurred.
*********************************************************************/
-
-static jb_err read_client_headers( struct client_state *csp, struct http_request *http )
+#ifdef __MINGW32__
+int real_main(int argc, const char *argv[])
+#else
+int main(int argc, const char *argv[])
+#endif
{
-
+ int argc_pos = 0;
+#ifdef unix
+ struct passwd *pw = NULL;
+ struct group *grp = NULL;
char *p;
- char *req;
- char buf[BUFFER_SIZE];
- int len; /* for buffer sizes */
+ int do_chroot = 0;
+#endif
+
+ Argc = argc;
+ Argv = argv;
+
+ configfile =
+#if !defined(_WIN32)
+ "config"
+#else
+ "config.txt"
+#endif
+ ;
/*
- * Read the client's request. Note that since we're not using select() we
- * could get blocked here if a client connected, then didn't say anything!
- *
- * This will read all the client headers.
+ * Parse the command line arguments
*/
-
- req = NULL ;
- for (;;)
+ while (++argc_pos < argc)
{
- len = read_socket(csp->cfd, buf, sizeof(buf));
-
- if (len <= 0) break; /* error! */
+ if (strcmp(argv[argc_pos], "--help") == 0)
+ {
+ usage(argv[0]);
+ }
- add_to_iob(csp, buf, len);
+ else if(strcmp(argv[argc_pos], "--version") == 0)
+ {
+ printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
+ exit(0);
+ }
- req = get_header(csp);
+#if defined(unix)
- if (req == NULL)
+ else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
{
- break; /* no HTTP request! */
+ no_daemon = 1;
}
- if (*req == '\0')
+ else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
{
- continue; /* more to come! */
+ if (++argc_pos == argc) usage(argv[0]);
+ pidfile = strdup(argv[argc_pos]);
}
- /* When we get here we have read one header which is enough */
- /* to check whether the connection is allowed */
- break;
- }
-
+ else if (strcmp(argv[argc_pos], "--user" ) == 0)
+ {
+ if (++argc_pos == argc) usage(argv[argc_pos]);
- for(;;)
- {
+ if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
+ {
+ *p++ = '\0';
+ if (NULL == (grp = getgrnam(p)))
+ {
+ log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
+ }
+ }
- if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
- {
- len = read_socket(csp->cfd, buf, sizeof(buf));
- if (len <= 0)
+ if (NULL == (pw = getpwnam(argv[argc_pos])))
{
- log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
- return JB_ERR_GENERIC;
+ log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
}
- add_to_iob(csp, buf, len);
- continue;
+
+ if (p != NULL) *--p = '\0';
}
- if (p == NULL) break;
+ else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
+ {
+ do_chroot = 1;
+ }
- enlist(csp->headers, p);
- freez(p);
+#endif /* defined(unix) */
- }
+ else
+ {
+ configfile = argv[argc_pos];
+ }
- parse_http_request(req, http, csp);
- freez(req);
+ } /* -END- while (more arguments) */
- if (http->cmd == NULL)
+#if defined(unix)
+ if ( *configfile != '/' )
{
- strcpy(buf, CHEADER);
- write_socket(csp->cfd, buf, strlen(buf));
+ char *abs_file, cwd[1024];
- log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
+ /* make config-filename absolute here */
+ if ( !(getcwd(cwd, sizeof(cwd))))
+ {
+ perror("get working dir failed");
+ exit( 1 );
+ }
- return JB_ERR_GENERIC;
+ if (!(basedir = strdup(cwd))
+ || (!(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 ))))
+ {
+ perror("malloc failed");
+ exit( 1 );
+ }
+ strcpy( abs_file, basedir );
+ strcat( abs_file, "/" );
+ strcat( abs_file, configfile );
+ configfile = abs_file;
}
+#endif /* defined unix */
- return JB_ERR_OK ;
+ files->next = NULL;
+ clients->next = NULL;
-} /* END read_client_headers */
+#ifdef AMIGA
+ InitAmiga();
+#elif defined(_WIN32)
+ InitWin32();
+#endif
+#ifdef OSX_DARWIN
+ /*
+ * Prepare global mutex semaphores
+ */
+ pthread_mutex_init(&gmtime_mutex,0);
+ pthread_mutex_init(&localtime_mutex,0);
+ pthread_mutex_init(&gethostbyaddr_mutex,0);
+ pthread_mutex_init(&gethostbyname_mutex,0);
+#endif /* def OSX_DARWIN */
-/*********************************************************************
- *
- * Function : process_client_headers
- *
- * Description : Process client headers
- * FIXME: Add description of what we do here!
- *
- * Parameters :
- * 1 : client_state structure
- * 2 : http_request structure
- *
- *
- * Returns : JB_ERR_OK - headers processed ok
- * : other values - an error occurred.
- *********************************************************************/
+#ifdef FEATURE_PTHREAD
+ pthread_mutex_init(&log_mutex,0);
+ pthread_mutex_init(&log_init_mutex,0);
+#endif /* FEATURE_PTHREAD */
-static jb_err process_client_headers( struct client_state *csp, struct http_request *http )
+ /*
+ * Unix signal handling
+ *
+ * Catch the abort, interrupt and terminate signals for a graceful exit
+ * Catch the hangup signal so the errlog can be reopened.
+ * Ignore the broken pipe signals (FIXME: Why?)
+ */
+#if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
{
+ int idx;
+ const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
+ const int ignored_signals[] = { SIGPIPE, 0 };
-
-#ifdef FEATURE_FORCE_LOAD
- /* If this request contains the FORCE_PREFIX,
- * better get rid of it now and set the force flag --oes
- * Changed to use the http structure rather than the req field --jaa
- * FIXME: This isn't enough -- there is the path and referrer etc! *
- */
-
- if (strstr(http->url, FORCE_PREFIX))
+ for (idx = 0; catched_signals[idx] != 0; idx++)
+ {
+ if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
{
- strclean(http->url, FORCE_PREFIX);
- strclean(http->path, FORCE_PREFIX);
- log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", http->url);
- csp->flags |= CSP_FLAG_FORCED;
+ log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
}
+ }
-#endif /* def FEATURE_FORCE_LOAD */
-
-
- /* decide how to route the HTTP request */
-
- if ((http->fwd = forward_url(http, csp)) == NULL)
+ for (idx = 0; ignored_signals[idx] != 0; idx++)
{
- log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
- /* Never get here - LOG_LEVEL_FATAL causes program exit */
+ if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
+ {
+ log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
+ }
}
- /* build the http request to send to the server
- * we have to do one of the following:
- *
- * create = use the original HTTP request to create a new
- * HTTP request that has either the path component
- * without the http://domainspec (w/path) or the
- * full orininal URL (w/url)
- * Note that the path and/or the HTTP version may
- * have been altered by now.
- *
- * connect = Open a socket to the host:port of the server
- * and short-circuit server and client socket.
- *
- * pass = Pass the request unchanged if forwarding a CONNECT
- * request to a parent proxy. Note that we'll be sending
- * the CFAIL message ourselves if connecting to the parent
- * fails, but we won't send a CSUCCEED message if it works,
- * since that would result in a double message (ours and the
- * parent's). After sending the request to the parent, we simply
- * tunnel.
- *
- * here's the matrix:
- * SSL
- * 0 1
- * +--------+--------+
- * | | |
- * 0 | create | connect|
- * | w/path | |
- * Forwarding +--------+--------+
- * | | |
- * 1 | create | pass |
- * | w/url | |
- * +--------+--------+
- *
- */
-
+}
+#else /* ifdef _WIN32 */
+# ifdef _WIN_CONSOLE
/*
- * Determine the actions for this URL
+ * We *are* in a windows console app.
+ * Print a verbose messages about FAQ's and such
*/
-#ifdef FEATURE_TOGGLE
- if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
- {
- /* Most compatible set of actions (i.e. none) */
- init_current_action(csp->action);
- }
- else
-#endif /* ndef FEATURE_TOGGLE */
- {
- url_actions(http, csp);
- }
-
-
+ printf(win32_blurb);
+# endif /* def _WIN_CONSOLE */
+#endif /* def _WIN32 */
+ /* Initialize the CGI subsystem */
+ cgi_init_error_messages();
/*
- * Downgrade http version from 1.1 to 1.0 if +downgrade
- * action applies
+ * If runnig on unix and without the --nodaemon
+ * option, become a daemon. I.e. fork, detach
+ * from tty and get process group leadership
*/
- if ( (http->ssl == 0)
- && (!strcmpic(http->ver, "HTTP/1.1"))
- && (csp->action->flags & ACTION_DOWNGRADE))
+#if defined(unix)
+{
+ pid_t pid = 0;
+#if 0
+ int fd;
+#endif
+
+ if (!no_daemon)
{
- freez(http->ver);
- http->ver = strdup("HTTP/1.0");
+ pid = fork();
- if (http->ver == NULL)
+ if ( pid < 0 ) /* error */
{
- log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
+ perror("fork");
+ exit( 3 );
}
- }
+ else if ( pid != 0 ) /* parent */
+ {
+ int status;
+ pid_t wpid;
+ /*
+ * must check for errors
+ * child died due to missing files aso
+ */
+ sleep( 1 );
+ wpid = waitpid( pid, &status, WNOHANG );
+ if ( wpid != 0 )
+ {
+ exit( 1 );
+ }
+ exit( 0 );
+ }
+ /* child */
+#if 1
+ /* Should be more portable, but not as well tested */
+ setsid();
+#else /* !1 */
+#ifdef __FreeBSD__
+ setpgrp(0,0);
+#else /* ndef __FreeBSD__ */
+ setpgrp();
+#endif /* ndef __FreeBSD__ */
+ fd = open("/dev/tty", O_RDONLY);
+ if ( fd )
+ {
+ /* no error check here */
+ ioctl( fd, TIOCNOTTY,0 );
+ close ( fd );
+ }
+#endif /* 1 */
+ /* FIXME: should close stderr (fd 2) here too, but the test
+ * for existence
+ * and load config file is done in listen_loop() and puts
+ * some messages on stderr there.
+ */
- /*
- * Save a copy of the original request for logging
- */
- http->ocmd = strdup(http->cmd);
+ close( 0 );
+ close( 1 );
+ chdir("/");
- if (http->ocmd == NULL)
- {
- log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
- }
+ } /* -END- if (!no_daemon) */
/*
- * (Re)build the HTTP request for non-SSL requests.
- * If forwarding, use the whole URL, else, use only the path.
+ * As soon as we have written the PID file, we can switch
+ * to the user and group ID indicated by the --user option
*/
- if (http->ssl == 0)
+ write_pid_file();
+
+ if (NULL != pw)
{
- freez(http->cmd);
-
- http->cmd = strdup(http->gpc);
- string_append(&http->cmd, " ");
-
- if (http->fwd->forward_host)
+ if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
{
- string_append(&http->cmd, http->url);
+ log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
+ }
+ if (do_chroot)
+ {
+ if (!pw->pw_dir)
+ {
+ log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
+ }
+ if (chroot(pw->pw_dir) < 0)
+ {
+ log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
+ }
+ if (chdir ("/"))
+ {
+ log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
+ }
}
- else
+ if (setuid(pw->pw_uid))
{
- string_append(&http->cmd, http->path);
+ log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
}
+ if (do_chroot)
+ {
+ char putenv_dummy[64];
- string_append(&http->cmd, " ");
- string_append(&http->cmd, http->ver);
+ strcpy(putenv_dummy, "HOME=/");
+ if (putenv(putenv_dummy) != 0)
+ {
+ log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
+ }
- if (http->cmd == NULL)
- {
- log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
+ snprintf(putenv_dummy, 64, "USER=%s", pw->pw_name);
+ if (putenv(putenv_dummy) != 0)
+ {
+ log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
+ }
}
}
- enlist_first(csp->headers, http->cmd);
-
-
- /*
- * If the user has not supplied any wafers, and the user has not
- * told us to suppress the vanilla wafer, then send the vanilla wafer.
- */
- if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
- && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
+ else if (do_chroot)
{
- enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
+ log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
}
+}
+#endif /* defined unix */
+
+ listen_loop();
+
+ /* NOTREACHED */
+ return(-1);
+
+}
- return JB_ERR_OK ;
-} /* process_client_headers */
/*********************************************************************
*
- * Function : intercept_page
+ * Function : bind_port_helper
*
- * Description : Check whether to intercept page
+ * Description : Bind the listen port. Handles logging, and aborts
+ * on failure.
*
* Parameters :
- * 1 : client_state structure
- * 2 : http_request structure
- *
+ * 1 : config = Privoxy configuration. Specifies port
+ * to bind to.
+ *
+ * Returns : Port that was opened.
*
- * Returns : JB_ERR_OK - Do NOT intercept this page
- * : JB_ERR_INTERCEPT - intercept this page
- * : all other values - an error occurred.
*********************************************************************/
-static jb_err intercept_page( struct client_state *csp, struct http_request *http )
+static jb_socket bind_port_helper(struct configuration_spec * config)
{
+ int result;
+ jb_socket bfd;
- /* Skeleton for HTTP response, if we should intercept the request */
- struct http_response *rsp;
-
-
-/*
- * These next lines are a little ugly, but they simplifies the if statements
- * below. Basically if TOGGLE, then we want the if to test if the
- * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
- * then we want the if to test for CSP_FLAG_FORCED , else we don't
- */
-#ifdef FEATURE_TOGGLE
-# define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
-#else /* ifndef FEATURE_TOGGLE */
-# define IS_TOGGLED_ON_AND
-#endif /* ndef FEATURE_TOGGLE */
-#ifdef FEATURE_FORCE_LOAD
-# define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
-#else /* ifndef FEATURE_FORCE_LOAD */
-# define IS_NOT_FORCED_AND
-#endif /* def FEATURE_FORCE_LOAD */
-
-#define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
-
- if (
- /* a CGI call was detected and answered */
- (NULL != (rsp = dispatch_cgi(csp)))
-
- /* or we are enabled and... */
- || (IS_ENABLED_AND (
-
- /* ..the request was blocked */
- ( NULL != (rsp = block_url(csp)))
+ if ( (config->haddr != NULL)
+ && (config->haddr[0] == '1')
+ && (config->haddr[1] == '2')
+ && (config->haddr[2] == '7')
+ && (config->haddr[3] == '.') )
+ {
+ log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
+ config->hport);
+ }
+ else if (config->haddr == NULL)
+ {
+ log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
+ config->hport);
+ }
+ else
+ {
+ log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
+ config->hport, config->haddr);
+ }
- /* ..or untrusted */
-#ifdef FEATURE_TRUST
- || ( NULL != (rsp = trust_url(csp)))
-#endif /* def FEATURE_TRUST */
+ result = bind_port(config->haddr, config->hport, &bfd);
- /* ..or a fast redirect kicked in */
-#ifdef FEATURE_FAST_REDIRECTS
- || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
- (NULL != (rsp = redirect_url(csp))))
-#endif /* def FEATURE_FAST_REDIRECTS */
- ))
- )
+ if (result < 0)
{
- /* Write the answer to the client */
- if (write_socket(csp->cfd, rsp->head, rsp->head_length)
- || write_socket(csp->cfd, rsp->body, rsp->content_length))
+ switch(result)
{
- log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
- }
+ case -3 :
+ log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
+ "There may be another Privoxy or some other "
+ "proxy running on port %d",
+ (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
+ config->hport, config->hport);
-#ifdef FEATURE_STATISTICS
- /* Count as a rejected request */
- csp->flags |= CSP_FLAG_REJECTED;
-#endif /* def FEATURE_STATISTICS */
+ case -2 :
+ log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
+ "The hostname is not resolvable",
+ (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
- /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
- log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
- log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
+ default :
+ log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
+ (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
+ }
- /* Clean up and return */
- free_http_response(rsp);
- return JB_ERR_INTERCEPT;
+ /* shouldn't get here */
+ return JB_INVALID_SOCKET;
}
- /* When we get here the request doesn't need to be intercepted */
- return JB_ERR_OK ;
+ config->need_bind = 0;
+
+ return bfd;
}
+
/*********************************************************************
*
- * Function : open_forwarding_connection
+ * Function : listen_loop
+ *
+ * Description : bind the listen port and enter a "FOREVER" listening loop.
*
- * Description : Check whether to intercept page
+ * Parameters : N/A
+ *
+ * Returns : Never.
*
- * Parameters :
- * 1 : client_state structure
- * 2 : http_request structure
- *
- * Returns : JB_ERR_OK - Connection opened ok
- * : all other values - an error occurred.
*********************************************************************/
-static jb_err open_forwarding_connection(struct client_state *csp )
+static void listen_loop(void)
{
- struct http_response *rsp;
-
-#ifdef FEATURE_ACTIVITY_CONSOLE
- accumulate_stats(STATS_REQUEST, 1);
-#endif /* def FEATURE_ACTIVITY_CONSOLE */
- log_error(LOG_LEVEL_GPC, "%s%s", csp->http->hostport, csp->http->path);
+ struct client_state *csp = NULL;
+ jb_socket bfd;
+ struct configuration_spec * config;
- if (csp->http->fwd->forward_host)
- {
- log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
- csp->http->fwd->forward_host, csp->http->fwd->forward_port,
- csp->http->hostport);
- }
- else
+ config = load_config();
+
+ bfd = bind_port_helper(config);
+
+#ifdef FEATURE_GRACEFUL_TERMINATION
+ while (!g_terminate)
+#else
+ for (;;)
+#endif
{
- log_error(LOG_LEVEL_CONNECT, "to %s", csp->http->hostport);
- }
+#if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
+ while (waitpid(-1, NULL, WNOHANG) > 0)
+ {
+ /* zombie children */
+ }
+#endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
- /* here we connect to the server, gateway, or the forwarder */
+ /*
+ * Free data that was used by died threads
+ */
+ sweep();
- csp->sfd = forwarded_connect(csp->http->fwd, csp->http, csp);
+#if defined(unix)
+ /*
+ * Re-open the errlog after HUP signal
+ */
+ if (received_hup_signal)
+ {
+ init_error_log(Argv[0], config->logfile, config->debug);
+ received_hup_signal = 0;
+ }
+#endif
- if (csp->sfd == JB_INVALID_SOCKET)
- {
- log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
- csp->http->hostport);
+#ifdef __OS2__
+#ifdef FEATURE_COOKIE_JAR
+ /*
+ * Need a workaround here: we have to fclose() the jarfile, or we die because it's
+ * already open. I think unload_configfile() is not being run, which should do
+ * this work. Until that can get resolved, we'll use this workaround.
+ */
+ if (csp)
+ if(csp->config)
+ if (csp->config->jar)
+ {
+ fclose(csp->config->jar);
+ csp->config->jar = NULL;
+ }
+#endif /* FEATURE_COOKIE_JAR */
+#endif /* __OS2__ */
+
+ if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
+ {
+ log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
+ continue;
+ }
+
+ csp->flags |= CSP_FLAG_ACTIVE;
+ csp->sfd = JB_INVALID_SOCKET;
+
+ csp->config = config = load_config();
+
+ if ( config->need_bind )
+ {
+ /*
+ * Since we were listening to the "old port", we will not see
+ * a "listen" param change until the next IJB request. So, at
+ * least 1 more request must be made for us to find the new
+ * setting. I am simply closing the old socket and binding the
+ * new one.
+ *
+ * Which-ever is correct, we will serve 1 more page via the
+ * old settings. This should probably be a "show-proxy-args"
+ * request. This should not be a so common of an operation
+ * that this will hurt people's feelings.
+ */
+
+ close_socket(bfd);
+
+ bfd = bind_port_helper(config);
+ }
+
+ log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
+
+ if (!accept_connection(csp, bfd))
+ {
+ log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
+
+#ifdef AMIGA
+ if(!childs)
+ {
+ exit(1);
+ }
+#endif
+ freez(csp);
+ continue;
+ }
+ else
+ {
+ log_error(LOG_LEVEL_CONNECT, "OK");
+ }
- if (errno == EINVAL)
+#ifdef FEATURE_TOGGLE
+ if (global_toggle_state)
{
- rsp = error_response(csp, "no-such-domain", errno);
-
- log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
- csp->ip_addr_str, csp->http->ocmd);
+ csp->flags |= CSP_FLAG_TOGGLED_ON;
}
- else
+#endif /* def FEATURE_TOGGLE */
+
+ if (run_loader(csp))
{
- rsp = error_response(csp, "connect-failed", errno);
+ log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
+ /* Never get here - LOG_LEVEL_FATAL causes program exit */
+ }
- log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
- csp->ip_addr_str, csp->http->ocmd);
+#ifdef FEATURE_ACL
+ if (block_acl(NULL,csp))
+ {
+ log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
+ close_socket(csp->cfd);
+ freez(csp);
+ continue;
}
+#endif /* def FEATURE_ACL */
+ /* add it to the list of clients */
+ csp->next = clients->next;
+ clients->next = csp;
- /* Write the answer to the client */
- if(rsp)
+ if (config->multi_threaded)
{
- if (write_socket(csp->cfd, rsp->head, rsp->head_length)
- || write_socket(csp->cfd, rsp->body, rsp->content_length))
+ int child_id;
+
+/* this is a switch () statment in the C preprocessor - ugh */
+#undef SELECTED_ONE_OPTION
+
+/* Use Pthreads in preference to native code */
+#if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
+#define SELECTED_ONE_OPTION
{
- log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
+ pthread_t the_thread;
+ pthread_attr_t attrs;
+
+ pthread_attr_init(&attrs);
+ pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
+ errno = pthread_create(&the_thread, &attrs,
+ (void*)serve, csp);
+ child_id = errno ? -1 : 0;
+ pthread_attr_destroy(&attrs);
}
- }
+#endif
- free_http_response(rsp);
- return JB_ERR_GENERIC;
- }
+#if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
+#define SELECTED_ONE_OPTION
+ child_id = _beginthread(
+ (void (*)(void *))serve,
+ 64 * 1024,
+ csp);
+#endif
- log_error(LOG_LEVEL_CONNECT, "OK");
- return JB_ERR_OK ;
+#if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
+#define SELECTED_ONE_OPTION
+ child_id = _beginthread(
+ (void(* _Optlink)(void*))serve,
+ NULL,
+ 64 * 1024,
+ csp);
+#endif
-} /* END open_forwarding_connection() */
+#if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
+#define SELECTED_ONE_OPTION
+ {
+ thread_id tid = spawn_thread
+ (server_thread, "server", B_NORMAL_PRIORITY, csp);
+ if ((tid >= 0) && (resume_thread(tid) == B_OK))
+ {
+ child_id = (int) tid;
+ }
+ else
+ {
+ child_id = -1;
+ }
+ }
+#endif
-/*********************************************************************
- *
- * Function : send_client_headers_to_server
- *
- * Description : send the client headers (possibly modified) to the server
- *
- * Parameters :
- * 1 : client_state structure
- * 2 : http_request structure
- *
- *
- * Returns : JB_ERR_OK - headers sent ok
- * : other values - an error occurred.
- *********************************************************************/
+#if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
+#define SELECTED_ONE_OPTION
+ csp->cfd = ReleaseSocket(csp->cfd, -1);
+
+ if((child_id = (int)CreateNewProcTags(
+ NP_Entry, (ULONG)server_thread,
+ NP_Output, Output(),
+ NP_CloseOutput, FALSE,
+ NP_Name, (ULONG)"privoxy child",
+ NP_StackSize, 200*1024,
+ TAG_DONE)))
+ {
+ childs++;
+ ((struct Task *)child_id)->tc_UserData = csp;
+ Signal((struct Task *)child_id, SIGF_SINGLE);
+ Wait(SIGF_SINGLE);
+ }
+#endif
-static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http, char *hdr )
-{
+#if !defined(SELECTED_ONE_OPTION)
+ child_id = fork();
- struct http_response *rsp;
+ /* This block is only needed when using fork().
+ * When using threads, the server thread was
+ * created and run by the call to _beginthread().
+ */
+ if (child_id == 0) /* child */
+ {
+ int rc = 0;
+#ifdef FEATURE_TOGGLE
+ int inherited_toggle_state = global_toggle_state;
+#endif /* def FEATURE_TOGGLE */
- if (http->fwd->forward_host || (http->ssl == 0))
- {
- /* write the client's (modified) header to the server
- * (along with anything else that may be in the buffer)
- */
+ serve(csp);
- if (write_socket(csp->sfd, hdr, strlen(hdr))
- || (flush_socket(csp->sfd, csp) < 0))
- {
- log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
- http->hostport);
+ /*
+ * If we've been toggled or we've blocked the request, tell Mom
+ */
- log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
- csp->ip_addr_str, http->ocmd);
+#ifdef FEATURE_TOGGLE
+ if (inherited_toggle_state != global_toggle_state)
+ {
+ rc |= RC_FLAG_TOGGLED;
+ }
+#endif /* def FEATURE_TOGGLE */
- rsp = error_response(csp, "connect-failed", errno);
+#ifdef FEATURE_STATISTICS
+ if (csp->flags & CSP_FLAG_REJECTED)
+ {
+ rc |= RC_FLAG_BLOCKED;
+ }
+#endif /* ndef FEATURE_STATISTICS */
- if(rsp)
+ _exit(rc);
+ }
+ else if (child_id > 0) /* parent */
{
- if (write_socket(csp->cfd, rsp->head, rsp->head_length)
- || write_socket(csp->cfd, rsp->body, rsp->content_length))
+ /* in a fork()'d environment, the parent's
+ * copy of the client socket and the CSP
+ * are not used.
+ */
+ int child_status;
+#if !defined(_WIN32) && !defined(__CYGWIN__)
+
+ wait( &child_status );
+
+ /*
+ * Evaluate child's return code: If the child has
+ * - been toggled, toggle ourselves
+ * - blocked its request, bump up the stats counter
+ */
+
+#ifdef FEATURE_TOGGLE
+ if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
{
- log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
+ global_toggle_state = !global_toggle_state;
+ }
+#endif /* def FEATURE_TOGGLE */
+
+#ifdef FEATURE_STATISTICS
+ urls_read++;
+ if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
+ {
+ urls_rejected++;
}
+#endif /* def FEATURE_STATISTICS */
+
+#endif /* !defined(_WIN32) && defined(__CYGWIN__) */
+ close_socket(csp->cfd);
+ csp->flags &= ~CSP_FLAG_ACTIVE;
}
+#endif
- free_http_response(rsp);
- return JB_ERR_GENERIC;
- }
- }
- else
- {
- /*
- * We're running an SSL tunnel and we're not forwarding,
- * so just send the "connect succeeded" message to the
- * client, flush the rest, and get out of the way.
- */
- log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
- csp->ip_addr_str, http->ocmd);
+#undef SELECTED_ONE_OPTION
+/* end of cpp switch () */
- if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
+ if (child_id < 0) /* failed */
+ {
+ char buf[BUFFER_SIZE];
+
+ log_error(LOG_LEVEL_ERROR, "can't fork: %E");
+
+ sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
+
+ write_socket(csp->cfd, buf, strlen(buf));
+ close_socket(csp->cfd);
+ csp->flags &= ~CSP_FLAG_ACTIVE;
+ sleep(5);
+ continue;
+ }
+ }
+ else
{
- return JB_ERR_OK;
+ serve(csp);
}
- IOB_RESET(csp);
}
- return JB_ERR_OK ;
-} /* END send_client_headers_to_server */
+ /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
+ /* Clean up. Aim: free all memory (no leaks) */
+#ifdef FEATURE_GRACEFUL_TERMINATION
-/*********************************************************************
- *
- * Function : is_connect_request_allowed
- *
- * Description : send the client headers (possibly modified) to the server
- *
- * Parameters :
- * 1 : client_state structure
- *
- *
- *
- * Returns : JB_ERR_OK - connect request allowed
- * : other values - connect request not allowed
- *********************************************************************/
-static jb_err is_connect_request_allowed( struct client_state *csp )
-{
- /*
- * Check if a CONNECT request is allowable:
- * In the absence of a +limit-connect action, allow only port 443.
- * If there is an action, allow whatever matches the specificaton.
- */
+ log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
+
+ unload_current_config_file();
+ unload_current_actions_file();
+ unload_current_re_filterfile();
+#ifdef FEATURE_TRUST
+ unload_current_trust_file();
+#endif
- if(csp->http->ssl)
+ if (config->multi_threaded)
{
- if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
- || (csp->action->flags & ACTION_LIMIT_CONNECT
- && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
+ int i = 60;
+ do
{
- char buf[BUFFER_SIZE];
- strcpy(buf, CFORBIDDEN);
- write_socket(csp->cfd, buf, strlen(buf));
-
- log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
- log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
+ sleep(1);
+ sweep();
+ } while ((clients->next != NULL) && (--i > 0));
- return JB_ERR_GENERIC;
+ if (i <= 0)
+ {
+ log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
}
}
+ sweep();
+ sweep();
+
+#if defined(unix)
+ freez(basedir);
+#endif
+ freez(configfile);
+
+#ifdef FEATURE_COOKIE_JAR
+ if (NULL != config->jar)
+ {
+ fclose(config->jar);
+ }
+#endif
+
+#if defined(_WIN32) && !defined(_WIN_CONSOLE)
+ /* Cleanup - remove taskbar icon etc. */
+ TermLogWindow();
+#endif
+
+ exit(0);
+#endif /* FEATURE_GRACEFUL_TERMINATION */
+
+}
- return JB_ERR_OK ;
-} /* END is_connect_request_allowed */
/*
Local Variables: