1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
5 * Purpose : Main file. Contains main() method, main loop, and
6 * the main connection-handling function.
8 * Copyright : Written by and Copyright (C) 2001-2017 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 # ifndef FEATURE_PTHREAD
52 # include <winsock2.h>
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
65 # if !defined (__OS2__)
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
74 #include <sys/termios.h>
85 # include <socket.h> /* BeOS has select() for sockets only. */
86 # include <OS.h> /* declarations for threads and stuff. */
89 # if defined(__EMX__) || defined(__OS2__)
90 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
102 #endif /* def __GLIBC__ */
107 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
108 #endif /* HAVE_POLL */
118 #include "miscutil.h"
120 #include "jbsockets.h"
125 #include "urlmatch.h"
126 #ifdef FEATURE_CLIENT_TAGS
127 #include "client-tags.h"
131 struct client_states clients[1];
132 struct file_list files[1];
134 #ifdef FEATURE_STATISTICS
135 int urls_read = 0; /* total nr of urls read inc rejected */
136 int urls_rejected = 0; /* total nr of urls rejected */
137 #endif /* def FEATURE_STATISTICS */
139 #ifdef FEATURE_GRACEFUL_TERMINATION
143 #if !defined(_WIN32) && !defined(__OS2__)
144 static void sig_handler(int the_signal);
146 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
147 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
148 static jb_err get_server_headers(struct client_state *csp);
149 static const char *crunch_reason(const struct http_response *rsp);
150 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
151 static char *get_request_line(struct client_state *csp);
152 static jb_err receive_client_request(struct client_state *csp);
153 static jb_err parse_client_request(struct client_state *csp);
154 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
155 static jb_err change_request_destination(struct client_state *csp);
156 static void chat(struct client_state *csp);
157 static void serve(struct client_state *csp);
158 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
159 static void usage(const char *myname);
161 static void initialize_mutexes(void);
162 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
163 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
164 static void close_ports_helper(jb_socket sockets[]);
165 static void listen_loop(void);
166 static void serve(struct client_state *csp);
169 static int32 server_thread(void *data);
170 #endif /* def __BEOS__ */
173 #define sleep(N) Sleep(((N) * 1000))
177 #define sleep(N) DosSleep(((N) * 100))
181 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
182 void show_fuzz_usage(const char *name);
185 #ifdef MUTEX_LOCKS_AVAILABLE
187 * XXX: Does the locking stuff really belong in this file?
189 privoxy_mutex_t log_mutex;
190 privoxy_mutex_t log_init_mutex;
191 privoxy_mutex_t connection_reuse_mutex;
193 #ifdef FEATURE_EXTERNAL_FILTERS
194 privoxy_mutex_t external_filter_mutex;
196 #ifdef FEATURE_CLIENT_TAGS
197 privoxy_mutex_t client_tags_mutex;
200 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
201 privoxy_mutex_t resolver_mutex;
202 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
204 #ifndef HAVE_GMTIME_R
205 privoxy_mutex_t gmtime_mutex;
206 #endif /* ndef HAVE_GMTIME_R */
208 #ifndef HAVE_LOCALTIME_R
209 privoxy_mutex_t localtime_mutex;
210 #endif /* ndef HAVE_GMTIME_R */
212 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
213 privoxy_mutex_t rand_mutex;
214 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
216 #endif /* def MUTEX_LOCKS_AVAILABLE */
219 const char *basedir = NULL;
220 const char *pidfile = NULL;
221 static int received_hup_signal = 0;
222 #endif /* defined unix */
224 /* HTTP snipplets. */
225 static const char CSUCCEED[] =
226 "HTTP/1.1 200 Connection established\r\n\r\n";
228 static const char CHEADER[] =
229 "HTTP/1.1 400 Invalid header received from client\r\n"
230 "Content-Type: text/plain\r\n"
231 "Connection: close\r\n\r\n"
232 "Invalid header received from client.\r\n";
234 static const char FTP_RESPONSE[] =
235 "HTTP/1.1 400 Invalid request received from client\r\n"
236 "Content-Type: text/plain\r\n"
237 "Connection: close\r\n\r\n"
238 "Invalid request. Privoxy doesn't support FTP.\r\n";
240 static const char GOPHER_RESPONSE[] =
241 "HTTP/1.1 400 Invalid request received from client\r\n"
242 "Content-Type: text/plain\r\n"
243 "Connection: close\r\n\r\n"
244 "Invalid request. Privoxy doesn't support gopher.\r\n";
246 /* XXX: should be a template */
247 static const char MISSING_DESTINATION_RESPONSE[] =
248 "HTTP/1.1 400 Bad request received from client\r\n"
249 "Content-Type: text/plain\r\n"
250 "Connection: close\r\n\r\n"
251 "Bad request. Privoxy was unable to extract the destination.\r\n";
253 /* XXX: should be a template */
254 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
255 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
256 "Content-Type: text/plain\r\n"
257 "Connection: close\r\n\r\n"
258 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
260 /* XXX: should be a template */
261 static const char MESSED_UP_REQUEST_RESPONSE[] =
262 "HTTP/1.1 400 Malformed request after rewriting\r\n"
263 "Content-Type: text/plain\r\n"
264 "Connection: close\r\n\r\n"
265 "Bad request. Messed up with header filters.\r\n";
267 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
268 "HTTP/1.1 503 Too many open connections\r\n"
269 "Content-Type: text/plain\r\n"
270 "Connection: close\r\n\r\n"
271 "Maximum number of open connections reached.\r\n";
273 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
274 "HTTP/1.1 504 Connection timeout\r\n"
275 "Content-Type: text/plain\r\n"
276 "Connection: close\r\n\r\n"
277 "The connection timed out because the client request didn't arrive in time.\r\n";
279 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
280 "HTTP/1.1 400 Failed reading client body\r\n"
281 "Content-Type: text/plain\r\n"
282 "Connection: close\r\n\r\n"
283 "Failed parsing or buffering the chunk-encoded client body.\r\n";
285 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
286 "HTTP/1.1 417 Expecting too much\r\n"
287 "Content-Type: text/plain\r\n"
288 "Connection: close\r\n\r\n"
289 "Privoxy detected an unsupported Expect header value.\r\n";
291 /* A function to crunch a response */
292 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
294 /* Crunch function flags */
295 #define CF_NO_FLAGS 0
296 /* Cruncher applies to forced requests as well */
297 #define CF_IGNORE_FORCE 1
298 /* Crunched requests are counted for the block statistics */
299 #define CF_COUNT_AS_REJECT 2
301 /* A crunch function and its flags */
304 const crunch_func_ptr cruncher;
308 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
310 /* Complete list of cruncher functions */
311 static const struct cruncher crunchers_all[] = {
312 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
313 { block_url, CF_COUNT_AS_REJECT },
315 { trust_url, CF_COUNT_AS_REJECT },
316 #endif /* def FEATURE_TRUST */
317 { redirect_url, CF_NO_FLAGS },
318 { dispatch_cgi, CF_IGNORE_FORCE},
322 /* Light version, used after tags are applied */
323 static const struct cruncher crunchers_light[] = {
324 { block_url, CF_COUNT_AS_REJECT },
325 { redirect_url, CF_NO_FLAGS },
331 * XXX: Don't we really mean
337 #if !defined(_WIN32) && !defined(__OS2__)
338 /*********************************************************************
340 * Function : sig_handler
342 * Description : Signal handler for different signals.
343 * Exit gracefully on TERM and INT
344 * or set a flag that will cause the errlog
345 * to be reopened by the main thread on HUP.
348 * 1 : the_signal = the signal cause this function to call
352 *********************************************************************/
353 static void sig_handler(int the_signal)
359 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
371 received_hup_signal = 1;
377 * We shouldn't be here, unless we catch signals
378 * in main() that we can't handle here!
380 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
388 /*********************************************************************
390 * Function : get_write_delay
392 * Description : Parse the delay-response parameter.
395 * 1 : csp = Current client state (buffers, headers, etc...)
397 * Returns : Number of milliseconds to delay writes.
399 *********************************************************************/
400 static unsigned int get_write_delay(const struct client_state *csp)
406 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
410 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
412 delay = (unsigned)strtol(newval, &endptr, 0);
415 log_error(LOG_LEVEL_FATAL,
416 "Invalid delay-response{} parameter: '%s'", newval);
424 /*********************************************************************
426 * Function : client_protocol_is_unsupported
428 * Description : Checks if the client used a known unsupported
429 * protocol and deals with it by sending an error
433 * 1 : csp = Current client state (buffers, headers, etc...)
434 * 2 : req = the first request line send by the client
436 * Returns : TRUE if an error response has been generated, or
437 * FALSE if the request doesn't look invalid.
439 *********************************************************************/
440 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
443 * If it's a FTP or gopher request, we don't support it.
445 * These checks are better than nothing, but they might
446 * not work in all configurations and some clients might
447 * have problems digesting the answer.
449 * They should, however, never cause more problems than
450 * Privoxy's old behaviour (returning the misleading HTML
453 * "Could not resolve http://(ftp|gopher)://example.org").
455 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
457 const char *response = NULL;
458 const char *protocol = NULL;
460 if (!strncmpic(req, "GET ftp://", 10))
462 response = FTP_RESPONSE;
467 response = GOPHER_RESPONSE;
470 log_error(LOG_LEVEL_ERROR,
471 "%s tried to use Privoxy as %s proxy: %s",
472 csp->ip_addr_str, protocol, req);
473 log_error(LOG_LEVEL_CLF,
474 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
476 write_socket_delayed(csp->cfd, response, strlen(response),
477 get_write_delay(csp));
486 /*********************************************************************
488 * Function : client_has_unsupported_expectations
490 * Description : Checks if the client used an unsupported expectation
491 * in which case an error message is delivered.
494 * 1 : csp = Current client state (buffers, headers, etc...)
496 * Returns : TRUE if an error response has been generated, or
497 * FALSE if the request doesn't look invalid.
499 *********************************************************************/
500 static int client_has_unsupported_expectations(const struct client_state *csp)
502 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
504 log_error(LOG_LEVEL_ERROR,
505 "Rejecting request from client %s with unsupported Expect header value",
507 log_error(LOG_LEVEL_CLF,
508 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
509 write_socket_delayed(csp->cfd,
510 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
511 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
512 get_write_delay(csp));
522 /*********************************************************************
524 * Function : get_request_destination_elsewhere
526 * Description : If the client's request was redirected into
527 * Privoxy without the client's knowledge,
528 * the request line lacks the destination host.
530 * This function tries to get it elsewhere,
531 * provided accept-intercepted-requests is enabled.
533 * "Elsewhere" currently only means "Host: header",
534 * but in the future we may ask the redirecting
535 * packet filter to look the destination up.
537 * If the destination stays unknown, an error
538 * response is send to the client and headers
539 * are freed so that chat() can return directly.
542 * 1 : csp = Current client state (buffers, headers, etc...)
543 * 2 : headers = a header list
545 * Returns : JB_ERR_OK if the destination is now known, or
546 * JB_ERR_PARSE if it isn't.
548 *********************************************************************/
549 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
553 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
555 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
556 " Privoxy isn't configured to accept intercepted requests.",
557 csp->ip_addr_str, csp->http->cmd);
558 /* XXX: Use correct size */
559 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
560 csp->ip_addr_str, csp->http->cmd);
562 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
563 get_write_delay(csp));
564 destroy_list(headers);
568 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
570 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
571 /* Split the domain we just got for pattern matching */
572 init_domain_components(csp->http);
579 /* We can't work without destination. Go spread the news.*/
581 req = list_to_text(headers);
583 /* XXX: Use correct size */
584 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
585 csp->ip_addr_str, csp->http->cmd);
586 log_error(LOG_LEVEL_ERROR,
587 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
588 csp->ip_addr_str, csp->http->cmd, req);
591 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
592 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
593 destroy_list(headers);
598 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
599 * to get the destination IP address, use it as host directly
600 * or do a reverse DNS lookup first.
605 /*********************************************************************
607 * Function : get_server_headers
609 * Description : Parses server headers in iob and fills them
610 * into csp->headers so that they can later be
614 * 1 : csp = Current client state (buffers, headers, etc...)
616 * Returns : JB_ERR_OK if everything went fine, or
617 * JB_ERR_PARSE if the headers were incomplete.
619 *********************************************************************/
620 static jb_err get_server_headers(struct client_state *csp)
622 int continue_hack_in_da_house = 0;
625 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
630 * continue hack in da house. Ignore the ending of
631 * this head and continue enlisting header lines.
632 * The reason is described below.
634 enlist(csp->headers, "");
635 continue_hack_in_da_house = 0;
638 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
641 * It's a bodyless continue response, don't
642 * stop header parsing after reaching its end.
644 * As a result Privoxy will concatenate the
645 * next response's head and parse and deliver
646 * the headers as if they belonged to one request.
648 * The client will separate them because of the
649 * empty line between them.
651 * XXX: What we're doing here is clearly against
652 * the intended purpose of the continue header,
653 * and under some conditions (HTTP/1.0 client request)
654 * it's a standard violation.
656 * Anyway, "sort of against the spec" is preferable
657 * to "always getting confused by Continue responses"
658 * (Privoxy's behaviour before this hack was added)
660 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
661 continue_hack_in_da_house = 1;
663 else if (*header == '\0')
666 * If the header is empty, but the Continue hack
667 * isn't active, we can assume that we reached the
668 * end of the buffer before we hit the end of the
671 * Inform the caller an let it decide how to handle it.
676 if (JB_ERR_MEMORY == enlist(csp->headers, header))
679 * XXX: Should we quit the request and return a
680 * out of memory error page instead?
682 log_error(LOG_LEVEL_ERROR,
683 "Out of memory while enlisting server headers. %s lost.",
693 /*********************************************************************
695 * Function : crunch_reason
697 * Description : Translates the crunch reason code into a string.
700 * 1 : rsp = a http_response
702 * Returns : A string with the crunch reason or an error description.
704 *********************************************************************/
705 static const char *crunch_reason(const struct http_response *rsp)
707 char * reason = NULL;
712 return "Internal error while searching for crunch reason";
715 switch (rsp->crunch_reason)
718 reason = "Unsupported HTTP feature";
724 reason = "Untrusted";
727 reason = "Redirected";
733 reason = "DNS failure";
735 case FORWARDING_FAILED:
736 reason = "Forwarding failed";
739 reason = "Connection failure";
742 reason = "Out of memory (may mask other reasons)";
744 case CONNECTION_TIMEOUT:
745 reason = "Connection timeout";
748 reason = "No server data received";
751 reason = "No reason recorded";
759 /*********************************************************************
761 * Function : log_applied_actions
763 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
767 * 1 : actions = Current action spec to log
771 *********************************************************************/
772 static void log_applied_actions(const struct current_action_spec *actions)
775 * The conversion to text requires lots of memory allocations so
776 * we only do the conversion if the user is actually interested.
778 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
780 char *actions_as_text = actions_to_line_of_text(actions);
781 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
782 freez(actions_as_text);
787 /*********************************************************************
789 * Function : send_crunch_response
791 * Description : Delivers already prepared response for
792 * intercepted requests, logs the interception
793 * and frees the response.
796 * 1 : csp = Current client state (buffers, headers, etc...)
797 * 2 : rsp = Fully prepared response. Will be freed on exit.
801 *********************************************************************/
802 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
804 const struct http_request *http = csp->http;
808 assert(rsp->head != NULL);
812 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
816 * Extract the status code from the actual head
817 * that will be send to the client. It is the only
818 * way to get it right for all requests, including
819 * the fixed ones for out-of-memory problems.
821 * A head starts like this: 'HTTP/1.1 200...'
825 status_code[0] = rsp->head[9];
826 status_code[1] = rsp->head[10];
827 status_code[2] = rsp->head[11];
828 status_code[3] = '\0';
830 /* Log that the request was crunched and why. */
831 log_applied_actions(csp->action);
832 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
833 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
834 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
836 /* Write the answer to the client */
837 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length, get_write_delay(csp))
838 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length, get_write_delay(csp)))
840 /* There is nothing we can do about it. */
841 log_error(LOG_LEVEL_ERROR,
842 "Couldn't deliver the error message through client socket %d: %E",
846 /* Clean up and return */
847 if (cgi_error_memory() != rsp)
849 free_http_response(rsp);
855 /*********************************************************************
857 * Function : crunch_response_triggered
859 * Description : Checks if the request has to be crunched,
860 * and delivers the crunch response if necessary.
863 * 1 : csp = Current client state (buffers, headers, etc...)
864 * 2 : crunchers = list of cruncher functions to run
866 * Returns : TRUE if the request was answered with a crunch response
869 *********************************************************************/
870 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
872 struct http_response *rsp = NULL;
873 const struct cruncher *c;
876 * If CGI request crunching is disabled,
877 * check the CGI dispatcher out of order to
878 * prevent unintentional blocks or redirects.
880 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
881 && (NULL != (rsp = dispatch_cgi(csp))))
883 /* Deliver, log and free the interception response. */
884 send_crunch_response(csp, rsp);
885 csp->flags |= CSP_FLAG_CRUNCHED;
889 for (c = crunchers; c->cruncher != NULL; c++)
892 * Check the cruncher if either Privoxy is toggled
893 * on and the request isn't forced, or if the cruncher
894 * applies to forced requests as well.
896 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
897 !(csp->flags & CSP_FLAG_FORCED)) ||
898 (c->flags & CF_IGNORE_FORCE))
900 rsp = c->cruncher(csp);
903 /* Deliver, log and free the interception response. */
904 send_crunch_response(csp, rsp);
905 csp->flags |= CSP_FLAG_CRUNCHED;
906 #ifdef FEATURE_STATISTICS
907 if (c->flags & CF_COUNT_AS_REJECT)
909 csp->flags |= CSP_FLAG_REJECTED;
911 #endif /* def FEATURE_STATISTICS */
922 /*********************************************************************
924 * Function : build_request_line
926 * Description : Builds the HTTP request line.
928 * If a HTTP forwarder is used it expects the whole URL,
929 * web servers only get the path.
932 * 1 : csp = Current client state (buffers, headers, etc...)
933 * 2 : fwd = The forwarding spec used for the request
934 * XXX: Should use http->fwd instead.
935 * 3 : request_line = The old request line which will be replaced.
937 * Returns : Nothing. Terminates in case of memory problems.
939 *********************************************************************/
940 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
942 struct http_request *http = csp->http;
944 assert(http->ssl == 0);
947 * Downgrade http version from 1.1 to 1.0
948 * if +downgrade action applies.
950 if ((csp->action->flags & ACTION_DOWNGRADE)
951 && (!strcmpic(http->ver, "HTTP/1.1")))
954 http->ver = strdup_or_die("HTTP/1.0");
958 * Rebuild the request line.
960 freez(*request_line);
961 *request_line = strdup(http->gpc);
962 string_append(request_line, " ");
964 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
966 string_append(request_line, http->url);
970 string_append(request_line, http->path);
972 string_append(request_line, " ");
973 string_append(request_line, http->ver);
975 if (*request_line == NULL)
977 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
979 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
983 /*********************************************************************
985 * Function : change_request_destination
987 * Description : Parse a (rewritten) request line and regenerate
988 * the http request data.
991 * 1 : csp = Current client state (buffers, headers, etc...)
993 * Returns : Forwards the parse_http_request() return code.
994 * Terminates in case of memory problems.
996 *********************************************************************/
997 static jb_err change_request_destination(struct client_state *csp)
999 struct http_request *http = csp->http;
1002 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1003 csp->headers->first->str);
1004 free_http_request(http);
1005 err = parse_http_request(csp->headers->first->str, http);
1006 if (JB_ERR_OK != err)
1008 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1009 jb_err_to_string(err));
1016 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1017 /*********************************************************************
1019 * Function : server_response_is_complete
1021 * Description : Determines whether we should stop reading
1022 * from the server socket.
1025 * 1 : csp = Current client state (buffers, headers, etc...)
1026 * 2 : content_length = Length of content received so far.
1028 * Returns : TRUE if the response is complete,
1031 *********************************************************************/
1032 static int server_response_is_complete(struct client_state *csp,
1033 unsigned long long content_length)
1035 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1037 if (!strcmpic(csp->http->gpc, "HEAD"))
1040 * "HEAD" implies no body, we are thus expecting
1041 * no content. XXX: incomplete "list" of methods?
1043 csp->expected_content_length = 0;
1044 content_length_known = TRUE;
1045 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1048 if (csp->http->status == 204 || csp->http->status == 304)
1051 * Expect no body. XXX: incomplete "list" of status codes?
1053 csp->expected_content_length = 0;
1054 content_length_known = TRUE;
1055 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1058 return (content_length_known && ((0 == csp->expected_content_length)
1059 || (csp->expected_content_length <= content_length)));
1063 #ifdef FEATURE_CONNECTION_SHARING
1064 /*********************************************************************
1066 * Function : wait_for_alive_connections
1068 * Description : Waits for alive connections to timeout.
1074 *********************************************************************/
1075 static void wait_for_alive_connections(void)
1077 int connections_alive = close_unusable_connections();
1079 while (0 < connections_alive)
1081 log_error(LOG_LEVEL_CONNECT,
1082 "Waiting for %d connections to timeout.",
1085 connections_alive = close_unusable_connections();
1088 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1091 #endif /* def FEATURE_CONNECTION_SHARING */
1094 /*********************************************************************
1096 * Function : save_connection_destination
1098 * Description : Remembers a connection for reuse later on.
1101 * 1 : sfd = Open socket to remember.
1102 * 2 : http = The destination for the connection.
1103 * 3 : fwd = The forwarder settings used.
1104 * 4 : server_connection = storage.
1108 *********************************************************************/
1109 void save_connection_destination(jb_socket sfd,
1110 const struct http_request *http,
1111 const struct forward_spec *fwd,
1112 struct reusable_connection *server_connection)
1114 assert(sfd != JB_INVALID_SOCKET);
1115 assert(NULL != http->host);
1117 server_connection->sfd = sfd;
1118 server_connection->host = strdup_or_die(http->host);
1119 server_connection->port = http->port;
1121 assert(NULL != fwd);
1122 assert(server_connection->gateway_host == NULL);
1123 assert(server_connection->gateway_port == 0);
1124 assert(server_connection->forwarder_type == 0);
1125 assert(server_connection->forward_host == NULL);
1126 assert(server_connection->forward_port == 0);
1128 server_connection->forwarder_type = fwd->type;
1129 if (NULL != fwd->gateway_host)
1131 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1135 server_connection->gateway_host = NULL;
1137 server_connection->gateway_port = fwd->gateway_port;
1139 if (NULL != fwd->forward_host)
1141 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1145 server_connection->forward_host = NULL;
1147 server_connection->forward_port = fwd->forward_port;
1151 /*********************************************************************
1153 * Function : verify_request_length
1155 * Description : Checks if we already got the whole client requests
1156 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1159 * Data that doesn't belong to the current request is
1160 * either thrown away to let the client retry on a clean
1161 * socket, or stashed to be dealt with after the current
1162 * request is served.
1165 * 1 : csp = Current client state (buffers, headers, etc...)
1169 *********************************************************************/
1170 static void verify_request_length(struct client_state *csp)
1172 unsigned long long buffered_request_bytes =
1173 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1175 if ((csp->expected_client_content_length != 0)
1176 && (buffered_request_bytes != 0))
1178 if (csp->expected_client_content_length >= buffered_request_bytes)
1180 csp->expected_client_content_length -= buffered_request_bytes;
1181 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1182 "to account for the %llu ones we already got.",
1183 csp->expected_client_content_length, buffered_request_bytes);
1187 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1188 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1189 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1190 "Marking the server socket tainted after throwing %llu bytes away.",
1191 buffered_request_bytes - csp->expected_client_content_length);
1192 csp->expected_client_content_length = 0;
1193 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1196 if (csp->expected_client_content_length == 0)
1198 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1202 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1203 && ((csp->client_iob->cur < csp->client_iob->eod)
1204 || (csp->expected_client_content_length != 0)))
1206 if (strcmpic(csp->http->gpc, "GET")
1207 && strcmpic(csp->http->gpc, "HEAD")
1208 && strcmpic(csp->http->gpc, "TRACE")
1209 && strcmpic(csp->http->gpc, "OPTIONS")
1210 && strcmpic(csp->http->gpc, "DELETE"))
1212 /* XXX: this is an incomplete hack */
1213 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1214 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1218 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1220 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1222 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1223 log_error(LOG_LEVEL_CONNECT,
1224 "Possible pipeline attempt detected. The connection will not "
1225 "be kept alive and we will only serve the first request.");
1226 /* Nuke the pipelined requests from orbit, just to be sure. */
1227 clear_iob(csp->client_iob);
1232 * Keep the pipelined data around for now, we'll deal with
1233 * it once we're done serving the current request.
1235 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1236 assert(csp->client_iob->eod >= csp->client_iob->cur);
1237 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1238 "%d bytes of pipelined data received.",
1239 (int)(csp->client_iob->eod - csp->client_iob->cur));
1245 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1246 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1249 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1252 /*********************************************************************
1254 * Function : mark_server_socket_tainted
1256 * Description : Makes sure we don't reuse a server socket
1257 * (if we didn't read everything the server sent
1258 * us reusing the socket would lead to garbage).
1261 * 1 : csp = Current client state (buffers, headers, etc...)
1265 *********************************************************************/
1266 static void mark_server_socket_tainted(struct client_state *csp)
1269 * For consistency we always mark the server socket
1270 * tainted, however, to reduce the log noise we only
1271 * emit a log message if the server socket could have
1272 * actually been reused.
1274 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1275 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1277 log_error(LOG_LEVEL_CONNECT,
1278 "Marking the server socket %d tainted.",
1279 csp->server_connection.sfd);
1281 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1284 /*********************************************************************
1286 * Function : get_request_line
1288 * Description : Read the client request line.
1291 * 1 : csp = Current client state (buffers, headers, etc...)
1293 * Returns : Pointer to request line or NULL in case of errors.
1295 *********************************************************************/
1296 static char *get_request_line(struct client_state *csp)
1298 char buf[BUFFER_SIZE];
1299 char *request_line = NULL;
1302 memset(buf, 0, sizeof(buf));
1304 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1307 * If there are multiple pipelined requests waiting,
1308 * the flag will be set again once the next request
1311 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1313 request_line = get_header(csp->client_iob);
1314 if ((NULL != request_line) && ('\0' != *request_line))
1316 return request_line;
1320 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1321 "received yet. Continuing reading from %d.", csp->cfd);
1329 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1331 !data_is_available(csp->cfd, csp->config->socket_timeout)
1334 if (socket_is_still_alive(csp->cfd))
1336 log_error(LOG_LEVEL_CONNECT,
1337 "No request line on socket %d received in time. Timeout: %d.",
1338 csp->cfd, csp->config->socket_timeout);
1339 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1340 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1341 get_write_delay(csp));
1345 log_error(LOG_LEVEL_CONNECT,
1346 "The client side of the connection on socket %d got "
1347 "closed without sending a complete request line.", csp->cfd);
1352 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1354 if (len <= 0) return NULL;
1357 * If there is no memory left for buffering the
1358 * request, there is nothing we can do but hang up
1360 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1365 request_line = get_header(csp->client_iob);
1367 } while ((NULL != request_line) && ('\0' == *request_line));
1369 return request_line;
1375 CHUNK_STATUS_MISSING_DATA,
1376 CHUNK_STATUS_BODY_COMPLETE,
1377 CHUNK_STATUS_PARSE_ERROR
1381 /*********************************************************************
1383 * Function : chunked_body_is_complete
1385 * Description : Figures out whether or not a chunked body is complete.
1387 * Currently it always starts at the beginning of the
1388 * buffer which is somewhat wasteful and prevents Privoxy
1389 * from starting to forward the correctly parsed chunks
1390 * as soon as theoretically possible.
1392 * Should be modified to work with a common buffer,
1393 * and allow the caller to skip already parsed chunks.
1395 * This would allow the function to be used for unbuffered
1396 * response bodies as well.
1399 * 1 : iob = Buffer with the body to check.
1400 * 2 : length = Length of complete body
1402 * Returns : Enum with the result of the check.
1404 *********************************************************************/
1405 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1407 unsigned int chunksize;
1413 * We need at least a single digit, followed by "\r\n",
1414 * followed by an unknown amount of data, followed by "\r\n".
1416 if (p + 5 > iob->eod)
1418 return CHUNK_STATUS_MISSING_DATA;
1420 if (sscanf(p, "%x", &chunksize) != 1)
1422 return CHUNK_STATUS_PARSE_ERROR;
1426 * We want at least a single digit, followed by "\r\n",
1427 * followed by the specified amount of data, followed by "\r\n".
1429 if (p + chunksize + 5 > iob->eod)
1431 return CHUNK_STATUS_MISSING_DATA;
1434 /* Skip chunk-size. */
1435 p = strstr(p, "\r\n");
1438 return CHUNK_STATUS_PARSE_ERROR;
1440 /* Move beyond the chunkdata. */
1443 /* There should be another "\r\n" to skip */
1444 if (memcmp(p, "\r\n", 2))
1446 return CHUNK_STATUS_PARSE_ERROR;
1449 } while (chunksize > 0U);
1451 *length = (size_t)(p - iob->cur);
1452 assert(*length <= (size_t)(iob->eod - iob->cur));
1453 assert(p <= iob->eod);
1455 return CHUNK_STATUS_BODY_COMPLETE;
1460 /*********************************************************************
1462 * Function : receive_chunked_client_request_body
1464 * Description : Read the chunk-encoded client request body.
1465 * Failures are dealt with.
1468 * 1 : csp = Current client state (buffers, headers, etc...)
1470 * Returns : JB_ERR_OK or JB_ERR_PARSE
1472 *********************************************************************/
1473 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1476 enum chunk_status status;
1478 while (CHUNK_STATUS_MISSING_DATA ==
1479 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1481 char buf[BUFFER_SIZE];
1484 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1486 log_error(LOG_LEVEL_ERROR,
1487 "Timeout while waiting for the client body.");
1490 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1493 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1496 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1501 if (status != CHUNK_STATUS_BODY_COMPLETE)
1503 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1504 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1505 log_error(LOG_LEVEL_CLF,
1506 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1507 return JB_ERR_PARSE;
1509 log_error(LOG_LEVEL_CONNECT,
1510 "Chunked client body completely read. Length: %d", body_length);
1511 csp->expected_client_content_length = body_length;
1519 /*********************************************************************
1521 * Function : fuzz_chunked_transfer_encoding
1523 * Description : Treat the fuzzed input as chunked transfer encoding
1524 * to check and dechunk.
1527 * 1 : csp = Used to store the data.
1528 * 2 : fuzz_input_file = File to read the input from.
1530 * Returns : Result of dechunking
1532 *********************************************************************/
1533 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1536 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1537 enum chunk_status status;
1539 status = chunked_body_is_complete(csp->iob, &length);
1540 if (CHUNK_STATUS_BODY_COMPLETE != status)
1542 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1545 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1550 /*********************************************************************
1552 * Function : fuzz_client_request
1554 * Description : Try to get a client request from the fuzzed input.
1557 * 1 : csp = Current client state (buffers, headers, etc...)
1558 * 2 : fuzz_input_file = File to read the input from.
1560 * Returns : Result of fuzzing.
1562 *********************************************************************/
1563 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1568 csp->ip_addr_str = "fuzzer";
1570 if (strcmp(fuzz_input_file, "-") != 0)
1572 log_error(LOG_LEVEL_FATAL,
1573 "Fuzzed client requests can currenty only be read from stdin (-).");
1575 err = receive_client_request(csp);
1576 if (err != JB_ERR_OK)
1580 err = parse_client_request(csp);
1581 if (err != JB_ERR_OK)
1589 #endif /* def FUZZ */
1592 #ifdef FEATURE_FORCE_LOAD
1593 /*********************************************************************
1595 * Function : force_required
1597 * Description : Checks a request line to see if it contains
1598 * the FORCE_PREFIX. If it does, it is removed
1599 * unless enforcing requests has beend disabled.
1602 * 1 : request_line = HTTP request line
1604 * Returns : TRUE if force is required, FALSE otherwise.
1606 *********************************************************************/
1607 static int force_required(const struct client_state *csp, char *request_line)
1611 p = strstr(request_line, "http://");
1615 p += strlen("http://");
1619 /* Intercepted request usually don't specify the protocol. */
1623 /* Go to the beginning of the path */
1628 * If the path is missing the request line is invalid and we
1629 * are done here. The client-visible rejection happens later on.
1634 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1636 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1638 /* XXX: Should clean more carefully */
1639 strclean(request_line, FORCE_PREFIX);
1640 log_error(LOG_LEVEL_FORCE,
1641 "Enforcing request: \"%s\".", request_line);
1645 log_error(LOG_LEVEL_FORCE,
1646 "Ignored force prefix in request: \"%s\".", request_line);
1652 #endif /* def FEATURE_FORCE_LOAD */
1655 /*********************************************************************
1657 * Function : receive_client_request
1659 * Description : Read the client's request (more precisely the
1660 * client headers) and answer it if necessary.
1663 * 1 : csp = Current client state (buffers, headers, etc...)
1665 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1667 *********************************************************************/
1668 static jb_err receive_client_request(struct client_state *csp)
1670 char buf[BUFFER_SIZE];
1673 struct http_request *http;
1677 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1678 struct list header_list;
1679 struct list *headers = &header_list;
1681 /* We don't care if the arriving data is a valid HTTP request or not. */
1682 csp->requests_received_total++;
1686 memset(buf, 0, sizeof(buf));
1688 req = get_request_line(csp);
1691 mark_server_socket_tainted(csp);
1692 return JB_ERR_PARSE;
1694 assert(*req != '\0');
1696 if (client_protocol_is_unsupported(csp, req))
1698 return JB_ERR_PARSE;
1701 #ifdef FEATURE_FORCE_LOAD
1702 if (force_required(csp, req))
1704 csp->flags |= CSP_FLAG_FORCED;
1706 #endif /* def FEATURE_FORCE_LOAD */
1708 err = parse_http_request(req, http);
1710 if (JB_ERR_OK != err)
1712 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1713 get_write_delay(csp));
1714 /* XXX: Use correct size */
1715 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1716 log_error(LOG_LEVEL_ERROR,
1717 "Couldn't parse request line received from %s: %s",
1718 csp->ip_addr_str, jb_err_to_string(err));
1720 free_http_request(http);
1721 return JB_ERR_PARSE;
1724 /* grab the rest of the client's headers */
1728 p = get_header(csp->client_iob);
1732 /* There are no additional headers to read. */
1739 * We didn't receive a complete header
1740 * line yet, get the rest of it.
1742 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1744 log_error(LOG_LEVEL_ERROR,
1745 "Stopped grabbing the client headers.");
1746 destroy_list(headers);
1747 return JB_ERR_PARSE;
1750 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1753 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1754 destroy_list(headers);
1755 return JB_ERR_PARSE;
1758 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1761 * If there is no memory left for buffering the
1762 * request, there is nothing we can do but hang up
1764 destroy_list(headers);
1765 return JB_ERR_MEMORY;
1770 if (!strncmpic(p, "Transfer-Encoding:", 18))
1773 * XXX: should be called through sed()
1774 * but currently can't.
1776 client_transfer_encoding(csp, &p);
1779 * We were able to read a complete
1780 * header and can finally enlist it.
1787 if (http->host == NULL)
1790 * If we still don't know the request destination,
1791 * the request is invalid or the client uses
1792 * Privoxy without its knowledge.
1794 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1797 * Our attempts to get the request destination
1798 * elsewhere failed or Privoxy is configured
1799 * to only accept proxy requests.
1801 * An error response has already been send
1802 * and we're done here.
1804 return JB_ERR_PARSE;
1808 #ifdef FEATURE_CLIENT_TAGS
1809 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1810 set_client_address(csp, headers);
1811 get_tag_list_for_client(csp->client_tags, csp->client_address);
1815 * Determine the actions for this URL
1817 #ifdef FEATURE_TOGGLE
1818 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1820 /* Most compatible set of actions (i.e. none) */
1821 init_current_action(csp->action);
1824 #endif /* ndef FEATURE_TOGGLE */
1826 get_url_actions(csp, http);
1829 enlist(csp->headers, http->cmd);
1831 /* Append the previously read headers */
1832 err = list_append_list_unique(csp->headers, headers);
1833 destroy_list(headers);
1840 /*********************************************************************
1842 * Function : parse_client_request
1844 * Description : Parses the client's request and decides what to do
1847 * Note that since we're not using select() we could get
1848 * blocked here if a client connected, then didn't say
1852 * 1 : csp = Current client state (buffers, headers, etc...)
1854 * Returns : JB_ERR_OK or JB_ERR_PARSE
1856 *********************************************************************/
1857 static jb_err parse_client_request(struct client_state *csp)
1859 struct http_request *http = csp->http;
1862 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1863 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1864 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1865 && (csp->http->ssl == 0))
1867 /* Assume persistence until further notice */
1868 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1871 if (csp->http->ssl == 0)
1874 * This whole block belongs to chat() but currently
1875 * has to be executed before sed().
1877 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1879 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1881 return JB_ERR_PARSE;
1886 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1888 verify_request_length(csp);
1892 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1894 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1896 err = sed(csp, FILTER_CLIENT_HEADERS);
1897 if (JB_ERR_OK != err)
1899 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1901 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1902 csp->ip_addr_str, csp->http->cmd);
1903 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1904 return JB_ERR_PARSE;
1906 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1908 /* Check request line for rewrites. */
1909 if ((NULL == csp->headers->first->str)
1910 || (strcmp(http->cmd, csp->headers->first->str) &&
1911 (JB_ERR_OK != change_request_destination(csp))))
1914 * A header filter broke the request line - bail out.
1916 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1917 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1918 /* XXX: Use correct size */
1919 log_error(LOG_LEVEL_CLF,
1920 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1921 log_error(LOG_LEVEL_ERROR,
1922 "Invalid request line after applying header filters.");
1923 free_http_request(http);
1925 return JB_ERR_PARSE;
1928 if (client_has_unsupported_expectations(csp))
1930 return JB_ERR_PARSE;
1938 /*********************************************************************
1940 * Function : send_http_request
1942 * Description : Sends the HTTP headers from the client request
1943 * and all the body data that has already been received.
1946 * 1 : csp = Current client state (buffers, headers, etc...)
1948 * Returns : 0 on success, anything else is na error.
1950 *********************************************************************/
1951 static int send_http_request(struct client_state *csp)
1956 hdr = list_to_text(csp->headers);
1959 /* FIXME Should handle error properly */
1960 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1962 list_remove_all(csp->headers);
1965 * Write the client's (modified) header to the server
1966 * (along with anything else that may be in the buffer)
1968 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
1973 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
1974 csp->http->hostport);
1976 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
1977 && (flush_socket(csp->server_connection.sfd, csp->client_iob, 0) < 0))
1980 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
1981 csp->http->hostport);
1984 return write_failure;
1989 /*********************************************************************
1991 * Function : handle_established_connection
1993 * Description : Shuffle data between client and server once the
1994 * connection has been established.
1997 * 1 : csp = Current client state (buffers, headers, etc...)
1999 * Returns : Nothing.
2001 *********************************************************************/
2002 static void handle_established_connection(struct client_state *csp)
2008 struct pollfd poll_fds[2];
2012 struct timeval timeout;
2015 int ms_iis5_hack = 0;
2016 unsigned long long byte_count = 0;
2017 struct http_request *http;
2018 long len = 0; /* for buffer sizes (and negative error codes) */
2019 int buffer_and_filter_content = 0;
2020 unsigned int write_delay;
2022 /* Skeleton for HTTP response, if we should intercept the request */
2023 struct http_response *rsp;
2024 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2025 int watch_client_socket;
2028 csp->receive_buffer_size = csp->config->receive_buffer_size;
2029 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2030 if (csp->receive_buffer == NULL)
2032 log_error(LOG_LEVEL_ERROR,
2033 "Out of memory. Failed to allocate the receive buffer.");
2034 rsp = cgi_error_memory();
2035 send_crunch_response(csp, rsp);
2042 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2043 csp->cfd : csp->server_connection.sfd;
2046 /* pass data between the client and server
2047 * until one or the other shuts down the connection.
2052 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2053 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2055 write_delay = get_write_delay(csp);
2062 * FD_ZERO here seems to point to an errant macro which crashes.
2063 * So do this by hand for now...
2065 memset(&rfds,0x00,sizeof(fd_set));
2069 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2070 if (!watch_client_socket)
2072 maxfd = csp->server_connection.sfd;
2075 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2077 FD_SET(csp->cfd, &rfds);
2080 FD_SET(csp->server_connection.sfd, &rfds);
2081 #endif /* ndef HAVE_POLL */
2083 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2084 if ((csp->flags & CSP_FLAG_CHUNKED)
2085 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2086 && ((csp->iob->eod - csp->iob->cur) >= 5)
2087 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2090 * XXX: This check should be obsolete now,
2091 * but let's wait a while to be sure.
2093 log_error(LOG_LEVEL_CONNECT,
2094 "Looks like we got the last chunk together with "
2095 "the server headers but didn't detect it earlier. "
2096 "We better stop reading.");
2097 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2098 csp->expected_content_length = byte_count;
2099 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2101 if (server_body && server_response_is_complete(csp, byte_count))
2103 if (csp->expected_content_length == byte_count)
2105 log_error(LOG_LEVEL_CONNECT,
2106 "Done reading from server. Content length: %llu as expected. "
2107 "Bytes most recently read: %d.",
2112 log_error(LOG_LEVEL_CONNECT,
2113 "Done reading from server. Expected content length: %llu. "
2114 "Actual content length: %llu. Bytes most recently read: %d.",
2115 csp->expected_content_length, byte_count, len);
2119 * XXX: should not jump around,
2120 * chat() is complicated enough already.
2124 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2127 poll_fds[0].fd = csp->cfd;
2128 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2129 if (!watch_client_socket)
2132 * Ignore incoming data, but still watch out
2133 * for disconnects etc. These flags are always
2134 * implied anyway but explicitly setting them
2137 poll_fds[0].events = POLLERR|POLLHUP;
2142 poll_fds[0].events = POLLIN;
2144 poll_fds[1].fd = csp->server_connection.sfd;
2145 poll_fds[1].events = POLLIN;
2146 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2148 timeout.tv_sec = csp->config->socket_timeout;
2149 timeout.tv_usec = 0;
2150 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2151 #endif /* def HAVE_POLL */
2155 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2156 csp->config->socket_timeout, http->url);
2157 if ((byte_count == 0) && (http->ssl == 0))
2159 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2161 mark_server_socket_tainted(csp);
2167 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2169 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2171 mark_server_socket_tainted(csp);
2176 * This is the body of the browser's request,
2177 * just read and write it.
2179 * XXX: Make sure the client doesn't use pipelining
2180 * behind Privoxy's back.
2183 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2185 log_error(LOG_LEVEL_CONNECT,
2186 "The client socket %d has become unusable while "
2187 "the server socket %d is still open.",
2188 csp->cfd, csp->server_connection.sfd);
2189 mark_server_socket_tainted(csp);
2193 if (poll_fds[0].revents != 0)
2195 if (FD_ISSET(csp->cfd, &rfds))
2196 #endif /* def HAVE_POLL*/
2198 int max_bytes_to_read = (int)csp->receive_buffer_size;
2200 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2201 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2203 if (data_is_available(csp->cfd, 0))
2206 * If the next request is already waiting, we have
2207 * to stop select()ing the client socket. Otherwise
2208 * we would always return right away and get nothing
2211 watch_client_socket = 0;
2212 log_error(LOG_LEVEL_CONNECT,
2213 "Stop watching client socket %d. "
2214 "There's already another request waiting.",
2219 * If the client socket is set, but there's no data
2220 * available on the socket, the client went fishing
2221 * and continuing talking to the server makes no sense.
2223 log_error(LOG_LEVEL_CONNECT,
2224 "The client closed socket %d while "
2225 "the server socket %d is still open.",
2226 csp->cfd, csp->server_connection.sfd);
2227 mark_server_socket_tainted(csp);
2230 if (csp->expected_client_content_length != 0)
2232 if (csp->expected_client_content_length < csp->receive_buffer_size)
2234 max_bytes_to_read = (int)csp->expected_client_content_length;
2236 log_error(LOG_LEVEL_CONNECT,
2237 "Waiting for up to %d bytes from the client.",
2240 assert(max_bytes_to_read <= csp->receive_buffer_size);
2241 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2243 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2247 /* XXX: not sure if this is necessary. */
2248 mark_server_socket_tainted(csp);
2249 break; /* "game over, man" */
2252 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2253 if (csp->expected_client_content_length != 0)
2255 assert(len <= max_bytes_to_read);
2256 csp->expected_client_content_length -= (unsigned)len;
2257 log_error(LOG_LEVEL_CONNECT,
2258 "Expected client content length set to %llu "
2259 "after reading %d bytes.",
2260 csp->expected_client_content_length, len);
2261 if (csp->expected_client_content_length == 0)
2263 log_error(LOG_LEVEL_CONNECT,
2264 "Done reading from the client.");
2265 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2268 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2270 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2272 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2273 mark_server_socket_tainted(csp);
2280 * The server wants to talk. It could be the header or the body.
2281 * If `hdr' is null, then it's the header otherwise it's the body.
2282 * FIXME: Does `hdr' really mean `host'? No.
2285 if (poll_fds[1].revents != 0)
2287 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2288 #endif /* HAVE_POLL */
2290 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2292 * If we are buffering content, we don't want to eat up to
2293 * buffer-limit bytes if the client no longer cares about them.
2294 * If we aren't buffering, however, a dead client socket will be
2295 * noticed pretty much right away anyway, so we can reduce the
2296 * overhead by skipping the check.
2298 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2301 log_error(LOG_LEVEL_CONNECT,
2302 "The server still wants to talk, but the client may already have hung up on us.");
2304 log_error(LOG_LEVEL_CONNECT,
2305 "The server still wants to talk, but the client hung up on us.");
2306 mark_server_socket_tainted(csp);
2308 #endif /* def _WIN32 */
2310 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2312 len = read_socket(csp->server_connection.sfd, csp->receive_buffer, (int)csp->receive_buffer_size);
2316 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2318 if (http->ssl && (csp->fwd == NULL))
2321 * Just hang up. We already confirmed the client's CONNECT
2322 * request with status code 200 and unencrypted content is
2323 * no longer welcome.
2325 log_error(LOG_LEVEL_ERROR,
2326 "CONNECT already confirmed. Unable to tell the client about the problem.");
2329 else if (byte_count)
2332 * Just hang up. We already transmitted the original headers
2333 * and parts of the original content and therefore missed the
2334 * chance to send an error message (without risking data corruption).
2336 * XXX: we could retry with a fancy range request here.
2338 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2339 "Unable to tell the client about the problem.");
2340 mark_server_socket_tainted(csp);
2344 * XXX: Consider handling the cases above the same.
2346 mark_server_socket_tainted(csp);
2350 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2351 if (csp->flags & CSP_FLAG_CHUNKED)
2353 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2355 /* XXX: this is a temporary hack */
2356 log_error(LOG_LEVEL_CONNECT,
2357 "Looks like we reached the end of the last chunk. "
2358 "We better stop reading.");
2359 csp->expected_content_length = byte_count + (unsigned long long)len;
2360 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2364 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2367 * This is guaranteed by allocating with zalloc_or_die()
2368 * and never (intentionally) writing to the last byte.
2370 * csp->receive_buffer_size is the size of the part of the
2371 * buffer we intentionally write to, but we actually
2372 * allocated csp->receive_buffer_size+1 bytes so the assertion
2373 * stays within the allocated range.
2375 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2378 * Add a trailing zero to let be able to use string operations.
2379 * XXX: do we still need this with filter_popups gone?
2381 assert(len <= csp->receive_buffer_size);
2382 csp->receive_buffer[len] = '\0';
2385 * Normally, this would indicate that we've read
2386 * as much as the server has sent us and we can
2387 * close the client connection. However, Microsoft
2388 * in its wisdom has released IIS/5 with a bug that
2389 * prevents it from sending the trailing \r\n in
2390 * a 302 redirect header (and possibly other headers).
2391 * To work around this if we've haven't parsed
2392 * a full header we'll append a trailing \r\n
2393 * and see if this now generates a valid one.
2395 * This hack shouldn't have any impacts. If we've
2396 * already transmitted the header or if this is a
2397 * SSL connection, then we won't bother with this
2398 * hack. So we only work on partially received
2399 * headers. If we append a \r\n and this still
2400 * doesn't generate a valid header, then we won't
2401 * transmit anything to the client.
2406 if (server_body || http->ssl)
2409 * If we have been buffering up the document,
2410 * now is the time to apply content modification
2411 * and send the result to the client.
2413 if (buffer_and_filter_content)
2415 p = execute_content_filters(csp);
2417 * If content filtering fails, use the original
2418 * buffer and length.
2419 * (see p != NULL ? p : csp->iob->cur below)
2423 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2425 #ifdef FEATURE_COMPRESSION
2426 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2427 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2429 char *compressed_content = compress_buffer(p,
2430 (size_t *)&csp->content_length, csp->config->compression_level);
2431 if (compressed_content != NULL)
2434 p = compressed_content;
2435 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2440 if (JB_ERR_OK != update_server_headers(csp))
2442 log_error(LOG_LEVEL_FATAL,
2443 "Failed to update server headers. after filtering.");
2446 hdr = list_to_text(csp->headers);
2449 /* FIXME Should handle error properly */
2450 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2453 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
2454 || write_socket_delayed(csp->cfd,
2455 ((p != NULL) ? p : csp->iob->cur),
2456 (size_t)csp->content_length, write_delay))
2458 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2461 mark_server_socket_tainted(csp);
2469 break; /* "game over, man" */
2473 * This is NOT the body, so
2474 * Let's pretend the server just sent us a blank line.
2476 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
2477 len = (int)strlen(csp->receive_buffer);
2480 * Now, let the normal header parsing algorithm below do its
2481 * job. If it fails, we'll exit instead of continuing.
2488 * If this is an SSL connection or we're in the body
2489 * of the server document, just write it to the client,
2490 * unless we need to buffer the body for later content-filtering
2492 if (server_body || http->ssl)
2494 if (buffer_and_filter_content)
2497 * If there is no memory left for buffering the content, or the buffer limit
2498 * has been reached, switch to non-filtering mode, i.e. make & write the
2499 * header, flush the iob and buf, and get out of the way.
2501 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
2506 log_error(LOG_LEVEL_INFO,
2507 "Flushing header and buffers. Stepping back from filtering.");
2509 hdr = list_to_text(csp->headers);
2513 * Memory is too tight to even generate the header.
2514 * Send our static "Out-of-memory" page.
2516 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2517 rsp = cgi_error_memory();
2518 send_crunch_response(csp, rsp);
2519 mark_server_socket_tainted(csp);
2522 hdrlen = strlen(hdr);
2524 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
2525 || ((flushed = flush_socket(csp->cfd, csp->iob,
2527 || (write_socket_delayed(csp->cfd, csp->receive_buffer,
2528 (size_t)len, write_delay))))
2530 log_error(LOG_LEVEL_CONNECT,
2531 "Flush header and buffers to client failed: %E");
2533 mark_server_socket_tainted(csp);
2538 * Reset the byte_count to the amount of bytes
2539 * we just flushed. len will be added a few lines below,
2540 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2542 byte_count = (unsigned long long)flushed;
2544 buffer_and_filter_content = 0;
2550 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
2551 (size_t)len, write_delay))
2553 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2554 mark_server_socket_tainted(csp);
2558 byte_count += (unsigned long long)len;
2564 * We're still looking for the end of the server's header.
2565 * Buffer up the data we just read. If that fails, there's
2566 * little we can do but send our static out-of-memory page.
2568 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
2570 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2571 rsp = cgi_error_memory();
2572 send_crunch_response(csp, rsp);
2573 mark_server_socket_tainted(csp);
2577 /* Convert iob into something sed() can digest */
2578 if (JB_ERR_PARSE == get_server_headers(csp))
2583 * Well, we tried our MS IIS/5 hack and it didn't work.
2584 * The header is incomplete and there isn't anything
2585 * we can do about it.
2587 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2588 "Applying the MS IIS5 hack didn't help.");
2589 log_error(LOG_LEVEL_CLF,
2590 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2591 write_socket_delayed(csp->cfd,
2592 INVALID_SERVER_HEADERS_RESPONSE,
2593 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
2594 mark_server_socket_tainted(csp);
2600 * Since we have to wait for more from the server before
2601 * we can parse the headers we just continue here.
2603 log_error(LOG_LEVEL_CONNECT,
2604 "Continuing buffering server headers from socket %d. "
2605 "Bytes most recently read: %d.", csp->cfd, len);
2612 * Account for the content bytes we
2613 * might have gotten with the headers.
2615 assert(csp->iob->eod >= csp->iob->cur);
2616 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2619 /* Did we actually get anything? */
2620 if (NULL == csp->headers->first)
2622 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2624 log_error(LOG_LEVEL_ERROR,
2625 "No server or forwarder response received on socket %d. "
2626 "Closing client socket %d without sending data.",
2627 csp->server_connection.sfd, csp->cfd);
2628 log_error(LOG_LEVEL_CLF,
2629 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2633 log_error(LOG_LEVEL_ERROR,
2634 "No server or forwarder response received on socket %d.",
2635 csp->server_connection.sfd);
2636 send_crunch_response(csp, error_response(csp, "no-server-data"));
2638 free_http_request(http);
2639 mark_server_socket_tainted(csp);
2643 assert(csp->headers->first->str);
2645 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2646 strncmpic(csp->headers->first->str, "ICY", 3))
2649 * It doesn't look like a HTTP (or Shoutcast) response:
2650 * tell the client and log the problem.
2652 if (strlen(csp->headers->first->str) > 30)
2654 csp->headers->first->str[30] = '\0';
2656 log_error(LOG_LEVEL_ERROR,
2657 "Invalid server or forwarder response. Starts with: %s",
2658 csp->headers->first->str);
2659 log_error(LOG_LEVEL_CLF,
2660 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2661 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2662 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
2663 free_http_request(http);
2664 mark_server_socket_tainted(csp);
2669 * We have now received the entire server header,
2670 * filter it and send the result to the client
2672 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2674 log_error(LOG_LEVEL_CLF,
2675 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2676 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2677 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
2678 free_http_request(http);
2679 mark_server_socket_tainted(csp);
2682 hdr = list_to_text(csp->headers);
2685 /* FIXME Should handle error properly */
2686 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2689 if ((csp->flags & CSP_FLAG_CHUNKED)
2690 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2691 && ((csp->iob->eod - csp->iob->cur) >= 5)
2692 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2694 log_error(LOG_LEVEL_CONNECT,
2695 "Looks like we got the last chunk together with "
2696 "the server headers. We better stop reading.");
2697 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2698 csp->expected_content_length = byte_count;
2699 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2702 csp->server_connection.response_received = time(NULL);
2704 if (crunch_response_triggered(csp, crunchers_light))
2707 * One of the tags created by a server-header
2708 * tagger triggered a crunch. We already
2709 * delivered the crunch response to the client
2710 * and are done here after cleaning up.
2713 mark_server_socket_tainted(csp);
2716 /* Buffer and pcrs filter this if appropriate. */
2718 if (!http->ssl) /* We talk plaintext */
2720 buffer_and_filter_content = content_requires_filtering(csp);
2723 * Only write if we're not buffering for content modification
2725 if (!buffer_and_filter_content)
2728 * Write the server's (modified) header to
2729 * the client (along with anything else that
2730 * may be in the buffer)
2733 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
2734 || ((len = flush_socket(csp->cfd, csp->iob, write_delay)) < 0))
2736 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2739 * The write failed, so don't bother mentioning it
2740 * to the client... it probably can't hear us anyway.
2743 mark_server_socket_tainted(csp);
2748 /* we're finished with the server's header */
2754 * If this was a MS IIS/5 hack then it means the server
2755 * has already closed the connection. Nothing more to read.
2760 log_error(LOG_LEVEL_ERROR,
2761 "Closed server connection detected. "
2762 "Applying the MS IIS5 hack didn't help.");
2763 log_error(LOG_LEVEL_CLF,
2764 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2765 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2766 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
2767 mark_server_socket_tainted(csp);
2773 mark_server_socket_tainted(csp);
2774 return; /* huh? we should never get here */
2777 if (csp->content_length == 0)
2780 * If Privoxy didn't recalculate the Content-Length,
2781 * byte_count is still correct.
2783 csp->content_length = byte_count;
2786 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2787 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2788 && (csp->expected_content_length != byte_count))
2790 log_error(LOG_LEVEL_CONNECT,
2791 "Received %llu bytes while expecting %llu.",
2792 byte_count, csp->expected_content_length);
2793 mark_server_socket_tainted(csp);
2797 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2798 csp->ip_addr_str, http->ocmd, csp->content_length);
2800 csp->server_connection.timestamp = time(NULL);
2804 /*********************************************************************
2808 * Description : Once a connection from the client has been accepted,
2809 * this function is called (via serve()) to handle the
2810 * main business of the communication. This function
2811 * returns after dealing with a single request. It can
2812 * be called multiple times with the same client socket
2813 * if the client is keeping the connection alive.
2815 * The decision whether or not a client connection will
2816 * be kept alive is up to the caller which also must
2817 * close the client socket when done.
2819 * FIXME: chat is nearly thousand lines long.
2823 * 1 : csp = Current client state (buffers, headers, etc...)
2825 * Returns : Nothing.
2827 *********************************************************************/
2828 static void chat(struct client_state *csp)
2830 const struct forward_spec *fwd;
2831 struct http_request *http;
2832 /* Skeleton for HTTP response, if we should intercept the request */
2833 struct http_response *rsp;
2837 if (receive_client_request(csp) != JB_ERR_OK)
2841 if (parse_client_request(csp) != JB_ERR_OK)
2846 /* decide how to route the HTTP request */
2847 fwd = forward_url(csp, http);
2850 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2851 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2856 * build the http request to send to the server
2857 * we have to do one of the following:
2859 * create = use the original HTTP request to create a new
2860 * HTTP request that has either the path component
2861 * without the http://domainspec (w/path) or the
2862 * full orininal URL (w/url)
2863 * Note that the path and/or the HTTP version may
2864 * have been altered by now.
2866 * connect = Open a socket to the host:port of the server
2867 * and short-circuit server and client socket.
2869 * pass = Pass the request unchanged if forwarding a CONNECT
2870 * request to a parent proxy. Note that we'll be sending
2871 * the CFAIL message ourselves if connecting to the parent
2872 * fails, but we won't send a CSUCCEED message if it works,
2873 * since that would result in a double message (ours and the
2874 * parent's). After sending the request to the parent, we simply
2877 * here's the matrix:
2880 * +--------+--------+
2882 * 0 | create | connect|
2884 * Forwarding +--------+--------+
2886 * 1 | create | pass |
2888 * +--------+--------+
2892 if (http->ssl && connect_port_is_forbidden(csp))
2894 const char *acceptable_connect_ports =
2895 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
2896 assert(NULL != acceptable_connect_ports);
2897 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
2898 "limit-connect{%s} doesn't allow CONNECT requests to %s",
2899 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
2900 csp->action->flags |= ACTION_BLOCK;
2906 freez(csp->headers->first->str);
2907 build_request_line(csp, fwd, &csp->headers->first->str);
2911 * We have a request. Check if one of the crunchers wants it.
2913 if (crunch_response_triggered(csp, crunchers_all))
2916 * Yes. The client got the crunch response and we're done here.
2921 log_applied_actions(csp->action);
2922 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
2924 if (fwd->forward_host)
2926 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
2927 fwd->forward_host, fwd->forward_port, http->hostport);
2931 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
2934 /* here we connect to the server, gateway, or the forwarder */
2936 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2937 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
2938 && socket_is_still_alive(csp->server_connection.sfd)
2939 && connection_destination_matches(&csp->server_connection, http, fwd))
2941 log_error(LOG_LEVEL_CONNECT,
2942 "Reusing server socket %d connected to %s. Total requests: %u.",
2943 csp->server_connection.sfd, csp->server_connection.host,
2944 csp->server_connection.requests_sent_total);
2948 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2950 #ifdef FEATURE_CONNECTION_SHARING
2951 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2953 remember_connection(&csp->server_connection);
2956 #endif /* def FEATURE_CONNECTION_SHARING */
2958 log_error(LOG_LEVEL_CONNECT,
2959 "Closing server socket %d connected to %s. Total requests: %u.",
2960 csp->server_connection.sfd, csp->server_connection.host,
2961 csp->server_connection.requests_sent_total);
2962 close_socket(csp->server_connection.sfd);
2964 mark_connection_closed(&csp->server_connection);
2966 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2968 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
2970 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
2972 if (fwd->type != SOCKS_NONE)
2975 rsp = error_response(csp, "forwarding-failed");
2977 else if (errno == EINVAL)
2979 rsp = error_response(csp, "no-such-domain");
2983 rsp = error_response(csp, "connect-failed");
2986 /* Write the answer to the client */
2989 send_crunch_response(csp, rsp);
2993 * Temporary workaround to prevent already-read client
2994 * bodies from being parsed as new requests. For now we
2995 * err on the safe side and throw all the following
2996 * requests under the bus, even if no client body has been
2997 * buffered. A compliant client will repeat the dropped
2998 * requests on an untainted connection.
3000 * The proper fix is to discard the no longer needed
3001 * client body in the buffer (if there is one) and to
3002 * continue parsing the bytes that follow.
3004 drain_and_close_socket(csp->cfd);
3005 csp->cfd = JB_INVALID_SOCKET;
3009 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3010 save_connection_destination(csp->server_connection.sfd,
3011 http, fwd, &csp->server_connection);
3012 csp->server_connection.keep_alive_timeout =
3013 (unsigned)csp->config->keep_alive_timeout;
3015 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3017 csp->server_connection.requests_sent_total++;
3019 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
3021 /* Client headers have been sent optimistically */
3022 assert(csp->headers->last == NULL);
3024 else if (fwd->forward_host || (http->ssl == 0))
3026 if (send_http_request(csp))
3028 rsp = error_response(csp, "connect-failed");
3031 send_crunch_response(csp, rsp);
3039 * We're running an SSL tunnel and we're not forwarding,
3040 * so just ditch the client headers, send the "connect succeeded"
3041 * message to the client, flush the rest, and get out of the way.
3043 list_remove_all(csp->headers);
3044 if (write_socket_delayed(csp->cfd, CSUCCEED,
3045 strlen(CSUCCEED), get_write_delay(csp)))
3049 clear_iob(csp->client_iob);
3052 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
3054 /* XXX: should the time start earlier for optimistically sent data? */
3055 csp->server_connection.request_sent = time(NULL);
3057 handle_established_connection(csp);
3058 freez(csp->receive_buffer);
3063 /*********************************************************************
3065 * Function : fuzz_server_response
3067 * Description : Treat the input as a whole server response.
3070 * 1 : csp = Current client state (buffers, headers, etc...)
3071 * 2 : fuzz_input_file = File to read the input from.
3075 *********************************************************************/
3076 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
3078 static struct forward_spec fwd; /* Zero'd due to being static */
3081 if (strcmp(fuzz_input_file, "-") == 0)
3083 /* XXX: Doesn'T work yet. */
3084 csp->server_connection.sfd = 0;
3088 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
3089 if (csp->server_connection.sfd == -1)
3091 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
3096 csp->content_type |= CT_GIF;
3097 csp->action->flags |= ACTION_DEANIMATE;
3098 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
3100 csp->http->path = strdup_or_die("/");
3101 csp->http->host = strdup_or_die("fuzz.example.org");
3102 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
3103 /* Prevent client socket monitoring */
3104 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3105 csp->flags |= CSP_FLAG_CHUNKED;
3107 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
3108 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3110 csp->content_type |= CT_DECLARED|CT_GIF;
3112 csp->config->socket_timeout = 0;
3114 cgi_init_error_messages();
3116 handle_established_connection(csp);
3117 freez(csp->receive_buffer);
3124 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3125 /*********************************************************************
3127 * Function : prepare_csp_for_next_request
3129 * Description : Put the csp in a mostly vergin state.
3132 * 1 : csp = Current client state (buffers, headers, etc...)
3136 *********************************************************************/
3137 static void prepare_csp_for_next_request(struct client_state *csp)
3139 csp->content_type = 0;
3140 csp->content_length = 0;
3141 csp->expected_content_length = 0;
3142 csp->expected_client_content_length = 0;
3143 list_remove_all(csp->headers);
3144 clear_iob(csp->iob);
3145 freez(csp->error_message);
3146 free_http_request(csp->http);
3147 destroy_list(csp->headers);
3148 destroy_list(csp->tags);
3149 #ifdef FEATURE_CLIENT_TAGS
3150 destroy_list(csp->client_tags);
3151 freez(csp->client_address);
3153 free_current_action(csp->action);
3154 if (NULL != csp->fwd)
3156 unload_forward_spec(csp->fwd);
3159 /* XXX: Store per-connection flags someplace else. */
3160 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
3161 #ifdef FEATURE_TOGGLE
3162 if (global_toggle_state)
3163 #endif /* def FEATURE_TOGGLE */
3165 csp->flags |= CSP_FLAG_TOGGLED_ON;
3168 if (csp->client_iob->eod > csp->client_iob->cur)
3170 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
3171 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
3173 assert(bytes_to_shift > 0);
3174 assert(data_length > 0);
3176 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
3177 data_length, bytes_to_shift);
3178 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
3179 csp->client_iob->cur = csp->client_iob->buf;
3180 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
3181 csp->client_iob->eod = csp->client_iob->buf + data_length;
3182 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
3184 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3189 * We mainly care about resetting client_iob->cur so we don't
3190 * waste buffer space at the beginning and don't mess up the
3191 * request restoration done by cgi_show_request().
3193 * Freeing the buffer itself isn't technically necessary,
3194 * but makes debugging more convenient.
3196 clear_iob(csp->client_iob);
3199 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3202 /*********************************************************************
3206 * Description : This is little more than chat. We only "serve" to
3207 * to close (or remember) any socket that chat may have
3211 * 1 : csp = Current client state (buffers, headers, etc...)
3215 *********************************************************************/
3216 static void serve(struct client_state *csp)
3218 int config_file_change_detected = 0; /* Only used for debugging */
3219 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3220 #ifdef FEATURE_CONNECTION_SHARING
3221 static int monitor_thread_running = 0;
3222 #endif /* def FEATURE_CONNECTION_SHARING */
3223 int continue_chatting = 0;
3225 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
3226 csp->ip_addr_str, csp->cfd);
3230 unsigned int latency;
3235 * If the request has been crunched,
3236 * the calculated latency is zero.
3238 latency = (unsigned)(csp->server_connection.response_received -
3239 csp->server_connection.request_sent) / 2;
3241 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3242 && (csp->flags & CSP_FLAG_CRUNCHED)
3243 && (csp->expected_client_content_length != 0))
3245 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
3246 log_error(LOG_LEVEL_CONNECT,
3247 "Tainting client socket %d due to unread data.", csp->cfd);
3250 continue_chatting = (csp->config->feature_flags
3251 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3252 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3253 && (csp->cfd != JB_INVALID_SOCKET)
3254 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3255 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3256 || (csp->flags & CSP_FLAG_CHUNKED));
3258 if (!(csp->flags & CSP_FLAG_CRUNCHED)
3259 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
3261 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
3263 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
3265 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
3266 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3267 || !socket_is_still_alive(csp->server_connection.sfd)
3268 || !(latency < csp->server_connection.keep_alive_timeout))
3270 log_error(LOG_LEVEL_CONNECT,
3271 "Closing server socket %d connected to %s. "
3272 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
3273 csp->server_connection.sfd, csp->server_connection.host,
3274 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3275 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3276 socket_is_still_alive(csp->server_connection.sfd),
3277 csp->server_connection.keep_alive_timeout);
3278 #ifdef FEATURE_CONNECTION_SHARING
3279 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3281 forget_connection(csp->server_connection.sfd);
3283 #endif /* def FEATURE_CONNECTION_SHARING */
3284 close_socket(csp->server_connection.sfd);
3285 mark_connection_closed(&csp->server_connection);
3289 if (continue_chatting && any_loaded_file_changed(csp))
3291 continue_chatting = 0;
3292 config_file_change_detected = 1;
3295 if (continue_chatting)
3297 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
3298 && socket_is_still_alive(csp->cfd))
3300 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
3301 "pipelined on socket %d and the socket is still alive.",
3302 csp->requests_received_total+1, csp->cfd);
3303 prepare_csp_for_next_request(csp);
3307 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3309 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3311 log_error(LOG_LEVEL_CONNECT,
3312 "Waiting for the next client request on socket %d. "
3313 "Keeping the server socket %d to %s open.",
3314 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
3318 log_error(LOG_LEVEL_CONNECT,
3319 "Waiting for the next client request on socket %d. "
3320 "No server socket to keep open.", csp->cfd);
3324 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3325 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
3326 && socket_is_still_alive(csp->cfd))
3328 log_error(LOG_LEVEL_CONNECT,
3329 "Client request %u arrived in time on socket %d.",
3330 csp->requests_received_total+1, csp->cfd);
3331 prepare_csp_for_next_request(csp);
3335 #ifdef FEATURE_CONNECTION_SHARING
3336 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3337 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3338 && (socket_is_still_alive(csp->server_connection.sfd)))
3340 time_t time_open = time(NULL) - csp->server_connection.timestamp;
3342 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3347 remember_connection(&csp->server_connection);
3348 csp->server_connection.sfd = JB_INVALID_SOCKET;
3349 drain_and_close_socket(csp->cfd);
3350 csp->cfd = JB_INVALID_SOCKET;
3351 privoxy_mutex_lock(&connection_reuse_mutex);
3352 if (!monitor_thread_running)
3354 monitor_thread_running = 1;
3355 privoxy_mutex_unlock(&connection_reuse_mutex);
3356 wait_for_alive_connections();
3357 privoxy_mutex_lock(&connection_reuse_mutex);
3358 monitor_thread_running = 0;
3360 privoxy_mutex_unlock(&connection_reuse_mutex);
3362 #endif /* def FEATURE_CONNECTION_SHARING */
3366 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3368 log_error(LOG_LEVEL_CONNECT,
3369 "Closing server socket %d connected to %s. Keep-alive: %u. "
3370 "Tainted: %u. Socket alive: %u. Timeout: %u. "
3371 "Configuration file change detected: %u",
3372 csp->server_connection.sfd, csp->server_connection.host,
3373 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3374 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3375 socket_is_still_alive(csp->server_connection.sfd),
3376 csp->server_connection.keep_alive_timeout,
3377 config_file_change_detected);
3379 } while (continue_chatting);
3383 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3385 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3387 #ifdef FEATURE_CONNECTION_SHARING
3388 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3390 forget_connection(csp->server_connection.sfd);
3392 #endif /* def FEATURE_CONNECTION_SHARING */
3393 close_socket(csp->server_connection.sfd);
3396 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3397 mark_connection_closed(&csp->server_connection);
3400 if (csp->cfd != JB_INVALID_SOCKET)
3402 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3403 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3404 "Configuration file change detected: %u. Requests received: %u.",
3405 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3406 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3407 config_file_change_detected, csp->requests_received_total);
3408 drain_and_close_socket(csp->cfd);
3411 free_csp_resources(csp);
3413 csp->flags &= ~CSP_FLAG_ACTIVE;
3419 /*********************************************************************
3421 * Function : server_thread
3423 * Description : We only exist to call `serve' in a threaded environment.
3426 * 1 : data = Current client state (buffers, headers, etc...)
3428 * Returns : Always 0.
3430 *********************************************************************/
3431 static int32 server_thread(void *data)
3433 serve((struct client_state *) data);
3440 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3441 /*********************************************************************
3445 * Description : Print usage info & exit.
3447 * Parameters : Pointer to argv[0] for identifying ourselves
3451 *********************************************************************/
3452 static void usage(const char *name)
3454 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3455 "Usage: %s [--config-test] "
3458 #endif /* defined(unix) */
3461 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3462 #endif /* defined(unix) */
3463 "[--version] [configfile]\n",
3467 show_fuzz_usage(name);
3470 printf("Aborting\n");
3475 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3478 #ifdef MUTEX_LOCKS_AVAILABLE
3479 /*********************************************************************
3481 * Function : privoxy_mutex_lock
3483 * Description : Locks a mutex.
3486 * 1 : mutex = The mutex to lock.
3488 * Returns : Void. May exit in case of errors.
3490 *********************************************************************/
3491 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3493 #ifdef FEATURE_PTHREAD
3494 int err = pthread_mutex_lock(mutex);
3497 if (mutex != &log_mutex)
3499 log_error(LOG_LEVEL_FATAL,
3500 "Mutex locking failed: %s.\n", strerror(err));
3505 EnterCriticalSection(mutex);
3506 #endif /* def FEATURE_PTHREAD */
3510 /*********************************************************************
3512 * Function : privoxy_mutex_unlock
3514 * Description : Unlocks a mutex.
3517 * 1 : mutex = The mutex to unlock.
3519 * Returns : Void. May exit in case of errors.
3521 *********************************************************************/
3522 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3524 #ifdef FEATURE_PTHREAD
3525 int err = pthread_mutex_unlock(mutex);
3528 if (mutex != &log_mutex)
3530 log_error(LOG_LEVEL_FATAL,
3531 "Mutex unlocking failed: %s.\n", strerror(err));
3536 LeaveCriticalSection(mutex);
3537 #endif /* def FEATURE_PTHREAD */
3541 /*********************************************************************
3543 * Function : privoxy_mutex_init
3545 * Description : Prepares a mutex.
3548 * 1 : mutex = The mutex to initialize.
3550 * Returns : Void. May exit in case of errors.
3552 *********************************************************************/
3553 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3555 #ifdef FEATURE_PTHREAD
3556 int err = pthread_mutex_init(mutex, 0);
3559 printf("Fatal error. Mutex initialization failed: %s.\n",
3564 InitializeCriticalSection(mutex);
3565 #endif /* def FEATURE_PTHREAD */
3567 #endif /* def MUTEX_LOCKS_AVAILABLE */
3569 /*********************************************************************
3571 * Function : initialize_mutexes
3573 * Description : Prepares mutexes if mutex support is available.
3577 * Returns : Void, exits in case of errors.
3579 *********************************************************************/
3580 static void initialize_mutexes(void)
3582 #ifdef MUTEX_LOCKS_AVAILABLE
3584 * Prepare global mutex semaphores
3586 privoxy_mutex_init(&log_mutex);
3587 privoxy_mutex_init(&log_init_mutex);
3588 privoxy_mutex_init(&connection_reuse_mutex);
3589 #ifdef FEATURE_EXTERNAL_FILTERS
3590 privoxy_mutex_init(&external_filter_mutex);
3592 #ifdef FEATURE_CLIENT_TAGS
3593 privoxy_mutex_init(&client_tags_mutex);
3597 * XXX: The assumptions below are a bit naive
3598 * and can cause locks that aren't necessary.
3600 * For example older FreeBSD versions (< 6.x?)
3601 * have no gethostbyname_r, but gethostbyname is
3604 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3605 privoxy_mutex_init(&resolver_mutex);
3606 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3608 * XXX: should we use a single mutex for
3609 * localtime() and gmtime() as well?
3611 #ifndef HAVE_GMTIME_R
3612 privoxy_mutex_init(&gmtime_mutex);
3613 #endif /* ndef HAVE_GMTIME_R */
3615 #ifndef HAVE_LOCALTIME_R
3616 privoxy_mutex_init(&localtime_mutex);
3617 #endif /* ndef HAVE_GMTIME_R */
3619 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
3620 privoxy_mutex_init(&rand_mutex);
3621 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
3623 #endif /* def MUTEX_LOCKS_AVAILABLE */
3626 /*********************************************************************
3630 * Description : Load the config file and start the listen loop.
3631 * This function is a lot more *sane* with the `load_config'
3632 * and `listen_loop' functions; although it stills does
3633 * a *little* too much for my taste.
3636 * 1 : argc = Number of parameters (including $0).
3637 * 2 : argv = Array of (char *)'s to the parameters.
3639 * Returns : 1 if : can't open config file, unrecognized directive,
3640 * stats requested in multi-thread mode, can't open the
3641 * log file, can't open the jar file, listen port is invalid,
3642 * any load fails, and can't bind port.
3644 * Else main never returns, the process must be signaled
3645 * to terminate execution. Or, on Windows, use the
3646 * "File", "Exit" menu option.
3648 *********************************************************************/
3650 int real_main(int argc, char **argv)
3652 int main(int argc, char **argv)
3656 int do_config_test = 0;
3657 #ifndef HAVE_ARC4RANDOM
3658 unsigned int random_seed;
3661 struct passwd *pw = NULL;
3662 struct group *grp = NULL;
3664 char *pre_chroot_nslookup_to_load_resolver = NULL;
3667 char *fuzz_input_type = NULL;
3668 char *fuzz_input_file = NULL;
3675 #if !defined(_WIN32)
3682 /* Prepare mutexes if supported and necessary. */
3683 initialize_mutexes();
3685 /* Enable logging until further notice. */
3689 * Parse the command line arguments
3691 * XXX: simply printing usage information in case of
3692 * invalid arguments isn't particularly user friendly.
3694 while (++argc_pos < argc)
3697 /* Check to see if the service must be installed or uninstalled */
3698 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3700 const char *pName = argv[argc_pos] + 9;
3703 exit((install_service(pName)) ? 0 : 1);
3705 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3707 const char *pName = argv[argc_pos] + 11;
3710 exit((uninstall_service(pName)) ? 0 : 1);
3712 else if (strcmp(argv[argc_pos], "--service") == 0)
3714 bRunAsService = TRUE;
3715 w32_set_service_cwd();
3716 atexit(w32_service_exit_notify);
3719 #endif /* defined(_WIN32) */
3722 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3724 if (strcmp(argv[argc_pos], "--help") == 0)
3729 else if (strcmp(argv[argc_pos], "--version") == 0)
3731 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3737 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3739 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3743 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3745 if (++argc_pos == argc) usage(argv[0]);
3746 pidfile = strdup_or_die(argv[argc_pos]);
3749 else if (strcmp(argv[argc_pos], "--user") == 0)
3754 if (++argc_pos == argc) usage(argv[argc_pos]);
3756 user_arg = strdup_or_die(argv[argc_pos]);
3757 group_name = strchr(user_arg, '.');
3758 if (NULL != group_name)
3760 /* Nul-terminate the user name */
3763 /* Skip the former delimiter to actually reach the group name */
3766 grp = getgrnam(group_name);
3769 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3772 pw = getpwnam(user_arg);
3775 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3781 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3783 if (++argc_pos == argc) usage(argv[0]);
3784 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3787 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3791 #endif /* defined(unix) */
3793 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3798 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
3801 if (argc < argc_pos + 2) usage(argv[0]);
3802 fuzz_input_type = argv[argc_pos];
3804 fuzz_input_file = argv[argc_pos];
3806 else if (strcmp(argv[argc_pos], "--stfu") == 0)
3808 set_debug_level(LOG_LEVEL_STFU);
3811 else if (argc_pos + 1 != argc)
3814 * This is neither the last command line
3815 * option, nor was it recognized before,
3816 * therefore it must be invalid.
3822 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3824 configfile = argv[argc_pos];
3827 } /* -END- while (more arguments) */
3829 show_version(Argv[0]);
3832 if (*configfile != '/')
3834 char cwd[BUFFER_SIZE];
3836 size_t abs_file_size;
3838 /* make config-filename absolute here */
3839 if (NULL == getcwd(cwd, sizeof(cwd)))
3841 perror("failed to get current working directory");
3845 basedir = strdup_or_die(cwd);
3847 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3848 abs_file = malloc_or_die(abs_file_size);
3849 strlcpy(abs_file, basedir, abs_file_size);
3850 strlcat(abs_file, "/", abs_file_size);
3851 strlcat(abs_file, configfile, abs_file_size);
3852 configfile = abs_file;
3854 #endif /* defined unix */
3858 clients->next = NULL;
3860 /* XXX: factor out initialising after the next stable release. */
3865 #ifndef HAVE_ARC4RANDOM
3866 random_seed = (unsigned int)time(NULL);
3868 srandom(random_seed);
3871 #endif /* ifdef HAVE_RANDOM */
3872 #endif /* ifndef HAVE_ARC4RANDOM */
3875 * Unix signal handling
3877 * Catch the abort, interrupt and terminate signals for a graceful exit
3878 * Catch the hangup signal so the errlog can be reopened.
3880 * Ignore the broken pipe signal as connection failures
3881 * are handled when and where they occur without relying
3884 #if !defined(_WIN32) && !defined(__OS2__)
3887 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3889 for (idx = 0; idx < SZ(catched_signals); idx++)
3891 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3892 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3894 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3895 #endif /* ifdef sun */
3897 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3901 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3903 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3907 #else /* ifdef _WIN32 */
3908 # ifdef _WIN_CONSOLE
3910 * We *are* in a windows console app.
3911 * Print a verbose messages about FAQ's and such
3913 printf("%s", win32_blurb);
3914 # endif /* def _WIN_CONSOLE */
3915 #endif /* def _WIN32 */
3918 if (fuzz_input_type != NULL)
3920 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
3922 log_error(LOG_LEVEL_FATAL,
3923 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
3924 "Various data structures are static which is unsafe when using threads.");
3929 exit(NULL == load_config());
3932 /* Initialize the CGI subsystem */
3933 cgi_init_error_messages();
3936 * If running on unix and without the --no-daemon
3937 * option, become a daemon. I.e. fork, detach
3938 * from tty and get process group leadership
3947 if (pid < 0) /* error */
3952 else if (pid != 0) /* parent */
3957 * must check for errors
3958 * child died due to missing files aso
3961 wpid = waitpid(pid, &status, WNOHANG);
3973 * stderr (fd 2) will be closed later on,
3974 * when the config file has been parsed.
3980 * Reserve fd 0 and 1 to prevent abort() and friends
3981 * from sending stuff to the clients or servers.
3983 fd = open("/dev/null", O_RDONLY);
3986 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3990 if (dup2(fd, 0) == -1)
3992 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3996 fd = open("/dev/null", O_WRONLY);
3999 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4003 if (dup2(fd, 1) == -1)
4005 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
4010 #ifdef FEATURE_EXTERNAL_FILTERS
4011 for (fd = 0; fd < 3; fd++)
4013 mark_socket_for_close_on_execute(fd);
4019 } /* -END- if (daemon_mode) */
4022 * As soon as we have written the PID file, we can switch
4023 * to the user and group ID indicated by the --user option
4025 if (pidfile != NULL)
4027 write_pid_file(pidfile);
4031 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
4033 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
4037 if (setgroups(1, &grp->gr_gid))
4039 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
4042 else if (initgroups(pw->pw_name, pw->pw_gid))
4044 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
4050 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
4052 /* Read the time zone file from /etc before doing chroot. */
4054 if (NULL != pre_chroot_nslookup_to_load_resolver
4055 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
4057 /* Initialize resolver library. */
4058 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
4060 if (chroot(pw->pw_dir) < 0)
4062 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
4066 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
4069 if (setuid(pw->pw_uid))
4071 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
4075 char putenv_dummy[64];
4077 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
4078 if (putenv(putenv_dummy) != 0)
4080 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
4083 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
4084 if (putenv(putenv_dummy) != 0)
4086 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
4092 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
4095 #endif /* defined unix */
4098 /* This will be FALSE unless the command line specified --service
4102 /* Yup, so now we must attempt to establish a connection
4103 * with the service dispatcher. This will only work if this
4104 * process was launched by the service control manager to
4105 * actually run as a service. If this isn't the case, i've
4106 * known it take around 30 seconds or so for the call to return.
4109 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
4110 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
4112 /* Service has run, and at this point is now being stopped, so just return */
4117 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
4119 /* An error occurred. Usually it's because --service was wrongly specified
4120 * and we were unable to connect to the Service Control Dispatcher because
4121 * it wasn't expecting us and is therefore not listening.
4123 * For now, just continue below to call the listen_loop function.
4126 #endif /* def _WIN32 */
4136 /*********************************************************************
4138 * Function : bind_port_helper
4140 * Description : Bind the listen port. Handles logging, and aborts
4144 * 1 : haddr = Host address to bind to. Use NULL to bind to
4146 * 2 : hport = Specifies port to bind to.
4147 * 3 : backlog = Listen backlog.
4149 * Returns : Port that was opened.
4151 *********************************************************************/
4152 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
4157 result = bind_port(haddr, hport, backlog, &bfd);
4161 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
4165 log_error(LOG_LEVEL_FATAL,
4166 "can't bind to %s:%d: There may be another Privoxy "
4167 "or some other proxy running on port %d",
4168 bind_address, hport, hport);
4171 log_error(LOG_LEVEL_FATAL,
4172 "can't bind to %s:%d: The hostname is not resolvable",
4173 bind_address, hport);
4176 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
4177 bind_address, hport);
4180 /* shouldn't get here */
4181 return JB_INVALID_SOCKET;
4186 if (bfd >= FD_SETSIZE)
4188 log_error(LOG_LEVEL_FATAL,
4189 "Bind socket number too high to use select(): %d >= %d",
4197 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
4202 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
4210 /*********************************************************************
4212 * Function : bind_ports_helper
4214 * Description : Bind the listen ports. Handles logging, and aborts
4218 * 1 : config = Privoxy configuration. Specifies ports
4220 * 2 : sockets = Preallocated array of opened sockets
4221 * corresponding to specification in config.
4222 * All non-opened sockets will be set to
4223 * JB_INVALID_SOCKET.
4225 * Returns : Nothing. Inspect sockets argument.
4227 *********************************************************************/
4228 static void bind_ports_helper(struct configuration_spec * config,
4229 jb_socket sockets[])
4233 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4235 if (config->hport[i])
4237 sockets[i] = bind_port_helper(config->haddr[i],
4238 config->hport[i], config->listen_backlog);
4239 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
4240 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
4242 struct accept_filter_arg af_options;
4243 bzero(&af_options, sizeof(af_options));
4244 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
4245 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
4246 sizeof(af_options)))
4248 log_error(LOG_LEVEL_ERROR,
4249 "Enabling accept filter for socket %d failed: %E", sockets[i]);
4256 sockets[i] = JB_INVALID_SOCKET;
4259 config->need_bind = 0;
4263 /*********************************************************************
4265 * Function : close_ports_helper
4267 * Description : Close listenings ports.
4270 * 1 : sockets = Array of opened and non-opened sockets to
4271 * close. All sockets will be set to
4272 * JB_INVALID_SOCKET.
4274 * Returns : Nothing.
4276 *********************************************************************/
4277 static void close_ports_helper(jb_socket sockets[])
4281 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4283 if (JB_INVALID_SOCKET != sockets[i])
4285 close_socket(sockets[i]);
4287 sockets[i] = JB_INVALID_SOCKET;
4293 /* Without this simple workaround we get this compiler warning from _beginthread
4294 * warning C4028: formal parameter 1 different from declaration
4296 void w32_service_listen_loop(void *p)
4300 #endif /* def _WIN32 */
4303 /*********************************************************************
4305 * Function : listen_loop
4307 * Description : bind the listen port and enter a "FOREVER" listening loop.
4313 *********************************************************************/
4314 static void listen_loop(void)
4316 struct client_states *csp_list = NULL;
4317 struct client_state *csp = NULL;
4318 jb_socket bfds[MAX_LISTENING_SOCKETS];
4319 struct configuration_spec *config;
4320 unsigned int active_threads = 0;
4321 #if defined(FEATURE_PTHREAD)
4322 pthread_attr_t attrs;
4324 pthread_attr_init(&attrs);
4325 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4328 config = load_config();
4330 #ifdef FEATURE_CONNECTION_SHARING
4332 * XXX: Should be relocated once it no
4333 * longer needs to emit log messages.
4335 initialize_reusable_connections();
4336 #endif /* def FEATURE_CONNECTION_SHARING */
4338 bind_ports_helper(config, bfds);
4340 #ifdef FEATURE_GRACEFUL_TERMINATION
4341 while (!g_terminate)
4346 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
4347 while (waitpid(-1, NULL, WNOHANG) > 0)
4349 /* zombie children */
4351 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
4354 * Free data that was used by died threads
4356 active_threads = sweep();
4360 * Re-open the errlog after HUP signal
4362 if (received_hup_signal)
4364 if (NULL != config->logfile)
4366 init_error_log(Argv[0], config->logfile);
4368 received_hup_signal = 0;
4372 csp_list = zalloc_or_die(sizeof(*csp_list));
4373 csp = &csp_list->csp;
4375 log_error(LOG_LEVEL_CONNECT,
4376 "Waiting for the next client connection. Currently active threads: %d",
4380 * This config may be outdated, but for accept_connection()
4381 * it's fresh enough.
4383 csp->config = config;
4385 if (!accept_connection(csp, bfds))
4387 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
4392 csp->flags |= CSP_FLAG_ACTIVE;
4393 csp->server_connection.sfd = JB_INVALID_SOCKET;
4395 csp->config = config = load_config();
4397 if (config->need_bind)
4400 * Since we were listening to the "old port", we will not see
4401 * a "listen" param change until the next request. So, at
4402 * least 1 more request must be made for us to find the new
4403 * setting. I am simply closing the old socket and binding the
4406 * Which-ever is correct, we will serve 1 more page via the
4407 * old settings. This should probably be a "show-status"
4408 * request. This should not be a so common of an operation
4409 * that this will hurt people's feelings.
4412 close_ports_helper(bfds);
4414 bind_ports_helper(config, bfds);
4417 #ifdef FEATURE_TOGGLE
4418 if (global_toggle_state)
4419 #endif /* def FEATURE_TOGGLE */
4421 csp->flags |= CSP_FLAG_TOGGLED_ON;
4424 if (run_loader(csp))
4426 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
4427 /* Never get here - LOG_LEVEL_FATAL causes program exit */
4431 if (block_acl(NULL,csp))
4433 log_error(LOG_LEVEL_CONNECT,
4434 "Connection from %s on %s (socket %d) dropped due to ACL",
4435 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
4436 close_socket(csp->cfd);
4437 freez(csp->ip_addr_str);
4438 freez(csp->listen_addr_str);
4442 #endif /* def FEATURE_ACL */
4444 if ((0 != config->max_client_connections)
4445 && (active_threads >= config->max_client_connections))
4447 log_error(LOG_LEVEL_CONNECT,
4448 "Rejecting connection from %s. Maximum number of connections reached.",
4450 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4451 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
4452 close_socket(csp->cfd);
4453 freez(csp->ip_addr_str);
4454 freez(csp->listen_addr_str);
4459 /* add it to the list of clients */
4460 csp_list->next = clients->next;
4461 clients->next = csp_list;
4463 if (config->multi_threaded)
4467 /* this is a switch () statement in the C preprocessor - ugh */
4468 #undef SELECTED_ONE_OPTION
4470 /* Use Pthreads in preference to native code */
4471 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
4472 #define SELECTED_ONE_OPTION
4474 pthread_t the_thread;
4476 errno = pthread_create(&the_thread, &attrs,
4477 (void * (*)(void *))serve, csp);
4478 child_id = errno ? -1 : 0;
4482 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
4483 #define SELECTED_ONE_OPTION
4484 child_id = _beginthread(
4485 (void (*)(void *))serve,
4490 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
4491 #define SELECTED_ONE_OPTION
4492 child_id = _beginthread(
4493 (void(* _Optlink)(void*))serve,
4499 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
4500 #define SELECTED_ONE_OPTION
4502 thread_id tid = spawn_thread
4503 (server_thread, "server", B_NORMAL_PRIORITY, csp);
4505 if ((tid >= 0) && (resume_thread(tid) == B_OK))
4507 child_id = (int) tid;
4516 #if !defined(SELECTED_ONE_OPTION)
4519 /* This block is only needed when using fork().
4520 * When using threads, the server thread was
4521 * created and run by the call to _beginthread().
4523 if (child_id == 0) /* child */
4526 #ifdef FEATURE_TOGGLE
4527 int inherited_toggle_state = global_toggle_state;
4528 #endif /* def FEATURE_TOGGLE */
4533 * If we've been toggled or we've blocked the request, tell Mom
4536 #ifdef FEATURE_TOGGLE
4537 if (inherited_toggle_state != global_toggle_state)
4539 rc |= RC_FLAG_TOGGLED;
4541 #endif /* def FEATURE_TOGGLE */
4543 #ifdef FEATURE_STATISTICS
4544 if (csp->flags & CSP_FLAG_REJECTED)
4546 rc |= RC_FLAG_BLOCKED;
4548 #endif /* ndef FEATURE_STATISTICS */
4552 else if (child_id > 0) /* parent */
4554 /* in a fork()'d environment, the parent's
4555 * copy of the client socket and the CSP
4559 #if !defined(_WIN32) && !defined(__CYGWIN__)
4561 wait(&child_status);
4564 * Evaluate child's return code: If the child has
4565 * - been toggled, toggle ourselves
4566 * - blocked its request, bump up the stats counter
4569 #ifdef FEATURE_TOGGLE
4570 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4572 global_toggle_state = !global_toggle_state;
4574 #endif /* def FEATURE_TOGGLE */
4576 #ifdef FEATURE_STATISTICS
4578 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4582 #endif /* def FEATURE_STATISTICS */
4584 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4585 close_socket(csp->cfd);
4586 csp->flags &= ~CSP_FLAG_ACTIVE;
4590 #undef SELECTED_ONE_OPTION
4591 /* end of cpp switch () */
4596 * Spawning the child failed, assume it's because
4597 * there are too many children running already.
4598 * XXX: If you assume ...
4600 log_error(LOG_LEVEL_ERROR,
4601 "Unable to take any additional connections: %E. Active threads: %d",
4603 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4604 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
4605 close_socket(csp->cfd);
4606 csp->flags &= ~CSP_FLAG_ACTIVE;
4615 #if defined(FEATURE_PTHREAD)
4616 pthread_attr_destroy(&attrs);
4619 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4621 /* Clean up. Aim: free all memory (no leaks) */
4622 #ifdef FEATURE_GRACEFUL_TERMINATION
4624 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4626 unload_current_config_file();
4627 unload_current_actions_file();
4628 unload_current_re_filterfile();
4629 #ifdef FEATURE_TRUST
4630 unload_current_trust_file();
4633 if (config->multi_threaded)
4640 } while ((clients->next != NULL) && (--i > 0));
4644 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4654 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4655 /* Cleanup - remove taskbar icon etc. */
4660 #endif /* FEATURE_GRACEFUL_TERMINATION */