1 const char jcc_rcs[] = "$Id: jcc.c,v 1.398 2012/10/21 12:51:57 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-2012 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.1 200 Connection established\r\n"
212 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
214 static const char CHEADER[] =
215 "HTTP/1.1 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.1 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.1 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.1 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.1 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.1 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.1 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.1 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 : log_applied_actions
668 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
672 * 1 : actions = Current action spec to log
676 *********************************************************************/
677 static void log_applied_actions(const struct current_action_spec *actions)
680 * The conversion to text requires lots of memory allocations so
681 * we only do the conversion if the user is actually interested.
683 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
685 char *actions_as_text = actions_to_line_of_text(actions);
686 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
687 freez(actions_as_text);
692 /*********************************************************************
694 * Function : send_crunch_response
696 * Description : Delivers already prepared response for
697 * intercepted requests, logs the interception
698 * and frees the response.
701 * 1 : csp = Current client state (buffers, headers, etc...)
702 * 1 : rsp = Fully prepared response. Will be freed on exit.
706 *********************************************************************/
707 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
709 const struct http_request *http = csp->http;
713 assert(rsp->head != NULL);
717 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
721 * Extract the status code from the actual head
722 * that will be send to the client. It is the only
723 * way to get it right for all requests, including
724 * the fixed ones for out-of-memory problems.
726 * A head starts like this: 'HTTP/1.1 200...'
730 status_code[0] = rsp->head[9];
731 status_code[1] = rsp->head[10];
732 status_code[2] = rsp->head[11];
733 status_code[3] = '\0';
735 /* Log that the request was crunched and why. */
736 log_applied_actions(csp->action);
737 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
738 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
739 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
741 /* Write the answer to the client */
742 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
743 || write_socket(csp->cfd, rsp->body, rsp->content_length))
745 /* There is nothing we can do about it. */
746 log_error(LOG_LEVEL_ERROR,
747 "Couldn't deliver the error message through client socket %d: %E",
751 /* Clean up and return */
752 if (cgi_error_memory() != rsp)
754 free_http_response(rsp);
760 /*********************************************************************
762 * Function : crunch_response_triggered
764 * Description : Checks if the request has to be crunched,
765 * and delivers the crunch response if necessary.
768 * 1 : csp = Current client state (buffers, headers, etc...)
769 * 2 : crunchers = list of cruncher functions to run
771 * Returns : TRUE if the request was answered with a crunch response
774 *********************************************************************/
775 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
777 struct http_response *rsp = NULL;
778 const struct cruncher *c;
781 * If CGI request crunching is disabled,
782 * check the CGI dispatcher out of order to
783 * prevent unintentional blocks or redirects.
785 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
786 && (NULL != (rsp = dispatch_cgi(csp))))
788 /* Deliver, log and free the interception response. */
789 send_crunch_response(csp, rsp);
790 csp->flags |= CSP_FLAG_CRUNCHED;
794 for (c = crunchers; c->cruncher != NULL; c++)
797 * Check the cruncher if either Privoxy is toggled
798 * on and the request isn't forced, or if the cruncher
799 * applies to forced requests as well.
801 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
802 !(csp->flags & CSP_FLAG_FORCED)) ||
803 (c->flags & CF_IGNORE_FORCE))
805 rsp = c->cruncher(csp);
808 /* Deliver, log and free the interception response. */
809 send_crunch_response(csp, rsp);
810 csp->flags |= CSP_FLAG_CRUNCHED;
811 #ifdef FEATURE_STATISTICS
812 if (c->flags & CF_COUNT_AS_REJECT)
814 csp->flags |= CSP_FLAG_REJECTED;
816 #endif /* def FEATURE_STATISTICS */
827 /*********************************************************************
829 * Function : build_request_line
831 * Description : Builds the HTTP request line.
833 * If a HTTP forwarder is used it expects the whole URL,
834 * web servers only get the path.
837 * 1 : csp = Current client state (buffers, headers, etc...)
838 * 2 : fwd = The forwarding spec used for the request
839 * XXX: Should use http->fwd instead.
840 * 3 : request_line = The old request line which will be replaced.
842 * Returns : Nothing. Terminates in case of memory problems.
844 *********************************************************************/
845 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
847 struct http_request *http = csp->http;
849 assert(http->ssl == 0);
852 * Downgrade http version from 1.1 to 1.0
853 * if +downgrade action applies.
855 if ((csp->action->flags & ACTION_DOWNGRADE)
856 && (!strcmpic(http->ver, "HTTP/1.1")))
859 http->ver = strdup_or_die("HTTP/1.0");
863 * Rebuild the request line.
865 freez(*request_line);
866 *request_line = strdup(http->gpc);
867 string_append(request_line, " ");
869 if (fwd->forward_host)
871 string_append(request_line, http->url);
875 string_append(request_line, http->path);
877 string_append(request_line, " ");
878 string_append(request_line, http->ver);
880 if (*request_line == NULL)
882 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
884 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
888 /*********************************************************************
890 * Function : change_request_destination
892 * Description : Parse a (rewritten) request line and regenerate
893 * the http request data.
896 * 1 : csp = Current client state (buffers, headers, etc...)
898 * Returns : Forwards the parse_http_request() return code.
899 * Terminates in case of memory problems.
901 *********************************************************************/
902 static jb_err change_request_destination(struct client_state *csp)
904 struct http_request *http = csp->http;
907 log_error(LOG_LEVEL_INFO, "Rewrite detected: %s", csp->headers->first->str);
908 free_http_request(http);
909 err = parse_http_request(csp->headers->first->str, http);
910 if (JB_ERR_OK != err)
912 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
913 jb_err_to_string(err));
917 /* XXX: ocmd is a misleading name */
918 http->ocmd = strdup_or_die(http->cmd);
925 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
926 /*********************************************************************
928 * Function : server_response_is_complete
930 * Description : Determines whether we should stop reading
931 * from the server socket.
934 * 1 : csp = Current client state (buffers, headers, etc...)
935 * 2 : content_length = Length of content received so far.
937 * Returns : TRUE if the response is complete,
940 *********************************************************************/
941 static int server_response_is_complete(struct client_state *csp,
942 unsigned long long content_length)
944 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
946 if (!strcmpic(csp->http->gpc, "HEAD"))
949 * "HEAD" implies no body, we are thus expecting
950 * no content. XXX: incomplete "list" of methods?
952 csp->expected_content_length = 0;
953 content_length_known = TRUE;
956 if (csp->http->status == 204 || csp->http->status == 304)
959 * Expect no body. XXX: incomplete "list" of status codes?
961 csp->expected_content_length = 0;
962 content_length_known = TRUE;
965 return (content_length_known && ((0 == csp->expected_content_length)
966 || (csp->expected_content_length <= content_length)));
970 #ifdef FEATURE_CONNECTION_SHARING
971 /*********************************************************************
973 * Function : wait_for_alive_connections
975 * Description : Waits for alive connections to timeout.
981 *********************************************************************/
982 static void wait_for_alive_connections(void)
984 int connections_alive = close_unusable_connections();
986 while (0 < connections_alive)
988 log_error(LOG_LEVEL_CONNECT,
989 "Waiting for %d connections to timeout.",
992 connections_alive = close_unusable_connections();
995 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
998 #endif /* def FEATURE_CONNECTION_SHARING */
1001 /*********************************************************************
1003 * Function : save_connection_destination
1005 * Description : Remembers a connection for reuse later on.
1008 * 1 : sfd = Open socket to remember.
1009 * 2 : http = The destination for the connection.
1010 * 3 : fwd = The forwarder settings used.
1011 * 3 : server_connection = storage.
1015 *********************************************************************/
1016 void save_connection_destination(jb_socket sfd,
1017 const struct http_request *http,
1018 const struct forward_spec *fwd,
1019 struct reusable_connection *server_connection)
1021 assert(sfd != JB_INVALID_SOCKET);
1022 assert(NULL != http->host);
1024 server_connection->sfd = sfd;
1025 server_connection->host = strdup_or_die(http->host);
1026 server_connection->port = http->port;
1028 assert(NULL != fwd);
1029 assert(server_connection->gateway_host == NULL);
1030 assert(server_connection->gateway_port == 0);
1031 assert(server_connection->forwarder_type == 0);
1032 assert(server_connection->forward_host == NULL);
1033 assert(server_connection->forward_port == 0);
1035 server_connection->forwarder_type = fwd->type;
1036 if (NULL != fwd->gateway_host)
1038 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1042 server_connection->gateway_host = NULL;
1044 server_connection->gateway_port = fwd->gateway_port;
1046 if (NULL != fwd->forward_host)
1048 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1052 server_connection->forward_host = NULL;
1054 server_connection->forward_port = fwd->forward_port;
1058 /*********************************************************************
1060 * Function : verify_request_length
1062 * Description : Checks if we already got the whole client requests
1063 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1066 * Data that doesn't belong to the current request is
1067 * thrown away to let the client retry on a clean socket.
1069 * XXX: This is a hack until we can deal with multiple
1070 * pipelined requests at the same time.
1074 * 1 : csp = Current client state (buffers, headers, etc...)
1078 *********************************************************************/
1079 static void verify_request_length(struct client_state *csp)
1081 unsigned long long buffered_request_bytes =
1082 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1084 if ((csp->expected_client_content_length != 0)
1085 && (buffered_request_bytes != 0))
1087 if (csp->expected_client_content_length >= buffered_request_bytes)
1089 csp->expected_client_content_length -= buffered_request_bytes;
1090 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1091 "to account for the %llu ones we already got.",
1092 csp->expected_client_content_length, buffered_request_bytes);
1096 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1097 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1098 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1099 "Marking the server socket tainted after throwing %llu bytes away.",
1100 buffered_request_bytes - csp->expected_client_content_length);
1101 csp->expected_client_content_length = 0;
1102 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1105 if (csp->expected_client_content_length == 0)
1107 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1111 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1112 && ((csp->client_iob->cur[0] != '\0') || (csp->expected_client_content_length != 0)))
1114 if (strcmpic(csp->http->gpc, "GET")
1115 && strcmpic(csp->http->gpc, "HEAD")
1116 && strcmpic(csp->http->gpc, "TRACE")
1117 && strcmpic(csp->http->gpc, "OPTIONS")
1118 && strcmpic(csp->http->gpc, "DELETE"))
1120 /* XXX: this is an incomplete hack */
1121 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1122 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1123 log_error(LOG_LEVEL_CONNECT,
1124 "There might be a request body. The connection will not be kept alive.");
1128 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1130 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1132 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1133 log_error(LOG_LEVEL_CONNECT,
1134 "Possible pipeline attempt detected. The connection will not "
1135 "be kept alive and we will only serve the first request.");
1136 /* Nuke the pipelined requests from orbit, just to be sure. */
1137 csp->client_iob->buf[0] = '\0';
1138 csp->client_iob->eod = csp->client_iob->cur = csp->client_iob->buf;
1143 * Keep the pipelined data around for now, we'll deal with
1144 * it once we're done serving the current request.
1146 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1147 assert(csp->client_iob->eod > csp->client_iob->cur);
1148 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1149 "%d bytes of pipelined data received.",
1150 (int)(csp->client_iob->eod - csp->client_iob->cur));
1156 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1157 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1160 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1163 /*********************************************************************
1165 * Function : mark_server_socket_tainted
1167 * Description : Makes sure we don't reuse a server socket
1168 * (if we didn't read everything the server sent
1169 * us reusing the socket would lead to garbage).
1172 * 1 : csp = Current client state (buffers, headers, etc...)
1176 *********************************************************************/
1177 static void mark_server_socket_tainted(struct client_state *csp)
1180 * For consistency we always mark the server socket
1181 * tainted, however, to reduce the log noise we only
1182 * emit a log message if the server socket could have
1183 * actually been reused.
1185 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1186 && !(csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED))
1188 log_error(LOG_LEVEL_CONNECT,
1189 "Marking the server socket %d tainted.",
1190 csp->server_connection.sfd);
1192 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1195 /*********************************************************************
1197 * Function : get_request_line
1199 * Description : Read the client request line.
1202 * 1 : csp = Current client state (buffers, headers, etc...)
1204 * Returns : Pointer to request line or NULL in case of errors.
1206 *********************************************************************/
1207 static char *get_request_line(struct client_state *csp)
1209 char buf[BUFFER_SIZE];
1210 char *request_line = NULL;
1213 memset(buf, 0, sizeof(buf));
1215 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1218 * If there are multiple pipelined requests waiting,
1219 * the flag will be set again once the next request
1222 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1224 request_line = get_header(csp->client_iob);
1225 if ((NULL != request_line) && ('\0' != *request_line))
1227 return request_line;
1231 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1232 "received yet. Continuing reading from %d.", csp->cfd);
1238 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1240 if (socket_is_still_alive(csp->cfd))
1242 log_error(LOG_LEVEL_CONNECT,
1243 "No request line on socket %d received in time. Timeout: %d.",
1244 csp->cfd, csp->config->socket_timeout);
1245 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1246 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1250 log_error(LOG_LEVEL_CONNECT,
1251 "The client side of the connection on socket %d got "
1252 "closed without sending a complete request line.", csp->cfd);
1257 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1259 if (len <= 0) return NULL;
1262 * If there is no memory left for buffering the
1263 * request, there is nothing we can do but hang up
1265 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1270 request_line = get_header(csp->client_iob);
1272 } while ((NULL != request_line) && ('\0' == *request_line));
1274 return request_line;
1279 /*********************************************************************
1281 * Function : receive_client_request
1283 * Description : Read the client's request (more precisely the
1284 * client headers) and answer it if necessary.
1287 * 1 : csp = Current client state (buffers, headers, etc...)
1289 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1291 *********************************************************************/
1292 static jb_err receive_client_request(struct client_state *csp)
1294 char buf[BUFFER_SIZE];
1297 struct http_request *http;
1301 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1302 struct list header_list;
1303 struct list *headers = &header_list;
1307 memset(buf, 0, sizeof(buf));
1309 req = get_request_line(csp);
1312 mark_server_socket_tainted(csp);
1313 return JB_ERR_PARSE;
1315 assert(*req != '\0');
1317 if (client_protocol_is_unsupported(csp, req))
1319 return JB_ERR_PARSE;
1322 #ifdef FEATURE_FORCE_LOAD
1324 * If this request contains the FORCE_PREFIX and blocks
1325 * aren't enforced, get rid of it and set the force flag.
1327 if (strstr(req, FORCE_PREFIX))
1329 if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1331 log_error(LOG_LEVEL_FORCE,
1332 "Ignored force prefix in request: \"%s\".", req);
1336 strclean(req, FORCE_PREFIX);
1337 log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1338 csp->flags |= CSP_FLAG_FORCED;
1341 #endif /* def FEATURE_FORCE_LOAD */
1343 err = parse_http_request(req, http);
1345 if (JB_ERR_OK != err)
1347 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1348 /* XXX: Use correct size */
1349 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1350 log_error(LOG_LEVEL_ERROR,
1351 "Couldn't parse request line received from %s: %s",
1352 csp->ip_addr_str, jb_err_to_string(err));
1354 free_http_request(http);
1355 return JB_ERR_PARSE;
1358 /* grab the rest of the client's headers */
1362 p = get_header(csp->client_iob);
1366 /* There are no additional headers to read. */
1373 * We didn't receive a complete header
1374 * line yet, get the rest of it.
1376 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1378 log_error(LOG_LEVEL_ERROR,
1379 "Stopped grabbing the client headers.");
1380 destroy_list(headers);
1381 return JB_ERR_PARSE;
1384 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1387 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1388 destroy_list(headers);
1389 return JB_ERR_PARSE;
1392 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1395 * If there is no memory left for buffering the
1396 * request, there is nothing we can do but hang up
1398 destroy_list(headers);
1399 return JB_ERR_MEMORY;
1405 * We were able to read a complete
1406 * header and can finally enlist it.
1413 if (http->host == NULL)
1416 * If we still don't know the request destination,
1417 * the request is invalid or the client uses
1418 * Privoxy without its knowledge.
1420 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1423 * Our attempts to get the request destination
1424 * elsewhere failed or Privoxy is configured
1425 * to only accept proxy requests.
1427 * An error response has already been send
1428 * and we're done here.
1430 return JB_ERR_PARSE;
1435 * Determine the actions for this URL
1437 #ifdef FEATURE_TOGGLE
1438 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1440 /* Most compatible set of actions (i.e. none) */
1441 init_current_action(csp->action);
1444 #endif /* ndef FEATURE_TOGGLE */
1446 get_url_actions(csp, http);
1450 * Save a copy of the original request for logging
1452 http->ocmd = strdup_or_die(http->cmd);
1453 enlist(csp->headers, http->cmd);
1455 /* Append the previously read headers */
1456 list_append_list_unique(csp->headers, headers);
1457 destroy_list(headers);
1464 /*********************************************************************
1466 * Function : parse_client_request
1468 * Description : Parses the client's request and decides what to do
1471 * Note that since we're not using select() we could get
1472 * blocked here if a client connected, then didn't say
1476 * 1 : csp = Current client state (buffers, headers, etc...)
1478 * Returns : JB_ERR_OK or JB_ERR_PARSE
1480 *********************************************************************/
1481 static jb_err parse_client_request(struct client_state *csp)
1483 struct http_request *http = csp->http;
1486 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1487 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1488 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1489 && (csp->http->ssl == 0))
1491 /* Assume persistence until further notice */
1492 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1495 if (csp->http->ssl == 0)
1497 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1498 verify_request_length(csp);
1500 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1502 err = sed(csp, FILTER_CLIENT_HEADERS);
1503 if (JB_ERR_OK != err)
1505 /* XXX: Should be handled in sed(). */
1506 assert(err == JB_ERR_PARSE);
1507 log_error(LOG_LEVEL_FATAL, "Failed to parse client headers.");
1509 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1511 /* Check request line for rewrites. */
1512 if ((NULL == csp->headers->first->str)
1513 || (strcmp(http->cmd, csp->headers->first->str) &&
1514 (JB_ERR_OK != change_request_destination(csp))))
1517 * A header filter broke the request line - bail out.
1519 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1520 /* XXX: Use correct size */
1521 log_error(LOG_LEVEL_CLF,
1522 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1523 log_error(LOG_LEVEL_ERROR,
1524 "Invalid request line after applying header filters.");
1525 free_http_request(http);
1527 return JB_ERR_PARSE;
1535 /*********************************************************************
1539 * Description : Once a connection from the client has been accepted,
1540 * this function is called (via serve()) to handle the
1541 * main business of the communication. This function
1542 * returns after dealing with a single request. It can
1543 * be called multiple times with the same client socket
1544 * if the client is keeping the connection alive.
1546 * The decision whether or not a client connection will
1547 * be kept alive is up to the caller which also must
1548 * close the client socket when done.
1550 * FIXME: chat is nearly thousand lines long.
1554 * 1 : csp = Current client state (buffers, headers, etc...)
1556 * Returns : Nothing.
1558 *********************************************************************/
1559 static void chat(struct client_state *csp)
1561 char buf[BUFFER_SIZE];
1568 int ms_iis5_hack = 0;
1569 unsigned long long byte_count = 0;
1570 const struct forward_spec *fwd;
1571 struct http_request *http;
1572 long len = 0; /* for buffer sizes (and negative error codes) */
1573 int buffer_and_filter_content = 0;
1575 /* Skeleton for HTTP response, if we should intercept the request */
1576 struct http_response *rsp;
1577 struct timeval timeout;
1578 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1579 int watch_client_socket;
1582 memset(buf, 0, sizeof(buf));
1586 if (receive_client_request(csp) != JB_ERR_OK)
1590 if (parse_client_request(csp) != JB_ERR_OK)
1595 /* decide how to route the HTTP request */
1596 fwd = forward_url(csp, http);
1599 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1600 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1605 * build the http request to send to the server
1606 * we have to do one of the following:
1608 * create = use the original HTTP request to create a new
1609 * HTTP request that has either the path component
1610 * without the http://domainspec (w/path) or the
1611 * full orininal URL (w/url)
1612 * Note that the path and/or the HTTP version may
1613 * have been altered by now.
1615 * connect = Open a socket to the host:port of the server
1616 * and short-circuit server and client socket.
1618 * pass = Pass the request unchanged if forwarding a CONNECT
1619 * request to a parent proxy. Note that we'll be sending
1620 * the CFAIL message ourselves if connecting to the parent
1621 * fails, but we won't send a CSUCCEED message if it works,
1622 * since that would result in a double message (ours and the
1623 * parent's). After sending the request to the parent, we simply
1626 * here's the matrix:
1629 * +--------+--------+
1631 * 0 | create | connect|
1633 * Forwarding +--------+--------+
1635 * 1 | create | pass |
1637 * +--------+--------+
1641 if (http->ssl && connect_port_is_forbidden(csp))
1643 const char *acceptable_connect_ports =
1644 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1645 assert(NULL != acceptable_connect_ports);
1646 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1647 "limit-connect{%s} doesn't allow CONNECT requests to %s",
1648 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
1649 csp->action->flags |= ACTION_BLOCK;
1655 freez(csp->headers->first->str);
1656 build_request_line(csp, fwd, &csp->headers->first->str);
1660 * We have a request. Check if one of the crunchers wants it.
1662 if (crunch_response_triggered(csp, crunchers_all))
1665 * Yes. The client got the crunch response and we're done here.
1670 log_applied_actions(csp->action);
1671 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1673 if (fwd->forward_host)
1675 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1676 fwd->forward_host, fwd->forward_port, http->hostport);
1680 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1683 /* here we connect to the server, gateway, or the forwarder */
1685 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1686 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
1687 && socket_is_still_alive(csp->server_connection.sfd)
1688 && connection_destination_matches(&csp->server_connection, http, fwd))
1690 log_error(LOG_LEVEL_CONNECT,
1691 "Reusing server socket %u. Opened for %s.",
1692 csp->server_connection.sfd, csp->server_connection.host);
1696 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
1698 log_error(LOG_LEVEL_CONNECT,
1699 "Closing server socket %u. Opened for %s.",
1700 csp->server_connection.sfd, csp->server_connection.host);
1701 close_socket(csp->server_connection.sfd);
1702 mark_connection_closed(&csp->server_connection);
1704 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1706 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
1708 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
1710 if (fwd->type != SOCKS_NONE)
1713 rsp = error_response(csp, "forwarding-failed");
1715 else if (errno == EINVAL)
1717 rsp = error_response(csp, "no-such-domain");
1721 rsp = error_response(csp, "connect-failed");
1724 /* Write the answer to the client */
1727 send_crunch_response(csp, rsp);
1732 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1733 save_connection_destination(csp->server_connection.sfd,
1734 http, fwd, &csp->server_connection);
1735 csp->server_connection.keep_alive_timeout =
1736 (unsigned)csp->config->keep_alive_timeout;
1738 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1740 if (fwd->forward_host || (http->ssl == 0))
1743 hdr = list_to_text(csp->headers);
1746 /* FIXME Should handle error properly */
1747 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1749 list_remove_all(csp->headers);
1752 * Write the client's (modified) header to the server
1753 * (along with anything else that may be in the buffer)
1755 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
1760 log_error(LOG_LEVEL_CONNECT,
1761 "Failed sending request headers to: %s: %E", http->hostport);
1763 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
1764 && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
1767 log_error(LOG_LEVEL_CONNECT,
1768 "Failed sending request body to: %s: %E", http->hostport);
1773 rsp = error_response(csp, "connect-failed");
1776 send_crunch_response(csp, rsp);
1784 * We're running an SSL tunnel and we're not forwarding,
1785 * so just ditch the client headers, send the "connect succeeded"
1786 * message to the client, flush the rest, and get out of the way.
1788 list_remove_all(csp->headers);
1789 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
1793 IOB_RESET(csp->client_iob);
1796 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
1798 csp->server_connection.request_sent = time(NULL);
1800 maxfd = (csp->cfd > csp->server_connection.sfd) ?
1801 csp->cfd : csp->server_connection.sfd;
1803 /* pass data between the client and server
1804 * until one or the other shuts down the connection.
1809 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
1815 * FD_ZERO here seems to point to an errant macro which crashes.
1816 * So do this by hand for now...
1818 memset(&rfds,0x00,sizeof(fd_set));
1822 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1823 if (!watch_client_socket)
1825 maxfd = csp->server_connection.sfd;
1828 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1830 FD_SET(csp->cfd, &rfds);
1833 FD_SET(csp->server_connection.sfd, &rfds);
1835 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1836 if ((csp->flags & CSP_FLAG_CHUNKED)
1837 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
1838 && ((csp->iob->eod - csp->iob->cur) >= 5)
1839 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
1842 * XXX: This check should be obsolete now,
1843 * but let's wait a while to be sure.
1845 log_error(LOG_LEVEL_CONNECT,
1846 "Looks like we got the last chunk together with "
1847 "the server headers but didn't detect it earlier. "
1848 "We better stop reading.");
1849 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
1850 csp->expected_content_length = byte_count;
1851 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
1853 if (server_body && server_response_is_complete(csp, byte_count))
1855 if (csp->expected_content_length == byte_count)
1857 log_error(LOG_LEVEL_CONNECT,
1858 "Done reading from server. Content length: %llu as expected. "
1859 "Bytes most recently read: %d.",
1864 log_error(LOG_LEVEL_CONNECT,
1865 "Done reading from server. Expected content length: %llu. "
1866 "Actual content length: %llu. Bytes most recently read: %d.",
1867 csp->expected_content_length, byte_count, len);
1871 * XXX: should not jump around,
1872 * chat() is complicated enough already.
1876 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1878 timeout.tv_sec = csp->config->socket_timeout;
1879 timeout.tv_usec = 0;
1880 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
1884 log_error(LOG_LEVEL_ERROR,
1885 "Didn't receive data in time: %s", http->url);
1886 if ((byte_count == 0) && (http->ssl == 0))
1888 send_crunch_response(csp, error_response(csp, "connection-timeout"));
1890 mark_server_socket_tainted(csp);
1895 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1896 mark_server_socket_tainted(csp);
1901 * This is the body of the browser's request,
1902 * just read and write it.
1904 * XXX: Make sure the client doesn't use pipelining
1905 * behind Privoxy's back.
1907 if (FD_ISSET(csp->cfd, &rfds))
1909 int max_bytes_to_read = sizeof(buf) - 1;
1911 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1912 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1914 if (data_is_available(csp->cfd, 0))
1917 * If the next request is already waiting, we have
1918 * to stop select()ing the client socket. Otherwise
1919 * we would always return right away and get nothing
1922 watch_client_socket = 0;
1923 log_error(LOG_LEVEL_CONNECT,
1924 "Stopping to watch the client socket %d. "
1925 "There's already another request waiting.",
1930 * If the client socket is set, but there's no data
1931 * available on the socket, the client went fishing
1932 * and continuing talking to the server makes no sense.
1934 log_error(LOG_LEVEL_CONNECT,
1935 "The client closed socket %d while "
1936 "the server socket %d is still open.",
1937 csp->cfd, csp->server_connection.sfd);
1938 mark_server_socket_tainted(csp);
1941 if (csp->expected_client_content_length != 0)
1943 if (csp->expected_client_content_length < (sizeof(buf) - 1))
1945 max_bytes_to_read = (int)csp->expected_client_content_length;
1947 log_error(LOG_LEVEL_CONNECT,
1948 "Waiting for up to %d bytes from the client.",
1951 assert(max_bytes_to_read < sizeof(buf));
1952 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1954 len = read_socket(csp->cfd, buf, max_bytes_to_read);
1958 /* XXX: not sure if this is necessary. */
1959 mark_server_socket_tainted(csp);
1960 break; /* "game over, man" */
1963 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1964 if (csp->expected_client_content_length != 0)
1966 assert(len <= max_bytes_to_read);
1967 csp->expected_client_content_length -= (unsigned)len;
1968 log_error(LOG_LEVEL_CONNECT,
1969 "Expected client content length set to %llu "
1970 "after reading %d bytes.",
1971 csp->expected_client_content_length, len);
1972 if (csp->expected_client_content_length == 0)
1974 log_error(LOG_LEVEL_CONNECT,
1975 "Done reading from the client.");
1976 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1979 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1981 if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
1983 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1984 mark_server_socket_tainted(csp);
1991 * The server wants to talk. It could be the header or the body.
1992 * If `hdr' is null, then it's the header otherwise it's the body.
1993 * FIXME: Does `hdr' really mean `host'? No.
1995 if (FD_ISSET(csp->server_connection.sfd, &rfds))
1997 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1999 * If we are buffering content, we don't want to eat up to
2000 * buffer-limit bytes if the client no longer cares about them.
2001 * If we aren't buffering, however, a dead client socket will be
2002 * noticed pretty much right away anyway, so we can reduce the
2003 * overhead by skipping the check.
2005 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2008 log_error(LOG_LEVEL_CONNECT,
2009 "The server still wants to talk, but the client may already have hung up on us.");
2011 log_error(LOG_LEVEL_CONNECT,
2012 "The server still wants to talk, but the client hung up on us.");
2013 mark_server_socket_tainted(csp);
2015 #endif /* def _WIN32 */
2017 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2019 len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
2023 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2025 if (http->ssl && (fwd->forward_host == NULL))
2028 * Just hang up. We already confirmed the client's CONNECT
2029 * request with status code 200 and unencrypted content is
2030 * no longer welcome.
2032 log_error(LOG_LEVEL_ERROR,
2033 "CONNECT already confirmed. Unable to tell the client about the problem.");
2036 else if (byte_count)
2039 * Just hang up. We already transmitted the original headers
2040 * and parts of the original content and therefore missed the
2041 * chance to send an error message (without risking data corruption).
2043 * XXX: we could retry with a fancy range request here.
2045 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2046 "Unable to tell the client about the problem.");
2047 mark_server_socket_tainted(csp);
2051 * XXX: Consider handling the cases above the same.
2053 mark_server_socket_tainted(csp);
2057 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2058 if (csp->flags & CSP_FLAG_CHUNKED)
2060 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2062 /* XXX: this is a temporary hack */
2063 log_error(LOG_LEVEL_CONNECT,
2064 "Looks like we reached the end of the last chunk. "
2065 "We better stop reading.");
2066 csp->expected_content_length = byte_count + (unsigned long long)len;
2067 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2071 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2074 * Add a trailing zero to let be able to use string operations.
2075 * XXX: do we still need this with filter_popups gone?
2080 * Normally, this would indicate that we've read
2081 * as much as the server has sent us and we can
2082 * close the client connection. However, Microsoft
2083 * in its wisdom has released IIS/5 with a bug that
2084 * prevents it from sending the trailing \r\n in
2085 * a 302 redirect header (and possibly other headers).
2086 * To work around this if we've haven't parsed
2087 * a full header we'll append a trailing \r\n
2088 * and see if this now generates a valid one.
2090 * This hack shouldn't have any impacts. If we've
2091 * already transmitted the header or if this is a
2092 * SSL connection, then we won't bother with this
2093 * hack. So we only work on partially received
2094 * headers. If we append a \r\n and this still
2095 * doesn't generate a valid header, then we won't
2096 * transmit anything to the client.
2101 if (server_body || http->ssl)
2104 * If we have been buffering up the document,
2105 * now is the time to apply content modification
2106 * and send the result to the client.
2108 if (buffer_and_filter_content)
2110 p = execute_content_filters(csp);
2112 * If content filtering fails, use the original
2113 * buffer and length.
2114 * (see p != NULL ? p : csp->iob->cur below)
2118 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2120 #ifdef FEATURE_COMPRESSION
2121 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2122 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2124 char *compressed_content = compress_buffer(p,
2125 (size_t *)&csp->content_length, csp->config->compression_level);
2126 if (compressed_content != NULL)
2129 p = compressed_content;
2130 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2135 if (JB_ERR_OK != update_server_headers(csp))
2137 log_error(LOG_LEVEL_FATAL,
2138 "Failed to update server headers. after filtering.");
2141 hdr = list_to_text(csp->headers);
2144 /* FIXME Should handle error properly */
2145 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2148 if (write_socket(csp->cfd, hdr, strlen(hdr))
2149 || write_socket(csp->cfd,
2150 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2152 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2155 mark_server_socket_tainted(csp);
2163 break; /* "game over, man" */
2167 * This is NOT the body, so
2168 * Let's pretend the server just sent us a blank line.
2170 snprintf(buf, sizeof(buf), "\r\n");
2171 len = (int)strlen(buf);
2174 * Now, let the normal header parsing algorithm below do its
2175 * job. If it fails, we'll exit instead of continuing.
2182 * If this is an SSL connection or we're in the body
2183 * of the server document, just write it to the client,
2184 * unless we need to buffer the body for later content-filtering
2186 if (server_body || http->ssl)
2188 if (buffer_and_filter_content)
2191 * If there is no memory left for buffering the content, or the buffer limit
2192 * has been reached, switch to non-filtering mode, i.e. make & write the
2193 * header, flush the iob and buf, and get out of the way.
2195 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2200 log_error(LOG_LEVEL_INFO,
2201 "Flushing header and buffers. Stepping back from filtering.");
2203 hdr = list_to_text(csp->headers);
2207 * Memory is too tight to even generate the header.
2208 * Send our static "Out-of-memory" page.
2210 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2211 rsp = cgi_error_memory();
2212 send_crunch_response(csp, rsp);
2213 mark_server_socket_tainted(csp);
2216 hdrlen = strlen(hdr);
2218 if (write_socket(csp->cfd, hdr, hdrlen)
2219 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2220 || (write_socket(csp->cfd, buf, (size_t)len)))
2222 log_error(LOG_LEVEL_CONNECT,
2223 "Flush header and buffers to client failed: %E");
2225 mark_server_socket_tainted(csp);
2230 * Reset the byte_count to the amount of bytes
2231 * we just flushed. len will be added a few lines below,
2232 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2234 byte_count = (unsigned long long)flushed;
2236 buffer_and_filter_content = 0;
2242 if (write_socket(csp->cfd, buf, (size_t)len))
2244 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2245 mark_server_socket_tainted(csp);
2249 byte_count += (unsigned long long)len;
2255 * We're still looking for the end of the server's header.
2256 * Buffer up the data we just read. If that fails, there's
2257 * little we can do but send our static out-of-memory page.
2259 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2261 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2262 rsp = cgi_error_memory();
2263 send_crunch_response(csp, rsp);
2264 mark_server_socket_tainted(csp);
2268 /* Convert iob into something sed() can digest */
2269 if (JB_ERR_PARSE == get_server_headers(csp))
2274 * Well, we tried our MS IIS/5 hack and it didn't work.
2275 * The header is incomplete and there isn't anything
2276 * we can do about it.
2278 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2279 "Applying the MS IIS5 hack didn't help.");
2280 log_error(LOG_LEVEL_CLF,
2281 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2282 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2283 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2284 mark_server_socket_tainted(csp);
2290 * Since we have to wait for more from the server before
2291 * we can parse the headers we just continue here.
2293 log_error(LOG_LEVEL_CONNECT,
2294 "Continuing buffering server headers from socket %d. "
2295 "Bytes most recently read: %d.", csp->cfd, len);
2302 * Account for the content bytes we
2303 * might have gotten with the headers.
2305 assert(csp->iob->eod >= csp->iob->cur);
2306 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2309 /* Did we actually get anything? */
2310 if (NULL == csp->headers->first)
2312 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2314 log_error(LOG_LEVEL_ERROR,
2315 "No server or forwarder response received on socket %d. "
2316 "Closing client socket %d without sending data.",
2317 csp->server_connection.sfd, csp->cfd);
2318 log_error(LOG_LEVEL_CLF,
2319 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2323 log_error(LOG_LEVEL_ERROR,
2324 "No server or forwarder response received on socket %d.",
2325 csp->server_connection.sfd);
2326 send_crunch_response(csp, error_response(csp, "no-server-data"));
2328 free_http_request(http);
2329 mark_server_socket_tainted(csp);
2333 assert(csp->headers->first->str);
2335 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2336 strncmpic(csp->headers->first->str, "ICY", 3))
2339 * It doesn't look like a HTTP (or Shoutcast) response:
2340 * tell the client and log the problem.
2342 if (strlen(csp->headers->first->str) > 30)
2344 csp->headers->first->str[30] = '\0';
2346 log_error(LOG_LEVEL_ERROR,
2347 "Invalid server or forwarder response. Starts with: %s",
2348 csp->headers->first->str);
2349 log_error(LOG_LEVEL_CLF,
2350 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2351 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2352 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2353 free_http_request(http);
2354 mark_server_socket_tainted(csp);
2359 * We have now received the entire server header,
2360 * filter it and send the result to the client
2362 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2364 log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2366 hdr = list_to_text(csp->headers);
2369 /* FIXME Should handle error properly */
2370 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2373 if ((csp->flags & CSP_FLAG_CHUNKED)
2374 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2375 && ((csp->iob->eod - csp->iob->cur) >= 5)
2376 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2378 log_error(LOG_LEVEL_CONNECT,
2379 "Looks like we got the last chunk together with "
2380 "the server headers. We better stop reading.");
2381 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2382 csp->expected_content_length = byte_count;
2383 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2386 csp->server_connection.response_received = time(NULL);
2388 if (crunch_response_triggered(csp, crunchers_light))
2391 * One of the tags created by a server-header
2392 * tagger triggered a crunch. We already
2393 * delivered the crunch response to the client
2394 * and are done here after cleaning up.
2397 mark_server_socket_tainted(csp);
2400 /* Buffer and pcrs filter this if appropriate. */
2402 if (!http->ssl) /* We talk plaintext */
2404 buffer_and_filter_content = content_requires_filtering(csp);
2407 * Only write if we're not buffering for content modification
2409 if (!buffer_and_filter_content)
2412 * Write the server's (modified) header to
2413 * the client (along with anything else that
2414 * may be in the buffer)
2417 if (write_socket(csp->cfd, hdr, strlen(hdr))
2418 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2420 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2423 * The write failed, so don't bother mentioning it
2424 * to the client... it probably can't hear us anyway.
2427 mark_server_socket_tainted(csp);
2432 /* we're finished with the server's header */
2438 * If this was a MS IIS/5 hack then it means the server
2439 * has already closed the connection. Nothing more to read.
2444 log_error(LOG_LEVEL_ERROR,
2445 "Closed server connection detected. "
2446 "Applying the MS IIS5 hack didn't help.");
2447 log_error(LOG_LEVEL_CLF,
2448 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2449 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2450 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2451 mark_server_socket_tainted(csp);
2457 mark_server_socket_tainted(csp);
2458 return; /* huh? we should never get here */
2461 if (csp->content_length == 0)
2464 * If Privoxy didn't recalculate the Content-Length,
2465 * byte_count is still correct.
2467 csp->content_length = byte_count;
2470 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2471 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2472 && (csp->expected_content_length != byte_count))
2474 log_error(LOG_LEVEL_CONNECT,
2475 "Received %llu bytes while expecting %llu.",
2476 byte_count, csp->expected_content_length);
2477 mark_server_socket_tainted(csp);
2481 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2482 csp->ip_addr_str, http->ocmd, csp->content_length);
2484 csp->server_connection.timestamp = time(NULL);
2488 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2489 /*********************************************************************
2491 * Function : prepare_csp_for_next_request
2493 * Description : Put the csp in a mostly vergin state.
2496 * 1 : csp = Current client state (buffers, headers, etc...)
2500 *********************************************************************/
2501 static void prepare_csp_for_next_request(struct client_state *csp)
2503 unsigned int toggled_on_flag_set = (0 != (csp->flags & CSP_FLAG_TOGGLED_ON));
2505 csp->content_type = 0;
2506 csp->content_length = 0;
2507 csp->expected_content_length = 0;
2508 csp->expected_client_content_length = 0;
2509 list_remove_all(csp->headers);
2510 IOB_RESET(csp->iob);
2511 freez(csp->error_message);
2512 free_http_request(csp->http);
2513 destroy_list(csp->headers);
2514 destroy_list(csp->tags);
2515 free_current_action(csp->action);
2516 if (NULL != csp->fwd)
2518 unload_forward_spec(csp->fwd);
2521 /* XXX: Store per-connection flags someplace else. */
2522 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
2523 if (toggled_on_flag_set)
2525 csp->flags |= CSP_FLAG_TOGGLED_ON;
2528 if (csp->client_iob->eod > csp->client_iob->cur)
2530 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
2531 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2533 assert(bytes_to_shift > 0);
2534 assert(data_length > 0);
2536 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
2537 data_length, bytes_to_shift);
2538 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
2539 csp->client_iob->cur = csp->client_iob->buf;
2540 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
2541 csp->client_iob->eod = csp->client_iob->buf + data_length;
2542 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
2544 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
2549 * We mainly care about resetting client_iob->cur so we don't
2550 * waste buffer space at the beginning and don't mess up the
2551 * request restoration done by cgi_show_request().
2553 * Freeing the buffer itself isn't technically necessary,
2554 * but makes debugging more convenient.
2556 IOB_RESET(csp->client_iob);
2559 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2562 /*********************************************************************
2566 * Description : This is little more than chat. We only "serve" to
2567 * to close (or remember) any socket that chat may have
2571 * 1 : csp = Current client state (buffers, headers, etc...)
2575 *********************************************************************/
2577 void serve(struct client_state *csp)
2578 #else /* ifndef AMIGA */
2579 static void serve(struct client_state *csp)
2580 #endif /* def AMIGA */
2582 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2583 #ifdef FEATURE_CONNECTION_SHARING
2584 static int monitor_thread_running = 0;
2585 #endif /* def FEATURE_CONNECTION_SHARING */
2586 int continue_chatting = 0;
2587 int config_file_change_detected = 0; /* Only used for debugging */
2589 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
2590 csp->ip_addr_str, csp->cfd);
2594 unsigned int latency;
2599 * If the request has been crunched,
2600 * the calculated latency is zero.
2602 latency = (unsigned)(csp->server_connection.response_received -
2603 csp->server_connection.request_sent) / 2;
2605 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2606 && (csp->flags & CSP_FLAG_CRUNCHED)
2607 && (csp->expected_client_content_length != 0))
2609 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
2610 log_error(LOG_LEVEL_CONNECT,
2611 "Tainting client socket %d due to unread data.", csp->cfd);
2614 continue_chatting = (csp->config->feature_flags
2615 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2616 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2617 && (csp->cfd != JB_INVALID_SOCKET)
2618 && ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2619 || (csp->config->feature_flags &
2620 RUNTIME_FEATURE_CONNECTION_SHARING));
2622 if (!(csp->flags & CSP_FLAG_CRUNCHED)
2623 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
2625 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
2627 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
2629 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2630 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2631 || !socket_is_still_alive(csp->server_connection.sfd)
2632 || !(latency < csp->server_connection.keep_alive_timeout))
2634 log_error(LOG_LEVEL_CONNECT,
2635 "Closing connection on server socket %d to %s: "
2636 "keep-alive %u, tainted: %u, socket alive %u. %s timeout: %u.",
2637 csp->server_connection.sfd, csp->server_connection.host,
2638 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2639 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2640 socket_is_still_alive(csp->server_connection.sfd),
2641 ((csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET) ?
2642 "Specified" : "Assumed"), csp->server_connection.keep_alive_timeout);
2643 #ifdef FEATURE_CONNECTION_SHARING
2644 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2646 forget_connection(csp->server_connection.sfd);
2648 #endif /* def FEATURE_CONNECTION_SHARING */
2649 close_socket(csp->server_connection.sfd);
2650 mark_connection_closed(&csp->server_connection);
2654 if (continue_chatting && any_loaded_file_changed(csp->config->config_file_list))
2656 continue_chatting = 0;
2657 config_file_change_detected = 1;
2660 if (continue_chatting)
2662 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
2663 && socket_is_still_alive(csp->cfd))
2665 log_error(LOG_LEVEL_CONNECT, "A client request has been "
2666 "pipelined on socket %d and the socket is still alive.",
2668 prepare_csp_for_next_request(csp);
2672 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
2674 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2676 log_error(LOG_LEVEL_CONNECT,
2677 "Waiting for the next client request on socket %d. "
2678 "Keeping the server socket %d to %s open.",
2679 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2683 log_error(LOG_LEVEL_CONNECT,
2684 "Waiting for the next client request on socket %d. "
2685 "No server socket to keep open.", csp->cfd);
2689 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2690 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
2691 && socket_is_still_alive(csp->cfd))
2693 log_error(LOG_LEVEL_CONNECT,
2694 "Client request arrived in time on socket %d.", csp->cfd);
2695 prepare_csp_for_next_request(csp);
2699 #ifdef FEATURE_CONNECTION_SHARING
2700 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2701 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
2702 && (socket_is_still_alive(csp->server_connection.sfd)))
2704 time_t time_open = time(NULL) - csp->server_connection.timestamp;
2706 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
2711 remember_connection(&csp->server_connection);
2712 csp->server_connection.sfd = JB_INVALID_SOCKET;
2713 drain_and_close_socket(csp->cfd);
2714 csp->cfd = JB_INVALID_SOCKET;
2715 privoxy_mutex_lock(&connection_reuse_mutex);
2716 if (!monitor_thread_running)
2718 monitor_thread_running = 1;
2719 privoxy_mutex_unlock(&connection_reuse_mutex);
2720 wait_for_alive_connections();
2721 privoxy_mutex_lock(&connection_reuse_mutex);
2722 monitor_thread_running = 0;
2724 privoxy_mutex_unlock(&connection_reuse_mutex);
2726 #endif /* def FEATURE_CONNECTION_SHARING */
2730 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2732 log_error(LOG_LEVEL_CONNECT,
2733 "Closing server socket %d connected to %s. Keep-alive %u. "
2734 "Tainted: %u. Socket alive %u. Timeout: %u. "
2735 "Configuration file change detected: %u",
2736 csp->server_connection.sfd, csp->server_connection.host,
2737 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2738 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2739 socket_is_still_alive(csp->server_connection.sfd),
2740 csp->server_connection.keep_alive_timeout,
2741 config_file_change_detected);
2743 } while (continue_chatting);
2747 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2749 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2751 #ifdef FEATURE_CONNECTION_SHARING
2752 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2754 forget_connection(csp->server_connection.sfd);
2756 #endif /* def FEATURE_CONNECTION_SHARING */
2757 close_socket(csp->server_connection.sfd);
2760 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2761 mark_connection_closed(&csp->server_connection);
2764 if (csp->cfd != JB_INVALID_SOCKET)
2766 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
2767 "Keep-alive: %u, Socket alive: %u. Data available: %u. "
2768 "Configuration file change detected: %u.",
2769 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
2770 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
2771 config_file_change_detected);
2772 drain_and_close_socket(csp->cfd);
2775 csp->flags &= ~CSP_FLAG_ACTIVE;
2781 /*********************************************************************
2783 * Function : server_thread
2785 * Description : We only exist to call `serve' in a threaded environment.
2788 * 1 : data = Current client state (buffers, headers, etc...)
2790 * Returns : Always 0.
2792 *********************************************************************/
2793 static int32 server_thread(void *data)
2795 serve((struct client_state *) data);
2802 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2803 /*********************************************************************
2807 * Description : Print usage info & exit.
2809 * Parameters : Pointer to argv[0] for identifying ourselves
2813 *********************************************************************/
2814 static void usage(const char *myname)
2816 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
2820 #endif /* defined(unix) */
2823 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
2824 #endif /* defined(unix) */
2825 "[--version] [configfile]\n"
2826 "Aborting\n", myname);
2831 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
2834 #ifdef MUTEX_LOCKS_AVAILABLE
2835 /*********************************************************************
2837 * Function : privoxy_mutex_lock
2839 * Description : Locks a mutex.
2842 * 1 : mutex = The mutex to lock.
2844 * Returns : Void. May exit in case of errors.
2846 *********************************************************************/
2847 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
2849 #ifdef FEATURE_PTHREAD
2850 int err = pthread_mutex_lock(mutex);
2853 if (mutex != &log_mutex)
2855 log_error(LOG_LEVEL_FATAL,
2856 "Mutex locking failed: %s.\n", strerror(err));
2861 EnterCriticalSection(mutex);
2862 #endif /* def FEATURE_PTHREAD */
2866 /*********************************************************************
2868 * Function : privoxy_mutex_unlock
2870 * Description : Unlocks a mutex.
2873 * 1 : mutex = The mutex to unlock.
2875 * Returns : Void. May exit in case of errors.
2877 *********************************************************************/
2878 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
2880 #ifdef FEATURE_PTHREAD
2881 int err = pthread_mutex_unlock(mutex);
2884 if (mutex != &log_mutex)
2886 log_error(LOG_LEVEL_FATAL,
2887 "Mutex unlocking failed: %s.\n", strerror(err));
2892 LeaveCriticalSection(mutex);
2893 #endif /* def FEATURE_PTHREAD */
2897 /*********************************************************************
2899 * Function : privoxy_mutex_init
2901 * Description : Prepares a mutex.
2904 * 1 : mutex = The mutex to initialize.
2906 * Returns : Void. May exit in case of errors.
2908 *********************************************************************/
2909 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
2911 #ifdef FEATURE_PTHREAD
2912 int err = pthread_mutex_init(mutex, 0);
2915 printf("Fatal error. Mutex initialization failed: %s.\n",
2920 InitializeCriticalSection(mutex);
2921 #endif /* def FEATURE_PTHREAD */
2923 #endif /* def MUTEX_LOCKS_AVAILABLE */
2925 /*********************************************************************
2927 * Function : initialize_mutexes
2929 * Description : Prepares mutexes if mutex support is available.
2933 * Returns : Void, exits in case of errors.
2935 *********************************************************************/
2936 static void initialize_mutexes(void)
2938 #ifdef MUTEX_LOCKS_AVAILABLE
2940 * Prepare global mutex semaphores
2942 privoxy_mutex_init(&log_mutex);
2943 privoxy_mutex_init(&log_init_mutex);
2944 privoxy_mutex_init(&connection_reuse_mutex);
2947 * XXX: The assumptions below are a bit naive
2948 * and can cause locks that aren't necessary.
2950 * For example older FreeBSD versions (< 6.x?)
2951 * have no gethostbyname_r, but gethostbyname is
2954 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
2955 privoxy_mutex_init(&resolver_mutex);
2956 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
2958 * XXX: should we use a single mutex for
2959 * localtime() and gmtime() as well?
2961 #ifndef HAVE_GMTIME_R
2962 privoxy_mutex_init(&gmtime_mutex);
2963 #endif /* ndef HAVE_GMTIME_R */
2965 #ifndef HAVE_LOCALTIME_R
2966 privoxy_mutex_init(&localtime_mutex);
2967 #endif /* ndef HAVE_GMTIME_R */
2970 privoxy_mutex_init(&rand_mutex);
2971 #endif /* ndef HAVE_RANDOM */
2973 #endif /* def MUTEX_LOCKS_AVAILABLE */
2977 /*********************************************************************
2981 * Description : Load the config file and start the listen loop.
2982 * This function is a lot more *sane* with the `load_config'
2983 * and `listen_loop' functions; although it stills does
2984 * a *little* too much for my taste.
2987 * 1 : argc = Number of parameters (including $0).
2988 * 2 : argv = Array of (char *)'s to the parameters.
2990 * Returns : 1 if : can't open config file, unrecognized directive,
2991 * stats requested in multi-thread mode, can't open the
2992 * log file, can't open the jar file, listen port is invalid,
2993 * any load fails, and can't bind port.
2995 * Else main never returns, the process must be signaled
2996 * to terminate execution. Or, on Windows, use the
2997 * "File", "Exit" menu option.
2999 *********************************************************************/
3001 int real_main(int argc, char **argv)
3003 int main(int argc, char **argv)
3007 unsigned int random_seed;
3009 struct passwd *pw = NULL;
3010 struct group *grp = NULL;
3012 char *pre_chroot_nslookup_to_load_resolver = NULL;
3019 #if !defined(_WIN32)
3026 /* Prepare mutexes if supported and necessary. */
3027 initialize_mutexes();
3029 /* Enable logging until further notice. */
3033 * Parse the command line arguments
3035 * XXX: simply printing usage information in case of
3036 * invalid arguments isn't particularly user friendly.
3038 while (++argc_pos < argc)
3041 /* Check to see if the service must be installed or uninstalled */
3042 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3044 const char *pName = argv[argc_pos] + 9;
3047 exit((install_service(pName)) ? 0 : 1);
3049 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3051 const char *pName = argv[argc_pos] + 11;
3054 exit((uninstall_service(pName)) ? 0 : 1);
3056 else if (strcmp(argv[argc_pos], "--service") == 0)
3058 bRunAsService = TRUE;
3059 w32_set_service_cwd();
3060 atexit(w32_service_exit_notify);
3063 #endif /* defined(_WIN32) */
3066 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3068 if (strcmp(argv[argc_pos], "--help") == 0)
3073 else if (strcmp(argv[argc_pos], "--version") == 0)
3075 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3081 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3083 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3087 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3089 if (++argc_pos == argc) usage(argv[0]);
3090 pidfile = strdup_or_die(argv[argc_pos]);
3093 else if (strcmp(argv[argc_pos], "--user") == 0)
3098 if (++argc_pos == argc) usage(argv[argc_pos]);
3100 user_arg = strdup_or_die(argv[argc_pos]);
3101 group_name = strchr(user_arg, '.');
3102 if (NULL != group_name)
3104 /* Nul-terminate the user name */
3107 /* Skip the former delimiter to actually reach the group name */
3110 grp = getgrnam(group_name);
3113 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3116 pw = getpwnam(user_arg);
3119 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3125 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3127 if (++argc_pos == argc) usage(argv[0]);
3128 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3131 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3135 #endif /* defined(unix) */
3137 else if (argc_pos + 1 != argc)
3140 * This is neither the last command line
3141 * option, nor was it recognized before,
3142 * therefore it must be invalid.
3148 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3150 configfile = argv[argc_pos];
3153 } /* -END- while (more arguments) */
3155 show_version(Argv[0]);
3158 if (*configfile != '/')
3160 char cwd[BUFFER_SIZE];
3162 size_t abs_file_size;
3164 /* make config-filename absolute here */
3165 if (NULL == getcwd(cwd, sizeof(cwd)))
3167 perror("failed to get current working directory");
3171 basedir = strdup_or_die(cwd);
3173 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3174 abs_file = malloc_or_die(abs_file_size);
3175 strlcpy(abs_file, basedir, abs_file_size);
3176 strlcat(abs_file, "/", abs_file_size);
3177 strlcat(abs_file, configfile, abs_file_size);
3178 configfile = abs_file;
3180 #endif /* defined unix */
3184 clients->next = NULL;
3186 /* XXX: factor out initialising after the next stable release. */
3189 #elif defined(_WIN32)
3193 random_seed = (unsigned int)time(NULL);
3195 srandom(random_seed);
3198 #endif /* ifdef HAVE_RANDOM */
3201 * Unix signal handling
3203 * Catch the abort, interrupt and terminate signals for a graceful exit
3204 * Catch the hangup signal so the errlog can be reopened.
3205 * Ignore the broken pipe signals (FIXME: Why?)
3207 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3210 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3212 for (idx = 0; idx < SZ(catched_signals); idx++)
3214 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3215 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3217 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3218 #endif /* ifdef sun */
3220 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3224 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3226 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3230 #else /* ifdef _WIN32 */
3231 # ifdef _WIN_CONSOLE
3233 * We *are* in a windows console app.
3234 * Print a verbose messages about FAQ's and such
3236 printf("%s", win32_blurb);
3237 # endif /* def _WIN_CONSOLE */
3238 #endif /* def _WIN32 */
3241 /* Initialize the CGI subsystem */
3242 cgi_init_error_messages();
3245 * If runnig on unix and without the --nodaemon
3246 * option, become a daemon. I.e. fork, detach
3247 * from tty and get process group leadership
3256 if (pid < 0) /* error */
3261 else if (pid != 0) /* parent */
3266 * must check for errors
3267 * child died due to missing files aso
3270 wpid = waitpid(pid, &status, WNOHANG);
3282 * stderr (fd 2) will be closed later on,
3283 * when the config file has been parsed.
3289 * Reserve fd 0 and 1 to prevent abort() and friends
3290 * from sending stuff to the clients or servers.
3292 fd = open("/dev/null", O_RDONLY);
3295 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3299 if (dup2(fd, 0) == -1)
3301 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3305 fd = open("/dev/null", O_WRONLY);
3308 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3312 if (dup2(fd, 1) == -1)
3314 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3321 } /* -END- if (daemon_mode) */
3324 * As soon as we have written the PID file, we can switch
3325 * to the user and group ID indicated by the --user option
3331 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3333 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3337 if (setgroups(1, &grp->gr_gid))
3339 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3342 else if (initgroups(pw->pw_name, pw->pw_gid))
3344 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3350 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3352 /* Read the time zone file from /etc before doing chroot. */
3354 if (NULL != pre_chroot_nslookup_to_load_resolver
3355 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3357 /* Initialize resolver library. */
3358 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3360 if (chroot(pw->pw_dir) < 0)
3362 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3366 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3369 if (setuid(pw->pw_uid))
3371 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3375 char putenv_dummy[64];
3377 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3378 if (putenv(putenv_dummy) != 0)
3380 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3383 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3384 if (putenv(putenv_dummy) != 0)
3386 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3392 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3395 #endif /* defined unix */
3398 /* This will be FALSE unless the command line specified --service
3402 /* Yup, so now we must attempt to establish a connection
3403 * with the service dispatcher. This will only work if this
3404 * process was launched by the service control manager to
3405 * actually run as a service. If this isn't the case, i've
3406 * known it take around 30 seconds or so for the call to return.
3409 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3410 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3412 /* Service has run, and at this point is now being stopped, so just return */
3417 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3419 /* An error occurred. Usually it's because --service was wrongly specified
3420 * and we were unable to connect to the Service Control Dispatcher because
3421 * it wasn't expecting us and is therefore not listening.
3423 * For now, just continue below to call the listen_loop function.
3426 #endif /* def _WIN32 */
3436 /*********************************************************************
3438 * Function : bind_port_helper
3440 * Description : Bind the listen port. Handles logging, and aborts
3444 * 1 : haddr = Host addres to bind to. Use NULL to bind to
3446 * 2 : hport = Specifies port to bind to.
3448 * Returns : Port that was opened.
3450 *********************************************************************/
3451 static jb_socket bind_port_helper(const char *haddr, int hport)
3456 result = bind_port(haddr, hport, &bfd);
3460 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
3464 log_error(LOG_LEVEL_FATAL,
3465 "can't bind to %s:%d: There may be another Privoxy "
3466 "or some other proxy running on port %d",
3467 bind_address, hport, hport);
3470 log_error(LOG_LEVEL_FATAL,
3471 "can't bind to %s:%d: The hostname is not resolvable",
3472 bind_address, hport);
3475 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3476 bind_address, hport);
3479 /* shouldn't get here */
3480 return JB_INVALID_SOCKET;
3485 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3490 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3498 /*********************************************************************
3500 * Function : bind_ports_helper
3502 * Description : Bind the listen ports. Handles logging, and aborts
3506 * 1 : config = Privoxy configuration. Specifies ports
3508 * 2 : sockets = Preallocated array of opened sockets
3509 * corresponding to specification in config.
3510 * All non-opened sockets will be set to
3511 * JB_INVALID_SOCKET.
3513 * Returns : Nothing. Inspect sockets argument.
3515 *********************************************************************/
3516 static void bind_ports_helper(struct configuration_spec * config,
3517 jb_socket sockets[])
3521 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3523 if (config->hport[i])
3525 sockets[i] = bind_port_helper(config->haddr[i], config->hport[i]);
3529 sockets[i] = JB_INVALID_SOCKET;
3532 config->need_bind = 0;
3536 /*********************************************************************
3538 * Function : close_ports_helper
3540 * Description : Close listenings ports.
3543 * 1 : sockets = Array of opened and non-opened sockets to
3544 * close. All sockets will be set to
3545 * JB_INVALID_SOCKET.
3547 * Returns : Nothing.
3549 *********************************************************************/
3550 static void close_ports_helper(jb_socket sockets[])
3554 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3556 if (JB_INVALID_SOCKET != sockets[i])
3558 close_socket(sockets[i]);
3560 sockets[i] = JB_INVALID_SOCKET;
3566 /* Without this simple workaround we get this compiler warning from _beginthread
3567 * warning C4028: formal parameter 1 different from declaration
3569 void w32_service_listen_loop(void *p)
3573 #endif /* def _WIN32 */
3576 /*********************************************************************
3578 * Function : listen_loop
3580 * Description : bind the listen port and enter a "FOREVER" listening loop.
3586 *********************************************************************/
3587 static void listen_loop(void)
3589 struct client_states *csp_list = NULL;
3590 struct client_state *csp = NULL;
3591 jb_socket bfds[MAX_LISTENING_SOCKETS];
3592 struct configuration_spec *config;
3593 unsigned int active_threads = 0;
3595 config = load_config();
3597 #ifdef FEATURE_CONNECTION_SHARING
3599 * XXX: Should be relocated once it no
3600 * longer needs to emit log messages.
3602 initialize_reusable_connections();
3603 #endif /* def FEATURE_CONNECTION_SHARING */
3605 bind_ports_helper(config, bfds);
3607 #ifdef FEATURE_GRACEFUL_TERMINATION
3608 while (!g_terminate)
3613 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3614 while (waitpid(-1, NULL, WNOHANG) > 0)
3616 /* zombie children */
3618 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3621 * Free data that was used by died threads
3623 active_threads = sweep();
3627 * Re-open the errlog after HUP signal
3629 if (received_hup_signal)
3631 if (NULL != config->logfile)
3633 init_error_log(Argv[0], config->logfile);
3635 received_hup_signal = 0;
3639 csp_list = (struct client_states *)zalloc(sizeof(*csp_list));
3640 if (NULL == csp_list)
3642 log_error(LOG_LEVEL_FATAL,
3643 "malloc(%d) for csp_list failed: %E", sizeof(*csp_list));
3646 csp = &csp_list->csp;
3648 log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
3650 if (!accept_connection(csp, bfds))
3652 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3664 csp->flags |= CSP_FLAG_ACTIVE;
3665 csp->server_connection.sfd = JB_INVALID_SOCKET;
3667 csp->config = config = load_config();
3669 if (config->need_bind)
3672 * Since we were listening to the "old port", we will not see
3673 * a "listen" param change until the next request. So, at
3674 * least 1 more request must be made for us to find the new
3675 * setting. I am simply closing the old socket and binding the
3678 * Which-ever is correct, we will serve 1 more page via the
3679 * old settings. This should probably be a "show-proxy-args"
3680 * request. This should not be a so common of an operation
3681 * that this will hurt people's feelings.
3684 close_ports_helper(bfds);
3686 bind_ports_helper(config, bfds);
3689 #ifdef FEATURE_TOGGLE
3690 if (global_toggle_state)
3691 #endif /* def FEATURE_TOGGLE */
3693 csp->flags |= CSP_FLAG_TOGGLED_ON;
3696 if (run_loader(csp))
3698 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3699 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3703 if (block_acl(NULL,csp))
3705 log_error(LOG_LEVEL_CONNECT,
3706 "Connection from %s on socket %d dropped due to ACL", csp->ip_addr_str, csp->cfd);
3707 close_socket(csp->cfd);
3708 freez(csp->ip_addr_str);
3712 #endif /* def FEATURE_ACL */
3714 if ((0 != config->max_client_connections)
3715 && (active_threads >= config->max_client_connections))
3717 log_error(LOG_LEVEL_CONNECT,
3718 "Rejecting connection from %s. Maximum number of connections reached.",
3720 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3721 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3722 close_socket(csp->cfd);
3723 freez(csp->ip_addr_str);
3728 /* add it to the list of clients */
3729 csp_list->next = clients->next;
3730 clients->next = csp_list;
3732 if (config->multi_threaded)
3736 /* this is a switch () statement in the C preprocessor - ugh */
3737 #undef SELECTED_ONE_OPTION
3739 /* Use Pthreads in preference to native code */
3740 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
3741 #define SELECTED_ONE_OPTION
3743 pthread_t the_thread;
3744 pthread_attr_t attrs;
3746 pthread_attr_init(&attrs);
3747 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
3748 errno = pthread_create(&the_thread, &attrs,
3749 (void * (*)(void *))serve, csp);
3750 child_id = errno ? -1 : 0;
3751 pthread_attr_destroy(&attrs);
3755 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
3756 #define SELECTED_ONE_OPTION
3757 child_id = _beginthread(
3758 (void (*)(void *))serve,
3763 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
3764 #define SELECTED_ONE_OPTION
3765 child_id = _beginthread(
3766 (void(* _Optlink)(void*))serve,
3772 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
3773 #define SELECTED_ONE_OPTION
3775 thread_id tid = spawn_thread
3776 (server_thread, "server", B_NORMAL_PRIORITY, csp);
3778 if ((tid >= 0) && (resume_thread(tid) == B_OK))
3780 child_id = (int) tid;
3789 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
3790 #define SELECTED_ONE_OPTION
3791 csp->cfd = ReleaseSocket(csp->cfd, -1);
3794 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3795 NP_Output, Output(),
3796 NP_CloseOutput, FALSE,
3797 NP_Name, (ULONG)"privoxy child",
3801 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3802 NP_Output, Output(),
3803 NP_CloseOutput, FALSE,
3804 NP_Name, (ULONG)"privoxy child",
3805 NP_StackSize, 200*1024,
3811 ((struct Task *)child_id)->tc_UserData = csp;
3812 Signal((struct Task *)child_id, SIGF_SINGLE);
3817 #if !defined(SELECTED_ONE_OPTION)
3820 /* This block is only needed when using fork().
3821 * When using threads, the server thread was
3822 * created and run by the call to _beginthread().
3824 if (child_id == 0) /* child */
3827 #ifdef FEATURE_TOGGLE
3828 int inherited_toggle_state = global_toggle_state;
3829 #endif /* def FEATURE_TOGGLE */
3834 * If we've been toggled or we've blocked the request, tell Mom
3837 #ifdef FEATURE_TOGGLE
3838 if (inherited_toggle_state != global_toggle_state)
3840 rc |= RC_FLAG_TOGGLED;
3842 #endif /* def FEATURE_TOGGLE */
3844 #ifdef FEATURE_STATISTICS
3845 if (csp->flags & CSP_FLAG_REJECTED)
3847 rc |= RC_FLAG_BLOCKED;
3849 #endif /* ndef FEATURE_STATISTICS */
3853 else if (child_id > 0) /* parent */
3855 /* in a fork()'d environment, the parent's
3856 * copy of the client socket and the CSP
3860 #if !defined(_WIN32) && !defined(__CYGWIN__)
3862 wait(&child_status);
3865 * Evaluate child's return code: If the child has
3866 * - been toggled, toggle ourselves
3867 * - blocked its request, bump up the stats counter
3870 #ifdef FEATURE_TOGGLE
3871 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
3873 global_toggle_state = !global_toggle_state;
3875 #endif /* def FEATURE_TOGGLE */
3877 #ifdef FEATURE_STATISTICS
3879 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
3883 #endif /* def FEATURE_STATISTICS */
3885 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
3886 close_socket(csp->cfd);
3887 csp->flags &= ~CSP_FLAG_ACTIVE;
3891 #undef SELECTED_ONE_OPTION
3892 /* end of cpp switch () */
3897 * Spawning the child failed, assume it's because
3898 * there are too many children running already.
3899 * XXX: If you assume ...
3901 log_error(LOG_LEVEL_ERROR,
3902 "Unable to take any additional connections: %E");
3903 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3904 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3905 close_socket(csp->cfd);
3906 csp->flags &= ~CSP_FLAG_ACTIVE;
3915 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
3917 /* Clean up. Aim: free all memory (no leaks) */
3918 #ifdef FEATURE_GRACEFUL_TERMINATION
3920 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
3922 unload_current_config_file();
3923 unload_current_actions_file();
3924 unload_current_re_filterfile();
3925 #ifdef FEATURE_TRUST
3926 unload_current_trust_file();
3929 if (config->multi_threaded)
3936 } while ((clients->next != NULL) && (--i > 0));
3940 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
3950 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
3951 /* Cleanup - remove taskbar icon etc. */
3956 #endif /* FEATURE_GRACEFUL_TERMINATION */