1 const char jcc_rcs[] = "$Id: jcc.c,v 1.343 2011/03/27 13:52:23 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(struct configuration_spec *config);
155 static void listen_loop(void);
158 void serve(struct client_state *csp);
159 #else /* ifndef AMIGA */
160 static void serve(struct client_state *csp);
161 #endif /* def AMIGA */
164 static int32 server_thread(void *data);
165 #endif /* def __BEOS__ */
168 #define sleep(N) Sleep(((N) * 1000))
172 #define sleep(N) DosSleep(((N) * 100))
175 #ifdef MUTEX_LOCKS_AVAILABLE
177 * XXX: Does the locking stuff really belong in this file?
179 privoxy_mutex_t log_mutex;
180 privoxy_mutex_t log_init_mutex;
181 privoxy_mutex_t connection_reuse_mutex;
183 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
184 privoxy_mutex_t resolver_mutex;
185 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
187 #ifndef HAVE_GMTIME_R
188 privoxy_mutex_t gmtime_mutex;
189 #endif /* ndef HAVE_GMTIME_R */
191 #ifndef HAVE_LOCALTIME_R
192 privoxy_mutex_t localtime_mutex;
193 #endif /* ndef HAVE_GMTIME_R */
196 privoxy_mutex_t rand_mutex;
197 #endif /* ndef HAVE_RANDOM */
199 #endif /* def MUTEX_LOCKS_AVAILABLE */
202 const char *basedir = NULL;
203 const char *pidfile = NULL;
204 static int received_hup_signal = 0;
205 #endif /* defined unix */
207 /* HTTP snipplets. */
208 static const char CSUCCEED[] =
209 "HTTP/1.0 200 Connection established\r\n"
210 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
212 static const char CHEADER[] =
213 "HTTP/1.0 400 Invalid header received from client\r\n"
214 "Proxy-Agent: Privoxy " VERSION "\r\n"
215 "Content-Type: text/plain\r\n"
216 "Connection: close\r\n\r\n"
217 "Invalid header received from client.\r\n";
219 static const char FTP_RESPONSE[] =
220 "HTTP/1.0 400 Invalid request received from client\r\n"
221 "Content-Type: text/plain\r\n"
222 "Connection: close\r\n\r\n"
223 "Invalid request. Privoxy doesn't support FTP.\r\n";
225 static const char GOPHER_RESPONSE[] =
226 "HTTP/1.0 400 Invalid request received from client\r\n"
227 "Content-Type: text/plain\r\n"
228 "Connection: close\r\n\r\n"
229 "Invalid request. Privoxy doesn't support gopher.\r\n";
231 /* XXX: should be a template */
232 static const char MISSING_DESTINATION_RESPONSE[] =
233 "HTTP/1.0 400 Bad request received from client\r\n"
234 "Proxy-Agent: Privoxy " VERSION "\r\n"
235 "Content-Type: text/plain\r\n"
236 "Connection: close\r\n\r\n"
237 "Bad request. Privoxy was unable to extract the destination.\r\n";
239 /* XXX: should be a template */
240 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
241 "HTTP/1.0 502 Server or forwarder response invalid\r\n"
242 "Proxy-Agent: Privoxy " VERSION "\r\n"
243 "Content-Type: text/plain\r\n"
244 "Connection: close\r\n\r\n"
245 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
247 /* XXX: should be a template */
248 static const char MESSED_UP_REQUEST_RESPONSE[] =
249 "HTTP/1.0 400 Malformed request after rewriting\r\n"
250 "Proxy-Agent: Privoxy " VERSION "\r\n"
251 "Content-Type: text/plain\r\n"
252 "Connection: close\r\n\r\n"
253 "Bad request. Messed up with header filters.\r\n";
255 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
256 "HTTP/1.0 503 Too many open connections\r\n"
257 "Proxy-Agent: Privoxy " VERSION "\r\n"
258 "Content-Type: text/plain\r\n"
259 "Connection: close\r\n\r\n"
260 "Maximum number of open connections reached.\r\n";
262 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
263 "HTTP/1.0 504 Connection timeout\r\n"
264 "Proxy-Agent: Privoxy " VERSION "\r\n"
265 "Content-Type: text/plain\r\n"
266 "Connection: close\r\n\r\n"
267 "The connection timed out because the client request didn't arrive in time.\r\n";
269 /* A function to crunch a response */
270 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
272 /* Crunch function flags */
273 #define CF_NO_FLAGS 0
274 /* Cruncher applies to forced requests as well */
275 #define CF_IGNORE_FORCE 1
276 /* Crunched requests are counted for the block statistics */
277 #define CF_COUNT_AS_REJECT 2
279 /* A crunch function and its flags */
282 const crunch_func_ptr cruncher;
286 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
288 /* Complete list of cruncher functions */
289 static const struct cruncher crunchers_all[] = {
290 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
291 { block_url, CF_COUNT_AS_REJECT },
293 { trust_url, CF_COUNT_AS_REJECT },
294 #endif /* def FEATURE_TRUST */
295 { redirect_url, CF_NO_FLAGS },
296 { dispatch_cgi, CF_IGNORE_FORCE},
300 /* Light version, used after tags are applied */
301 static const struct cruncher crunchers_light[] = {
302 { block_url, CF_COUNT_AS_REJECT },
303 { redirect_url, CF_NO_FLAGS },
309 * XXX: Don't we really mean
315 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
316 /*********************************************************************
318 * Function : sig_handler
320 * Description : Signal handler for different signals.
321 * Exit gracefully on TERM and INT
322 * or set a flag that will cause the errlog
323 * to be reopened by the main thread on HUP.
326 * 1 : the_signal = the signal cause this function to call
330 *********************************************************************/
331 static void sig_handler(int the_signal)
337 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
349 received_hup_signal = 1;
355 * We shouldn't be here, unless we catch signals
356 * in main() that we can't handle here!
358 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
366 /*********************************************************************
368 * Function : client_protocol_is_unsupported
370 * Description : Checks if the client used a known unsupported
371 * protocol and deals with it by sending an error
375 * 1 : csp = Current client state (buffers, headers, etc...)
376 * 2 : req = the first request line send by the client
378 * Returns : TRUE if an error response has been generated, or
379 * FALSE if the request doesn't look invalid.
381 *********************************************************************/
382 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
385 * If it's a FTP or gopher request, we don't support it.
387 * These checks are better than nothing, but they might
388 * not work in all configurations and some clients might
389 * have problems digesting the answer.
391 * They should, however, never cause more problems than
392 * Privoxy's old behaviour (returning the misleading HTML
395 * "Could not resolve http://(ftp|gopher)://example.org").
397 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
399 const char *response = NULL;
400 const char *protocol = NULL;
402 if (!strncmpic(req, "GET ftp://", 10))
404 response = FTP_RESPONSE;
409 response = GOPHER_RESPONSE;
412 log_error(LOG_LEVEL_ERROR,
413 "%s tried to use Privoxy as %s proxy: %s",
414 csp->ip_addr_str, protocol, req);
415 log_error(LOG_LEVEL_CLF,
416 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
418 write_socket(csp->cfd, response, strlen(response));
427 /*********************************************************************
429 * Function : get_request_destination_elsewhere
431 * Description : If the client's request was redirected into
432 * Privoxy without the client's knowledge,
433 * the request line lacks the destination host.
435 * This function tries to get it elsewhere,
436 * provided accept-intercepted-requests is enabled.
438 * "Elsewhere" currently only means "Host: header",
439 * but in the future we may ask the redirecting
440 * packet filter to look the destination up.
442 * If the destination stays unknown, an error
443 * response is send to the client and headers
444 * are freed so that chat() can return directly.
447 * 1 : csp = Current client state (buffers, headers, etc...)
448 * 2 : headers = a header list
450 * Returns : JB_ERR_OK if the destination is now known, or
451 * JB_ERR_PARSE if it isn't.
453 *********************************************************************/
454 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
458 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
460 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
461 " Privoxy isn't configured to accept intercepted requests.",
462 csp->ip_addr_str, csp->http->cmd);
463 /* XXX: Use correct size */
464 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
465 csp->ip_addr_str, csp->http->cmd);
467 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
468 destroy_list(headers);
472 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
474 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
475 /* Split the domain we just got for pattern matching */
476 init_domain_components(csp->http);
483 /* We can't work without destination. Go spread the news.*/
485 req = list_to_text(headers);
487 /* XXX: Use correct size */
488 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
489 csp->ip_addr_str, csp->http->cmd);
490 log_error(LOG_LEVEL_ERROR,
491 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
492 csp->ip_addr_str, csp->http->cmd, req);
495 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
496 destroy_list(headers);
501 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
502 * to get the destination IP address, use it as host directly
503 * or do a reverse DNS lookup first.
508 /*********************************************************************
510 * Function : get_server_headers
512 * Description : Parses server headers in iob and fills them
513 * into csp->headers so that they can later be
517 * 1 : csp = Current client state (buffers, headers, etc...)
519 * Returns : JB_ERR_OK if everything went fine, or
520 * JB_ERR_PARSE if the headers were incomplete.
522 *********************************************************************/
523 static jb_err get_server_headers(struct client_state *csp)
525 int continue_hack_in_da_house = 0;
528 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
533 * continue hack in da house. Ignore the ending of
534 * this head and continue enlisting header lines.
535 * The reason is described below.
537 enlist(csp->headers, "");
538 continue_hack_in_da_house = 0;
541 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
544 * It's a bodyless continue response, don't
545 * stop header parsing after reaching its end.
547 * As a result Privoxy will concatenate the
548 * next response's head and parse and deliver
549 * the headers as if they belonged to one request.
551 * The client will separate them because of the
552 * empty line between them.
554 * XXX: What we're doing here is clearly against
555 * the intended purpose of the continue header,
556 * and under some conditions (HTTP/1.0 client request)
557 * it's a standard violation.
559 * Anyway, "sort of against the spec" is preferable
560 * to "always getting confused by Continue responses"
561 * (Privoxy's behaviour before this hack was added)
563 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
564 continue_hack_in_da_house = 1;
566 else if (*header == '\0')
569 * If the header is empty, but the Continue hack
570 * isn't active, we can assume that we reached the
571 * end of the buffer before we hit the end of the
574 * Inform the caller an let it decide how to handle it.
579 if (JB_ERR_MEMORY == enlist(csp->headers, header))
582 * XXX: Should we quit the request and return a
583 * out of memory error page instead?
585 log_error(LOG_LEVEL_ERROR,
586 "Out of memory while enlisting server headers. %s lost.",
596 /*********************************************************************
598 * Function : crunch_reason
600 * Description : Translates the crunch reason code into a string.
603 * 1 : rsp = a http_response
605 * Returns : A string with the crunch reason or an error description.
607 *********************************************************************/
608 static const char *crunch_reason(const struct http_response *rsp)
610 char * reason = NULL;
615 return "Internal error while searching for crunch reason";
618 switch (rsp->crunch_reason)
621 reason = "Unsupported HTTP feature";
627 reason = "Untrusted";
630 reason = "Redirected";
636 reason = "DNS failure";
638 case FORWARDING_FAILED:
639 reason = "Forwarding failed";
642 reason = "Connection failure";
645 reason = "Out of memory (may mask other reasons)";
647 case CONNECTION_TIMEOUT:
648 reason = "Connection timeout";
651 reason = "No server data received";
654 reason = "No reason recorded";
662 /*********************************************************************
664 * Function : send_crunch_response
666 * Description : Delivers already prepared response for
667 * intercepted requests, logs the interception
668 * and frees the response.
671 * 1 : csp = Current client state (buffers, headers, etc...)
672 * 1 : rsp = Fully prepared response. Will be freed on exit.
676 *********************************************************************/
677 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
679 const struct http_request *http = csp->http;
683 assert(rsp->head != NULL);
687 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
691 * Extract the status code from the actual head
692 * that will be send to the client. It is the only
693 * way to get it right for all requests, including
694 * the fixed ones for out-of-memory problems.
696 * A head starts like this: 'HTTP/1.1 200...'
700 status_code[0] = rsp->head[9];
701 status_code[1] = rsp->head[10];
702 status_code[2] = rsp->head[11];
703 status_code[3] = '\0';
705 /* Log that the request was crunched and why. */
706 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
707 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
708 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
710 /* Write the answer to the client */
711 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
712 || write_socket(csp->cfd, rsp->body, rsp->content_length))
714 /* There is nothing we can do about it. */
715 log_error(LOG_LEVEL_ERROR,
716 "Couldn't deliver the error message through client socket %d: %E",
720 /* Clean up and return */
721 if (cgi_error_memory() != rsp)
723 free_http_response(rsp);
729 /*********************************************************************
731 * Function : crunch_response_triggered
733 * Description : Checks if the request has to be crunched,
734 * and delivers the crunch response if necessary.
737 * 1 : csp = Current client state (buffers, headers, etc...)
738 * 2 : crunchers = list of cruncher functions to run
740 * Returns : TRUE if the request was answered with a crunch response
743 *********************************************************************/
744 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
746 struct http_response *rsp = NULL;
747 const struct cruncher *c;
750 * If CGI request crunching is disabled,
751 * check the CGI dispatcher out of order to
752 * prevent unintentional blocks or redirects.
754 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
755 && (NULL != (rsp = dispatch_cgi(csp))))
757 /* Deliver, log and free the interception response. */
758 send_crunch_response(csp, rsp);
759 csp->flags |= CSP_FLAG_CRUNCHED;
763 for (c = crunchers; c->cruncher != NULL; c++)
766 * Check the cruncher if either Privoxy is toggled
767 * on and the request isn't forced, or if the cruncher
768 * applies to forced requests as well.
770 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
771 !(csp->flags & CSP_FLAG_FORCED)) ||
772 (c->flags & CF_IGNORE_FORCE))
774 rsp = c->cruncher(csp);
777 /* Deliver, log and free the interception response. */
778 send_crunch_response(csp, rsp);
779 csp->flags |= CSP_FLAG_CRUNCHED;
780 #ifdef FEATURE_STATISTICS
781 if (c->flags & CF_COUNT_AS_REJECT)
783 csp->flags |= CSP_FLAG_REJECTED;
785 #endif /* def FEATURE_STATISTICS */
796 /*********************************************************************
798 * Function : build_request_line
800 * Description : Builds the HTTP request line.
802 * If a HTTP forwarder is used it expects the whole URL,
803 * web servers only get the path.
806 * 1 : csp = Current client state (buffers, headers, etc...)
807 * 2 : fwd = The forwarding spec used for the request
808 * XXX: Should use http->fwd instead.
809 * 3 : request_line = The old request line which will be replaced.
811 * Returns : Nothing. Terminates in case of memory problems.
813 *********************************************************************/
814 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
816 struct http_request *http = csp->http;
818 assert(http->ssl == 0);
821 * Downgrade http version from 1.1 to 1.0
822 * if +downgrade action applies.
824 if ( (csp->action->flags & ACTION_DOWNGRADE)
825 && (!strcmpic(http->ver, "HTTP/1.1")))
828 http->ver = strdup("HTTP/1.0");
830 if (http->ver == NULL)
832 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
837 * Rebuild the request line.
839 freez(*request_line);
840 *request_line = strdup(http->gpc);
841 string_append(request_line, " ");
843 if (fwd->forward_host)
845 string_append(request_line, http->url);
849 string_append(request_line, http->path);
851 string_append(request_line, " ");
852 string_append(request_line, http->ver);
854 if (*request_line == NULL)
856 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
858 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
862 /*********************************************************************
864 * Function : change_request_destination
866 * Description : Parse a (rewritten) request line and regenerate
867 * the http request data.
870 * 1 : csp = Current client state (buffers, headers, etc...)
872 * Returns : Forwards the parse_http_request() return code.
873 * Terminates in case of memory problems.
875 *********************************************************************/
876 static jb_err change_request_destination(struct client_state *csp)
878 struct http_request *http = csp->http;
881 log_error(LOG_LEVEL_INFO, "Rewrite detected: %s", csp->headers->first->str);
882 free_http_request(http);
883 err = parse_http_request(csp->headers->first->str, http);
884 if (JB_ERR_OK != err)
886 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
887 jb_err_to_string(err));
891 /* XXX: ocmd is a misleading name */
892 http->ocmd = strdup(http->cmd);
893 if (http->ocmd == NULL)
895 log_error(LOG_LEVEL_FATAL,
896 "Out of memory copying rewritten HTTP request line");
904 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
905 /*********************************************************************
907 * Function : server_response_is_complete
909 * Description : Determines whether we should stop reading
910 * from the server socket.
913 * 1 : csp = Current client state (buffers, headers, etc...)
914 * 2 : content_length = Length of content received so far.
916 * Returns : TRUE if the response is complete,
919 *********************************************************************/
920 static int server_response_is_complete(struct client_state *csp,
921 unsigned long long content_length)
923 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
925 if (!strcmpic(csp->http->gpc, "HEAD"))
928 * "HEAD" implies no body, we are thus expecting
929 * no content. XXX: incomplete "list" of methods?
931 csp->expected_content_length = 0;
932 content_length_known = TRUE;
935 if (csp->http->status == 204 || csp->http->status == 304)
938 * Expect no body. XXX: incomplete "list" of status codes?
940 csp->expected_content_length = 0;
941 content_length_known = TRUE;
944 return (content_length_known && ((0 == csp->expected_content_length)
945 || (csp->expected_content_length <= content_length)));
949 #ifdef FEATURE_CONNECTION_SHARING
950 /*********************************************************************
952 * Function : wait_for_alive_connections
954 * Description : Waits for alive connections to timeout.
960 *********************************************************************/
961 static void wait_for_alive_connections(void)
963 int connections_alive = close_unusable_connections();
965 while (0 < connections_alive)
967 log_error(LOG_LEVEL_CONNECT,
968 "Waiting for %d connections to timeout.",
971 connections_alive = close_unusable_connections();
974 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
977 #endif /* def FEATURE_CONNECTION_SHARING */
980 /*********************************************************************
982 * Function : save_connection_destination
984 * Description : Remembers a connection for reuse later on.
987 * 1 : sfd = Open socket to remember.
988 * 2 : http = The destination for the connection.
989 * 3 : fwd = The forwarder settings used.
990 * 3 : server_connection = storage.
994 *********************************************************************/
995 void save_connection_destination(jb_socket sfd,
996 const struct http_request *http,
997 const struct forward_spec *fwd,
998 struct reusable_connection *server_connection)
1000 assert(sfd != JB_INVALID_SOCKET);
1001 assert(NULL != http->host);
1003 server_connection->sfd = sfd;
1004 server_connection->host = strdup(http->host);
1005 if (NULL == server_connection->host)
1007 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
1009 server_connection->port = http->port;
1011 assert(NULL != fwd);
1012 assert(server_connection->gateway_host == NULL);
1013 assert(server_connection->gateway_port == 0);
1014 assert(server_connection->forwarder_type == 0);
1015 assert(server_connection->forward_host == NULL);
1016 assert(server_connection->forward_port == 0);
1018 server_connection->forwarder_type = fwd->type;
1019 if (NULL != fwd->gateway_host)
1021 server_connection->gateway_host = strdup(fwd->gateway_host);
1022 if (NULL == server_connection->gateway_host)
1024 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
1029 server_connection->gateway_host = NULL;
1031 server_connection->gateway_port = fwd->gateway_port;
1033 if (NULL != fwd->forward_host)
1035 server_connection->forward_host = strdup(fwd->forward_host);
1036 if (NULL == server_connection->forward_host)
1038 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
1043 server_connection->forward_host = NULL;
1045 server_connection->forward_port = fwd->forward_port;
1049 /*********************************************************************
1051 * Function : verify_request_length
1053 * Description : Checks if we already got the whole client requests
1054 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1057 * Data that doesn't belong to the current request is
1058 * thrown away to let the client retry on a clean socket.
1060 * XXX: This is a hack until we can deal with multiple
1061 * pipelined requests at the same time.
1065 * 1 : csp = Current client state (buffers, headers, etc...)
1069 *********************************************************************/
1070 static void verify_request_length(struct client_state *csp)
1072 unsigned long long buffered_request_bytes =
1073 (unsigned long long)(csp->iob->eod - csp->iob->cur);
1075 if ((csp->expected_client_content_length != 0)
1076 && (buffered_request_bytes != 0))
1078 if (csp->expected_client_content_length >= buffered_request_bytes)
1080 csp->expected_client_content_length -= buffered_request_bytes;
1081 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1082 "to account for the %llu ones we already got.",
1083 csp->expected_client_content_length, buffered_request_bytes);
1087 assert(csp->iob->eod > csp->iob->cur + csp->expected_client_content_length);
1088 csp->iob->eod = csp->iob->cur + csp->expected_client_content_length;
1089 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1090 "Marking the server socket tainted after throwing %llu bytes away.",
1091 buffered_request_bytes - csp->expected_client_content_length);
1092 csp->expected_client_content_length = 0;
1093 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1096 if (csp->expected_client_content_length == 0)
1098 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1102 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1103 && ((csp->iob->cur[0] != '\0') || (csp->expected_client_content_length != 0)))
1105 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1106 if (strcmpic(csp->http->gpc, "GET")
1107 && strcmpic(csp->http->gpc, "HEAD")
1108 && strcmpic(csp->http->gpc, "TRACE")
1109 && strcmpic(csp->http->gpc, "OPTIONS")
1110 && strcmpic(csp->http->gpc, "DELETE"))
1112 /* XXX: this is an incomplete hack */
1113 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1114 log_error(LOG_LEVEL_CONNECT,
1115 "There might be a request body. The connection will not be kept alive.");
1119 /* XXX: and so is this */
1120 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1121 log_error(LOG_LEVEL_CONNECT,
1122 "Possible pipeline attempt detected. The connection will not "
1123 "be kept alive and we will only serve the first request.");
1124 /* Nuke the pipelined requests from orbit, just to be sure. */
1125 csp->iob->buf[0] = '\0';
1126 csp->iob->eod = csp->iob->cur = csp->iob->buf;
1131 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1132 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1135 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1138 /*********************************************************************
1140 * Function : mark_server_socket_tainted
1142 * Description : Makes sure we don't reuse a server socket
1143 * (if we didn't read everything the server sent
1144 * us reusing the socket would lead to garbage).
1147 * 1 : csp = Current client state (buffers, headers, etc...)
1151 *********************************************************************/
1152 static void mark_server_socket_tainted(struct client_state *csp)
1155 * For consistency we always mark the server socket
1156 * tainted, however, to reduce the log noise we only
1157 * emit a log message if the server socket could have
1158 * actually been reused.
1160 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1161 && !(csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED))
1163 log_error(LOG_LEVEL_CONNECT,
1164 "Marking the server socket %d tainted.",
1165 csp->server_connection.sfd);
1167 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1170 /*********************************************************************
1172 * Function : get_request_line
1174 * Description : Read the client request line.
1177 * 1 : csp = Current client state (buffers, headers, etc...)
1179 * Returns : Pointer to request line or NULL in case of errors.
1181 *********************************************************************/
1182 static char *get_request_line(struct client_state *csp)
1184 char buf[BUFFER_SIZE];
1185 char *request_line = NULL;
1188 memset(buf, 0, sizeof(buf));
1192 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1194 log_error(LOG_LEVEL_CONNECT,
1195 "Stopped waiting for the request line. Timeout: %d.",
1196 csp->config->socket_timeout);
1197 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1198 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1202 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1204 if (len <= 0) return NULL;
1207 * If there is no memory left for buffering the
1208 * request, there is nothing we can do but hang up
1210 if (add_to_iob(csp, buf, len))
1215 request_line = get_header(csp->iob);
1217 } while ((NULL != request_line) && ('\0' == *request_line));
1219 return request_line;
1224 /*********************************************************************
1226 * Function : receive_client_request
1228 * Description : Read the client's request (more precisely the
1229 * client headers) and answer it if necessary.
1231 * Note that since we're not using select() we could get
1232 * blocked here if a client connected, then didn't say
1236 * 1 : csp = Current client state (buffers, headers, etc...)
1238 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1240 *********************************************************************/
1241 static jb_err receive_client_request(struct client_state *csp)
1243 char buf[BUFFER_SIZE];
1246 struct http_request *http;
1250 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1251 struct list header_list;
1252 struct list *headers = &header_list;
1256 memset(buf, 0, sizeof(buf));
1258 req = get_request_line(csp);
1261 mark_server_socket_tainted(csp);
1262 return JB_ERR_PARSE;
1264 assert(*req != '\0');
1266 if (client_protocol_is_unsupported(csp, req))
1268 return JB_ERR_PARSE;
1271 #ifdef FEATURE_FORCE_LOAD
1273 * If this request contains the FORCE_PREFIX and blocks
1274 * aren't enforced, get rid of it and set the force flag.
1276 if (strstr(req, FORCE_PREFIX))
1278 if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1280 log_error(LOG_LEVEL_FORCE,
1281 "Ignored force prefix in request: \"%s\".", req);
1285 strclean(req, FORCE_PREFIX);
1286 log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1287 csp->flags |= CSP_FLAG_FORCED;
1290 #endif /* def FEATURE_FORCE_LOAD */
1292 err = parse_http_request(req, http);
1294 if (JB_ERR_OK != err)
1296 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1297 /* XXX: Use correct size */
1298 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1299 log_error(LOG_LEVEL_ERROR,
1300 "Couldn't parse request line received from %s: %s",
1301 csp->ip_addr_str, jb_err_to_string(err));
1303 free_http_request(http);
1304 return JB_ERR_PARSE;
1307 /* grab the rest of the client's headers */
1311 p = get_header(csp->iob);
1315 /* There are no additional headers to read. */
1322 * We didn't receive a complete header
1323 * line yet, get the rest of it.
1325 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1327 log_error(LOG_LEVEL_ERROR,
1328 "Stopped grabbing the client headers.");
1329 destroy_list(headers);
1330 return JB_ERR_PARSE;
1333 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1336 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1337 destroy_list(headers);
1338 return JB_ERR_PARSE;
1341 if (add_to_iob(csp, buf, len))
1344 * If there is no memory left for buffering the
1345 * request, there is nothing we can do but hang up
1347 destroy_list(headers);
1348 return JB_ERR_MEMORY;
1354 * We were able to read a complete
1355 * header and can finaly enlist it.
1362 if (http->host == NULL)
1365 * If we still don't know the request destination,
1366 * the request is invalid or the client uses
1367 * Privoxy without its knowledge.
1369 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1372 * Our attempts to get the request destination
1373 * elsewhere failed or Privoxy is configured
1374 * to only accept proxy requests.
1376 * An error response has already been send
1377 * and we're done here.
1379 return JB_ERR_PARSE;
1384 * Determine the actions for this URL
1386 #ifdef FEATURE_TOGGLE
1387 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1389 /* Most compatible set of actions (i.e. none) */
1390 init_current_action(csp->action);
1393 #endif /* ndef FEATURE_TOGGLE */
1395 get_url_actions(csp, http);
1399 * Save a copy of the original request for logging
1401 http->ocmd = strdup(http->cmd);
1402 if (http->ocmd == NULL)
1404 log_error(LOG_LEVEL_FATAL,
1405 "Out of memory copying HTTP request line");
1407 enlist(csp->headers, http->cmd);
1409 /* Append the previously read headers */
1410 list_append_list_unique(csp->headers, headers);
1411 destroy_list(headers);
1418 /*********************************************************************
1420 * Function : parse_client_request
1422 * Description : Parses the client's request and decides what to do
1425 * Note that since we're not using select() we could get
1426 * blocked here if a client connected, then didn't say
1430 * 1 : csp = Current client state (buffers, headers, etc...)
1432 * Returns : JB_ERR_OK or JB_ERR_PARSE
1434 *********************************************************************/
1435 static jb_err parse_client_request(struct client_state *csp)
1437 struct http_request *http = csp->http;
1440 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1441 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1442 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1443 && (csp->http->ssl == 0))
1445 /* Assume persistence until further notice */
1446 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1448 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1450 err = sed(csp, FILTER_CLIENT_HEADERS);
1451 if (JB_ERR_OK != err)
1453 /* XXX: Should be handled in sed(). */
1454 assert(err == JB_ERR_PARSE);
1455 log_error(LOG_LEVEL_FATAL, "Failed to parse client headers.");
1457 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1459 /* Check request line for rewrites. */
1460 if ((NULL == csp->headers->first->str)
1461 || (strcmp(http->cmd, csp->headers->first->str) &&
1462 (JB_ERR_OK != change_request_destination(csp))))
1465 * A header filter broke the request line - bail out.
1467 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1468 /* XXX: Use correct size */
1469 log_error(LOG_LEVEL_CLF,
1470 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1471 log_error(LOG_LEVEL_ERROR,
1472 "Invalid request line after applying header filters.");
1473 free_http_request(http);
1475 return JB_ERR_PARSE;
1478 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1479 if (csp->http->ssl == 0)
1481 verify_request_length(csp);
1483 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1490 /*********************************************************************
1494 * Description : Once a connection from the client has been accepted,
1495 * this function is called (via serve()) to handle the
1496 * main business of the communication. This function
1497 * returns after dealing with a single request. It can
1498 * be called multiple times witht the same client socket
1499 * if the client is keeping the connection alive.
1501 * The decision whether or not a client connection will
1502 * be kept alive is up to the caller which also must
1503 * close the client socket when done.
1505 * FIXME: chat is nearly thousand lines long.
1509 * 1 : csp = Current client state (buffers, headers, etc...)
1511 * Returns : Nothing.
1513 *********************************************************************/
1514 static void chat(struct client_state *csp)
1516 char buf[BUFFER_SIZE];
1523 int ms_iis5_hack = 0;
1524 unsigned long long byte_count = 0;
1525 const struct forward_spec *fwd;
1526 struct http_request *http;
1527 long len = 0; /* for buffer sizes (and negative error codes) */
1528 int buffer_and_filter_content = 0;
1530 /* Skeleton for HTTP response, if we should intercept the request */
1531 struct http_response *rsp;
1532 struct timeval timeout;
1533 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1534 int watch_client_socket = 1;
1537 memset(buf, 0, sizeof(buf));
1541 if (receive_client_request(csp) != JB_ERR_OK)
1545 if (parse_client_request(csp) != JB_ERR_OK)
1550 /* decide how to route the HTTP request */
1551 fwd = forward_url(csp, http);
1554 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1555 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1560 * build the http request to send to the server
1561 * we have to do one of the following:
1563 * create = use the original HTTP request to create a new
1564 * HTTP request that has either the path component
1565 * without the http://domainspec (w/path) or the
1566 * full orininal URL (w/url)
1567 * Note that the path and/or the HTTP version may
1568 * have been altered by now.
1570 * connect = Open a socket to the host:port of the server
1571 * and short-circuit server and client socket.
1573 * pass = Pass the request unchanged if forwarding a CONNECT
1574 * request to a parent proxy. Note that we'll be sending
1575 * the CFAIL message ourselves if connecting to the parent
1576 * fails, but we won't send a CSUCCEED message if it works,
1577 * since that would result in a double message (ours and the
1578 * parent's). After sending the request to the parent, we simply
1581 * here's the matrix:
1584 * +--------+--------+
1586 * 0 | create | connect|
1588 * Forwarding +--------+--------+
1590 * 1 | create | pass |
1592 * +--------+--------+
1596 if (http->ssl && connect_port_is_forbidden(csp))
1598 const char *acceptable_connect_ports =
1599 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1600 assert(NULL != acceptable_connect_ports);
1601 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1602 "limit-connect{%s} doesn't allow CONNECT requests to port %d.",
1603 csp->ip_addr_str, acceptable_connect_ports, csp->http->port);
1604 csp->action->flags |= ACTION_BLOCK;
1610 freez(csp->headers->first->str);
1611 build_request_line(csp, fwd, &csp->headers->first->str);
1615 * We have a request. Check if one of the crunchers wants it.
1617 if (crunch_response_triggered(csp, crunchers_all))
1620 * Yes. The client got the crunch response and we're done here.
1625 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1627 if (fwd->forward_host)
1629 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1630 fwd->forward_host, fwd->forward_port, http->hostport);
1634 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1637 /* here we connect to the server, gateway, or the forwarder */
1639 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1640 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
1641 && socket_is_still_alive(csp->server_connection.sfd)
1642 && connection_destination_matches(&csp->server_connection, http, fwd))
1644 log_error(LOG_LEVEL_CONNECT,
1645 "Reusing server socket %u. Opened for %s.",
1646 csp->server_connection.sfd, csp->server_connection.host);
1650 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
1652 log_error(LOG_LEVEL_CONNECT,
1653 "Closing server socket %u. Opened for %s.",
1654 csp->server_connection.sfd, csp->server_connection.host);
1655 close_socket(csp->server_connection.sfd);
1656 mark_connection_closed(&csp->server_connection);
1658 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1660 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
1662 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
1664 if (fwd->type != SOCKS_NONE)
1667 rsp = error_response(csp, "forwarding-failed");
1669 else if (errno == EINVAL)
1671 rsp = error_response(csp, "no-such-domain");
1675 rsp = error_response(csp, "connect-failed");
1678 /* Write the answer to the client */
1681 send_crunch_response(csp, rsp);
1686 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1687 save_connection_destination(csp->server_connection.sfd,
1688 http, fwd, &csp->server_connection);
1689 csp->server_connection.keep_alive_timeout =
1690 (unsigned)csp->config->keep_alive_timeout;
1692 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1694 hdr = list_to_text(csp->headers);
1697 /* FIXME Should handle error properly */
1698 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1700 list_remove_all(csp->headers);
1702 if (fwd->forward_host || (http->ssl == 0))
1705 * Write the client's (modified) header to the server
1706 * (along with anything else that may be in the buffer)
1708 if (write_socket(csp->server_connection.sfd, hdr, strlen(hdr))
1709 || (flush_socket(csp->server_connection.sfd, csp->iob) < 0))
1711 log_error(LOG_LEVEL_CONNECT,
1712 "write header to: %s failed: %E", http->hostport);
1714 rsp = error_response(csp, "connect-failed");
1717 send_crunch_response(csp, rsp);
1727 * We're running an SSL tunnel and we're not forwarding,
1728 * so just send the "connect succeeded" message to the
1729 * client, flush the rest, and get out of the way.
1731 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
1739 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
1741 csp->server_connection.request_sent = time(NULL);
1743 /* we're finished with the client's header */
1746 maxfd = (csp->cfd > csp->server_connection.sfd) ?
1747 csp->cfd : csp->server_connection.sfd;
1749 /* pass data between the client and server
1750 * until one or the other shuts down the connection.
1759 * FD_ZERO here seems to point to an errant macro which crashes.
1760 * So do this by hand for now...
1762 memset(&rfds,0x00,sizeof(fd_set));
1766 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1767 if (!watch_client_socket)
1769 maxfd = csp->server_connection.sfd;
1772 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1774 FD_SET(csp->cfd, &rfds);
1777 FD_SET(csp->server_connection.sfd, &rfds);
1779 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1780 if ((csp->flags & CSP_FLAG_CHUNKED)
1781 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
1782 && ((csp->iob->eod - csp->iob->cur) >= 5)
1783 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
1786 * XXX: This check should be obsolete now,
1787 * but let's wait a while to be sure.
1789 log_error(LOG_LEVEL_CONNECT,
1790 "Looks like we got the last chunk together with "
1791 "the server headers but didn't detect it earlier. "
1792 "We better stop reading.");
1793 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
1794 csp->expected_content_length = byte_count;
1795 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
1797 if (server_body && server_response_is_complete(csp, byte_count))
1799 if (csp->expected_content_length == byte_count)
1801 log_error(LOG_LEVEL_CONNECT,
1802 "Done reading from server. Content length: %llu as expected. "
1803 "Bytes most recently read: %d.",
1808 log_error(LOG_LEVEL_CONNECT,
1809 "Done reading from server. Expected content length: %llu. "
1810 "Actual content length: %llu. Bytes most recently read: %d.",
1811 csp->expected_content_length, byte_count, len);
1815 * XXX: should not jump around,
1816 * chat() is complicated enough already.
1820 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1822 timeout.tv_sec = csp->config->socket_timeout;
1823 timeout.tv_usec = 0;
1824 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
1828 log_error(LOG_LEVEL_ERROR,
1829 "Didn't receive data in time: %s", http->url);
1830 if ((byte_count == 0) && (http->ssl == 0))
1832 send_crunch_response(csp, error_response(csp, "connection-timeout"));
1834 mark_server_socket_tainted(csp);
1839 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1840 mark_server_socket_tainted(csp);
1845 * This is the body of the browser's request,
1846 * just read and write it.
1848 * XXX: Make sure the client doesn't use pipelining
1849 * behind Privoxy's back.
1851 if (FD_ISSET(csp->cfd, &rfds))
1853 int max_bytes_to_read = sizeof(buf) - 1;
1855 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1856 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1858 if (data_is_available(csp->cfd, 0))
1861 * If the next request is already waiting, we have
1862 * to stop select()ing the client socket. Otherwise
1863 * we would always return right away and get nothing
1866 watch_client_socket = 0;
1867 log_error(LOG_LEVEL_CONNECT,
1868 "Stopping to watch the client socket. "
1869 "There's already another request waiting.");
1873 * If the client socket is set, but there's no data
1874 * available on the socket, the client went fishing
1875 * and continuing talking to the server makes no sense.
1877 log_error(LOG_LEVEL_CONNECT,
1878 "The client closed socket %d while "
1879 "the server socket %d is still open.",
1880 csp->cfd, csp->server_connection.sfd);
1881 mark_server_socket_tainted(csp);
1884 if (csp->expected_client_content_length != 0)
1886 if (csp->expected_client_content_length < (sizeof(buf) - 1))
1888 max_bytes_to_read = (int)csp->expected_client_content_length;
1890 log_error(LOG_LEVEL_CONNECT,
1891 "Waiting for up to %d bytes from the client.",
1894 assert(max_bytes_to_read < sizeof(buf));
1895 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1897 len = read_socket(csp->cfd, buf, max_bytes_to_read);
1901 /* XXX: not sure if this is necessary. */
1902 mark_server_socket_tainted(csp);
1903 break; /* "game over, man" */
1906 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1907 if (csp->expected_client_content_length != 0)
1909 assert(len <= max_bytes_to_read);
1910 csp->expected_client_content_length -= (unsigned)len;
1911 log_error(LOG_LEVEL_CONNECT,
1912 "Expected client content length set to %llu "
1913 "after reading %d bytes.",
1914 csp->expected_client_content_length, len);
1915 if (csp->expected_client_content_length == 0)
1917 log_error(LOG_LEVEL_CONNECT,
1918 "Done reading from the client.");
1919 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1922 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1924 if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
1926 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1927 mark_server_socket_tainted(csp);
1934 * The server wants to talk. It could be the header or the body.
1935 * If `hdr' is null, then it's the header otherwise it's the body.
1936 * FIXME: Does `hdr' really mean `host'? No.
1938 if (FD_ISSET(csp->server_connection.sfd, &rfds))
1940 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1942 * If we are buffering content, we don't want to eat up to
1943 * buffer-limit bytes if the client no longer cares about them.
1944 * If we aren't buffering, however, a dead client socket will be
1945 * noticed pretty much right away anyway, so we can reduce the
1946 * overhead by skipping the check.
1948 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
1951 log_error(LOG_LEVEL_CONNECT,
1952 "The server still wants to talk, but the client may already have hung up on us.");
1954 log_error(LOG_LEVEL_CONNECT,
1955 "The server still wants to talk, but the client hung up on us.");
1956 mark_server_socket_tainted(csp);
1958 #endif /* def _WIN32 */
1960 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1963 len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
1967 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1969 if (http->ssl && (fwd->forward_host == NULL))
1972 * Just hang up. We already confirmed the client's CONNECT
1973 * request with status code 200 and unencrypted content is
1974 * no longer welcome.
1976 log_error(LOG_LEVEL_ERROR,
1977 "CONNECT already confirmed. Unable to tell the client about the problem.");
1980 else if (byte_count)
1983 * Just hang up. We already transmitted the original headers
1984 * and parts of the original content and therefore missed the
1985 * chance to send an error message (without risking data corruption).
1987 * XXX: we could retry with a fancy range request here.
1989 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
1990 "Unable to tell the client about the problem.");
1991 mark_server_socket_tainted(csp);
1995 * XXX: Consider handling the cases above the same.
1997 mark_server_socket_tainted(csp);
2001 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2002 if (csp->flags & CSP_FLAG_CHUNKED)
2004 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2006 /* XXX: this is a temporary hack */
2007 log_error(LOG_LEVEL_CONNECT,
2008 "Looks like we reached the end of the last chunk. "
2009 "We better stop reading.");
2010 csp->expected_content_length = byte_count + (unsigned long long)len;
2011 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2015 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2018 * Add a trailing zero to let be able to use string operations.
2019 * XXX: do we still need this with filter_popups gone?
2024 * Normally, this would indicate that we've read
2025 * as much as the server has sent us and we can
2026 * close the client connection. However, Microsoft
2027 * in its wisdom has released IIS/5 with a bug that
2028 * prevents it from sending the trailing \r\n in
2029 * a 302 redirect header (and possibly other headers).
2030 * To work around this if we've haven't parsed
2031 * a full header we'll append a trailing \r\n
2032 * and see if this now generates a valid one.
2034 * This hack shouldn't have any impacts. If we've
2035 * already transmitted the header or if this is a
2036 * SSL connection, then we won't bother with this
2037 * hack. So we only work on partially received
2038 * headers. If we append a \r\n and this still
2039 * doesn't generate a valid header, then we won't
2040 * transmit anything to the client.
2045 if (server_body || http->ssl)
2048 * If we have been buffering up the document,
2049 * now is the time to apply content modification
2050 * and send the result to the client.
2052 if (buffer_and_filter_content)
2054 p = execute_content_filters(csp);
2056 * If content filtering fails, use the original
2057 * buffer and length.
2058 * (see p != NULL ? p : csp->iob->cur below)
2062 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2065 if (JB_ERR_OK != update_server_headers(csp))
2067 log_error(LOG_LEVEL_FATAL,
2068 "Failed to update server headers. after filtering.");
2071 hdr = list_to_text(csp->headers);
2074 /* FIXME Should handle error properly */
2075 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2078 if (write_socket(csp->cfd, hdr, strlen(hdr))
2079 || write_socket(csp->cfd,
2080 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2082 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2085 mark_server_socket_tainted(csp);
2093 break; /* "game over, man" */
2097 * This is NOT the body, so
2098 * Let's pretend the server just sent us a blank line.
2100 snprintf(buf, sizeof(buf), "\r\n");
2101 len = (int)strlen(buf);
2104 * Now, let the normal header parsing algorithm below do its
2105 * job. If it fails, we'll exit instead of continuing.
2112 * If this is an SSL connection or we're in the body
2113 * of the server document, just write it to the client,
2114 * unless we need to buffer the body for later content-filtering
2116 if (server_body || http->ssl)
2118 if (buffer_and_filter_content)
2121 * If there is no memory left for buffering the content, or the buffer limit
2122 * has been reached, switch to non-filtering mode, i.e. make & write the
2123 * header, flush the iob and buf, and get out of the way.
2125 if (add_to_iob(csp, buf, len))
2130 log_error(LOG_LEVEL_INFO,
2131 "Flushing header and buffers. Stepping back from filtering.");
2133 hdr = list_to_text(csp->headers);
2137 * Memory is too tight to even generate the header.
2138 * Send our static "Out-of-memory" page.
2140 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2141 rsp = cgi_error_memory();
2142 send_crunch_response(csp, rsp);
2143 mark_server_socket_tainted(csp);
2146 hdrlen = strlen(hdr);
2148 if (write_socket(csp->cfd, hdr, hdrlen)
2149 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2150 || (write_socket(csp->cfd, buf, (size_t)len)))
2152 log_error(LOG_LEVEL_CONNECT,
2153 "Flush header and buffers to client failed: %E");
2155 mark_server_socket_tainted(csp);
2160 * Reset the byte_count to the amount of bytes
2161 * we just flushed. len will be added a few lines below,
2162 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2164 byte_count = (unsigned long long)flushed;
2166 buffer_and_filter_content = 0;
2172 if (write_socket(csp->cfd, buf, (size_t)len))
2174 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2175 mark_server_socket_tainted(csp);
2179 byte_count += (unsigned long long)len;
2185 * We're still looking for the end of the server's header.
2186 * Buffer up the data we just read. If that fails, there's
2187 * little we can do but send our static out-of-memory page.
2189 if (add_to_iob(csp, buf, len))
2191 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2192 rsp = cgi_error_memory();
2193 send_crunch_response(csp, rsp);
2194 mark_server_socket_tainted(csp);
2198 /* Convert iob into something sed() can digest */
2199 if (JB_ERR_PARSE == get_server_headers(csp))
2204 * Well, we tried our MS IIS/5 hack and it didn't work.
2205 * The header is incomplete and there isn't anything
2206 * we can do about it.
2208 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2209 "Applying the MS IIS5 hack didn't help.");
2210 log_error(LOG_LEVEL_CLF,
2211 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2212 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2213 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2214 mark_server_socket_tainted(csp);
2220 * Since we have to wait for more from the server before
2221 * we can parse the headers we just continue here.
2223 log_error(LOG_LEVEL_CONNECT,
2224 "Continuing buffering headers. Bytes most recently read: %d.",
2232 * Account for the content bytes we
2233 * might have gotten with the headers.
2235 assert(csp->iob->eod >= csp->iob->cur);
2236 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2239 /* Did we actually get anything? */
2240 if (NULL == csp->headers->first)
2242 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2244 log_error(LOG_LEVEL_ERROR,
2245 "Empty server or forwarder response received on socket %d. "
2246 "Closing client socket %d without sending data.",
2247 csp->server_connection.sfd, csp->cfd);
2251 log_error(LOG_LEVEL_ERROR,
2252 "Empty server or forwarder response received on socket %d.",
2253 csp->server_connection.sfd);
2254 send_crunch_response(csp, error_response(csp, "no-server-data"));
2256 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2257 free_http_request(http);
2258 mark_server_socket_tainted(csp);
2262 assert(csp->headers->first->str);
2264 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2265 strncmpic(csp->headers->first->str, "ICY", 3))
2268 * It doesn't look like a HTTP (or Shoutcast) response:
2269 * tell the client and log the problem.
2271 if (strlen(csp->headers->first->str) > 30)
2273 csp->headers->first->str[30] = '\0';
2275 log_error(LOG_LEVEL_ERROR,
2276 "Invalid server or forwarder response. Starts with: %s",
2277 csp->headers->first->str);
2278 log_error(LOG_LEVEL_CLF,
2279 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2280 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2281 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2282 free_http_request(http);
2283 mark_server_socket_tainted(csp);
2288 * We have now received the entire server header,
2289 * filter it and send the result to the client
2291 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2293 log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2295 hdr = list_to_text(csp->headers);
2298 /* FIXME Should handle error properly */
2299 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2302 if ((csp->flags & CSP_FLAG_CHUNKED)
2303 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2304 && ((csp->iob->eod - csp->iob->cur) >= 5)
2305 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2307 log_error(LOG_LEVEL_CONNECT,
2308 "Looks like we got the last chunk together with "
2309 "the server headers. We better stop reading.");
2310 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2311 csp->expected_content_length = byte_count;
2312 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2315 csp->server_connection.response_received = time(NULL);
2317 if (crunch_response_triggered(csp, crunchers_light))
2320 * One of the tags created by a server-header
2321 * tagger triggered a crunch. We already
2322 * delivered the crunch response to the client
2323 * and are done here after cleaning up.
2326 mark_server_socket_tainted(csp);
2329 /* Buffer and pcrs filter this if appropriate. */
2331 if (!http->ssl) /* We talk plaintext */
2333 buffer_and_filter_content = content_requires_filtering(csp);
2336 * Only write if we're not buffering for content modification
2338 if (!buffer_and_filter_content)
2341 * Write the server's (modified) header to
2342 * the client (along with anything else that
2343 * may be in the buffer)
2346 if (write_socket(csp->cfd, hdr, strlen(hdr))
2347 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2349 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2352 * The write failed, so don't bother mentioning it
2353 * to the client... it probably can't hear us anyway.
2356 mark_server_socket_tainted(csp);
2361 /* we're finished with the server's header */
2367 * If this was a MS IIS/5 hack then it means the server
2368 * has already closed the connection. Nothing more to read.
2373 log_error(LOG_LEVEL_ERROR,
2374 "Closed server connection detected. "
2375 "Applying the MS IIS5 hack didn't help.");
2376 log_error(LOG_LEVEL_CLF,
2377 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2378 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2379 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2380 mark_server_socket_tainted(csp);
2386 mark_server_socket_tainted(csp);
2387 return; /* huh? we should never get here */
2390 if (csp->content_length == 0)
2393 * If Privoxy didn't recalculate the Content-Length,
2394 * byte_count is still correct.
2396 csp->content_length = byte_count;
2399 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2400 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2401 && (csp->expected_content_length != byte_count))
2403 log_error(LOG_LEVEL_CONNECT,
2404 "Received %llu bytes while expecting %llu.",
2405 byte_count, csp->expected_content_length);
2406 mark_server_socket_tainted(csp);
2410 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2411 csp->ip_addr_str, http->ocmd, csp->content_length);
2413 csp->server_connection.timestamp = time(NULL);
2417 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2418 /*********************************************************************
2420 * Function : prepare_csp_for_next_request
2422 * Description : Put the csp in a mostly vergin state.
2425 * 1 : csp = Current client state (buffers, headers, etc...)
2429 *********************************************************************/
2430 static void prepare_csp_for_next_request(struct client_state *csp)
2432 csp->content_type = 0;
2433 csp->content_length = 0;
2434 csp->expected_content_length = 0;
2435 csp->expected_client_content_length = 0;
2436 list_remove_all(csp->headers);
2437 freez(csp->iob->buf);
2438 memset(csp->iob, 0, sizeof(csp->iob));
2439 freez(csp->error_message);
2440 free_http_request(csp->http);
2441 destroy_list(csp->headers);
2442 destroy_list(csp->tags);
2443 free_current_action(csp->action);
2444 if (NULL != csp->fwd)
2446 unload_forward_spec(csp->fwd);
2449 /* XXX: Store per-connection flags someplace else. */
2450 csp->flags &= CSP_FLAG_TOGGLED_ON;
2451 csp->flags |= CSP_FLAG_ACTIVE;
2452 csp->flags |= CSP_FLAG_REUSED_CLIENT_CONNECTION;
2454 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2457 /*********************************************************************
2461 * Description : This is little more than chat. We only "serve" to
2462 * to close (or remember) any socket that chat may have
2466 * 1 : csp = Current client state (buffers, headers, etc...)
2470 *********************************************************************/
2472 void serve(struct client_state *csp)
2473 #else /* ifndef AMIGA */
2474 static void serve(struct client_state *csp)
2475 #endif /* def AMIGA */
2477 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2478 #ifdef FEATURE_CONNECTION_SHARING
2479 static int monitor_thread_running = 0;
2480 #endif /* def FEATURE_CONNECTION_SHARING */
2481 int continue_chatting = 0;
2485 unsigned int latency;
2486 int config_file_change_detected = 0; /* Only used for debugging */
2491 * If the request has been crunched,
2492 * the calculated latency is zero.
2494 latency = (unsigned)(csp->server_connection.response_received -
2495 csp->server_connection.request_sent) / 2;
2497 continue_chatting = (csp->config->feature_flags
2498 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2499 && (((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2500 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2501 || (csp->flags & CSP_FLAG_CRUNCHED))
2502 && (csp->cfd != JB_INVALID_SOCKET)
2503 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE);
2505 if (continue_chatting && !(csp->flags & CSP_FLAG_CRUNCHED))
2507 continue_chatting = (csp->server_connection.sfd != JB_INVALID_SOCKET)
2508 && socket_is_still_alive(csp->server_connection.sfd);
2509 if (continue_chatting)
2511 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
2513 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
2514 log_error(LOG_LEVEL_CONNECT,
2515 "The server didn't specify how long the connection will stay open. "
2516 "Assumed timeout is: %u.", csp->server_connection.keep_alive_timeout);
2518 continue_chatting = (latency < csp->server_connection.keep_alive_timeout);
2522 if (continue_chatting && any_loaded_file_changed(csp->config->config_file_list))
2524 continue_chatting = 0;
2525 config_file_change_detected = 1;
2528 if (continue_chatting)
2530 unsigned int client_timeout;
2532 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2534 client_timeout = (unsigned)csp->server_connection.keep_alive_timeout - latency;
2535 log_error(LOG_LEVEL_CONNECT,
2536 "Waiting for the next client request on socket %d. "
2537 "Keeping the server socket %d to %s open.",
2538 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2542 client_timeout = 1; /* XXX: Use something else here? */
2543 log_error(LOG_LEVEL_CONNECT,
2544 "Waiting for the next client request on socket %d. "
2545 "No server socket to keep open.", csp->cfd);
2547 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2548 && data_is_available(csp->cfd, (int)client_timeout)
2549 && socket_is_still_alive(csp->cfd))
2551 log_error(LOG_LEVEL_CONNECT,
2552 "Client request arrived in time on socket %d.", csp->cfd);
2553 prepare_csp_for_next_request(csp);
2557 log_error(LOG_LEVEL_CONNECT,
2558 "No additional client request received in time on socket %d.",
2560 #ifdef FEATURE_CONNECTION_SHARING
2561 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2562 && (socket_is_still_alive(csp->server_connection.sfd)))
2564 time_t time_open = time(NULL) - csp->server_connection.timestamp;
2566 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
2571 remember_connection(&csp->server_connection);
2572 csp->server_connection.sfd = JB_INVALID_SOCKET;
2573 close_socket(csp->cfd);
2574 csp->cfd = JB_INVALID_SOCKET;
2575 privoxy_mutex_lock(&connection_reuse_mutex);
2576 if (!monitor_thread_running)
2578 monitor_thread_running = 1;
2579 privoxy_mutex_unlock(&connection_reuse_mutex);
2580 wait_for_alive_connections();
2581 privoxy_mutex_lock(&connection_reuse_mutex);
2582 monitor_thread_running = 0;
2584 privoxy_mutex_unlock(&connection_reuse_mutex);
2586 #endif /* def FEATURE_CONNECTION_SHARING */
2590 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2592 log_error(LOG_LEVEL_CONNECT,
2593 "The connection on server socket %d to %s isn't reusable. Closing. "
2594 "Server connection: keep-alive %u, tainted: %u, socket alive %u. "
2595 "Client connection: socket alive: %u. Server timeout: %u. "
2596 "Configuration file change detected: %u",
2597 csp->server_connection.sfd, csp->server_connection.host,
2598 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2599 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2600 socket_is_still_alive(csp->server_connection.sfd),
2601 socket_is_still_alive(csp->cfd),
2602 csp->server_connection.keep_alive_timeout,
2603 config_file_change_detected);
2605 } while (continue_chatting);
2609 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2611 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2613 #ifdef FEATURE_CONNECTION_SHARING
2614 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2616 forget_connection(csp->server_connection.sfd);
2618 #endif /* def FEATURE_CONNECTION_SHARING */
2619 close_socket(csp->server_connection.sfd);
2622 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2623 mark_connection_closed(&csp->server_connection);
2626 if (csp->cfd != JB_INVALID_SOCKET)
2628 close_socket(csp->cfd);
2631 csp->flags &= ~CSP_FLAG_ACTIVE;
2637 /*********************************************************************
2639 * Function : server_thread
2641 * Description : We only exist to call `serve' in a threaded environment.
2644 * 1 : data = Current client state (buffers, headers, etc...)
2646 * Returns : Always 0.
2648 *********************************************************************/
2649 static int32 server_thread(void *data)
2651 serve((struct client_state *) data);
2658 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2659 /*********************************************************************
2663 * Description : Print usage info & exit.
2665 * Parameters : Pointer to argv[0] for identifying ourselves
2669 *********************************************************************/
2670 static void usage(const char *myname)
2672 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
2676 #endif /* defined(unix) */
2679 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
2680 #endif /* defined(unix) */
2681 "[--version] [configfile]\n"
2682 "Aborting\n", myname);
2687 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
2690 #ifdef MUTEX_LOCKS_AVAILABLE
2691 /*********************************************************************
2693 * Function : privoxy_mutex_lock
2695 * Description : Locks a mutex.
2698 * 1 : mutex = The mutex to lock.
2700 * Returns : Void. May exit in case of errors.
2702 *********************************************************************/
2703 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
2705 #ifdef FEATURE_PTHREAD
2706 int err = pthread_mutex_lock(mutex);
2709 if (mutex != &log_mutex)
2711 log_error(LOG_LEVEL_FATAL,
2712 "Mutex locking failed: %s.\n", strerror(err));
2717 EnterCriticalSection(mutex);
2718 #endif /* def FEATURE_PTHREAD */
2722 /*********************************************************************
2724 * Function : privoxy_mutex_unlock
2726 * Description : Unlocks a mutex.
2729 * 1 : mutex = The mutex to unlock.
2731 * Returns : Void. May exit in case of errors.
2733 *********************************************************************/
2734 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
2736 #ifdef FEATURE_PTHREAD
2737 int err = pthread_mutex_unlock(mutex);
2740 if (mutex != &log_mutex)
2742 log_error(LOG_LEVEL_FATAL,
2743 "Mutex unlocking failed: %s.\n", strerror(err));
2748 LeaveCriticalSection(mutex);
2749 #endif /* def FEATURE_PTHREAD */
2753 /*********************************************************************
2755 * Function : privoxy_mutex_init
2757 * Description : Prepares a mutex.
2760 * 1 : mutex = The mutex to initialize.
2762 * Returns : Void. May exit in case of errors.
2764 *********************************************************************/
2765 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
2767 #ifdef FEATURE_PTHREAD
2768 int err = pthread_mutex_init(mutex, 0);
2771 printf("Fatal error. Mutex initialization failed: %s.\n",
2776 InitializeCriticalSection(mutex);
2777 #endif /* def FEATURE_PTHREAD */
2779 #endif /* def MUTEX_LOCKS_AVAILABLE */
2781 /*********************************************************************
2783 * Function : initialize_mutexes
2785 * Description : Prepares mutexes if mutex support is available.
2789 * Returns : Void, exits in case of errors.
2791 *********************************************************************/
2792 static void initialize_mutexes(void)
2794 #ifdef MUTEX_LOCKS_AVAILABLE
2796 * Prepare global mutex semaphores
2798 privoxy_mutex_init(&log_mutex);
2799 privoxy_mutex_init(&log_init_mutex);
2800 privoxy_mutex_init(&connection_reuse_mutex);
2803 * XXX: The assumptions below are a bit naive
2804 * and can cause locks that aren't necessary.
2806 * For example older FreeBSD versions (< 6.x?)
2807 * have no gethostbyname_r, but gethostbyname is
2810 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
2811 privoxy_mutex_init(&resolver_mutex);
2812 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
2814 * XXX: should we use a single mutex for
2815 * localtime() and gmtime() as well?
2817 #ifndef HAVE_GMTIME_R
2818 privoxy_mutex_init(&gmtime_mutex);
2819 #endif /* ndef HAVE_GMTIME_R */
2821 #ifndef HAVE_LOCALTIME_R
2822 privoxy_mutex_init(&localtime_mutex);
2823 #endif /* ndef HAVE_GMTIME_R */
2826 privoxy_mutex_init(&rand_mutex);
2827 #endif /* ndef HAVE_RANDOM */
2828 #endif /* def MUTEX_LOCKS_AVAILABLE */
2832 /*********************************************************************
2836 * Description : Load the config file and start the listen loop.
2837 * This function is a lot more *sane* with the `load_config'
2838 * and `listen_loop' functions; although it stills does
2839 * a *little* too much for my taste.
2842 * 1 : argc = Number of parameters (including $0).
2843 * 2 : argv = Array of (char *)'s to the parameters.
2845 * Returns : 1 if : can't open config file, unrecognized directive,
2846 * stats requested in multi-thread mode, can't open the
2847 * log file, can't open the jar file, listen port is invalid,
2848 * any load fails, and can't bind port.
2850 * Else main never returns, the process must be signaled
2851 * to terminate execution. Or, on Windows, use the
2852 * "File", "Exit" menu option.
2854 *********************************************************************/
2856 int real_main(int argc, char **argv)
2858 int main(int argc, char **argv)
2862 unsigned int random_seed;
2864 struct passwd *pw = NULL;
2865 struct group *grp = NULL;
2868 char *pre_chroot_nslookup_to_load_resolver = NULL;
2875 #if !defined(_WIN32)
2882 /* Prepare mutexes if supported and necessary. */
2883 initialize_mutexes();
2885 /* Enable logging until further notice. */
2889 * Parse the command line arguments
2891 * XXX: simply printing usage information in case of
2892 * invalid arguments isn't particularly user friendly.
2894 while (++argc_pos < argc)
2897 /* Check to see if the service must be installed or uninstalled */
2898 if (strncmp(argv[argc_pos], "--install", 9) == 0)
2900 const char *pName = argv[argc_pos] + 9;
2903 exit( (install_service(pName)) ? 0 : 1 );
2905 else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
2907 const char *pName = argv[argc_pos] + 11;
2910 exit((uninstall_service(pName)) ? 0 : 1);
2912 else if (strcmp(argv[argc_pos], "--service" ) == 0)
2914 bRunAsService = TRUE;
2915 w32_set_service_cwd();
2916 atexit(w32_service_exit_notify);
2919 #endif /* defined(_WIN32) */
2922 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2924 if (strcmp(argv[argc_pos], "--help") == 0)
2929 else if(strcmp(argv[argc_pos], "--version") == 0)
2931 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2937 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
2939 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
2943 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
2945 if (++argc_pos == argc) usage(argv[0]);
2946 pidfile = strdup(argv[argc_pos]);
2949 else if (strcmp(argv[argc_pos], "--user" ) == 0)
2951 if (++argc_pos == argc) usage(argv[argc_pos]);
2953 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
2956 if (NULL == (grp = getgrnam(p)))
2958 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
2962 if (NULL == (pw = getpwnam(argv[argc_pos])))
2964 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
2967 if (p != NULL) *--p = '\0';
2970 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup" ) == 0)
2972 if (++argc_pos == argc) usage(argv[0]);
2973 pre_chroot_nslookup_to_load_resolver = strdup(argv[argc_pos]);
2976 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
2980 #endif /* defined(unix) */
2982 else if (argc_pos + 1 != argc)
2985 * This is neither the last command line
2986 * option, nor was it recognized before,
2987 * therefore it must be invalid.
2993 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
2995 configfile = argv[argc_pos];
2998 } /* -END- while (more arguments) */
3000 show_version(Argv[0]);
3003 if ( *configfile != '/' )
3005 char cwd[BUFFER_SIZE];
3007 size_t abs_file_size;
3009 /* make config-filename absolute here */
3010 if (NULL == getcwd(cwd, sizeof(cwd)))
3012 perror("failed to get current working directory");
3017 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3018 basedir = strdup(cwd);
3020 if (NULL == basedir ||
3021 NULL == (abs_file = malloc(abs_file_size)))
3023 perror("malloc failed");
3026 strlcpy(abs_file, basedir, abs_file_size);
3027 strlcat(abs_file, "/", abs_file_size );
3028 strlcat(abs_file, configfile, abs_file_size);
3029 configfile = abs_file;
3031 #endif /* defined unix */
3035 clients->next = NULL;
3037 /* XXX: factor out initialising after the next stable release. */
3040 #elif defined(_WIN32)
3044 random_seed = (unsigned int)time(NULL);
3046 srandom(random_seed);
3049 #endif /* ifdef HAVE_RANDOM */
3052 * Unix signal handling
3054 * Catch the abort, interrupt and terminate signals for a graceful exit
3055 * Catch the hangup signal so the errlog can be reopened.
3056 * Ignore the broken pipe signals (FIXME: Why?)
3058 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3061 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP, 0 };
3062 const int ignored_signals[] = { SIGPIPE, 0 };
3064 for (idx = 0; catched_signals[idx] != 0; idx++)
3066 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3067 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3069 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3070 #endif /* ifdef sun */
3072 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3076 for (idx = 0; ignored_signals[idx] != 0; idx++)
3078 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
3080 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
3085 #else /* ifdef _WIN32 */
3086 # ifdef _WIN_CONSOLE
3088 * We *are* in a windows console app.
3089 * Print a verbose messages about FAQ's and such
3091 printf("%s", win32_blurb);
3092 # endif /* def _WIN_CONSOLE */
3093 #endif /* def _WIN32 */
3096 /* Initialize the CGI subsystem */
3097 cgi_init_error_messages();
3100 * If runnig on unix and without the --nodaemon
3101 * option, become a daemon. I.e. fork, detach
3102 * from tty and get process group leadership
3111 if ( pid < 0 ) /* error */
3116 else if ( pid != 0 ) /* parent */
3121 * must check for errors
3122 * child died due to missing files aso
3125 wpid = waitpid( pid, &status, WNOHANG );
3137 * stderr (fd 2) will be closed later on,
3138 * when the config file has been parsed.
3144 * Reserve fd 0 and 1 to prevent abort() and friends
3145 * from sending stuff to the clients or servers.
3147 fd = open("/dev/null", O_RDONLY);
3150 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3154 if (dup2(fd, 0) == -1)
3156 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3160 fd = open("/dev/null", O_WRONLY);
3163 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3167 if (dup2(fd, 1) == -1)
3169 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3176 } /* -END- if (daemon_mode) */
3179 * As soon as we have written the PID file, we can switch
3180 * to the user and group ID indicated by the --user option
3186 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3188 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3192 if (setgroups(1, &grp->gr_gid))
3194 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3197 else if (initgroups(pw->pw_name, pw->pw_gid))
3199 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3205 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3207 /* Read the time zone file from /etc before doing chroot. */
3209 if (NULL != pre_chroot_nslookup_to_load_resolver
3210 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3212 /* Initialize resolver library. */
3213 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3215 if (chroot(pw->pw_dir) < 0)
3217 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3221 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3224 if (setuid(pw->pw_uid))
3226 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3230 char putenv_dummy[64];
3232 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3233 if (putenv(putenv_dummy) != 0)
3235 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3238 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3239 if (putenv(putenv_dummy) != 0)
3241 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3247 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3250 #endif /* defined unix */
3253 /* This will be FALSE unless the command line specified --service
3257 /* Yup, so now we must attempt to establish a connection
3258 * with the service dispatcher. This will only work if this
3259 * process was launched by the service control manager to
3260 * actually run as a service. If this isn't the case, i've
3261 * known it take around 30 seconds or so for the call to return.
3264 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3265 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3267 /* Service has run, and at this point is now being stopped, so just return */
3272 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3274 /* An error occurred. Usually it's because --service was wrongly specified
3275 * and we were unable to connect to the Service Control Dispatcher because
3276 * it wasn't expecting us and is therefore not listening.
3278 * For now, just continue below to call the listen_loop function.
3281 #endif /* def _WIN32 */
3291 /*********************************************************************
3293 * Function : bind_port_helper
3295 * Description : Bind the listen port. Handles logging, and aborts
3299 * 1 : config = Privoxy configuration. Specifies port
3302 * Returns : Port that was opened.
3304 *********************************************************************/
3305 static jb_socket bind_port_helper(struct configuration_spec * config)
3310 if (config->haddr == NULL)
3312 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3317 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3318 config->hport, config->haddr);
3321 result = bind_port(config->haddr, config->hport, &bfd);
3328 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
3329 "There may be another Privoxy or some other "
3330 "proxy running on port %d",
3331 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
3332 config->hport, config->hport);
3335 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
3336 "The hostname is not resolvable",
3337 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3340 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3341 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3344 /* shouldn't get here */
3345 return JB_INVALID_SOCKET;
3348 config->need_bind = 0;
3355 /* Without this simple workaround we get this compiler warning from _beginthread
3356 * warning C4028: formal parameter 1 different from declaration
3358 void w32_service_listen_loop(void *p)
3362 #endif /* def _WIN32 */
3365 /*********************************************************************
3367 * Function : listen_loop
3369 * Description : bind the listen port and enter a "FOREVER" listening loop.
3375 *********************************************************************/
3376 static void listen_loop(void)
3378 struct client_states *csp_list = NULL;
3379 struct client_state *csp = NULL;
3381 struct configuration_spec *config;
3382 unsigned int active_threads = 0;
3384 config = load_config();
3386 #ifdef FEATURE_CONNECTION_SHARING
3388 * XXX: Should be relocated once it no
3389 * longer needs to emit log messages.
3391 initialize_reusable_connections();
3392 #endif /* def FEATURE_CONNECTION_SHARING */
3394 bfd = bind_port_helper(config);
3396 #ifdef FEATURE_GRACEFUL_TERMINATION
3397 while (!g_terminate)
3402 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3403 while (waitpid(-1, NULL, WNOHANG) > 0)
3405 /* zombie children */
3407 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3410 * Free data that was used by died threads
3412 active_threads = sweep();
3416 * Re-open the errlog after HUP signal
3418 if (received_hup_signal)
3420 if (NULL != config->logfile)
3422 init_error_log(Argv[0], config->logfile);
3424 received_hup_signal = 0;
3428 csp_list = (struct client_states *)zalloc(sizeof(*csp_list));
3429 if (NULL == csp_list)
3431 log_error(LOG_LEVEL_FATAL,
3432 "malloc(%d) for csp_list failed: %E", sizeof(*csp_list));
3435 csp = &csp_list->csp;
3437 log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
3439 if (!accept_connection(csp, bfd))
3441 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3454 log_error(LOG_LEVEL_CONNECT,
3455 "accepted connection from %s on socket %d",
3456 csp->ip_addr_str, csp->cfd);
3459 csp->flags |= CSP_FLAG_ACTIVE;
3460 csp->server_connection.sfd = JB_INVALID_SOCKET;
3462 csp->config = config = load_config();
3464 if ( config->need_bind )
3467 * Since we were listening to the "old port", we will not see
3468 * a "listen" param change until the next request. So, at
3469 * least 1 more request must be made for us to find the new
3470 * setting. I am simply closing the old socket and binding the
3473 * Which-ever is correct, we will serve 1 more page via the
3474 * old settings. This should probably be a "show-proxy-args"
3475 * request. This should not be a so common of an operation
3476 * that this will hurt people's feelings.
3481 bfd = bind_port_helper(config);
3484 #ifdef FEATURE_TOGGLE
3485 if (global_toggle_state)
3486 #endif /* def FEATURE_TOGGLE */
3488 csp->flags |= CSP_FLAG_TOGGLED_ON;
3491 if (run_loader(csp))
3493 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3494 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3498 if (block_acl(NULL,csp))
3500 log_error(LOG_LEVEL_CONNECT, "Connection from %s dropped due to ACL", csp->ip_addr_str);
3501 close_socket(csp->cfd);
3502 freez(csp->ip_addr_str);
3506 #endif /* def FEATURE_ACL */
3508 if ((0 != config->max_client_connections)
3509 && (active_threads >= config->max_client_connections))
3511 log_error(LOG_LEVEL_CONNECT,
3512 "Rejecting connection from %s. Maximum number of connections reached.",
3514 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3515 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3516 close_socket(csp->cfd);
3517 freez(csp->ip_addr_str);
3522 /* add it to the list of clients */
3523 csp_list->next = clients->next;
3524 clients->next = csp_list;
3526 if (config->multi_threaded)
3530 /* this is a switch () statment in the C preprocessor - ugh */
3531 #undef SELECTED_ONE_OPTION
3533 /* Use Pthreads in preference to native code */
3534 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
3535 #define SELECTED_ONE_OPTION
3537 pthread_t the_thread;
3538 pthread_attr_t attrs;
3540 pthread_attr_init(&attrs);
3541 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
3542 errno = pthread_create(&the_thread, &attrs,
3543 (void * (*)(void *))serve, csp);
3544 child_id = errno ? -1 : 0;
3545 pthread_attr_destroy(&attrs);
3549 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
3550 #define SELECTED_ONE_OPTION
3551 child_id = _beginthread(
3552 (void (*)(void *))serve,
3557 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
3558 #define SELECTED_ONE_OPTION
3559 child_id = _beginthread(
3560 (void(* _Optlink)(void*))serve,
3566 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
3567 #define SELECTED_ONE_OPTION
3569 thread_id tid = spawn_thread
3570 (server_thread, "server", B_NORMAL_PRIORITY, csp);
3572 if ((tid >= 0) && (resume_thread(tid) == B_OK))
3574 child_id = (int) tid;
3583 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
3584 #define SELECTED_ONE_OPTION
3585 csp->cfd = ReleaseSocket(csp->cfd, -1);
3588 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3589 NP_Output, Output(),
3590 NP_CloseOutput, FALSE,
3591 NP_Name, (ULONG)"privoxy child",
3595 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3596 NP_Output, Output(),
3597 NP_CloseOutput, FALSE,
3598 NP_Name, (ULONG)"privoxy child",
3599 NP_StackSize, 200*1024,
3605 ((struct Task *)child_id)->tc_UserData = csp;
3606 Signal((struct Task *)child_id, SIGF_SINGLE);
3611 #if !defined(SELECTED_ONE_OPTION)
3614 /* This block is only needed when using fork().
3615 * When using threads, the server thread was
3616 * created and run by the call to _beginthread().
3618 if (child_id == 0) /* child */
3621 #ifdef FEATURE_TOGGLE
3622 int inherited_toggle_state = global_toggle_state;
3623 #endif /* def FEATURE_TOGGLE */
3628 * If we've been toggled or we've blocked the request, tell Mom
3631 #ifdef FEATURE_TOGGLE
3632 if (inherited_toggle_state != global_toggle_state)
3634 rc |= RC_FLAG_TOGGLED;
3636 #endif /* def FEATURE_TOGGLE */
3638 #ifdef FEATURE_STATISTICS
3639 if (csp->flags & CSP_FLAG_REJECTED)
3641 rc |= RC_FLAG_BLOCKED;
3643 #endif /* ndef FEATURE_STATISTICS */
3647 else if (child_id > 0) /* parent */
3649 /* in a fork()'d environment, the parent's
3650 * copy of the client socket and the CSP
3654 #if !defined(_WIN32) && !defined(__CYGWIN__)
3656 wait( &child_status );
3659 * Evaluate child's return code: If the child has
3660 * - been toggled, toggle ourselves
3661 * - blocked its request, bump up the stats counter
3664 #ifdef FEATURE_TOGGLE
3665 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
3667 global_toggle_state = !global_toggle_state;
3669 #endif /* def FEATURE_TOGGLE */
3671 #ifdef FEATURE_STATISTICS
3673 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
3677 #endif /* def FEATURE_STATISTICS */
3679 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
3680 close_socket(csp->cfd);
3681 csp->flags &= ~CSP_FLAG_ACTIVE;
3685 #undef SELECTED_ONE_OPTION
3686 /* end of cpp switch () */
3691 * Spawning the child failed, assume it's because
3692 * there are too many children running already.
3693 * XXX: If you assume ...
3695 log_error(LOG_LEVEL_ERROR,
3696 "Unable to take any additional connections: %E");
3697 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3698 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3699 close_socket(csp->cfd);
3700 csp->flags &= ~CSP_FLAG_ACTIVE;
3709 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
3711 /* Clean up. Aim: free all memory (no leaks) */
3712 #ifdef FEATURE_GRACEFUL_TERMINATION
3714 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
3716 unload_current_config_file();
3717 unload_current_actions_file();
3718 unload_current_re_filterfile();
3719 #ifdef FEATURE_TRUST
3720 unload_current_trust_file();
3723 if (config->multi_threaded)
3730 } while ((clients->next != NULL) && (--i > 0));
3734 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
3744 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
3745 /* Cleanup - remove taskbar icon etc. */
3750 #endif /* FEATURE_GRACEFUL_TERMINATION */