1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
5 * Purpose : Main file. Contains main() method, main loop, and
6 * the main connection-handling function.
8 * Copyright : Written by and Copyright (C) 2001-2017 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 # ifndef FEATURE_PTHREAD
52 # include <winsock2.h>
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
65 # if !defined (__OS2__)
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
74 #include <sys/termios.h>
85 # include <socket.h> /* BeOS has select() for sockets only. */
86 # include <OS.h> /* declarations for threads and stuff. */
89 # if defined(__EMX__) || defined(__OS2__)
90 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
102 #endif /* def __GLIBC__ */
107 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
108 #endif /* HAVE_POLL */
118 #include "miscutil.h"
120 #include "jbsockets.h"
125 #include "urlmatch.h"
126 #ifdef FEATURE_CLIENT_TAGS
127 #include "client-tags.h"
131 struct client_states clients[1];
132 struct file_list files[1];
134 #ifdef FEATURE_STATISTICS
135 int urls_read = 0; /* total nr of urls read inc rejected */
136 int urls_rejected = 0; /* total nr of urls rejected */
137 #endif /* def FEATURE_STATISTICS */
139 #ifdef FEATURE_GRACEFUL_TERMINATION
143 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
144 static void sig_handler(int the_signal);
146 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
147 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
148 static jb_err get_server_headers(struct client_state *csp);
149 static const char *crunch_reason(const struct http_response *rsp);
150 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
151 static char *get_request_line(struct client_state *csp);
152 static jb_err receive_client_request(struct client_state *csp);
153 static jb_err parse_client_request(struct client_state *csp);
154 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
155 static jb_err change_request_destination(struct client_state *csp);
156 static void chat(struct client_state *csp);
157 static void serve(struct client_state *csp);
158 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
159 static void usage(const char *myname);
161 static void initialize_mutexes(void);
162 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
163 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
164 static void close_ports_helper(jb_socket sockets[]);
165 static void listen_loop(void);
168 void serve(struct client_state *csp);
169 #else /* ifndef AMIGA */
170 static void serve(struct client_state *csp);
171 #endif /* def AMIGA */
174 static int32 server_thread(void *data);
175 #endif /* def __BEOS__ */
178 #define sleep(N) Sleep(((N) * 1000))
182 #define sleep(N) DosSleep(((N) * 100))
186 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
187 void show_fuzz_usage(const char *name);
190 #ifdef MUTEX_LOCKS_AVAILABLE
192 * XXX: Does the locking stuff really belong in this file?
194 privoxy_mutex_t log_mutex;
195 privoxy_mutex_t log_init_mutex;
196 privoxy_mutex_t connection_reuse_mutex;
198 #ifdef FEATURE_EXTERNAL_FILTERS
199 privoxy_mutex_t external_filter_mutex;
201 #ifdef FEATURE_CLIENT_TAGS
202 privoxy_mutex_t client_tags_mutex;
205 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
206 privoxy_mutex_t resolver_mutex;
207 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
209 #ifndef HAVE_GMTIME_R
210 privoxy_mutex_t gmtime_mutex;
211 #endif /* ndef HAVE_GMTIME_R */
213 #ifndef HAVE_LOCALTIME_R
214 privoxy_mutex_t localtime_mutex;
215 #endif /* ndef HAVE_GMTIME_R */
217 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
218 privoxy_mutex_t rand_mutex;
219 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
221 #endif /* def MUTEX_LOCKS_AVAILABLE */
224 const char *basedir = NULL;
225 const char *pidfile = NULL;
226 static int received_hup_signal = 0;
227 #endif /* defined unix */
229 /* HTTP snipplets. */
230 static const char CSUCCEED[] =
231 "HTTP/1.1 200 Connection established\r\n\r\n";
233 static const char CHEADER[] =
234 "HTTP/1.1 400 Invalid header received from client\r\n"
235 "Content-Type: text/plain\r\n"
236 "Connection: close\r\n\r\n"
237 "Invalid header received from client.\r\n";
239 static const char FTP_RESPONSE[] =
240 "HTTP/1.1 400 Invalid request received from client\r\n"
241 "Content-Type: text/plain\r\n"
242 "Connection: close\r\n\r\n"
243 "Invalid request. Privoxy doesn't support FTP.\r\n";
245 static const char GOPHER_RESPONSE[] =
246 "HTTP/1.1 400 Invalid request received from client\r\n"
247 "Content-Type: text/plain\r\n"
248 "Connection: close\r\n\r\n"
249 "Invalid request. Privoxy doesn't support gopher.\r\n";
251 /* XXX: should be a template */
252 static const char MISSING_DESTINATION_RESPONSE[] =
253 "HTTP/1.1 400 Bad request received from client\r\n"
254 "Content-Type: text/plain\r\n"
255 "Connection: close\r\n\r\n"
256 "Bad request. Privoxy was unable to extract the destination.\r\n";
258 /* XXX: should be a template */
259 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
260 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
261 "Content-Type: text/plain\r\n"
262 "Connection: close\r\n\r\n"
263 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
265 /* XXX: should be a template */
266 static const char MESSED_UP_REQUEST_RESPONSE[] =
267 "HTTP/1.1 400 Malformed request after rewriting\r\n"
268 "Content-Type: text/plain\r\n"
269 "Connection: close\r\n\r\n"
270 "Bad request. Messed up with header filters.\r\n";
272 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
273 "HTTP/1.1 503 Too many open connections\r\n"
274 "Content-Type: text/plain\r\n"
275 "Connection: close\r\n\r\n"
276 "Maximum number of open connections reached.\r\n";
278 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
279 "HTTP/1.1 504 Connection timeout\r\n"
280 "Content-Type: text/plain\r\n"
281 "Connection: close\r\n\r\n"
282 "The connection timed out because the client request didn't arrive in time.\r\n";
284 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
285 "HTTP/1.1 400 Failed reading client body\r\n"
286 "Content-Type: text/plain\r\n"
287 "Connection: close\r\n\r\n"
288 "Failed parsing or buffering the chunk-encoded client body.\r\n";
290 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
291 "HTTP/1.1 417 Expecting too much\r\n"
292 "Content-Type: text/plain\r\n"
293 "Connection: close\r\n\r\n"
294 "Privoxy detected an unsupported Expect header value.\r\n";
296 /* A function to crunch a response */
297 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
299 /* Crunch function flags */
300 #define CF_NO_FLAGS 0
301 /* Cruncher applies to forced requests as well */
302 #define CF_IGNORE_FORCE 1
303 /* Crunched requests are counted for the block statistics */
304 #define CF_COUNT_AS_REJECT 2
306 /* A crunch function and its flags */
309 const crunch_func_ptr cruncher;
313 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
315 /* Complete list of cruncher functions */
316 static const struct cruncher crunchers_all[] = {
317 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
318 { block_url, CF_COUNT_AS_REJECT },
320 { trust_url, CF_COUNT_AS_REJECT },
321 #endif /* def FEATURE_TRUST */
322 { redirect_url, CF_NO_FLAGS },
323 { dispatch_cgi, CF_IGNORE_FORCE},
327 /* Light version, used after tags are applied */
328 static const struct cruncher crunchers_light[] = {
329 { block_url, CF_COUNT_AS_REJECT },
330 { redirect_url, CF_NO_FLAGS },
336 * XXX: Don't we really mean
342 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
343 /*********************************************************************
345 * Function : sig_handler
347 * Description : Signal handler for different signals.
348 * Exit gracefully on TERM and INT
349 * or set a flag that will cause the errlog
350 * to be reopened by the main thread on HUP.
353 * 1 : the_signal = the signal cause this function to call
357 *********************************************************************/
358 static void sig_handler(int the_signal)
364 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
376 received_hup_signal = 1;
382 * We shouldn't be here, unless we catch signals
383 * in main() that we can't handle here!
385 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
393 /*********************************************************************
395 * Function : client_protocol_is_unsupported
397 * Description : Checks if the client used a known unsupported
398 * protocol and deals with it by sending an error
402 * 1 : csp = Current client state (buffers, headers, etc...)
403 * 2 : req = the first request line send by the client
405 * Returns : TRUE if an error response has been generated, or
406 * FALSE if the request doesn't look invalid.
408 *********************************************************************/
409 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
412 * If it's a FTP or gopher request, we don't support it.
414 * These checks are better than nothing, but they might
415 * not work in all configurations and some clients might
416 * have problems digesting the answer.
418 * They should, however, never cause more problems than
419 * Privoxy's old behaviour (returning the misleading HTML
422 * "Could not resolve http://(ftp|gopher)://example.org").
424 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
426 const char *response = NULL;
427 const char *protocol = NULL;
429 if (!strncmpic(req, "GET ftp://", 10))
431 response = FTP_RESPONSE;
436 response = GOPHER_RESPONSE;
439 log_error(LOG_LEVEL_ERROR,
440 "%s tried to use Privoxy as %s proxy: %s",
441 csp->ip_addr_str, protocol, req);
442 log_error(LOG_LEVEL_CLF,
443 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
445 write_socket(csp->cfd, response, strlen(response));
454 /*********************************************************************
456 * Function : client_has_unsupported_expectations
458 * Description : Checks if the client used an unsupported expectation
459 * in which case an error message is delivered.
462 * 1 : csp = Current client state (buffers, headers, etc...)
464 * Returns : TRUE if an error response has been generated, or
465 * FALSE if the request doesn't look invalid.
467 *********************************************************************/
468 static int client_has_unsupported_expectations(const struct client_state *csp)
470 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
472 log_error(LOG_LEVEL_ERROR,
473 "Rejecting request from client %s with unsupported Expect header value",
475 log_error(LOG_LEVEL_CLF,
476 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
477 write_socket(csp->cfd, UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
478 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE));
488 /*********************************************************************
490 * Function : get_request_destination_elsewhere
492 * Description : If the client's request was redirected into
493 * Privoxy without the client's knowledge,
494 * the request line lacks the destination host.
496 * This function tries to get it elsewhere,
497 * provided accept-intercepted-requests is enabled.
499 * "Elsewhere" currently only means "Host: header",
500 * but in the future we may ask the redirecting
501 * packet filter to look the destination up.
503 * If the destination stays unknown, an error
504 * response is send to the client and headers
505 * are freed so that chat() can return directly.
508 * 1 : csp = Current client state (buffers, headers, etc...)
509 * 2 : headers = a header list
511 * Returns : JB_ERR_OK if the destination is now known, or
512 * JB_ERR_PARSE if it isn't.
514 *********************************************************************/
515 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
519 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
521 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
522 " Privoxy isn't configured to accept intercepted requests.",
523 csp->ip_addr_str, csp->http->cmd);
524 /* XXX: Use correct size */
525 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
526 csp->ip_addr_str, csp->http->cmd);
528 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
529 destroy_list(headers);
533 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
535 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
536 /* Split the domain we just got for pattern matching */
537 init_domain_components(csp->http);
544 /* We can't work without destination. Go spread the news.*/
546 req = list_to_text(headers);
548 /* XXX: Use correct size */
549 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
550 csp->ip_addr_str, csp->http->cmd);
551 log_error(LOG_LEVEL_ERROR,
552 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
553 csp->ip_addr_str, csp->http->cmd, req);
556 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
557 destroy_list(headers);
562 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
563 * to get the destination IP address, use it as host directly
564 * or do a reverse DNS lookup first.
569 /*********************************************************************
571 * Function : get_server_headers
573 * Description : Parses server headers in iob and fills them
574 * into csp->headers so that they can later be
578 * 1 : csp = Current client state (buffers, headers, etc...)
580 * Returns : JB_ERR_OK if everything went fine, or
581 * JB_ERR_PARSE if the headers were incomplete.
583 *********************************************************************/
584 static jb_err get_server_headers(struct client_state *csp)
586 int continue_hack_in_da_house = 0;
589 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
594 * continue hack in da house. Ignore the ending of
595 * this head and continue enlisting header lines.
596 * The reason is described below.
598 enlist(csp->headers, "");
599 continue_hack_in_da_house = 0;
602 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
605 * It's a bodyless continue response, don't
606 * stop header parsing after reaching its end.
608 * As a result Privoxy will concatenate the
609 * next response's head and parse and deliver
610 * the headers as if they belonged to one request.
612 * The client will separate them because of the
613 * empty line between them.
615 * XXX: What we're doing here is clearly against
616 * the intended purpose of the continue header,
617 * and under some conditions (HTTP/1.0 client request)
618 * it's a standard violation.
620 * Anyway, "sort of against the spec" is preferable
621 * to "always getting confused by Continue responses"
622 * (Privoxy's behaviour before this hack was added)
624 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
625 continue_hack_in_da_house = 1;
627 else if (*header == '\0')
630 * If the header is empty, but the Continue hack
631 * isn't active, we can assume that we reached the
632 * end of the buffer before we hit the end of the
635 * Inform the caller an let it decide how to handle it.
640 if (JB_ERR_MEMORY == enlist(csp->headers, header))
643 * XXX: Should we quit the request and return a
644 * out of memory error page instead?
646 log_error(LOG_LEVEL_ERROR,
647 "Out of memory while enlisting server headers. %s lost.",
657 /*********************************************************************
659 * Function : crunch_reason
661 * Description : Translates the crunch reason code into a string.
664 * 1 : rsp = a http_response
666 * Returns : A string with the crunch reason or an error description.
668 *********************************************************************/
669 static const char *crunch_reason(const struct http_response *rsp)
671 char * reason = NULL;
676 return "Internal error while searching for crunch reason";
679 switch (rsp->crunch_reason)
682 reason = "Unsupported HTTP feature";
688 reason = "Untrusted";
691 reason = "Redirected";
697 reason = "DNS failure";
699 case FORWARDING_FAILED:
700 reason = "Forwarding failed";
703 reason = "Connection failure";
706 reason = "Out of memory (may mask other reasons)";
708 case CONNECTION_TIMEOUT:
709 reason = "Connection timeout";
712 reason = "No server data received";
715 reason = "No reason recorded";
723 /*********************************************************************
725 * Function : log_applied_actions
727 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
731 * 1 : actions = Current action spec to log
735 *********************************************************************/
736 static void log_applied_actions(const struct current_action_spec *actions)
739 * The conversion to text requires lots of memory allocations so
740 * we only do the conversion if the user is actually interested.
742 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
744 char *actions_as_text = actions_to_line_of_text(actions);
745 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
746 freez(actions_as_text);
751 /*********************************************************************
753 * Function : send_crunch_response
755 * Description : Delivers already prepared response for
756 * intercepted requests, logs the interception
757 * and frees the response.
760 * 1 : csp = Current client state (buffers, headers, etc...)
761 * 2 : rsp = Fully prepared response. Will be freed on exit.
765 *********************************************************************/
766 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
768 const struct http_request *http = csp->http;
772 assert(rsp->head != NULL);
776 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
780 * Extract the status code from the actual head
781 * that will be send to the client. It is the only
782 * way to get it right for all requests, including
783 * the fixed ones for out-of-memory problems.
785 * A head starts like this: 'HTTP/1.1 200...'
789 status_code[0] = rsp->head[9];
790 status_code[1] = rsp->head[10];
791 status_code[2] = rsp->head[11];
792 status_code[3] = '\0';
794 /* Log that the request was crunched and why. */
795 log_applied_actions(csp->action);
796 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
797 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
798 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
800 /* Write the answer to the client */
801 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
802 || write_socket(csp->cfd, rsp->body, rsp->content_length))
804 /* There is nothing we can do about it. */
805 log_error(LOG_LEVEL_ERROR,
806 "Couldn't deliver the error message through client socket %d: %E",
810 /* Clean up and return */
811 if (cgi_error_memory() != rsp)
813 free_http_response(rsp);
819 /*********************************************************************
821 * Function : crunch_response_triggered
823 * Description : Checks if the request has to be crunched,
824 * and delivers the crunch response if necessary.
827 * 1 : csp = Current client state (buffers, headers, etc...)
828 * 2 : crunchers = list of cruncher functions to run
830 * Returns : TRUE if the request was answered with a crunch response
833 *********************************************************************/
834 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
836 struct http_response *rsp = NULL;
837 const struct cruncher *c;
840 * If CGI request crunching is disabled,
841 * check the CGI dispatcher out of order to
842 * prevent unintentional blocks or redirects.
844 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
845 && (NULL != (rsp = dispatch_cgi(csp))))
847 /* Deliver, log and free the interception response. */
848 send_crunch_response(csp, rsp);
849 csp->flags |= CSP_FLAG_CRUNCHED;
853 for (c = crunchers; c->cruncher != NULL; c++)
856 * Check the cruncher if either Privoxy is toggled
857 * on and the request isn't forced, or if the cruncher
858 * applies to forced requests as well.
860 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
861 !(csp->flags & CSP_FLAG_FORCED)) ||
862 (c->flags & CF_IGNORE_FORCE))
864 rsp = c->cruncher(csp);
867 /* Deliver, log and free the interception response. */
868 send_crunch_response(csp, rsp);
869 csp->flags |= CSP_FLAG_CRUNCHED;
870 #ifdef FEATURE_STATISTICS
871 if (c->flags & CF_COUNT_AS_REJECT)
873 csp->flags |= CSP_FLAG_REJECTED;
875 #endif /* def FEATURE_STATISTICS */
886 /*********************************************************************
888 * Function : build_request_line
890 * Description : Builds the HTTP request line.
892 * If a HTTP forwarder is used it expects the whole URL,
893 * web servers only get the path.
896 * 1 : csp = Current client state (buffers, headers, etc...)
897 * 2 : fwd = The forwarding spec used for the request
898 * XXX: Should use http->fwd instead.
899 * 3 : request_line = The old request line which will be replaced.
901 * Returns : Nothing. Terminates in case of memory problems.
903 *********************************************************************/
904 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
906 struct http_request *http = csp->http;
908 assert(http->ssl == 0);
911 * Downgrade http version from 1.1 to 1.0
912 * if +downgrade action applies.
914 if ((csp->action->flags & ACTION_DOWNGRADE)
915 && (!strcmpic(http->ver, "HTTP/1.1")))
918 http->ver = strdup_or_die("HTTP/1.0");
922 * Rebuild the request line.
924 freez(*request_line);
925 *request_line = strdup(http->gpc);
926 string_append(request_line, " ");
928 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
930 string_append(request_line, http->url);
934 string_append(request_line, http->path);
936 string_append(request_line, " ");
937 string_append(request_line, http->ver);
939 if (*request_line == NULL)
941 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
943 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
947 /*********************************************************************
949 * Function : change_request_destination
951 * Description : Parse a (rewritten) request line and regenerate
952 * the http request data.
955 * 1 : csp = Current client state (buffers, headers, etc...)
957 * Returns : Forwards the parse_http_request() return code.
958 * Terminates in case of memory problems.
960 *********************************************************************/
961 static jb_err change_request_destination(struct client_state *csp)
963 struct http_request *http = csp->http;
966 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
967 csp->headers->first->str);
968 free_http_request(http);
969 err = parse_http_request(csp->headers->first->str, http);
970 if (JB_ERR_OK != err)
972 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
973 jb_err_to_string(err));
980 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
981 /*********************************************************************
983 * Function : server_response_is_complete
985 * Description : Determines whether we should stop reading
986 * from the server socket.
989 * 1 : csp = Current client state (buffers, headers, etc...)
990 * 2 : content_length = Length of content received so far.
992 * Returns : TRUE if the response is complete,
995 *********************************************************************/
996 static int server_response_is_complete(struct client_state *csp,
997 unsigned long long content_length)
999 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1001 if (!strcmpic(csp->http->gpc, "HEAD"))
1004 * "HEAD" implies no body, we are thus expecting
1005 * no content. XXX: incomplete "list" of methods?
1007 csp->expected_content_length = 0;
1008 content_length_known = TRUE;
1009 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1012 if (csp->http->status == 204 || csp->http->status == 304)
1015 * Expect no body. XXX: incomplete "list" of status codes?
1017 csp->expected_content_length = 0;
1018 content_length_known = TRUE;
1019 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1022 return (content_length_known && ((0 == csp->expected_content_length)
1023 || (csp->expected_content_length <= content_length)));
1027 #ifdef FEATURE_CONNECTION_SHARING
1028 /*********************************************************************
1030 * Function : wait_for_alive_connections
1032 * Description : Waits for alive connections to timeout.
1038 *********************************************************************/
1039 static void wait_for_alive_connections(void)
1041 int connections_alive = close_unusable_connections();
1043 while (0 < connections_alive)
1045 log_error(LOG_LEVEL_CONNECT,
1046 "Waiting for %d connections to timeout.",
1049 connections_alive = close_unusable_connections();
1052 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1055 #endif /* def FEATURE_CONNECTION_SHARING */
1058 /*********************************************************************
1060 * Function : save_connection_destination
1062 * Description : Remembers a connection for reuse later on.
1065 * 1 : sfd = Open socket to remember.
1066 * 2 : http = The destination for the connection.
1067 * 3 : fwd = The forwarder settings used.
1068 * 4 : server_connection = storage.
1072 *********************************************************************/
1073 void save_connection_destination(jb_socket sfd,
1074 const struct http_request *http,
1075 const struct forward_spec *fwd,
1076 struct reusable_connection *server_connection)
1078 assert(sfd != JB_INVALID_SOCKET);
1079 assert(NULL != http->host);
1081 server_connection->sfd = sfd;
1082 server_connection->host = strdup_or_die(http->host);
1083 server_connection->port = http->port;
1085 assert(NULL != fwd);
1086 assert(server_connection->gateway_host == NULL);
1087 assert(server_connection->gateway_port == 0);
1088 assert(server_connection->forwarder_type == 0);
1089 assert(server_connection->forward_host == NULL);
1090 assert(server_connection->forward_port == 0);
1092 server_connection->forwarder_type = fwd->type;
1093 if (NULL != fwd->gateway_host)
1095 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1099 server_connection->gateway_host = NULL;
1101 server_connection->gateway_port = fwd->gateway_port;
1103 if (NULL != fwd->forward_host)
1105 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1109 server_connection->forward_host = NULL;
1111 server_connection->forward_port = fwd->forward_port;
1115 /*********************************************************************
1117 * Function : verify_request_length
1119 * Description : Checks if we already got the whole client requests
1120 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1123 * Data that doesn't belong to the current request is
1124 * either thrown away to let the client retry on a clean
1125 * socket, or stashed to be dealt with after the current
1126 * request is served.
1129 * 1 : csp = Current client state (buffers, headers, etc...)
1133 *********************************************************************/
1134 static void verify_request_length(struct client_state *csp)
1136 unsigned long long buffered_request_bytes =
1137 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1139 if ((csp->expected_client_content_length != 0)
1140 && (buffered_request_bytes != 0))
1142 if (csp->expected_client_content_length >= buffered_request_bytes)
1144 csp->expected_client_content_length -= buffered_request_bytes;
1145 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1146 "to account for the %llu ones we already got.",
1147 csp->expected_client_content_length, buffered_request_bytes);
1151 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1152 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1153 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1154 "Marking the server socket tainted after throwing %llu bytes away.",
1155 buffered_request_bytes - csp->expected_client_content_length);
1156 csp->expected_client_content_length = 0;
1157 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1160 if (csp->expected_client_content_length == 0)
1162 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1166 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1167 && ((csp->client_iob->cur < csp->client_iob->eod)
1168 || (csp->expected_client_content_length != 0)))
1170 if (strcmpic(csp->http->gpc, "GET")
1171 && strcmpic(csp->http->gpc, "HEAD")
1172 && strcmpic(csp->http->gpc, "TRACE")
1173 && strcmpic(csp->http->gpc, "OPTIONS")
1174 && strcmpic(csp->http->gpc, "DELETE"))
1176 /* XXX: this is an incomplete hack */
1177 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1178 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1182 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1184 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1186 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1187 log_error(LOG_LEVEL_CONNECT,
1188 "Possible pipeline attempt detected. The connection will not "
1189 "be kept alive and we will only serve the first request.");
1190 /* Nuke the pipelined requests from orbit, just to be sure. */
1191 clear_iob(csp->client_iob);
1196 * Keep the pipelined data around for now, we'll deal with
1197 * it once we're done serving the current request.
1199 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1200 assert(csp->client_iob->eod >= csp->client_iob->cur);
1201 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1202 "%d bytes of pipelined data received.",
1203 (int)(csp->client_iob->eod - csp->client_iob->cur));
1209 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1210 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1213 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1216 /*********************************************************************
1218 * Function : mark_server_socket_tainted
1220 * Description : Makes sure we don't reuse a server socket
1221 * (if we didn't read everything the server sent
1222 * us reusing the socket would lead to garbage).
1225 * 1 : csp = Current client state (buffers, headers, etc...)
1229 *********************************************************************/
1230 static void mark_server_socket_tainted(struct client_state *csp)
1233 * For consistency we always mark the server socket
1234 * tainted, however, to reduce the log noise we only
1235 * emit a log message if the server socket could have
1236 * actually been reused.
1238 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1239 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1241 log_error(LOG_LEVEL_CONNECT,
1242 "Marking the server socket %d tainted.",
1243 csp->server_connection.sfd);
1245 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1248 /*********************************************************************
1250 * Function : get_request_line
1252 * Description : Read the client request line.
1255 * 1 : csp = Current client state (buffers, headers, etc...)
1257 * Returns : Pointer to request line or NULL in case of errors.
1259 *********************************************************************/
1260 static char *get_request_line(struct client_state *csp)
1262 char buf[BUFFER_SIZE];
1263 char *request_line = NULL;
1266 memset(buf, 0, sizeof(buf));
1268 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1271 * If there are multiple pipelined requests waiting,
1272 * the flag will be set again once the next request
1275 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1277 request_line = get_header(csp->client_iob);
1278 if ((NULL != request_line) && ('\0' != *request_line))
1280 return request_line;
1284 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1285 "received yet. Continuing reading from %d.", csp->cfd);
1293 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1295 !data_is_available(csp->cfd, csp->config->socket_timeout)
1298 if (socket_is_still_alive(csp->cfd))
1300 log_error(LOG_LEVEL_CONNECT,
1301 "No request line on socket %d received in time. Timeout: %d.",
1302 csp->cfd, csp->config->socket_timeout);
1303 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1304 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1308 log_error(LOG_LEVEL_CONNECT,
1309 "The client side of the connection on socket %d got "
1310 "closed without sending a complete request line.", csp->cfd);
1315 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1317 if (len <= 0) return NULL;
1320 * If there is no memory left for buffering the
1321 * request, there is nothing we can do but hang up
1323 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1328 request_line = get_header(csp->client_iob);
1330 } while ((NULL != request_line) && ('\0' == *request_line));
1332 return request_line;
1338 CHUNK_STATUS_MISSING_DATA,
1339 CHUNK_STATUS_BODY_COMPLETE,
1340 CHUNK_STATUS_PARSE_ERROR
1344 /*********************************************************************
1346 * Function : chunked_body_is_complete
1348 * Description : Figures out whether or not a chunked body is complete.
1350 * Currently it always starts at the beginning of the
1351 * buffer which is somewhat wasteful and prevents Privoxy
1352 * from starting to forward the correctly parsed chunks
1353 * as soon as theoretically possible.
1355 * Should be modified to work with a common buffer,
1356 * and allow the caller to skip already parsed chunks.
1358 * This would allow the function to be used for unbuffered
1359 * response bodies as well.
1362 * 1 : iob = Buffer with the body to check.
1363 * 2 : length = Length of complete body
1365 * Returns : Enum with the result of the check.
1367 *********************************************************************/
1368 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1370 unsigned int chunksize;
1376 * We need at least a single digit, followed by "\r\n",
1377 * followed by an unknown amount of data, followed by "\r\n".
1379 if (p + 5 > iob->eod)
1381 return CHUNK_STATUS_MISSING_DATA;
1383 if (sscanf(p, "%x", &chunksize) != 1)
1385 return CHUNK_STATUS_PARSE_ERROR;
1389 * We want at least a single digit, followed by "\r\n",
1390 * followed by the specified amount of data, followed by "\r\n".
1392 if (p + chunksize + 5 > iob->eod)
1394 return CHUNK_STATUS_MISSING_DATA;
1397 /* Skip chunk-size. */
1398 p = strstr(p, "\r\n");
1401 return CHUNK_STATUS_PARSE_ERROR;
1403 /* Move beyond the chunkdata. */
1406 /* There should be another "\r\n" to skip */
1407 if (memcmp(p, "\r\n", 2))
1409 return CHUNK_STATUS_PARSE_ERROR;
1412 } while (chunksize > 0U);
1414 *length = (size_t)(p - iob->cur);
1415 assert(*length <= (size_t)(iob->eod - iob->cur));
1416 assert(p <= iob->eod);
1418 return CHUNK_STATUS_BODY_COMPLETE;
1423 /*********************************************************************
1425 * Function : receive_chunked_client_request_body
1427 * Description : Read the chunk-encoded client request body.
1428 * Failures are dealt with.
1431 * 1 : csp = Current client state (buffers, headers, etc...)
1433 * Returns : JB_ERR_OK or JB_ERR_PARSE
1435 *********************************************************************/
1436 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1439 enum chunk_status status;
1441 while (CHUNK_STATUS_MISSING_DATA ==
1442 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1444 char buf[BUFFER_SIZE];
1447 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1449 log_error(LOG_LEVEL_ERROR,
1450 "Timeout while waiting for the client body.");
1453 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1456 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1459 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1464 if (status != CHUNK_STATUS_BODY_COMPLETE)
1466 write_socket(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1467 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE));
1468 log_error(LOG_LEVEL_CLF,
1469 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1470 return JB_ERR_PARSE;
1472 log_error(LOG_LEVEL_CONNECT,
1473 "Chunked client body completely read. Length: %d", body_length);
1474 csp->expected_client_content_length = body_length;
1482 /*********************************************************************
1484 * Function : fuzz_chunked_transfer_encoding
1486 * Description : Treat the fuzzed input as chunked transfer encoding
1487 * to check and dechunk.
1490 * 1 : csp = Used to store the data.
1491 * 2 : fuzz_input_file = File to read the input from.
1493 * Returns : Result of dechunking
1495 *********************************************************************/
1496 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1499 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1500 enum chunk_status status;
1502 status = chunked_body_is_complete(csp->iob, &length);
1503 if (CHUNK_STATUS_BODY_COMPLETE != status)
1505 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1508 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1513 /*********************************************************************
1515 * Function : fuzz_client_request
1517 * Description : Try to get a client request from the fuzzed input.
1520 * 1 : csp = Current client state (buffers, headers, etc...)
1521 * 2 : fuzz_input_file = File to read the input from.
1523 * Returns : Result of fuzzing.
1525 *********************************************************************/
1526 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1531 csp->ip_addr_str = "fuzzer";
1533 if (strcmp(fuzz_input_file, "-") != 0)
1535 log_error(LOG_LEVEL_FATAL,
1536 "Fuzzed client requests can currenty only be read from stdin (-).");
1538 err = receive_client_request(csp);
1539 if (err != JB_ERR_OK)
1543 err = parse_client_request(csp);
1544 if (err != JB_ERR_OK)
1552 #endif /* def FUZZ */
1555 #ifdef FEATURE_FORCE_LOAD
1556 /*********************************************************************
1558 * Function : force_required
1560 * Description : Checks a request line to see if it contains
1561 * the FORCE_PREFIX. If it does, it is removed
1562 * unless enforcing requests has beend disabled.
1565 * 1 : request_line = HTTP request line
1567 * Returns : TRUE if force is required, FALSE otherwise.
1569 *********************************************************************/
1570 static int force_required(const struct client_state *csp, char *request_line)
1574 p = strstr(request_line, "http://");
1578 p += strlen("http://");
1582 /* Intercepted request usually don't specify the protocol. */
1586 /* Go to the beginning of the path */
1591 * If the path is missing the request line is invalid and we
1592 * are done here. The client-visible rejection happens later on.
1597 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1599 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1601 /* XXX: Should clean more carefully */
1602 strclean(request_line, FORCE_PREFIX);
1603 log_error(LOG_LEVEL_FORCE,
1604 "Enforcing request: \"%s\".", request_line);
1608 log_error(LOG_LEVEL_FORCE,
1609 "Ignored force prefix in request: \"%s\".", request_line);
1615 #endif /* def FEATURE_FORCE_LOAD */
1618 /*********************************************************************
1620 * Function : receive_client_request
1622 * Description : Read the client's request (more precisely the
1623 * client headers) and answer it if necessary.
1626 * 1 : csp = Current client state (buffers, headers, etc...)
1628 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1630 *********************************************************************/
1631 static jb_err receive_client_request(struct client_state *csp)
1633 char buf[BUFFER_SIZE];
1636 struct http_request *http;
1640 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1641 struct list header_list;
1642 struct list *headers = &header_list;
1644 /* We don't care if the arriving data is a valid HTTP request or not. */
1645 csp->requests_received_total++;
1649 memset(buf, 0, sizeof(buf));
1651 req = get_request_line(csp);
1654 mark_server_socket_tainted(csp);
1655 return JB_ERR_PARSE;
1657 assert(*req != '\0');
1659 if (client_protocol_is_unsupported(csp, req))
1661 return JB_ERR_PARSE;
1664 #ifdef FEATURE_FORCE_LOAD
1665 if (force_required(csp, req))
1667 csp->flags |= CSP_FLAG_FORCED;
1669 #endif /* def FEATURE_FORCE_LOAD */
1671 err = parse_http_request(req, http);
1673 if (JB_ERR_OK != err)
1675 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1676 /* XXX: Use correct size */
1677 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1678 log_error(LOG_LEVEL_ERROR,
1679 "Couldn't parse request line received from %s: %s",
1680 csp->ip_addr_str, jb_err_to_string(err));
1682 free_http_request(http);
1683 return JB_ERR_PARSE;
1686 /* grab the rest of the client's headers */
1690 p = get_header(csp->client_iob);
1694 /* There are no additional headers to read. */
1701 * We didn't receive a complete header
1702 * line yet, get the rest of it.
1704 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1706 log_error(LOG_LEVEL_ERROR,
1707 "Stopped grabbing the client headers.");
1708 destroy_list(headers);
1709 return JB_ERR_PARSE;
1712 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1715 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1716 destroy_list(headers);
1717 return JB_ERR_PARSE;
1720 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1723 * If there is no memory left for buffering the
1724 * request, there is nothing we can do but hang up
1726 destroy_list(headers);
1727 return JB_ERR_MEMORY;
1732 if (!strncmpic(p, "Transfer-Encoding:", 18))
1735 * XXX: should be called through sed()
1736 * but currently can't.
1738 client_transfer_encoding(csp, &p);
1741 * We were able to read a complete
1742 * header and can finally enlist it.
1749 if (http->host == NULL)
1752 * If we still don't know the request destination,
1753 * the request is invalid or the client uses
1754 * Privoxy without its knowledge.
1756 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1759 * Our attempts to get the request destination
1760 * elsewhere failed or Privoxy is configured
1761 * to only accept proxy requests.
1763 * An error response has already been send
1764 * and we're done here.
1766 return JB_ERR_PARSE;
1770 #ifdef FEATURE_CLIENT_TAGS
1771 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1772 set_client_address(csp, headers);
1773 get_tag_list_for_client(csp->client_tags, csp->client_address);
1777 * Determine the actions for this URL
1779 #ifdef FEATURE_TOGGLE
1780 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1782 /* Most compatible set of actions (i.e. none) */
1783 init_current_action(csp->action);
1786 #endif /* ndef FEATURE_TOGGLE */
1788 get_url_actions(csp, http);
1791 enlist(csp->headers, http->cmd);
1793 /* Append the previously read headers */
1794 err = list_append_list_unique(csp->headers, headers);
1795 destroy_list(headers);
1802 /*********************************************************************
1804 * Function : parse_client_request
1806 * Description : Parses the client's request and decides what to do
1809 * Note that since we're not using select() we could get
1810 * blocked here if a client connected, then didn't say
1814 * 1 : csp = Current client state (buffers, headers, etc...)
1816 * Returns : JB_ERR_OK or JB_ERR_PARSE
1818 *********************************************************************/
1819 static jb_err parse_client_request(struct client_state *csp)
1821 struct http_request *http = csp->http;
1824 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1825 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1826 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1827 && (csp->http->ssl == 0))
1829 /* Assume persistence until further notice */
1830 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1833 if (csp->http->ssl == 0)
1836 * This whole block belongs to chat() but currently
1837 * has to be executed before sed().
1839 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1841 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1843 return JB_ERR_PARSE;
1848 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1850 verify_request_length(csp);
1854 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1856 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1858 err = sed(csp, FILTER_CLIENT_HEADERS);
1859 if (JB_ERR_OK != err)
1861 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1863 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1864 csp->ip_addr_str, csp->http->cmd);
1865 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1866 return JB_ERR_PARSE;
1868 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1870 /* Check request line for rewrites. */
1871 if ((NULL == csp->headers->first->str)
1872 || (strcmp(http->cmd, csp->headers->first->str) &&
1873 (JB_ERR_OK != change_request_destination(csp))))
1876 * A header filter broke the request line - bail out.
1878 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1879 /* XXX: Use correct size */
1880 log_error(LOG_LEVEL_CLF,
1881 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1882 log_error(LOG_LEVEL_ERROR,
1883 "Invalid request line after applying header filters.");
1884 free_http_request(http);
1886 return JB_ERR_PARSE;
1889 if (client_has_unsupported_expectations(csp))
1891 return JB_ERR_PARSE;
1899 /*********************************************************************
1901 * Function : send_http_request
1903 * Description : Sends the HTTP headers from the client request
1904 * and all the body data that has already been received.
1907 * 1 : csp = Current client state (buffers, headers, etc...)
1909 * Returns : 0 on success, anything else is na error.
1911 *********************************************************************/
1912 static int send_http_request(struct client_state *csp)
1917 hdr = list_to_text(csp->headers);
1920 /* FIXME Should handle error properly */
1921 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1923 list_remove_all(csp->headers);
1926 * Write the client's (modified) header to the server
1927 * (along with anything else that may be in the buffer)
1929 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
1934 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
1935 csp->http->hostport);
1937 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
1938 && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
1941 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
1942 csp->http->hostport);
1945 return write_failure;
1950 /*********************************************************************
1952 * Function : handle_established_connection
1954 * Description : Shuffle data between client and server once the
1955 * connection has been established.
1958 * 1 : csp = Current client state (buffers, headers, etc...)
1960 * Returns : Nothing.
1962 *********************************************************************/
1963 static void handle_established_connection(struct client_state *csp)
1969 struct pollfd poll_fds[2];
1973 struct timeval timeout;
1976 int ms_iis5_hack = 0;
1977 unsigned long long byte_count = 0;
1978 struct http_request *http;
1979 long len = 0; /* for buffer sizes (and negative error codes) */
1980 int buffer_and_filter_content = 0;
1982 /* Skeleton for HTTP response, if we should intercept the request */
1983 struct http_response *rsp;
1984 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1985 int watch_client_socket;
1988 csp->receive_buffer_size = csp->config->receive_buffer_size;
1989 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
1990 if (csp->receive_buffer == NULL)
1992 log_error(LOG_LEVEL_ERROR,
1993 "Out of memory. Failed to allocate the receive buffer.");
1994 rsp = cgi_error_memory();
1995 send_crunch_response(csp, rsp);
2002 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2003 csp->cfd : csp->server_connection.sfd;
2006 /* pass data between the client and server
2007 * until one or the other shuts down the connection.
2012 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2013 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2021 * FD_ZERO here seems to point to an errant macro which crashes.
2022 * So do this by hand for now...
2024 memset(&rfds,0x00,sizeof(fd_set));
2028 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2029 if (!watch_client_socket)
2031 maxfd = csp->server_connection.sfd;
2034 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2036 FD_SET(csp->cfd, &rfds);
2039 FD_SET(csp->server_connection.sfd, &rfds);
2040 #endif /* ndef HAVE_POLL */
2042 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2043 if ((csp->flags & CSP_FLAG_CHUNKED)
2044 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2045 && ((csp->iob->eod - csp->iob->cur) >= 5)
2046 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2049 * XXX: This check should be obsolete now,
2050 * but let's wait a while to be sure.
2052 log_error(LOG_LEVEL_CONNECT,
2053 "Looks like we got the last chunk together with "
2054 "the server headers but didn't detect it earlier. "
2055 "We better stop reading.");
2056 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2057 csp->expected_content_length = byte_count;
2058 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2060 if (server_body && server_response_is_complete(csp, byte_count))
2062 if (csp->expected_content_length == byte_count)
2064 log_error(LOG_LEVEL_CONNECT,
2065 "Done reading from server. Content length: %llu as expected. "
2066 "Bytes most recently read: %d.",
2071 log_error(LOG_LEVEL_CONNECT,
2072 "Done reading from server. Expected content length: %llu. "
2073 "Actual content length: %llu. Bytes most recently read: %d.",
2074 csp->expected_content_length, byte_count, len);
2078 * XXX: should not jump around,
2079 * chat() is complicated enough already.
2083 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2086 poll_fds[0].fd = csp->cfd;
2087 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2088 if (!watch_client_socket)
2091 * Ignore incoming data, but still watch out
2092 * for disconnects etc. These flags are always
2093 * implied anyway but explicitly setting them
2096 poll_fds[0].events = POLLERR|POLLHUP;
2101 poll_fds[0].events = POLLIN;
2103 poll_fds[1].fd = csp->server_connection.sfd;
2104 poll_fds[1].events = POLLIN;
2105 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2107 timeout.tv_sec = csp->config->socket_timeout;
2108 timeout.tv_usec = 0;
2109 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2110 #endif /* def HAVE_POLL */
2114 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2115 csp->config->socket_timeout, http->url);
2116 if ((byte_count == 0) && (http->ssl == 0))
2118 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2120 mark_server_socket_tainted(csp);
2126 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2128 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2130 mark_server_socket_tainted(csp);
2135 * This is the body of the browser's request,
2136 * just read and write it.
2138 * XXX: Make sure the client doesn't use pipelining
2139 * behind Privoxy's back.
2142 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2144 log_error(LOG_LEVEL_CONNECT,
2145 "The client socket %d has become unusable while "
2146 "the server socket %d is still open.",
2147 csp->cfd, csp->server_connection.sfd);
2148 mark_server_socket_tainted(csp);
2152 if (poll_fds[0].revents != 0)
2154 if (FD_ISSET(csp->cfd, &rfds))
2155 #endif /* def HAVE_POLL*/
2157 int max_bytes_to_read = (int)csp->receive_buffer_size;
2159 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2160 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2162 if (data_is_available(csp->cfd, 0))
2165 * If the next request is already waiting, we have
2166 * to stop select()ing the client socket. Otherwise
2167 * we would always return right away and get nothing
2170 watch_client_socket = 0;
2171 log_error(LOG_LEVEL_CONNECT,
2172 "Stop watching client socket %d. "
2173 "There's already another request waiting.",
2178 * If the client socket is set, but there's no data
2179 * available on the socket, the client went fishing
2180 * and continuing talking to the server makes no sense.
2182 log_error(LOG_LEVEL_CONNECT,
2183 "The client closed socket %d while "
2184 "the server socket %d is still open.",
2185 csp->cfd, csp->server_connection.sfd);
2186 mark_server_socket_tainted(csp);
2189 if (csp->expected_client_content_length != 0)
2191 if (csp->expected_client_content_length < csp->receive_buffer_size)
2193 max_bytes_to_read = (int)csp->expected_client_content_length;
2195 log_error(LOG_LEVEL_CONNECT,
2196 "Waiting for up to %d bytes from the client.",
2199 assert(max_bytes_to_read <= csp->receive_buffer_size);
2200 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2202 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2206 /* XXX: not sure if this is necessary. */
2207 mark_server_socket_tainted(csp);
2208 break; /* "game over, man" */
2211 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2212 if (csp->expected_client_content_length != 0)
2214 assert(len <= max_bytes_to_read);
2215 csp->expected_client_content_length -= (unsigned)len;
2216 log_error(LOG_LEVEL_CONNECT,
2217 "Expected client content length set to %llu "
2218 "after reading %d bytes.",
2219 csp->expected_client_content_length, len);
2220 if (csp->expected_client_content_length == 0)
2222 log_error(LOG_LEVEL_CONNECT,
2223 "Done reading from the client.");
2224 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2227 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2229 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2231 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2232 mark_server_socket_tainted(csp);
2239 * The server wants to talk. It could be the header or the body.
2240 * If `hdr' is null, then it's the header otherwise it's the body.
2241 * FIXME: Does `hdr' really mean `host'? No.
2244 if (poll_fds[1].revents != 0)
2246 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2247 #endif /* HAVE_POLL */
2249 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2251 * If we are buffering content, we don't want to eat up to
2252 * buffer-limit bytes if the client no longer cares about them.
2253 * If we aren't buffering, however, a dead client socket will be
2254 * noticed pretty much right away anyway, so we can reduce the
2255 * overhead by skipping the check.
2257 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2260 log_error(LOG_LEVEL_CONNECT,
2261 "The server still wants to talk, but the client may already have hung up on us.");
2263 log_error(LOG_LEVEL_CONNECT,
2264 "The server still wants to talk, but the client hung up on us.");
2265 mark_server_socket_tainted(csp);
2267 #endif /* def _WIN32 */
2269 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2271 len = read_socket(csp->server_connection.sfd, csp->receive_buffer, (int)csp->receive_buffer_size);
2275 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2277 if (http->ssl && (csp->fwd == NULL))
2280 * Just hang up. We already confirmed the client's CONNECT
2281 * request with status code 200 and unencrypted content is
2282 * no longer welcome.
2284 log_error(LOG_LEVEL_ERROR,
2285 "CONNECT already confirmed. Unable to tell the client about the problem.");
2288 else if (byte_count)
2291 * Just hang up. We already transmitted the original headers
2292 * and parts of the original content and therefore missed the
2293 * chance to send an error message (without risking data corruption).
2295 * XXX: we could retry with a fancy range request here.
2297 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2298 "Unable to tell the client about the problem.");
2299 mark_server_socket_tainted(csp);
2303 * XXX: Consider handling the cases above the same.
2305 mark_server_socket_tainted(csp);
2309 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2310 if (csp->flags & CSP_FLAG_CHUNKED)
2312 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2314 /* XXX: this is a temporary hack */
2315 log_error(LOG_LEVEL_CONNECT,
2316 "Looks like we reached the end of the last chunk. "
2317 "We better stop reading.");
2318 csp->expected_content_length = byte_count + (unsigned long long)len;
2319 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2323 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2326 * This is guaranteed by allocating with zalloc_or_die()
2327 * and never (intentionally) writing to the last byte.
2329 * csp->receive_buffer_size is the size of the part of the
2330 * buffer we intentionally write to, but we actually
2331 * allocated csp->receive_buffer_size+1 bytes so the assertion
2332 * stays within the allocated range.
2334 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2337 * Add a trailing zero to let be able to use string operations.
2338 * XXX: do we still need this with filter_popups gone?
2340 assert(len <= csp->receive_buffer_size);
2341 csp->receive_buffer[len] = '\0';
2344 * Normally, this would indicate that we've read
2345 * as much as the server has sent us and we can
2346 * close the client connection. However, Microsoft
2347 * in its wisdom has released IIS/5 with a bug that
2348 * prevents it from sending the trailing \r\n in
2349 * a 302 redirect header (and possibly other headers).
2350 * To work around this if we've haven't parsed
2351 * a full header we'll append a trailing \r\n
2352 * and see if this now generates a valid one.
2354 * This hack shouldn't have any impacts. If we've
2355 * already transmitted the header or if this is a
2356 * SSL connection, then we won't bother with this
2357 * hack. So we only work on partially received
2358 * headers. If we append a \r\n and this still
2359 * doesn't generate a valid header, then we won't
2360 * transmit anything to the client.
2365 if (server_body || http->ssl)
2368 * If we have been buffering up the document,
2369 * now is the time to apply content modification
2370 * and send the result to the client.
2372 if (buffer_and_filter_content)
2374 p = execute_content_filters(csp);
2376 * If content filtering fails, use the original
2377 * buffer and length.
2378 * (see p != NULL ? p : csp->iob->cur below)
2382 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2384 #ifdef FEATURE_COMPRESSION
2385 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2386 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2388 char *compressed_content = compress_buffer(p,
2389 (size_t *)&csp->content_length, csp->config->compression_level);
2390 if (compressed_content != NULL)
2393 p = compressed_content;
2394 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2399 if (JB_ERR_OK != update_server_headers(csp))
2401 log_error(LOG_LEVEL_FATAL,
2402 "Failed to update server headers. after filtering.");
2405 hdr = list_to_text(csp->headers);
2408 /* FIXME Should handle error properly */
2409 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2412 if (write_socket(csp->cfd, hdr, strlen(hdr))
2413 || write_socket(csp->cfd,
2414 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2416 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2419 mark_server_socket_tainted(csp);
2427 break; /* "game over, man" */
2431 * This is NOT the body, so
2432 * Let's pretend the server just sent us a blank line.
2434 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
2435 len = (int)strlen(csp->receive_buffer);
2438 * Now, let the normal header parsing algorithm below do its
2439 * job. If it fails, we'll exit instead of continuing.
2446 * If this is an SSL connection or we're in the body
2447 * of the server document, just write it to the client,
2448 * unless we need to buffer the body for later content-filtering
2450 if (server_body || http->ssl)
2452 if (buffer_and_filter_content)
2455 * If there is no memory left for buffering the content, or the buffer limit
2456 * has been reached, switch to non-filtering mode, i.e. make & write the
2457 * header, flush the iob and buf, and get out of the way.
2459 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
2464 log_error(LOG_LEVEL_INFO,
2465 "Flushing header and buffers. Stepping back from filtering.");
2467 hdr = list_to_text(csp->headers);
2471 * Memory is too tight to even generate the header.
2472 * Send our static "Out-of-memory" page.
2474 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2475 rsp = cgi_error_memory();
2476 send_crunch_response(csp, rsp);
2477 mark_server_socket_tainted(csp);
2480 hdrlen = strlen(hdr);
2482 if (write_socket(csp->cfd, hdr, hdrlen)
2483 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2484 || (write_socket(csp->cfd, csp->receive_buffer, (size_t)len)))
2486 log_error(LOG_LEVEL_CONNECT,
2487 "Flush header and buffers to client failed: %E");
2489 mark_server_socket_tainted(csp);
2494 * Reset the byte_count to the amount of bytes
2495 * we just flushed. len will be added a few lines below,
2496 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2498 byte_count = (unsigned long long)flushed;
2500 buffer_and_filter_content = 0;
2506 if (write_socket(csp->cfd, csp->receive_buffer, (size_t)len))
2508 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2509 mark_server_socket_tainted(csp);
2513 byte_count += (unsigned long long)len;
2519 * We're still looking for the end of the server's header.
2520 * Buffer up the data we just read. If that fails, there's
2521 * little we can do but send our static out-of-memory page.
2523 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
2525 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2526 rsp = cgi_error_memory();
2527 send_crunch_response(csp, rsp);
2528 mark_server_socket_tainted(csp);
2532 /* Convert iob into something sed() can digest */
2533 if (JB_ERR_PARSE == get_server_headers(csp))
2538 * Well, we tried our MS IIS/5 hack and it didn't work.
2539 * The header is incomplete and there isn't anything
2540 * we can do about it.
2542 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2543 "Applying the MS IIS5 hack didn't help.");
2544 log_error(LOG_LEVEL_CLF,
2545 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2546 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2547 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2548 mark_server_socket_tainted(csp);
2554 * Since we have to wait for more from the server before
2555 * we can parse the headers we just continue here.
2557 log_error(LOG_LEVEL_CONNECT,
2558 "Continuing buffering server headers from socket %d. "
2559 "Bytes most recently read: %d.", csp->cfd, len);
2566 * Account for the content bytes we
2567 * might have gotten with the headers.
2569 assert(csp->iob->eod >= csp->iob->cur);
2570 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2573 /* Did we actually get anything? */
2574 if (NULL == csp->headers->first)
2576 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2578 log_error(LOG_LEVEL_ERROR,
2579 "No server or forwarder response received on socket %d. "
2580 "Closing client socket %d without sending data.",
2581 csp->server_connection.sfd, csp->cfd);
2582 log_error(LOG_LEVEL_CLF,
2583 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2587 log_error(LOG_LEVEL_ERROR,
2588 "No server or forwarder response received on socket %d.",
2589 csp->server_connection.sfd);
2590 send_crunch_response(csp, error_response(csp, "no-server-data"));
2592 free_http_request(http);
2593 mark_server_socket_tainted(csp);
2597 assert(csp->headers->first->str);
2599 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2600 strncmpic(csp->headers->first->str, "ICY", 3))
2603 * It doesn't look like a HTTP (or Shoutcast) response:
2604 * tell the client and log the problem.
2606 if (strlen(csp->headers->first->str) > 30)
2608 csp->headers->first->str[30] = '\0';
2610 log_error(LOG_LEVEL_ERROR,
2611 "Invalid server or forwarder response. Starts with: %s",
2612 csp->headers->first->str);
2613 log_error(LOG_LEVEL_CLF,
2614 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2615 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2616 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2617 free_http_request(http);
2618 mark_server_socket_tainted(csp);
2623 * We have now received the entire server header,
2624 * filter it and send the result to the client
2626 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2628 log_error(LOG_LEVEL_CLF,
2629 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2630 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2631 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2632 free_http_request(http);
2633 mark_server_socket_tainted(csp);
2636 hdr = list_to_text(csp->headers);
2639 /* FIXME Should handle error properly */
2640 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2643 if ((csp->flags & CSP_FLAG_CHUNKED)
2644 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2645 && ((csp->iob->eod - csp->iob->cur) >= 5)
2646 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2648 log_error(LOG_LEVEL_CONNECT,
2649 "Looks like we got the last chunk together with "
2650 "the server headers. We better stop reading.");
2651 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2652 csp->expected_content_length = byte_count;
2653 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2656 csp->server_connection.response_received = time(NULL);
2658 if (crunch_response_triggered(csp, crunchers_light))
2661 * One of the tags created by a server-header
2662 * tagger triggered a crunch. We already
2663 * delivered the crunch response to the client
2664 * and are done here after cleaning up.
2667 mark_server_socket_tainted(csp);
2670 /* Buffer and pcrs filter this if appropriate. */
2672 if (!http->ssl) /* We talk plaintext */
2674 buffer_and_filter_content = content_requires_filtering(csp);
2677 * Only write if we're not buffering for content modification
2679 if (!buffer_and_filter_content)
2682 * Write the server's (modified) header to
2683 * the client (along with anything else that
2684 * may be in the buffer)
2687 if (write_socket(csp->cfd, hdr, strlen(hdr))
2688 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2690 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2693 * The write failed, so don't bother mentioning it
2694 * to the client... it probably can't hear us anyway.
2697 mark_server_socket_tainted(csp);
2702 /* we're finished with the server's header */
2708 * If this was a MS IIS/5 hack then it means the server
2709 * has already closed the connection. Nothing more to read.
2714 log_error(LOG_LEVEL_ERROR,
2715 "Closed server connection detected. "
2716 "Applying the MS IIS5 hack didn't help.");
2717 log_error(LOG_LEVEL_CLF,
2718 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2719 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2720 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2721 mark_server_socket_tainted(csp);
2727 mark_server_socket_tainted(csp);
2728 return; /* huh? we should never get here */
2731 if (csp->content_length == 0)
2734 * If Privoxy didn't recalculate the Content-Length,
2735 * byte_count is still correct.
2737 csp->content_length = byte_count;
2740 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2741 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2742 && (csp->expected_content_length != byte_count))
2744 log_error(LOG_LEVEL_CONNECT,
2745 "Received %llu bytes while expecting %llu.",
2746 byte_count, csp->expected_content_length);
2747 mark_server_socket_tainted(csp);
2751 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2752 csp->ip_addr_str, http->ocmd, csp->content_length);
2754 csp->server_connection.timestamp = time(NULL);
2758 /*********************************************************************
2762 * Description : Once a connection from the client has been accepted,
2763 * this function is called (via serve()) to handle the
2764 * main business of the communication. This function
2765 * returns after dealing with a single request. It can
2766 * be called multiple times with the same client socket
2767 * if the client is keeping the connection alive.
2769 * The decision whether or not a client connection will
2770 * be kept alive is up to the caller which also must
2771 * close the client socket when done.
2773 * FIXME: chat is nearly thousand lines long.
2777 * 1 : csp = Current client state (buffers, headers, etc...)
2779 * Returns : Nothing.
2781 *********************************************************************/
2782 static void chat(struct client_state *csp)
2784 const struct forward_spec *fwd;
2785 struct http_request *http;
2786 /* Skeleton for HTTP response, if we should intercept the request */
2787 struct http_response *rsp;
2791 if (receive_client_request(csp) != JB_ERR_OK)
2795 if (parse_client_request(csp) != JB_ERR_OK)
2800 /* decide how to route the HTTP request */
2801 fwd = forward_url(csp, http);
2804 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2805 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2810 * build the http request to send to the server
2811 * we have to do one of the following:
2813 * create = use the original HTTP request to create a new
2814 * HTTP request that has either the path component
2815 * without the http://domainspec (w/path) or the
2816 * full orininal URL (w/url)
2817 * Note that the path and/or the HTTP version may
2818 * have been altered by now.
2820 * connect = Open a socket to the host:port of the server
2821 * and short-circuit server and client socket.
2823 * pass = Pass the request unchanged if forwarding a CONNECT
2824 * request to a parent proxy. Note that we'll be sending
2825 * the CFAIL message ourselves if connecting to the parent
2826 * fails, but we won't send a CSUCCEED message if it works,
2827 * since that would result in a double message (ours and the
2828 * parent's). After sending the request to the parent, we simply
2831 * here's the matrix:
2834 * +--------+--------+
2836 * 0 | create | connect|
2838 * Forwarding +--------+--------+
2840 * 1 | create | pass |
2842 * +--------+--------+
2846 if (http->ssl && connect_port_is_forbidden(csp))
2848 const char *acceptable_connect_ports =
2849 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
2850 assert(NULL != acceptable_connect_ports);
2851 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
2852 "limit-connect{%s} doesn't allow CONNECT requests to %s",
2853 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
2854 csp->action->flags |= ACTION_BLOCK;
2860 freez(csp->headers->first->str);
2861 build_request_line(csp, fwd, &csp->headers->first->str);
2865 * We have a request. Check if one of the crunchers wants it.
2867 if (crunch_response_triggered(csp, crunchers_all))
2870 * Yes. The client got the crunch response and we're done here.
2875 log_applied_actions(csp->action);
2876 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
2878 if (fwd->forward_host)
2880 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
2881 fwd->forward_host, fwd->forward_port, http->hostport);
2885 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
2888 /* here we connect to the server, gateway, or the forwarder */
2890 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2891 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
2892 && socket_is_still_alive(csp->server_connection.sfd)
2893 && connection_destination_matches(&csp->server_connection, http, fwd))
2895 log_error(LOG_LEVEL_CONNECT,
2896 "Reusing server socket %d connected to %s. Total requests: %u.",
2897 csp->server_connection.sfd, csp->server_connection.host,
2898 csp->server_connection.requests_sent_total);
2902 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2904 #ifdef FEATURE_CONNECTION_SHARING
2905 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2907 remember_connection(&csp->server_connection);
2910 #endif /* def FEATURE_CONNECTION_SHARING */
2912 log_error(LOG_LEVEL_CONNECT,
2913 "Closing server socket %d connected to %s. Total requests: %u.",
2914 csp->server_connection.sfd, csp->server_connection.host,
2915 csp->server_connection.requests_sent_total);
2916 close_socket(csp->server_connection.sfd);
2918 mark_connection_closed(&csp->server_connection);
2920 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2922 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
2924 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
2926 if (fwd->type != SOCKS_NONE)
2929 rsp = error_response(csp, "forwarding-failed");
2931 else if (errno == EINVAL)
2933 rsp = error_response(csp, "no-such-domain");
2937 rsp = error_response(csp, "connect-failed");
2940 /* Write the answer to the client */
2943 send_crunch_response(csp, rsp);
2947 * Temporary workaround to prevent already-read client
2948 * bodies from being parsed as new requests. For now we
2949 * err on the safe side and throw all the following
2950 * requests under the bus, even if no client body has been
2951 * buffered. A compliant client will repeat the dropped
2952 * requests on an untainted connection.
2954 * The proper fix is to discard the no longer needed
2955 * client body in the buffer (if there is one) and to
2956 * continue parsing the bytes that follow.
2958 drain_and_close_socket(csp->cfd);
2959 csp->cfd = JB_INVALID_SOCKET;
2963 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2964 save_connection_destination(csp->server_connection.sfd,
2965 http, fwd, &csp->server_connection);
2966 csp->server_connection.keep_alive_timeout =
2967 (unsigned)csp->config->keep_alive_timeout;
2969 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2971 csp->server_connection.requests_sent_total++;
2973 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
2975 /* Client headers have been sent optimistically */
2976 assert(csp->headers->last == NULL);
2978 else if (fwd->forward_host || (http->ssl == 0))
2980 if (send_http_request(csp))
2982 rsp = error_response(csp, "connect-failed");
2985 send_crunch_response(csp, rsp);
2993 * We're running an SSL tunnel and we're not forwarding,
2994 * so just ditch the client headers, send the "connect succeeded"
2995 * message to the client, flush the rest, and get out of the way.
2997 list_remove_all(csp->headers);
2998 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
3002 clear_iob(csp->client_iob);
3005 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
3007 /* XXX: should the time start earlier for optimistically sent data? */
3008 csp->server_connection.request_sent = time(NULL);
3010 handle_established_connection(csp);
3011 freez(csp->receive_buffer);
3016 /*********************************************************************
3018 * Function : fuzz_server_response
3020 * Description : Treat the input as a whole server response.
3023 * 1 : csp = Current client state (buffers, headers, etc...)
3024 * 2 : fuzz_input_file = File to read the input from.
3028 *********************************************************************/
3029 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
3031 static struct forward_spec fwd; /* Zero'd due to being static */
3034 if (strcmp(fuzz_input_file, "-") == 0)
3036 /* XXX: Doesn'T work yet. */
3037 csp->server_connection.sfd = 0;
3041 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
3042 if (csp->server_connection.sfd == -1)
3044 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
3049 csp->content_type |= CT_GIF;
3050 csp->action->flags |= ACTION_DEANIMATE;
3051 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
3053 csp->http->path = strdup_or_die("/");
3054 csp->http->host = strdup_or_die("fuzz.example.org");
3055 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
3056 /* Prevent client socket monitoring */
3057 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3058 csp->flags |= CSP_FLAG_CHUNKED;
3060 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
3061 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3063 csp->content_type |= CT_DECLARED|CT_GIF;
3065 csp->config->socket_timeout = 0;
3067 cgi_init_error_messages();
3069 handle_established_connection(csp);
3070 freez(csp->receive_buffer);
3077 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3078 /*********************************************************************
3080 * Function : prepare_csp_for_next_request
3082 * Description : Put the csp in a mostly vergin state.
3085 * 1 : csp = Current client state (buffers, headers, etc...)
3089 *********************************************************************/
3090 static void prepare_csp_for_next_request(struct client_state *csp)
3092 csp->content_type = 0;
3093 csp->content_length = 0;
3094 csp->expected_content_length = 0;
3095 csp->expected_client_content_length = 0;
3096 list_remove_all(csp->headers);
3097 clear_iob(csp->iob);
3098 freez(csp->error_message);
3099 free_http_request(csp->http);
3100 destroy_list(csp->headers);
3101 destroy_list(csp->tags);
3102 #ifdef FEATURE_CLIENT_TAGS
3103 destroy_list(csp->client_tags);
3104 freez(csp->client_address);
3106 free_current_action(csp->action);
3107 if (NULL != csp->fwd)
3109 unload_forward_spec(csp->fwd);
3112 /* XXX: Store per-connection flags someplace else. */
3113 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
3114 #ifdef FEATURE_TOGGLE
3115 if (global_toggle_state)
3116 #endif /* def FEATURE_TOGGLE */
3118 csp->flags |= CSP_FLAG_TOGGLED_ON;
3121 if (csp->client_iob->eod > csp->client_iob->cur)
3123 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
3124 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
3126 assert(bytes_to_shift > 0);
3127 assert(data_length > 0);
3129 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
3130 data_length, bytes_to_shift);
3131 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
3132 csp->client_iob->cur = csp->client_iob->buf;
3133 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
3134 csp->client_iob->eod = csp->client_iob->buf + data_length;
3135 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
3137 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3142 * We mainly care about resetting client_iob->cur so we don't
3143 * waste buffer space at the beginning and don't mess up the
3144 * request restoration done by cgi_show_request().
3146 * Freeing the buffer itself isn't technically necessary,
3147 * but makes debugging more convenient.
3149 clear_iob(csp->client_iob);
3152 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3155 /*********************************************************************
3159 * Description : This is little more than chat. We only "serve" to
3160 * to close (or remember) any socket that chat may have
3164 * 1 : csp = Current client state (buffers, headers, etc...)
3168 *********************************************************************/
3170 void serve(struct client_state *csp)
3171 #else /* ifndef AMIGA */
3172 static void serve(struct client_state *csp)
3173 #endif /* def AMIGA */
3175 int config_file_change_detected = 0; /* Only used for debugging */
3176 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3177 #ifdef FEATURE_CONNECTION_SHARING
3178 static int monitor_thread_running = 0;
3179 #endif /* def FEATURE_CONNECTION_SHARING */
3180 int continue_chatting = 0;
3182 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
3183 csp->ip_addr_str, csp->cfd);
3187 unsigned int latency;
3192 * If the request has been crunched,
3193 * the calculated latency is zero.
3195 latency = (unsigned)(csp->server_connection.response_received -
3196 csp->server_connection.request_sent) / 2;
3198 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3199 && (csp->flags & CSP_FLAG_CRUNCHED)
3200 && (csp->expected_client_content_length != 0))
3202 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
3203 log_error(LOG_LEVEL_CONNECT,
3204 "Tainting client socket %d due to unread data.", csp->cfd);
3207 continue_chatting = (csp->config->feature_flags
3208 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3209 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3210 && (csp->cfd != JB_INVALID_SOCKET)
3211 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3212 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3213 || (csp->flags & CSP_FLAG_CHUNKED));
3215 if (!(csp->flags & CSP_FLAG_CRUNCHED)
3216 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
3218 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
3220 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
3222 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
3223 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3224 || !socket_is_still_alive(csp->server_connection.sfd)
3225 || !(latency < csp->server_connection.keep_alive_timeout))
3227 log_error(LOG_LEVEL_CONNECT,
3228 "Closing server socket %d connected to %s. "
3229 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
3230 csp->server_connection.sfd, csp->server_connection.host,
3231 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3232 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3233 socket_is_still_alive(csp->server_connection.sfd),
3234 csp->server_connection.keep_alive_timeout);
3235 #ifdef FEATURE_CONNECTION_SHARING
3236 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3238 forget_connection(csp->server_connection.sfd);
3240 #endif /* def FEATURE_CONNECTION_SHARING */
3241 close_socket(csp->server_connection.sfd);
3242 mark_connection_closed(&csp->server_connection);
3246 if (continue_chatting && any_loaded_file_changed(csp))
3248 continue_chatting = 0;
3249 config_file_change_detected = 1;
3252 if (continue_chatting)
3254 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
3255 && socket_is_still_alive(csp->cfd))
3257 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
3258 "pipelined on socket %d and the socket is still alive.",
3259 csp->requests_received_total+1, csp->cfd);
3260 prepare_csp_for_next_request(csp);
3264 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3266 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3268 log_error(LOG_LEVEL_CONNECT,
3269 "Waiting for the next client request on socket %d. "
3270 "Keeping the server socket %d to %s open.",
3271 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
3275 log_error(LOG_LEVEL_CONNECT,
3276 "Waiting for the next client request on socket %d. "
3277 "No server socket to keep open.", csp->cfd);
3281 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3282 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
3283 && socket_is_still_alive(csp->cfd))
3285 log_error(LOG_LEVEL_CONNECT,
3286 "Client request %u arrived in time on socket %d.",
3287 csp->requests_received_total+1, csp->cfd);
3288 prepare_csp_for_next_request(csp);
3292 #ifdef FEATURE_CONNECTION_SHARING
3293 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3294 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3295 && (socket_is_still_alive(csp->server_connection.sfd)))
3297 time_t time_open = time(NULL) - csp->server_connection.timestamp;
3299 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3304 remember_connection(&csp->server_connection);
3305 csp->server_connection.sfd = JB_INVALID_SOCKET;
3306 drain_and_close_socket(csp->cfd);
3307 csp->cfd = JB_INVALID_SOCKET;
3308 privoxy_mutex_lock(&connection_reuse_mutex);
3309 if (!monitor_thread_running)
3311 monitor_thread_running = 1;
3312 privoxy_mutex_unlock(&connection_reuse_mutex);
3313 wait_for_alive_connections();
3314 privoxy_mutex_lock(&connection_reuse_mutex);
3315 monitor_thread_running = 0;
3317 privoxy_mutex_unlock(&connection_reuse_mutex);
3319 #endif /* def FEATURE_CONNECTION_SHARING */
3323 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3325 log_error(LOG_LEVEL_CONNECT,
3326 "Closing server socket %d connected to %s. Keep-alive: %u. "
3327 "Tainted: %u. Socket alive: %u. Timeout: %u. "
3328 "Configuration file change detected: %u",
3329 csp->server_connection.sfd, csp->server_connection.host,
3330 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3331 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3332 socket_is_still_alive(csp->server_connection.sfd),
3333 csp->server_connection.keep_alive_timeout,
3334 config_file_change_detected);
3336 } while (continue_chatting);
3340 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3342 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3344 #ifdef FEATURE_CONNECTION_SHARING
3345 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3347 forget_connection(csp->server_connection.sfd);
3349 #endif /* def FEATURE_CONNECTION_SHARING */
3350 close_socket(csp->server_connection.sfd);
3353 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3354 mark_connection_closed(&csp->server_connection);
3357 if (csp->cfd != JB_INVALID_SOCKET)
3359 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3360 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3361 "Configuration file change detected: %u. Requests received: %u.",
3362 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3363 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3364 config_file_change_detected, csp->requests_received_total);
3365 drain_and_close_socket(csp->cfd);
3368 free_csp_resources(csp);
3370 csp->flags &= ~CSP_FLAG_ACTIVE;
3376 /*********************************************************************
3378 * Function : server_thread
3380 * Description : We only exist to call `serve' in a threaded environment.
3383 * 1 : data = Current client state (buffers, headers, etc...)
3385 * Returns : Always 0.
3387 *********************************************************************/
3388 static int32 server_thread(void *data)
3390 serve((struct client_state *) data);
3397 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3398 /*********************************************************************
3402 * Description : Print usage info & exit.
3404 * Parameters : Pointer to argv[0] for identifying ourselves
3408 *********************************************************************/
3409 static void usage(const char *name)
3411 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3412 "Usage: %s [--config-test] "
3415 #endif /* defined(unix) */
3418 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3419 #endif /* defined(unix) */
3420 "[--version] [configfile]\n",
3424 show_fuzz_usage(name);
3427 printf("Aborting\n");
3432 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3435 #ifdef MUTEX_LOCKS_AVAILABLE
3436 /*********************************************************************
3438 * Function : privoxy_mutex_lock
3440 * Description : Locks a mutex.
3443 * 1 : mutex = The mutex to lock.
3445 * Returns : Void. May exit in case of errors.
3447 *********************************************************************/
3448 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3450 #ifdef FEATURE_PTHREAD
3451 int err = pthread_mutex_lock(mutex);
3454 if (mutex != &log_mutex)
3456 log_error(LOG_LEVEL_FATAL,
3457 "Mutex locking failed: %s.\n", strerror(err));
3462 EnterCriticalSection(mutex);
3463 #endif /* def FEATURE_PTHREAD */
3467 /*********************************************************************
3469 * Function : privoxy_mutex_unlock
3471 * Description : Unlocks a mutex.
3474 * 1 : mutex = The mutex to unlock.
3476 * Returns : Void. May exit in case of errors.
3478 *********************************************************************/
3479 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3481 #ifdef FEATURE_PTHREAD
3482 int err = pthread_mutex_unlock(mutex);
3485 if (mutex != &log_mutex)
3487 log_error(LOG_LEVEL_FATAL,
3488 "Mutex unlocking failed: %s.\n", strerror(err));
3493 LeaveCriticalSection(mutex);
3494 #endif /* def FEATURE_PTHREAD */
3498 /*********************************************************************
3500 * Function : privoxy_mutex_init
3502 * Description : Prepares a mutex.
3505 * 1 : mutex = The mutex to initialize.
3507 * Returns : Void. May exit in case of errors.
3509 *********************************************************************/
3510 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3512 #ifdef FEATURE_PTHREAD
3513 int err = pthread_mutex_init(mutex, 0);
3516 printf("Fatal error. Mutex initialization failed: %s.\n",
3521 InitializeCriticalSection(mutex);
3522 #endif /* def FEATURE_PTHREAD */
3524 #endif /* def MUTEX_LOCKS_AVAILABLE */
3526 /*********************************************************************
3528 * Function : initialize_mutexes
3530 * Description : Prepares mutexes if mutex support is available.
3534 * Returns : Void, exits in case of errors.
3536 *********************************************************************/
3537 static void initialize_mutexes(void)
3539 #ifdef MUTEX_LOCKS_AVAILABLE
3541 * Prepare global mutex semaphores
3543 privoxy_mutex_init(&log_mutex);
3544 privoxy_mutex_init(&log_init_mutex);
3545 privoxy_mutex_init(&connection_reuse_mutex);
3546 #ifdef FEATURE_EXTERNAL_FILTERS
3547 privoxy_mutex_init(&external_filter_mutex);
3549 #ifdef FEATURE_CLIENT_TAGS
3550 privoxy_mutex_init(&client_tags_mutex);
3554 * XXX: The assumptions below are a bit naive
3555 * and can cause locks that aren't necessary.
3557 * For example older FreeBSD versions (< 6.x?)
3558 * have no gethostbyname_r, but gethostbyname is
3561 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3562 privoxy_mutex_init(&resolver_mutex);
3563 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3565 * XXX: should we use a single mutex for
3566 * localtime() and gmtime() as well?
3568 #ifndef HAVE_GMTIME_R
3569 privoxy_mutex_init(&gmtime_mutex);
3570 #endif /* ndef HAVE_GMTIME_R */
3572 #ifndef HAVE_LOCALTIME_R
3573 privoxy_mutex_init(&localtime_mutex);
3574 #endif /* ndef HAVE_GMTIME_R */
3576 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
3577 privoxy_mutex_init(&rand_mutex);
3578 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
3580 #endif /* def MUTEX_LOCKS_AVAILABLE */
3583 /*********************************************************************
3587 * Description : Load the config file and start the listen loop.
3588 * This function is a lot more *sane* with the `load_config'
3589 * and `listen_loop' functions; although it stills does
3590 * a *little* too much for my taste.
3593 * 1 : argc = Number of parameters (including $0).
3594 * 2 : argv = Array of (char *)'s to the parameters.
3596 * Returns : 1 if : can't open config file, unrecognized directive,
3597 * stats requested in multi-thread mode, can't open the
3598 * log file, can't open the jar file, listen port is invalid,
3599 * any load fails, and can't bind port.
3601 * Else main never returns, the process must be signaled
3602 * to terminate execution. Or, on Windows, use the
3603 * "File", "Exit" menu option.
3605 *********************************************************************/
3607 int real_main(int argc, char **argv)
3609 int main(int argc, char **argv)
3613 int do_config_test = 0;
3614 #ifndef HAVE_ARC4RANDOM
3615 unsigned int random_seed;
3618 struct passwd *pw = NULL;
3619 struct group *grp = NULL;
3621 char *pre_chroot_nslookup_to_load_resolver = NULL;
3624 char *fuzz_input_type = NULL;
3625 char *fuzz_input_file = NULL;
3632 #if !defined(_WIN32)
3639 /* Prepare mutexes if supported and necessary. */
3640 initialize_mutexes();
3642 /* Enable logging until further notice. */
3646 * Parse the command line arguments
3648 * XXX: simply printing usage information in case of
3649 * invalid arguments isn't particularly user friendly.
3651 while (++argc_pos < argc)
3654 /* Check to see if the service must be installed or uninstalled */
3655 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3657 const char *pName = argv[argc_pos] + 9;
3660 exit((install_service(pName)) ? 0 : 1);
3662 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3664 const char *pName = argv[argc_pos] + 11;
3667 exit((uninstall_service(pName)) ? 0 : 1);
3669 else if (strcmp(argv[argc_pos], "--service") == 0)
3671 bRunAsService = TRUE;
3672 w32_set_service_cwd();
3673 atexit(w32_service_exit_notify);
3676 #endif /* defined(_WIN32) */
3679 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3681 if (strcmp(argv[argc_pos], "--help") == 0)
3686 else if (strcmp(argv[argc_pos], "--version") == 0)
3688 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3694 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3696 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3700 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3702 if (++argc_pos == argc) usage(argv[0]);
3703 pidfile = strdup_or_die(argv[argc_pos]);
3706 else if (strcmp(argv[argc_pos], "--user") == 0)
3711 if (++argc_pos == argc) usage(argv[argc_pos]);
3713 user_arg = strdup_or_die(argv[argc_pos]);
3714 group_name = strchr(user_arg, '.');
3715 if (NULL != group_name)
3717 /* Nul-terminate the user name */
3720 /* Skip the former delimiter to actually reach the group name */
3723 grp = getgrnam(group_name);
3726 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3729 pw = getpwnam(user_arg);
3732 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3738 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3740 if (++argc_pos == argc) usage(argv[0]);
3741 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3744 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3748 #endif /* defined(unix) */
3750 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3755 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
3758 if (argc < argc_pos + 2) usage(argv[0]);
3759 fuzz_input_type = argv[argc_pos];
3761 fuzz_input_file = argv[argc_pos];
3763 else if (strcmp(argv[argc_pos], "--stfu") == 0)
3765 set_debug_level(LOG_LEVEL_STFU);
3768 else if (argc_pos + 1 != argc)
3771 * This is neither the last command line
3772 * option, nor was it recognized before,
3773 * therefore it must be invalid.
3779 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3781 configfile = argv[argc_pos];
3784 } /* -END- while (more arguments) */
3786 show_version(Argv[0]);
3789 if (*configfile != '/')
3791 char cwd[BUFFER_SIZE];
3793 size_t abs_file_size;
3795 /* make config-filename absolute here */
3796 if (NULL == getcwd(cwd, sizeof(cwd)))
3798 perror("failed to get current working directory");
3802 basedir = strdup_or_die(cwd);
3804 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3805 abs_file = malloc_or_die(abs_file_size);
3806 strlcpy(abs_file, basedir, abs_file_size);
3807 strlcat(abs_file, "/", abs_file_size);
3808 strlcat(abs_file, configfile, abs_file_size);
3809 configfile = abs_file;
3811 #endif /* defined unix */
3815 clients->next = NULL;
3817 /* XXX: factor out initialising after the next stable release. */
3820 #elif defined(_WIN32)
3824 #ifndef HAVE_ARC4RANDOM
3825 random_seed = (unsigned int)time(NULL);
3827 srandom(random_seed);
3830 #endif /* ifdef HAVE_RANDOM */
3831 #endif /* ifndef HAVE_ARC4RANDOM */
3834 * Unix signal handling
3836 * Catch the abort, interrupt and terminate signals for a graceful exit
3837 * Catch the hangup signal so the errlog can be reopened.
3839 * Ignore the broken pipe signal as connection failures
3840 * are handled when and where they occur without relying
3843 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3846 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3848 for (idx = 0; idx < SZ(catched_signals); idx++)
3850 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3851 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3853 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3854 #endif /* ifdef sun */
3856 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3860 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3862 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3866 #else /* ifdef _WIN32 */
3867 # ifdef _WIN_CONSOLE
3869 * We *are* in a windows console app.
3870 * Print a verbose messages about FAQ's and such
3872 printf("%s", win32_blurb);
3873 # endif /* def _WIN_CONSOLE */
3874 #endif /* def _WIN32 */
3877 if (fuzz_input_type != NULL)
3879 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
3881 log_error(LOG_LEVEL_FATAL,
3882 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
3883 "Various data structures are static which is unsafe when using threads.");
3888 exit(NULL == load_config());
3891 /* Initialize the CGI subsystem */
3892 cgi_init_error_messages();
3895 * If running on unix and without the --no-daemon
3896 * option, become a daemon. I.e. fork, detach
3897 * from tty and get process group leadership
3906 if (pid < 0) /* error */
3911 else if (pid != 0) /* parent */
3916 * must check for errors
3917 * child died due to missing files aso
3920 wpid = waitpid(pid, &status, WNOHANG);
3932 * stderr (fd 2) will be closed later on,
3933 * when the config file has been parsed.
3939 * Reserve fd 0 and 1 to prevent abort() and friends
3940 * from sending stuff to the clients or servers.
3942 fd = open("/dev/null", O_RDONLY);
3945 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3949 if (dup2(fd, 0) == -1)
3951 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3955 fd = open("/dev/null", O_WRONLY);
3958 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3962 if (dup2(fd, 1) == -1)
3964 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3969 #ifdef FEATURE_EXTERNAL_FILTERS
3970 for (fd = 0; fd < 3; fd++)
3972 mark_socket_for_close_on_execute(fd);
3978 } /* -END- if (daemon_mode) */
3981 * As soon as we have written the PID file, we can switch
3982 * to the user and group ID indicated by the --user option
3984 if (pidfile != NULL)
3986 write_pid_file(pidfile);
3990 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3992 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3996 if (setgroups(1, &grp->gr_gid))
3998 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
4001 else if (initgroups(pw->pw_name, pw->pw_gid))
4003 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
4009 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
4011 /* Read the time zone file from /etc before doing chroot. */
4013 if (NULL != pre_chroot_nslookup_to_load_resolver
4014 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
4016 /* Initialize resolver library. */
4017 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
4019 if (chroot(pw->pw_dir) < 0)
4021 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
4025 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
4028 if (setuid(pw->pw_uid))
4030 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
4034 char putenv_dummy[64];
4036 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
4037 if (putenv(putenv_dummy) != 0)
4039 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
4042 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
4043 if (putenv(putenv_dummy) != 0)
4045 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
4051 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
4054 #endif /* defined unix */
4057 /* This will be FALSE unless the command line specified --service
4061 /* Yup, so now we must attempt to establish a connection
4062 * with the service dispatcher. This will only work if this
4063 * process was launched by the service control manager to
4064 * actually run as a service. If this isn't the case, i've
4065 * known it take around 30 seconds or so for the call to return.
4068 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
4069 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
4071 /* Service has run, and at this point is now being stopped, so just return */
4076 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
4078 /* An error occurred. Usually it's because --service was wrongly specified
4079 * and we were unable to connect to the Service Control Dispatcher because
4080 * it wasn't expecting us and is therefore not listening.
4082 * For now, just continue below to call the listen_loop function.
4085 #endif /* def _WIN32 */
4095 /*********************************************************************
4097 * Function : bind_port_helper
4099 * Description : Bind the listen port. Handles logging, and aborts
4103 * 1 : haddr = Host address to bind to. Use NULL to bind to
4105 * 2 : hport = Specifies port to bind to.
4106 * 3 : backlog = Listen backlog.
4108 * Returns : Port that was opened.
4110 *********************************************************************/
4111 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
4116 result = bind_port(haddr, hport, backlog, &bfd);
4120 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
4124 log_error(LOG_LEVEL_FATAL,
4125 "can't bind to %s:%d: There may be another Privoxy "
4126 "or some other proxy running on port %d",
4127 bind_address, hport, hport);
4130 log_error(LOG_LEVEL_FATAL,
4131 "can't bind to %s:%d: The hostname is not resolvable",
4132 bind_address, hport);
4135 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
4136 bind_address, hport);
4139 /* shouldn't get here */
4140 return JB_INVALID_SOCKET;
4145 if (bfd >= FD_SETSIZE)
4147 log_error(LOG_LEVEL_FATAL,
4148 "Bind socket number too high to use select(): %d >= %d",
4156 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
4161 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
4169 /*********************************************************************
4171 * Function : bind_ports_helper
4173 * Description : Bind the listen ports. Handles logging, and aborts
4177 * 1 : config = Privoxy configuration. Specifies ports
4179 * 2 : sockets = Preallocated array of opened sockets
4180 * corresponding to specification in config.
4181 * All non-opened sockets will be set to
4182 * JB_INVALID_SOCKET.
4184 * Returns : Nothing. Inspect sockets argument.
4186 *********************************************************************/
4187 static void bind_ports_helper(struct configuration_spec * config,
4188 jb_socket sockets[])
4192 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4194 if (config->hport[i])
4196 sockets[i] = bind_port_helper(config->haddr[i],
4197 config->hport[i], config->listen_backlog);
4198 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
4199 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
4201 struct accept_filter_arg af_options;
4202 bzero(&af_options, sizeof(af_options));
4203 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
4204 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
4205 sizeof(af_options)))
4207 log_error(LOG_LEVEL_ERROR,
4208 "Enabling accept filter for socket %d failed: %E", sockets[i]);
4215 sockets[i] = JB_INVALID_SOCKET;
4218 config->need_bind = 0;
4222 /*********************************************************************
4224 * Function : close_ports_helper
4226 * Description : Close listenings ports.
4229 * 1 : sockets = Array of opened and non-opened sockets to
4230 * close. All sockets will be set to
4231 * JB_INVALID_SOCKET.
4233 * Returns : Nothing.
4235 *********************************************************************/
4236 static void close_ports_helper(jb_socket sockets[])
4240 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4242 if (JB_INVALID_SOCKET != sockets[i])
4244 close_socket(sockets[i]);
4246 sockets[i] = JB_INVALID_SOCKET;
4252 /* Without this simple workaround we get this compiler warning from _beginthread
4253 * warning C4028: formal parameter 1 different from declaration
4255 void w32_service_listen_loop(void *p)
4259 #endif /* def _WIN32 */
4262 /*********************************************************************
4264 * Function : listen_loop
4266 * Description : bind the listen port and enter a "FOREVER" listening loop.
4272 *********************************************************************/
4273 static void listen_loop(void)
4275 struct client_states *csp_list = NULL;
4276 struct client_state *csp = NULL;
4277 jb_socket bfds[MAX_LISTENING_SOCKETS];
4278 struct configuration_spec *config;
4279 unsigned int active_threads = 0;
4280 #if defined(FEATURE_PTHREAD)
4281 pthread_attr_t attrs;
4283 pthread_attr_init(&attrs);
4284 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4287 config = load_config();
4289 #ifdef FEATURE_CONNECTION_SHARING
4291 * XXX: Should be relocated once it no
4292 * longer needs to emit log messages.
4294 initialize_reusable_connections();
4295 #endif /* def FEATURE_CONNECTION_SHARING */
4297 bind_ports_helper(config, bfds);
4299 #ifdef FEATURE_GRACEFUL_TERMINATION
4300 while (!g_terminate)
4305 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
4306 while (waitpid(-1, NULL, WNOHANG) > 0)
4308 /* zombie children */
4310 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
4313 * Free data that was used by died threads
4315 active_threads = sweep();
4319 * Re-open the errlog after HUP signal
4321 if (received_hup_signal)
4323 if (NULL != config->logfile)
4325 init_error_log(Argv[0], config->logfile);
4327 received_hup_signal = 0;
4331 csp_list = zalloc_or_die(sizeof(*csp_list));
4332 csp = &csp_list->csp;
4334 log_error(LOG_LEVEL_CONNECT,
4335 "Waiting for the next client connection. Currently active threads: %d",
4339 * This config may be outdated, but for accept_connection()
4340 * it's fresh enough.
4342 csp->config = config;
4344 if (!accept_connection(csp, bfds))
4346 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
4358 csp->flags |= CSP_FLAG_ACTIVE;
4359 csp->server_connection.sfd = JB_INVALID_SOCKET;
4361 csp->config = config = load_config();
4363 if (config->need_bind)
4366 * Since we were listening to the "old port", we will not see
4367 * a "listen" param change until the next request. So, at
4368 * least 1 more request must be made for us to find the new
4369 * setting. I am simply closing the old socket and binding the
4372 * Which-ever is correct, we will serve 1 more page via the
4373 * old settings. This should probably be a "show-status"
4374 * request. This should not be a so common of an operation
4375 * that this will hurt people's feelings.
4378 close_ports_helper(bfds);
4380 bind_ports_helper(config, bfds);
4383 #ifdef FEATURE_TOGGLE
4384 if (global_toggle_state)
4385 #endif /* def FEATURE_TOGGLE */
4387 csp->flags |= CSP_FLAG_TOGGLED_ON;
4390 if (run_loader(csp))
4392 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
4393 /* Never get here - LOG_LEVEL_FATAL causes program exit */
4397 if (block_acl(NULL,csp))
4399 log_error(LOG_LEVEL_CONNECT,
4400 "Connection from %s on %s (socket %d) dropped due to ACL",
4401 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
4402 close_socket(csp->cfd);
4403 freez(csp->ip_addr_str);
4404 freez(csp->listen_addr_str);
4408 #endif /* def FEATURE_ACL */
4410 if ((0 != config->max_client_connections)
4411 && (active_threads >= config->max_client_connections))
4413 log_error(LOG_LEVEL_CONNECT,
4414 "Rejecting connection from %s. Maximum number of connections reached.",
4416 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4417 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4418 close_socket(csp->cfd);
4419 freez(csp->ip_addr_str);
4420 freez(csp->listen_addr_str);
4425 /* add it to the list of clients */
4426 csp_list->next = clients->next;
4427 clients->next = csp_list;
4429 if (config->multi_threaded)
4433 /* this is a switch () statement in the C preprocessor - ugh */
4434 #undef SELECTED_ONE_OPTION
4436 /* Use Pthreads in preference to native code */
4437 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
4438 #define SELECTED_ONE_OPTION
4440 pthread_t the_thread;
4442 errno = pthread_create(&the_thread, &attrs,
4443 (void * (*)(void *))serve, csp);
4444 child_id = errno ? -1 : 0;
4448 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
4449 #define SELECTED_ONE_OPTION
4450 child_id = _beginthread(
4451 (void (*)(void *))serve,
4456 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
4457 #define SELECTED_ONE_OPTION
4458 child_id = _beginthread(
4459 (void(* _Optlink)(void*))serve,
4465 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
4466 #define SELECTED_ONE_OPTION
4468 thread_id tid = spawn_thread
4469 (server_thread, "server", B_NORMAL_PRIORITY, csp);
4471 if ((tid >= 0) && (resume_thread(tid) == B_OK))
4473 child_id = (int) tid;
4482 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
4483 #define SELECTED_ONE_OPTION
4484 csp->cfd = ReleaseSocket(csp->cfd, -1);
4487 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4488 NP_Output, Output(),
4489 NP_CloseOutput, FALSE,
4490 NP_Name, (ULONG)"privoxy child",
4494 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4495 NP_Output, Output(),
4496 NP_CloseOutput, FALSE,
4497 NP_Name, (ULONG)"privoxy child",
4498 NP_StackSize, 200*1024,
4504 ((struct Task *)child_id)->tc_UserData = csp;
4505 Signal((struct Task *)child_id, SIGF_SINGLE);
4510 #if !defined(SELECTED_ONE_OPTION)
4513 /* This block is only needed when using fork().
4514 * When using threads, the server thread was
4515 * created and run by the call to _beginthread().
4517 if (child_id == 0) /* child */
4520 #ifdef FEATURE_TOGGLE
4521 int inherited_toggle_state = global_toggle_state;
4522 #endif /* def FEATURE_TOGGLE */
4527 * If we've been toggled or we've blocked the request, tell Mom
4530 #ifdef FEATURE_TOGGLE
4531 if (inherited_toggle_state != global_toggle_state)
4533 rc |= RC_FLAG_TOGGLED;
4535 #endif /* def FEATURE_TOGGLE */
4537 #ifdef FEATURE_STATISTICS
4538 if (csp->flags & CSP_FLAG_REJECTED)
4540 rc |= RC_FLAG_BLOCKED;
4542 #endif /* ndef FEATURE_STATISTICS */
4546 else if (child_id > 0) /* parent */
4548 /* in a fork()'d environment, the parent's
4549 * copy of the client socket and the CSP
4553 #if !defined(_WIN32) && !defined(__CYGWIN__)
4555 wait(&child_status);
4558 * Evaluate child's return code: If the child has
4559 * - been toggled, toggle ourselves
4560 * - blocked its request, bump up the stats counter
4563 #ifdef FEATURE_TOGGLE
4564 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4566 global_toggle_state = !global_toggle_state;
4568 #endif /* def FEATURE_TOGGLE */
4570 #ifdef FEATURE_STATISTICS
4572 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4576 #endif /* def FEATURE_STATISTICS */
4578 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4579 close_socket(csp->cfd);
4580 csp->flags &= ~CSP_FLAG_ACTIVE;
4584 #undef SELECTED_ONE_OPTION
4585 /* end of cpp switch () */
4590 * Spawning the child failed, assume it's because
4591 * there are too many children running already.
4592 * XXX: If you assume ...
4594 log_error(LOG_LEVEL_ERROR,
4595 "Unable to take any additional connections: %E. Active threads: %d",
4597 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4598 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4599 close_socket(csp->cfd);
4600 csp->flags &= ~CSP_FLAG_ACTIVE;
4609 #if defined(FEATURE_PTHREAD)
4610 pthread_attr_destroy(&attrs);
4613 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4615 /* Clean up. Aim: free all memory (no leaks) */
4616 #ifdef FEATURE_GRACEFUL_TERMINATION
4618 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4620 unload_current_config_file();
4621 unload_current_actions_file();
4622 unload_current_re_filterfile();
4623 #ifdef FEATURE_TRUST
4624 unload_current_trust_file();
4627 if (config->multi_threaded)
4634 } while ((clients->next != NULL) && (--i > 0));
4638 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4648 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4649 /* Cleanup - remove taskbar icon etc. */
4654 #endif /* FEATURE_GRACEFUL_TERMINATION */