1 const char jcc_rcs[] = "$Id: jcc.c,v 1.361 2011/07/17 13:37:32 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/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-2010 the
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.
34 *********************************************************************/
40 #include <sys/types.h>
49 # ifndef FEATURE_PTHREAD
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
65 # if !defined (__OS2__)
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
74 #include <sys/termios.h>
85 # include <socket.h> /* BeOS has select() for sockets only. */
86 # include <OS.h> /* declarations for threads and stuff. */
89 # if defined(__EMX__) || defined(__OS2__)
90 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
95 #define bzero(B,N) memset(B,0x00,n)
110 #include "miscutil.h"
112 #include "jbsockets.h"
117 #include "urlmatch.h"
119 const char jcc_h_rcs[] = JCC_H_VERSION;
120 const char project_h_rcs[] = PROJECT_H_VERSION;
123 struct client_states clients[1];
124 struct file_list files[1];
126 #ifdef FEATURE_STATISTICS
127 int urls_read = 0; /* total nr of urls read inc rejected */
128 int urls_rejected = 0; /* total nr of urls rejected */
129 #endif /* def FEATURE_STATISTICS */
131 #ifdef FEATURE_GRACEFUL_TERMINATION
135 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
136 static void sig_handler(int the_signal);
138 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
139 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
140 static jb_err get_server_headers(struct client_state *csp);
141 static const char *crunch_reason(const struct http_response *rsp);
142 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
143 static char *get_request_line(struct client_state *csp);
144 static jb_err receive_client_request(struct client_state *csp);
145 static jb_err parse_client_request(struct client_state *csp);
146 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
147 static jb_err change_request_destination(struct client_state *csp);
148 static void chat(struct client_state *csp);
149 static void serve(struct client_state *csp);
150 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
151 static void usage(const char *myname);
153 static void initialize_mutexes(void);
154 static jb_socket bind_port_helper(const char *haddr, int hport);
155 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
156 static void close_ports_helper(jb_socket sockets[]);
157 static void listen_loop(void);
160 void serve(struct client_state *csp);
161 #else /* ifndef AMIGA */
162 static void serve(struct client_state *csp);
163 #endif /* def AMIGA */
166 static int32 server_thread(void *data);
167 #endif /* def __BEOS__ */
170 #define sleep(N) Sleep(((N) * 1000))
174 #define sleep(N) DosSleep(((N) * 100))
177 #ifdef MUTEX_LOCKS_AVAILABLE
179 * XXX: Does the locking stuff really belong in this file?
181 privoxy_mutex_t log_mutex;
182 privoxy_mutex_t log_init_mutex;
183 privoxy_mutex_t connection_reuse_mutex;
185 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
186 privoxy_mutex_t resolver_mutex;
187 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
189 #ifndef HAVE_GMTIME_R
190 privoxy_mutex_t gmtime_mutex;
191 #endif /* ndef HAVE_GMTIME_R */
193 #ifndef HAVE_LOCALTIME_R
194 privoxy_mutex_t localtime_mutex;
195 #endif /* ndef HAVE_GMTIME_R */
198 privoxy_mutex_t rand_mutex;
199 #endif /* ndef HAVE_RANDOM */
201 #endif /* def MUTEX_LOCKS_AVAILABLE */
204 const char *basedir = NULL;
205 const char *pidfile = NULL;
206 static int received_hup_signal = 0;
207 #endif /* defined unix */
209 /* HTTP snipplets. */
210 static const char CSUCCEED[] =
211 "HTTP/1.0 200 Connection established\r\n"
212 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
214 static const char CHEADER[] =
215 "HTTP/1.0 400 Invalid header received from client\r\n"
216 "Proxy-Agent: Privoxy " VERSION "\r\n"
217 "Content-Type: text/plain\r\n"
218 "Connection: close\r\n\r\n"
219 "Invalid header received from client.\r\n";
221 static const char FTP_RESPONSE[] =
222 "HTTP/1.0 400 Invalid request received from client\r\n"
223 "Content-Type: text/plain\r\n"
224 "Connection: close\r\n\r\n"
225 "Invalid request. Privoxy doesn't support FTP.\r\n";
227 static const char GOPHER_RESPONSE[] =
228 "HTTP/1.0 400 Invalid request received from client\r\n"
229 "Content-Type: text/plain\r\n"
230 "Connection: close\r\n\r\n"
231 "Invalid request. Privoxy doesn't support gopher.\r\n";
233 /* XXX: should be a template */
234 static const char MISSING_DESTINATION_RESPONSE[] =
235 "HTTP/1.0 400 Bad request received from client\r\n"
236 "Proxy-Agent: Privoxy " VERSION "\r\n"
237 "Content-Type: text/plain\r\n"
238 "Connection: close\r\n\r\n"
239 "Bad request. Privoxy was unable to extract the destination.\r\n";
241 /* XXX: should be a template */
242 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
243 "HTTP/1.0 502 Server or forwarder response invalid\r\n"
244 "Proxy-Agent: Privoxy " VERSION "\r\n"
245 "Content-Type: text/plain\r\n"
246 "Connection: close\r\n\r\n"
247 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
249 /* XXX: should be a template */
250 static const char MESSED_UP_REQUEST_RESPONSE[] =
251 "HTTP/1.0 400 Malformed request after rewriting\r\n"
252 "Proxy-Agent: Privoxy " VERSION "\r\n"
253 "Content-Type: text/plain\r\n"
254 "Connection: close\r\n\r\n"
255 "Bad request. Messed up with header filters.\r\n";
257 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
258 "HTTP/1.0 503 Too many open connections\r\n"
259 "Proxy-Agent: Privoxy " VERSION "\r\n"
260 "Content-Type: text/plain\r\n"
261 "Connection: close\r\n\r\n"
262 "Maximum number of open connections reached.\r\n";
264 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
265 "HTTP/1.0 504 Connection timeout\r\n"
266 "Proxy-Agent: Privoxy " VERSION "\r\n"
267 "Content-Type: text/plain\r\n"
268 "Connection: close\r\n\r\n"
269 "The connection timed out because the client request didn't arrive in time.\r\n";
271 /* A function to crunch a response */
272 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
274 /* Crunch function flags */
275 #define CF_NO_FLAGS 0
276 /* Cruncher applies to forced requests as well */
277 #define CF_IGNORE_FORCE 1
278 /* Crunched requests are counted for the block statistics */
279 #define CF_COUNT_AS_REJECT 2
281 /* A crunch function and its flags */
284 const crunch_func_ptr cruncher;
288 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
290 /* Complete list of cruncher functions */
291 static const struct cruncher crunchers_all[] = {
292 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
293 { block_url, CF_COUNT_AS_REJECT },
295 { trust_url, CF_COUNT_AS_REJECT },
296 #endif /* def FEATURE_TRUST */
297 { redirect_url, CF_NO_FLAGS },
298 { dispatch_cgi, CF_IGNORE_FORCE},
302 /* Light version, used after tags are applied */
303 static const struct cruncher crunchers_light[] = {
304 { block_url, CF_COUNT_AS_REJECT },
305 { redirect_url, CF_NO_FLAGS },
311 * XXX: Don't we really mean
317 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
318 /*********************************************************************
320 * Function : sig_handler
322 * Description : Signal handler for different signals.
323 * Exit gracefully on TERM and INT
324 * or set a flag that will cause the errlog
325 * to be reopened by the main thread on HUP.
328 * 1 : the_signal = the signal cause this function to call
332 *********************************************************************/
333 static void sig_handler(int the_signal)
339 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
351 received_hup_signal = 1;
357 * We shouldn't be here, unless we catch signals
358 * in main() that we can't handle here!
360 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
368 /*********************************************************************
370 * Function : client_protocol_is_unsupported
372 * Description : Checks if the client used a known unsupported
373 * protocol and deals with it by sending an error
377 * 1 : csp = Current client state (buffers, headers, etc...)
378 * 2 : req = the first request line send by the client
380 * Returns : TRUE if an error response has been generated, or
381 * FALSE if the request doesn't look invalid.
383 *********************************************************************/
384 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
387 * If it's a FTP or gopher request, we don't support it.
389 * These checks are better than nothing, but they might
390 * not work in all configurations and some clients might
391 * have problems digesting the answer.
393 * They should, however, never cause more problems than
394 * Privoxy's old behaviour (returning the misleading HTML
397 * "Could not resolve http://(ftp|gopher)://example.org").
399 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
401 const char *response = NULL;
402 const char *protocol = NULL;
404 if (!strncmpic(req, "GET ftp://", 10))
406 response = FTP_RESPONSE;
411 response = GOPHER_RESPONSE;
414 log_error(LOG_LEVEL_ERROR,
415 "%s tried to use Privoxy as %s proxy: %s",
416 csp->ip_addr_str, protocol, req);
417 log_error(LOG_LEVEL_CLF,
418 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
420 write_socket(csp->cfd, response, strlen(response));
429 /*********************************************************************
431 * Function : get_request_destination_elsewhere
433 * Description : If the client's request was redirected into
434 * Privoxy without the client's knowledge,
435 * the request line lacks the destination host.
437 * This function tries to get it elsewhere,
438 * provided accept-intercepted-requests is enabled.
440 * "Elsewhere" currently only means "Host: header",
441 * but in the future we may ask the redirecting
442 * packet filter to look the destination up.
444 * If the destination stays unknown, an error
445 * response is send to the client and headers
446 * are freed so that chat() can return directly.
449 * 1 : csp = Current client state (buffers, headers, etc...)
450 * 2 : headers = a header list
452 * Returns : JB_ERR_OK if the destination is now known, or
453 * JB_ERR_PARSE if it isn't.
455 *********************************************************************/
456 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
460 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
462 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
463 " Privoxy isn't configured to accept intercepted requests.",
464 csp->ip_addr_str, csp->http->cmd);
465 /* XXX: Use correct size */
466 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
467 csp->ip_addr_str, csp->http->cmd);
469 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
470 destroy_list(headers);
474 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
476 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
477 /* Split the domain we just got for pattern matching */
478 init_domain_components(csp->http);
485 /* We can't work without destination. Go spread the news.*/
487 req = list_to_text(headers);
489 /* XXX: Use correct size */
490 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
491 csp->ip_addr_str, csp->http->cmd);
492 log_error(LOG_LEVEL_ERROR,
493 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
494 csp->ip_addr_str, csp->http->cmd, req);
497 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
498 destroy_list(headers);
503 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
504 * to get the destination IP address, use it as host directly
505 * or do a reverse DNS lookup first.
510 /*********************************************************************
512 * Function : get_server_headers
514 * Description : Parses server headers in iob and fills them
515 * into csp->headers so that they can later be
519 * 1 : csp = Current client state (buffers, headers, etc...)
521 * Returns : JB_ERR_OK if everything went fine, or
522 * JB_ERR_PARSE if the headers were incomplete.
524 *********************************************************************/
525 static jb_err get_server_headers(struct client_state *csp)
527 int continue_hack_in_da_house = 0;
530 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
535 * continue hack in da house. Ignore the ending of
536 * this head and continue enlisting header lines.
537 * The reason is described below.
539 enlist(csp->headers, "");
540 continue_hack_in_da_house = 0;
543 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
546 * It's a bodyless continue response, don't
547 * stop header parsing after reaching its end.
549 * As a result Privoxy will concatenate the
550 * next response's head and parse and deliver
551 * the headers as if they belonged to one request.
553 * The client will separate them because of the
554 * empty line between them.
556 * XXX: What we're doing here is clearly against
557 * the intended purpose of the continue header,
558 * and under some conditions (HTTP/1.0 client request)
559 * it's a standard violation.
561 * Anyway, "sort of against the spec" is preferable
562 * to "always getting confused by Continue responses"
563 * (Privoxy's behaviour before this hack was added)
565 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
566 continue_hack_in_da_house = 1;
568 else if (*header == '\0')
571 * If the header is empty, but the Continue hack
572 * isn't active, we can assume that we reached the
573 * end of the buffer before we hit the end of the
576 * Inform the caller an let it decide how to handle it.
581 if (JB_ERR_MEMORY == enlist(csp->headers, header))
584 * XXX: Should we quit the request and return a
585 * out of memory error page instead?
587 log_error(LOG_LEVEL_ERROR,
588 "Out of memory while enlisting server headers. %s lost.",
598 /*********************************************************************
600 * Function : crunch_reason
602 * Description : Translates the crunch reason code into a string.
605 * 1 : rsp = a http_response
607 * Returns : A string with the crunch reason or an error description.
609 *********************************************************************/
610 static const char *crunch_reason(const struct http_response *rsp)
612 char * reason = NULL;
617 return "Internal error while searching for crunch reason";
620 switch (rsp->crunch_reason)
623 reason = "Unsupported HTTP feature";
629 reason = "Untrusted";
632 reason = "Redirected";
638 reason = "DNS failure";
640 case FORWARDING_FAILED:
641 reason = "Forwarding failed";
644 reason = "Connection failure";
647 reason = "Out of memory (may mask other reasons)";
649 case CONNECTION_TIMEOUT:
650 reason = "Connection timeout";
653 reason = "No server data received";
656 reason = "No reason recorded";
664 /*********************************************************************
666 * Function : send_crunch_response
668 * Description : Delivers already prepared response for
669 * intercepted requests, logs the interception
670 * and frees the response.
673 * 1 : csp = Current client state (buffers, headers, etc...)
674 * 1 : rsp = Fully prepared response. Will be freed on exit.
678 *********************************************************************/
679 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
681 const struct http_request *http = csp->http;
685 assert(rsp->head != NULL);
689 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
693 * Extract the status code from the actual head
694 * that will be send to the client. It is the only
695 * way to get it right for all requests, including
696 * the fixed ones for out-of-memory problems.
698 * A head starts like this: 'HTTP/1.1 200...'
702 status_code[0] = rsp->head[9];
703 status_code[1] = rsp->head[10];
704 status_code[2] = rsp->head[11];
705 status_code[3] = '\0';
707 /* Log that the request was crunched and why. */
708 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
709 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
710 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
712 /* Write the answer to the client */
713 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
714 || write_socket(csp->cfd, rsp->body, rsp->content_length))
716 /* There is nothing we can do about it. */
717 log_error(LOG_LEVEL_ERROR,
718 "Couldn't deliver the error message through client socket %d: %E",
722 /* Clean up and return */
723 if (cgi_error_memory() != rsp)
725 free_http_response(rsp);
731 /*********************************************************************
733 * Function : crunch_response_triggered
735 * Description : Checks if the request has to be crunched,
736 * and delivers the crunch response if necessary.
739 * 1 : csp = Current client state (buffers, headers, etc...)
740 * 2 : crunchers = list of cruncher functions to run
742 * Returns : TRUE if the request was answered with a crunch response
745 *********************************************************************/
746 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
748 struct http_response *rsp = NULL;
749 const struct cruncher *c;
752 * If CGI request crunching is disabled,
753 * check the CGI dispatcher out of order to
754 * prevent unintentional blocks or redirects.
756 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
757 && (NULL != (rsp = dispatch_cgi(csp))))
759 /* Deliver, log and free the interception response. */
760 send_crunch_response(csp, rsp);
761 csp->flags |= CSP_FLAG_CRUNCHED;
765 for (c = crunchers; c->cruncher != NULL; c++)
768 * Check the cruncher if either Privoxy is toggled
769 * on and the request isn't forced, or if the cruncher
770 * applies to forced requests as well.
772 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
773 !(csp->flags & CSP_FLAG_FORCED)) ||
774 (c->flags & CF_IGNORE_FORCE))
776 rsp = c->cruncher(csp);
779 /* Deliver, log and free the interception response. */
780 send_crunch_response(csp, rsp);
781 csp->flags |= CSP_FLAG_CRUNCHED;
782 #ifdef FEATURE_STATISTICS
783 if (c->flags & CF_COUNT_AS_REJECT)
785 csp->flags |= CSP_FLAG_REJECTED;
787 #endif /* def FEATURE_STATISTICS */
798 /*********************************************************************
800 * Function : build_request_line
802 * Description : Builds the HTTP request line.
804 * If a HTTP forwarder is used it expects the whole URL,
805 * web servers only get the path.
808 * 1 : csp = Current client state (buffers, headers, etc...)
809 * 2 : fwd = The forwarding spec used for the request
810 * XXX: Should use http->fwd instead.
811 * 3 : request_line = The old request line which will be replaced.
813 * Returns : Nothing. Terminates in case of memory problems.
815 *********************************************************************/
816 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
818 struct http_request *http = csp->http;
820 assert(http->ssl == 0);
823 * Downgrade http version from 1.1 to 1.0
824 * if +downgrade action applies.
826 if ( (csp->action->flags & ACTION_DOWNGRADE)
827 && (!strcmpic(http->ver, "HTTP/1.1")))
830 http->ver = strdup("HTTP/1.0");
832 if (http->ver == NULL)
834 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
839 * Rebuild the request line.
841 freez(*request_line);
842 *request_line = strdup(http->gpc);
843 string_append(request_line, " ");
845 if (fwd->forward_host)
847 string_append(request_line, http->url);
851 string_append(request_line, http->path);
853 string_append(request_line, " ");
854 string_append(request_line, http->ver);
856 if (*request_line == NULL)
858 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
860 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
864 /*********************************************************************
866 * Function : change_request_destination
868 * Description : Parse a (rewritten) request line and regenerate
869 * the http request data.
872 * 1 : csp = Current client state (buffers, headers, etc...)
874 * Returns : Forwards the parse_http_request() return code.
875 * Terminates in case of memory problems.
877 *********************************************************************/
878 static jb_err change_request_destination(struct client_state *csp)
880 struct http_request *http = csp->http;
883 log_error(LOG_LEVEL_INFO, "Rewrite detected: %s", csp->headers->first->str);
884 free_http_request(http);
885 err = parse_http_request(csp->headers->first->str, http);
886 if (JB_ERR_OK != err)
888 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
889 jb_err_to_string(err));
893 /* XXX: ocmd is a misleading name */
894 http->ocmd = strdup(http->cmd);
895 if (http->ocmd == NULL)
897 log_error(LOG_LEVEL_FATAL,
898 "Out of memory copying rewritten HTTP request line");
906 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
907 /*********************************************************************
909 * Function : server_response_is_complete
911 * Description : Determines whether we should stop reading
912 * from the server socket.
915 * 1 : csp = Current client state (buffers, headers, etc...)
916 * 2 : content_length = Length of content received so far.
918 * Returns : TRUE if the response is complete,
921 *********************************************************************/
922 static int server_response_is_complete(struct client_state *csp,
923 unsigned long long content_length)
925 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
927 if (!strcmpic(csp->http->gpc, "HEAD"))
930 * "HEAD" implies no body, we are thus expecting
931 * no content. XXX: incomplete "list" of methods?
933 csp->expected_content_length = 0;
934 content_length_known = TRUE;
937 if (csp->http->status == 204 || csp->http->status == 304)
940 * Expect no body. XXX: incomplete "list" of status codes?
942 csp->expected_content_length = 0;
943 content_length_known = TRUE;
946 return (content_length_known && ((0 == csp->expected_content_length)
947 || (csp->expected_content_length <= content_length)));
951 #ifdef FEATURE_CONNECTION_SHARING
952 /*********************************************************************
954 * Function : wait_for_alive_connections
956 * Description : Waits for alive connections to timeout.
962 *********************************************************************/
963 static void wait_for_alive_connections(void)
965 int connections_alive = close_unusable_connections();
967 while (0 < connections_alive)
969 log_error(LOG_LEVEL_CONNECT,
970 "Waiting for %d connections to timeout.",
973 connections_alive = close_unusable_connections();
976 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
979 #endif /* def FEATURE_CONNECTION_SHARING */
982 /*********************************************************************
984 * Function : save_connection_destination
986 * Description : Remembers a connection for reuse later on.
989 * 1 : sfd = Open socket to remember.
990 * 2 : http = The destination for the connection.
991 * 3 : fwd = The forwarder settings used.
992 * 3 : server_connection = storage.
996 *********************************************************************/
997 void save_connection_destination(jb_socket sfd,
998 const struct http_request *http,
999 const struct forward_spec *fwd,
1000 struct reusable_connection *server_connection)
1002 assert(sfd != JB_INVALID_SOCKET);
1003 assert(NULL != http->host);
1005 server_connection->sfd = sfd;
1006 server_connection->host = strdup(http->host);
1007 if (NULL == server_connection->host)
1009 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
1011 server_connection->port = http->port;
1013 assert(NULL != fwd);
1014 assert(server_connection->gateway_host == NULL);
1015 assert(server_connection->gateway_port == 0);
1016 assert(server_connection->forwarder_type == 0);
1017 assert(server_connection->forward_host == NULL);
1018 assert(server_connection->forward_port == 0);
1020 server_connection->forwarder_type = fwd->type;
1021 if (NULL != fwd->gateway_host)
1023 server_connection->gateway_host = strdup(fwd->gateway_host);
1024 if (NULL == server_connection->gateway_host)
1026 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
1031 server_connection->gateway_host = NULL;
1033 server_connection->gateway_port = fwd->gateway_port;
1035 if (NULL != fwd->forward_host)
1037 server_connection->forward_host = strdup(fwd->forward_host);
1038 if (NULL == server_connection->forward_host)
1040 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
1045 server_connection->forward_host = NULL;
1047 server_connection->forward_port = fwd->forward_port;
1051 /*********************************************************************
1053 * Function : verify_request_length
1055 * Description : Checks if we already got the whole client requests
1056 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1059 * Data that doesn't belong to the current request is
1060 * thrown away to let the client retry on a clean socket.
1062 * XXX: This is a hack until we can deal with multiple
1063 * pipelined requests at the same time.
1067 * 1 : csp = Current client state (buffers, headers, etc...)
1071 *********************************************************************/
1072 static void verify_request_length(struct client_state *csp)
1074 unsigned long long buffered_request_bytes =
1075 (unsigned long long)(csp->iob->eod - csp->iob->cur);
1077 if ((csp->expected_client_content_length != 0)
1078 && (buffered_request_bytes != 0))
1080 if (csp->expected_client_content_length >= buffered_request_bytes)
1082 csp->expected_client_content_length -= buffered_request_bytes;
1083 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1084 "to account for the %llu ones we already got.",
1085 csp->expected_client_content_length, buffered_request_bytes);
1089 assert(csp->iob->eod > csp->iob->cur + csp->expected_client_content_length);
1090 csp->iob->eod = csp->iob->cur + csp->expected_client_content_length;
1091 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1092 "Marking the server socket tainted after throwing %llu bytes away.",
1093 buffered_request_bytes - csp->expected_client_content_length);
1094 csp->expected_client_content_length = 0;
1095 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1098 if (csp->expected_client_content_length == 0)
1100 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1104 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1105 && ((csp->iob->cur[0] != '\0') || (csp->expected_client_content_length != 0)))
1107 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1108 if (strcmpic(csp->http->gpc, "GET")
1109 && strcmpic(csp->http->gpc, "HEAD")
1110 && strcmpic(csp->http->gpc, "TRACE")
1111 && strcmpic(csp->http->gpc, "OPTIONS")
1112 && strcmpic(csp->http->gpc, "DELETE"))
1114 /* XXX: this is an incomplete hack */
1115 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1116 log_error(LOG_LEVEL_CONNECT,
1117 "There might be a request body. The connection will not be kept alive.");
1121 /* XXX: and so is this */
1122 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1123 log_error(LOG_LEVEL_CONNECT,
1124 "Possible pipeline attempt detected. The connection will not "
1125 "be kept alive and we will only serve the first request.");
1126 /* Nuke the pipelined requests from orbit, just to be sure. */
1127 csp->iob->buf[0] = '\0';
1128 csp->iob->eod = csp->iob->cur = csp->iob->buf;
1133 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1134 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1137 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1140 /*********************************************************************
1142 * Function : mark_server_socket_tainted
1144 * Description : Makes sure we don't reuse a server socket
1145 * (if we didn't read everything the server sent
1146 * us reusing the socket would lead to garbage).
1149 * 1 : csp = Current client state (buffers, headers, etc...)
1153 *********************************************************************/
1154 static void mark_server_socket_tainted(struct client_state *csp)
1157 * For consistency we always mark the server socket
1158 * tainted, however, to reduce the log noise we only
1159 * emit a log message if the server socket could have
1160 * actually been reused.
1162 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1163 && !(csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED))
1165 log_error(LOG_LEVEL_CONNECT,
1166 "Marking the server socket %d tainted.",
1167 csp->server_connection.sfd);
1169 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1172 /*********************************************************************
1174 * Function : get_request_line
1176 * Description : Read the client request line.
1179 * 1 : csp = Current client state (buffers, headers, etc...)
1181 * Returns : Pointer to request line or NULL in case of errors.
1183 *********************************************************************/
1184 static char *get_request_line(struct client_state *csp)
1186 char buf[BUFFER_SIZE];
1187 char *request_line = NULL;
1190 memset(buf, 0, sizeof(buf));
1194 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1196 log_error(LOG_LEVEL_CONNECT,
1197 "Stopped waiting for the request line. Timeout: %d.",
1198 csp->config->socket_timeout);
1199 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1200 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1204 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1206 if (len <= 0) return NULL;
1209 * If there is no memory left for buffering the
1210 * request, there is nothing we can do but hang up
1212 if (add_to_iob(csp, buf, len))
1217 request_line = get_header(csp->iob);
1219 } while ((NULL != request_line) && ('\0' == *request_line));
1221 return request_line;
1226 /*********************************************************************
1228 * Function : receive_client_request
1230 * Description : Read the client's request (more precisely the
1231 * client headers) and answer it if necessary.
1233 * Note that since we're not using select() we could get
1234 * blocked here if a client connected, then didn't say
1238 * 1 : csp = Current client state (buffers, headers, etc...)
1240 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1242 *********************************************************************/
1243 static jb_err receive_client_request(struct client_state *csp)
1245 char buf[BUFFER_SIZE];
1248 struct http_request *http;
1252 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1253 struct list header_list;
1254 struct list *headers = &header_list;
1258 memset(buf, 0, sizeof(buf));
1260 req = get_request_line(csp);
1263 mark_server_socket_tainted(csp);
1264 return JB_ERR_PARSE;
1266 assert(*req != '\0');
1268 if (client_protocol_is_unsupported(csp, req))
1270 return JB_ERR_PARSE;
1273 #ifdef FEATURE_FORCE_LOAD
1275 * If this request contains the FORCE_PREFIX and blocks
1276 * aren't enforced, get rid of it and set the force flag.
1278 if (strstr(req, FORCE_PREFIX))
1280 if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1282 log_error(LOG_LEVEL_FORCE,
1283 "Ignored force prefix in request: \"%s\".", req);
1287 strclean(req, FORCE_PREFIX);
1288 log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1289 csp->flags |= CSP_FLAG_FORCED;
1292 #endif /* def FEATURE_FORCE_LOAD */
1294 err = parse_http_request(req, http);
1296 if (JB_ERR_OK != err)
1298 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1299 /* XXX: Use correct size */
1300 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1301 log_error(LOG_LEVEL_ERROR,
1302 "Couldn't parse request line received from %s: %s",
1303 csp->ip_addr_str, jb_err_to_string(err));
1305 free_http_request(http);
1306 return JB_ERR_PARSE;
1309 /* grab the rest of the client's headers */
1313 p = get_header(csp->iob);
1317 /* There are no additional headers to read. */
1324 * We didn't receive a complete header
1325 * line yet, get the rest of it.
1327 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1329 log_error(LOG_LEVEL_ERROR,
1330 "Stopped grabbing the client headers.");
1331 destroy_list(headers);
1332 return JB_ERR_PARSE;
1335 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1338 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1339 destroy_list(headers);
1340 return JB_ERR_PARSE;
1343 if (add_to_iob(csp, buf, len))
1346 * If there is no memory left for buffering the
1347 * request, there is nothing we can do but hang up
1349 destroy_list(headers);
1350 return JB_ERR_MEMORY;
1356 * We were able to read a complete
1357 * header and can finally enlist it.
1364 if (http->host == NULL)
1367 * If we still don't know the request destination,
1368 * the request is invalid or the client uses
1369 * Privoxy without its knowledge.
1371 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1374 * Our attempts to get the request destination
1375 * elsewhere failed or Privoxy is configured
1376 * to only accept proxy requests.
1378 * An error response has already been send
1379 * and we're done here.
1381 return JB_ERR_PARSE;
1386 * Determine the actions for this URL
1388 #ifdef FEATURE_TOGGLE
1389 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1391 /* Most compatible set of actions (i.e. none) */
1392 init_current_action(csp->action);
1395 #endif /* ndef FEATURE_TOGGLE */
1397 get_url_actions(csp, http);
1401 * Save a copy of the original request for logging
1403 http->ocmd = strdup(http->cmd);
1404 if (http->ocmd == NULL)
1406 log_error(LOG_LEVEL_FATAL,
1407 "Out of memory copying HTTP request line");
1409 enlist(csp->headers, http->cmd);
1411 /* Append the previously read headers */
1412 list_append_list_unique(csp->headers, headers);
1413 destroy_list(headers);
1420 /*********************************************************************
1422 * Function : parse_client_request
1424 * Description : Parses the client's request and decides what to do
1427 * Note that since we're not using select() we could get
1428 * blocked here if a client connected, then didn't say
1432 * 1 : csp = Current client state (buffers, headers, etc...)
1434 * Returns : JB_ERR_OK or JB_ERR_PARSE
1436 *********************************************************************/
1437 static jb_err parse_client_request(struct client_state *csp)
1439 struct http_request *http = csp->http;
1442 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1443 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1444 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1445 && (csp->http->ssl == 0))
1447 /* Assume persistence until further notice */
1448 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1450 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1452 err = sed(csp, FILTER_CLIENT_HEADERS);
1453 if (JB_ERR_OK != err)
1455 /* XXX: Should be handled in sed(). */
1456 assert(err == JB_ERR_PARSE);
1457 log_error(LOG_LEVEL_FATAL, "Failed to parse client headers.");
1459 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1461 /* Check request line for rewrites. */
1462 if ((NULL == csp->headers->first->str)
1463 || (strcmp(http->cmd, csp->headers->first->str) &&
1464 (JB_ERR_OK != change_request_destination(csp))))
1467 * A header filter broke the request line - bail out.
1469 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1470 /* XXX: Use correct size */
1471 log_error(LOG_LEVEL_CLF,
1472 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1473 log_error(LOG_LEVEL_ERROR,
1474 "Invalid request line after applying header filters.");
1475 free_http_request(http);
1477 return JB_ERR_PARSE;
1480 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1481 if (csp->http->ssl == 0)
1483 verify_request_length(csp);
1485 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1492 /*********************************************************************
1496 * Description : Once a connection from the client has been accepted,
1497 * this function is called (via serve()) to handle the
1498 * main business of the communication. This function
1499 * returns after dealing with a single request. It can
1500 * be called multiple times with the same client socket
1501 * if the client is keeping the connection alive.
1503 * The decision whether or not a client connection will
1504 * be kept alive is up to the caller which also must
1505 * close the client socket when done.
1507 * FIXME: chat is nearly thousand lines long.
1511 * 1 : csp = Current client state (buffers, headers, etc...)
1513 * Returns : Nothing.
1515 *********************************************************************/
1516 static void chat(struct client_state *csp)
1518 char buf[BUFFER_SIZE];
1525 int ms_iis5_hack = 0;
1526 unsigned long long byte_count = 0;
1527 const struct forward_spec *fwd;
1528 struct http_request *http;
1529 long len = 0; /* for buffer sizes (and negative error codes) */
1530 int buffer_and_filter_content = 0;
1532 /* Skeleton for HTTP response, if we should intercept the request */
1533 struct http_response *rsp;
1534 struct timeval timeout;
1535 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1536 int watch_client_socket = 1;
1539 memset(buf, 0, sizeof(buf));
1543 if (receive_client_request(csp) != JB_ERR_OK)
1547 if (parse_client_request(csp) != JB_ERR_OK)
1552 /* decide how to route the HTTP request */
1553 fwd = forward_url(csp, http);
1556 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1557 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1562 * build the http request to send to the server
1563 * we have to do one of the following:
1565 * create = use the original HTTP request to create a new
1566 * HTTP request that has either the path component
1567 * without the http://domainspec (w/path) or the
1568 * full orininal URL (w/url)
1569 * Note that the path and/or the HTTP version may
1570 * have been altered by now.
1572 * connect = Open a socket to the host:port of the server
1573 * and short-circuit server and client socket.
1575 * pass = Pass the request unchanged if forwarding a CONNECT
1576 * request to a parent proxy. Note that we'll be sending
1577 * the CFAIL message ourselves if connecting to the parent
1578 * fails, but we won't send a CSUCCEED message if it works,
1579 * since that would result in a double message (ours and the
1580 * parent's). After sending the request to the parent, we simply
1583 * here's the matrix:
1586 * +--------+--------+
1588 * 0 | create | connect|
1590 * Forwarding +--------+--------+
1592 * 1 | create | pass |
1594 * +--------+--------+
1598 if (http->ssl && connect_port_is_forbidden(csp))
1600 const char *acceptable_connect_ports =
1601 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1602 assert(NULL != acceptable_connect_ports);
1603 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1604 "limit-connect{%s} doesn't allow CONNECT requests to %s",
1605 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
1606 csp->action->flags |= ACTION_BLOCK;
1612 freez(csp->headers->first->str);
1613 build_request_line(csp, fwd, &csp->headers->first->str);
1617 * We have a request. Check if one of the crunchers wants it.
1619 if (crunch_response_triggered(csp, crunchers_all))
1622 * Yes. The client got the crunch response and we're done here.
1627 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1629 if (fwd->forward_host)
1631 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1632 fwd->forward_host, fwd->forward_port, http->hostport);
1636 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1639 /* here we connect to the server, gateway, or the forwarder */
1641 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1642 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
1643 && socket_is_still_alive(csp->server_connection.sfd)
1644 && connection_destination_matches(&csp->server_connection, http, fwd))
1646 log_error(LOG_LEVEL_CONNECT,
1647 "Reusing server socket %u. Opened for %s.",
1648 csp->server_connection.sfd, csp->server_connection.host);
1652 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
1654 log_error(LOG_LEVEL_CONNECT,
1655 "Closing server socket %u. Opened for %s.",
1656 csp->server_connection.sfd, csp->server_connection.host);
1657 close_socket(csp->server_connection.sfd);
1658 mark_connection_closed(&csp->server_connection);
1660 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1662 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
1664 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
1666 if (fwd->type != SOCKS_NONE)
1669 rsp = error_response(csp, "forwarding-failed");
1671 else if (errno == EINVAL)
1673 rsp = error_response(csp, "no-such-domain");
1677 rsp = error_response(csp, "connect-failed");
1680 /* Write the answer to the client */
1683 send_crunch_response(csp, rsp);
1688 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1689 save_connection_destination(csp->server_connection.sfd,
1690 http, fwd, &csp->server_connection);
1691 csp->server_connection.keep_alive_timeout =
1692 (unsigned)csp->config->keep_alive_timeout;
1694 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1696 hdr = list_to_text(csp->headers);
1699 /* FIXME Should handle error properly */
1700 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1702 list_remove_all(csp->headers);
1704 if (fwd->forward_host || (http->ssl == 0))
1707 * Write the client's (modified) header to the server
1708 * (along with anything else that may be in the buffer)
1710 if (write_socket(csp->server_connection.sfd, hdr, strlen(hdr))
1711 || (flush_socket(csp->server_connection.sfd, csp->iob) < 0))
1713 log_error(LOG_LEVEL_CONNECT,
1714 "write header to: %s failed: %E", http->hostport);
1716 rsp = error_response(csp, "connect-failed");
1719 send_crunch_response(csp, rsp);
1729 * We're running an SSL tunnel and we're not forwarding,
1730 * so just send the "connect succeeded" message to the
1731 * client, flush the rest, and get out of the way.
1733 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
1741 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
1743 csp->server_connection.request_sent = time(NULL);
1745 /* we're finished with the client's header */
1748 maxfd = (csp->cfd > csp->server_connection.sfd) ?
1749 csp->cfd : csp->server_connection.sfd;
1751 /* pass data between the client and server
1752 * until one or the other shuts down the connection.
1761 * FD_ZERO here seems to point to an errant macro which crashes.
1762 * So do this by hand for now...
1764 memset(&rfds,0x00,sizeof(fd_set));
1768 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1769 if (!watch_client_socket)
1771 maxfd = csp->server_connection.sfd;
1774 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1776 FD_SET(csp->cfd, &rfds);
1779 FD_SET(csp->server_connection.sfd, &rfds);
1781 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1782 if ((csp->flags & CSP_FLAG_CHUNKED)
1783 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
1784 && ((csp->iob->eod - csp->iob->cur) >= 5)
1785 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
1788 * XXX: This check should be obsolete now,
1789 * but let's wait a while to be sure.
1791 log_error(LOG_LEVEL_CONNECT,
1792 "Looks like we got the last chunk together with "
1793 "the server headers but didn't detect it earlier. "
1794 "We better stop reading.");
1795 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
1796 csp->expected_content_length = byte_count;
1797 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
1799 if (server_body && server_response_is_complete(csp, byte_count))
1801 if (csp->expected_content_length == byte_count)
1803 log_error(LOG_LEVEL_CONNECT,
1804 "Done reading from server. Content length: %llu as expected. "
1805 "Bytes most recently read: %d.",
1810 log_error(LOG_LEVEL_CONNECT,
1811 "Done reading from server. Expected content length: %llu. "
1812 "Actual content length: %llu. Bytes most recently read: %d.",
1813 csp->expected_content_length, byte_count, len);
1817 * XXX: should not jump around,
1818 * chat() is complicated enough already.
1822 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1824 timeout.tv_sec = csp->config->socket_timeout;
1825 timeout.tv_usec = 0;
1826 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
1830 log_error(LOG_LEVEL_ERROR,
1831 "Didn't receive data in time: %s", http->url);
1832 if ((byte_count == 0) && (http->ssl == 0))
1834 send_crunch_response(csp, error_response(csp, "connection-timeout"));
1836 mark_server_socket_tainted(csp);
1841 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1842 mark_server_socket_tainted(csp);
1847 * This is the body of the browser's request,
1848 * just read and write it.
1850 * XXX: Make sure the client doesn't use pipelining
1851 * behind Privoxy's back.
1853 if (FD_ISSET(csp->cfd, &rfds))
1855 int max_bytes_to_read = sizeof(buf) - 1;
1857 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1858 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1860 if (data_is_available(csp->cfd, 0))
1863 * If the next request is already waiting, we have
1864 * to stop select()ing the client socket. Otherwise
1865 * we would always return right away and get nothing
1868 watch_client_socket = 0;
1869 log_error(LOG_LEVEL_CONNECT,
1870 "Stopping to watch the client socket. "
1871 "There's already another request waiting.");
1875 * If the client socket is set, but there's no data
1876 * available on the socket, the client went fishing
1877 * and continuing talking to the server makes no sense.
1879 log_error(LOG_LEVEL_CONNECT,
1880 "The client closed socket %d while "
1881 "the server socket %d is still open.",
1882 csp->cfd, csp->server_connection.sfd);
1883 mark_server_socket_tainted(csp);
1886 if (csp->expected_client_content_length != 0)
1888 if (csp->expected_client_content_length < (sizeof(buf) - 1))
1890 max_bytes_to_read = (int)csp->expected_client_content_length;
1892 log_error(LOG_LEVEL_CONNECT,
1893 "Waiting for up to %d bytes from the client.",
1896 assert(max_bytes_to_read < sizeof(buf));
1897 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1899 len = read_socket(csp->cfd, buf, max_bytes_to_read);
1903 /* XXX: not sure if this is necessary. */
1904 mark_server_socket_tainted(csp);
1905 break; /* "game over, man" */
1908 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1909 if (csp->expected_client_content_length != 0)
1911 assert(len <= max_bytes_to_read);
1912 csp->expected_client_content_length -= (unsigned)len;
1913 log_error(LOG_LEVEL_CONNECT,
1914 "Expected client content length set to %llu "
1915 "after reading %d bytes.",
1916 csp->expected_client_content_length, len);
1917 if (csp->expected_client_content_length == 0)
1919 log_error(LOG_LEVEL_CONNECT,
1920 "Done reading from the client.");
1921 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1924 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1926 if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
1928 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1929 mark_server_socket_tainted(csp);
1936 * The server wants to talk. It could be the header or the body.
1937 * If `hdr' is null, then it's the header otherwise it's the body.
1938 * FIXME: Does `hdr' really mean `host'? No.
1940 if (FD_ISSET(csp->server_connection.sfd, &rfds))
1942 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1944 * If we are buffering content, we don't want to eat up to
1945 * buffer-limit bytes if the client no longer cares about them.
1946 * If we aren't buffering, however, a dead client socket will be
1947 * noticed pretty much right away anyway, so we can reduce the
1948 * overhead by skipping the check.
1950 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
1953 log_error(LOG_LEVEL_CONNECT,
1954 "The server still wants to talk, but the client may already have hung up on us.");
1956 log_error(LOG_LEVEL_CONNECT,
1957 "The server still wants to talk, but the client hung up on us.");
1958 mark_server_socket_tainted(csp);
1960 #endif /* def _WIN32 */
1962 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1965 len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
1969 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1971 if (http->ssl && (fwd->forward_host == NULL))
1974 * Just hang up. We already confirmed the client's CONNECT
1975 * request with status code 200 and unencrypted content is
1976 * no longer welcome.
1978 log_error(LOG_LEVEL_ERROR,
1979 "CONNECT already confirmed. Unable to tell the client about the problem.");
1982 else if (byte_count)
1985 * Just hang up. We already transmitted the original headers
1986 * and parts of the original content and therefore missed the
1987 * chance to send an error message (without risking data corruption).
1989 * XXX: we could retry with a fancy range request here.
1991 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
1992 "Unable to tell the client about the problem.");
1993 mark_server_socket_tainted(csp);
1997 * XXX: Consider handling the cases above the same.
1999 mark_server_socket_tainted(csp);
2003 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2004 if (csp->flags & CSP_FLAG_CHUNKED)
2006 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2008 /* XXX: this is a temporary hack */
2009 log_error(LOG_LEVEL_CONNECT,
2010 "Looks like we reached the end of the last chunk. "
2011 "We better stop reading.");
2012 csp->expected_content_length = byte_count + (unsigned long long)len;
2013 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2017 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2020 * Add a trailing zero to let be able to use string operations.
2021 * XXX: do we still need this with filter_popups gone?
2026 * Normally, this would indicate that we've read
2027 * as much as the server has sent us and we can
2028 * close the client connection. However, Microsoft
2029 * in its wisdom has released IIS/5 with a bug that
2030 * prevents it from sending the trailing \r\n in
2031 * a 302 redirect header (and possibly other headers).
2032 * To work around this if we've haven't parsed
2033 * a full header we'll append a trailing \r\n
2034 * and see if this now generates a valid one.
2036 * This hack shouldn't have any impacts. If we've
2037 * already transmitted the header or if this is a
2038 * SSL connection, then we won't bother with this
2039 * hack. So we only work on partially received
2040 * headers. If we append a \r\n and this still
2041 * doesn't generate a valid header, then we won't
2042 * transmit anything to the client.
2047 if (server_body || http->ssl)
2050 * If we have been buffering up the document,
2051 * now is the time to apply content modification
2052 * and send the result to the client.
2054 if (buffer_and_filter_content)
2056 p = execute_content_filters(csp);
2058 * If content filtering fails, use the original
2059 * buffer and length.
2060 * (see p != NULL ? p : csp->iob->cur below)
2064 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2066 #ifdef FEATURE_COMPRESSION
2067 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2068 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2070 char *compressed_content = compress_buffer(p,
2071 (size_t *)&csp->content_length, csp->config->compression_level);
2072 if (compressed_content != NULL)
2075 p = compressed_content;
2076 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2081 if (JB_ERR_OK != update_server_headers(csp))
2083 log_error(LOG_LEVEL_FATAL,
2084 "Failed to update server headers. after filtering.");
2087 hdr = list_to_text(csp->headers);
2090 /* FIXME Should handle error properly */
2091 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2094 if (write_socket(csp->cfd, hdr, strlen(hdr))
2095 || write_socket(csp->cfd,
2096 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2098 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2101 mark_server_socket_tainted(csp);
2109 break; /* "game over, man" */
2113 * This is NOT the body, so
2114 * Let's pretend the server just sent us a blank line.
2116 snprintf(buf, sizeof(buf), "\r\n");
2117 len = (int)strlen(buf);
2120 * Now, let the normal header parsing algorithm below do its
2121 * job. If it fails, we'll exit instead of continuing.
2128 * If this is an SSL connection or we're in the body
2129 * of the server document, just write it to the client,
2130 * unless we need to buffer the body for later content-filtering
2132 if (server_body || http->ssl)
2134 if (buffer_and_filter_content)
2137 * If there is no memory left for buffering the content, or the buffer limit
2138 * has been reached, switch to non-filtering mode, i.e. make & write the
2139 * header, flush the iob and buf, and get out of the way.
2141 if (add_to_iob(csp, buf, len))
2146 log_error(LOG_LEVEL_INFO,
2147 "Flushing header and buffers. Stepping back from filtering.");
2149 hdr = list_to_text(csp->headers);
2153 * Memory is too tight to even generate the header.
2154 * Send our static "Out-of-memory" page.
2156 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2157 rsp = cgi_error_memory();
2158 send_crunch_response(csp, rsp);
2159 mark_server_socket_tainted(csp);
2162 hdrlen = strlen(hdr);
2164 if (write_socket(csp->cfd, hdr, hdrlen)
2165 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2166 || (write_socket(csp->cfd, buf, (size_t)len)))
2168 log_error(LOG_LEVEL_CONNECT,
2169 "Flush header and buffers to client failed: %E");
2171 mark_server_socket_tainted(csp);
2176 * Reset the byte_count to the amount of bytes
2177 * we just flushed. len will be added a few lines below,
2178 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2180 byte_count = (unsigned long long)flushed;
2182 buffer_and_filter_content = 0;
2188 if (write_socket(csp->cfd, buf, (size_t)len))
2190 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2191 mark_server_socket_tainted(csp);
2195 byte_count += (unsigned long long)len;
2201 * We're still looking for the end of the server's header.
2202 * Buffer up the data we just read. If that fails, there's
2203 * little we can do but send our static out-of-memory page.
2205 if (add_to_iob(csp, buf, len))
2207 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2208 rsp = cgi_error_memory();
2209 send_crunch_response(csp, rsp);
2210 mark_server_socket_tainted(csp);
2214 /* Convert iob into something sed() can digest */
2215 if (JB_ERR_PARSE == get_server_headers(csp))
2220 * Well, we tried our MS IIS/5 hack and it didn't work.
2221 * The header is incomplete and there isn't anything
2222 * we can do about it.
2224 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2225 "Applying the MS IIS5 hack didn't help.");
2226 log_error(LOG_LEVEL_CLF,
2227 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2228 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2229 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2230 mark_server_socket_tainted(csp);
2236 * Since we have to wait for more from the server before
2237 * we can parse the headers we just continue here.
2239 log_error(LOG_LEVEL_CONNECT,
2240 "Continuing buffering headers. Bytes most recently read: %d.",
2248 * Account for the content bytes we
2249 * might have gotten with the headers.
2251 assert(csp->iob->eod >= csp->iob->cur);
2252 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2255 /* Did we actually get anything? */
2256 if (NULL == csp->headers->first)
2258 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2260 log_error(LOG_LEVEL_ERROR,
2261 "Empty server or forwarder response received on socket %d. "
2262 "Closing client socket %d without sending data.",
2263 csp->server_connection.sfd, csp->cfd);
2267 log_error(LOG_LEVEL_ERROR,
2268 "Empty server or forwarder response received on socket %d.",
2269 csp->server_connection.sfd);
2270 send_crunch_response(csp, error_response(csp, "no-server-data"));
2272 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2273 free_http_request(http);
2274 mark_server_socket_tainted(csp);
2278 assert(csp->headers->first->str);
2280 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2281 strncmpic(csp->headers->first->str, "ICY", 3))
2284 * It doesn't look like a HTTP (or Shoutcast) response:
2285 * tell the client and log the problem.
2287 if (strlen(csp->headers->first->str) > 30)
2289 csp->headers->first->str[30] = '\0';
2291 log_error(LOG_LEVEL_ERROR,
2292 "Invalid server or forwarder response. Starts with: %s",
2293 csp->headers->first->str);
2294 log_error(LOG_LEVEL_CLF,
2295 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2296 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2297 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2298 free_http_request(http);
2299 mark_server_socket_tainted(csp);
2304 * We have now received the entire server header,
2305 * filter it and send the result to the client
2307 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2309 log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2311 hdr = list_to_text(csp->headers);
2314 /* FIXME Should handle error properly */
2315 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2318 if ((csp->flags & CSP_FLAG_CHUNKED)
2319 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2320 && ((csp->iob->eod - csp->iob->cur) >= 5)
2321 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2323 log_error(LOG_LEVEL_CONNECT,
2324 "Looks like we got the last chunk together with "
2325 "the server headers. We better stop reading.");
2326 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2327 csp->expected_content_length = byte_count;
2328 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2331 csp->server_connection.response_received = time(NULL);
2333 if (crunch_response_triggered(csp, crunchers_light))
2336 * One of the tags created by a server-header
2337 * tagger triggered a crunch. We already
2338 * delivered the crunch response to the client
2339 * and are done here after cleaning up.
2342 mark_server_socket_tainted(csp);
2345 /* Buffer and pcrs filter this if appropriate. */
2347 if (!http->ssl) /* We talk plaintext */
2349 buffer_and_filter_content = content_requires_filtering(csp);
2352 * Only write if we're not buffering for content modification
2354 if (!buffer_and_filter_content)
2357 * Write the server's (modified) header to
2358 * the client (along with anything else that
2359 * may be in the buffer)
2362 if (write_socket(csp->cfd, hdr, strlen(hdr))
2363 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2365 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2368 * The write failed, so don't bother mentioning it
2369 * to the client... it probably can't hear us anyway.
2372 mark_server_socket_tainted(csp);
2377 /* we're finished with the server's header */
2383 * If this was a MS IIS/5 hack then it means the server
2384 * has already closed the connection. Nothing more to read.
2389 log_error(LOG_LEVEL_ERROR,
2390 "Closed server connection detected. "
2391 "Applying the MS IIS5 hack didn't help.");
2392 log_error(LOG_LEVEL_CLF,
2393 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2394 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2395 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2396 mark_server_socket_tainted(csp);
2402 mark_server_socket_tainted(csp);
2403 return; /* huh? we should never get here */
2406 if (csp->content_length == 0)
2409 * If Privoxy didn't recalculate the Content-Length,
2410 * byte_count is still correct.
2412 csp->content_length = byte_count;
2415 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2416 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2417 && (csp->expected_content_length != byte_count))
2419 log_error(LOG_LEVEL_CONNECT,
2420 "Received %llu bytes while expecting %llu.",
2421 byte_count, csp->expected_content_length);
2422 mark_server_socket_tainted(csp);
2426 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2427 csp->ip_addr_str, http->ocmd, csp->content_length);
2429 csp->server_connection.timestamp = time(NULL);
2433 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2434 /*********************************************************************
2436 * Function : prepare_csp_for_next_request
2438 * Description : Put the csp in a mostly vergin state.
2441 * 1 : csp = Current client state (buffers, headers, etc...)
2445 *********************************************************************/
2446 static void prepare_csp_for_next_request(struct client_state *csp)
2448 csp->content_type = 0;
2449 csp->content_length = 0;
2450 csp->expected_content_length = 0;
2451 csp->expected_client_content_length = 0;
2452 list_remove_all(csp->headers);
2453 freez(csp->iob->buf);
2454 memset(csp->iob, 0, sizeof(csp->iob));
2455 freez(csp->error_message);
2456 free_http_request(csp->http);
2457 destroy_list(csp->headers);
2458 destroy_list(csp->tags);
2459 free_current_action(csp->action);
2460 if (NULL != csp->fwd)
2462 unload_forward_spec(csp->fwd);
2465 /* XXX: Store per-connection flags someplace else. */
2466 csp->flags &= CSP_FLAG_TOGGLED_ON;
2467 csp->flags |= CSP_FLAG_ACTIVE;
2468 csp->flags |= CSP_FLAG_REUSED_CLIENT_CONNECTION;
2470 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2473 /*********************************************************************
2477 * Description : This is little more than chat. We only "serve" to
2478 * to close (or remember) any socket that chat may have
2482 * 1 : csp = Current client state (buffers, headers, etc...)
2486 *********************************************************************/
2488 void serve(struct client_state *csp)
2489 #else /* ifndef AMIGA */
2490 static void serve(struct client_state *csp)
2491 #endif /* def AMIGA */
2493 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2494 #ifdef FEATURE_CONNECTION_SHARING
2495 static int monitor_thread_running = 0;
2496 #endif /* def FEATURE_CONNECTION_SHARING */
2497 int continue_chatting = 0;
2501 unsigned int latency;
2502 int config_file_change_detected = 0; /* Only used for debugging */
2507 * If the request has been crunched,
2508 * the calculated latency is zero.
2510 latency = (unsigned)(csp->server_connection.response_received -
2511 csp->server_connection.request_sent) / 2;
2513 continue_chatting = (csp->config->feature_flags
2514 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2515 && (((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2516 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2517 || (csp->flags & CSP_FLAG_CRUNCHED))
2518 && (csp->cfd != JB_INVALID_SOCKET)
2519 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE);
2521 if (continue_chatting && !(csp->flags & CSP_FLAG_CRUNCHED))
2523 continue_chatting = (csp->server_connection.sfd != JB_INVALID_SOCKET)
2524 && socket_is_still_alive(csp->server_connection.sfd);
2525 if (continue_chatting)
2527 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
2529 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
2530 log_error(LOG_LEVEL_CONNECT,
2531 "The server didn't specify how long the connection will stay open. "
2532 "Assumed timeout is: %u.", csp->server_connection.keep_alive_timeout);
2534 continue_chatting = (latency < csp->server_connection.keep_alive_timeout);
2538 if (continue_chatting && any_loaded_file_changed(csp->config->config_file_list))
2540 continue_chatting = 0;
2541 config_file_change_detected = 1;
2544 if (continue_chatting)
2546 unsigned int client_timeout;
2548 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2550 client_timeout = (unsigned)csp->server_connection.keep_alive_timeout - latency;
2551 log_error(LOG_LEVEL_CONNECT,
2552 "Waiting for the next client request on socket %d. "
2553 "Keeping the server socket %d to %s open.",
2554 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2558 client_timeout = 1; /* XXX: Use something else here? */
2559 log_error(LOG_LEVEL_CONNECT,
2560 "Waiting for the next client request on socket %d. "
2561 "No server socket to keep open.", csp->cfd);
2563 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2564 && data_is_available(csp->cfd, (int)client_timeout)
2565 && socket_is_still_alive(csp->cfd))
2567 log_error(LOG_LEVEL_CONNECT,
2568 "Client request arrived in time on socket %d.", csp->cfd);
2569 prepare_csp_for_next_request(csp);
2573 log_error(LOG_LEVEL_CONNECT,
2574 "No additional client request received in time on socket %d.",
2576 #ifdef FEATURE_CONNECTION_SHARING
2577 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2578 && (socket_is_still_alive(csp->server_connection.sfd)))
2580 time_t time_open = time(NULL) - csp->server_connection.timestamp;
2582 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
2587 remember_connection(&csp->server_connection);
2588 csp->server_connection.sfd = JB_INVALID_SOCKET;
2589 close_socket(csp->cfd);
2590 csp->cfd = JB_INVALID_SOCKET;
2591 privoxy_mutex_lock(&connection_reuse_mutex);
2592 if (!monitor_thread_running)
2594 monitor_thread_running = 1;
2595 privoxy_mutex_unlock(&connection_reuse_mutex);
2596 wait_for_alive_connections();
2597 privoxy_mutex_lock(&connection_reuse_mutex);
2598 monitor_thread_running = 0;
2600 privoxy_mutex_unlock(&connection_reuse_mutex);
2602 #endif /* def FEATURE_CONNECTION_SHARING */
2606 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2608 log_error(LOG_LEVEL_CONNECT,
2609 "The connection on server socket %d to %s isn't reusable. Closing. "
2610 "Server connection: keep-alive %u, tainted: %u, socket alive %u. "
2611 "Client connection: socket alive: %u. Server timeout: %u. "
2612 "Configuration file change detected: %u",
2613 csp->server_connection.sfd, csp->server_connection.host,
2614 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2615 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2616 socket_is_still_alive(csp->server_connection.sfd),
2617 socket_is_still_alive(csp->cfd),
2618 csp->server_connection.keep_alive_timeout,
2619 config_file_change_detected);
2621 } while (continue_chatting);
2625 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2627 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2629 #ifdef FEATURE_CONNECTION_SHARING
2630 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2632 forget_connection(csp->server_connection.sfd);
2634 #endif /* def FEATURE_CONNECTION_SHARING */
2635 close_socket(csp->server_connection.sfd);
2638 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2639 mark_connection_closed(&csp->server_connection);
2642 if (csp->cfd != JB_INVALID_SOCKET)
2644 close_socket(csp->cfd);
2647 csp->flags &= ~CSP_FLAG_ACTIVE;
2653 /*********************************************************************
2655 * Function : server_thread
2657 * Description : We only exist to call `serve' in a threaded environment.
2660 * 1 : data = Current client state (buffers, headers, etc...)
2662 * Returns : Always 0.
2664 *********************************************************************/
2665 static int32 server_thread(void *data)
2667 serve((struct client_state *) data);
2674 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2675 /*********************************************************************
2679 * Description : Print usage info & exit.
2681 * Parameters : Pointer to argv[0] for identifying ourselves
2685 *********************************************************************/
2686 static void usage(const char *myname)
2688 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
2692 #endif /* defined(unix) */
2695 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
2696 #endif /* defined(unix) */
2697 "[--version] [configfile]\n"
2698 "Aborting\n", myname);
2703 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
2706 #ifdef MUTEX_LOCKS_AVAILABLE
2707 /*********************************************************************
2709 * Function : privoxy_mutex_lock
2711 * Description : Locks a mutex.
2714 * 1 : mutex = The mutex to lock.
2716 * Returns : Void. May exit in case of errors.
2718 *********************************************************************/
2719 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
2721 #ifdef FEATURE_PTHREAD
2722 int err = pthread_mutex_lock(mutex);
2725 if (mutex != &log_mutex)
2727 log_error(LOG_LEVEL_FATAL,
2728 "Mutex locking failed: %s.\n", strerror(err));
2733 EnterCriticalSection(mutex);
2734 #endif /* def FEATURE_PTHREAD */
2738 /*********************************************************************
2740 * Function : privoxy_mutex_unlock
2742 * Description : Unlocks a mutex.
2745 * 1 : mutex = The mutex to unlock.
2747 * Returns : Void. May exit in case of errors.
2749 *********************************************************************/
2750 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
2752 #ifdef FEATURE_PTHREAD
2753 int err = pthread_mutex_unlock(mutex);
2756 if (mutex != &log_mutex)
2758 log_error(LOG_LEVEL_FATAL,
2759 "Mutex unlocking failed: %s.\n", strerror(err));
2764 LeaveCriticalSection(mutex);
2765 #endif /* def FEATURE_PTHREAD */
2769 /*********************************************************************
2771 * Function : privoxy_mutex_init
2773 * Description : Prepares a mutex.
2776 * 1 : mutex = The mutex to initialize.
2778 * Returns : Void. May exit in case of errors.
2780 *********************************************************************/
2781 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
2783 #ifdef FEATURE_PTHREAD
2784 int err = pthread_mutex_init(mutex, 0);
2787 printf("Fatal error. Mutex initialization failed: %s.\n",
2792 InitializeCriticalSection(mutex);
2793 #endif /* def FEATURE_PTHREAD */
2795 #endif /* def MUTEX_LOCKS_AVAILABLE */
2797 /*********************************************************************
2799 * Function : initialize_mutexes
2801 * Description : Prepares mutexes if mutex support is available.
2805 * Returns : Void, exits in case of errors.
2807 *********************************************************************/
2808 static void initialize_mutexes(void)
2810 #ifdef MUTEX_LOCKS_AVAILABLE
2812 * Prepare global mutex semaphores
2814 privoxy_mutex_init(&log_mutex);
2815 privoxy_mutex_init(&log_init_mutex);
2816 privoxy_mutex_init(&connection_reuse_mutex);
2819 * XXX: The assumptions below are a bit naive
2820 * and can cause locks that aren't necessary.
2822 * For example older FreeBSD versions (< 6.x?)
2823 * have no gethostbyname_r, but gethostbyname is
2826 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
2827 privoxy_mutex_init(&resolver_mutex);
2828 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
2830 * XXX: should we use a single mutex for
2831 * localtime() and gmtime() as well?
2833 #ifndef HAVE_GMTIME_R
2834 privoxy_mutex_init(&gmtime_mutex);
2835 #endif /* ndef HAVE_GMTIME_R */
2837 #ifndef HAVE_LOCALTIME_R
2838 privoxy_mutex_init(&localtime_mutex);
2839 #endif /* ndef HAVE_GMTIME_R */
2842 privoxy_mutex_init(&rand_mutex);
2843 #endif /* ndef HAVE_RANDOM */
2844 #endif /* def MUTEX_LOCKS_AVAILABLE */
2848 /*********************************************************************
2852 * Description : Load the config file and start the listen loop.
2853 * This function is a lot more *sane* with the `load_config'
2854 * and `listen_loop' functions; although it stills does
2855 * a *little* too much for my taste.
2858 * 1 : argc = Number of parameters (including $0).
2859 * 2 : argv = Array of (char *)'s to the parameters.
2861 * Returns : 1 if : can't open config file, unrecognized directive,
2862 * stats requested in multi-thread mode, can't open the
2863 * log file, can't open the jar file, listen port is invalid,
2864 * any load fails, and can't bind port.
2866 * Else main never returns, the process must be signaled
2867 * to terminate execution. Or, on Windows, use the
2868 * "File", "Exit" menu option.
2870 *********************************************************************/
2872 int real_main(int argc, char **argv)
2874 int main(int argc, char **argv)
2878 unsigned int random_seed;
2880 struct passwd *pw = NULL;
2881 struct group *grp = NULL;
2883 char *pre_chroot_nslookup_to_load_resolver = NULL;
2890 #if !defined(_WIN32)
2897 /* Prepare mutexes if supported and necessary. */
2898 initialize_mutexes();
2900 /* Enable logging until further notice. */
2904 * Parse the command line arguments
2906 * XXX: simply printing usage information in case of
2907 * invalid arguments isn't particularly user friendly.
2909 while (++argc_pos < argc)
2912 /* Check to see if the service must be installed or uninstalled */
2913 if (strncmp(argv[argc_pos], "--install", 9) == 0)
2915 const char *pName = argv[argc_pos] + 9;
2918 exit( (install_service(pName)) ? 0 : 1 );
2920 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
2922 const char *pName = argv[argc_pos] + 11;
2925 exit((uninstall_service(pName)) ? 0 : 1);
2927 else if (strcmp(argv[argc_pos], "--service" ) == 0)
2929 bRunAsService = TRUE;
2930 w32_set_service_cwd();
2931 atexit(w32_service_exit_notify);
2934 #endif /* defined(_WIN32) */
2937 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2939 if (strcmp(argv[argc_pos], "--help") == 0)
2944 else if(strcmp(argv[argc_pos], "--version") == 0)
2946 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2952 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
2954 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
2958 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
2960 if (++argc_pos == argc) usage(argv[0]);
2961 pidfile = strdup(argv[argc_pos]);
2964 else if (strcmp(argv[argc_pos], "--user" ) == 0)
2969 if (++argc_pos == argc) usage(argv[argc_pos]);
2971 user_arg = strdup(argv[argc_pos]);
2972 if (NULL == user_arg)
2974 log_error(LOG_LEVEL_FATAL,
2975 "Out of memory splitting --user argument '%s'.", argv[argc_pos]);
2977 group_name = strchr(user_arg, '.');
2978 if (NULL != group_name)
2980 /* Nul-terminate the user name */
2983 /* Skip the former delimiter to actually reach the group name */
2986 grp = getgrnam(group_name);
2989 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
2992 pw = getpwnam(user_arg);
2995 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3001 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup" ) == 0)
3003 if (++argc_pos == argc) usage(argv[0]);
3004 pre_chroot_nslookup_to_load_resolver = strdup(argv[argc_pos]);
3007 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
3011 #endif /* defined(unix) */
3013 else if (argc_pos + 1 != argc)
3016 * This is neither the last command line
3017 * option, nor was it recognized before,
3018 * therefore it must be invalid.
3024 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3026 configfile = argv[argc_pos];
3029 } /* -END- while (more arguments) */
3031 show_version(Argv[0]);
3034 if ( *configfile != '/' )
3036 char cwd[BUFFER_SIZE];
3038 size_t abs_file_size;
3040 /* make config-filename absolute here */
3041 if (NULL == getcwd(cwd, sizeof(cwd)))
3043 perror("failed to get current working directory");
3048 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3049 basedir = strdup(cwd);
3051 if (NULL == basedir ||
3052 NULL == (abs_file = malloc(abs_file_size)))
3054 perror("malloc failed");
3057 strlcpy(abs_file, basedir, abs_file_size);
3058 strlcat(abs_file, "/", abs_file_size );
3059 strlcat(abs_file, configfile, abs_file_size);
3060 configfile = abs_file;
3062 #endif /* defined unix */
3066 clients->next = NULL;
3068 /* XXX: factor out initialising after the next stable release. */
3071 #elif defined(_WIN32)
3075 random_seed = (unsigned int)time(NULL);
3077 srandom(random_seed);
3080 #endif /* ifdef HAVE_RANDOM */
3083 * Unix signal handling
3085 * Catch the abort, interrupt and terminate signals for a graceful exit
3086 * Catch the hangup signal so the errlog can be reopened.
3087 * Ignore the broken pipe signals (FIXME: Why?)
3089 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3092 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP, 0 };
3093 const int ignored_signals[] = { SIGPIPE, 0 };
3095 for (idx = 0; catched_signals[idx] != 0; idx++)
3097 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3098 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3100 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3101 #endif /* ifdef sun */
3103 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3107 for (idx = 0; ignored_signals[idx] != 0; idx++)
3109 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
3111 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
3116 #else /* ifdef _WIN32 */
3117 # ifdef _WIN_CONSOLE
3119 * We *are* in a windows console app.
3120 * Print a verbose messages about FAQ's and such
3122 printf("%s", win32_blurb);
3123 # endif /* def _WIN_CONSOLE */
3124 #endif /* def _WIN32 */
3127 /* Initialize the CGI subsystem */
3128 cgi_init_error_messages();
3131 * If runnig on unix and without the --nodaemon
3132 * option, become a daemon. I.e. fork, detach
3133 * from tty and get process group leadership
3142 if ( pid < 0 ) /* error */
3147 else if ( pid != 0 ) /* parent */
3152 * must check for errors
3153 * child died due to missing files aso
3156 wpid = waitpid( pid, &status, WNOHANG );
3168 * stderr (fd 2) will be closed later on,
3169 * when the config file has been parsed.
3175 * Reserve fd 0 and 1 to prevent abort() and friends
3176 * from sending stuff to the clients or servers.
3178 fd = open("/dev/null", O_RDONLY);
3181 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3185 if (dup2(fd, 0) == -1)
3187 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3191 fd = open("/dev/null", O_WRONLY);
3194 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3198 if (dup2(fd, 1) == -1)
3200 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3207 } /* -END- if (daemon_mode) */
3210 * As soon as we have written the PID file, we can switch
3211 * to the user and group ID indicated by the --user option
3217 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3219 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3223 if (setgroups(1, &grp->gr_gid))
3225 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3228 else if (initgroups(pw->pw_name, pw->pw_gid))
3230 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3236 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3238 /* Read the time zone file from /etc before doing chroot. */
3240 if (NULL != pre_chroot_nslookup_to_load_resolver
3241 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3243 /* Initialize resolver library. */
3244 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3246 if (chroot(pw->pw_dir) < 0)
3248 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3252 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3255 if (setuid(pw->pw_uid))
3257 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3261 char putenv_dummy[64];
3263 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3264 if (putenv(putenv_dummy) != 0)
3266 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3269 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3270 if (putenv(putenv_dummy) != 0)
3272 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3278 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3281 #endif /* defined unix */
3284 /* This will be FALSE unless the command line specified --service
3288 /* Yup, so now we must attempt to establish a connection
3289 * with the service dispatcher. This will only work if this
3290 * process was launched by the service control manager to
3291 * actually run as a service. If this isn't the case, i've
3292 * known it take around 30 seconds or so for the call to return.
3295 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3296 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3298 /* Service has run, and at this point is now being stopped, so just return */
3303 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3305 /* An error occurred. Usually it's because --service was wrongly specified
3306 * and we were unable to connect to the Service Control Dispatcher because
3307 * it wasn't expecting us and is therefore not listening.
3309 * For now, just continue below to call the listen_loop function.
3312 #endif /* def _WIN32 */
3322 /*********************************************************************
3324 * Function : bind_port_helper
3326 * Description : Bind the listen port. Handles logging, and aborts
3330 * 1 : haddr = Host addres to bind to. Use NULL to bind to
3332 * 2 : hport = Specifies port to bind to.
3334 * Returns : Port that was opened.
3336 *********************************************************************/
3337 static jb_socket bind_port_helper(const char *haddr, int hport)
3342 result = bind_port(haddr, hport, &bfd);
3346 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
3350 log_error(LOG_LEVEL_FATAL,
3351 "can't bind to %s:%d: There may be another Privoxy "
3352 "or some other proxy running on port %d",
3353 bind_address, hport, hport);
3356 log_error(LOG_LEVEL_FATAL,
3357 "can't bind to %s:%d: The hostname is not resolvable",
3358 bind_address, hport);
3361 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3362 bind_address, hport);
3365 /* shouldn't get here */
3366 return JB_INVALID_SOCKET;
3371 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3376 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3384 /*********************************************************************
3386 * Function : bind_ports_helper
3388 * Description : Bind the listen ports. Handles logging, and aborts
3392 * 1 : config = Privoxy configuration. Specifies ports
3394 * 2 : sockets = Preallocated array of opened sockets
3395 * corresponding to specification in config.
3396 * All non-opened sockets will be set to
3397 * JB_INVALID_SOCKET.
3399 * Returns : Nothing. Inspect sockets argument.
3401 *********************************************************************/
3402 static void bind_ports_helper(struct configuration_spec * config,
3403 jb_socket sockets[])
3407 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3409 if (config->hport[i])
3411 sockets[i] = bind_port_helper(config->haddr[i], config->hport[i]);
3415 sockets[i] = JB_INVALID_SOCKET;
3418 config->need_bind = 0;
3422 /*********************************************************************
3424 * Function : close_ports_helper
3426 * Description : Close listenings ports.
3429 * 1 : sockets = Array of opened and non-opened sockets to
3430 * close. All sockets will be set to
3431 * JB_INVALID_SOCKET.
3433 * Returns : Nothing.
3435 *********************************************************************/
3436 static void close_ports_helper(jb_socket sockets[])
3440 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3442 if (JB_INVALID_SOCKET != sockets[i])
3444 close_socket(sockets[i]);
3446 sockets[i] = JB_INVALID_SOCKET;
3452 /* Without this simple workaround we get this compiler warning from _beginthread
3453 * warning C4028: formal parameter 1 different from declaration
3455 void w32_service_listen_loop(void *p)
3459 #endif /* def _WIN32 */
3462 /*********************************************************************
3464 * Function : listen_loop
3466 * Description : bind the listen port and enter a "FOREVER" listening loop.
3472 *********************************************************************/
3473 static void listen_loop(void)
3475 struct client_states *csp_list = NULL;
3476 struct client_state *csp = NULL;
3477 jb_socket bfds[MAX_LISTENING_SOCKETS];
3478 struct configuration_spec *config;
3479 unsigned int active_threads = 0;
3481 config = load_config();
3483 #ifdef FEATURE_CONNECTION_SHARING
3485 * XXX: Should be relocated once it no
3486 * longer needs to emit log messages.
3488 initialize_reusable_connections();
3489 #endif /* def FEATURE_CONNECTION_SHARING */
3491 bind_ports_helper(config, bfds);
3493 #ifdef FEATURE_GRACEFUL_TERMINATION
3494 while (!g_terminate)
3499 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3500 while (waitpid(-1, NULL, WNOHANG) > 0)
3502 /* zombie children */
3504 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3507 * Free data that was used by died threads
3509 active_threads = sweep();
3513 * Re-open the errlog after HUP signal
3515 if (received_hup_signal)
3517 if (NULL != config->logfile)
3519 init_error_log(Argv[0], config->logfile);
3521 received_hup_signal = 0;
3525 csp_list = (struct client_states *)zalloc(sizeof(*csp_list));
3526 if (NULL == csp_list)
3528 log_error(LOG_LEVEL_FATAL,
3529 "malloc(%d) for csp_list failed: %E", sizeof(*csp_list));
3532 csp = &csp_list->csp;
3534 log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
3536 if (!accept_connection(csp, bfds))
3538 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3551 log_error(LOG_LEVEL_CONNECT,
3552 "accepted connection from %s on socket %d",
3553 csp->ip_addr_str, csp->cfd);
3556 csp->flags |= CSP_FLAG_ACTIVE;
3557 csp->server_connection.sfd = JB_INVALID_SOCKET;
3559 csp->config = config = load_config();
3561 if (config->need_bind)
3564 * Since we were listening to the "old port", we will not see
3565 * a "listen" param change until the next request. So, at
3566 * least 1 more request must be made for us to find the new
3567 * setting. I am simply closing the old socket and binding the
3570 * Which-ever is correct, we will serve 1 more page via the
3571 * old settings. This should probably be a "show-proxy-args"
3572 * request. This should not be a so common of an operation
3573 * that this will hurt people's feelings.
3576 close_ports_helper(bfds);
3578 bind_ports_helper(config, bfds);
3581 #ifdef FEATURE_TOGGLE
3582 if (global_toggle_state)
3583 #endif /* def FEATURE_TOGGLE */
3585 csp->flags |= CSP_FLAG_TOGGLED_ON;
3588 if (run_loader(csp))
3590 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3591 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3595 if (block_acl(NULL,csp))
3597 log_error(LOG_LEVEL_CONNECT,
3598 "Connection from %s on socket %d dropped due to ACL", csp->ip_addr_str, csp->cfd);
3599 close_socket(csp->cfd);
3600 freez(csp->ip_addr_str);
3604 #endif /* def FEATURE_ACL */
3606 if ((0 != config->max_client_connections)
3607 && (active_threads >= config->max_client_connections))
3609 log_error(LOG_LEVEL_CONNECT,
3610 "Rejecting connection from %s. Maximum number of connections reached.",
3612 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3613 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3614 close_socket(csp->cfd);
3615 freez(csp->ip_addr_str);
3620 /* add it to the list of clients */
3621 csp_list->next = clients->next;
3622 clients->next = csp_list;
3624 if (config->multi_threaded)
3628 /* this is a switch () statement in the C preprocessor - ugh */
3629 #undef SELECTED_ONE_OPTION
3631 /* Use Pthreads in preference to native code */
3632 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
3633 #define SELECTED_ONE_OPTION
3635 pthread_t the_thread;
3636 pthread_attr_t attrs;
3638 pthread_attr_init(&attrs);
3639 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
3640 errno = pthread_create(&the_thread, &attrs,
3641 (void * (*)(void *))serve, csp);
3642 child_id = errno ? -1 : 0;
3643 pthread_attr_destroy(&attrs);
3647 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
3648 #define SELECTED_ONE_OPTION
3649 child_id = _beginthread(
3650 (void (*)(void *))serve,
3655 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
3656 #define SELECTED_ONE_OPTION
3657 child_id = _beginthread(
3658 (void(* _Optlink)(void*))serve,
3664 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
3665 #define SELECTED_ONE_OPTION
3667 thread_id tid = spawn_thread
3668 (server_thread, "server", B_NORMAL_PRIORITY, csp);
3670 if ((tid >= 0) && (resume_thread(tid) == B_OK))
3672 child_id = (int) tid;
3681 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
3682 #define SELECTED_ONE_OPTION
3683 csp->cfd = ReleaseSocket(csp->cfd, -1);
3686 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3687 NP_Output, Output(),
3688 NP_CloseOutput, FALSE,
3689 NP_Name, (ULONG)"privoxy child",
3693 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3694 NP_Output, Output(),
3695 NP_CloseOutput, FALSE,
3696 NP_Name, (ULONG)"privoxy child",
3697 NP_StackSize, 200*1024,
3703 ((struct Task *)child_id)->tc_UserData = csp;
3704 Signal((struct Task *)child_id, SIGF_SINGLE);
3709 #if !defined(SELECTED_ONE_OPTION)
3712 /* This block is only needed when using fork().
3713 * When using threads, the server thread was
3714 * created and run by the call to _beginthread().
3716 if (child_id == 0) /* child */
3719 #ifdef FEATURE_TOGGLE
3720 int inherited_toggle_state = global_toggle_state;
3721 #endif /* def FEATURE_TOGGLE */
3726 * If we've been toggled or we've blocked the request, tell Mom
3729 #ifdef FEATURE_TOGGLE
3730 if (inherited_toggle_state != global_toggle_state)
3732 rc |= RC_FLAG_TOGGLED;
3734 #endif /* def FEATURE_TOGGLE */
3736 #ifdef FEATURE_STATISTICS
3737 if (csp->flags & CSP_FLAG_REJECTED)
3739 rc |= RC_FLAG_BLOCKED;
3741 #endif /* ndef FEATURE_STATISTICS */
3745 else if (child_id > 0) /* parent */
3747 /* in a fork()'d environment, the parent's
3748 * copy of the client socket and the CSP
3752 #if !defined(_WIN32) && !defined(__CYGWIN__)
3754 wait( &child_status );
3757 * Evaluate child's return code: If the child has
3758 * - been toggled, toggle ourselves
3759 * - blocked its request, bump up the stats counter
3762 #ifdef FEATURE_TOGGLE
3763 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
3765 global_toggle_state = !global_toggle_state;
3767 #endif /* def FEATURE_TOGGLE */
3769 #ifdef FEATURE_STATISTICS
3771 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
3775 #endif /* def FEATURE_STATISTICS */
3777 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
3778 close_socket(csp->cfd);
3779 csp->flags &= ~CSP_FLAG_ACTIVE;
3783 #undef SELECTED_ONE_OPTION
3784 /* end of cpp switch () */
3789 * Spawning the child failed, assume it's because
3790 * there are too many children running already.
3791 * XXX: If you assume ...
3793 log_error(LOG_LEVEL_ERROR,
3794 "Unable to take any additional connections: %E");
3795 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3796 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3797 close_socket(csp->cfd);
3798 csp->flags &= ~CSP_FLAG_ACTIVE;
3807 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
3809 /* Clean up. Aim: free all memory (no leaks) */
3810 #ifdef FEATURE_GRACEFUL_TERMINATION
3812 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
3814 unload_current_config_file();
3815 unload_current_actions_file();
3816 unload_current_re_filterfile();
3817 #ifdef FEATURE_TRUST
3818 unload_current_trust_file();
3821 if (config->multi_threaded)
3828 } while ((clients->next != NULL) && (--i > 0));
3832 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
3842 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
3843 /* Cleanup - remove taskbar icon etc. */
3848 #endif /* FEATURE_GRACEFUL_TERMINATION */