1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
5 * Purpose : Main file. Contains main() method, main loop, and
6 * the main connection-handling function.
8 * Copyright : Written by and Copyright (C) 2001-2017 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 # ifndef FEATURE_PTHREAD
52 # include <winsock2.h>
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 */
102 #endif /* def __GLIBC__ */
107 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
108 #endif /* HAVE_POLL */
118 #include "miscutil.h"
120 #include "jbsockets.h"
125 #include "urlmatch.h"
126 #ifdef FEATURE_CLIENT_TAGS
127 #include "client-tags.h"
131 struct client_states clients[1];
132 struct file_list files[1];
134 #ifdef FEATURE_STATISTICS
135 int urls_read = 0; /* total nr of urls read inc rejected */
136 int urls_rejected = 0; /* total nr of urls rejected */
137 #endif /* def FEATURE_STATISTICS */
139 #ifdef FEATURE_GRACEFUL_TERMINATION
143 #if !defined(_WIN32) && !defined(__OS2__)
144 static void sig_handler(int the_signal);
146 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
147 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
148 static jb_err get_server_headers(struct client_state *csp);
149 static const char *crunch_reason(const struct http_response *rsp);
150 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
151 static char *get_request_line(struct client_state *csp);
152 static jb_err receive_client_request(struct client_state *csp);
153 static jb_err parse_client_request(struct client_state *csp);
154 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
155 static jb_err change_request_destination(struct client_state *csp);
156 static void chat(struct client_state *csp);
157 static void serve(struct client_state *csp);
158 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
159 static void usage(const char *myname);
161 static void initialize_mutexes(void);
162 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
163 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
164 static void close_ports_helper(jb_socket sockets[]);
165 static void listen_loop(void);
166 static void serve(struct client_state *csp);
169 static int32 server_thread(void *data);
170 #endif /* def __BEOS__ */
173 #define sleep(N) Sleep(((N) * 1000))
177 #define sleep(N) DosSleep(((N) * 100))
181 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
182 void show_fuzz_usage(const char *name);
185 #ifdef MUTEX_LOCKS_AVAILABLE
187 * XXX: Does the locking stuff really belong in this file?
189 privoxy_mutex_t log_mutex;
190 privoxy_mutex_t log_init_mutex;
191 privoxy_mutex_t connection_reuse_mutex;
193 #ifdef FEATURE_EXTERNAL_FILTERS
194 privoxy_mutex_t external_filter_mutex;
196 #ifdef FEATURE_CLIENT_TAGS
197 privoxy_mutex_t client_tags_mutex;
200 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
201 privoxy_mutex_t resolver_mutex;
202 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
204 #ifndef HAVE_GMTIME_R
205 privoxy_mutex_t gmtime_mutex;
206 #endif /* ndef HAVE_GMTIME_R */
208 #ifndef HAVE_LOCALTIME_R
209 privoxy_mutex_t localtime_mutex;
210 #endif /* ndef HAVE_GMTIME_R */
212 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
213 privoxy_mutex_t rand_mutex;
214 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
216 #endif /* def MUTEX_LOCKS_AVAILABLE */
219 const char *basedir = NULL;
220 const char *pidfile = NULL;
221 static int received_hup_signal = 0;
222 #endif /* defined unix */
224 /* HTTP snipplets. */
225 static const char CSUCCEED[] =
226 "HTTP/1.1 200 Connection established\r\n\r\n";
228 static const char CHEADER[] =
229 "HTTP/1.1 400 Invalid header received from client\r\n"
230 "Content-Type: text/plain\r\n"
231 "Connection: close\r\n\r\n"
232 "Invalid header received from client.\r\n";
234 static const char FTP_RESPONSE[] =
235 "HTTP/1.1 400 Invalid request received from client\r\n"
236 "Content-Type: text/plain\r\n"
237 "Connection: close\r\n\r\n"
238 "Invalid request. Privoxy doesn't support FTP.\r\n";
240 static const char GOPHER_RESPONSE[] =
241 "HTTP/1.1 400 Invalid request received from client\r\n"
242 "Content-Type: text/plain\r\n"
243 "Connection: close\r\n\r\n"
244 "Invalid request. Privoxy doesn't support gopher.\r\n";
246 /* XXX: should be a template */
247 static const char MISSING_DESTINATION_RESPONSE[] =
248 "HTTP/1.1 400 Bad request received from client\r\n"
249 "Content-Type: text/plain\r\n"
250 "Connection: close\r\n\r\n"
251 "Bad request. Privoxy was unable to extract the destination.\r\n";
253 /* XXX: should be a template */
254 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
255 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
256 "Content-Type: text/plain\r\n"
257 "Connection: close\r\n\r\n"
258 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
260 /* XXX: should be a template */
261 static const char MESSED_UP_REQUEST_RESPONSE[] =
262 "HTTP/1.1 400 Malformed request after rewriting\r\n"
263 "Content-Type: text/plain\r\n"
264 "Connection: close\r\n\r\n"
265 "Bad request. Messed up with header filters.\r\n";
267 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
268 "HTTP/1.1 503 Too many open connections\r\n"
269 "Content-Type: text/plain\r\n"
270 "Connection: close\r\n\r\n"
271 "Maximum number of open connections reached.\r\n";
273 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
274 "HTTP/1.1 504 Connection timeout\r\n"
275 "Content-Type: text/plain\r\n"
276 "Connection: close\r\n\r\n"
277 "The connection timed out because the client request didn't arrive in time.\r\n";
279 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
280 "HTTP/1.1 400 Failed reading client body\r\n"
281 "Content-Type: text/plain\r\n"
282 "Connection: close\r\n\r\n"
283 "Failed parsing or buffering the chunk-encoded client body.\r\n";
285 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
286 "HTTP/1.1 417 Expecting too much\r\n"
287 "Content-Type: text/plain\r\n"
288 "Connection: close\r\n\r\n"
289 "Privoxy detected an unsupported Expect header value.\r\n";
291 /* A function to crunch a response */
292 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
294 /* Crunch function flags */
295 #define CF_NO_FLAGS 0
296 /* Cruncher applies to forced requests as well */
297 #define CF_IGNORE_FORCE 1
298 /* Crunched requests are counted for the block statistics */
299 #define CF_COUNT_AS_REJECT 2
301 /* A crunch function and its flags */
304 const crunch_func_ptr cruncher;
308 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
310 /* Complete list of cruncher functions */
311 static const struct cruncher crunchers_all[] = {
312 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
313 { block_url, CF_COUNT_AS_REJECT },
315 { trust_url, CF_COUNT_AS_REJECT },
316 #endif /* def FEATURE_TRUST */
317 { redirect_url, CF_NO_FLAGS },
318 { dispatch_cgi, CF_IGNORE_FORCE},
322 /* Light version, used after tags are applied */
323 static const struct cruncher crunchers_light[] = {
324 { block_url, CF_COUNT_AS_REJECT },
325 { redirect_url, CF_NO_FLAGS },
331 * XXX: Don't we really mean
337 #if !defined(_WIN32) && !defined(__OS2__)
338 /*********************************************************************
340 * Function : sig_handler
342 * Description : Signal handler for different signals.
343 * Exit gracefully on TERM and INT
344 * or set a flag that will cause the errlog
345 * to be reopened by the main thread on HUP.
348 * 1 : the_signal = the signal cause this function to call
352 *********************************************************************/
353 static void sig_handler(int the_signal)
359 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
371 received_hup_signal = 1;
377 * We shouldn't be here, unless we catch signals
378 * in main() that we can't handle here!
380 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
388 /*********************************************************************
390 * Function : client_protocol_is_unsupported
392 * Description : Checks if the client used a known unsupported
393 * protocol and deals with it by sending an error
397 * 1 : csp = Current client state (buffers, headers, etc...)
398 * 2 : req = the first request line send by the client
400 * Returns : TRUE if an error response has been generated, or
401 * FALSE if the request doesn't look invalid.
403 *********************************************************************/
404 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
407 * If it's a FTP or gopher request, we don't support it.
409 * These checks are better than nothing, but they might
410 * not work in all configurations and some clients might
411 * have problems digesting the answer.
413 * They should, however, never cause more problems than
414 * Privoxy's old behaviour (returning the misleading HTML
417 * "Could not resolve http://(ftp|gopher)://example.org").
419 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
421 const char *response = NULL;
422 const char *protocol = NULL;
424 if (!strncmpic(req, "GET ftp://", 10))
426 response = FTP_RESPONSE;
431 response = GOPHER_RESPONSE;
434 log_error(LOG_LEVEL_ERROR,
435 "%s tried to use Privoxy as %s proxy: %s",
436 csp->ip_addr_str, protocol, req);
437 log_error(LOG_LEVEL_CLF,
438 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
440 write_socket(csp->cfd, response, strlen(response));
449 /*********************************************************************
451 * Function : client_has_unsupported_expectations
453 * Description : Checks if the client used an unsupported expectation
454 * in which case an error message is delivered.
457 * 1 : csp = Current client state (buffers, headers, etc...)
459 * Returns : TRUE if an error response has been generated, or
460 * FALSE if the request doesn't look invalid.
462 *********************************************************************/
463 static int client_has_unsupported_expectations(const struct client_state *csp)
465 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
467 log_error(LOG_LEVEL_ERROR,
468 "Rejecting request from client %s with unsupported Expect header value",
470 log_error(LOG_LEVEL_CLF,
471 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
472 write_socket(csp->cfd, UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
473 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE));
483 /*********************************************************************
485 * Function : get_request_destination_elsewhere
487 * Description : If the client's request was redirected into
488 * Privoxy without the client's knowledge,
489 * the request line lacks the destination host.
491 * This function tries to get it elsewhere,
492 * provided accept-intercepted-requests is enabled.
494 * "Elsewhere" currently only means "Host: header",
495 * but in the future we may ask the redirecting
496 * packet filter to look the destination up.
498 * If the destination stays unknown, an error
499 * response is send to the client and headers
500 * are freed so that chat() can return directly.
503 * 1 : csp = Current client state (buffers, headers, etc...)
504 * 2 : headers = a header list
506 * Returns : JB_ERR_OK if the destination is now known, or
507 * JB_ERR_PARSE if it isn't.
509 *********************************************************************/
510 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
514 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
516 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
517 " Privoxy isn't configured to accept intercepted requests.",
518 csp->ip_addr_str, csp->http->cmd);
519 /* XXX: Use correct size */
520 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
521 csp->ip_addr_str, csp->http->cmd);
523 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
524 destroy_list(headers);
528 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
530 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
531 /* Split the domain we just got for pattern matching */
532 init_domain_components(csp->http);
539 /* We can't work without destination. Go spread the news.*/
541 req = list_to_text(headers);
543 /* XXX: Use correct size */
544 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
545 csp->ip_addr_str, csp->http->cmd);
546 log_error(LOG_LEVEL_ERROR,
547 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
548 csp->ip_addr_str, csp->http->cmd, req);
551 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
552 destroy_list(headers);
557 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
558 * to get the destination IP address, use it as host directly
559 * or do a reverse DNS lookup first.
564 /*********************************************************************
566 * Function : get_server_headers
568 * Description : Parses server headers in iob and fills them
569 * into csp->headers so that they can later be
573 * 1 : csp = Current client state (buffers, headers, etc...)
575 * Returns : JB_ERR_OK if everything went fine, or
576 * JB_ERR_PARSE if the headers were incomplete.
578 *********************************************************************/
579 static jb_err get_server_headers(struct client_state *csp)
581 int continue_hack_in_da_house = 0;
584 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
589 * continue hack in da house. Ignore the ending of
590 * this head and continue enlisting header lines.
591 * The reason is described below.
593 enlist(csp->headers, "");
594 continue_hack_in_da_house = 0;
597 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
600 * It's a bodyless continue response, don't
601 * stop header parsing after reaching its end.
603 * As a result Privoxy will concatenate the
604 * next response's head and parse and deliver
605 * the headers as if they belonged to one request.
607 * The client will separate them because of the
608 * empty line between them.
610 * XXX: What we're doing here is clearly against
611 * the intended purpose of the continue header,
612 * and under some conditions (HTTP/1.0 client request)
613 * it's a standard violation.
615 * Anyway, "sort of against the spec" is preferable
616 * to "always getting confused by Continue responses"
617 * (Privoxy's behaviour before this hack was added)
619 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
620 continue_hack_in_da_house = 1;
622 else if (*header == '\0')
625 * If the header is empty, but the Continue hack
626 * isn't active, we can assume that we reached the
627 * end of the buffer before we hit the end of the
630 * Inform the caller an let it decide how to handle it.
635 if (JB_ERR_MEMORY == enlist(csp->headers, header))
638 * XXX: Should we quit the request and return a
639 * out of memory error page instead?
641 log_error(LOG_LEVEL_ERROR,
642 "Out of memory while enlisting server headers. %s lost.",
652 /*********************************************************************
654 * Function : crunch_reason
656 * Description : Translates the crunch reason code into a string.
659 * 1 : rsp = a http_response
661 * Returns : A string with the crunch reason or an error description.
663 *********************************************************************/
664 static const char *crunch_reason(const struct http_response *rsp)
666 char * reason = NULL;
671 return "Internal error while searching for crunch reason";
674 switch (rsp->crunch_reason)
677 reason = "Unsupported HTTP feature";
683 reason = "Untrusted";
686 reason = "Redirected";
692 reason = "DNS failure";
694 case FORWARDING_FAILED:
695 reason = "Forwarding failed";
698 reason = "Connection failure";
701 reason = "Out of memory (may mask other reasons)";
703 case CONNECTION_TIMEOUT:
704 reason = "Connection timeout";
707 reason = "No server data received";
710 reason = "No reason recorded";
718 /*********************************************************************
720 * Function : log_applied_actions
722 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
726 * 1 : actions = Current action spec to log
730 *********************************************************************/
731 static void log_applied_actions(const struct current_action_spec *actions)
734 * The conversion to text requires lots of memory allocations so
735 * we only do the conversion if the user is actually interested.
737 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
739 char *actions_as_text = actions_to_line_of_text(actions);
740 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
741 freez(actions_as_text);
746 /*********************************************************************
748 * Function : send_crunch_response
750 * Description : Delivers already prepared response for
751 * intercepted requests, logs the interception
752 * and frees the response.
755 * 1 : csp = Current client state (buffers, headers, etc...)
756 * 2 : rsp = Fully prepared response. Will be freed on exit.
760 *********************************************************************/
761 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
763 const struct http_request *http = csp->http;
767 assert(rsp->head != NULL);
771 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
775 * Extract the status code from the actual head
776 * that will be send to the client. It is the only
777 * way to get it right for all requests, including
778 * the fixed ones for out-of-memory problems.
780 * A head starts like this: 'HTTP/1.1 200...'
784 status_code[0] = rsp->head[9];
785 status_code[1] = rsp->head[10];
786 status_code[2] = rsp->head[11];
787 status_code[3] = '\0';
789 /* Log that the request was crunched and why. */
790 log_applied_actions(csp->action);
791 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
792 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
793 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
795 /* Write the answer to the client */
796 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
797 || write_socket(csp->cfd, rsp->body, rsp->content_length))
799 /* There is nothing we can do about it. */
800 log_error(LOG_LEVEL_ERROR,
801 "Couldn't deliver the error message through client socket %d: %E",
805 /* Clean up and return */
806 if (cgi_error_memory() != rsp)
808 free_http_response(rsp);
814 /*********************************************************************
816 * Function : crunch_response_triggered
818 * Description : Checks if the request has to be crunched,
819 * and delivers the crunch response if necessary.
822 * 1 : csp = Current client state (buffers, headers, etc...)
823 * 2 : crunchers = list of cruncher functions to run
825 * Returns : TRUE if the request was answered with a crunch response
828 *********************************************************************/
829 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
831 struct http_response *rsp = NULL;
832 const struct cruncher *c;
835 * If CGI request crunching is disabled,
836 * check the CGI dispatcher out of order to
837 * prevent unintentional blocks or redirects.
839 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
840 && (NULL != (rsp = dispatch_cgi(csp))))
842 /* Deliver, log and free the interception response. */
843 send_crunch_response(csp, rsp);
844 csp->flags |= CSP_FLAG_CRUNCHED;
848 for (c = crunchers; c->cruncher != NULL; c++)
851 * Check the cruncher if either Privoxy is toggled
852 * on and the request isn't forced, or if the cruncher
853 * applies to forced requests as well.
855 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
856 !(csp->flags & CSP_FLAG_FORCED)) ||
857 (c->flags & CF_IGNORE_FORCE))
859 rsp = c->cruncher(csp);
862 /* Deliver, log and free the interception response. */
863 send_crunch_response(csp, rsp);
864 csp->flags |= CSP_FLAG_CRUNCHED;
865 #ifdef FEATURE_STATISTICS
866 if (c->flags & CF_COUNT_AS_REJECT)
868 csp->flags |= CSP_FLAG_REJECTED;
870 #endif /* def FEATURE_STATISTICS */
881 /*********************************************************************
883 * Function : build_request_line
885 * Description : Builds the HTTP request line.
887 * If a HTTP forwarder is used it expects the whole URL,
888 * web servers only get the path.
891 * 1 : csp = Current client state (buffers, headers, etc...)
892 * 2 : fwd = The forwarding spec used for the request
893 * XXX: Should use http->fwd instead.
894 * 3 : request_line = The old request line which will be replaced.
896 * Returns : Nothing. Terminates in case of memory problems.
898 *********************************************************************/
899 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
901 struct http_request *http = csp->http;
903 assert(http->ssl == 0);
906 * Downgrade http version from 1.1 to 1.0
907 * if +downgrade action applies.
909 if ((csp->action->flags & ACTION_DOWNGRADE)
910 && (!strcmpic(http->ver, "HTTP/1.1")))
913 http->ver = strdup_or_die("HTTP/1.0");
917 * Rebuild the request line.
919 freez(*request_line);
920 *request_line = strdup(http->gpc);
921 string_append(request_line, " ");
923 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
925 string_append(request_line, http->url);
929 string_append(request_line, http->path);
931 string_append(request_line, " ");
932 string_append(request_line, http->ver);
934 if (*request_line == NULL)
936 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
938 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
942 /*********************************************************************
944 * Function : change_request_destination
946 * Description : Parse a (rewritten) request line and regenerate
947 * the http request data.
950 * 1 : csp = Current client state (buffers, headers, etc...)
952 * Returns : Forwards the parse_http_request() return code.
953 * Terminates in case of memory problems.
955 *********************************************************************/
956 static jb_err change_request_destination(struct client_state *csp)
958 struct http_request *http = csp->http;
961 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
962 csp->headers->first->str);
963 free_http_request(http);
964 err = parse_http_request(csp->headers->first->str, http);
965 if (JB_ERR_OK != err)
967 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
968 jb_err_to_string(err));
975 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
976 /*********************************************************************
978 * Function : server_response_is_complete
980 * Description : Determines whether we should stop reading
981 * from the server socket.
984 * 1 : csp = Current client state (buffers, headers, etc...)
985 * 2 : content_length = Length of content received so far.
987 * Returns : TRUE if the response is complete,
990 *********************************************************************/
991 static int server_response_is_complete(struct client_state *csp,
992 unsigned long long content_length)
994 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
996 if (!strcmpic(csp->http->gpc, "HEAD"))
999 * "HEAD" implies no body, we are thus expecting
1000 * no content. XXX: incomplete "list" of methods?
1002 csp->expected_content_length = 0;
1003 content_length_known = TRUE;
1004 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1007 if (csp->http->status == 204 || csp->http->status == 304)
1010 * Expect no body. XXX: incomplete "list" of status codes?
1012 csp->expected_content_length = 0;
1013 content_length_known = TRUE;
1014 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1017 return (content_length_known && ((0 == csp->expected_content_length)
1018 || (csp->expected_content_length <= content_length)));
1022 #ifdef FEATURE_CONNECTION_SHARING
1023 /*********************************************************************
1025 * Function : wait_for_alive_connections
1027 * Description : Waits for alive connections to timeout.
1033 *********************************************************************/
1034 static void wait_for_alive_connections(void)
1036 int connections_alive = close_unusable_connections();
1038 while (0 < connections_alive)
1040 log_error(LOG_LEVEL_CONNECT,
1041 "Waiting for %d connections to timeout.",
1044 connections_alive = close_unusable_connections();
1047 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1050 #endif /* def FEATURE_CONNECTION_SHARING */
1053 /*********************************************************************
1055 * Function : save_connection_destination
1057 * Description : Remembers a connection for reuse later on.
1060 * 1 : sfd = Open socket to remember.
1061 * 2 : http = The destination for the connection.
1062 * 3 : fwd = The forwarder settings used.
1063 * 4 : server_connection = storage.
1067 *********************************************************************/
1068 void save_connection_destination(jb_socket sfd,
1069 const struct http_request *http,
1070 const struct forward_spec *fwd,
1071 struct reusable_connection *server_connection)
1073 assert(sfd != JB_INVALID_SOCKET);
1074 assert(NULL != http->host);
1076 server_connection->sfd = sfd;
1077 server_connection->host = strdup_or_die(http->host);
1078 server_connection->port = http->port;
1080 assert(NULL != fwd);
1081 assert(server_connection->gateway_host == NULL);
1082 assert(server_connection->gateway_port == 0);
1083 assert(server_connection->forwarder_type == 0);
1084 assert(server_connection->forward_host == NULL);
1085 assert(server_connection->forward_port == 0);
1087 server_connection->forwarder_type = fwd->type;
1088 if (NULL != fwd->gateway_host)
1090 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1094 server_connection->gateway_host = NULL;
1096 server_connection->gateway_port = fwd->gateway_port;
1098 if (NULL != fwd->forward_host)
1100 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1104 server_connection->forward_host = NULL;
1106 server_connection->forward_port = fwd->forward_port;
1110 /*********************************************************************
1112 * Function : verify_request_length
1114 * Description : Checks if we already got the whole client requests
1115 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1118 * Data that doesn't belong to the current request is
1119 * either thrown away to let the client retry on a clean
1120 * socket, or stashed to be dealt with after the current
1121 * request is served.
1124 * 1 : csp = Current client state (buffers, headers, etc...)
1128 *********************************************************************/
1129 static void verify_request_length(struct client_state *csp)
1131 unsigned long long buffered_request_bytes =
1132 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1134 if ((csp->expected_client_content_length != 0)
1135 && (buffered_request_bytes != 0))
1137 if (csp->expected_client_content_length >= buffered_request_bytes)
1139 csp->expected_client_content_length -= buffered_request_bytes;
1140 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1141 "to account for the %llu ones we already got.",
1142 csp->expected_client_content_length, buffered_request_bytes);
1146 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1147 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1148 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1149 "Marking the server socket tainted after throwing %llu bytes away.",
1150 buffered_request_bytes - csp->expected_client_content_length);
1151 csp->expected_client_content_length = 0;
1152 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1155 if (csp->expected_client_content_length == 0)
1157 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1161 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1162 && ((csp->client_iob->cur < csp->client_iob->eod)
1163 || (csp->expected_client_content_length != 0)))
1165 if (strcmpic(csp->http->gpc, "GET")
1166 && strcmpic(csp->http->gpc, "HEAD")
1167 && strcmpic(csp->http->gpc, "TRACE")
1168 && strcmpic(csp->http->gpc, "OPTIONS")
1169 && strcmpic(csp->http->gpc, "DELETE"))
1171 /* XXX: this is an incomplete hack */
1172 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1173 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1177 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1179 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1181 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1182 log_error(LOG_LEVEL_CONNECT,
1183 "Possible pipeline attempt detected. The connection will not "
1184 "be kept alive and we will only serve the first request.");
1185 /* Nuke the pipelined requests from orbit, just to be sure. */
1186 clear_iob(csp->client_iob);
1191 * Keep the pipelined data around for now, we'll deal with
1192 * it once we're done serving the current request.
1194 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1195 assert(csp->client_iob->eod >= csp->client_iob->cur);
1196 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1197 "%d bytes of pipelined data received.",
1198 (int)(csp->client_iob->eod - csp->client_iob->cur));
1204 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1205 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1208 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1211 /*********************************************************************
1213 * Function : mark_server_socket_tainted
1215 * Description : Makes sure we don't reuse a server socket
1216 * (if we didn't read everything the server sent
1217 * us reusing the socket would lead to garbage).
1220 * 1 : csp = Current client state (buffers, headers, etc...)
1224 *********************************************************************/
1225 static void mark_server_socket_tainted(struct client_state *csp)
1228 * For consistency we always mark the server socket
1229 * tainted, however, to reduce the log noise we only
1230 * emit a log message if the server socket could have
1231 * actually been reused.
1233 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1234 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1236 log_error(LOG_LEVEL_CONNECT,
1237 "Marking the server socket %d tainted.",
1238 csp->server_connection.sfd);
1240 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1243 /*********************************************************************
1245 * Function : get_request_line
1247 * Description : Read the client request line.
1250 * 1 : csp = Current client state (buffers, headers, etc...)
1252 * Returns : Pointer to request line or NULL in case of errors.
1254 *********************************************************************/
1255 static char *get_request_line(struct client_state *csp)
1257 char buf[BUFFER_SIZE];
1258 char *request_line = NULL;
1261 memset(buf, 0, sizeof(buf));
1263 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1266 * If there are multiple pipelined requests waiting,
1267 * the flag will be set again once the next request
1270 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1272 request_line = get_header(csp->client_iob);
1273 if ((NULL != request_line) && ('\0' != *request_line))
1275 return request_line;
1279 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1280 "received yet. Continuing reading from %d.", csp->cfd);
1288 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1290 !data_is_available(csp->cfd, csp->config->socket_timeout)
1293 if (socket_is_still_alive(csp->cfd))
1295 log_error(LOG_LEVEL_CONNECT,
1296 "No request line on socket %d received in time. Timeout: %d.",
1297 csp->cfd, csp->config->socket_timeout);
1298 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1299 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1303 log_error(LOG_LEVEL_CONNECT,
1304 "The client side of the connection on socket %d got "
1305 "closed without sending a complete request line.", csp->cfd);
1310 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1312 if (len <= 0) return NULL;
1315 * If there is no memory left for buffering the
1316 * request, there is nothing we can do but hang up
1318 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1323 request_line = get_header(csp->client_iob);
1325 } while ((NULL != request_line) && ('\0' == *request_line));
1327 return request_line;
1333 CHUNK_STATUS_MISSING_DATA,
1334 CHUNK_STATUS_BODY_COMPLETE,
1335 CHUNK_STATUS_PARSE_ERROR
1339 /*********************************************************************
1341 * Function : chunked_body_is_complete
1343 * Description : Figures out whether or not a chunked body is complete.
1345 * Currently it always starts at the beginning of the
1346 * buffer which is somewhat wasteful and prevents Privoxy
1347 * from starting to forward the correctly parsed chunks
1348 * as soon as theoretically possible.
1350 * Should be modified to work with a common buffer,
1351 * and allow the caller to skip already parsed chunks.
1353 * This would allow the function to be used for unbuffered
1354 * response bodies as well.
1357 * 1 : iob = Buffer with the body to check.
1358 * 2 : length = Length of complete body
1360 * Returns : Enum with the result of the check.
1362 *********************************************************************/
1363 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1365 unsigned int chunksize;
1371 * We need at least a single digit, followed by "\r\n",
1372 * followed by an unknown amount of data, followed by "\r\n".
1374 if (p + 5 > iob->eod)
1376 return CHUNK_STATUS_MISSING_DATA;
1378 if (sscanf(p, "%x", &chunksize) != 1)
1380 return CHUNK_STATUS_PARSE_ERROR;
1384 * We want at least a single digit, followed by "\r\n",
1385 * followed by the specified amount of data, followed by "\r\n".
1387 if (p + chunksize + 5 > iob->eod)
1389 return CHUNK_STATUS_MISSING_DATA;
1392 /* Skip chunk-size. */
1393 p = strstr(p, "\r\n");
1396 return CHUNK_STATUS_PARSE_ERROR;
1398 /* Move beyond the chunkdata. */
1401 /* There should be another "\r\n" to skip */
1402 if (memcmp(p, "\r\n", 2))
1404 return CHUNK_STATUS_PARSE_ERROR;
1407 } while (chunksize > 0U);
1409 *length = (size_t)(p - iob->cur);
1410 assert(*length <= (size_t)(iob->eod - iob->cur));
1411 assert(p <= iob->eod);
1413 return CHUNK_STATUS_BODY_COMPLETE;
1418 /*********************************************************************
1420 * Function : receive_chunked_client_request_body
1422 * Description : Read the chunk-encoded client request body.
1423 * Failures are dealt with.
1426 * 1 : csp = Current client state (buffers, headers, etc...)
1428 * Returns : JB_ERR_OK or JB_ERR_PARSE
1430 *********************************************************************/
1431 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1434 enum chunk_status status;
1436 while (CHUNK_STATUS_MISSING_DATA ==
1437 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1439 char buf[BUFFER_SIZE];
1442 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1444 log_error(LOG_LEVEL_ERROR,
1445 "Timeout while waiting for the client body.");
1448 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1451 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1454 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1459 if (status != CHUNK_STATUS_BODY_COMPLETE)
1461 write_socket(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1462 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE));
1463 log_error(LOG_LEVEL_CLF,
1464 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1465 return JB_ERR_PARSE;
1467 log_error(LOG_LEVEL_CONNECT,
1468 "Chunked client body completely read. Length: %d", body_length);
1469 csp->expected_client_content_length = body_length;
1477 /*********************************************************************
1479 * Function : fuzz_chunked_transfer_encoding
1481 * Description : Treat the fuzzed input as chunked transfer encoding
1482 * to check and dechunk.
1485 * 1 : csp = Used to store the data.
1486 * 2 : fuzz_input_file = File to read the input from.
1488 * Returns : Result of dechunking
1490 *********************************************************************/
1491 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1494 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1495 enum chunk_status status;
1497 status = chunked_body_is_complete(csp->iob, &length);
1498 if (CHUNK_STATUS_BODY_COMPLETE != status)
1500 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1503 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1508 /*********************************************************************
1510 * Function : fuzz_client_request
1512 * Description : Try to get a client request from the fuzzed input.
1515 * 1 : csp = Current client state (buffers, headers, etc...)
1516 * 2 : fuzz_input_file = File to read the input from.
1518 * Returns : Result of fuzzing.
1520 *********************************************************************/
1521 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1526 csp->ip_addr_str = "fuzzer";
1528 if (strcmp(fuzz_input_file, "-") != 0)
1530 log_error(LOG_LEVEL_FATAL,
1531 "Fuzzed client requests can currenty only be read from stdin (-).");
1533 err = receive_client_request(csp);
1534 if (err != JB_ERR_OK)
1538 err = parse_client_request(csp);
1539 if (err != JB_ERR_OK)
1547 #endif /* def FUZZ */
1550 #ifdef FEATURE_FORCE_LOAD
1551 /*********************************************************************
1553 * Function : force_required
1555 * Description : Checks a request line to see if it contains
1556 * the FORCE_PREFIX. If it does, it is removed
1557 * unless enforcing requests has beend disabled.
1560 * 1 : request_line = HTTP request line
1562 * Returns : TRUE if force is required, FALSE otherwise.
1564 *********************************************************************/
1565 static int force_required(const struct client_state *csp, char *request_line)
1569 p = strstr(request_line, "http://");
1573 p += strlen("http://");
1577 /* Intercepted request usually don't specify the protocol. */
1581 /* Go to the beginning of the path */
1586 * If the path is missing the request line is invalid and we
1587 * are done here. The client-visible rejection happens later on.
1592 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1594 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1596 /* XXX: Should clean more carefully */
1597 strclean(request_line, FORCE_PREFIX);
1598 log_error(LOG_LEVEL_FORCE,
1599 "Enforcing request: \"%s\".", request_line);
1603 log_error(LOG_LEVEL_FORCE,
1604 "Ignored force prefix in request: \"%s\".", request_line);
1610 #endif /* def FEATURE_FORCE_LOAD */
1613 /*********************************************************************
1615 * Function : receive_client_request
1617 * Description : Read the client's request (more precisely the
1618 * client headers) and answer it if necessary.
1621 * 1 : csp = Current client state (buffers, headers, etc...)
1623 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1625 *********************************************************************/
1626 static jb_err receive_client_request(struct client_state *csp)
1628 char buf[BUFFER_SIZE];
1631 struct http_request *http;
1635 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1636 struct list header_list;
1637 struct list *headers = &header_list;
1639 /* We don't care if the arriving data is a valid HTTP request or not. */
1640 csp->requests_received_total++;
1644 memset(buf, 0, sizeof(buf));
1646 req = get_request_line(csp);
1649 mark_server_socket_tainted(csp);
1650 return JB_ERR_PARSE;
1652 assert(*req != '\0');
1654 if (client_protocol_is_unsupported(csp, req))
1656 return JB_ERR_PARSE;
1659 #ifdef FEATURE_FORCE_LOAD
1660 if (force_required(csp, req))
1662 csp->flags |= CSP_FLAG_FORCED;
1664 #endif /* def FEATURE_FORCE_LOAD */
1666 err = parse_http_request(req, http);
1668 if (JB_ERR_OK != err)
1670 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1671 /* XXX: Use correct size */
1672 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1673 log_error(LOG_LEVEL_ERROR,
1674 "Couldn't parse request line received from %s: %s",
1675 csp->ip_addr_str, jb_err_to_string(err));
1677 free_http_request(http);
1678 return JB_ERR_PARSE;
1681 /* grab the rest of the client's headers */
1685 p = get_header(csp->client_iob);
1689 /* There are no additional headers to read. */
1696 * We didn't receive a complete header
1697 * line yet, get the rest of it.
1699 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1701 log_error(LOG_LEVEL_ERROR,
1702 "Stopped grabbing the client headers.");
1703 destroy_list(headers);
1704 return JB_ERR_PARSE;
1707 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1710 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1711 destroy_list(headers);
1712 return JB_ERR_PARSE;
1715 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1718 * If there is no memory left for buffering the
1719 * request, there is nothing we can do but hang up
1721 destroy_list(headers);
1722 return JB_ERR_MEMORY;
1727 if (!strncmpic(p, "Transfer-Encoding:", 18))
1730 * XXX: should be called through sed()
1731 * but currently can't.
1733 client_transfer_encoding(csp, &p);
1736 * We were able to read a complete
1737 * header and can finally enlist it.
1744 if (http->host == NULL)
1747 * If we still don't know the request destination,
1748 * the request is invalid or the client uses
1749 * Privoxy without its knowledge.
1751 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1754 * Our attempts to get the request destination
1755 * elsewhere failed or Privoxy is configured
1756 * to only accept proxy requests.
1758 * An error response has already been send
1759 * and we're done here.
1761 return JB_ERR_PARSE;
1765 #ifdef FEATURE_CLIENT_TAGS
1766 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1767 set_client_address(csp, headers);
1768 get_tag_list_for_client(csp->client_tags, csp->client_address);
1772 * Determine the actions for this URL
1774 #ifdef FEATURE_TOGGLE
1775 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1777 /* Most compatible set of actions (i.e. none) */
1778 init_current_action(csp->action);
1781 #endif /* ndef FEATURE_TOGGLE */
1783 get_url_actions(csp, http);
1786 enlist(csp->headers, http->cmd);
1788 /* Append the previously read headers */
1789 err = list_append_list_unique(csp->headers, headers);
1790 destroy_list(headers);
1797 /*********************************************************************
1799 * Function : parse_client_request
1801 * Description : Parses the client's request and decides what to do
1804 * Note that since we're not using select() we could get
1805 * blocked here if a client connected, then didn't say
1809 * 1 : csp = Current client state (buffers, headers, etc...)
1811 * Returns : JB_ERR_OK or JB_ERR_PARSE
1813 *********************************************************************/
1814 static jb_err parse_client_request(struct client_state *csp)
1816 struct http_request *http = csp->http;
1819 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1820 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1821 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1822 && (csp->http->ssl == 0))
1824 /* Assume persistence until further notice */
1825 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1828 if (csp->http->ssl == 0)
1831 * This whole block belongs to chat() but currently
1832 * has to be executed before sed().
1834 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1836 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1838 return JB_ERR_PARSE;
1843 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1845 verify_request_length(csp);
1849 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1851 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1853 err = sed(csp, FILTER_CLIENT_HEADERS);
1854 if (JB_ERR_OK != err)
1856 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1858 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1859 csp->ip_addr_str, csp->http->cmd);
1860 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1861 return JB_ERR_PARSE;
1863 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1865 /* Check request line for rewrites. */
1866 if ((NULL == csp->headers->first->str)
1867 || (strcmp(http->cmd, csp->headers->first->str) &&
1868 (JB_ERR_OK != change_request_destination(csp))))
1871 * A header filter broke the request line - bail out.
1873 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1874 /* XXX: Use correct size */
1875 log_error(LOG_LEVEL_CLF,
1876 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1877 log_error(LOG_LEVEL_ERROR,
1878 "Invalid request line after applying header filters.");
1879 free_http_request(http);
1881 return JB_ERR_PARSE;
1884 if (client_has_unsupported_expectations(csp))
1886 return JB_ERR_PARSE;
1894 /*********************************************************************
1896 * Function : send_http_request
1898 * Description : Sends the HTTP headers from the client request
1899 * and all the body data that has already been received.
1902 * 1 : csp = Current client state (buffers, headers, etc...)
1904 * Returns : 0 on success, anything else is na error.
1906 *********************************************************************/
1907 static int send_http_request(struct client_state *csp)
1912 hdr = list_to_text(csp->headers);
1915 /* FIXME Should handle error properly */
1916 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1918 list_remove_all(csp->headers);
1921 * Write the client's (modified) header to the server
1922 * (along with anything else that may be in the buffer)
1924 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
1929 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
1930 csp->http->hostport);
1932 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
1933 && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
1936 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
1937 csp->http->hostport);
1940 return write_failure;
1945 /*********************************************************************
1947 * Function : handle_established_connection
1949 * Description : Shuffle data between client and server once the
1950 * connection has been established.
1953 * 1 : csp = Current client state (buffers, headers, etc...)
1955 * Returns : Nothing.
1957 *********************************************************************/
1958 static void handle_established_connection(struct client_state *csp)
1964 struct pollfd poll_fds[2];
1968 struct timeval timeout;
1971 int ms_iis5_hack = 0;
1972 unsigned long long byte_count = 0;
1973 struct http_request *http;
1974 long len = 0; /* for buffer sizes (and negative error codes) */
1975 int buffer_and_filter_content = 0;
1977 /* Skeleton for HTTP response, if we should intercept the request */
1978 struct http_response *rsp;
1979 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1980 int watch_client_socket;
1983 csp->receive_buffer_size = csp->config->receive_buffer_size;
1984 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
1985 if (csp->receive_buffer == NULL)
1987 log_error(LOG_LEVEL_ERROR,
1988 "Out of memory. Failed to allocate the receive buffer.");
1989 rsp = cgi_error_memory();
1990 send_crunch_response(csp, rsp);
1997 maxfd = (csp->cfd > csp->server_connection.sfd) ?
1998 csp->cfd : csp->server_connection.sfd;
2001 /* pass data between the client and server
2002 * until one or the other shuts down the connection.
2007 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2008 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2016 * FD_ZERO here seems to point to an errant macro which crashes.
2017 * So do this by hand for now...
2019 memset(&rfds,0x00,sizeof(fd_set));
2023 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2024 if (!watch_client_socket)
2026 maxfd = csp->server_connection.sfd;
2029 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2031 FD_SET(csp->cfd, &rfds);
2034 FD_SET(csp->server_connection.sfd, &rfds);
2035 #endif /* ndef HAVE_POLL */
2037 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2038 if ((csp->flags & CSP_FLAG_CHUNKED)
2039 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2040 && ((csp->iob->eod - csp->iob->cur) >= 5)
2041 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2044 * XXX: This check should be obsolete now,
2045 * but let's wait a while to be sure.
2047 log_error(LOG_LEVEL_CONNECT,
2048 "Looks like we got the last chunk together with "
2049 "the server headers but didn't detect it earlier. "
2050 "We better stop reading.");
2051 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2052 csp->expected_content_length = byte_count;
2053 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2055 if (server_body && server_response_is_complete(csp, byte_count))
2057 if (csp->expected_content_length == byte_count)
2059 log_error(LOG_LEVEL_CONNECT,
2060 "Done reading from server. Content length: %llu as expected. "
2061 "Bytes most recently read: %d.",
2066 log_error(LOG_LEVEL_CONNECT,
2067 "Done reading from server. Expected content length: %llu. "
2068 "Actual content length: %llu. Bytes most recently read: %d.",
2069 csp->expected_content_length, byte_count, len);
2073 * XXX: should not jump around,
2074 * chat() is complicated enough already.
2078 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2081 poll_fds[0].fd = csp->cfd;
2082 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2083 if (!watch_client_socket)
2086 * Ignore incoming data, but still watch out
2087 * for disconnects etc. These flags are always
2088 * implied anyway but explicitly setting them
2091 poll_fds[0].events = POLLERR|POLLHUP;
2096 poll_fds[0].events = POLLIN;
2098 poll_fds[1].fd = csp->server_connection.sfd;
2099 poll_fds[1].events = POLLIN;
2100 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2102 timeout.tv_sec = csp->config->socket_timeout;
2103 timeout.tv_usec = 0;
2104 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2105 #endif /* def HAVE_POLL */
2109 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2110 csp->config->socket_timeout, http->url);
2111 if ((byte_count == 0) && (http->ssl == 0))
2113 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2115 mark_server_socket_tainted(csp);
2121 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2123 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2125 mark_server_socket_tainted(csp);
2130 * This is the body of the browser's request,
2131 * just read and write it.
2133 * XXX: Make sure the client doesn't use pipelining
2134 * behind Privoxy's back.
2137 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2139 log_error(LOG_LEVEL_CONNECT,
2140 "The client socket %d has become unusable while "
2141 "the server socket %d is still open.",
2142 csp->cfd, csp->server_connection.sfd);
2143 mark_server_socket_tainted(csp);
2147 if (poll_fds[0].revents != 0)
2149 if (FD_ISSET(csp->cfd, &rfds))
2150 #endif /* def HAVE_POLL*/
2152 int max_bytes_to_read = (int)csp->receive_buffer_size;
2154 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2155 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2157 if (data_is_available(csp->cfd, 0))
2160 * If the next request is already waiting, we have
2161 * to stop select()ing the client socket. Otherwise
2162 * we would always return right away and get nothing
2165 watch_client_socket = 0;
2166 log_error(LOG_LEVEL_CONNECT,
2167 "Stop watching client socket %d. "
2168 "There's already another request waiting.",
2173 * If the client socket is set, but there's no data
2174 * available on the socket, the client went fishing
2175 * and continuing talking to the server makes no sense.
2177 log_error(LOG_LEVEL_CONNECT,
2178 "The client closed socket %d while "
2179 "the server socket %d is still open.",
2180 csp->cfd, csp->server_connection.sfd);
2181 mark_server_socket_tainted(csp);
2184 if (csp->expected_client_content_length != 0)
2186 if (csp->expected_client_content_length < csp->receive_buffer_size)
2188 max_bytes_to_read = (int)csp->expected_client_content_length;
2190 log_error(LOG_LEVEL_CONNECT,
2191 "Waiting for up to %d bytes from the client.",
2194 assert(max_bytes_to_read <= csp->receive_buffer_size);
2195 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2197 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2201 /* XXX: not sure if this is necessary. */
2202 mark_server_socket_tainted(csp);
2203 break; /* "game over, man" */
2206 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2207 if (csp->expected_client_content_length != 0)
2209 assert(len <= max_bytes_to_read);
2210 csp->expected_client_content_length -= (unsigned)len;
2211 log_error(LOG_LEVEL_CONNECT,
2212 "Expected client content length set to %llu "
2213 "after reading %d bytes.",
2214 csp->expected_client_content_length, len);
2215 if (csp->expected_client_content_length == 0)
2217 log_error(LOG_LEVEL_CONNECT,
2218 "Done reading from the client.");
2219 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2222 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2224 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2226 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2227 mark_server_socket_tainted(csp);
2234 * The server wants to talk. It could be the header or the body.
2235 * If `hdr' is null, then it's the header otherwise it's the body.
2236 * FIXME: Does `hdr' really mean `host'? No.
2239 if (poll_fds[1].revents != 0)
2241 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2242 #endif /* HAVE_POLL */
2244 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2246 * If we are buffering content, we don't want to eat up to
2247 * buffer-limit bytes if the client no longer cares about them.
2248 * If we aren't buffering, however, a dead client socket will be
2249 * noticed pretty much right away anyway, so we can reduce the
2250 * overhead by skipping the check.
2252 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2255 log_error(LOG_LEVEL_CONNECT,
2256 "The server still wants to talk, but the client may already have hung up on us.");
2258 log_error(LOG_LEVEL_CONNECT,
2259 "The server still wants to talk, but the client hung up on us.");
2260 mark_server_socket_tainted(csp);
2262 #endif /* def _WIN32 */
2264 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2266 len = read_socket(csp->server_connection.sfd, csp->receive_buffer, (int)csp->receive_buffer_size);
2270 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2272 if (http->ssl && (csp->fwd == NULL))
2275 * Just hang up. We already confirmed the client's CONNECT
2276 * request with status code 200 and unencrypted content is
2277 * no longer welcome.
2279 log_error(LOG_LEVEL_ERROR,
2280 "CONNECT already confirmed. Unable to tell the client about the problem.");
2283 else if (byte_count)
2286 * Just hang up. We already transmitted the original headers
2287 * and parts of the original content and therefore missed the
2288 * chance to send an error message (without risking data corruption).
2290 * XXX: we could retry with a fancy range request here.
2292 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2293 "Unable to tell the client about the problem.");
2294 mark_server_socket_tainted(csp);
2298 * XXX: Consider handling the cases above the same.
2300 mark_server_socket_tainted(csp);
2304 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2305 if (csp->flags & CSP_FLAG_CHUNKED)
2307 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2309 /* XXX: this is a temporary hack */
2310 log_error(LOG_LEVEL_CONNECT,
2311 "Looks like we reached the end of the last chunk. "
2312 "We better stop reading.");
2313 csp->expected_content_length = byte_count + (unsigned long long)len;
2314 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2318 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2321 * This is guaranteed by allocating with zalloc_or_die()
2322 * and never (intentionally) writing to the last byte.
2324 * csp->receive_buffer_size is the size of the part of the
2325 * buffer we intentionally write to, but we actually
2326 * allocated csp->receive_buffer_size+1 bytes so the assertion
2327 * stays within the allocated range.
2329 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2332 * Add a trailing zero to let be able to use string operations.
2333 * XXX: do we still need this with filter_popups gone?
2335 assert(len <= csp->receive_buffer_size);
2336 csp->receive_buffer[len] = '\0';
2339 * Normally, this would indicate that we've read
2340 * as much as the server has sent us and we can
2341 * close the client connection. However, Microsoft
2342 * in its wisdom has released IIS/5 with a bug that
2343 * prevents it from sending the trailing \r\n in
2344 * a 302 redirect header (and possibly other headers).
2345 * To work around this if we've haven't parsed
2346 * a full header we'll append a trailing \r\n
2347 * and see if this now generates a valid one.
2349 * This hack shouldn't have any impacts. If we've
2350 * already transmitted the header or if this is a
2351 * SSL connection, then we won't bother with this
2352 * hack. So we only work on partially received
2353 * headers. If we append a \r\n and this still
2354 * doesn't generate a valid header, then we won't
2355 * transmit anything to the client.
2360 if (server_body || http->ssl)
2363 * If we have been buffering up the document,
2364 * now is the time to apply content modification
2365 * and send the result to the client.
2367 if (buffer_and_filter_content)
2369 p = execute_content_filters(csp);
2371 * If content filtering fails, use the original
2372 * buffer and length.
2373 * (see p != NULL ? p : csp->iob->cur below)
2377 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2379 #ifdef FEATURE_COMPRESSION
2380 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2381 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2383 char *compressed_content = compress_buffer(p,
2384 (size_t *)&csp->content_length, csp->config->compression_level);
2385 if (compressed_content != NULL)
2388 p = compressed_content;
2389 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2394 if (JB_ERR_OK != update_server_headers(csp))
2396 log_error(LOG_LEVEL_FATAL,
2397 "Failed to update server headers. after filtering.");
2400 hdr = list_to_text(csp->headers);
2403 /* FIXME Should handle error properly */
2404 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2407 if (write_socket(csp->cfd, hdr, strlen(hdr))
2408 || write_socket(csp->cfd,
2409 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2411 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2414 mark_server_socket_tainted(csp);
2422 break; /* "game over, man" */
2426 * This is NOT the body, so
2427 * Let's pretend the server just sent us a blank line.
2429 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
2430 len = (int)strlen(csp->receive_buffer);
2433 * Now, let the normal header parsing algorithm below do its
2434 * job. If it fails, we'll exit instead of continuing.
2441 * If this is an SSL connection or we're in the body
2442 * of the server document, just write it to the client,
2443 * unless we need to buffer the body for later content-filtering
2445 if (server_body || http->ssl)
2447 if (buffer_and_filter_content)
2450 * If there is no memory left for buffering the content, or the buffer limit
2451 * has been reached, switch to non-filtering mode, i.e. make & write the
2452 * header, flush the iob and buf, and get out of the way.
2454 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
2459 log_error(LOG_LEVEL_INFO,
2460 "Flushing header and buffers. Stepping back from filtering.");
2462 hdr = list_to_text(csp->headers);
2466 * Memory is too tight to even generate the header.
2467 * Send our static "Out-of-memory" page.
2469 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2470 rsp = cgi_error_memory();
2471 send_crunch_response(csp, rsp);
2472 mark_server_socket_tainted(csp);
2475 hdrlen = strlen(hdr);
2477 if (write_socket(csp->cfd, hdr, hdrlen)
2478 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2479 || (write_socket(csp->cfd, csp->receive_buffer, (size_t)len)))
2481 log_error(LOG_LEVEL_CONNECT,
2482 "Flush header and buffers to client failed: %E");
2484 mark_server_socket_tainted(csp);
2489 * Reset the byte_count to the amount of bytes
2490 * we just flushed. len will be added a few lines below,
2491 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2493 byte_count = (unsigned long long)flushed;
2495 buffer_and_filter_content = 0;
2501 if (write_socket(csp->cfd, csp->receive_buffer, (size_t)len))
2503 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2504 mark_server_socket_tainted(csp);
2508 byte_count += (unsigned long long)len;
2514 * We're still looking for the end of the server's header.
2515 * Buffer up the data we just read. If that fails, there's
2516 * little we can do but send our static out-of-memory page.
2518 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
2520 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2521 rsp = cgi_error_memory();
2522 send_crunch_response(csp, rsp);
2523 mark_server_socket_tainted(csp);
2527 /* Convert iob into something sed() can digest */
2528 if (JB_ERR_PARSE == get_server_headers(csp))
2533 * Well, we tried our MS IIS/5 hack and it didn't work.
2534 * The header is incomplete and there isn't anything
2535 * we can do about it.
2537 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2538 "Applying the MS IIS5 hack didn't help.");
2539 log_error(LOG_LEVEL_CLF,
2540 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2541 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2542 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2543 mark_server_socket_tainted(csp);
2549 * Since we have to wait for more from the server before
2550 * we can parse the headers we just continue here.
2552 log_error(LOG_LEVEL_CONNECT,
2553 "Continuing buffering server headers from socket %d. "
2554 "Bytes most recently read: %d.", csp->cfd, len);
2561 * Account for the content bytes we
2562 * might have gotten with the headers.
2564 assert(csp->iob->eod >= csp->iob->cur);
2565 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2568 /* Did we actually get anything? */
2569 if (NULL == csp->headers->first)
2571 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2573 log_error(LOG_LEVEL_ERROR,
2574 "No server or forwarder response received on socket %d. "
2575 "Closing client socket %d without sending data.",
2576 csp->server_connection.sfd, csp->cfd);
2577 log_error(LOG_LEVEL_CLF,
2578 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2582 log_error(LOG_LEVEL_ERROR,
2583 "No server or forwarder response received on socket %d.",
2584 csp->server_connection.sfd);
2585 send_crunch_response(csp, error_response(csp, "no-server-data"));
2587 free_http_request(http);
2588 mark_server_socket_tainted(csp);
2592 assert(csp->headers->first->str);
2594 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2595 strncmpic(csp->headers->first->str, "ICY", 3))
2598 * It doesn't look like a HTTP (or Shoutcast) response:
2599 * tell the client and log the problem.
2601 if (strlen(csp->headers->first->str) > 30)
2603 csp->headers->first->str[30] = '\0';
2605 log_error(LOG_LEVEL_ERROR,
2606 "Invalid server or forwarder response. Starts with: %s",
2607 csp->headers->first->str);
2608 log_error(LOG_LEVEL_CLF,
2609 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2610 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2611 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2612 free_http_request(http);
2613 mark_server_socket_tainted(csp);
2618 * We have now received the entire server header,
2619 * filter it and send the result to the client
2621 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2623 log_error(LOG_LEVEL_CLF,
2624 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2625 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2626 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2627 free_http_request(http);
2628 mark_server_socket_tainted(csp);
2631 hdr = list_to_text(csp->headers);
2634 /* FIXME Should handle error properly */
2635 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2638 if ((csp->flags & CSP_FLAG_CHUNKED)
2639 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2640 && ((csp->iob->eod - csp->iob->cur) >= 5)
2641 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2643 log_error(LOG_LEVEL_CONNECT,
2644 "Looks like we got the last chunk together with "
2645 "the server headers. We better stop reading.");
2646 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2647 csp->expected_content_length = byte_count;
2648 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2651 csp->server_connection.response_received = time(NULL);
2653 if (crunch_response_triggered(csp, crunchers_light))
2656 * One of the tags created by a server-header
2657 * tagger triggered a crunch. We already
2658 * delivered the crunch response to the client
2659 * and are done here after cleaning up.
2662 mark_server_socket_tainted(csp);
2665 /* Buffer and pcrs filter this if appropriate. */
2667 if (!http->ssl) /* We talk plaintext */
2669 buffer_and_filter_content = content_requires_filtering(csp);
2672 * Only write if we're not buffering for content modification
2674 if (!buffer_and_filter_content)
2677 * Write the server's (modified) header to
2678 * the client (along with anything else that
2679 * may be in the buffer)
2682 if (write_socket(csp->cfd, hdr, strlen(hdr))
2683 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2685 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2688 * The write failed, so don't bother mentioning it
2689 * to the client... it probably can't hear us anyway.
2692 mark_server_socket_tainted(csp);
2697 /* we're finished with the server's header */
2703 * If this was a MS IIS/5 hack then it means the server
2704 * has already closed the connection. Nothing more to read.
2709 log_error(LOG_LEVEL_ERROR,
2710 "Closed server connection detected. "
2711 "Applying the MS IIS5 hack didn't help.");
2712 log_error(LOG_LEVEL_CLF,
2713 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2714 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2715 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2716 mark_server_socket_tainted(csp);
2722 mark_server_socket_tainted(csp);
2723 return; /* huh? we should never get here */
2726 if (csp->content_length == 0)
2729 * If Privoxy didn't recalculate the Content-Length,
2730 * byte_count is still correct.
2732 csp->content_length = byte_count;
2735 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2736 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2737 && (csp->expected_content_length != byte_count))
2739 log_error(LOG_LEVEL_CONNECT,
2740 "Received %llu bytes while expecting %llu.",
2741 byte_count, csp->expected_content_length);
2742 mark_server_socket_tainted(csp);
2746 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2747 csp->ip_addr_str, http->ocmd, csp->content_length);
2749 csp->server_connection.timestamp = time(NULL);
2753 /*********************************************************************
2757 * Description : Once a connection from the client has been accepted,
2758 * this function is called (via serve()) to handle the
2759 * main business of the communication. This function
2760 * returns after dealing with a single request. It can
2761 * be called multiple times with the same client socket
2762 * if the client is keeping the connection alive.
2764 * The decision whether or not a client connection will
2765 * be kept alive is up to the caller which also must
2766 * close the client socket when done.
2768 * FIXME: chat is nearly thousand lines long.
2772 * 1 : csp = Current client state (buffers, headers, etc...)
2774 * Returns : Nothing.
2776 *********************************************************************/
2777 static void chat(struct client_state *csp)
2779 const struct forward_spec *fwd;
2780 struct http_request *http;
2781 /* Skeleton for HTTP response, if we should intercept the request */
2782 struct http_response *rsp;
2786 if (receive_client_request(csp) != JB_ERR_OK)
2790 if (parse_client_request(csp) != JB_ERR_OK)
2795 /* decide how to route the HTTP request */
2796 fwd = forward_url(csp, http);
2799 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2800 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2805 * build the http request to send to the server
2806 * we have to do one of the following:
2808 * create = use the original HTTP request to create a new
2809 * HTTP request that has either the path component
2810 * without the http://domainspec (w/path) or the
2811 * full orininal URL (w/url)
2812 * Note that the path and/or the HTTP version may
2813 * have been altered by now.
2815 * connect = Open a socket to the host:port of the server
2816 * and short-circuit server and client socket.
2818 * pass = Pass the request unchanged if forwarding a CONNECT
2819 * request to a parent proxy. Note that we'll be sending
2820 * the CFAIL message ourselves if connecting to the parent
2821 * fails, but we won't send a CSUCCEED message if it works,
2822 * since that would result in a double message (ours and the
2823 * parent's). After sending the request to the parent, we simply
2826 * here's the matrix:
2829 * +--------+--------+
2831 * 0 | create | connect|
2833 * Forwarding +--------+--------+
2835 * 1 | create | pass |
2837 * +--------+--------+
2841 if (http->ssl && connect_port_is_forbidden(csp))
2843 const char *acceptable_connect_ports =
2844 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
2845 assert(NULL != acceptable_connect_ports);
2846 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
2847 "limit-connect{%s} doesn't allow CONNECT requests to %s",
2848 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
2849 csp->action->flags |= ACTION_BLOCK;
2855 freez(csp->headers->first->str);
2856 build_request_line(csp, fwd, &csp->headers->first->str);
2860 * We have a request. Check if one of the crunchers wants it.
2862 if (crunch_response_triggered(csp, crunchers_all))
2865 * Yes. The client got the crunch response and we're done here.
2870 log_applied_actions(csp->action);
2871 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
2873 if (fwd->forward_host)
2875 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
2876 fwd->forward_host, fwd->forward_port, http->hostport);
2880 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
2883 /* here we connect to the server, gateway, or the forwarder */
2885 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2886 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
2887 && socket_is_still_alive(csp->server_connection.sfd)
2888 && connection_destination_matches(&csp->server_connection, http, fwd))
2890 log_error(LOG_LEVEL_CONNECT,
2891 "Reusing server socket %d connected to %s. Total requests: %u.",
2892 csp->server_connection.sfd, csp->server_connection.host,
2893 csp->server_connection.requests_sent_total);
2897 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2899 #ifdef FEATURE_CONNECTION_SHARING
2900 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2902 remember_connection(&csp->server_connection);
2905 #endif /* def FEATURE_CONNECTION_SHARING */
2907 log_error(LOG_LEVEL_CONNECT,
2908 "Closing server socket %d connected to %s. Total requests: %u.",
2909 csp->server_connection.sfd, csp->server_connection.host,
2910 csp->server_connection.requests_sent_total);
2911 close_socket(csp->server_connection.sfd);
2913 mark_connection_closed(&csp->server_connection);
2915 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2917 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
2919 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
2921 if (fwd->type != SOCKS_NONE)
2924 rsp = error_response(csp, "forwarding-failed");
2926 else if (errno == EINVAL)
2928 rsp = error_response(csp, "no-such-domain");
2932 rsp = error_response(csp, "connect-failed");
2935 /* Write the answer to the client */
2938 send_crunch_response(csp, rsp);
2942 * Temporary workaround to prevent already-read client
2943 * bodies from being parsed as new requests. For now we
2944 * err on the safe side and throw all the following
2945 * requests under the bus, even if no client body has been
2946 * buffered. A compliant client will repeat the dropped
2947 * requests on an untainted connection.
2949 * The proper fix is to discard the no longer needed
2950 * client body in the buffer (if there is one) and to
2951 * continue parsing the bytes that follow.
2953 drain_and_close_socket(csp->cfd);
2954 csp->cfd = JB_INVALID_SOCKET;
2958 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2959 save_connection_destination(csp->server_connection.sfd,
2960 http, fwd, &csp->server_connection);
2961 csp->server_connection.keep_alive_timeout =
2962 (unsigned)csp->config->keep_alive_timeout;
2964 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2966 csp->server_connection.requests_sent_total++;
2968 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
2970 /* Client headers have been sent optimistically */
2971 assert(csp->headers->last == NULL);
2973 else if (fwd->forward_host || (http->ssl == 0))
2975 if (send_http_request(csp))
2977 rsp = error_response(csp, "connect-failed");
2980 send_crunch_response(csp, rsp);
2988 * We're running an SSL tunnel and we're not forwarding,
2989 * so just ditch the client headers, send the "connect succeeded"
2990 * message to the client, flush the rest, and get out of the way.
2992 list_remove_all(csp->headers);
2993 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
2997 clear_iob(csp->client_iob);
3000 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
3002 /* XXX: should the time start earlier for optimistically sent data? */
3003 csp->server_connection.request_sent = time(NULL);
3005 handle_established_connection(csp);
3006 freez(csp->receive_buffer);
3011 /*********************************************************************
3013 * Function : fuzz_server_response
3015 * Description : Treat the input as a whole server response.
3018 * 1 : csp = Current client state (buffers, headers, etc...)
3019 * 2 : fuzz_input_file = File to read the input from.
3023 *********************************************************************/
3024 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
3026 static struct forward_spec fwd; /* Zero'd due to being static */
3029 if (strcmp(fuzz_input_file, "-") == 0)
3031 /* XXX: Doesn'T work yet. */
3032 csp->server_connection.sfd = 0;
3036 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
3037 if (csp->server_connection.sfd == -1)
3039 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
3044 csp->content_type |= CT_GIF;
3045 csp->action->flags |= ACTION_DEANIMATE;
3046 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
3048 csp->http->path = strdup_or_die("/");
3049 csp->http->host = strdup_or_die("fuzz.example.org");
3050 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
3051 /* Prevent client socket monitoring */
3052 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3053 csp->flags |= CSP_FLAG_CHUNKED;
3055 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
3056 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3058 csp->content_type |= CT_DECLARED|CT_GIF;
3060 csp->config->socket_timeout = 0;
3062 cgi_init_error_messages();
3064 handle_established_connection(csp);
3065 freez(csp->receive_buffer);
3072 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3073 /*********************************************************************
3075 * Function : prepare_csp_for_next_request
3077 * Description : Put the csp in a mostly vergin state.
3080 * 1 : csp = Current client state (buffers, headers, etc...)
3084 *********************************************************************/
3085 static void prepare_csp_for_next_request(struct client_state *csp)
3087 csp->content_type = 0;
3088 csp->content_length = 0;
3089 csp->expected_content_length = 0;
3090 csp->expected_client_content_length = 0;
3091 list_remove_all(csp->headers);
3092 clear_iob(csp->iob);
3093 freez(csp->error_message);
3094 free_http_request(csp->http);
3095 destroy_list(csp->headers);
3096 destroy_list(csp->tags);
3097 #ifdef FEATURE_CLIENT_TAGS
3098 destroy_list(csp->client_tags);
3099 freez(csp->client_address);
3101 free_current_action(csp->action);
3102 if (NULL != csp->fwd)
3104 unload_forward_spec(csp->fwd);
3107 /* XXX: Store per-connection flags someplace else. */
3108 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
3109 #ifdef FEATURE_TOGGLE
3110 if (global_toggle_state)
3111 #endif /* def FEATURE_TOGGLE */
3113 csp->flags |= CSP_FLAG_TOGGLED_ON;
3116 if (csp->client_iob->eod > csp->client_iob->cur)
3118 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
3119 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
3121 assert(bytes_to_shift > 0);
3122 assert(data_length > 0);
3124 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
3125 data_length, bytes_to_shift);
3126 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
3127 csp->client_iob->cur = csp->client_iob->buf;
3128 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
3129 csp->client_iob->eod = csp->client_iob->buf + data_length;
3130 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
3132 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3137 * We mainly care about resetting client_iob->cur so we don't
3138 * waste buffer space at the beginning and don't mess up the
3139 * request restoration done by cgi_show_request().
3141 * Freeing the buffer itself isn't technically necessary,
3142 * but makes debugging more convenient.
3144 clear_iob(csp->client_iob);
3147 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3150 /*********************************************************************
3154 * Description : This is little more than chat. We only "serve" to
3155 * to close (or remember) any socket that chat may have
3159 * 1 : csp = Current client state (buffers, headers, etc...)
3163 *********************************************************************/
3164 static void serve(struct client_state *csp)
3166 int config_file_change_detected = 0; /* Only used for debugging */
3167 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3168 #ifdef FEATURE_CONNECTION_SHARING
3169 static int monitor_thread_running = 0;
3170 #endif /* def FEATURE_CONNECTION_SHARING */
3171 int continue_chatting = 0;
3173 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
3174 csp->ip_addr_str, csp->cfd);
3178 unsigned int latency;
3183 * If the request has been crunched,
3184 * the calculated latency is zero.
3186 latency = (unsigned)(csp->server_connection.response_received -
3187 csp->server_connection.request_sent) / 2;
3189 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3190 && (csp->flags & CSP_FLAG_CRUNCHED)
3191 && (csp->expected_client_content_length != 0))
3193 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
3194 log_error(LOG_LEVEL_CONNECT,
3195 "Tainting client socket %d due to unread data.", csp->cfd);
3198 continue_chatting = (csp->config->feature_flags
3199 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3200 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3201 && (csp->cfd != JB_INVALID_SOCKET)
3202 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3203 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3204 || (csp->flags & CSP_FLAG_CHUNKED));
3206 if (!(csp->flags & CSP_FLAG_CRUNCHED)
3207 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
3209 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
3211 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
3213 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
3214 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3215 || !socket_is_still_alive(csp->server_connection.sfd)
3216 || !(latency < csp->server_connection.keep_alive_timeout))
3218 log_error(LOG_LEVEL_CONNECT,
3219 "Closing server socket %d connected to %s. "
3220 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
3221 csp->server_connection.sfd, csp->server_connection.host,
3222 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3223 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3224 socket_is_still_alive(csp->server_connection.sfd),
3225 csp->server_connection.keep_alive_timeout);
3226 #ifdef FEATURE_CONNECTION_SHARING
3227 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3229 forget_connection(csp->server_connection.sfd);
3231 #endif /* def FEATURE_CONNECTION_SHARING */
3232 close_socket(csp->server_connection.sfd);
3233 mark_connection_closed(&csp->server_connection);
3237 if (continue_chatting && any_loaded_file_changed(csp))
3239 continue_chatting = 0;
3240 config_file_change_detected = 1;
3243 if (continue_chatting)
3245 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
3246 && socket_is_still_alive(csp->cfd))
3248 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
3249 "pipelined on socket %d and the socket is still alive.",
3250 csp->requests_received_total+1, csp->cfd);
3251 prepare_csp_for_next_request(csp);
3255 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3257 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3259 log_error(LOG_LEVEL_CONNECT,
3260 "Waiting for the next client request on socket %d. "
3261 "Keeping the server socket %d to %s open.",
3262 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
3266 log_error(LOG_LEVEL_CONNECT,
3267 "Waiting for the next client request on socket %d. "
3268 "No server socket to keep open.", csp->cfd);
3272 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3273 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
3274 && socket_is_still_alive(csp->cfd))
3276 log_error(LOG_LEVEL_CONNECT,
3277 "Client request %u arrived in time on socket %d.",
3278 csp->requests_received_total+1, csp->cfd);
3279 prepare_csp_for_next_request(csp);
3283 #ifdef FEATURE_CONNECTION_SHARING
3284 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3285 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3286 && (socket_is_still_alive(csp->server_connection.sfd)))
3288 time_t time_open = time(NULL) - csp->server_connection.timestamp;
3290 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3295 remember_connection(&csp->server_connection);
3296 csp->server_connection.sfd = JB_INVALID_SOCKET;
3297 drain_and_close_socket(csp->cfd);
3298 csp->cfd = JB_INVALID_SOCKET;
3299 privoxy_mutex_lock(&connection_reuse_mutex);
3300 if (!monitor_thread_running)
3302 monitor_thread_running = 1;
3303 privoxy_mutex_unlock(&connection_reuse_mutex);
3304 wait_for_alive_connections();
3305 privoxy_mutex_lock(&connection_reuse_mutex);
3306 monitor_thread_running = 0;
3308 privoxy_mutex_unlock(&connection_reuse_mutex);
3310 #endif /* def FEATURE_CONNECTION_SHARING */
3314 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3316 log_error(LOG_LEVEL_CONNECT,
3317 "Closing server socket %d connected to %s. Keep-alive: %u. "
3318 "Tainted: %u. Socket alive: %u. Timeout: %u. "
3319 "Configuration file change detected: %u",
3320 csp->server_connection.sfd, csp->server_connection.host,
3321 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3322 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3323 socket_is_still_alive(csp->server_connection.sfd),
3324 csp->server_connection.keep_alive_timeout,
3325 config_file_change_detected);
3327 } while (continue_chatting);
3331 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3333 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3335 #ifdef FEATURE_CONNECTION_SHARING
3336 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3338 forget_connection(csp->server_connection.sfd);
3340 #endif /* def FEATURE_CONNECTION_SHARING */
3341 close_socket(csp->server_connection.sfd);
3344 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3345 mark_connection_closed(&csp->server_connection);
3348 if (csp->cfd != JB_INVALID_SOCKET)
3350 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3351 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3352 "Configuration file change detected: %u. Requests received: %u.",
3353 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3354 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3355 config_file_change_detected, csp->requests_received_total);
3356 drain_and_close_socket(csp->cfd);
3359 free_csp_resources(csp);
3361 csp->flags &= ~CSP_FLAG_ACTIVE;
3367 /*********************************************************************
3369 * Function : server_thread
3371 * Description : We only exist to call `serve' in a threaded environment.
3374 * 1 : data = Current client state (buffers, headers, etc...)
3376 * Returns : Always 0.
3378 *********************************************************************/
3379 static int32 server_thread(void *data)
3381 serve((struct client_state *) data);
3388 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3389 /*********************************************************************
3393 * Description : Print usage info & exit.
3395 * Parameters : Pointer to argv[0] for identifying ourselves
3399 *********************************************************************/
3400 static void usage(const char *name)
3402 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3403 "Usage: %s [--config-test] "
3406 #endif /* defined(unix) */
3409 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3410 #endif /* defined(unix) */
3411 "[--version] [configfile]\n",
3415 show_fuzz_usage(name);
3418 printf("Aborting\n");
3423 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3426 #ifdef MUTEX_LOCKS_AVAILABLE
3427 /*********************************************************************
3429 * Function : privoxy_mutex_lock
3431 * Description : Locks a mutex.
3434 * 1 : mutex = The mutex to lock.
3436 * Returns : Void. May exit in case of errors.
3438 *********************************************************************/
3439 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3441 #ifdef FEATURE_PTHREAD
3442 int err = pthread_mutex_lock(mutex);
3445 if (mutex != &log_mutex)
3447 log_error(LOG_LEVEL_FATAL,
3448 "Mutex locking failed: %s.\n", strerror(err));
3453 EnterCriticalSection(mutex);
3454 #endif /* def FEATURE_PTHREAD */
3458 /*********************************************************************
3460 * Function : privoxy_mutex_unlock
3462 * Description : Unlocks a mutex.
3465 * 1 : mutex = The mutex to unlock.
3467 * Returns : Void. May exit in case of errors.
3469 *********************************************************************/
3470 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3472 #ifdef FEATURE_PTHREAD
3473 int err = pthread_mutex_unlock(mutex);
3476 if (mutex != &log_mutex)
3478 log_error(LOG_LEVEL_FATAL,
3479 "Mutex unlocking failed: %s.\n", strerror(err));
3484 LeaveCriticalSection(mutex);
3485 #endif /* def FEATURE_PTHREAD */
3489 /*********************************************************************
3491 * Function : privoxy_mutex_init
3493 * Description : Prepares a mutex.
3496 * 1 : mutex = The mutex to initialize.
3498 * Returns : Void. May exit in case of errors.
3500 *********************************************************************/
3501 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3503 #ifdef FEATURE_PTHREAD
3504 int err = pthread_mutex_init(mutex, 0);
3507 printf("Fatal error. Mutex initialization failed: %s.\n",
3512 InitializeCriticalSection(mutex);
3513 #endif /* def FEATURE_PTHREAD */
3515 #endif /* def MUTEX_LOCKS_AVAILABLE */
3517 /*********************************************************************
3519 * Function : initialize_mutexes
3521 * Description : Prepares mutexes if mutex support is available.
3525 * Returns : Void, exits in case of errors.
3527 *********************************************************************/
3528 static void initialize_mutexes(void)
3530 #ifdef MUTEX_LOCKS_AVAILABLE
3532 * Prepare global mutex semaphores
3534 privoxy_mutex_init(&log_mutex);
3535 privoxy_mutex_init(&log_init_mutex);
3536 privoxy_mutex_init(&connection_reuse_mutex);
3537 #ifdef FEATURE_EXTERNAL_FILTERS
3538 privoxy_mutex_init(&external_filter_mutex);
3540 #ifdef FEATURE_CLIENT_TAGS
3541 privoxy_mutex_init(&client_tags_mutex);
3545 * XXX: The assumptions below are a bit naive
3546 * and can cause locks that aren't necessary.
3548 * For example older FreeBSD versions (< 6.x?)
3549 * have no gethostbyname_r, but gethostbyname is
3552 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3553 privoxy_mutex_init(&resolver_mutex);
3554 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3556 * XXX: should we use a single mutex for
3557 * localtime() and gmtime() as well?
3559 #ifndef HAVE_GMTIME_R
3560 privoxy_mutex_init(&gmtime_mutex);
3561 #endif /* ndef HAVE_GMTIME_R */
3563 #ifndef HAVE_LOCALTIME_R
3564 privoxy_mutex_init(&localtime_mutex);
3565 #endif /* ndef HAVE_GMTIME_R */
3567 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
3568 privoxy_mutex_init(&rand_mutex);
3569 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
3571 #endif /* def MUTEX_LOCKS_AVAILABLE */
3574 /*********************************************************************
3578 * Description : Load the config file and start the listen loop.
3579 * This function is a lot more *sane* with the `load_config'
3580 * and `listen_loop' functions; although it stills does
3581 * a *little* too much for my taste.
3584 * 1 : argc = Number of parameters (including $0).
3585 * 2 : argv = Array of (char *)'s to the parameters.
3587 * Returns : 1 if : can't open config file, unrecognized directive,
3588 * stats requested in multi-thread mode, can't open the
3589 * log file, can't open the jar file, listen port is invalid,
3590 * any load fails, and can't bind port.
3592 * Else main never returns, the process must be signaled
3593 * to terminate execution. Or, on Windows, use the
3594 * "File", "Exit" menu option.
3596 *********************************************************************/
3598 int real_main(int argc, char **argv)
3600 int main(int argc, char **argv)
3604 int do_config_test = 0;
3605 #ifndef HAVE_ARC4RANDOM
3606 unsigned int random_seed;
3609 struct passwd *pw = NULL;
3610 struct group *grp = NULL;
3612 char *pre_chroot_nslookup_to_load_resolver = NULL;
3615 char *fuzz_input_type = NULL;
3616 char *fuzz_input_file = NULL;
3623 #if !defined(_WIN32)
3630 /* Prepare mutexes if supported and necessary. */
3631 initialize_mutexes();
3633 /* Enable logging until further notice. */
3637 * Parse the command line arguments
3639 * XXX: simply printing usage information in case of
3640 * invalid arguments isn't particularly user friendly.
3642 while (++argc_pos < argc)
3645 /* Check to see if the service must be installed or uninstalled */
3646 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3648 const char *pName = argv[argc_pos] + 9;
3651 exit((install_service(pName)) ? 0 : 1);
3653 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3655 const char *pName = argv[argc_pos] + 11;
3658 exit((uninstall_service(pName)) ? 0 : 1);
3660 else if (strcmp(argv[argc_pos], "--service") == 0)
3662 bRunAsService = TRUE;
3663 w32_set_service_cwd();
3664 atexit(w32_service_exit_notify);
3667 #endif /* defined(_WIN32) */
3670 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3672 if (strcmp(argv[argc_pos], "--help") == 0)
3677 else if (strcmp(argv[argc_pos], "--version") == 0)
3679 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3685 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3687 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3691 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3693 if (++argc_pos == argc) usage(argv[0]);
3694 pidfile = strdup_or_die(argv[argc_pos]);
3697 else if (strcmp(argv[argc_pos], "--user") == 0)
3702 if (++argc_pos == argc) usage(argv[argc_pos]);
3704 user_arg = strdup_or_die(argv[argc_pos]);
3705 group_name = strchr(user_arg, '.');
3706 if (NULL != group_name)
3708 /* Nul-terminate the user name */
3711 /* Skip the former delimiter to actually reach the group name */
3714 grp = getgrnam(group_name);
3717 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3720 pw = getpwnam(user_arg);
3723 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3729 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3731 if (++argc_pos == argc) usage(argv[0]);
3732 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3735 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3739 #endif /* defined(unix) */
3741 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3746 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
3749 if (argc < argc_pos + 2) usage(argv[0]);
3750 fuzz_input_type = argv[argc_pos];
3752 fuzz_input_file = argv[argc_pos];
3754 else if (strcmp(argv[argc_pos], "--stfu") == 0)
3756 set_debug_level(LOG_LEVEL_STFU);
3759 else if (argc_pos + 1 != argc)
3762 * This is neither the last command line
3763 * option, nor was it recognized before,
3764 * therefore it must be invalid.
3770 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3772 configfile = argv[argc_pos];
3775 } /* -END- while (more arguments) */
3777 show_version(Argv[0]);
3780 if (*configfile != '/')
3782 char cwd[BUFFER_SIZE];
3784 size_t abs_file_size;
3786 /* make config-filename absolute here */
3787 if (NULL == getcwd(cwd, sizeof(cwd)))
3789 perror("failed to get current working directory");
3793 basedir = strdup_or_die(cwd);
3795 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3796 abs_file = malloc_or_die(abs_file_size);
3797 strlcpy(abs_file, basedir, abs_file_size);
3798 strlcat(abs_file, "/", abs_file_size);
3799 strlcat(abs_file, configfile, abs_file_size);
3800 configfile = abs_file;
3802 #endif /* defined unix */
3806 clients->next = NULL;
3808 /* XXX: factor out initialising after the next stable release. */
3813 #ifndef HAVE_ARC4RANDOM
3814 random_seed = (unsigned int)time(NULL);
3816 srandom(random_seed);
3819 #endif /* ifdef HAVE_RANDOM */
3820 #endif /* ifndef HAVE_ARC4RANDOM */
3823 * Unix signal handling
3825 * Catch the abort, interrupt and terminate signals for a graceful exit
3826 * Catch the hangup signal so the errlog can be reopened.
3828 * Ignore the broken pipe signal as connection failures
3829 * are handled when and where they occur without relying
3832 #if !defined(_WIN32) && !defined(__OS2__)
3835 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3837 for (idx = 0; idx < SZ(catched_signals); idx++)
3839 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3840 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3842 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3843 #endif /* ifdef sun */
3845 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3849 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3851 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3855 #else /* ifdef _WIN32 */
3856 # ifdef _WIN_CONSOLE
3858 * We *are* in a windows console app.
3859 * Print a verbose messages about FAQ's and such
3861 printf("%s", win32_blurb);
3862 # endif /* def _WIN_CONSOLE */
3863 #endif /* def _WIN32 */
3866 if (fuzz_input_type != NULL)
3868 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
3870 log_error(LOG_LEVEL_FATAL,
3871 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
3872 "Various data structures are static which is unsafe when using threads.");
3877 exit(NULL == load_config());
3880 /* Initialize the CGI subsystem */
3881 cgi_init_error_messages();
3884 * If running on unix and without the --no-daemon
3885 * option, become a daemon. I.e. fork, detach
3886 * from tty and get process group leadership
3895 if (pid < 0) /* error */
3900 else if (pid != 0) /* parent */
3905 * must check for errors
3906 * child died due to missing files aso
3909 wpid = waitpid(pid, &status, WNOHANG);
3921 * stderr (fd 2) will be closed later on,
3922 * when the config file has been parsed.
3928 * Reserve fd 0 and 1 to prevent abort() and friends
3929 * from sending stuff to the clients or servers.
3931 fd = open("/dev/null", O_RDONLY);
3934 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3938 if (dup2(fd, 0) == -1)
3940 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3944 fd = open("/dev/null", O_WRONLY);
3947 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3951 if (dup2(fd, 1) == -1)
3953 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3958 #ifdef FEATURE_EXTERNAL_FILTERS
3959 for (fd = 0; fd < 3; fd++)
3961 mark_socket_for_close_on_execute(fd);
3967 } /* -END- if (daemon_mode) */
3970 * As soon as we have written the PID file, we can switch
3971 * to the user and group ID indicated by the --user option
3973 if (pidfile != NULL)
3975 write_pid_file(pidfile);
3979 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3981 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3985 if (setgroups(1, &grp->gr_gid))
3987 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3990 else if (initgroups(pw->pw_name, pw->pw_gid))
3992 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3998 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
4000 /* Read the time zone file from /etc before doing chroot. */
4002 if (NULL != pre_chroot_nslookup_to_load_resolver
4003 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
4005 /* Initialize resolver library. */
4006 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
4008 if (chroot(pw->pw_dir) < 0)
4010 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
4014 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
4017 if (setuid(pw->pw_uid))
4019 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
4023 char putenv_dummy[64];
4025 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
4026 if (putenv(putenv_dummy) != 0)
4028 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
4031 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
4032 if (putenv(putenv_dummy) != 0)
4034 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
4040 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
4043 #endif /* defined unix */
4046 /* This will be FALSE unless the command line specified --service
4050 /* Yup, so now we must attempt to establish a connection
4051 * with the service dispatcher. This will only work if this
4052 * process was launched by the service control manager to
4053 * actually run as a service. If this isn't the case, i've
4054 * known it take around 30 seconds or so for the call to return.
4057 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
4058 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
4060 /* Service has run, and at this point is now being stopped, so just return */
4065 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
4067 /* An error occurred. Usually it's because --service was wrongly specified
4068 * and we were unable to connect to the Service Control Dispatcher because
4069 * it wasn't expecting us and is therefore not listening.
4071 * For now, just continue below to call the listen_loop function.
4074 #endif /* def _WIN32 */
4084 /*********************************************************************
4086 * Function : bind_port_helper
4088 * Description : Bind the listen port. Handles logging, and aborts
4092 * 1 : haddr = Host address to bind to. Use NULL to bind to
4094 * 2 : hport = Specifies port to bind to.
4095 * 3 : backlog = Listen backlog.
4097 * Returns : Port that was opened.
4099 *********************************************************************/
4100 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
4105 result = bind_port(haddr, hport, backlog, &bfd);
4109 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
4113 log_error(LOG_LEVEL_FATAL,
4114 "can't bind to %s:%d: There may be another Privoxy "
4115 "or some other proxy running on port %d",
4116 bind_address, hport, hport);
4119 log_error(LOG_LEVEL_FATAL,
4120 "can't bind to %s:%d: The hostname is not resolvable",
4121 bind_address, hport);
4124 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
4125 bind_address, hport);
4128 /* shouldn't get here */
4129 return JB_INVALID_SOCKET;
4134 if (bfd >= FD_SETSIZE)
4136 log_error(LOG_LEVEL_FATAL,
4137 "Bind socket number too high to use select(): %d >= %d",
4145 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
4150 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
4158 /*********************************************************************
4160 * Function : bind_ports_helper
4162 * Description : Bind the listen ports. Handles logging, and aborts
4166 * 1 : config = Privoxy configuration. Specifies ports
4168 * 2 : sockets = Preallocated array of opened sockets
4169 * corresponding to specification in config.
4170 * All non-opened sockets will be set to
4171 * JB_INVALID_SOCKET.
4173 * Returns : Nothing. Inspect sockets argument.
4175 *********************************************************************/
4176 static void bind_ports_helper(struct configuration_spec * config,
4177 jb_socket sockets[])
4181 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4183 if (config->hport[i])
4185 sockets[i] = bind_port_helper(config->haddr[i],
4186 config->hport[i], config->listen_backlog);
4187 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
4188 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
4190 struct accept_filter_arg af_options;
4191 bzero(&af_options, sizeof(af_options));
4192 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
4193 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
4194 sizeof(af_options)))
4196 log_error(LOG_LEVEL_ERROR,
4197 "Enabling accept filter for socket %d failed: %E", sockets[i]);
4204 sockets[i] = JB_INVALID_SOCKET;
4207 config->need_bind = 0;
4211 /*********************************************************************
4213 * Function : close_ports_helper
4215 * Description : Close listenings ports.
4218 * 1 : sockets = Array of opened and non-opened sockets to
4219 * close. All sockets will be set to
4220 * JB_INVALID_SOCKET.
4222 * Returns : Nothing.
4224 *********************************************************************/
4225 static void close_ports_helper(jb_socket sockets[])
4229 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4231 if (JB_INVALID_SOCKET != sockets[i])
4233 close_socket(sockets[i]);
4235 sockets[i] = JB_INVALID_SOCKET;
4241 /* Without this simple workaround we get this compiler warning from _beginthread
4242 * warning C4028: formal parameter 1 different from declaration
4244 void w32_service_listen_loop(void *p)
4248 #endif /* def _WIN32 */
4251 /*********************************************************************
4253 * Function : listen_loop
4255 * Description : bind the listen port and enter a "FOREVER" listening loop.
4261 *********************************************************************/
4262 static void listen_loop(void)
4264 struct client_states *csp_list = NULL;
4265 struct client_state *csp = NULL;
4266 jb_socket bfds[MAX_LISTENING_SOCKETS];
4267 struct configuration_spec *config;
4268 unsigned int active_threads = 0;
4269 #if defined(FEATURE_PTHREAD)
4270 pthread_attr_t attrs;
4272 pthread_attr_init(&attrs);
4273 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4276 config = load_config();
4278 #ifdef FEATURE_CONNECTION_SHARING
4280 * XXX: Should be relocated once it no
4281 * longer needs to emit log messages.
4283 initialize_reusable_connections();
4284 #endif /* def FEATURE_CONNECTION_SHARING */
4286 bind_ports_helper(config, bfds);
4288 #ifdef FEATURE_GRACEFUL_TERMINATION
4289 while (!g_terminate)
4294 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
4295 while (waitpid(-1, NULL, WNOHANG) > 0)
4297 /* zombie children */
4299 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
4302 * Free data that was used by died threads
4304 active_threads = sweep();
4308 * Re-open the errlog after HUP signal
4310 if (received_hup_signal)
4312 if (NULL != config->logfile)
4314 init_error_log(Argv[0], config->logfile);
4316 received_hup_signal = 0;
4320 csp_list = zalloc_or_die(sizeof(*csp_list));
4321 csp = &csp_list->csp;
4323 log_error(LOG_LEVEL_CONNECT,
4324 "Waiting for the next client connection. Currently active threads: %d",
4328 * This config may be outdated, but for accept_connection()
4329 * it's fresh enough.
4331 csp->config = config;
4333 if (!accept_connection(csp, bfds))
4335 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
4340 csp->flags |= CSP_FLAG_ACTIVE;
4341 csp->server_connection.sfd = JB_INVALID_SOCKET;
4343 csp->config = config = load_config();
4345 if (config->need_bind)
4348 * Since we were listening to the "old port", we will not see
4349 * a "listen" param change until the next request. So, at
4350 * least 1 more request must be made for us to find the new
4351 * setting. I am simply closing the old socket and binding the
4354 * Which-ever is correct, we will serve 1 more page via the
4355 * old settings. This should probably be a "show-status"
4356 * request. This should not be a so common of an operation
4357 * that this will hurt people's feelings.
4360 close_ports_helper(bfds);
4362 bind_ports_helper(config, bfds);
4365 #ifdef FEATURE_TOGGLE
4366 if (global_toggle_state)
4367 #endif /* def FEATURE_TOGGLE */
4369 csp->flags |= CSP_FLAG_TOGGLED_ON;
4372 if (run_loader(csp))
4374 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
4375 /* Never get here - LOG_LEVEL_FATAL causes program exit */
4379 if (block_acl(NULL,csp))
4381 log_error(LOG_LEVEL_CONNECT,
4382 "Connection from %s on %s (socket %d) dropped due to ACL",
4383 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
4384 close_socket(csp->cfd);
4385 freez(csp->ip_addr_str);
4386 freez(csp->listen_addr_str);
4390 #endif /* def FEATURE_ACL */
4392 if ((0 != config->max_client_connections)
4393 && (active_threads >= config->max_client_connections))
4395 log_error(LOG_LEVEL_CONNECT,
4396 "Rejecting connection from %s. Maximum number of connections reached.",
4398 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4399 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4400 close_socket(csp->cfd);
4401 freez(csp->ip_addr_str);
4402 freez(csp->listen_addr_str);
4407 /* add it to the list of clients */
4408 csp_list->next = clients->next;
4409 clients->next = csp_list;
4411 if (config->multi_threaded)
4415 /* this is a switch () statement in the C preprocessor - ugh */
4416 #undef SELECTED_ONE_OPTION
4418 /* Use Pthreads in preference to native code */
4419 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
4420 #define SELECTED_ONE_OPTION
4422 pthread_t the_thread;
4424 errno = pthread_create(&the_thread, &attrs,
4425 (void * (*)(void *))serve, csp);
4426 child_id = errno ? -1 : 0;
4430 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
4431 #define SELECTED_ONE_OPTION
4432 child_id = _beginthread(
4433 (void (*)(void *))serve,
4438 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
4439 #define SELECTED_ONE_OPTION
4440 child_id = _beginthread(
4441 (void(* _Optlink)(void*))serve,
4447 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
4448 #define SELECTED_ONE_OPTION
4450 thread_id tid = spawn_thread
4451 (server_thread, "server", B_NORMAL_PRIORITY, csp);
4453 if ((tid >= 0) && (resume_thread(tid) == B_OK))
4455 child_id = (int) tid;
4464 #if !defined(SELECTED_ONE_OPTION)
4467 /* This block is only needed when using fork().
4468 * When using threads, the server thread was
4469 * created and run by the call to _beginthread().
4471 if (child_id == 0) /* child */
4474 #ifdef FEATURE_TOGGLE
4475 int inherited_toggle_state = global_toggle_state;
4476 #endif /* def FEATURE_TOGGLE */
4481 * If we've been toggled or we've blocked the request, tell Mom
4484 #ifdef FEATURE_TOGGLE
4485 if (inherited_toggle_state != global_toggle_state)
4487 rc |= RC_FLAG_TOGGLED;
4489 #endif /* def FEATURE_TOGGLE */
4491 #ifdef FEATURE_STATISTICS
4492 if (csp->flags & CSP_FLAG_REJECTED)
4494 rc |= RC_FLAG_BLOCKED;
4496 #endif /* ndef FEATURE_STATISTICS */
4500 else if (child_id > 0) /* parent */
4502 /* in a fork()'d environment, the parent's
4503 * copy of the client socket and the CSP
4507 #if !defined(_WIN32) && !defined(__CYGWIN__)
4509 wait(&child_status);
4512 * Evaluate child's return code: If the child has
4513 * - been toggled, toggle ourselves
4514 * - blocked its request, bump up the stats counter
4517 #ifdef FEATURE_TOGGLE
4518 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4520 global_toggle_state = !global_toggle_state;
4522 #endif /* def FEATURE_TOGGLE */
4524 #ifdef FEATURE_STATISTICS
4526 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4530 #endif /* def FEATURE_STATISTICS */
4532 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4533 close_socket(csp->cfd);
4534 csp->flags &= ~CSP_FLAG_ACTIVE;
4538 #undef SELECTED_ONE_OPTION
4539 /* end of cpp switch () */
4544 * Spawning the child failed, assume it's because
4545 * there are too many children running already.
4546 * XXX: If you assume ...
4548 log_error(LOG_LEVEL_ERROR,
4549 "Unable to take any additional connections: %E. Active threads: %d",
4551 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4552 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4553 close_socket(csp->cfd);
4554 csp->flags &= ~CSP_FLAG_ACTIVE;
4563 #if defined(FEATURE_PTHREAD)
4564 pthread_attr_destroy(&attrs);
4567 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4569 /* Clean up. Aim: free all memory (no leaks) */
4570 #ifdef FEATURE_GRACEFUL_TERMINATION
4572 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4574 unload_current_config_file();
4575 unload_current_actions_file();
4576 unload_current_re_filterfile();
4577 #ifdef FEATURE_TRUST
4578 unload_current_trust_file();
4581 if (config->multi_threaded)
4588 } while ((clients->next != NULL) && (--i > 0));
4592 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4602 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4603 /* Cleanup - remove taskbar icon etc. */
4608 #endif /* FEATURE_GRACEFUL_TERMINATION */