1 const char jcc_rcs[] = "$Id: jcc.c,v 1.458 2017/05/29 10:02:11 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001-2017 the
10 * Privoxy team. http://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 *********************************************************************/
40 #include <sys/types.h>
49 # ifndef FEATURE_PTHREAD
53 # include <winsock2.h>
56 # endif /* ndef FEATURE_PTHREAD */
61 # endif /* ndef _WIN_CONSOLE */
62 # include "w32svrapi.h"
64 #else /* ifndef _WIN32 */
66 # if !defined (__OS2__)
68 # include <sys/wait.h>
69 # endif /* ndef __OS2__ */
70 # include <sys/time.h>
71 # include <sys/stat.h>
72 # include <sys/ioctl.h>
75 #include <sys/termios.h>
86 # include <socket.h> /* BeOS has select() for sockets only. */
87 # include <OS.h> /* declarations for threads and stuff. */
90 # if defined(__EMX__) || defined(__OS2__)
91 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
100 #include <sys/poll.h>
103 #endif /* def __GLIBC__ */
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"
130 const char jcc_h_rcs[] = JCC_H_VERSION;
131 const char project_h_rcs[] = PROJECT_H_VERSION;
134 struct client_states clients[1];
135 struct file_list files[1];
137 #ifdef FEATURE_STATISTICS
138 int urls_read = 0; /* total nr of urls read inc rejected */
139 int urls_rejected = 0; /* total nr of urls rejected */
140 #endif /* def FEATURE_STATISTICS */
142 #ifdef FEATURE_GRACEFUL_TERMINATION
146 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
147 static void sig_handler(int the_signal);
149 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
150 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
151 static jb_err get_server_headers(struct client_state *csp);
152 static const char *crunch_reason(const struct http_response *rsp);
153 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
154 static char *get_request_line(struct client_state *csp);
155 static jb_err receive_client_request(struct client_state *csp);
156 static jb_err parse_client_request(struct client_state *csp);
157 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
158 static jb_err change_request_destination(struct client_state *csp);
159 static void chat(struct client_state *csp);
160 static void serve(struct client_state *csp);
161 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
162 static void usage(const char *myname);
164 static void initialize_mutexes(void);
165 static jb_socket bind_port_helper(const char *haddr, int hport);
166 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
167 static void close_ports_helper(jb_socket sockets[]);
168 static void listen_loop(void);
171 void serve(struct client_state *csp);
172 #else /* ifndef AMIGA */
173 static void serve(struct client_state *csp);
174 #endif /* def AMIGA */
177 static int32 server_thread(void *data);
178 #endif /* def __BEOS__ */
181 #define sleep(N) Sleep(((N) * 1000))
185 #define sleep(N) DosSleep(((N) * 100))
189 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
190 void show_fuzz_usage(const char *name);
193 #ifdef MUTEX_LOCKS_AVAILABLE
195 * XXX: Does the locking stuff really belong in this file?
197 privoxy_mutex_t log_mutex;
198 privoxy_mutex_t log_init_mutex;
199 privoxy_mutex_t connection_reuse_mutex;
201 #ifdef FEATURE_EXTERNAL_FILTERS
202 privoxy_mutex_t external_filter_mutex;
204 #ifdef FEATURE_CLIENT_TAGS
205 privoxy_mutex_t client_tags_mutex;
208 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
209 privoxy_mutex_t resolver_mutex;
210 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
212 #ifndef HAVE_GMTIME_R
213 privoxy_mutex_t gmtime_mutex;
214 #endif /* ndef HAVE_GMTIME_R */
216 #ifndef HAVE_LOCALTIME_R
217 privoxy_mutex_t localtime_mutex;
218 #endif /* ndef HAVE_GMTIME_R */
220 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
221 privoxy_mutex_t rand_mutex;
222 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
224 #endif /* def MUTEX_LOCKS_AVAILABLE */
227 const char *basedir = NULL;
228 const char *pidfile = NULL;
229 static int received_hup_signal = 0;
230 #endif /* defined unix */
232 /* HTTP snipplets. */
233 static const char CSUCCEED[] =
234 "HTTP/1.1 200 Connection established\r\n\r\n";
236 static const char CHEADER[] =
237 "HTTP/1.1 400 Invalid header received from client\r\n"
238 "Content-Type: text/plain\r\n"
239 "Connection: close\r\n\r\n"
240 "Invalid header received from client.\r\n";
242 static const char FTP_RESPONSE[] =
243 "HTTP/1.1 400 Invalid request received from client\r\n"
244 "Content-Type: text/plain\r\n"
245 "Connection: close\r\n\r\n"
246 "Invalid request. Privoxy doesn't support FTP.\r\n";
248 static const char GOPHER_RESPONSE[] =
249 "HTTP/1.1 400 Invalid request received from client\r\n"
250 "Content-Type: text/plain\r\n"
251 "Connection: close\r\n\r\n"
252 "Invalid request. Privoxy doesn't support gopher.\r\n";
254 /* XXX: should be a template */
255 static const char MISSING_DESTINATION_RESPONSE[] =
256 "HTTP/1.1 400 Bad request received from client\r\n"
257 "Content-Type: text/plain\r\n"
258 "Connection: close\r\n\r\n"
259 "Bad request. Privoxy was unable to extract the destination.\r\n";
261 /* XXX: should be a template */
262 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
263 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
264 "Content-Type: text/plain\r\n"
265 "Connection: close\r\n\r\n"
266 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
268 /* XXX: should be a template */
269 static const char MESSED_UP_REQUEST_RESPONSE[] =
270 "HTTP/1.1 400 Malformed request after rewriting\r\n"
271 "Content-Type: text/plain\r\n"
272 "Connection: close\r\n\r\n"
273 "Bad request. Messed up with header filters.\r\n";
275 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
276 "HTTP/1.1 503 Too many open connections\r\n"
277 "Content-Type: text/plain\r\n"
278 "Connection: close\r\n\r\n"
279 "Maximum number of open connections reached.\r\n";
281 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
282 "HTTP/1.1 504 Connection timeout\r\n"
283 "Content-Type: text/plain\r\n"
284 "Connection: close\r\n\r\n"
285 "The connection timed out because the client request didn't arrive in time.\r\n";
287 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
288 "HTTP/1.1 400 Failed reading client body\r\n"
289 "Content-Type: text/plain\r\n"
290 "Connection: close\r\n\r\n"
291 "Failed parsing or buffering the chunk-encoded client body.\r\n";
293 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
294 "HTTP/1.1 417 Expecting too much\r\n"
295 "Content-Type: text/plain\r\n"
296 "Connection: close\r\n\r\n"
297 "Privoxy detected an unsupported Expect header value.\r\n";
299 /* A function to crunch a response */
300 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
302 /* Crunch function flags */
303 #define CF_NO_FLAGS 0
304 /* Cruncher applies to forced requests as well */
305 #define CF_IGNORE_FORCE 1
306 /* Crunched requests are counted for the block statistics */
307 #define CF_COUNT_AS_REJECT 2
309 /* A crunch function and its flags */
312 const crunch_func_ptr cruncher;
316 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
318 /* Complete list of cruncher functions */
319 static const struct cruncher crunchers_all[] = {
320 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
321 { block_url, CF_COUNT_AS_REJECT },
323 { trust_url, CF_COUNT_AS_REJECT },
324 #endif /* def FEATURE_TRUST */
325 { redirect_url, CF_NO_FLAGS },
326 { dispatch_cgi, CF_IGNORE_FORCE},
330 /* Light version, used after tags are applied */
331 static const struct cruncher crunchers_light[] = {
332 { block_url, CF_COUNT_AS_REJECT },
333 { redirect_url, CF_NO_FLAGS },
339 * XXX: Don't we really mean
345 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
346 /*********************************************************************
348 * Function : sig_handler
350 * Description : Signal handler for different signals.
351 * Exit gracefully on TERM and INT
352 * or set a flag that will cause the errlog
353 * to be reopened by the main thread on HUP.
356 * 1 : the_signal = the signal cause this function to call
360 *********************************************************************/
361 static void sig_handler(int the_signal)
367 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
379 received_hup_signal = 1;
385 * We shouldn't be here, unless we catch signals
386 * in main() that we can't handle here!
388 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
396 /*********************************************************************
398 * Function : client_protocol_is_unsupported
400 * Description : Checks if the client used a known unsupported
401 * protocol and deals with it by sending an error
405 * 1 : csp = Current client state (buffers, headers, etc...)
406 * 2 : req = the first request line send by the client
408 * Returns : TRUE if an error response has been generated, or
409 * FALSE if the request doesn't look invalid.
411 *********************************************************************/
412 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
415 * If it's a FTP or gopher request, we don't support it.
417 * These checks are better than nothing, but they might
418 * not work in all configurations and some clients might
419 * have problems digesting the answer.
421 * They should, however, never cause more problems than
422 * Privoxy's old behaviour (returning the misleading HTML
425 * "Could not resolve http://(ftp|gopher)://example.org").
427 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
429 const char *response = NULL;
430 const char *protocol = NULL;
432 if (!strncmpic(req, "GET ftp://", 10))
434 response = FTP_RESPONSE;
439 response = GOPHER_RESPONSE;
442 log_error(LOG_LEVEL_ERROR,
443 "%s tried to use Privoxy as %s proxy: %s",
444 csp->ip_addr_str, protocol, req);
445 log_error(LOG_LEVEL_CLF,
446 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
448 write_socket(csp->cfd, response, strlen(response));
457 /*********************************************************************
459 * Function : client_has_unsupported_expectations
461 * Description : Checks if the client used an unsupported expectation
462 * in which case an error message is delivered.
465 * 1 : csp = Current client state (buffers, headers, etc...)
467 * Returns : TRUE if an error response has been generated, or
468 * FALSE if the request doesn't look invalid.
470 *********************************************************************/
471 static int client_has_unsupported_expectations(const struct client_state *csp)
473 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
475 log_error(LOG_LEVEL_ERROR,
476 "Rejecting request from client %s with unsupported Expect header value",
478 log_error(LOG_LEVEL_CLF,
479 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
480 write_socket(csp->cfd, UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
481 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE));
491 /*********************************************************************
493 * Function : get_request_destination_elsewhere
495 * Description : If the client's request was redirected into
496 * Privoxy without the client's knowledge,
497 * the request line lacks the destination host.
499 * This function tries to get it elsewhere,
500 * provided accept-intercepted-requests is enabled.
502 * "Elsewhere" currently only means "Host: header",
503 * but in the future we may ask the redirecting
504 * packet filter to look the destination up.
506 * If the destination stays unknown, an error
507 * response is send to the client and headers
508 * are freed so that chat() can return directly.
511 * 1 : csp = Current client state (buffers, headers, etc...)
512 * 2 : headers = a header list
514 * Returns : JB_ERR_OK if the destination is now known, or
515 * JB_ERR_PARSE if it isn't.
517 *********************************************************************/
518 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
522 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
524 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
525 " Privoxy isn't configured to accept intercepted requests.",
526 csp->ip_addr_str, csp->http->cmd);
527 /* XXX: Use correct size */
528 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
529 csp->ip_addr_str, csp->http->cmd);
531 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
532 destroy_list(headers);
536 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
538 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
539 /* Split the domain we just got for pattern matching */
540 init_domain_components(csp->http);
547 /* We can't work without destination. Go spread the news.*/
549 req = list_to_text(headers);
551 /* XXX: Use correct size */
552 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
553 csp->ip_addr_str, csp->http->cmd);
554 log_error(LOG_LEVEL_ERROR,
555 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
556 csp->ip_addr_str, csp->http->cmd, req);
559 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
560 destroy_list(headers);
565 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
566 * to get the destination IP address, use it as host directly
567 * or do a reverse DNS lookup first.
572 /*********************************************************************
574 * Function : get_server_headers
576 * Description : Parses server headers in iob and fills them
577 * into csp->headers so that they can later be
581 * 1 : csp = Current client state (buffers, headers, etc...)
583 * Returns : JB_ERR_OK if everything went fine, or
584 * JB_ERR_PARSE if the headers were incomplete.
586 *********************************************************************/
587 static jb_err get_server_headers(struct client_state *csp)
589 int continue_hack_in_da_house = 0;
592 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
597 * continue hack in da house. Ignore the ending of
598 * this head and continue enlisting header lines.
599 * The reason is described below.
601 enlist(csp->headers, "");
602 continue_hack_in_da_house = 0;
605 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
608 * It's a bodyless continue response, don't
609 * stop header parsing after reaching its end.
611 * As a result Privoxy will concatenate the
612 * next response's head and parse and deliver
613 * the headers as if they belonged to one request.
615 * The client will separate them because of the
616 * empty line between them.
618 * XXX: What we're doing here is clearly against
619 * the intended purpose of the continue header,
620 * and under some conditions (HTTP/1.0 client request)
621 * it's a standard violation.
623 * Anyway, "sort of against the spec" is preferable
624 * to "always getting confused by Continue responses"
625 * (Privoxy's behaviour before this hack was added)
627 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
628 continue_hack_in_da_house = 1;
630 else if (*header == '\0')
633 * If the header is empty, but the Continue hack
634 * isn't active, we can assume that we reached the
635 * end of the buffer before we hit the end of the
638 * Inform the caller an let it decide how to handle it.
643 if (JB_ERR_MEMORY == enlist(csp->headers, header))
646 * XXX: Should we quit the request and return a
647 * out of memory error page instead?
649 log_error(LOG_LEVEL_ERROR,
650 "Out of memory while enlisting server headers. %s lost.",
660 /*********************************************************************
662 * Function : crunch_reason
664 * Description : Translates the crunch reason code into a string.
667 * 1 : rsp = a http_response
669 * Returns : A string with the crunch reason or an error description.
671 *********************************************************************/
672 static const char *crunch_reason(const struct http_response *rsp)
674 char * reason = NULL;
679 return "Internal error while searching for crunch reason";
682 switch (rsp->crunch_reason)
685 reason = "Unsupported HTTP feature";
691 reason = "Untrusted";
694 reason = "Redirected";
700 reason = "DNS failure";
702 case FORWARDING_FAILED:
703 reason = "Forwarding failed";
706 reason = "Connection failure";
709 reason = "Out of memory (may mask other reasons)";
711 case CONNECTION_TIMEOUT:
712 reason = "Connection timeout";
715 reason = "No server data received";
718 reason = "No reason recorded";
726 /*********************************************************************
728 * Function : log_applied_actions
730 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
734 * 1 : actions = Current action spec to log
738 *********************************************************************/
739 static void log_applied_actions(const struct current_action_spec *actions)
742 * The conversion to text requires lots of memory allocations so
743 * we only do the conversion if the user is actually interested.
745 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
747 char *actions_as_text = actions_to_line_of_text(actions);
748 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
749 freez(actions_as_text);
754 /*********************************************************************
756 * Function : send_crunch_response
758 * Description : Delivers already prepared response for
759 * intercepted requests, logs the interception
760 * and frees the response.
763 * 1 : csp = Current client state (buffers, headers, etc...)
764 * 1 : rsp = Fully prepared response. Will be freed on exit.
768 *********************************************************************/
769 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
771 const struct http_request *http = csp->http;
775 assert(rsp->head != NULL);
779 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
783 * Extract the status code from the actual head
784 * that will be send to the client. It is the only
785 * way to get it right for all requests, including
786 * the fixed ones for out-of-memory problems.
788 * A head starts like this: 'HTTP/1.1 200...'
792 status_code[0] = rsp->head[9];
793 status_code[1] = rsp->head[10];
794 status_code[2] = rsp->head[11];
795 status_code[3] = '\0';
797 /* Log that the request was crunched and why. */
798 log_applied_actions(csp->action);
799 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
800 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
801 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
803 /* Write the answer to the client */
804 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
805 || write_socket(csp->cfd, rsp->body, rsp->content_length))
807 /* There is nothing we can do about it. */
808 log_error(LOG_LEVEL_ERROR,
809 "Couldn't deliver the error message through client socket %d: %E",
813 /* Clean up and return */
814 if (cgi_error_memory() != rsp)
816 free_http_response(rsp);
822 /*********************************************************************
824 * Function : crunch_response_triggered
826 * Description : Checks if the request has to be crunched,
827 * and delivers the crunch response if necessary.
830 * 1 : csp = Current client state (buffers, headers, etc...)
831 * 2 : crunchers = list of cruncher functions to run
833 * Returns : TRUE if the request was answered with a crunch response
836 *********************************************************************/
837 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
839 struct http_response *rsp = NULL;
840 const struct cruncher *c;
843 * If CGI request crunching is disabled,
844 * check the CGI dispatcher out of order to
845 * prevent unintentional blocks or redirects.
847 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
848 && (NULL != (rsp = dispatch_cgi(csp))))
850 /* Deliver, log and free the interception response. */
851 send_crunch_response(csp, rsp);
852 csp->flags |= CSP_FLAG_CRUNCHED;
856 for (c = crunchers; c->cruncher != NULL; c++)
859 * Check the cruncher if either Privoxy is toggled
860 * on and the request isn't forced, or if the cruncher
861 * applies to forced requests as well.
863 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
864 !(csp->flags & CSP_FLAG_FORCED)) ||
865 (c->flags & CF_IGNORE_FORCE))
867 rsp = c->cruncher(csp);
870 /* Deliver, log and free the interception response. */
871 send_crunch_response(csp, rsp);
872 csp->flags |= CSP_FLAG_CRUNCHED;
873 #ifdef FEATURE_STATISTICS
874 if (c->flags & CF_COUNT_AS_REJECT)
876 csp->flags |= CSP_FLAG_REJECTED;
878 #endif /* def FEATURE_STATISTICS */
889 /*********************************************************************
891 * Function : build_request_line
893 * Description : Builds the HTTP request line.
895 * If a HTTP forwarder is used it expects the whole URL,
896 * web servers only get the path.
899 * 1 : csp = Current client state (buffers, headers, etc...)
900 * 2 : fwd = The forwarding spec used for the request
901 * XXX: Should use http->fwd instead.
902 * 3 : request_line = The old request line which will be replaced.
904 * Returns : Nothing. Terminates in case of memory problems.
906 *********************************************************************/
907 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
909 struct http_request *http = csp->http;
911 assert(http->ssl == 0);
914 * Downgrade http version from 1.1 to 1.0
915 * if +downgrade action applies.
917 if ((csp->action->flags & ACTION_DOWNGRADE)
918 && (!strcmpic(http->ver, "HTTP/1.1")))
921 http->ver = strdup_or_die("HTTP/1.0");
925 * Rebuild the request line.
927 freez(*request_line);
928 *request_line = strdup(http->gpc);
929 string_append(request_line, " ");
931 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
933 string_append(request_line, http->url);
937 string_append(request_line, http->path);
939 string_append(request_line, " ");
940 string_append(request_line, http->ver);
942 if (*request_line == NULL)
944 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
946 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
950 /*********************************************************************
952 * Function : change_request_destination
954 * Description : Parse a (rewritten) request line and regenerate
955 * the http request data.
958 * 1 : csp = Current client state (buffers, headers, etc...)
960 * Returns : Forwards the parse_http_request() return code.
961 * Terminates in case of memory problems.
963 *********************************************************************/
964 static jb_err change_request_destination(struct client_state *csp)
966 struct http_request *http = csp->http;
969 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
970 csp->headers->first->str);
971 free_http_request(http);
972 err = parse_http_request(csp->headers->first->str, http);
973 if (JB_ERR_OK != err)
975 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
976 jb_err_to_string(err));
983 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
984 /*********************************************************************
986 * Function : server_response_is_complete
988 * Description : Determines whether we should stop reading
989 * from the server socket.
992 * 1 : csp = Current client state (buffers, headers, etc...)
993 * 2 : content_length = Length of content received so far.
995 * Returns : TRUE if the response is complete,
998 *********************************************************************/
999 static int server_response_is_complete(struct client_state *csp,
1000 unsigned long long content_length)
1002 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1004 if (!strcmpic(csp->http->gpc, "HEAD"))
1007 * "HEAD" implies no body, we are thus expecting
1008 * no content. XXX: incomplete "list" of methods?
1010 csp->expected_content_length = 0;
1011 content_length_known = TRUE;
1012 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1015 if (csp->http->status == 204 || csp->http->status == 304)
1018 * Expect no body. XXX: incomplete "list" of status codes?
1020 csp->expected_content_length = 0;
1021 content_length_known = TRUE;
1022 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1025 return (content_length_known && ((0 == csp->expected_content_length)
1026 || (csp->expected_content_length <= content_length)));
1030 #ifdef FEATURE_CONNECTION_SHARING
1031 /*********************************************************************
1033 * Function : wait_for_alive_connections
1035 * Description : Waits for alive connections to timeout.
1041 *********************************************************************/
1042 static void wait_for_alive_connections(void)
1044 int connections_alive = close_unusable_connections();
1046 while (0 < connections_alive)
1048 log_error(LOG_LEVEL_CONNECT,
1049 "Waiting for %d connections to timeout.",
1052 connections_alive = close_unusable_connections();
1055 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1058 #endif /* def FEATURE_CONNECTION_SHARING */
1061 /*********************************************************************
1063 * Function : save_connection_destination
1065 * Description : Remembers a connection for reuse later on.
1068 * 1 : sfd = Open socket to remember.
1069 * 2 : http = The destination for the connection.
1070 * 3 : fwd = The forwarder settings used.
1071 * 3 : server_connection = storage.
1075 *********************************************************************/
1076 void save_connection_destination(jb_socket sfd,
1077 const struct http_request *http,
1078 const struct forward_spec *fwd,
1079 struct reusable_connection *server_connection)
1081 assert(sfd != JB_INVALID_SOCKET);
1082 assert(NULL != http->host);
1084 server_connection->sfd = sfd;
1085 server_connection->host = strdup_or_die(http->host);
1086 server_connection->port = http->port;
1088 assert(NULL != fwd);
1089 assert(server_connection->gateway_host == NULL);
1090 assert(server_connection->gateway_port == 0);
1091 assert(server_connection->forwarder_type == 0);
1092 assert(server_connection->forward_host == NULL);
1093 assert(server_connection->forward_port == 0);
1095 server_connection->forwarder_type = fwd->type;
1096 if (NULL != fwd->gateway_host)
1098 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1102 server_connection->gateway_host = NULL;
1104 server_connection->gateway_port = fwd->gateway_port;
1106 if (NULL != fwd->forward_host)
1108 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1112 server_connection->forward_host = NULL;
1114 server_connection->forward_port = fwd->forward_port;
1118 /*********************************************************************
1120 * Function : verify_request_length
1122 * Description : Checks if we already got the whole client requests
1123 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1126 * Data that doesn't belong to the current request is
1127 * either thrown away to let the client retry on a clean
1128 * socket, or stashed to be dealt with after the current
1129 * request is served.
1132 * 1 : csp = Current client state (buffers, headers, etc...)
1136 *********************************************************************/
1137 static void verify_request_length(struct client_state *csp)
1139 unsigned long long buffered_request_bytes =
1140 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1142 if ((csp->expected_client_content_length != 0)
1143 && (buffered_request_bytes != 0))
1145 if (csp->expected_client_content_length >= buffered_request_bytes)
1147 csp->expected_client_content_length -= buffered_request_bytes;
1148 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1149 "to account for the %llu ones we already got.",
1150 csp->expected_client_content_length, buffered_request_bytes);
1154 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1155 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1156 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1157 "Marking the server socket tainted after throwing %llu bytes away.",
1158 buffered_request_bytes - csp->expected_client_content_length);
1159 csp->expected_client_content_length = 0;
1160 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1163 if (csp->expected_client_content_length == 0)
1165 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1169 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1170 && ((csp->client_iob->cur < csp->client_iob->eod)
1171 || (csp->expected_client_content_length != 0)))
1173 if (strcmpic(csp->http->gpc, "GET")
1174 && strcmpic(csp->http->gpc, "HEAD")
1175 && strcmpic(csp->http->gpc, "TRACE")
1176 && strcmpic(csp->http->gpc, "OPTIONS")
1177 && strcmpic(csp->http->gpc, "DELETE"))
1179 /* XXX: this is an incomplete hack */
1180 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1181 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1185 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1187 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1189 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1190 log_error(LOG_LEVEL_CONNECT,
1191 "Possible pipeline attempt detected. The connection will not "
1192 "be kept alive and we will only serve the first request.");
1193 /* Nuke the pipelined requests from orbit, just to be sure. */
1194 clear_iob(csp->client_iob);
1199 * Keep the pipelined data around for now, we'll deal with
1200 * it once we're done serving the current request.
1202 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1203 assert(csp->client_iob->eod >= csp->client_iob->cur);
1204 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1205 "%d bytes of pipelined data received.",
1206 (int)(csp->client_iob->eod - csp->client_iob->cur));
1212 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1213 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1216 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1219 /*********************************************************************
1221 * Function : mark_server_socket_tainted
1223 * Description : Makes sure we don't reuse a server socket
1224 * (if we didn't read everything the server sent
1225 * us reusing the socket would lead to garbage).
1228 * 1 : csp = Current client state (buffers, headers, etc...)
1232 *********************************************************************/
1233 static void mark_server_socket_tainted(struct client_state *csp)
1236 * For consistency we always mark the server socket
1237 * tainted, however, to reduce the log noise we only
1238 * emit a log message if the server socket could have
1239 * actually been reused.
1241 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1242 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1244 log_error(LOG_LEVEL_CONNECT,
1245 "Marking the server socket %d tainted.",
1246 csp->server_connection.sfd);
1248 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1251 /*********************************************************************
1253 * Function : get_request_line
1255 * Description : Read the client request line.
1258 * 1 : csp = Current client state (buffers, headers, etc...)
1260 * Returns : Pointer to request line or NULL in case of errors.
1262 *********************************************************************/
1263 static char *get_request_line(struct client_state *csp)
1265 char buf[BUFFER_SIZE];
1266 char *request_line = NULL;
1269 memset(buf, 0, sizeof(buf));
1271 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1274 * If there are multiple pipelined requests waiting,
1275 * the flag will be set again once the next request
1278 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1280 request_line = get_header(csp->client_iob);
1281 if ((NULL != request_line) && ('\0' != *request_line))
1283 return request_line;
1287 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1288 "received yet. Continuing reading from %d.", csp->cfd);
1296 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1298 !data_is_available(csp->cfd, csp->config->socket_timeout)
1301 if (socket_is_still_alive(csp->cfd))
1303 log_error(LOG_LEVEL_CONNECT,
1304 "No request line on socket %d received in time. Timeout: %d.",
1305 csp->cfd, csp->config->socket_timeout);
1306 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1307 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1311 log_error(LOG_LEVEL_CONNECT,
1312 "The client side of the connection on socket %d got "
1313 "closed without sending a complete request line.", csp->cfd);
1318 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1320 if (len <= 0) return NULL;
1323 * If there is no memory left for buffering the
1324 * request, there is nothing we can do but hang up
1326 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1331 request_line = get_header(csp->client_iob);
1333 } while ((NULL != request_line) && ('\0' == *request_line));
1335 return request_line;
1341 CHUNK_STATUS_MISSING_DATA,
1342 CHUNK_STATUS_BODY_COMPLETE,
1343 CHUNK_STATUS_PARSE_ERROR
1347 /*********************************************************************
1349 * Function : chunked_body_is_complete
1351 * Description : Figures out whether or not a chunked body is complete.
1353 * Currently it always starts at the beginning of the
1354 * buffer which is somewhat wasteful and prevents Privoxy
1355 * from starting to forward the correctly parsed chunks
1356 * as soon as theoretically possible.
1358 * Should be modified to work with a common buffer,
1359 * and allow the caller to skip already parsed chunks.
1361 * This would allow the function to be used for unbuffered
1362 * response bodies as well.
1365 * 1 : iob = Buffer with the body to check.
1366 * 2 : length = Length of complete body
1368 * Returns : Enum with the result of the check.
1370 *********************************************************************/
1371 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1373 unsigned int chunksize;
1379 * We need at least a single digit, followed by "\r\n",
1380 * followed by an unknown amount of data, followed by "\r\n".
1382 if (p + 5 > iob->eod)
1384 return CHUNK_STATUS_MISSING_DATA;
1386 if (sscanf(p, "%x", &chunksize) != 1)
1388 return CHUNK_STATUS_PARSE_ERROR;
1392 * We want at least a single digit, followed by "\r\n",
1393 * followed by the specified amount of data, followed by "\r\n".
1395 if (p + chunksize + 5 > iob->eod)
1397 return CHUNK_STATUS_MISSING_DATA;
1400 /* Skip chunk-size. */
1401 p = strstr(p, "\r\n");
1404 return CHUNK_STATUS_PARSE_ERROR;
1406 /* Move beyond the chunkdata. */
1409 /* There should be another "\r\n" to skip */
1410 if (memcmp(p, "\r\n", 2))
1412 return CHUNK_STATUS_PARSE_ERROR;
1415 } while (chunksize > 0U);
1417 *length = (size_t)(p - iob->cur);
1418 assert(*length <= (size_t)(iob->eod - iob->cur));
1419 assert(p <= iob->eod);
1421 return CHUNK_STATUS_BODY_COMPLETE;
1426 /*********************************************************************
1428 * Function : receive_chunked_client_request_body
1430 * Description : Read the chunk-encoded client request body.
1431 * Failures are dealt with.
1434 * 1 : csp = Current client state (buffers, headers, etc...)
1436 * Returns : JB_ERR_OK or JB_ERR_PARSE
1438 *********************************************************************/
1439 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1442 enum chunk_status status;
1444 while (CHUNK_STATUS_MISSING_DATA ==
1445 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1447 char buf[BUFFER_SIZE];
1450 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1452 log_error(LOG_LEVEL_ERROR,
1453 "Timeout while waiting for the client body.");
1456 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1459 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1462 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1467 if (status != CHUNK_STATUS_BODY_COMPLETE)
1469 write_socket(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1470 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE));
1471 log_error(LOG_LEVEL_CLF,
1472 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1473 return JB_ERR_PARSE;
1475 log_error(LOG_LEVEL_CONNECT,
1476 "Chunked client body completely read. Length: %d", body_length);
1477 csp->expected_client_content_length = body_length;
1485 /*********************************************************************
1487 * Function : fuzz_chunked_transfer_encoding
1489 * Description : Treat the fuzzed input as chunked transfer encoding
1490 * to check and dechunk.
1493 * 1 : csp = Used to store the data.
1494 * 2 : fuzz_input_file = File to read the input from.
1496 * Returns : Result of dechunking
1498 *********************************************************************/
1499 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1502 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1503 enum chunk_status status;
1505 status = chunked_body_is_complete(csp->iob, &length);
1506 if (CHUNK_STATUS_BODY_COMPLETE != status)
1508 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1511 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1516 /*********************************************************************
1518 * Function : fuzz_client_request
1520 * Description : Try to get a client request from the fuzzed input.
1523 * 1 : csp = Current client state (buffers, headers, etc...)
1524 * 2 : fuzz_input_file = File to read the input from.
1526 * Returns : Result of fuzzing.
1528 *********************************************************************/
1529 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1534 csp->ip_addr_str = "fuzzer";
1536 if (strcmp(fuzz_input_file, "-") != 0)
1538 log_error(LOG_LEVEL_FATAL,
1539 "Fuzzed client requests can currenty only be read from stdin (-).");
1541 err = receive_client_request(csp);
1542 if (err != JB_ERR_OK)
1546 err = parse_client_request(csp);
1547 if (err != JB_ERR_OK)
1555 #endif /* def FUZZ */
1558 #ifdef FEATURE_FORCE_LOAD
1559 /*********************************************************************
1561 * Function : force_required
1563 * Description : Checks a request line to see if it contains
1564 * the FORCE_PREFIX. If it does, it is removed
1565 * unless enforcing requests has beend disabled.
1568 * 1 : request_line = HTTP request line
1570 * Returns : TRUE if force is required, FALSE otherwise.
1572 *********************************************************************/
1573 static int force_required(const struct client_state *csp, char *request_line)
1577 p = strstr(request_line, "http://");
1581 p += strlen("http://");
1585 /* Intercepted request usually don't specify the protocol. */
1589 /* Go to the beginning of the path */
1594 * If the path is missing the request line is invalid and we
1595 * are done here. The client-visible rejection happens later on.
1600 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1602 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1604 /* XXX: Should clean more carefully */
1605 strclean(request_line, FORCE_PREFIX);
1606 log_error(LOG_LEVEL_FORCE,
1607 "Enforcing request: \"%s\".", request_line);
1611 log_error(LOG_LEVEL_FORCE,
1612 "Ignored force prefix in request: \"%s\".", request_line);
1618 #endif /* def FEATURE_FORCE_LOAD */
1621 /*********************************************************************
1623 * Function : receive_client_request
1625 * Description : Read the client's request (more precisely the
1626 * client headers) and answer it if necessary.
1629 * 1 : csp = Current client state (buffers, headers, etc...)
1631 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1633 *********************************************************************/
1634 static jb_err receive_client_request(struct client_state *csp)
1636 char buf[BUFFER_SIZE];
1639 struct http_request *http;
1643 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1644 struct list header_list;
1645 struct list *headers = &header_list;
1647 /* We don't care if the arriving data is a valid HTTP request or not. */
1648 csp->requests_received_total++;
1652 memset(buf, 0, sizeof(buf));
1654 req = get_request_line(csp);
1657 mark_server_socket_tainted(csp);
1658 return JB_ERR_PARSE;
1660 assert(*req != '\0');
1662 if (client_protocol_is_unsupported(csp, req))
1664 return JB_ERR_PARSE;
1667 #ifdef FEATURE_FORCE_LOAD
1668 if (force_required(csp, req))
1670 csp->flags |= CSP_FLAG_FORCED;
1672 #endif /* def FEATURE_FORCE_LOAD */
1674 err = parse_http_request(req, http);
1676 if (JB_ERR_OK != err)
1678 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1679 /* XXX: Use correct size */
1680 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1681 log_error(LOG_LEVEL_ERROR,
1682 "Couldn't parse request line received from %s: %s",
1683 csp->ip_addr_str, jb_err_to_string(err));
1685 free_http_request(http);
1686 return JB_ERR_PARSE;
1689 /* grab the rest of the client's headers */
1693 p = get_header(csp->client_iob);
1697 /* There are no additional headers to read. */
1704 * We didn't receive a complete header
1705 * line yet, get the rest of it.
1707 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1709 log_error(LOG_LEVEL_ERROR,
1710 "Stopped grabbing the client headers.");
1711 destroy_list(headers);
1712 return JB_ERR_PARSE;
1715 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1718 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1719 destroy_list(headers);
1720 return JB_ERR_PARSE;
1723 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1726 * If there is no memory left for buffering the
1727 * request, there is nothing we can do but hang up
1729 destroy_list(headers);
1730 return JB_ERR_MEMORY;
1735 if (!strncmpic(p, "Transfer-Encoding:", 18))
1738 * XXX: should be called through sed()
1739 * but currently can't.
1741 client_transfer_encoding(csp, &p);
1744 * We were able to read a complete
1745 * header and can finally enlist it.
1752 if (http->host == NULL)
1755 * If we still don't know the request destination,
1756 * the request is invalid or the client uses
1757 * Privoxy without its knowledge.
1759 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1762 * Our attempts to get the request destination
1763 * elsewhere failed or Privoxy is configured
1764 * to only accept proxy requests.
1766 * An error response has already been send
1767 * and we're done here.
1769 return JB_ERR_PARSE;
1773 #ifdef FEATURE_CLIENT_TAGS
1774 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1775 set_client_address(csp, headers);
1776 get_tag_list_for_client(csp->client_tags, csp->client_address);
1780 * Determine the actions for this URL
1782 #ifdef FEATURE_TOGGLE
1783 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1785 /* Most compatible set of actions (i.e. none) */
1786 init_current_action(csp->action);
1789 #endif /* ndef FEATURE_TOGGLE */
1791 get_url_actions(csp, http);
1794 enlist(csp->headers, http->cmd);
1796 /* Append the previously read headers */
1797 err = list_append_list_unique(csp->headers, headers);
1798 destroy_list(headers);
1805 /*********************************************************************
1807 * Function : parse_client_request
1809 * Description : Parses the client's request and decides what to do
1812 * Note that since we're not using select() we could get
1813 * blocked here if a client connected, then didn't say
1817 * 1 : csp = Current client state (buffers, headers, etc...)
1819 * Returns : JB_ERR_OK or JB_ERR_PARSE
1821 *********************************************************************/
1822 static jb_err parse_client_request(struct client_state *csp)
1824 struct http_request *http = csp->http;
1827 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1828 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1829 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1830 && (csp->http->ssl == 0))
1832 /* Assume persistence until further notice */
1833 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1836 if (csp->http->ssl == 0)
1839 * This whole block belongs to chat() but currently
1840 * has to be executed before sed().
1842 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1844 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1846 return JB_ERR_PARSE;
1851 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1853 verify_request_length(csp);
1855 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1857 err = sed(csp, FILTER_CLIENT_HEADERS);
1858 if (JB_ERR_OK != err)
1860 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1862 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1863 csp->ip_addr_str, csp->http->cmd);
1864 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1865 return JB_ERR_PARSE;
1867 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1869 /* Check request line for rewrites. */
1870 if ((NULL == csp->headers->first->str)
1871 || (strcmp(http->cmd, csp->headers->first->str) &&
1872 (JB_ERR_OK != change_request_destination(csp))))
1875 * A header filter broke the request line - bail out.
1877 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1878 /* XXX: Use correct size */
1879 log_error(LOG_LEVEL_CLF,
1880 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1881 log_error(LOG_LEVEL_ERROR,
1882 "Invalid request line after applying header filters.");
1883 free_http_request(http);
1885 return JB_ERR_PARSE;
1888 if (client_has_unsupported_expectations(csp))
1890 return JB_ERR_PARSE;
1898 /*********************************************************************
1900 * Function : send_http_request
1902 * Description : Sends the HTTP headers from the client request
1903 * and all the body data that has already been received.
1906 * 1 : csp = Current client state (buffers, headers, etc...)
1908 * Returns : 0 on success, anything else is na error.
1910 *********************************************************************/
1911 static int send_http_request(struct client_state *csp)
1916 hdr = list_to_text(csp->headers);
1919 /* FIXME Should handle error properly */
1920 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1922 list_remove_all(csp->headers);
1925 * Write the client's (modified) header to the server
1926 * (along with anything else that may be in the buffer)
1928 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
1933 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
1934 csp->http->hostport);
1936 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
1937 && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
1940 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
1941 csp->http->hostport);
1944 return write_failure;
1949 /*********************************************************************
1951 * Function : handle_established_connection
1953 * Description : Shuffle data between client and server once the
1954 * connection has been established.
1957 * 1 : csp = Current client state (buffers, headers, etc...)
1959 * Returns : Nothing.
1961 *********************************************************************/
1962 static void handle_established_connection(struct client_state *csp,
1963 const struct forward_spec *fwd)
1965 char *receive_buffer;
1970 struct pollfd poll_fds[2];
1974 struct timeval timeout;
1977 int ms_iis5_hack = 0;
1978 unsigned long long byte_count = 0;
1979 struct http_request *http;
1980 long len = 0; /* for buffer sizes (and negative error codes) */
1981 int buffer_and_filter_content = 0;
1983 /* Skeleton for HTTP response, if we should intercept the request */
1984 struct http_response *rsp;
1985 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1986 int watch_client_socket;
1988 const size_t receive_buffer_size = csp->config->receive_buffer_size;
1990 receive_buffer = zalloc(receive_buffer_size + 1);
1991 if (receive_buffer == NULL)
1993 log_error(LOG_LEVEL_ERROR,
1994 "Out of memory. Failed to allocate the receive buffer.");
1995 rsp = cgi_error_memory();
1996 send_crunch_response(csp, rsp);
2003 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2004 csp->cfd : csp->server_connection.sfd;
2007 /* pass data between the client and server
2008 * until one or the other shuts down the connection.
2013 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2014 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2022 * FD_ZERO here seems to point to an errant macro which crashes.
2023 * So do this by hand for now...
2025 memset(&rfds,0x00,sizeof(fd_set));
2029 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2030 if (!watch_client_socket)
2032 maxfd = csp->server_connection.sfd;
2035 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2037 FD_SET(csp->cfd, &rfds);
2040 FD_SET(csp->server_connection.sfd, &rfds);
2041 #endif /* ndef HAVE_POLL */
2043 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2044 if ((csp->flags & CSP_FLAG_CHUNKED)
2045 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2046 && ((csp->iob->eod - csp->iob->cur) >= 5)
2047 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2050 * XXX: This check should be obsolete now,
2051 * but let's wait a while to be sure.
2053 log_error(LOG_LEVEL_CONNECT,
2054 "Looks like we got the last chunk together with "
2055 "the server headers but didn't detect it earlier. "
2056 "We better stop reading.");
2057 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2058 csp->expected_content_length = byte_count;
2059 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2061 if (server_body && server_response_is_complete(csp, byte_count))
2063 if (csp->expected_content_length == byte_count)
2065 log_error(LOG_LEVEL_CONNECT,
2066 "Done reading from server. Content length: %llu as expected. "
2067 "Bytes most recently read: %d.",
2072 log_error(LOG_LEVEL_CONNECT,
2073 "Done reading from server. Expected content length: %llu. "
2074 "Actual content length: %llu. Bytes most recently read: %d.",
2075 csp->expected_content_length, byte_count, len);
2079 * XXX: should not jump around,
2080 * chat() is complicated enough already.
2084 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2087 poll_fds[0].fd = csp->cfd;
2088 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2089 if (!watch_client_socket)
2092 * Ignore incoming data, but still watch out
2093 * for disconnects etc. These flags are always
2094 * implied anyway but explicitly setting them
2097 poll_fds[0].events = POLLERR|POLLHUP;
2102 poll_fds[0].events = POLLIN;
2104 poll_fds[1].fd = csp->server_connection.sfd;
2105 poll_fds[1].events = POLLIN;
2106 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2108 timeout.tv_sec = csp->config->socket_timeout;
2109 timeout.tv_usec = 0;
2110 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2111 #endif /* def HAVE_POLL */
2115 log_error(LOG_LEVEL_ERROR,
2116 "Didn't receive data in time: %s", http->url);
2117 if ((byte_count == 0) && (http->ssl == 0))
2119 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2121 mark_server_socket_tainted(csp);
2122 freez(receive_buffer);
2128 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2130 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2132 mark_server_socket_tainted(csp);
2133 freez(receive_buffer);
2138 * This is the body of the browser's request,
2139 * just read and write it.
2141 * XXX: Make sure the client doesn't use pipelining
2142 * behind Privoxy's back.
2145 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2147 log_error(LOG_LEVEL_CONNECT,
2148 "The client socket %d has become unusable while "
2149 "the server socket %d is still open.",
2150 csp->cfd, csp->server_connection.sfd);
2151 mark_server_socket_tainted(csp);
2155 if (poll_fds[0].revents != 0)
2157 if (FD_ISSET(csp->cfd, &rfds))
2158 #endif /* def HAVE_POLL*/
2160 int max_bytes_to_read = (int)receive_buffer_size;
2162 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2163 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2165 if (data_is_available(csp->cfd, 0))
2168 * If the next request is already waiting, we have
2169 * to stop select()ing the client socket. Otherwise
2170 * we would always return right away and get nothing
2173 watch_client_socket = 0;
2174 log_error(LOG_LEVEL_CONNECT,
2175 "Stopping to watch the client socket %d. "
2176 "There's already another request waiting.",
2181 * If the client socket is set, but there's no data
2182 * available on the socket, the client went fishing
2183 * and continuing talking to the server makes no sense.
2185 log_error(LOG_LEVEL_CONNECT,
2186 "The client closed socket %d while "
2187 "the server socket %d is still open.",
2188 csp->cfd, csp->server_connection.sfd);
2189 mark_server_socket_tainted(csp);
2192 if (csp->expected_client_content_length != 0)
2194 if (csp->expected_client_content_length < receive_buffer_size)
2196 max_bytes_to_read = (int)csp->expected_client_content_length;
2198 log_error(LOG_LEVEL_CONNECT,
2199 "Waiting for up to %d bytes from the client.",
2202 assert(max_bytes_to_read <= receive_buffer_size);
2203 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2205 len = read_socket(csp->cfd, receive_buffer, max_bytes_to_read);
2209 /* XXX: not sure if this is necessary. */
2210 mark_server_socket_tainted(csp);
2211 break; /* "game over, man" */
2214 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2215 if (csp->expected_client_content_length != 0)
2217 assert(len <= max_bytes_to_read);
2218 csp->expected_client_content_length -= (unsigned)len;
2219 log_error(LOG_LEVEL_CONNECT,
2220 "Expected client content length set to %llu "
2221 "after reading %d bytes.",
2222 csp->expected_client_content_length, len);
2223 if (csp->expected_client_content_length == 0)
2225 log_error(LOG_LEVEL_CONNECT,
2226 "Done reading from the client.");
2227 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2230 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2232 if (write_socket(csp->server_connection.sfd, receive_buffer, (size_t)len))
2234 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2235 mark_server_socket_tainted(csp);
2236 freez(receive_buffer);
2243 * The server wants to talk. It could be the header or the body.
2244 * If `hdr' is null, then it's the header otherwise it's the body.
2245 * FIXME: Does `hdr' really mean `host'? No.
2248 if (poll_fds[1].revents != 0)
2250 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2251 #endif /* HAVE_POLL */
2253 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2255 * If we are buffering content, we don't want to eat up to
2256 * buffer-limit bytes if the client no longer cares about them.
2257 * If we aren't buffering, however, a dead client socket will be
2258 * noticed pretty much right away anyway, so we can reduce the
2259 * overhead by skipping the check.
2261 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2264 log_error(LOG_LEVEL_CONNECT,
2265 "The server still wants to talk, but the client may already have hung up on us.");
2267 log_error(LOG_LEVEL_CONNECT,
2268 "The server still wants to talk, but the client hung up on us.");
2269 mark_server_socket_tainted(csp);
2270 freez(receive_buffer);
2272 #endif /* def _WIN32 */
2274 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2276 len = read_socket(csp->server_connection.sfd, receive_buffer, (int)receive_buffer_size);
2280 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2282 if (http->ssl && (fwd->forward_host == NULL))
2285 * Just hang up. We already confirmed the client's CONNECT
2286 * request with status code 200 and unencrypted content is
2287 * no longer welcome.
2289 log_error(LOG_LEVEL_ERROR,
2290 "CONNECT already confirmed. Unable to tell the client about the problem.");
2291 freez(receive_buffer);
2294 else if (byte_count)
2297 * Just hang up. We already transmitted the original headers
2298 * and parts of the original content and therefore missed the
2299 * chance to send an error message (without risking data corruption).
2301 * XXX: we could retry with a fancy range request here.
2303 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2304 "Unable to tell the client about the problem.");
2305 mark_server_socket_tainted(csp);
2306 freez(receive_buffer);
2310 * XXX: Consider handling the cases above the same.
2312 mark_server_socket_tainted(csp);
2316 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2317 if (csp->flags & CSP_FLAG_CHUNKED)
2319 if ((len >= 5) && !memcmp(receive_buffer+len-5, "0\r\n\r\n", 5))
2321 /* XXX: this is a temporary hack */
2322 log_error(LOG_LEVEL_CONNECT,
2323 "Looks like we reached the end of the last chunk. "
2324 "We better stop reading.");
2325 csp->expected_content_length = byte_count + (unsigned long long)len;
2326 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2330 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2333 * This is guaranteed by allocating with zalloc_or_die()
2334 * and never (intentionally) writing to the last byte.
2336 * receive_buffer_size is the size of the part of the
2337 * buffer we intentionally write to, but we actually
2338 * allocated receive_buffer_size+1 bytes so the assertion
2339 * stays within the allocated range.
2341 assert(receive_buffer[receive_buffer_size] == '\0');
2344 * Add a trailing zero to let be able to use string operations.
2345 * XXX: do we still need this with filter_popups gone?
2347 assert(len <= receive_buffer_size);
2348 receive_buffer[len] = '\0';
2351 * Normally, this would indicate that we've read
2352 * as much as the server has sent us and we can
2353 * close the client connection. However, Microsoft
2354 * in its wisdom has released IIS/5 with a bug that
2355 * prevents it from sending the trailing \r\n in
2356 * a 302 redirect header (and possibly other headers).
2357 * To work around this if we've haven't parsed
2358 * a full header we'll append a trailing \r\n
2359 * and see if this now generates a valid one.
2361 * This hack shouldn't have any impacts. If we've
2362 * already transmitted the header or if this is a
2363 * SSL connection, then we won't bother with this
2364 * hack. So we only work on partially received
2365 * headers. If we append a \r\n and this still
2366 * doesn't generate a valid header, then we won't
2367 * transmit anything to the client.
2372 if (server_body || http->ssl)
2375 * If we have been buffering up the document,
2376 * now is the time to apply content modification
2377 * and send the result to the client.
2379 if (buffer_and_filter_content)
2381 p = execute_content_filters(csp);
2383 * If content filtering fails, use the original
2384 * buffer and length.
2385 * (see p != NULL ? p : csp->iob->cur below)
2389 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2391 #ifdef FEATURE_COMPRESSION
2392 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2393 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2395 char *compressed_content = compress_buffer(p,
2396 (size_t *)&csp->content_length, csp->config->compression_level);
2397 if (compressed_content != NULL)
2400 p = compressed_content;
2401 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2406 if (JB_ERR_OK != update_server_headers(csp))
2408 log_error(LOG_LEVEL_FATAL,
2409 "Failed to update server headers. after filtering.");
2412 hdr = list_to_text(csp->headers);
2415 /* FIXME Should handle error properly */
2416 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2419 if (write_socket(csp->cfd, hdr, strlen(hdr))
2420 || write_socket(csp->cfd,
2421 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2423 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2426 mark_server_socket_tainted(csp);
2427 freez(receive_buffer);
2435 break; /* "game over, man" */
2439 * This is NOT the body, so
2440 * Let's pretend the server just sent us a blank line.
2442 snprintf(receive_buffer, receive_buffer_size, "\r\n");
2443 len = (int)strlen(receive_buffer);
2446 * Now, let the normal header parsing algorithm below do its
2447 * job. If it fails, we'll exit instead of continuing.
2454 * If this is an SSL connection or we're in the body
2455 * of the server document, just write it to the client,
2456 * unless we need to buffer the body for later content-filtering
2458 if (server_body || http->ssl)
2460 if (buffer_and_filter_content)
2463 * If there is no memory left for buffering the content, or the buffer limit
2464 * has been reached, switch to non-filtering mode, i.e. make & write the
2465 * header, flush the iob and buf, and get out of the way.
2467 if (add_to_iob(csp->iob, csp->config->buffer_limit, receive_buffer, len))
2472 log_error(LOG_LEVEL_INFO,
2473 "Flushing header and buffers. Stepping back from filtering.");
2475 hdr = list_to_text(csp->headers);
2479 * Memory is too tight to even generate the header.
2480 * Send our static "Out-of-memory" page.
2482 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2483 rsp = cgi_error_memory();
2484 send_crunch_response(csp, rsp);
2485 mark_server_socket_tainted(csp);
2486 freez(receive_buffer);
2489 hdrlen = strlen(hdr);
2491 if (write_socket(csp->cfd, hdr, hdrlen)
2492 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2493 || (write_socket(csp->cfd, receive_buffer, (size_t)len)))
2495 log_error(LOG_LEVEL_CONNECT,
2496 "Flush header and buffers to client failed: %E");
2498 mark_server_socket_tainted(csp);
2499 freez(receive_buffer);
2504 * Reset the byte_count to the amount of bytes
2505 * we just flushed. len will be added a few lines below,
2506 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2508 byte_count = (unsigned long long)flushed;
2510 buffer_and_filter_content = 0;
2516 if (write_socket(csp->cfd, receive_buffer, (size_t)len))
2518 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2519 mark_server_socket_tainted(csp);
2520 freez(receive_buffer);
2524 byte_count += (unsigned long long)len;
2530 * We're still looking for the end of the server's header.
2531 * Buffer up the data we just read. If that fails, there's
2532 * little we can do but send our static out-of-memory page.
2534 if (add_to_iob(csp->iob, csp->config->buffer_limit, receive_buffer, len))
2536 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2537 rsp = cgi_error_memory();
2538 send_crunch_response(csp, rsp);
2539 mark_server_socket_tainted(csp);
2540 freez(receive_buffer);
2544 /* Convert iob into something sed() can digest */
2545 if (JB_ERR_PARSE == get_server_headers(csp))
2550 * Well, we tried our MS IIS/5 hack and it didn't work.
2551 * The header is incomplete and there isn't anything
2552 * we can do about it.
2554 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2555 "Applying the MS IIS5 hack didn't help.");
2556 log_error(LOG_LEVEL_CLF,
2557 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2558 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2559 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2560 mark_server_socket_tainted(csp);
2561 freez(receive_buffer);
2567 * Since we have to wait for more from the server before
2568 * we can parse the headers we just continue here.
2570 log_error(LOG_LEVEL_CONNECT,
2571 "Continuing buffering server headers from socket %d. "
2572 "Bytes most recently read: %d.", csp->cfd, len);
2579 * Account for the content bytes we
2580 * might have gotten with the headers.
2582 assert(csp->iob->eod >= csp->iob->cur);
2583 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2586 /* Did we actually get anything? */
2587 if (NULL == csp->headers->first)
2589 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2591 log_error(LOG_LEVEL_ERROR,
2592 "No server or forwarder response received on socket %d. "
2593 "Closing client socket %d without sending data.",
2594 csp->server_connection.sfd, csp->cfd);
2595 log_error(LOG_LEVEL_CLF,
2596 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2600 log_error(LOG_LEVEL_ERROR,
2601 "No server or forwarder response received on socket %d.",
2602 csp->server_connection.sfd);
2603 send_crunch_response(csp, error_response(csp, "no-server-data"));
2605 free_http_request(http);
2606 mark_server_socket_tainted(csp);
2607 freez(receive_buffer);
2611 assert(csp->headers->first->str);
2613 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2614 strncmpic(csp->headers->first->str, "ICY", 3))
2617 * It doesn't look like a HTTP (or Shoutcast) response:
2618 * tell the client and log the problem.
2620 if (strlen(csp->headers->first->str) > 30)
2622 csp->headers->first->str[30] = '\0';
2624 log_error(LOG_LEVEL_ERROR,
2625 "Invalid server or forwarder response. Starts with: %s",
2626 csp->headers->first->str);
2627 log_error(LOG_LEVEL_CLF,
2628 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2629 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2630 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2631 free_http_request(http);
2632 mark_server_socket_tainted(csp);
2637 * We have now received the entire server header,
2638 * filter it and send the result to the client
2640 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2642 log_error(LOG_LEVEL_CLF,
2643 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2644 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2645 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2646 free_http_request(http);
2647 mark_server_socket_tainted(csp);
2648 freez(receive_buffer);
2651 hdr = list_to_text(csp->headers);
2654 /* FIXME Should handle error properly */
2655 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2658 if ((csp->flags & CSP_FLAG_CHUNKED)
2659 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2660 && ((csp->iob->eod - csp->iob->cur) >= 5)
2661 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2663 log_error(LOG_LEVEL_CONNECT,
2664 "Looks like we got the last chunk together with "
2665 "the server headers. We better stop reading.");
2666 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2667 csp->expected_content_length = byte_count;
2668 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2671 csp->server_connection.response_received = time(NULL);
2673 if (crunch_response_triggered(csp, crunchers_light))
2676 * One of the tags created by a server-header
2677 * tagger triggered a crunch. We already
2678 * delivered the crunch response to the client
2679 * and are done here after cleaning up.
2682 mark_server_socket_tainted(csp);
2683 freez(receive_buffer);
2686 /* Buffer and pcrs filter this if appropriate. */
2688 if (!http->ssl) /* We talk plaintext */
2690 buffer_and_filter_content = content_requires_filtering(csp);
2693 * Only write if we're not buffering for content modification
2695 if (!buffer_and_filter_content)
2698 * Write the server's (modified) header to
2699 * the client (along with anything else that
2700 * may be in the buffer)
2703 if (write_socket(csp->cfd, hdr, strlen(hdr))
2704 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2706 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2709 * The write failed, so don't bother mentioning it
2710 * to the client... it probably can't hear us anyway.
2713 mark_server_socket_tainted(csp);
2714 freez(receive_buffer);
2719 /* we're finished with the server's header */
2725 * If this was a MS IIS/5 hack then it means the server
2726 * has already closed the connection. Nothing more to read.
2731 log_error(LOG_LEVEL_ERROR,
2732 "Closed server connection detected. "
2733 "Applying the MS IIS5 hack didn't help.");
2734 log_error(LOG_LEVEL_CLF,
2735 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2736 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2737 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2738 mark_server_socket_tainted(csp);
2739 freez(receive_buffer);
2745 mark_server_socket_tainted(csp);
2746 freez(receive_buffer);
2747 return; /* huh? we should never get here */
2749 freez(receive_buffer);
2751 if (csp->content_length == 0)
2754 * If Privoxy didn't recalculate the Content-Length,
2755 * byte_count is still correct.
2757 csp->content_length = byte_count;
2760 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2761 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2762 && (csp->expected_content_length != byte_count))
2764 log_error(LOG_LEVEL_CONNECT,
2765 "Received %llu bytes while expecting %llu.",
2766 byte_count, csp->expected_content_length);
2767 mark_server_socket_tainted(csp);
2771 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2772 csp->ip_addr_str, http->ocmd, csp->content_length);
2774 csp->server_connection.timestamp = time(NULL);
2778 /*********************************************************************
2782 * Description : Once a connection from the client has been accepted,
2783 * this function is called (via serve()) to handle the
2784 * main business of the communication. This function
2785 * returns after dealing with a single request. It can
2786 * be called multiple times with the same client socket
2787 * if the client is keeping the connection alive.
2789 * The decision whether or not a client connection will
2790 * be kept alive is up to the caller which also must
2791 * close the client socket when done.
2793 * FIXME: chat is nearly thousand lines long.
2797 * 1 : csp = Current client state (buffers, headers, etc...)
2799 * Returns : Nothing.
2801 *********************************************************************/
2802 static void chat(struct client_state *csp)
2804 const struct forward_spec *fwd;
2805 struct http_request *http;
2806 /* Skeleton for HTTP response, if we should intercept the request */
2807 struct http_response *rsp;
2811 if (receive_client_request(csp) != JB_ERR_OK)
2815 if (parse_client_request(csp) != JB_ERR_OK)
2820 /* decide how to route the HTTP request */
2821 fwd = forward_url(csp, http);
2824 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2825 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2830 * build the http request to send to the server
2831 * we have to do one of the following:
2833 * create = use the original HTTP request to create a new
2834 * HTTP request that has either the path component
2835 * without the http://domainspec (w/path) or the
2836 * full orininal URL (w/url)
2837 * Note that the path and/or the HTTP version may
2838 * have been altered by now.
2840 * connect = Open a socket to the host:port of the server
2841 * and short-circuit server and client socket.
2843 * pass = Pass the request unchanged if forwarding a CONNECT
2844 * request to a parent proxy. Note that we'll be sending
2845 * the CFAIL message ourselves if connecting to the parent
2846 * fails, but we won't send a CSUCCEED message if it works,
2847 * since that would result in a double message (ours and the
2848 * parent's). After sending the request to the parent, we simply
2851 * here's the matrix:
2854 * +--------+--------+
2856 * 0 | create | connect|
2858 * Forwarding +--------+--------+
2860 * 1 | create | pass |
2862 * +--------+--------+
2866 if (http->ssl && connect_port_is_forbidden(csp))
2868 const char *acceptable_connect_ports =
2869 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
2870 assert(NULL != acceptable_connect_ports);
2871 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
2872 "limit-connect{%s} doesn't allow CONNECT requests to %s",
2873 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
2874 csp->action->flags |= ACTION_BLOCK;
2880 freez(csp->headers->first->str);
2881 build_request_line(csp, fwd, &csp->headers->first->str);
2885 * We have a request. Check if one of the crunchers wants it.
2887 if (crunch_response_triggered(csp, crunchers_all))
2890 * Yes. The client got the crunch response and we're done here.
2895 log_applied_actions(csp->action);
2896 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
2898 if (fwd->forward_host)
2900 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
2901 fwd->forward_host, fwd->forward_port, http->hostport);
2905 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
2908 /* here we connect to the server, gateway, or the forwarder */
2910 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2911 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
2912 && socket_is_still_alive(csp->server_connection.sfd)
2913 && connection_destination_matches(&csp->server_connection, http, fwd))
2915 log_error(LOG_LEVEL_CONNECT,
2916 "Reusing server socket %d connected to %s. Total requests: %u.",
2917 csp->server_connection.sfd, csp->server_connection.host,
2918 csp->server_connection.requests_sent_total);
2922 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2924 #ifdef FEATURE_CONNECTION_SHARING
2925 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2927 remember_connection(&csp->server_connection);
2930 #endif /* def FEATURE_CONNECTION_SHARING */
2932 log_error(LOG_LEVEL_CONNECT,
2933 "Closing server socket %d connected to %s. Total requests: %u.",
2934 csp->server_connection.sfd, csp->server_connection.host,
2935 csp->server_connection.requests_sent_total);
2936 close_socket(csp->server_connection.sfd);
2938 mark_connection_closed(&csp->server_connection);
2940 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2942 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
2944 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
2946 if (fwd->type != SOCKS_NONE)
2949 rsp = error_response(csp, "forwarding-failed");
2951 else if (errno == EINVAL)
2953 rsp = error_response(csp, "no-such-domain");
2957 rsp = error_response(csp, "connect-failed");
2960 /* Write the answer to the client */
2963 send_crunch_response(csp, rsp);
2967 * Temporary workaround to prevent already-read client
2968 * bodies from being parsed as new requests. For now we
2969 * err on the safe side and throw all the following
2970 * requests under the bus, even if no client body has been
2971 * buffered. A compliant client will repeat the dropped
2972 * requests on an untainted connection.
2974 * The proper fix is to discard the no longer needed
2975 * client body in the buffer (if there is one) and to
2976 * continue parsing the bytes that follow.
2978 drain_and_close_socket(csp->cfd);
2979 csp->cfd = JB_INVALID_SOCKET;
2983 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2984 save_connection_destination(csp->server_connection.sfd,
2985 http, fwd, &csp->server_connection);
2986 csp->server_connection.keep_alive_timeout =
2987 (unsigned)csp->config->keep_alive_timeout;
2989 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2991 csp->server_connection.requests_sent_total++;
2993 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
2995 /* Client headers have been sent optimistically */
2996 assert(csp->headers->last == NULL);
2998 else if (fwd->forward_host || (http->ssl == 0))
3000 if (send_http_request(csp))
3002 rsp = error_response(csp, "connect-failed");
3005 send_crunch_response(csp, rsp);
3013 * We're running an SSL tunnel and we're not forwarding,
3014 * so just ditch the client headers, send the "connect succeeded"
3015 * message to the client, flush the rest, and get out of the way.
3017 list_remove_all(csp->headers);
3018 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
3022 clear_iob(csp->client_iob);
3025 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
3027 /* XXX: should the time start earlier for optimistically sent data? */
3028 csp->server_connection.request_sent = time(NULL);
3030 handle_established_connection(csp, fwd);
3035 /*********************************************************************
3037 * Function : fuzz_server_response
3039 * Description : Treat the input as a whole server response.
3042 * 1 : csp = Current client state (buffers, headers, etc...)
3043 * 2 : fuzz_input_file = File to read the input from.
3047 *********************************************************************/
3048 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
3050 static struct forward_spec fwd; /* Zero'd due to being static */
3053 if (strcmp(fuzz_input_file, "-") == 0)
3055 /* XXX: Doesn'T work yet. */
3056 csp->server_connection.sfd = 0;
3060 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
3061 if (csp->server_connection.sfd == -1)
3063 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
3067 csp->content_type |= CT_GIF;
3068 csp->action->flags |= ACTION_DEANIMATE;
3069 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
3071 csp->http->path = strdup_or_die("/");
3072 csp->http->host = strdup_or_die("fuzz.example.org");
3073 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
3074 /* Prevent client socket monitoring */
3075 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3076 csp->flags |= CSP_FLAG_CHUNKED;
3078 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
3079 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3081 csp->content_type |= CT_DECLARED|CT_GIF;
3083 csp->config->socket_timeout = 0;
3085 cgi_init_error_messages();
3087 handle_established_connection(csp, &fwd);
3094 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3095 /*********************************************************************
3097 * Function : prepare_csp_for_next_request
3099 * Description : Put the csp in a mostly vergin state.
3102 * 1 : csp = Current client state (buffers, headers, etc...)
3106 *********************************************************************/
3107 static void prepare_csp_for_next_request(struct client_state *csp)
3109 csp->content_type = 0;
3110 csp->content_length = 0;
3111 csp->expected_content_length = 0;
3112 csp->expected_client_content_length = 0;
3113 list_remove_all(csp->headers);
3114 clear_iob(csp->iob);
3115 freez(csp->error_message);
3116 free_http_request(csp->http);
3117 destroy_list(csp->headers);
3118 destroy_list(csp->tags);
3119 #ifdef FEATURE_CLIENT_TAGS
3120 destroy_list(csp->client_tags);
3121 freez(csp->client_address);
3123 free_current_action(csp->action);
3124 if (NULL != csp->fwd)
3126 unload_forward_spec(csp->fwd);
3129 /* XXX: Store per-connection flags someplace else. */
3130 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
3131 #ifdef FEATURE_TOGGLE
3132 if (global_toggle_state)
3133 #endif /* def FEATURE_TOGGLE */
3135 csp->flags |= CSP_FLAG_TOGGLED_ON;
3138 if (csp->client_iob->eod > csp->client_iob->cur)
3140 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
3141 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
3143 assert(bytes_to_shift > 0);
3144 assert(data_length > 0);
3146 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
3147 data_length, bytes_to_shift);
3148 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
3149 csp->client_iob->cur = csp->client_iob->buf;
3150 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
3151 csp->client_iob->eod = csp->client_iob->buf + data_length;
3152 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
3154 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3159 * We mainly care about resetting client_iob->cur so we don't
3160 * waste buffer space at the beginning and don't mess up the
3161 * request restoration done by cgi_show_request().
3163 * Freeing the buffer itself isn't technically necessary,
3164 * but makes debugging more convenient.
3166 clear_iob(csp->client_iob);
3169 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3172 /*********************************************************************
3176 * Description : This is little more than chat. We only "serve" to
3177 * to close (or remember) any socket that chat may have
3181 * 1 : csp = Current client state (buffers, headers, etc...)
3185 *********************************************************************/
3187 void serve(struct client_state *csp)
3188 #else /* ifndef AMIGA */
3189 static void serve(struct client_state *csp)
3190 #endif /* def AMIGA */
3192 int config_file_change_detected = 0; /* Only used for debugging */
3193 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3194 #ifdef FEATURE_CONNECTION_SHARING
3195 static int monitor_thread_running = 0;
3196 #endif /* def FEATURE_CONNECTION_SHARING */
3197 int continue_chatting = 0;
3199 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
3200 csp->ip_addr_str, csp->cfd);
3204 unsigned int latency;
3209 * If the request has been crunched,
3210 * the calculated latency is zero.
3212 latency = (unsigned)(csp->server_connection.response_received -
3213 csp->server_connection.request_sent) / 2;
3215 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3216 && (csp->flags & CSP_FLAG_CRUNCHED)
3217 && (csp->expected_client_content_length != 0))
3219 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
3220 log_error(LOG_LEVEL_CONNECT,
3221 "Tainting client socket %d due to unread data.", csp->cfd);
3224 continue_chatting = (csp->config->feature_flags
3225 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3226 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3227 && (csp->cfd != JB_INVALID_SOCKET)
3228 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3229 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3230 || (csp->flags & CSP_FLAG_CHUNKED));
3232 if (!(csp->flags & CSP_FLAG_CRUNCHED)
3233 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
3235 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
3237 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
3239 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
3240 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3241 || !socket_is_still_alive(csp->server_connection.sfd)
3242 || !(latency < csp->server_connection.keep_alive_timeout))
3244 log_error(LOG_LEVEL_CONNECT,
3245 "Closing server socket %d connected to %s. "
3246 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
3247 csp->server_connection.sfd, csp->server_connection.host,
3248 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3249 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3250 socket_is_still_alive(csp->server_connection.sfd),
3251 csp->server_connection.keep_alive_timeout);
3252 #ifdef FEATURE_CONNECTION_SHARING
3253 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3255 forget_connection(csp->server_connection.sfd);
3257 #endif /* def FEATURE_CONNECTION_SHARING */
3258 close_socket(csp->server_connection.sfd);
3259 mark_connection_closed(&csp->server_connection);
3263 if (continue_chatting && any_loaded_file_changed(csp))
3265 continue_chatting = 0;
3266 config_file_change_detected = 1;
3269 if (continue_chatting)
3271 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
3272 && socket_is_still_alive(csp->cfd))
3274 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
3275 "pipelined on socket %d and the socket is still alive.",
3276 csp->requests_received_total+1, csp->cfd);
3277 prepare_csp_for_next_request(csp);
3281 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3283 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3285 log_error(LOG_LEVEL_CONNECT,
3286 "Waiting for the next client request on socket %d. "
3287 "Keeping the server socket %d to %s open.",
3288 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
3292 log_error(LOG_LEVEL_CONNECT,
3293 "Waiting for the next client request on socket %d. "
3294 "No server socket to keep open.", csp->cfd);
3298 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3299 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
3300 && socket_is_still_alive(csp->cfd))
3302 log_error(LOG_LEVEL_CONNECT,
3303 "Client request %u arrived in time on socket %d.",
3304 csp->requests_received_total+1, csp->cfd);
3305 prepare_csp_for_next_request(csp);
3309 #ifdef FEATURE_CONNECTION_SHARING
3310 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3311 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3312 && (socket_is_still_alive(csp->server_connection.sfd)))
3314 time_t time_open = time(NULL) - csp->server_connection.timestamp;
3316 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3321 remember_connection(&csp->server_connection);
3322 csp->server_connection.sfd = JB_INVALID_SOCKET;
3323 drain_and_close_socket(csp->cfd);
3324 csp->cfd = JB_INVALID_SOCKET;
3325 privoxy_mutex_lock(&connection_reuse_mutex);
3326 if (!monitor_thread_running)
3328 monitor_thread_running = 1;
3329 privoxy_mutex_unlock(&connection_reuse_mutex);
3330 wait_for_alive_connections();
3331 privoxy_mutex_lock(&connection_reuse_mutex);
3332 monitor_thread_running = 0;
3334 privoxy_mutex_unlock(&connection_reuse_mutex);
3336 #endif /* def FEATURE_CONNECTION_SHARING */
3340 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3342 log_error(LOG_LEVEL_CONNECT,
3343 "Closing server socket %d connected to %s. Keep-alive: %u. "
3344 "Tainted: %u. Socket alive: %u. Timeout: %u. "
3345 "Configuration file change detected: %u",
3346 csp->server_connection.sfd, csp->server_connection.host,
3347 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3348 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3349 socket_is_still_alive(csp->server_connection.sfd),
3350 csp->server_connection.keep_alive_timeout,
3351 config_file_change_detected);
3353 } while (continue_chatting);
3357 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3359 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3361 #ifdef FEATURE_CONNECTION_SHARING
3362 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3364 forget_connection(csp->server_connection.sfd);
3366 #endif /* def FEATURE_CONNECTION_SHARING */
3367 close_socket(csp->server_connection.sfd);
3370 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3371 mark_connection_closed(&csp->server_connection);
3374 if (csp->cfd != JB_INVALID_SOCKET)
3376 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3377 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3378 "Configuration file change detected: %u. Requests received: %u.",
3379 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3380 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3381 config_file_change_detected, csp->requests_received_total);
3382 drain_and_close_socket(csp->cfd);
3385 csp->flags &= ~CSP_FLAG_ACTIVE;
3391 /*********************************************************************
3393 * Function : server_thread
3395 * Description : We only exist to call `serve' in a threaded environment.
3398 * 1 : data = Current client state (buffers, headers, etc...)
3400 * Returns : Always 0.
3402 *********************************************************************/
3403 static int32 server_thread(void *data)
3405 serve((struct client_state *) data);
3412 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3413 /*********************************************************************
3417 * Description : Print usage info & exit.
3419 * Parameters : Pointer to argv[0] for identifying ourselves
3423 *********************************************************************/
3424 static void usage(const char *name)
3426 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3427 "Usage: %s [--config-test] "
3430 #endif /* defined(unix) */
3433 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3434 #endif /* defined(unix) */
3435 "[--version] [configfile]\n",
3439 show_fuzz_usage(name);
3442 printf("Aborting\n");
3447 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3450 #ifdef MUTEX_LOCKS_AVAILABLE
3451 /*********************************************************************
3453 * Function : privoxy_mutex_lock
3455 * Description : Locks a mutex.
3458 * 1 : mutex = The mutex to lock.
3460 * Returns : Void. May exit in case of errors.
3462 *********************************************************************/
3463 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3465 #ifdef FEATURE_PTHREAD
3466 int err = pthread_mutex_lock(mutex);
3469 if (mutex != &log_mutex)
3471 log_error(LOG_LEVEL_FATAL,
3472 "Mutex locking failed: %s.\n", strerror(err));
3477 EnterCriticalSection(mutex);
3478 #endif /* def FEATURE_PTHREAD */
3482 /*********************************************************************
3484 * Function : privoxy_mutex_unlock
3486 * Description : Unlocks a mutex.
3489 * 1 : mutex = The mutex to unlock.
3491 * Returns : Void. May exit in case of errors.
3493 *********************************************************************/
3494 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3496 #ifdef FEATURE_PTHREAD
3497 int err = pthread_mutex_unlock(mutex);
3500 if (mutex != &log_mutex)
3502 log_error(LOG_LEVEL_FATAL,
3503 "Mutex unlocking failed: %s.\n", strerror(err));
3508 LeaveCriticalSection(mutex);
3509 #endif /* def FEATURE_PTHREAD */
3513 /*********************************************************************
3515 * Function : privoxy_mutex_init
3517 * Description : Prepares a mutex.
3520 * 1 : mutex = The mutex to initialize.
3522 * Returns : Void. May exit in case of errors.
3524 *********************************************************************/
3525 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3527 #ifdef FEATURE_PTHREAD
3528 int err = pthread_mutex_init(mutex, 0);
3531 printf("Fatal error. Mutex initialization failed: %s.\n",
3536 InitializeCriticalSection(mutex);
3537 #endif /* def FEATURE_PTHREAD */
3539 #endif /* def MUTEX_LOCKS_AVAILABLE */
3541 /*********************************************************************
3543 * Function : initialize_mutexes
3545 * Description : Prepares mutexes if mutex support is available.
3549 * Returns : Void, exits in case of errors.
3551 *********************************************************************/
3552 static void initialize_mutexes(void)
3554 #ifdef MUTEX_LOCKS_AVAILABLE
3556 * Prepare global mutex semaphores
3558 privoxy_mutex_init(&log_mutex);
3559 privoxy_mutex_init(&log_init_mutex);
3560 privoxy_mutex_init(&connection_reuse_mutex);
3561 #ifdef FEATURE_EXTERNAL_FILTERS
3562 privoxy_mutex_init(&external_filter_mutex);
3564 #ifdef FEATURE_CLIENT_TAGS
3565 privoxy_mutex_init(&client_tags_mutex);
3569 * XXX: The assumptions below are a bit naive
3570 * and can cause locks that aren't necessary.
3572 * For example older FreeBSD versions (< 6.x?)
3573 * have no gethostbyname_r, but gethostbyname is
3576 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3577 privoxy_mutex_init(&resolver_mutex);
3578 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3580 * XXX: should we use a single mutex for
3581 * localtime() and gmtime() as well?
3583 #ifndef HAVE_GMTIME_R
3584 privoxy_mutex_init(&gmtime_mutex);
3585 #endif /* ndef HAVE_GMTIME_R */
3587 #ifndef HAVE_LOCALTIME_R
3588 privoxy_mutex_init(&localtime_mutex);
3589 #endif /* ndef HAVE_GMTIME_R */
3591 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
3592 privoxy_mutex_init(&rand_mutex);
3593 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
3595 #endif /* def MUTEX_LOCKS_AVAILABLE */
3598 /*********************************************************************
3602 * Description : Load the config file and start the listen loop.
3603 * This function is a lot more *sane* with the `load_config'
3604 * and `listen_loop' functions; although it stills does
3605 * a *little* too much for my taste.
3608 * 1 : argc = Number of parameters (including $0).
3609 * 2 : argv = Array of (char *)'s to the parameters.
3611 * Returns : 1 if : can't open config file, unrecognized directive,
3612 * stats requested in multi-thread mode, can't open the
3613 * log file, can't open the jar file, listen port is invalid,
3614 * any load fails, and can't bind port.
3616 * Else main never returns, the process must be signaled
3617 * to terminate execution. Or, on Windows, use the
3618 * "File", "Exit" menu option.
3620 *********************************************************************/
3622 int real_main(int argc, char **argv)
3624 int main(int argc, char **argv)
3628 int do_config_test = 0;
3629 #ifndef HAVE_ARC4RANDOM
3630 unsigned int random_seed;
3633 struct passwd *pw = NULL;
3634 struct group *grp = NULL;
3636 char *pre_chroot_nslookup_to_load_resolver = NULL;
3639 char *fuzz_input_type = NULL;
3640 char *fuzz_input_file = NULL;
3647 #if !defined(_WIN32)
3654 /* Prepare mutexes if supported and necessary. */
3655 initialize_mutexes();
3657 /* Enable logging until further notice. */
3661 * Parse the command line arguments
3663 * XXX: simply printing usage information in case of
3664 * invalid arguments isn't particularly user friendly.
3666 while (++argc_pos < argc)
3669 /* Check to see if the service must be installed or uninstalled */
3670 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3672 const char *pName = argv[argc_pos] + 9;
3675 exit((install_service(pName)) ? 0 : 1);
3677 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3679 const char *pName = argv[argc_pos] + 11;
3682 exit((uninstall_service(pName)) ? 0 : 1);
3684 else if (strcmp(argv[argc_pos], "--service") == 0)
3686 bRunAsService = TRUE;
3687 w32_set_service_cwd();
3688 atexit(w32_service_exit_notify);
3691 #endif /* defined(_WIN32) */
3694 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3696 if (strcmp(argv[argc_pos], "--help") == 0)
3701 else if (strcmp(argv[argc_pos], "--version") == 0)
3703 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3709 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3711 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3715 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3717 if (++argc_pos == argc) usage(argv[0]);
3718 pidfile = strdup_or_die(argv[argc_pos]);
3721 else if (strcmp(argv[argc_pos], "--user") == 0)
3726 if (++argc_pos == argc) usage(argv[argc_pos]);
3728 user_arg = strdup_or_die(argv[argc_pos]);
3729 group_name = strchr(user_arg, '.');
3730 if (NULL != group_name)
3732 /* Nul-terminate the user name */
3735 /* Skip the former delimiter to actually reach the group name */
3738 grp = getgrnam(group_name);
3741 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3744 pw = getpwnam(user_arg);
3747 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3753 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3755 if (++argc_pos == argc) usage(argv[0]);
3756 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3759 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3763 #endif /* defined(unix) */
3765 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3770 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
3773 if (argc < argc_pos + 2) usage(argv[0]);
3774 fuzz_input_type = argv[argc_pos];
3776 fuzz_input_file = argv[argc_pos];
3778 else if (strcmp(argv[argc_pos], "--stfu") == 0)
3780 set_debug_level(LOG_LEVEL_STFU);
3783 else if (argc_pos + 1 != argc)
3786 * This is neither the last command line
3787 * option, nor was it recognized before,
3788 * therefore it must be invalid.
3794 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3796 configfile = argv[argc_pos];
3799 } /* -END- while (more arguments) */
3801 show_version(Argv[0]);
3804 if (*configfile != '/')
3806 char cwd[BUFFER_SIZE];
3808 size_t abs_file_size;
3810 /* make config-filename absolute here */
3811 if (NULL == getcwd(cwd, sizeof(cwd)))
3813 perror("failed to get current working directory");
3817 basedir = strdup_or_die(cwd);
3819 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3820 abs_file = malloc_or_die(abs_file_size);
3821 strlcpy(abs_file, basedir, abs_file_size);
3822 strlcat(abs_file, "/", abs_file_size);
3823 strlcat(abs_file, configfile, abs_file_size);
3824 configfile = abs_file;
3826 #endif /* defined unix */
3830 clients->next = NULL;
3832 /* XXX: factor out initialising after the next stable release. */
3835 #elif defined(_WIN32)
3839 #ifndef HAVE_ARC4RANDOM
3840 random_seed = (unsigned int)time(NULL);
3842 srandom(random_seed);
3845 #endif /* ifdef HAVE_RANDOM */
3846 #endif /* ifndef HAVE_ARC4RANDOM */
3849 * Unix signal handling
3851 * Catch the abort, interrupt and terminate signals for a graceful exit
3852 * Catch the hangup signal so the errlog can be reopened.
3854 * Ignore the broken pipe signal as connection failures
3855 * are handled when and where they occur without relying
3858 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3861 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3863 for (idx = 0; idx < SZ(catched_signals); idx++)
3865 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3866 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3868 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3869 #endif /* ifdef sun */
3871 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3875 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3877 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3881 #else /* ifdef _WIN32 */
3882 # ifdef _WIN_CONSOLE
3884 * We *are* in a windows console app.
3885 * Print a verbose messages about FAQ's and such
3887 printf("%s", win32_blurb);
3888 # endif /* def _WIN_CONSOLE */
3889 #endif /* def _WIN32 */
3892 if (fuzz_input_type != NULL)
3894 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
3896 log_error(LOG_LEVEL_FATAL,
3897 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
3898 "Various data structures are static which is unsafe when using threads.");
3903 exit(NULL == load_config());
3906 /* Initialize the CGI subsystem */
3907 cgi_init_error_messages();
3910 * If running on unix and without the --no-daemon
3911 * option, become a daemon. I.e. fork, detach
3912 * from tty and get process group leadership
3921 if (pid < 0) /* error */
3926 else if (pid != 0) /* parent */
3931 * must check for errors
3932 * child died due to missing files aso
3935 wpid = waitpid(pid, &status, WNOHANG);
3947 * stderr (fd 2) will be closed later on,
3948 * when the config file has been parsed.
3954 * Reserve fd 0 and 1 to prevent abort() and friends
3955 * from sending stuff to the clients or servers.
3957 fd = open("/dev/null", O_RDONLY);
3960 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3964 if (dup2(fd, 0) == -1)
3966 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3970 fd = open("/dev/null", O_WRONLY);
3973 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3977 if (dup2(fd, 1) == -1)
3979 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3984 #ifdef FEATURE_EXTERNAL_FILTERS
3985 for (fd = 0; fd < 3; fd++)
3987 mark_socket_for_close_on_execute(fd);
3993 } /* -END- if (daemon_mode) */
3996 * As soon as we have written the PID file, we can switch
3997 * to the user and group ID indicated by the --user option
4003 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
4005 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
4009 if (setgroups(1, &grp->gr_gid))
4011 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
4014 else if (initgroups(pw->pw_name, pw->pw_gid))
4016 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
4022 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
4024 /* Read the time zone file from /etc before doing chroot. */
4026 if (NULL != pre_chroot_nslookup_to_load_resolver
4027 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
4029 /* Initialize resolver library. */
4030 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
4032 if (chroot(pw->pw_dir) < 0)
4034 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
4038 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
4041 if (setuid(pw->pw_uid))
4043 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
4047 char putenv_dummy[64];
4049 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
4050 if (putenv(putenv_dummy) != 0)
4052 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
4055 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
4056 if (putenv(putenv_dummy) != 0)
4058 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
4064 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
4067 #endif /* defined unix */
4070 /* This will be FALSE unless the command line specified --service
4074 /* Yup, so now we must attempt to establish a connection
4075 * with the service dispatcher. This will only work if this
4076 * process was launched by the service control manager to
4077 * actually run as a service. If this isn't the case, i've
4078 * known it take around 30 seconds or so for the call to return.
4081 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
4082 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
4084 /* Service has run, and at this point is now being stopped, so just return */
4089 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
4091 /* An error occurred. Usually it's because --service was wrongly specified
4092 * and we were unable to connect to the Service Control Dispatcher because
4093 * it wasn't expecting us and is therefore not listening.
4095 * For now, just continue below to call the listen_loop function.
4098 #endif /* def _WIN32 */
4108 /*********************************************************************
4110 * Function : bind_port_helper
4112 * Description : Bind the listen port. Handles logging, and aborts
4116 * 1 : haddr = Host address to bind to. Use NULL to bind to
4118 * 2 : hport = Specifies port to bind to.
4120 * Returns : Port that was opened.
4122 *********************************************************************/
4123 static jb_socket bind_port_helper(const char *haddr, int hport)
4128 result = bind_port(haddr, hport, &bfd);
4132 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
4136 log_error(LOG_LEVEL_FATAL,
4137 "can't bind to %s:%d: There may be another Privoxy "
4138 "or some other proxy running on port %d",
4139 bind_address, hport, hport);
4142 log_error(LOG_LEVEL_FATAL,
4143 "can't bind to %s:%d: The hostname is not resolvable",
4144 bind_address, hport);
4147 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
4148 bind_address, hport);
4151 /* shouldn't get here */
4152 return JB_INVALID_SOCKET;
4157 if (bfd >= FD_SETSIZE)
4159 log_error(LOG_LEVEL_FATAL,
4160 "Bind socket number too high to use select(): %d >= %d",
4168 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
4173 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
4181 /*********************************************************************
4183 * Function : bind_ports_helper
4185 * Description : Bind the listen ports. Handles logging, and aborts
4189 * 1 : config = Privoxy configuration. Specifies ports
4191 * 2 : sockets = Preallocated array of opened sockets
4192 * corresponding to specification in config.
4193 * All non-opened sockets will be set to
4194 * JB_INVALID_SOCKET.
4196 * Returns : Nothing. Inspect sockets argument.
4198 *********************************************************************/
4199 static void bind_ports_helper(struct configuration_spec * config,
4200 jb_socket sockets[])
4204 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4206 if (config->hport[i])
4208 sockets[i] = bind_port_helper(config->haddr[i], config->hport[i]);
4212 sockets[i] = JB_INVALID_SOCKET;
4215 config->need_bind = 0;
4219 /*********************************************************************
4221 * Function : close_ports_helper
4223 * Description : Close listenings ports.
4226 * 1 : sockets = Array of opened and non-opened sockets to
4227 * close. All sockets will be set to
4228 * JB_INVALID_SOCKET.
4230 * Returns : Nothing.
4232 *********************************************************************/
4233 static void close_ports_helper(jb_socket sockets[])
4237 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4239 if (JB_INVALID_SOCKET != sockets[i])
4241 close_socket(sockets[i]);
4243 sockets[i] = JB_INVALID_SOCKET;
4249 /* Without this simple workaround we get this compiler warning from _beginthread
4250 * warning C4028: formal parameter 1 different from declaration
4252 void w32_service_listen_loop(void *p)
4256 #endif /* def _WIN32 */
4259 /*********************************************************************
4261 * Function : listen_loop
4263 * Description : bind the listen port and enter a "FOREVER" listening loop.
4269 *********************************************************************/
4270 static void listen_loop(void)
4272 struct client_states *csp_list = NULL;
4273 struct client_state *csp = NULL;
4274 jb_socket bfds[MAX_LISTENING_SOCKETS];
4275 struct configuration_spec *config;
4276 unsigned int active_threads = 0;
4278 config = load_config();
4280 #ifdef FEATURE_CONNECTION_SHARING
4282 * XXX: Should be relocated once it no
4283 * longer needs to emit log messages.
4285 initialize_reusable_connections();
4286 #endif /* def FEATURE_CONNECTION_SHARING */
4288 bind_ports_helper(config, bfds);
4290 #ifdef FEATURE_GRACEFUL_TERMINATION
4291 while (!g_terminate)
4296 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
4297 while (waitpid(-1, NULL, WNOHANG) > 0)
4299 /* zombie children */
4301 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
4304 * Free data that was used by died threads
4306 active_threads = sweep();
4310 * Re-open the errlog after HUP signal
4312 if (received_hup_signal)
4314 if (NULL != config->logfile)
4316 init_error_log(Argv[0], config->logfile);
4318 received_hup_signal = 0;
4322 csp_list = zalloc_or_die(sizeof(*csp_list));
4323 csp = &csp_list->csp;
4325 log_error(LOG_LEVEL_CONNECT,
4326 "Waiting for the next client connection. Currently active threads: %d",
4330 * This config may be outdated, but for accept_connection()
4331 * it's fresh enough.
4333 csp->config = config;
4335 if (!accept_connection(csp, bfds))
4337 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
4349 csp->flags |= CSP_FLAG_ACTIVE;
4350 csp->server_connection.sfd = JB_INVALID_SOCKET;
4352 csp->config = config = load_config();
4354 if (config->need_bind)
4357 * Since we were listening to the "old port", we will not see
4358 * a "listen" param change until the next request. So, at
4359 * least 1 more request must be made for us to find the new
4360 * setting. I am simply closing the old socket and binding the
4363 * Which-ever is correct, we will serve 1 more page via the
4364 * old settings. This should probably be a "show-proxy-args"
4365 * request. This should not be a so common of an operation
4366 * that this will hurt people's feelings.
4369 close_ports_helper(bfds);
4371 bind_ports_helper(config, bfds);
4374 #ifdef FEATURE_TOGGLE
4375 if (global_toggle_state)
4376 #endif /* def FEATURE_TOGGLE */
4378 csp->flags |= CSP_FLAG_TOGGLED_ON;
4381 if (run_loader(csp))
4383 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
4384 /* Never get here - LOG_LEVEL_FATAL causes program exit */
4388 if (block_acl(NULL,csp))
4390 log_error(LOG_LEVEL_CONNECT,
4391 "Connection from %s on %s (socket %d) dropped due to ACL",
4392 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
4393 close_socket(csp->cfd);
4394 freez(csp->ip_addr_str);
4395 freez(csp->listen_addr_str);
4399 #endif /* def FEATURE_ACL */
4401 if ((0 != config->max_client_connections)
4402 && (active_threads >= config->max_client_connections))
4404 log_error(LOG_LEVEL_CONNECT,
4405 "Rejecting connection from %s. Maximum number of connections reached.",
4407 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4408 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4409 close_socket(csp->cfd);
4410 freez(csp->ip_addr_str);
4411 freez(csp->listen_addr_str);
4416 /* add it to the list of clients */
4417 csp_list->next = clients->next;
4418 clients->next = csp_list;
4420 if (config->multi_threaded)
4424 /* this is a switch () statement in the C preprocessor - ugh */
4425 #undef SELECTED_ONE_OPTION
4427 /* Use Pthreads in preference to native code */
4428 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
4429 #define SELECTED_ONE_OPTION
4431 pthread_t the_thread;
4432 pthread_attr_t attrs;
4434 pthread_attr_init(&attrs);
4435 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4436 errno = pthread_create(&the_thread, &attrs,
4437 (void * (*)(void *))serve, csp);
4438 child_id = errno ? -1 : 0;
4439 pthread_attr_destroy(&attrs);
4443 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
4444 #define SELECTED_ONE_OPTION
4445 child_id = _beginthread(
4446 (void (*)(void *))serve,
4451 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
4452 #define SELECTED_ONE_OPTION
4453 child_id = _beginthread(
4454 (void(* _Optlink)(void*))serve,
4460 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
4461 #define SELECTED_ONE_OPTION
4463 thread_id tid = spawn_thread
4464 (server_thread, "server", B_NORMAL_PRIORITY, csp);
4466 if ((tid >= 0) && (resume_thread(tid) == B_OK))
4468 child_id = (int) tid;
4477 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
4478 #define SELECTED_ONE_OPTION
4479 csp->cfd = ReleaseSocket(csp->cfd, -1);
4482 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4483 NP_Output, Output(),
4484 NP_CloseOutput, FALSE,
4485 NP_Name, (ULONG)"privoxy child",
4489 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4490 NP_Output, Output(),
4491 NP_CloseOutput, FALSE,
4492 NP_Name, (ULONG)"privoxy child",
4493 NP_StackSize, 200*1024,
4499 ((struct Task *)child_id)->tc_UserData = csp;
4500 Signal((struct Task *)child_id, SIGF_SINGLE);
4505 #if !defined(SELECTED_ONE_OPTION)
4508 /* This block is only needed when using fork().
4509 * When using threads, the server thread was
4510 * created and run by the call to _beginthread().
4512 if (child_id == 0) /* child */
4515 #ifdef FEATURE_TOGGLE
4516 int inherited_toggle_state = global_toggle_state;
4517 #endif /* def FEATURE_TOGGLE */
4522 * If we've been toggled or we've blocked the request, tell Mom
4525 #ifdef FEATURE_TOGGLE
4526 if (inherited_toggle_state != global_toggle_state)
4528 rc |= RC_FLAG_TOGGLED;
4530 #endif /* def FEATURE_TOGGLE */
4532 #ifdef FEATURE_STATISTICS
4533 if (csp->flags & CSP_FLAG_REJECTED)
4535 rc |= RC_FLAG_BLOCKED;
4537 #endif /* ndef FEATURE_STATISTICS */
4541 else if (child_id > 0) /* parent */
4543 /* in a fork()'d environment, the parent's
4544 * copy of the client socket and the CSP
4548 #if !defined(_WIN32) && !defined(__CYGWIN__)
4550 wait(&child_status);
4553 * Evaluate child's return code: If the child has
4554 * - been toggled, toggle ourselves
4555 * - blocked its request, bump up the stats counter
4558 #ifdef FEATURE_TOGGLE
4559 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4561 global_toggle_state = !global_toggle_state;
4563 #endif /* def FEATURE_TOGGLE */
4565 #ifdef FEATURE_STATISTICS
4567 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4571 #endif /* def FEATURE_STATISTICS */
4573 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4574 close_socket(csp->cfd);
4575 csp->flags &= ~CSP_FLAG_ACTIVE;
4579 #undef SELECTED_ONE_OPTION
4580 /* end of cpp switch () */
4585 * Spawning the child failed, assume it's because
4586 * there are too many children running already.
4587 * XXX: If you assume ...
4589 log_error(LOG_LEVEL_ERROR,
4590 "Unable to take any additional connections: %E. Active threads: %d",
4592 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4593 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4594 close_socket(csp->cfd);
4595 csp->flags &= ~CSP_FLAG_ACTIVE;
4604 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4606 /* Clean up. Aim: free all memory (no leaks) */
4607 #ifdef FEATURE_GRACEFUL_TERMINATION
4609 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4611 unload_current_config_file();
4612 unload_current_actions_file();
4613 unload_current_re_filterfile();
4614 #ifdef FEATURE_TRUST
4615 unload_current_trust_file();
4618 if (config->multi_threaded)
4625 } while ((clients->next != NULL) && (--i > 0));
4629 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4639 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4640 /* Cleanup - remove taskbar icon etc. */
4645 #endif /* FEATURE_GRACEFUL_TERMINATION */