1 const char jcc_rcs[] = "$Id: jcc.c,v 1.371 2011/10/23 11:24:33 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001-2010 the
10 * Privoxy team. http://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 *********************************************************************/
40 #include <sys/types.h>
49 # ifndef FEATURE_PTHREAD
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
65 # if !defined (__OS2__)
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
74 #include <sys/termios.h>
85 # include <socket.h> /* BeOS has select() for sockets only. */
86 # include <OS.h> /* declarations for threads and stuff. */
89 # if defined(__EMX__) || defined(__OS2__)
90 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
95 #define bzero(B,N) memset(B,0x00,n)
110 #include "miscutil.h"
112 #include "jbsockets.h"
117 #include "urlmatch.h"
119 const char jcc_h_rcs[] = JCC_H_VERSION;
120 const char project_h_rcs[] = PROJECT_H_VERSION;
123 struct client_states clients[1];
124 struct file_list files[1];
126 #ifdef FEATURE_STATISTICS
127 int urls_read = 0; /* total nr of urls read inc rejected */
128 int urls_rejected = 0; /* total nr of urls rejected */
129 #endif /* def FEATURE_STATISTICS */
131 #ifdef FEATURE_GRACEFUL_TERMINATION
135 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
136 static void sig_handler(int the_signal);
138 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
139 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
140 static jb_err get_server_headers(struct client_state *csp);
141 static const char *crunch_reason(const struct http_response *rsp);
142 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
143 static char *get_request_line(struct client_state *csp);
144 static jb_err receive_client_request(struct client_state *csp);
145 static jb_err parse_client_request(struct client_state *csp);
146 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
147 static jb_err change_request_destination(struct client_state *csp);
148 static void chat(struct client_state *csp);
149 static void serve(struct client_state *csp);
150 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
151 static void usage(const char *myname);
153 static void initialize_mutexes(void);
154 static jb_socket bind_port_helper(const char *haddr, int hport);
155 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
156 static void close_ports_helper(jb_socket sockets[]);
157 static void listen_loop(void);
160 void serve(struct client_state *csp);
161 #else /* ifndef AMIGA */
162 static void serve(struct client_state *csp);
163 #endif /* def AMIGA */
166 static int32 server_thread(void *data);
167 #endif /* def __BEOS__ */
170 #define sleep(N) Sleep(((N) * 1000))
174 #define sleep(N) DosSleep(((N) * 100))
177 #ifdef MUTEX_LOCKS_AVAILABLE
179 * XXX: Does the locking stuff really belong in this file?
181 privoxy_mutex_t log_mutex;
182 privoxy_mutex_t log_init_mutex;
183 privoxy_mutex_t connection_reuse_mutex;
185 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
186 privoxy_mutex_t resolver_mutex;
187 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
189 #ifndef HAVE_GMTIME_R
190 privoxy_mutex_t gmtime_mutex;
191 #endif /* ndef HAVE_GMTIME_R */
193 #ifndef HAVE_LOCALTIME_R
194 privoxy_mutex_t localtime_mutex;
195 #endif /* ndef HAVE_GMTIME_R */
198 privoxy_mutex_t rand_mutex;
199 #endif /* ndef HAVE_RANDOM */
202 privoxy_mutex_t strtok_mutex;
203 #endif /* def HAVE_STRTOK */
205 #endif /* def MUTEX_LOCKS_AVAILABLE */
208 const char *basedir = NULL;
209 const char *pidfile = NULL;
210 static int received_hup_signal = 0;
211 #endif /* defined unix */
213 /* HTTP snipplets. */
214 static const char CSUCCEED[] =
215 "HTTP/1.1 200 Connection established\r\n"
216 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
218 static const char CHEADER[] =
219 "HTTP/1.1 400 Invalid header received from client\r\n"
220 "Proxy-Agent: Privoxy " VERSION "\r\n"
221 "Content-Type: text/plain\r\n"
222 "Connection: close\r\n\r\n"
223 "Invalid header received from client.\r\n";
225 static const char FTP_RESPONSE[] =
226 "HTTP/1.1 400 Invalid request received from client\r\n"
227 "Content-Type: text/plain\r\n"
228 "Connection: close\r\n\r\n"
229 "Invalid request. Privoxy doesn't support FTP.\r\n";
231 static const char GOPHER_RESPONSE[] =
232 "HTTP/1.1 400 Invalid request received from client\r\n"
233 "Content-Type: text/plain\r\n"
234 "Connection: close\r\n\r\n"
235 "Invalid request. Privoxy doesn't support gopher.\r\n";
237 /* XXX: should be a template */
238 static const char MISSING_DESTINATION_RESPONSE[] =
239 "HTTP/1.1 400 Bad request received from client\r\n"
240 "Proxy-Agent: Privoxy " VERSION "\r\n"
241 "Content-Type: text/plain\r\n"
242 "Connection: close\r\n\r\n"
243 "Bad request. Privoxy was unable to extract the destination.\r\n";
245 /* XXX: should be a template */
246 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
247 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
248 "Proxy-Agent: Privoxy " VERSION "\r\n"
249 "Content-Type: text/plain\r\n"
250 "Connection: close\r\n\r\n"
251 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
253 /* XXX: should be a template */
254 static const char MESSED_UP_REQUEST_RESPONSE[] =
255 "HTTP/1.1 400 Malformed request after rewriting\r\n"
256 "Proxy-Agent: Privoxy " VERSION "\r\n"
257 "Content-Type: text/plain\r\n"
258 "Connection: close\r\n\r\n"
259 "Bad request. Messed up with header filters.\r\n";
261 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
262 "HTTP/1.1 503 Too many open connections\r\n"
263 "Proxy-Agent: Privoxy " VERSION "\r\n"
264 "Content-Type: text/plain\r\n"
265 "Connection: close\r\n\r\n"
266 "Maximum number of open connections reached.\r\n";
268 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
269 "HTTP/1.1 504 Connection timeout\r\n"
270 "Proxy-Agent: Privoxy " VERSION "\r\n"
271 "Content-Type: text/plain\r\n"
272 "Connection: close\r\n\r\n"
273 "The connection timed out because the client request didn't arrive in time.\r\n";
275 /* A function to crunch a response */
276 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
278 /* Crunch function flags */
279 #define CF_NO_FLAGS 0
280 /* Cruncher applies to forced requests as well */
281 #define CF_IGNORE_FORCE 1
282 /* Crunched requests are counted for the block statistics */
283 #define CF_COUNT_AS_REJECT 2
285 /* A crunch function and its flags */
288 const crunch_func_ptr cruncher;
292 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
294 /* Complete list of cruncher functions */
295 static const struct cruncher crunchers_all[] = {
296 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
297 { block_url, CF_COUNT_AS_REJECT },
299 { trust_url, CF_COUNT_AS_REJECT },
300 #endif /* def FEATURE_TRUST */
301 { redirect_url, CF_NO_FLAGS },
302 { dispatch_cgi, CF_IGNORE_FORCE},
306 /* Light version, used after tags are applied */
307 static const struct cruncher crunchers_light[] = {
308 { block_url, CF_COUNT_AS_REJECT },
309 { redirect_url, CF_NO_FLAGS },
315 * XXX: Don't we really mean
321 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
322 /*********************************************************************
324 * Function : sig_handler
326 * Description : Signal handler for different signals.
327 * Exit gracefully on TERM and INT
328 * or set a flag that will cause the errlog
329 * to be reopened by the main thread on HUP.
332 * 1 : the_signal = the signal cause this function to call
336 *********************************************************************/
337 static void sig_handler(int the_signal)
343 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
355 received_hup_signal = 1;
361 * We shouldn't be here, unless we catch signals
362 * in main() that we can't handle here!
364 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
372 /*********************************************************************
374 * Function : client_protocol_is_unsupported
376 * Description : Checks if the client used a known unsupported
377 * protocol and deals with it by sending an error
381 * 1 : csp = Current client state (buffers, headers, etc...)
382 * 2 : req = the first request line send by the client
384 * Returns : TRUE if an error response has been generated, or
385 * FALSE if the request doesn't look invalid.
387 *********************************************************************/
388 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
391 * If it's a FTP or gopher request, we don't support it.
393 * These checks are better than nothing, but they might
394 * not work in all configurations and some clients might
395 * have problems digesting the answer.
397 * They should, however, never cause more problems than
398 * Privoxy's old behaviour (returning the misleading HTML
401 * "Could not resolve http://(ftp|gopher)://example.org").
403 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
405 const char *response = NULL;
406 const char *protocol = NULL;
408 if (!strncmpic(req, "GET ftp://", 10))
410 response = FTP_RESPONSE;
415 response = GOPHER_RESPONSE;
418 log_error(LOG_LEVEL_ERROR,
419 "%s tried to use Privoxy as %s proxy: %s",
420 csp->ip_addr_str, protocol, req);
421 log_error(LOG_LEVEL_CLF,
422 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
424 write_socket(csp->cfd, response, strlen(response));
433 /*********************************************************************
435 * Function : get_request_destination_elsewhere
437 * Description : If the client's request was redirected into
438 * Privoxy without the client's knowledge,
439 * the request line lacks the destination host.
441 * This function tries to get it elsewhere,
442 * provided accept-intercepted-requests is enabled.
444 * "Elsewhere" currently only means "Host: header",
445 * but in the future we may ask the redirecting
446 * packet filter to look the destination up.
448 * If the destination stays unknown, an error
449 * response is send to the client and headers
450 * are freed so that chat() can return directly.
453 * 1 : csp = Current client state (buffers, headers, etc...)
454 * 2 : headers = a header list
456 * Returns : JB_ERR_OK if the destination is now known, or
457 * JB_ERR_PARSE if it isn't.
459 *********************************************************************/
460 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
464 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
466 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
467 " Privoxy isn't configured to accept intercepted requests.",
468 csp->ip_addr_str, csp->http->cmd);
469 /* XXX: Use correct size */
470 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
471 csp->ip_addr_str, csp->http->cmd);
473 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
474 destroy_list(headers);
478 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
480 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
481 /* Split the domain we just got for pattern matching */
482 init_domain_components(csp->http);
489 /* We can't work without destination. Go spread the news.*/
491 req = list_to_text(headers);
493 /* XXX: Use correct size */
494 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
495 csp->ip_addr_str, csp->http->cmd);
496 log_error(LOG_LEVEL_ERROR,
497 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
498 csp->ip_addr_str, csp->http->cmd, req);
501 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
502 destroy_list(headers);
507 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
508 * to get the destination IP address, use it as host directly
509 * or do a reverse DNS lookup first.
514 /*********************************************************************
516 * Function : get_server_headers
518 * Description : Parses server headers in iob and fills them
519 * into csp->headers so that they can later be
523 * 1 : csp = Current client state (buffers, headers, etc...)
525 * Returns : JB_ERR_OK if everything went fine, or
526 * JB_ERR_PARSE if the headers were incomplete.
528 *********************************************************************/
529 static jb_err get_server_headers(struct client_state *csp)
531 int continue_hack_in_da_house = 0;
534 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
539 * continue hack in da house. Ignore the ending of
540 * this head and continue enlisting header lines.
541 * The reason is described below.
543 enlist(csp->headers, "");
544 continue_hack_in_da_house = 0;
547 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
550 * It's a bodyless continue response, don't
551 * stop header parsing after reaching its end.
553 * As a result Privoxy will concatenate the
554 * next response's head and parse and deliver
555 * the headers as if they belonged to one request.
557 * The client will separate them because of the
558 * empty line between them.
560 * XXX: What we're doing here is clearly against
561 * the intended purpose of the continue header,
562 * and under some conditions (HTTP/1.0 client request)
563 * it's a standard violation.
565 * Anyway, "sort of against the spec" is preferable
566 * to "always getting confused by Continue responses"
567 * (Privoxy's behaviour before this hack was added)
569 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
570 continue_hack_in_da_house = 1;
572 else if (*header == '\0')
575 * If the header is empty, but the Continue hack
576 * isn't active, we can assume that we reached the
577 * end of the buffer before we hit the end of the
580 * Inform the caller an let it decide how to handle it.
585 if (JB_ERR_MEMORY == enlist(csp->headers, header))
588 * XXX: Should we quit the request and return a
589 * out of memory error page instead?
591 log_error(LOG_LEVEL_ERROR,
592 "Out of memory while enlisting server headers. %s lost.",
602 /*********************************************************************
604 * Function : crunch_reason
606 * Description : Translates the crunch reason code into a string.
609 * 1 : rsp = a http_response
611 * Returns : A string with the crunch reason or an error description.
613 *********************************************************************/
614 static const char *crunch_reason(const struct http_response *rsp)
616 char * reason = NULL;
621 return "Internal error while searching for crunch reason";
624 switch (rsp->crunch_reason)
627 reason = "Unsupported HTTP feature";
633 reason = "Untrusted";
636 reason = "Redirected";
642 reason = "DNS failure";
644 case FORWARDING_FAILED:
645 reason = "Forwarding failed";
648 reason = "Connection failure";
651 reason = "Out of memory (may mask other reasons)";
653 case CONNECTION_TIMEOUT:
654 reason = "Connection timeout";
657 reason = "No server data received";
660 reason = "No reason recorded";
668 /*********************************************************************
670 * Function : send_crunch_response
672 * Description : Delivers already prepared response for
673 * intercepted requests, logs the interception
674 * and frees the response.
677 * 1 : csp = Current client state (buffers, headers, etc...)
678 * 1 : rsp = Fully prepared response. Will be freed on exit.
682 *********************************************************************/
683 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
685 const struct http_request *http = csp->http;
689 assert(rsp->head != NULL);
693 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
697 * Extract the status code from the actual head
698 * that will be send to the client. It is the only
699 * way to get it right for all requests, including
700 * the fixed ones for out-of-memory problems.
702 * A head starts like this: 'HTTP/1.1 200...'
706 status_code[0] = rsp->head[9];
707 status_code[1] = rsp->head[10];
708 status_code[2] = rsp->head[11];
709 status_code[3] = '\0';
711 /* Log that the request was crunched and why. */
712 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
713 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
714 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
716 /* Write the answer to the client */
717 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
718 || write_socket(csp->cfd, rsp->body, rsp->content_length))
720 /* There is nothing we can do about it. */
721 log_error(LOG_LEVEL_ERROR,
722 "Couldn't deliver the error message through client socket %d: %E",
726 /* Clean up and return */
727 if (cgi_error_memory() != rsp)
729 free_http_response(rsp);
735 /*********************************************************************
737 * Function : crunch_response_triggered
739 * Description : Checks if the request has to be crunched,
740 * and delivers the crunch response if necessary.
743 * 1 : csp = Current client state (buffers, headers, etc...)
744 * 2 : crunchers = list of cruncher functions to run
746 * Returns : TRUE if the request was answered with a crunch response
749 *********************************************************************/
750 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
752 struct http_response *rsp = NULL;
753 const struct cruncher *c;
756 * If CGI request crunching is disabled,
757 * check the CGI dispatcher out of order to
758 * prevent unintentional blocks or redirects.
760 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
761 && (NULL != (rsp = dispatch_cgi(csp))))
763 /* Deliver, log and free the interception response. */
764 send_crunch_response(csp, rsp);
765 csp->flags |= CSP_FLAG_CRUNCHED;
769 for (c = crunchers; c->cruncher != NULL; c++)
772 * Check the cruncher if either Privoxy is toggled
773 * on and the request isn't forced, or if the cruncher
774 * applies to forced requests as well.
776 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
777 !(csp->flags & CSP_FLAG_FORCED)) ||
778 (c->flags & CF_IGNORE_FORCE))
780 rsp = c->cruncher(csp);
783 /* Deliver, log and free the interception response. */
784 send_crunch_response(csp, rsp);
785 csp->flags |= CSP_FLAG_CRUNCHED;
786 #ifdef FEATURE_STATISTICS
787 if (c->flags & CF_COUNT_AS_REJECT)
789 csp->flags |= CSP_FLAG_REJECTED;
791 #endif /* def FEATURE_STATISTICS */
802 /*********************************************************************
804 * Function : build_request_line
806 * Description : Builds the HTTP request line.
808 * If a HTTP forwarder is used it expects the whole URL,
809 * web servers only get the path.
812 * 1 : csp = Current client state (buffers, headers, etc...)
813 * 2 : fwd = The forwarding spec used for the request
814 * XXX: Should use http->fwd instead.
815 * 3 : request_line = The old request line which will be replaced.
817 * Returns : Nothing. Terminates in case of memory problems.
819 *********************************************************************/
820 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
822 struct http_request *http = csp->http;
824 assert(http->ssl == 0);
827 * Downgrade http version from 1.1 to 1.0
828 * if +downgrade action applies.
830 if ( (csp->action->flags & ACTION_DOWNGRADE)
831 && (!strcmpic(http->ver, "HTTP/1.1")))
834 http->ver = strdup("HTTP/1.0");
836 if (http->ver == NULL)
838 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
843 * Rebuild the request line.
845 freez(*request_line);
846 *request_line = strdup(http->gpc);
847 string_append(request_line, " ");
849 if (fwd->forward_host)
851 string_append(request_line, http->url);
855 string_append(request_line, http->path);
857 string_append(request_line, " ");
858 string_append(request_line, http->ver);
860 if (*request_line == NULL)
862 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
864 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
868 /*********************************************************************
870 * Function : change_request_destination
872 * Description : Parse a (rewritten) request line and regenerate
873 * the http request data.
876 * 1 : csp = Current client state (buffers, headers, etc...)
878 * Returns : Forwards the parse_http_request() return code.
879 * Terminates in case of memory problems.
881 *********************************************************************/
882 static jb_err change_request_destination(struct client_state *csp)
884 struct http_request *http = csp->http;
887 log_error(LOG_LEVEL_INFO, "Rewrite detected: %s", csp->headers->first->str);
888 free_http_request(http);
889 err = parse_http_request(csp->headers->first->str, http);
890 if (JB_ERR_OK != err)
892 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
893 jb_err_to_string(err));
897 /* XXX: ocmd is a misleading name */
898 http->ocmd = strdup(http->cmd);
899 if (http->ocmd == NULL)
901 log_error(LOG_LEVEL_FATAL,
902 "Out of memory copying rewritten HTTP request line");
910 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
911 /*********************************************************************
913 * Function : server_response_is_complete
915 * Description : Determines whether we should stop reading
916 * from the server socket.
919 * 1 : csp = Current client state (buffers, headers, etc...)
920 * 2 : content_length = Length of content received so far.
922 * Returns : TRUE if the response is complete,
925 *********************************************************************/
926 static int server_response_is_complete(struct client_state *csp,
927 unsigned long long content_length)
929 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
931 if (!strcmpic(csp->http->gpc, "HEAD"))
934 * "HEAD" implies no body, we are thus expecting
935 * no content. XXX: incomplete "list" of methods?
937 csp->expected_content_length = 0;
938 content_length_known = TRUE;
941 if (csp->http->status == 204 || csp->http->status == 304)
944 * Expect no body. XXX: incomplete "list" of status codes?
946 csp->expected_content_length = 0;
947 content_length_known = TRUE;
950 return (content_length_known && ((0 == csp->expected_content_length)
951 || (csp->expected_content_length <= content_length)));
955 #ifdef FEATURE_CONNECTION_SHARING
956 /*********************************************************************
958 * Function : wait_for_alive_connections
960 * Description : Waits for alive connections to timeout.
966 *********************************************************************/
967 static void wait_for_alive_connections(void)
969 int connections_alive = close_unusable_connections();
971 while (0 < connections_alive)
973 log_error(LOG_LEVEL_CONNECT,
974 "Waiting for %d connections to timeout.",
977 connections_alive = close_unusable_connections();
980 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
983 #endif /* def FEATURE_CONNECTION_SHARING */
986 /*********************************************************************
988 * Function : save_connection_destination
990 * Description : Remembers a connection for reuse later on.
993 * 1 : sfd = Open socket to remember.
994 * 2 : http = The destination for the connection.
995 * 3 : fwd = The forwarder settings used.
996 * 3 : server_connection = storage.
1000 *********************************************************************/
1001 void save_connection_destination(jb_socket sfd,
1002 const struct http_request *http,
1003 const struct forward_spec *fwd,
1004 struct reusable_connection *server_connection)
1006 assert(sfd != JB_INVALID_SOCKET);
1007 assert(NULL != http->host);
1009 server_connection->sfd = sfd;
1010 server_connection->host = strdup(http->host);
1011 if (NULL == server_connection->host)
1013 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
1015 server_connection->port = http->port;
1017 assert(NULL != fwd);
1018 assert(server_connection->gateway_host == NULL);
1019 assert(server_connection->gateway_port == 0);
1020 assert(server_connection->forwarder_type == 0);
1021 assert(server_connection->forward_host == NULL);
1022 assert(server_connection->forward_port == 0);
1024 server_connection->forwarder_type = fwd->type;
1025 if (NULL != fwd->gateway_host)
1027 server_connection->gateway_host = strdup(fwd->gateway_host);
1028 if (NULL == server_connection->gateway_host)
1030 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
1035 server_connection->gateway_host = NULL;
1037 server_connection->gateway_port = fwd->gateway_port;
1039 if (NULL != fwd->forward_host)
1041 server_connection->forward_host = strdup(fwd->forward_host);
1042 if (NULL == server_connection->forward_host)
1044 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
1049 server_connection->forward_host = NULL;
1051 server_connection->forward_port = fwd->forward_port;
1055 /*********************************************************************
1057 * Function : verify_request_length
1059 * Description : Checks if we already got the whole client requests
1060 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1063 * Data that doesn't belong to the current request is
1064 * thrown away to let the client retry on a clean socket.
1066 * XXX: This is a hack until we can deal with multiple
1067 * pipelined requests at the same time.
1071 * 1 : csp = Current client state (buffers, headers, etc...)
1075 *********************************************************************/
1076 static void verify_request_length(struct client_state *csp)
1078 unsigned long long buffered_request_bytes =
1079 (unsigned long long)(csp->iob->eod - csp->iob->cur);
1081 if ((csp->expected_client_content_length != 0)
1082 && (buffered_request_bytes != 0))
1084 if (csp->expected_client_content_length >= buffered_request_bytes)
1086 csp->expected_client_content_length -= buffered_request_bytes;
1087 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1088 "to account for the %llu ones we already got.",
1089 csp->expected_client_content_length, buffered_request_bytes);
1093 assert(csp->iob->eod > csp->iob->cur + csp->expected_client_content_length);
1094 csp->iob->eod = csp->iob->cur + csp->expected_client_content_length;
1095 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1096 "Marking the server socket tainted after throwing %llu bytes away.",
1097 buffered_request_bytes - csp->expected_client_content_length);
1098 csp->expected_client_content_length = 0;
1099 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1102 if (csp->expected_client_content_length == 0)
1104 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1108 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1109 && ((csp->iob->cur[0] != '\0') || (csp->expected_client_content_length != 0)))
1111 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1112 if (strcmpic(csp->http->gpc, "GET")
1113 && strcmpic(csp->http->gpc, "HEAD")
1114 && strcmpic(csp->http->gpc, "TRACE")
1115 && strcmpic(csp->http->gpc, "OPTIONS")
1116 && strcmpic(csp->http->gpc, "DELETE"))
1118 /* XXX: this is an incomplete hack */
1119 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1120 log_error(LOG_LEVEL_CONNECT,
1121 "There might be a request body. The connection will not be kept alive.");
1125 /* XXX: and so is this */
1126 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1127 log_error(LOG_LEVEL_CONNECT,
1128 "Possible pipeline attempt detected. The connection will not "
1129 "be kept alive and we will only serve the first request.");
1130 /* Nuke the pipelined requests from orbit, just to be sure. */
1131 csp->iob->buf[0] = '\0';
1132 csp->iob->eod = csp->iob->cur = csp->iob->buf;
1137 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1138 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1141 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1144 /*********************************************************************
1146 * Function : mark_server_socket_tainted
1148 * Description : Makes sure we don't reuse a server socket
1149 * (if we didn't read everything the server sent
1150 * us reusing the socket would lead to garbage).
1153 * 1 : csp = Current client state (buffers, headers, etc...)
1157 *********************************************************************/
1158 static void mark_server_socket_tainted(struct client_state *csp)
1161 * For consistency we always mark the server socket
1162 * tainted, however, to reduce the log noise we only
1163 * emit a log message if the server socket could have
1164 * actually been reused.
1166 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1167 && !(csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED))
1169 log_error(LOG_LEVEL_CONNECT,
1170 "Marking the server socket %d tainted.",
1171 csp->server_connection.sfd);
1173 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1176 /*********************************************************************
1178 * Function : get_request_line
1180 * Description : Read the client request line.
1183 * 1 : csp = Current client state (buffers, headers, etc...)
1185 * Returns : Pointer to request line or NULL in case of errors.
1187 *********************************************************************/
1188 static char *get_request_line(struct client_state *csp)
1190 char buf[BUFFER_SIZE];
1191 char *request_line = NULL;
1194 memset(buf, 0, sizeof(buf));
1198 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1200 log_error(LOG_LEVEL_CONNECT,
1201 "Stopped waiting for the request line. Timeout: %d.",
1202 csp->config->socket_timeout);
1203 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1204 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1208 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1210 if (len <= 0) return NULL;
1213 * If there is no memory left for buffering the
1214 * request, there is nothing we can do but hang up
1216 if (add_to_iob(csp, buf, len))
1221 request_line = get_header(csp->iob);
1223 } while ((NULL != request_line) && ('\0' == *request_line));
1225 return request_line;
1230 /*********************************************************************
1232 * Function : receive_client_request
1234 * Description : Read the client's request (more precisely the
1235 * client headers) and answer it if necessary.
1237 * Note that since we're not using select() we could get
1238 * blocked here if a client connected, then didn't say
1242 * 1 : csp = Current client state (buffers, headers, etc...)
1244 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1246 *********************************************************************/
1247 static jb_err receive_client_request(struct client_state *csp)
1249 char buf[BUFFER_SIZE];
1252 struct http_request *http;
1256 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1257 struct list header_list;
1258 struct list *headers = &header_list;
1262 memset(buf, 0, sizeof(buf));
1264 req = get_request_line(csp);
1267 mark_server_socket_tainted(csp);
1268 return JB_ERR_PARSE;
1270 assert(*req != '\0');
1272 if (client_protocol_is_unsupported(csp, req))
1274 return JB_ERR_PARSE;
1277 #ifdef FEATURE_FORCE_LOAD
1279 * If this request contains the FORCE_PREFIX and blocks
1280 * aren't enforced, get rid of it and set the force flag.
1282 if (strstr(req, FORCE_PREFIX))
1284 if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1286 log_error(LOG_LEVEL_FORCE,
1287 "Ignored force prefix in request: \"%s\".", req);
1291 strclean(req, FORCE_PREFIX);
1292 log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1293 csp->flags |= CSP_FLAG_FORCED;
1296 #endif /* def FEATURE_FORCE_LOAD */
1298 err = parse_http_request(req, http);
1300 if (JB_ERR_OK != err)
1302 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1303 /* XXX: Use correct size */
1304 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1305 log_error(LOG_LEVEL_ERROR,
1306 "Couldn't parse request line received from %s: %s",
1307 csp->ip_addr_str, jb_err_to_string(err));
1309 free_http_request(http);
1310 return JB_ERR_PARSE;
1313 /* grab the rest of the client's headers */
1317 p = get_header(csp->iob);
1321 /* There are no additional headers to read. */
1328 * We didn't receive a complete header
1329 * line yet, get the rest of it.
1331 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1333 log_error(LOG_LEVEL_ERROR,
1334 "Stopped grabbing the client headers.");
1335 destroy_list(headers);
1336 return JB_ERR_PARSE;
1339 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1342 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1343 destroy_list(headers);
1344 return JB_ERR_PARSE;
1347 if (add_to_iob(csp, buf, len))
1350 * If there is no memory left for buffering the
1351 * request, there is nothing we can do but hang up
1353 destroy_list(headers);
1354 return JB_ERR_MEMORY;
1360 * We were able to read a complete
1361 * header and can finally enlist it.
1368 if (http->host == NULL)
1371 * If we still don't know the request destination,
1372 * the request is invalid or the client uses
1373 * Privoxy without its knowledge.
1375 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1378 * Our attempts to get the request destination
1379 * elsewhere failed or Privoxy is configured
1380 * to only accept proxy requests.
1382 * An error response has already been send
1383 * and we're done here.
1385 return JB_ERR_PARSE;
1390 * Determine the actions for this URL
1392 #ifdef FEATURE_TOGGLE
1393 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1395 /* Most compatible set of actions (i.e. none) */
1396 init_current_action(csp->action);
1399 #endif /* ndef FEATURE_TOGGLE */
1401 get_url_actions(csp, http);
1405 * Save a copy of the original request for logging
1407 http->ocmd = strdup(http->cmd);
1408 if (http->ocmd == NULL)
1410 log_error(LOG_LEVEL_FATAL,
1411 "Out of memory copying HTTP request line");
1413 enlist(csp->headers, http->cmd);
1415 /* Append the previously read headers */
1416 list_append_list_unique(csp->headers, headers);
1417 destroy_list(headers);
1424 /*********************************************************************
1426 * Function : parse_client_request
1428 * Description : Parses the client's request and decides what to do
1431 * Note that since we're not using select() we could get
1432 * blocked here if a client connected, then didn't say
1436 * 1 : csp = Current client state (buffers, headers, etc...)
1438 * Returns : JB_ERR_OK or JB_ERR_PARSE
1440 *********************************************************************/
1441 static jb_err parse_client_request(struct client_state *csp)
1443 struct http_request *http = csp->http;
1446 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1447 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1448 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1449 && (csp->http->ssl == 0))
1451 /* Assume persistence until further notice */
1452 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1454 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1456 err = sed(csp, FILTER_CLIENT_HEADERS);
1457 if (JB_ERR_OK != err)
1459 /* XXX: Should be handled in sed(). */
1460 assert(err == JB_ERR_PARSE);
1461 log_error(LOG_LEVEL_FATAL, "Failed to parse client headers.");
1463 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1465 /* Check request line for rewrites. */
1466 if ((NULL == csp->headers->first->str)
1467 || (strcmp(http->cmd, csp->headers->first->str) &&
1468 (JB_ERR_OK != change_request_destination(csp))))
1471 * A header filter broke the request line - bail out.
1473 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1474 /* XXX: Use correct size */
1475 log_error(LOG_LEVEL_CLF,
1476 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1477 log_error(LOG_LEVEL_ERROR,
1478 "Invalid request line after applying header filters.");
1479 free_http_request(http);
1481 return JB_ERR_PARSE;
1484 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1485 if (csp->http->ssl == 0)
1487 verify_request_length(csp);
1489 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1496 /*********************************************************************
1500 * Description : Once a connection from the client has been accepted,
1501 * this function is called (via serve()) to handle the
1502 * main business of the communication. This function
1503 * returns after dealing with a single request. It can
1504 * be called multiple times with the same client socket
1505 * if the client is keeping the connection alive.
1507 * The decision whether or not a client connection will
1508 * be kept alive is up to the caller which also must
1509 * close the client socket when done.
1511 * FIXME: chat is nearly thousand lines long.
1515 * 1 : csp = Current client state (buffers, headers, etc...)
1517 * Returns : Nothing.
1519 *********************************************************************/
1520 static void chat(struct client_state *csp)
1522 char buf[BUFFER_SIZE];
1529 int ms_iis5_hack = 0;
1530 unsigned long long byte_count = 0;
1531 const struct forward_spec *fwd;
1532 struct http_request *http;
1533 long len = 0; /* for buffer sizes (and negative error codes) */
1534 int buffer_and_filter_content = 0;
1536 /* Skeleton for HTTP response, if we should intercept the request */
1537 struct http_response *rsp;
1538 struct timeval timeout;
1539 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1540 int watch_client_socket = 1;
1543 memset(buf, 0, sizeof(buf));
1547 if (receive_client_request(csp) != JB_ERR_OK)
1551 if (parse_client_request(csp) != JB_ERR_OK)
1556 /* decide how to route the HTTP request */
1557 fwd = forward_url(csp, http);
1560 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1561 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1566 * build the http request to send to the server
1567 * we have to do one of the following:
1569 * create = use the original HTTP request to create a new
1570 * HTTP request that has either the path component
1571 * without the http://domainspec (w/path) or the
1572 * full orininal URL (w/url)
1573 * Note that the path and/or the HTTP version may
1574 * have been altered by now.
1576 * connect = Open a socket to the host:port of the server
1577 * and short-circuit server and client socket.
1579 * pass = Pass the request unchanged if forwarding a CONNECT
1580 * request to a parent proxy. Note that we'll be sending
1581 * the CFAIL message ourselves if connecting to the parent
1582 * fails, but we won't send a CSUCCEED message if it works,
1583 * since that would result in a double message (ours and the
1584 * parent's). After sending the request to the parent, we simply
1587 * here's the matrix:
1590 * +--------+--------+
1592 * 0 | create | connect|
1594 * Forwarding +--------+--------+
1596 * 1 | create | pass |
1598 * +--------+--------+
1602 if (http->ssl && connect_port_is_forbidden(csp))
1604 const char *acceptable_connect_ports =
1605 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1606 assert(NULL != acceptable_connect_ports);
1607 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1608 "limit-connect{%s} doesn't allow CONNECT requests to %s",
1609 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
1610 csp->action->flags |= ACTION_BLOCK;
1616 freez(csp->headers->first->str);
1617 build_request_line(csp, fwd, &csp->headers->first->str);
1621 * We have a request. Check if one of the crunchers wants it.
1623 if (crunch_response_triggered(csp, crunchers_all))
1626 * Yes. The client got the crunch response and we're done here.
1631 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1633 if (fwd->forward_host)
1635 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1636 fwd->forward_host, fwd->forward_port, http->hostport);
1640 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1643 /* here we connect to the server, gateway, or the forwarder */
1645 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1646 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
1647 && socket_is_still_alive(csp->server_connection.sfd)
1648 && connection_destination_matches(&csp->server_connection, http, fwd))
1650 log_error(LOG_LEVEL_CONNECT,
1651 "Reusing server socket %u. Opened for %s.",
1652 csp->server_connection.sfd, csp->server_connection.host);
1656 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
1658 log_error(LOG_LEVEL_CONNECT,
1659 "Closing server socket %u. Opened for %s.",
1660 csp->server_connection.sfd, csp->server_connection.host);
1661 close_socket(csp->server_connection.sfd);
1662 mark_connection_closed(&csp->server_connection);
1664 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1666 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
1668 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
1670 if (fwd->type != SOCKS_NONE)
1673 rsp = error_response(csp, "forwarding-failed");
1675 else if (errno == EINVAL)
1677 rsp = error_response(csp, "no-such-domain");
1681 rsp = error_response(csp, "connect-failed");
1684 /* Write the answer to the client */
1687 send_crunch_response(csp, rsp);
1692 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1693 save_connection_destination(csp->server_connection.sfd,
1694 http, fwd, &csp->server_connection);
1695 csp->server_connection.keep_alive_timeout =
1696 (unsigned)csp->config->keep_alive_timeout;
1698 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1700 if (fwd->forward_host || (http->ssl == 0))
1702 hdr = list_to_text(csp->headers);
1705 /* FIXME Should handle error properly */
1706 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1708 list_remove_all(csp->headers);
1711 * Write the client's (modified) header to the server
1712 * (along with anything else that may be in the buffer)
1714 if (write_socket(csp->server_connection.sfd, hdr, strlen(hdr))
1715 || (flush_socket(csp->server_connection.sfd, csp->iob) < 0))
1717 log_error(LOG_LEVEL_CONNECT,
1718 "write header to: %s failed: %E", http->hostport);
1720 rsp = error_response(csp, "connect-failed");
1723 send_crunch_response(csp, rsp);
1734 * We're running an SSL tunnel and we're not forwarding,
1735 * so just ditch the client headers, send the "connect succeeded"
1736 * message to the client, flush the rest, and get out of the way.
1738 list_remove_all(csp->headers);
1739 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
1746 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
1748 csp->server_connection.request_sent = time(NULL);
1750 maxfd = (csp->cfd > csp->server_connection.sfd) ?
1751 csp->cfd : csp->server_connection.sfd;
1753 /* pass data between the client and server
1754 * until one or the other shuts down the connection.
1763 * FD_ZERO here seems to point to an errant macro which crashes.
1764 * So do this by hand for now...
1766 memset(&rfds,0x00,sizeof(fd_set));
1770 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1771 if (!watch_client_socket)
1773 maxfd = csp->server_connection.sfd;
1776 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1778 FD_SET(csp->cfd, &rfds);
1781 FD_SET(csp->server_connection.sfd, &rfds);
1783 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1784 if ((csp->flags & CSP_FLAG_CHUNKED)
1785 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
1786 && ((csp->iob->eod - csp->iob->cur) >= 5)
1787 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
1790 * XXX: This check should be obsolete now,
1791 * but let's wait a while to be sure.
1793 log_error(LOG_LEVEL_CONNECT,
1794 "Looks like we got the last chunk together with "
1795 "the server headers but didn't detect it earlier. "
1796 "We better stop reading.");
1797 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
1798 csp->expected_content_length = byte_count;
1799 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
1801 if (server_body && server_response_is_complete(csp, byte_count))
1803 if (csp->expected_content_length == byte_count)
1805 log_error(LOG_LEVEL_CONNECT,
1806 "Done reading from server. Content length: %llu as expected. "
1807 "Bytes most recently read: %d.",
1812 log_error(LOG_LEVEL_CONNECT,
1813 "Done reading from server. Expected content length: %llu. "
1814 "Actual content length: %llu. Bytes most recently read: %d.",
1815 csp->expected_content_length, byte_count, len);
1819 * XXX: should not jump around,
1820 * chat() is complicated enough already.
1824 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1826 timeout.tv_sec = csp->config->socket_timeout;
1827 timeout.tv_usec = 0;
1828 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
1832 log_error(LOG_LEVEL_ERROR,
1833 "Didn't receive data in time: %s", http->url);
1834 if ((byte_count == 0) && (http->ssl == 0))
1836 send_crunch_response(csp, error_response(csp, "connection-timeout"));
1838 mark_server_socket_tainted(csp);
1843 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1844 mark_server_socket_tainted(csp);
1849 * This is the body of the browser's request,
1850 * just read and write it.
1852 * XXX: Make sure the client doesn't use pipelining
1853 * behind Privoxy's back.
1855 if (FD_ISSET(csp->cfd, &rfds))
1857 int max_bytes_to_read = sizeof(buf) - 1;
1859 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1860 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1862 if (data_is_available(csp->cfd, 0))
1865 * If the next request is already waiting, we have
1866 * to stop select()ing the client socket. Otherwise
1867 * we would always return right away and get nothing
1870 watch_client_socket = 0;
1871 log_error(LOG_LEVEL_CONNECT,
1872 "Stopping to watch the client socket. "
1873 "There's already another request waiting.");
1877 * If the client socket is set, but there's no data
1878 * available on the socket, the client went fishing
1879 * and continuing talking to the server makes no sense.
1881 log_error(LOG_LEVEL_CONNECT,
1882 "The client closed socket %d while "
1883 "the server socket %d is still open.",
1884 csp->cfd, csp->server_connection.sfd);
1885 mark_server_socket_tainted(csp);
1888 if (csp->expected_client_content_length != 0)
1890 if (csp->expected_client_content_length < (sizeof(buf) - 1))
1892 max_bytes_to_read = (int)csp->expected_client_content_length;
1894 log_error(LOG_LEVEL_CONNECT,
1895 "Waiting for up to %d bytes from the client.",
1898 assert(max_bytes_to_read < sizeof(buf));
1899 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1901 len = read_socket(csp->cfd, buf, max_bytes_to_read);
1905 /* XXX: not sure if this is necessary. */
1906 mark_server_socket_tainted(csp);
1907 break; /* "game over, man" */
1910 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1911 if (csp->expected_client_content_length != 0)
1913 assert(len <= max_bytes_to_read);
1914 csp->expected_client_content_length -= (unsigned)len;
1915 log_error(LOG_LEVEL_CONNECT,
1916 "Expected client content length set to %llu "
1917 "after reading %d bytes.",
1918 csp->expected_client_content_length, len);
1919 if (csp->expected_client_content_length == 0)
1921 log_error(LOG_LEVEL_CONNECT,
1922 "Done reading from the client.");
1923 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1926 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1928 if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
1930 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1931 mark_server_socket_tainted(csp);
1938 * The server wants to talk. It could be the header or the body.
1939 * If `hdr' is null, then it's the header otherwise it's the body.
1940 * FIXME: Does `hdr' really mean `host'? No.
1942 if (FD_ISSET(csp->server_connection.sfd, &rfds))
1944 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1946 * If we are buffering content, we don't want to eat up to
1947 * buffer-limit bytes if the client no longer cares about them.
1948 * If we aren't buffering, however, a dead client socket will be
1949 * noticed pretty much right away anyway, so we can reduce the
1950 * overhead by skipping the check.
1952 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
1955 log_error(LOG_LEVEL_CONNECT,
1956 "The server still wants to talk, but the client may already have hung up on us.");
1958 log_error(LOG_LEVEL_CONNECT,
1959 "The server still wants to talk, but the client hung up on us.");
1960 mark_server_socket_tainted(csp);
1962 #endif /* def _WIN32 */
1964 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1967 len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
1971 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1973 if (http->ssl && (fwd->forward_host == NULL))
1976 * Just hang up. We already confirmed the client's CONNECT
1977 * request with status code 200 and unencrypted content is
1978 * no longer welcome.
1980 log_error(LOG_LEVEL_ERROR,
1981 "CONNECT already confirmed. Unable to tell the client about the problem.");
1984 else if (byte_count)
1987 * Just hang up. We already transmitted the original headers
1988 * and parts of the original content and therefore missed the
1989 * chance to send an error message (without risking data corruption).
1991 * XXX: we could retry with a fancy range request here.
1993 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
1994 "Unable to tell the client about the problem.");
1995 mark_server_socket_tainted(csp);
1999 * XXX: Consider handling the cases above the same.
2001 mark_server_socket_tainted(csp);
2005 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2006 if (csp->flags & CSP_FLAG_CHUNKED)
2008 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2010 /* XXX: this is a temporary hack */
2011 log_error(LOG_LEVEL_CONNECT,
2012 "Looks like we reached the end of the last chunk. "
2013 "We better stop reading.");
2014 csp->expected_content_length = byte_count + (unsigned long long)len;
2015 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2019 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2022 * Add a trailing zero to let be able to use string operations.
2023 * XXX: do we still need this with filter_popups gone?
2028 * Normally, this would indicate that we've read
2029 * as much as the server has sent us and we can
2030 * close the client connection. However, Microsoft
2031 * in its wisdom has released IIS/5 with a bug that
2032 * prevents it from sending the trailing \r\n in
2033 * a 302 redirect header (and possibly other headers).
2034 * To work around this if we've haven't parsed
2035 * a full header we'll append a trailing \r\n
2036 * and see if this now generates a valid one.
2038 * This hack shouldn't have any impacts. If we've
2039 * already transmitted the header or if this is a
2040 * SSL connection, then we won't bother with this
2041 * hack. So we only work on partially received
2042 * headers. If we append a \r\n and this still
2043 * doesn't generate a valid header, then we won't
2044 * transmit anything to the client.
2049 if (server_body || http->ssl)
2052 * If we have been buffering up the document,
2053 * now is the time to apply content modification
2054 * and send the result to the client.
2056 if (buffer_and_filter_content)
2058 p = execute_content_filters(csp);
2060 * If content filtering fails, use the original
2061 * buffer and length.
2062 * (see p != NULL ? p : csp->iob->cur below)
2066 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2068 #ifdef FEATURE_COMPRESSION
2069 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2070 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2072 char *compressed_content = compress_buffer(p,
2073 (size_t *)&csp->content_length, csp->config->compression_level);
2074 if (compressed_content != NULL)
2077 p = compressed_content;
2078 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2083 if (JB_ERR_OK != update_server_headers(csp))
2085 log_error(LOG_LEVEL_FATAL,
2086 "Failed to update server headers. after filtering.");
2089 hdr = list_to_text(csp->headers);
2092 /* FIXME Should handle error properly */
2093 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2096 if (write_socket(csp->cfd, hdr, strlen(hdr))
2097 || write_socket(csp->cfd,
2098 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2100 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2103 mark_server_socket_tainted(csp);
2111 break; /* "game over, man" */
2115 * This is NOT the body, so
2116 * Let's pretend the server just sent us a blank line.
2118 snprintf(buf, sizeof(buf), "\r\n");
2119 len = (int)strlen(buf);
2122 * Now, let the normal header parsing algorithm below do its
2123 * job. If it fails, we'll exit instead of continuing.
2130 * If this is an SSL connection or we're in the body
2131 * of the server document, just write it to the client,
2132 * unless we need to buffer the body for later content-filtering
2134 if (server_body || http->ssl)
2136 if (buffer_and_filter_content)
2139 * If there is no memory left for buffering the content, or the buffer limit
2140 * has been reached, switch to non-filtering mode, i.e. make & write the
2141 * header, flush the iob and buf, and get out of the way.
2143 if (add_to_iob(csp, buf, len))
2148 log_error(LOG_LEVEL_INFO,
2149 "Flushing header and buffers. Stepping back from filtering.");
2151 hdr = list_to_text(csp->headers);
2155 * Memory is too tight to even generate the header.
2156 * Send our static "Out-of-memory" page.
2158 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2159 rsp = cgi_error_memory();
2160 send_crunch_response(csp, rsp);
2161 mark_server_socket_tainted(csp);
2164 hdrlen = strlen(hdr);
2166 if (write_socket(csp->cfd, hdr, hdrlen)
2167 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2168 || (write_socket(csp->cfd, buf, (size_t)len)))
2170 log_error(LOG_LEVEL_CONNECT,
2171 "Flush header and buffers to client failed: %E");
2173 mark_server_socket_tainted(csp);
2178 * Reset the byte_count to the amount of bytes
2179 * we just flushed. len will be added a few lines below,
2180 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2182 byte_count = (unsigned long long)flushed;
2184 buffer_and_filter_content = 0;
2190 if (write_socket(csp->cfd, buf, (size_t)len))
2192 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2193 mark_server_socket_tainted(csp);
2197 byte_count += (unsigned long long)len;
2203 * We're still looking for the end of the server's header.
2204 * Buffer up the data we just read. If that fails, there's
2205 * little we can do but send our static out-of-memory page.
2207 if (add_to_iob(csp, buf, len))
2209 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2210 rsp = cgi_error_memory();
2211 send_crunch_response(csp, rsp);
2212 mark_server_socket_tainted(csp);
2216 /* Convert iob into something sed() can digest */
2217 if (JB_ERR_PARSE == get_server_headers(csp))
2222 * Well, we tried our MS IIS/5 hack and it didn't work.
2223 * The header is incomplete and there isn't anything
2224 * we can do about it.
2226 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2227 "Applying the MS IIS5 hack didn't help.");
2228 log_error(LOG_LEVEL_CLF,
2229 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2230 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2231 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2232 mark_server_socket_tainted(csp);
2238 * Since we have to wait for more from the server before
2239 * we can parse the headers we just continue here.
2241 log_error(LOG_LEVEL_CONNECT,
2242 "Continuing buffering headers. Bytes most recently read: %d.",
2250 * Account for the content bytes we
2251 * might have gotten with the headers.
2253 assert(csp->iob->eod >= csp->iob->cur);
2254 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2257 /* Did we actually get anything? */
2258 if (NULL == csp->headers->first)
2260 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2262 log_error(LOG_LEVEL_ERROR,
2263 "No server or forwarder response received on socket %d. "
2264 "Closing client socket %d without sending data.",
2265 csp->server_connection.sfd, csp->cfd);
2266 log_error(LOG_LEVEL_CLF,
2267 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2271 log_error(LOG_LEVEL_ERROR,
2272 "No server or forwarder response received on socket %d.",
2273 csp->server_connection.sfd);
2274 send_crunch_response(csp, error_response(csp, "no-server-data"));
2276 free_http_request(http);
2277 mark_server_socket_tainted(csp);
2281 assert(csp->headers->first->str);
2283 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2284 strncmpic(csp->headers->first->str, "ICY", 3))
2287 * It doesn't look like a HTTP (or Shoutcast) response:
2288 * tell the client and log the problem.
2290 if (strlen(csp->headers->first->str) > 30)
2292 csp->headers->first->str[30] = '\0';
2294 log_error(LOG_LEVEL_ERROR,
2295 "Invalid server or forwarder response. Starts with: %s",
2296 csp->headers->first->str);
2297 log_error(LOG_LEVEL_CLF,
2298 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2299 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2300 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2301 free_http_request(http);
2302 mark_server_socket_tainted(csp);
2307 * We have now received the entire server header,
2308 * filter it and send the result to the client
2310 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2312 log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2314 hdr = list_to_text(csp->headers);
2317 /* FIXME Should handle error properly */
2318 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2321 if ((csp->flags & CSP_FLAG_CHUNKED)
2322 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2323 && ((csp->iob->eod - csp->iob->cur) >= 5)
2324 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2326 log_error(LOG_LEVEL_CONNECT,
2327 "Looks like we got the last chunk together with "
2328 "the server headers. We better stop reading.");
2329 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2330 csp->expected_content_length = byte_count;
2331 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2334 csp->server_connection.response_received = time(NULL);
2336 if (crunch_response_triggered(csp, crunchers_light))
2339 * One of the tags created by a server-header
2340 * tagger triggered a crunch. We already
2341 * delivered the crunch response to the client
2342 * and are done here after cleaning up.
2345 mark_server_socket_tainted(csp);
2348 /* Buffer and pcrs filter this if appropriate. */
2350 if (!http->ssl) /* We talk plaintext */
2352 buffer_and_filter_content = content_requires_filtering(csp);
2355 * Only write if we're not buffering for content modification
2357 if (!buffer_and_filter_content)
2360 * Write the server's (modified) header to
2361 * the client (along with anything else that
2362 * may be in the buffer)
2365 if (write_socket(csp->cfd, hdr, strlen(hdr))
2366 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2368 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2371 * The write failed, so don't bother mentioning it
2372 * to the client... it probably can't hear us anyway.
2375 mark_server_socket_tainted(csp);
2380 /* we're finished with the server's header */
2386 * If this was a MS IIS/5 hack then it means the server
2387 * has already closed the connection. Nothing more to read.
2392 log_error(LOG_LEVEL_ERROR,
2393 "Closed server connection detected. "
2394 "Applying the MS IIS5 hack didn't help.");
2395 log_error(LOG_LEVEL_CLF,
2396 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2397 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2398 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2399 mark_server_socket_tainted(csp);
2405 mark_server_socket_tainted(csp);
2406 return; /* huh? we should never get here */
2409 if (csp->content_length == 0)
2412 * If Privoxy didn't recalculate the Content-Length,
2413 * byte_count is still correct.
2415 csp->content_length = byte_count;
2418 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2419 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2420 && (csp->expected_content_length != byte_count))
2422 log_error(LOG_LEVEL_CONNECT,
2423 "Received %llu bytes while expecting %llu.",
2424 byte_count, csp->expected_content_length);
2425 mark_server_socket_tainted(csp);
2429 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2430 csp->ip_addr_str, http->ocmd, csp->content_length);
2432 csp->server_connection.timestamp = time(NULL);
2436 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2437 /*********************************************************************
2439 * Function : prepare_csp_for_next_request
2441 * Description : Put the csp in a mostly vergin state.
2444 * 1 : csp = Current client state (buffers, headers, etc...)
2448 *********************************************************************/
2449 static void prepare_csp_for_next_request(struct client_state *csp)
2451 csp->content_type = 0;
2452 csp->content_length = 0;
2453 csp->expected_content_length = 0;
2454 csp->expected_client_content_length = 0;
2455 list_remove_all(csp->headers);
2456 freez(csp->iob->buf);
2457 memset(csp->iob, 0, sizeof(csp->iob));
2458 freez(csp->error_message);
2459 free_http_request(csp->http);
2460 destroy_list(csp->headers);
2461 destroy_list(csp->tags);
2462 free_current_action(csp->action);
2463 if (NULL != csp->fwd)
2465 unload_forward_spec(csp->fwd);
2468 /* XXX: Store per-connection flags someplace else. */
2469 csp->flags &= CSP_FLAG_TOGGLED_ON;
2470 csp->flags |= CSP_FLAG_ACTIVE;
2471 csp->flags |= CSP_FLAG_REUSED_CLIENT_CONNECTION;
2473 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2476 /*********************************************************************
2480 * Description : This is little more than chat. We only "serve" to
2481 * to close (or remember) any socket that chat may have
2485 * 1 : csp = Current client state (buffers, headers, etc...)
2489 *********************************************************************/
2491 void serve(struct client_state *csp)
2492 #else /* ifndef AMIGA */
2493 static void serve(struct client_state *csp)
2494 #endif /* def AMIGA */
2496 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2497 #ifdef FEATURE_CONNECTION_SHARING
2498 static int monitor_thread_running = 0;
2499 #endif /* def FEATURE_CONNECTION_SHARING */
2500 int continue_chatting = 0;
2504 unsigned int latency;
2505 int config_file_change_detected = 0; /* Only used for debugging */
2510 * If the request has been crunched,
2511 * the calculated latency is zero.
2513 latency = (unsigned)(csp->server_connection.response_received -
2514 csp->server_connection.request_sent) / 2;
2516 continue_chatting = (csp->config->feature_flags
2517 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2518 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2519 && ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2520 || (csp->flags & CSP_FLAG_CRUNCHED))
2521 && (csp->cfd != JB_INVALID_SOCKET)
2522 && ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2523 || (csp->config->feature_flags &
2524 RUNTIME_FEATURE_CONNECTION_SHARING));
2526 if (continue_chatting && !(csp->flags & CSP_FLAG_CRUNCHED))
2528 continue_chatting = (csp->server_connection.sfd != JB_INVALID_SOCKET)
2529 && socket_is_still_alive(csp->server_connection.sfd);
2530 if (continue_chatting)
2532 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
2534 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
2535 log_error(LOG_LEVEL_CONNECT,
2536 "The server didn't specify how long the connection will stay open. "
2537 "Assumed timeout is: %u.", csp->server_connection.keep_alive_timeout);
2539 continue_chatting = (latency < csp->server_connection.keep_alive_timeout);
2543 if (continue_chatting && any_loaded_file_changed(csp->config->config_file_list))
2545 continue_chatting = 0;
2546 config_file_change_detected = 1;
2549 if (continue_chatting)
2551 unsigned int client_timeout = 1; /* XXX: Use something else here? */
2553 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
2555 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2557 client_timeout = (unsigned)csp->server_connection.keep_alive_timeout - latency;
2558 log_error(LOG_LEVEL_CONNECT,
2559 "Waiting for the next client request on socket %d. "
2560 "Keeping the server socket %d to %s open.",
2561 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2565 log_error(LOG_LEVEL_CONNECT,
2566 "Waiting for the next client request on socket %d. "
2567 "No server socket to keep open.", csp->cfd);
2570 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2571 && data_is_available(csp->cfd, (int)client_timeout)
2572 && socket_is_still_alive(csp->cfd))
2574 log_error(LOG_LEVEL_CONNECT,
2575 "Client request arrived in time on socket %d.", csp->cfd);
2576 prepare_csp_for_next_request(csp);
2580 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
2582 log_error(LOG_LEVEL_CONNECT,
2583 "No additional client request received in time on socket %d.",
2586 #ifdef FEATURE_CONNECTION_SHARING
2587 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2588 && (socket_is_still_alive(csp->server_connection.sfd)))
2590 time_t time_open = time(NULL) - csp->server_connection.timestamp;
2592 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
2597 remember_connection(&csp->server_connection);
2598 csp->server_connection.sfd = JB_INVALID_SOCKET;
2599 close_socket(csp->cfd);
2600 csp->cfd = JB_INVALID_SOCKET;
2601 privoxy_mutex_lock(&connection_reuse_mutex);
2602 if (!monitor_thread_running)
2604 monitor_thread_running = 1;
2605 privoxy_mutex_unlock(&connection_reuse_mutex);
2606 wait_for_alive_connections();
2607 privoxy_mutex_lock(&connection_reuse_mutex);
2608 monitor_thread_running = 0;
2610 privoxy_mutex_unlock(&connection_reuse_mutex);
2612 #endif /* def FEATURE_CONNECTION_SHARING */
2616 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2618 log_error(LOG_LEVEL_CONNECT,
2619 "The connection on server socket %d to %s isn't reusable. Closing. "
2620 "Server connection: keep-alive %u, tainted: %u, socket alive %u. "
2621 "Client connection: socket alive: %u. Server timeout: %u. "
2622 "Configuration file change detected: %u",
2623 csp->server_connection.sfd, csp->server_connection.host,
2624 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2625 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2626 socket_is_still_alive(csp->server_connection.sfd),
2627 socket_is_still_alive(csp->cfd),
2628 csp->server_connection.keep_alive_timeout,
2629 config_file_change_detected);
2631 } while (continue_chatting);
2635 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2637 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2639 #ifdef FEATURE_CONNECTION_SHARING
2640 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2642 forget_connection(csp->server_connection.sfd);
2644 #endif /* def FEATURE_CONNECTION_SHARING */
2645 close_socket(csp->server_connection.sfd);
2648 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2649 mark_connection_closed(&csp->server_connection);
2652 if (csp->cfd != JB_INVALID_SOCKET)
2654 close_socket(csp->cfd);
2657 csp->flags &= ~CSP_FLAG_ACTIVE;
2663 /*********************************************************************
2665 * Function : server_thread
2667 * Description : We only exist to call `serve' in a threaded environment.
2670 * 1 : data = Current client state (buffers, headers, etc...)
2672 * Returns : Always 0.
2674 *********************************************************************/
2675 static int32 server_thread(void *data)
2677 serve((struct client_state *) data);
2684 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2685 /*********************************************************************
2689 * Description : Print usage info & exit.
2691 * Parameters : Pointer to argv[0] for identifying ourselves
2695 *********************************************************************/
2696 static void usage(const char *myname)
2698 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
2702 #endif /* defined(unix) */
2705 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
2706 #endif /* defined(unix) */
2707 "[--version] [configfile]\n"
2708 "Aborting\n", myname);
2713 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
2716 #ifdef MUTEX_LOCKS_AVAILABLE
2717 /*********************************************************************
2719 * Function : privoxy_mutex_lock
2721 * Description : Locks a mutex.
2724 * 1 : mutex = The mutex to lock.
2726 * Returns : Void. May exit in case of errors.
2728 *********************************************************************/
2729 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
2731 #ifdef FEATURE_PTHREAD
2732 int err = pthread_mutex_lock(mutex);
2735 if (mutex != &log_mutex)
2737 log_error(LOG_LEVEL_FATAL,
2738 "Mutex locking failed: %s.\n", strerror(err));
2743 EnterCriticalSection(mutex);
2744 #endif /* def FEATURE_PTHREAD */
2748 /*********************************************************************
2750 * Function : privoxy_mutex_unlock
2752 * Description : Unlocks a mutex.
2755 * 1 : mutex = The mutex to unlock.
2757 * Returns : Void. May exit in case of errors.
2759 *********************************************************************/
2760 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
2762 #ifdef FEATURE_PTHREAD
2763 int err = pthread_mutex_unlock(mutex);
2766 if (mutex != &log_mutex)
2768 log_error(LOG_LEVEL_FATAL,
2769 "Mutex unlocking failed: %s.\n", strerror(err));
2774 LeaveCriticalSection(mutex);
2775 #endif /* def FEATURE_PTHREAD */
2779 /*********************************************************************
2781 * Function : privoxy_mutex_init
2783 * Description : Prepares a mutex.
2786 * 1 : mutex = The mutex to initialize.
2788 * Returns : Void. May exit in case of errors.
2790 *********************************************************************/
2791 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
2793 #ifdef FEATURE_PTHREAD
2794 int err = pthread_mutex_init(mutex, 0);
2797 printf("Fatal error. Mutex initialization failed: %s.\n",
2802 InitializeCriticalSection(mutex);
2803 #endif /* def FEATURE_PTHREAD */
2805 #endif /* def MUTEX_LOCKS_AVAILABLE */
2807 /*********************************************************************
2809 * Function : initialize_mutexes
2811 * Description : Prepares mutexes if mutex support is available.
2815 * Returns : Void, exits in case of errors.
2817 *********************************************************************/
2818 static void initialize_mutexes(void)
2820 #ifdef MUTEX_LOCKS_AVAILABLE
2822 * Prepare global mutex semaphores
2824 privoxy_mutex_init(&log_mutex);
2825 privoxy_mutex_init(&log_init_mutex);
2826 privoxy_mutex_init(&connection_reuse_mutex);
2829 * XXX: The assumptions below are a bit naive
2830 * and can cause locks that aren't necessary.
2832 * For example older FreeBSD versions (< 6.x?)
2833 * have no gethostbyname_r, but gethostbyname is
2836 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
2837 privoxy_mutex_init(&resolver_mutex);
2838 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
2840 * XXX: should we use a single mutex for
2841 * localtime() and gmtime() as well?
2843 #ifndef HAVE_GMTIME_R
2844 privoxy_mutex_init(&gmtime_mutex);
2845 #endif /* ndef HAVE_GMTIME_R */
2847 #ifndef HAVE_LOCALTIME_R
2848 privoxy_mutex_init(&localtime_mutex);
2849 #endif /* ndef HAVE_GMTIME_R */
2852 privoxy_mutex_init(&rand_mutex);
2853 #endif /* ndef HAVE_RANDOM */
2856 privoxy_mutex_init(&strtok_mutex);
2857 #endif /* def HAVE_STRTOK */
2858 #endif /* def MUTEX_LOCKS_AVAILABLE */
2862 /*********************************************************************
2866 * Description : Load the config file and start the listen loop.
2867 * This function is a lot more *sane* with the `load_config'
2868 * and `listen_loop' functions; although it stills does
2869 * a *little* too much for my taste.
2872 * 1 : argc = Number of parameters (including $0).
2873 * 2 : argv = Array of (char *)'s to the parameters.
2875 * Returns : 1 if : can't open config file, unrecognized directive,
2876 * stats requested in multi-thread mode, can't open the
2877 * log file, can't open the jar file, listen port is invalid,
2878 * any load fails, and can't bind port.
2880 * Else main never returns, the process must be signaled
2881 * to terminate execution. Or, on Windows, use the
2882 * "File", "Exit" menu option.
2884 *********************************************************************/
2886 int real_main(int argc, char **argv)
2888 int main(int argc, char **argv)
2892 unsigned int random_seed;
2894 struct passwd *pw = NULL;
2895 struct group *grp = NULL;
2897 char *pre_chroot_nslookup_to_load_resolver = NULL;
2904 #if !defined(_WIN32)
2911 /* Prepare mutexes if supported and necessary. */
2912 initialize_mutexes();
2914 /* Enable logging until further notice. */
2918 * Parse the command line arguments
2920 * XXX: simply printing usage information in case of
2921 * invalid arguments isn't particularly user friendly.
2923 while (++argc_pos < argc)
2926 /* Check to see if the service must be installed or uninstalled */
2927 if (strncmp(argv[argc_pos], "--install", 9) == 0)
2929 const char *pName = argv[argc_pos] + 9;
2932 exit( (install_service(pName)) ? 0 : 1 );
2934 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
2936 const char *pName = argv[argc_pos] + 11;
2939 exit((uninstall_service(pName)) ? 0 : 1);
2941 else if (strcmp(argv[argc_pos], "--service" ) == 0)
2943 bRunAsService = TRUE;
2944 w32_set_service_cwd();
2945 atexit(w32_service_exit_notify);
2948 #endif /* defined(_WIN32) */
2951 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2953 if (strcmp(argv[argc_pos], "--help") == 0)
2958 else if(strcmp(argv[argc_pos], "--version") == 0)
2960 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2966 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
2968 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
2972 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
2974 if (++argc_pos == argc) usage(argv[0]);
2975 pidfile = strdup(argv[argc_pos]);
2978 else if (strcmp(argv[argc_pos], "--user" ) == 0)
2983 if (++argc_pos == argc) usage(argv[argc_pos]);
2985 user_arg = strdup(argv[argc_pos]);
2986 if (NULL == user_arg)
2988 log_error(LOG_LEVEL_FATAL,
2989 "Out of memory splitting --user argument '%s'.", argv[argc_pos]);
2991 group_name = strchr(user_arg, '.');
2992 if (NULL != group_name)
2994 /* Nul-terminate the user name */
2997 /* Skip the former delimiter to actually reach the group name */
3000 grp = getgrnam(group_name);
3003 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3006 pw = getpwnam(user_arg);
3009 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3015 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup" ) == 0)
3017 if (++argc_pos == argc) usage(argv[0]);
3018 pre_chroot_nslookup_to_load_resolver = strdup(argv[argc_pos]);
3021 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
3025 #endif /* defined(unix) */
3027 else if (argc_pos + 1 != argc)
3030 * This is neither the last command line
3031 * option, nor was it recognized before,
3032 * therefore it must be invalid.
3038 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3040 configfile = argv[argc_pos];
3043 } /* -END- while (more arguments) */
3045 show_version(Argv[0]);
3048 if ( *configfile != '/' )
3050 char cwd[BUFFER_SIZE];
3052 size_t abs_file_size;
3054 /* make config-filename absolute here */
3055 if (NULL == getcwd(cwd, sizeof(cwd)))
3057 perror("failed to get current working directory");
3062 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3063 basedir = strdup(cwd);
3065 if (NULL == basedir ||
3066 NULL == (abs_file = malloc(abs_file_size)))
3068 perror("malloc failed");
3071 strlcpy(abs_file, basedir, abs_file_size);
3072 strlcat(abs_file, "/", abs_file_size );
3073 strlcat(abs_file, configfile, abs_file_size);
3074 configfile = abs_file;
3076 #endif /* defined unix */
3080 clients->next = NULL;
3082 /* XXX: factor out initialising after the next stable release. */
3085 #elif defined(_WIN32)
3089 random_seed = (unsigned int)time(NULL);
3091 srandom(random_seed);
3094 #endif /* ifdef HAVE_RANDOM */
3097 * Unix signal handling
3099 * Catch the abort, interrupt and terminate signals for a graceful exit
3100 * Catch the hangup signal so the errlog can be reopened.
3101 * Ignore the broken pipe signals (FIXME: Why?)
3103 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3106 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3108 for (idx = 0; idx < SZ(catched_signals); idx++)
3110 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3111 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3113 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3114 #endif /* ifdef sun */
3116 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3120 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3122 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3126 #else /* ifdef _WIN32 */
3127 # ifdef _WIN_CONSOLE
3129 * We *are* in a windows console app.
3130 * Print a verbose messages about FAQ's and such
3132 printf("%s", win32_blurb);
3133 # endif /* def _WIN_CONSOLE */
3134 #endif /* def _WIN32 */
3137 /* Initialize the CGI subsystem */
3138 cgi_init_error_messages();
3141 * If runnig on unix and without the --nodaemon
3142 * option, become a daemon. I.e. fork, detach
3143 * from tty and get process group leadership
3152 if ( pid < 0 ) /* error */
3157 else if ( pid != 0 ) /* parent */
3162 * must check for errors
3163 * child died due to missing files aso
3166 wpid = waitpid( pid, &status, WNOHANG );
3178 * stderr (fd 2) will be closed later on,
3179 * when the config file has been parsed.
3185 * Reserve fd 0 and 1 to prevent abort() and friends
3186 * from sending stuff to the clients or servers.
3188 fd = open("/dev/null", O_RDONLY);
3191 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3195 if (dup2(fd, 0) == -1)
3197 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3201 fd = open("/dev/null", O_WRONLY);
3204 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3208 if (dup2(fd, 1) == -1)
3210 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3217 } /* -END- if (daemon_mode) */
3220 * As soon as we have written the PID file, we can switch
3221 * to the user and group ID indicated by the --user option
3227 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3229 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3233 if (setgroups(1, &grp->gr_gid))
3235 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3238 else if (initgroups(pw->pw_name, pw->pw_gid))
3240 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3246 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3248 /* Read the time zone file from /etc before doing chroot. */
3250 if (NULL != pre_chroot_nslookup_to_load_resolver
3251 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3253 /* Initialize resolver library. */
3254 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3256 if (chroot(pw->pw_dir) < 0)
3258 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3262 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3265 if (setuid(pw->pw_uid))
3267 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3271 char putenv_dummy[64];
3273 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3274 if (putenv(putenv_dummy) != 0)
3276 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3279 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3280 if (putenv(putenv_dummy) != 0)
3282 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3288 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3291 #endif /* defined unix */
3294 /* This will be FALSE unless the command line specified --service
3298 /* Yup, so now we must attempt to establish a connection
3299 * with the service dispatcher. This will only work if this
3300 * process was launched by the service control manager to
3301 * actually run as a service. If this isn't the case, i've
3302 * known it take around 30 seconds or so for the call to return.
3305 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3306 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3308 /* Service has run, and at this point is now being stopped, so just return */
3313 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3315 /* An error occurred. Usually it's because --service was wrongly specified
3316 * and we were unable to connect to the Service Control Dispatcher because
3317 * it wasn't expecting us and is therefore not listening.
3319 * For now, just continue below to call the listen_loop function.
3322 #endif /* def _WIN32 */
3332 /*********************************************************************
3334 * Function : bind_port_helper
3336 * Description : Bind the listen port. Handles logging, and aborts
3340 * 1 : haddr = Host addres to bind to. Use NULL to bind to
3342 * 2 : hport = Specifies port to bind to.
3344 * Returns : Port that was opened.
3346 *********************************************************************/
3347 static jb_socket bind_port_helper(const char *haddr, int hport)
3352 result = bind_port(haddr, hport, &bfd);
3356 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
3360 log_error(LOG_LEVEL_FATAL,
3361 "can't bind to %s:%d: There may be another Privoxy "
3362 "or some other proxy running on port %d",
3363 bind_address, hport, hport);
3366 log_error(LOG_LEVEL_FATAL,
3367 "can't bind to %s:%d: The hostname is not resolvable",
3368 bind_address, hport);
3371 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3372 bind_address, hport);
3375 /* shouldn't get here */
3376 return JB_INVALID_SOCKET;
3381 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3386 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3394 /*********************************************************************
3396 * Function : bind_ports_helper
3398 * Description : Bind the listen ports. Handles logging, and aborts
3402 * 1 : config = Privoxy configuration. Specifies ports
3404 * 2 : sockets = Preallocated array of opened sockets
3405 * corresponding to specification in config.
3406 * All non-opened sockets will be set to
3407 * JB_INVALID_SOCKET.
3409 * Returns : Nothing. Inspect sockets argument.
3411 *********************************************************************/
3412 static void bind_ports_helper(struct configuration_spec * config,
3413 jb_socket sockets[])
3417 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3419 if (config->hport[i])
3421 sockets[i] = bind_port_helper(config->haddr[i], config->hport[i]);
3425 sockets[i] = JB_INVALID_SOCKET;
3428 config->need_bind = 0;
3432 /*********************************************************************
3434 * Function : close_ports_helper
3436 * Description : Close listenings ports.
3439 * 1 : sockets = Array of opened and non-opened sockets to
3440 * close. All sockets will be set to
3441 * JB_INVALID_SOCKET.
3443 * Returns : Nothing.
3445 *********************************************************************/
3446 static void close_ports_helper(jb_socket sockets[])
3450 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3452 if (JB_INVALID_SOCKET != sockets[i])
3454 close_socket(sockets[i]);
3456 sockets[i] = JB_INVALID_SOCKET;
3462 /* Without this simple workaround we get this compiler warning from _beginthread
3463 * warning C4028: formal parameter 1 different from declaration
3465 void w32_service_listen_loop(void *p)
3469 #endif /* def _WIN32 */
3472 /*********************************************************************
3474 * Function : listen_loop
3476 * Description : bind the listen port and enter a "FOREVER" listening loop.
3482 *********************************************************************/
3483 static void listen_loop(void)
3485 struct client_states *csp_list = NULL;
3486 struct client_state *csp = NULL;
3487 jb_socket bfds[MAX_LISTENING_SOCKETS];
3488 struct configuration_spec *config;
3489 unsigned int active_threads = 0;
3491 config = load_config();
3493 #ifdef FEATURE_CONNECTION_SHARING
3495 * XXX: Should be relocated once it no
3496 * longer needs to emit log messages.
3498 initialize_reusable_connections();
3499 #endif /* def FEATURE_CONNECTION_SHARING */
3501 bind_ports_helper(config, bfds);
3503 #ifdef FEATURE_GRACEFUL_TERMINATION
3504 while (!g_terminate)
3509 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3510 while (waitpid(-1, NULL, WNOHANG) > 0)
3512 /* zombie children */
3514 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3517 * Free data that was used by died threads
3519 active_threads = sweep();
3523 * Re-open the errlog after HUP signal
3525 if (received_hup_signal)
3527 if (NULL != config->logfile)
3529 init_error_log(Argv[0], config->logfile);
3531 received_hup_signal = 0;
3535 csp_list = (struct client_states *)zalloc(sizeof(*csp_list));
3536 if (NULL == csp_list)
3538 log_error(LOG_LEVEL_FATAL,
3539 "malloc(%d) for csp_list failed: %E", sizeof(*csp_list));
3542 csp = &csp_list->csp;
3544 log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
3546 if (!accept_connection(csp, bfds))
3548 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3561 log_error(LOG_LEVEL_CONNECT,
3562 "accepted connection from %s on socket %d",
3563 csp->ip_addr_str, csp->cfd);
3566 csp->flags |= CSP_FLAG_ACTIVE;
3567 csp->server_connection.sfd = JB_INVALID_SOCKET;
3569 csp->config = config = load_config();
3571 if (config->need_bind)
3574 * Since we were listening to the "old port", we will not see
3575 * a "listen" param change until the next request. So, at
3576 * least 1 more request must be made for us to find the new
3577 * setting. I am simply closing the old socket and binding the
3580 * Which-ever is correct, we will serve 1 more page via the
3581 * old settings. This should probably be a "show-proxy-args"
3582 * request. This should not be a so common of an operation
3583 * that this will hurt people's feelings.
3586 close_ports_helper(bfds);
3588 bind_ports_helper(config, bfds);
3591 #ifdef FEATURE_TOGGLE
3592 if (global_toggle_state)
3593 #endif /* def FEATURE_TOGGLE */
3595 csp->flags |= CSP_FLAG_TOGGLED_ON;
3598 if (run_loader(csp))
3600 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3601 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3605 if (block_acl(NULL,csp))
3607 log_error(LOG_LEVEL_CONNECT,
3608 "Connection from %s on socket %d dropped due to ACL", csp->ip_addr_str, csp->cfd);
3609 close_socket(csp->cfd);
3610 freez(csp->ip_addr_str);
3614 #endif /* def FEATURE_ACL */
3616 if ((0 != config->max_client_connections)
3617 && (active_threads >= config->max_client_connections))
3619 log_error(LOG_LEVEL_CONNECT,
3620 "Rejecting connection from %s. Maximum number of connections reached.",
3622 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3623 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3624 close_socket(csp->cfd);
3625 freez(csp->ip_addr_str);
3630 /* add it to the list of clients */
3631 csp_list->next = clients->next;
3632 clients->next = csp_list;
3634 if (config->multi_threaded)
3638 /* this is a switch () statement in the C preprocessor - ugh */
3639 #undef SELECTED_ONE_OPTION
3641 /* Use Pthreads in preference to native code */
3642 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
3643 #define SELECTED_ONE_OPTION
3645 pthread_t the_thread;
3646 pthread_attr_t attrs;
3648 pthread_attr_init(&attrs);
3649 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
3650 errno = pthread_create(&the_thread, &attrs,
3651 (void * (*)(void *))serve, csp);
3652 child_id = errno ? -1 : 0;
3653 pthread_attr_destroy(&attrs);
3657 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
3658 #define SELECTED_ONE_OPTION
3659 child_id = _beginthread(
3660 (void (*)(void *))serve,
3665 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
3666 #define SELECTED_ONE_OPTION
3667 child_id = _beginthread(
3668 (void(* _Optlink)(void*))serve,
3674 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
3675 #define SELECTED_ONE_OPTION
3677 thread_id tid = spawn_thread
3678 (server_thread, "server", B_NORMAL_PRIORITY, csp);
3680 if ((tid >= 0) && (resume_thread(tid) == B_OK))
3682 child_id = (int) tid;
3691 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
3692 #define SELECTED_ONE_OPTION
3693 csp->cfd = ReleaseSocket(csp->cfd, -1);
3696 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3697 NP_Output, Output(),
3698 NP_CloseOutput, FALSE,
3699 NP_Name, (ULONG)"privoxy child",
3703 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3704 NP_Output, Output(),
3705 NP_CloseOutput, FALSE,
3706 NP_Name, (ULONG)"privoxy child",
3707 NP_StackSize, 200*1024,
3713 ((struct Task *)child_id)->tc_UserData = csp;
3714 Signal((struct Task *)child_id, SIGF_SINGLE);
3719 #if !defined(SELECTED_ONE_OPTION)
3722 /* This block is only needed when using fork().
3723 * When using threads, the server thread was
3724 * created and run by the call to _beginthread().
3726 if (child_id == 0) /* child */
3729 #ifdef FEATURE_TOGGLE
3730 int inherited_toggle_state = global_toggle_state;
3731 #endif /* def FEATURE_TOGGLE */
3736 * If we've been toggled or we've blocked the request, tell Mom
3739 #ifdef FEATURE_TOGGLE
3740 if (inherited_toggle_state != global_toggle_state)
3742 rc |= RC_FLAG_TOGGLED;
3744 #endif /* def FEATURE_TOGGLE */
3746 #ifdef FEATURE_STATISTICS
3747 if (csp->flags & CSP_FLAG_REJECTED)
3749 rc |= RC_FLAG_BLOCKED;
3751 #endif /* ndef FEATURE_STATISTICS */
3755 else if (child_id > 0) /* parent */
3757 /* in a fork()'d environment, the parent's
3758 * copy of the client socket and the CSP
3762 #if !defined(_WIN32) && !defined(__CYGWIN__)
3764 wait( &child_status );
3767 * Evaluate child's return code: If the child has
3768 * - been toggled, toggle ourselves
3769 * - blocked its request, bump up the stats counter
3772 #ifdef FEATURE_TOGGLE
3773 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
3775 global_toggle_state = !global_toggle_state;
3777 #endif /* def FEATURE_TOGGLE */
3779 #ifdef FEATURE_STATISTICS
3781 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
3785 #endif /* def FEATURE_STATISTICS */
3787 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
3788 close_socket(csp->cfd);
3789 csp->flags &= ~CSP_FLAG_ACTIVE;
3793 #undef SELECTED_ONE_OPTION
3794 /* end of cpp switch () */
3799 * Spawning the child failed, assume it's because
3800 * there are too many children running already.
3801 * XXX: If you assume ...
3803 log_error(LOG_LEVEL_ERROR,
3804 "Unable to take any additional connections: %E");
3805 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3806 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3807 close_socket(csp->cfd);
3808 csp->flags &= ~CSP_FLAG_ACTIVE;
3817 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
3819 /* Clean up. Aim: free all memory (no leaks) */
3820 #ifdef FEATURE_GRACEFUL_TERMINATION
3822 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
3824 unload_current_config_file();
3825 unload_current_actions_file();
3826 unload_current_re_filterfile();
3827 #ifdef FEATURE_TRUST
3828 unload_current_trust_file();
3831 if (config->multi_threaded)
3838 } while ((clients->next != NULL) && (--i > 0));
3842 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
3852 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
3853 /* Cleanup - remove taskbar icon etc. */
3858 #endif /* FEATURE_GRACEFUL_TERMINATION */