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-2018 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_CONNECT,
842 "Couldn't deliver the error message for %s through client socket %d: %E",
843 http->url, csp->cfd);
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 an 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_iob(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_iob(csp->cfd, csp->iob, write_delay)) < 0)
2526 || write_socket_delayed(csp->cfd, csp->receive_buffer,
2527 (size_t)len, write_delay))
2529 log_error(LOG_LEVEL_CONNECT,
2530 "Flush header and buffers to client failed: %E");
2532 mark_server_socket_tainted(csp);
2537 * Reset the byte_count to the amount of bytes
2538 * we just flushed. len will be added a few lines below,
2539 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2541 byte_count = (unsigned long long)flushed;
2543 buffer_and_filter_content = 0;
2549 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
2550 (size_t)len, write_delay))
2552 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2553 mark_server_socket_tainted(csp);
2557 byte_count += (unsigned long long)len;
2563 * We're still looking for the end of the server's header.
2564 * Buffer up the data we just read. If that fails, there's
2565 * little we can do but send our static out-of-memory page.
2567 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
2569 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2570 rsp = cgi_error_memory();
2571 send_crunch_response(csp, rsp);
2572 mark_server_socket_tainted(csp);
2576 /* Convert iob into something sed() can digest */
2577 if (JB_ERR_PARSE == get_server_headers(csp))
2582 * Well, we tried our MS IIS/5 hack and it didn't work.
2583 * The header is incomplete and there isn't anything
2584 * we can do about it.
2586 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2587 "Applying the MS IIS5 hack didn't help.");
2588 log_error(LOG_LEVEL_CLF,
2589 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2590 write_socket_delayed(csp->cfd,
2591 INVALID_SERVER_HEADERS_RESPONSE,
2592 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
2593 mark_server_socket_tainted(csp);
2599 * Since we have to wait for more from the server before
2600 * we can parse the headers we just continue here.
2602 log_error(LOG_LEVEL_CONNECT,
2603 "Continuing buffering server headers from socket %d. "
2604 "Bytes most recently read: %d.", csp->cfd, len);
2611 * Account for the content bytes we
2612 * might have gotten with the headers.
2614 assert(csp->iob->eod >= csp->iob->cur);
2615 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2618 /* Did we actually get anything? */
2619 if (NULL == csp->headers->first)
2621 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2623 log_error(LOG_LEVEL_ERROR,
2624 "No server or forwarder response received on socket %d. "
2625 "Closing client socket %d without sending data.",
2626 csp->server_connection.sfd, csp->cfd);
2627 log_error(LOG_LEVEL_CLF,
2628 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2632 log_error(LOG_LEVEL_ERROR,
2633 "No server or forwarder response received on socket %d.",
2634 csp->server_connection.sfd);
2635 send_crunch_response(csp, error_response(csp, "no-server-data"));
2637 free_http_request(http);
2638 mark_server_socket_tainted(csp);
2642 assert(csp->headers->first->str);
2644 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2645 strncmpic(csp->headers->first->str, "ICY", 3))
2648 * It doesn't look like a HTTP (or Shoutcast) response:
2649 * tell the client and log the problem.
2651 if (strlen(csp->headers->first->str) > 30)
2653 csp->headers->first->str[30] = '\0';
2655 log_error(LOG_LEVEL_ERROR,
2656 "Invalid server or forwarder response. Starts with: %s",
2657 csp->headers->first->str);
2658 log_error(LOG_LEVEL_CLF,
2659 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2660 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2661 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
2662 free_http_request(http);
2663 mark_server_socket_tainted(csp);
2668 * We have now received the entire server header,
2669 * filter it and send the result to the client
2671 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2673 log_error(LOG_LEVEL_CLF,
2674 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2675 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2676 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
2677 free_http_request(http);
2678 mark_server_socket_tainted(csp);
2681 hdr = list_to_text(csp->headers);
2684 /* FIXME Should handle error properly */
2685 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2688 if ((csp->flags & CSP_FLAG_CHUNKED)
2689 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2690 && ((csp->iob->eod - csp->iob->cur) >= 5)
2691 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2693 log_error(LOG_LEVEL_CONNECT,
2694 "Looks like we got the last chunk together with "
2695 "the server headers. We better stop reading.");
2696 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2697 csp->expected_content_length = byte_count;
2698 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2701 csp->server_connection.response_received = time(NULL);
2703 if (crunch_response_triggered(csp, crunchers_light))
2706 * One of the tags created by a server-header
2707 * tagger triggered a crunch. We already
2708 * delivered the crunch response to the client
2709 * and are done here after cleaning up.
2712 mark_server_socket_tainted(csp);
2715 /* Buffer and pcrs filter this if appropriate. */
2717 if (!http->ssl) /* We talk plaintext */
2719 buffer_and_filter_content = content_requires_filtering(csp);
2722 * Only write if we're not buffering for content modification
2724 if (!buffer_and_filter_content)
2727 * Write the server's (modified) header to
2728 * the client (along with anything else that
2729 * may be in the buffer)
2732 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
2733 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
2735 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2738 * The write failed, so don't bother mentioning it
2739 * to the client... it probably can't hear us anyway.
2742 mark_server_socket_tainted(csp);
2747 /* we're finished with the server's header */
2753 * If this was a MS IIS/5 hack then it means the server
2754 * has already closed the connection. Nothing more to read.
2759 log_error(LOG_LEVEL_ERROR,
2760 "Closed server connection detected. "
2761 "Applying the MS IIS5 hack didn't help.");
2762 log_error(LOG_LEVEL_CLF,
2763 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2764 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2765 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
2766 mark_server_socket_tainted(csp);
2772 mark_server_socket_tainted(csp);
2773 return; /* huh? we should never get here */
2776 if (csp->content_length == 0)
2779 * If Privoxy didn't recalculate the Content-Length,
2780 * byte_count is still correct.
2782 csp->content_length = byte_count;
2785 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2786 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2787 && (csp->expected_content_length != byte_count))
2789 log_error(LOG_LEVEL_CONNECT,
2790 "Received %llu bytes while expecting %llu.",
2791 byte_count, csp->expected_content_length);
2792 mark_server_socket_tainted(csp);
2796 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2797 csp->ip_addr_str, http->ocmd, csp->content_length);
2799 csp->server_connection.timestamp = time(NULL);
2803 /*********************************************************************
2807 * Description : Once a connection from the client has been accepted,
2808 * this function is called (via serve()) to handle the
2809 * main business of the communication. This function
2810 * returns after dealing with a single request. It can
2811 * be called multiple times with the same client socket
2812 * if the client is keeping the connection alive.
2814 * The decision whether or not a client connection will
2815 * be kept alive is up to the caller which also must
2816 * close the client socket when done.
2818 * FIXME: chat is nearly thousand lines long.
2822 * 1 : csp = Current client state (buffers, headers, etc...)
2824 * Returns : Nothing.
2826 *********************************************************************/
2827 static void chat(struct client_state *csp)
2829 const struct forward_spec *fwd;
2830 struct http_request *http;
2831 /* Skeleton for HTTP response, if we should intercept the request */
2832 struct http_response *rsp;
2836 if (receive_client_request(csp) != JB_ERR_OK)
2840 if (parse_client_request(csp) != JB_ERR_OK)
2845 /* decide how to route the HTTP request */
2846 fwd = forward_url(csp, http);
2849 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2850 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2855 * build the http request to send to the server
2856 * we have to do one of the following:
2858 * create = use the original HTTP request to create a new
2859 * HTTP request that has either the path component
2860 * without the http://domainspec (w/path) or the
2861 * full orininal URL (w/url)
2862 * Note that the path and/or the HTTP version may
2863 * have been altered by now.
2865 * connect = Open a socket to the host:port of the server
2866 * and short-circuit server and client socket.
2868 * pass = Pass the request unchanged if forwarding a CONNECT
2869 * request to a parent proxy. Note that we'll be sending
2870 * the CFAIL message ourselves if connecting to the parent
2871 * fails, but we won't send a CSUCCEED message if it works,
2872 * since that would result in a double message (ours and the
2873 * parent's). After sending the request to the parent, we simply
2876 * here's the matrix:
2879 * +--------+--------+
2881 * 0 | create | connect|
2883 * Forwarding +--------+--------+
2885 * 1 | create | pass |
2887 * +--------+--------+
2891 if (http->ssl && connect_port_is_forbidden(csp))
2893 const char *acceptable_connect_ports =
2894 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
2895 assert(NULL != acceptable_connect_ports);
2896 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
2897 "limit-connect{%s} doesn't allow CONNECT requests to %s",
2898 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
2899 csp->action->flags |= ACTION_BLOCK;
2905 freez(csp->headers->first->str);
2906 build_request_line(csp, fwd, &csp->headers->first->str);
2910 * We have a request. Check if one of the crunchers wants it.
2912 if (crunch_response_triggered(csp, crunchers_all))
2915 * Yes. The client got the crunch response and we're done here.
2920 log_applied_actions(csp->action);
2921 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
2923 if (fwd->forward_host)
2925 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
2926 fwd->forward_host, fwd->forward_port, http->hostport);
2930 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
2933 /* here we connect to the server, gateway, or the forwarder */
2935 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2936 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
2937 && socket_is_still_alive(csp->server_connection.sfd)
2938 && connection_destination_matches(&csp->server_connection, http, fwd))
2940 log_error(LOG_LEVEL_CONNECT,
2941 "Reusing server socket %d connected to %s. Total requests: %u.",
2942 csp->server_connection.sfd, csp->server_connection.host,
2943 csp->server_connection.requests_sent_total);
2947 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2949 #ifdef FEATURE_CONNECTION_SHARING
2950 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2952 remember_connection(&csp->server_connection);
2955 #endif /* def FEATURE_CONNECTION_SHARING */
2957 log_error(LOG_LEVEL_CONNECT,
2958 "Closing server socket %d connected to %s. Total requests: %u.",
2959 csp->server_connection.sfd, csp->server_connection.host,
2960 csp->server_connection.requests_sent_total);
2961 close_socket(csp->server_connection.sfd);
2963 mark_connection_closed(&csp->server_connection);
2965 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2967 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
2969 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
2971 if (fwd->type != SOCKS_NONE)
2974 rsp = error_response(csp, "forwarding-failed");
2976 else if (errno == EINVAL)
2978 rsp = error_response(csp, "no-such-domain");
2982 rsp = error_response(csp, "connect-failed");
2985 /* Write the answer to the client */
2988 send_crunch_response(csp, rsp);
2992 * Temporary workaround to prevent already-read client
2993 * bodies from being parsed as new requests. For now we
2994 * err on the safe side and throw all the following
2995 * requests under the bus, even if no client body has been
2996 * buffered. A compliant client will repeat the dropped
2997 * requests on an untainted connection.
2999 * The proper fix is to discard the no longer needed
3000 * client body in the buffer (if there is one) and to
3001 * continue parsing the bytes that follow.
3003 drain_and_close_socket(csp->cfd);
3004 csp->cfd = JB_INVALID_SOCKET;
3008 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3009 save_connection_destination(csp->server_connection.sfd,
3010 http, fwd, &csp->server_connection);
3011 csp->server_connection.keep_alive_timeout =
3012 (unsigned)csp->config->keep_alive_timeout;
3014 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3016 csp->server_connection.requests_sent_total++;
3018 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
3020 /* Client headers have been sent optimistically */
3021 assert(csp->headers->last == NULL);
3023 else if (fwd->forward_host || (http->ssl == 0))
3025 if (send_http_request(csp))
3027 rsp = error_response(csp, "connect-failed");
3030 send_crunch_response(csp, rsp);
3038 * We're running an SSL tunnel and we're not forwarding,
3039 * so just ditch the client headers, send the "connect succeeded"
3040 * message to the client, flush the rest, and get out of the way.
3042 list_remove_all(csp->headers);
3043 if (write_socket_delayed(csp->cfd, CSUCCEED,
3044 strlen(CSUCCEED), get_write_delay(csp)))
3048 clear_iob(csp->client_iob);
3051 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
3053 /* XXX: should the time start earlier for optimistically sent data? */
3054 csp->server_connection.request_sent = time(NULL);
3056 handle_established_connection(csp);
3057 freez(csp->receive_buffer);
3062 /*********************************************************************
3064 * Function : fuzz_server_response
3066 * Description : Treat the input as a whole server response.
3069 * 1 : csp = Current client state (buffers, headers, etc...)
3070 * 2 : fuzz_input_file = File to read the input from.
3074 *********************************************************************/
3075 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
3077 static struct forward_spec fwd; /* Zero'd due to being static */
3080 if (strcmp(fuzz_input_file, "-") == 0)
3082 /* XXX: Doesn'T work yet. */
3083 csp->server_connection.sfd = 0;
3087 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
3088 if (csp->server_connection.sfd == -1)
3090 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
3095 csp->content_type |= CT_GIF;
3096 csp->action->flags |= ACTION_DEANIMATE;
3097 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
3099 csp->http->path = strdup_or_die("/");
3100 csp->http->host = strdup_or_die("fuzz.example.org");
3101 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
3102 /* Prevent client socket monitoring */
3103 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3104 csp->flags |= CSP_FLAG_CHUNKED;
3106 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
3107 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3109 csp->content_type |= CT_DECLARED|CT_GIF;
3111 csp->config->socket_timeout = 0;
3113 cgi_init_error_messages();
3115 handle_established_connection(csp);
3116 freez(csp->receive_buffer);
3123 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3124 /*********************************************************************
3126 * Function : prepare_csp_for_next_request
3128 * Description : Put the csp in a mostly vergin state.
3131 * 1 : csp = Current client state (buffers, headers, etc...)
3135 *********************************************************************/
3136 static void prepare_csp_for_next_request(struct client_state *csp)
3138 csp->content_type = 0;
3139 csp->content_length = 0;
3140 csp->expected_content_length = 0;
3141 csp->expected_client_content_length = 0;
3142 list_remove_all(csp->headers);
3143 clear_iob(csp->iob);
3144 freez(csp->error_message);
3145 free_http_request(csp->http);
3146 destroy_list(csp->headers);
3147 destroy_list(csp->tags);
3148 #ifdef FEATURE_CLIENT_TAGS
3149 destroy_list(csp->client_tags);
3150 freez(csp->client_address);
3152 free_current_action(csp->action);
3153 if (NULL != csp->fwd)
3155 unload_forward_spec(csp->fwd);
3158 /* XXX: Store per-connection flags someplace else. */
3159 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
3160 #ifdef FEATURE_TOGGLE
3161 if (global_toggle_state)
3162 #endif /* def FEATURE_TOGGLE */
3164 csp->flags |= CSP_FLAG_TOGGLED_ON;
3167 if (csp->client_iob->eod > csp->client_iob->cur)
3169 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
3170 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
3172 assert(bytes_to_shift > 0);
3173 assert(data_length > 0);
3175 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
3176 data_length, bytes_to_shift);
3177 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
3178 csp->client_iob->cur = csp->client_iob->buf;
3179 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
3180 csp->client_iob->eod = csp->client_iob->buf + data_length;
3181 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
3183 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3188 * We mainly care about resetting client_iob->cur so we don't
3189 * waste buffer space at the beginning and don't mess up the
3190 * request restoration done by cgi_show_request().
3192 * Freeing the buffer itself isn't technically necessary,
3193 * but makes debugging more convenient.
3195 clear_iob(csp->client_iob);
3198 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3201 /*********************************************************************
3205 * Description : This is little more than chat. We only "serve" to
3206 * to close (or remember) any socket that chat may have
3210 * 1 : csp = Current client state (buffers, headers, etc...)
3214 *********************************************************************/
3215 static void serve(struct client_state *csp)
3217 int config_file_change_detected = 0; /* Only used for debugging */
3218 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3219 #ifdef FEATURE_CONNECTION_SHARING
3220 static int monitor_thread_running = 0;
3221 #endif /* def FEATURE_CONNECTION_SHARING */
3222 int continue_chatting = 0;
3224 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
3225 csp->ip_addr_str, csp->cfd);
3229 unsigned int latency;
3234 * If the request has been crunched,
3235 * the calculated latency is zero.
3237 latency = (unsigned)(csp->server_connection.response_received -
3238 csp->server_connection.request_sent) / 2;
3240 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3241 && (csp->flags & CSP_FLAG_CRUNCHED)
3242 && (csp->expected_client_content_length != 0))
3244 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
3245 log_error(LOG_LEVEL_CONNECT,
3246 "Tainting client socket %d due to unread data.", csp->cfd);
3249 continue_chatting = (csp->config->feature_flags
3250 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3251 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3252 && (csp->cfd != JB_INVALID_SOCKET)
3253 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3254 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3255 || (csp->flags & CSP_FLAG_CHUNKED));
3257 if (!(csp->flags & CSP_FLAG_CRUNCHED)
3258 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
3260 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
3262 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
3264 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
3265 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3266 || !socket_is_still_alive(csp->server_connection.sfd)
3267 || !(latency < csp->server_connection.keep_alive_timeout))
3269 log_error(LOG_LEVEL_CONNECT,
3270 "Closing server socket %d connected to %s. "
3271 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
3272 csp->server_connection.sfd, csp->server_connection.host,
3273 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3274 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3275 socket_is_still_alive(csp->server_connection.sfd),
3276 csp->server_connection.keep_alive_timeout);
3277 #ifdef FEATURE_CONNECTION_SHARING
3278 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3280 forget_connection(csp->server_connection.sfd);
3282 #endif /* def FEATURE_CONNECTION_SHARING */
3283 close_socket(csp->server_connection.sfd);
3284 mark_connection_closed(&csp->server_connection);
3288 if (continue_chatting && any_loaded_file_changed(csp))
3290 continue_chatting = 0;
3291 config_file_change_detected = 1;
3294 if (continue_chatting)
3296 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
3297 && socket_is_still_alive(csp->cfd))
3299 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
3300 "pipelined on socket %d and the socket is still alive.",
3301 csp->requests_received_total+1, csp->cfd);
3302 prepare_csp_for_next_request(csp);
3306 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3308 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3310 log_error(LOG_LEVEL_CONNECT,
3311 "Waiting for the next client request on socket %d. "
3312 "Keeping the server socket %d to %s open.",
3313 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
3317 log_error(LOG_LEVEL_CONNECT,
3318 "Waiting for the next client request on socket %d. "
3319 "No server socket to keep open.", csp->cfd);
3323 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3324 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
3325 && socket_is_still_alive(csp->cfd))
3327 log_error(LOG_LEVEL_CONNECT,
3328 "Client request %u arrived in time on socket %d.",
3329 csp->requests_received_total+1, csp->cfd);
3330 prepare_csp_for_next_request(csp);
3334 #ifdef FEATURE_CONNECTION_SHARING
3335 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3336 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3337 && (socket_is_still_alive(csp->server_connection.sfd)))
3339 time_t time_open = time(NULL) - csp->server_connection.timestamp;
3341 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3346 remember_connection(&csp->server_connection);
3347 csp->server_connection.sfd = JB_INVALID_SOCKET;
3348 drain_and_close_socket(csp->cfd);
3349 csp->cfd = JB_INVALID_SOCKET;
3350 privoxy_mutex_lock(&connection_reuse_mutex);
3351 if (!monitor_thread_running)
3353 monitor_thread_running = 1;
3354 privoxy_mutex_unlock(&connection_reuse_mutex);
3355 wait_for_alive_connections();
3356 privoxy_mutex_lock(&connection_reuse_mutex);
3357 monitor_thread_running = 0;
3359 privoxy_mutex_unlock(&connection_reuse_mutex);
3361 #endif /* def FEATURE_CONNECTION_SHARING */
3365 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3367 log_error(LOG_LEVEL_CONNECT,
3368 "Closing server socket %d connected to %s. Keep-alive: %u. "
3369 "Tainted: %u. Socket alive: %u. Timeout: %u. "
3370 "Configuration file change detected: %u",
3371 csp->server_connection.sfd, csp->server_connection.host,
3372 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3373 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3374 socket_is_still_alive(csp->server_connection.sfd),
3375 csp->server_connection.keep_alive_timeout,
3376 config_file_change_detected);
3378 } while (continue_chatting);
3382 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3384 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3386 #ifdef FEATURE_CONNECTION_SHARING
3387 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3389 forget_connection(csp->server_connection.sfd);
3391 #endif /* def FEATURE_CONNECTION_SHARING */
3392 close_socket(csp->server_connection.sfd);
3395 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3396 mark_connection_closed(&csp->server_connection);
3399 if (csp->cfd != JB_INVALID_SOCKET)
3401 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3402 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3403 "Configuration file change detected: %u. Requests received: %u.",
3404 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3405 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3406 config_file_change_detected, csp->requests_received_total);
3407 drain_and_close_socket(csp->cfd);
3410 free_csp_resources(csp);
3412 csp->flags &= ~CSP_FLAG_ACTIVE;
3418 /*********************************************************************
3420 * Function : server_thread
3422 * Description : We only exist to call `serve' in a threaded environment.
3425 * 1 : data = Current client state (buffers, headers, etc...)
3427 * Returns : Always 0.
3429 *********************************************************************/
3430 static int32 server_thread(void *data)
3432 serve((struct client_state *) data);
3439 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3440 /*********************************************************************
3444 * Description : Print usage info & exit.
3446 * Parameters : Pointer to argv[0] for identifying ourselves
3450 *********************************************************************/
3451 static void usage(const char *name)
3453 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3454 "Usage: %s [--config-test] "
3457 #endif /* defined(unix) */
3460 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3461 #endif /* defined(unix) */
3462 "[--version] [configfile]\n",
3466 show_fuzz_usage(name);
3469 printf("Aborting\n");
3474 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3477 #ifdef MUTEX_LOCKS_AVAILABLE
3478 /*********************************************************************
3480 * Function : privoxy_mutex_lock
3482 * Description : Locks a mutex.
3485 * 1 : mutex = The mutex to lock.
3487 * Returns : Void. May exit in case of errors.
3489 *********************************************************************/
3490 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3492 #ifdef FEATURE_PTHREAD
3493 int err = pthread_mutex_lock(mutex);
3496 if (mutex != &log_mutex)
3498 log_error(LOG_LEVEL_FATAL,
3499 "Mutex locking failed: %s.\n", strerror(err));
3504 EnterCriticalSection(mutex);
3505 #endif /* def FEATURE_PTHREAD */
3509 /*********************************************************************
3511 * Function : privoxy_mutex_unlock
3513 * Description : Unlocks a mutex.
3516 * 1 : mutex = The mutex to unlock.
3518 * Returns : Void. May exit in case of errors.
3520 *********************************************************************/
3521 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3523 #ifdef FEATURE_PTHREAD
3524 int err = pthread_mutex_unlock(mutex);
3527 if (mutex != &log_mutex)
3529 log_error(LOG_LEVEL_FATAL,
3530 "Mutex unlocking failed: %s.\n", strerror(err));
3535 LeaveCriticalSection(mutex);
3536 #endif /* def FEATURE_PTHREAD */
3540 /*********************************************************************
3542 * Function : privoxy_mutex_init
3544 * Description : Prepares a mutex.
3547 * 1 : mutex = The mutex to initialize.
3549 * Returns : Void. May exit in case of errors.
3551 *********************************************************************/
3552 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3554 #ifdef FEATURE_PTHREAD
3555 int err = pthread_mutex_init(mutex, 0);
3558 printf("Fatal error. Mutex initialization failed: %s.\n",
3563 InitializeCriticalSection(mutex);
3564 #endif /* def FEATURE_PTHREAD */
3566 #endif /* def MUTEX_LOCKS_AVAILABLE */
3568 /*********************************************************************
3570 * Function : initialize_mutexes
3572 * Description : Prepares mutexes if mutex support is available.
3576 * Returns : Void, exits in case of errors.
3578 *********************************************************************/
3579 static void initialize_mutexes(void)
3581 #ifdef MUTEX_LOCKS_AVAILABLE
3583 * Prepare global mutex semaphores
3585 privoxy_mutex_init(&log_mutex);
3586 privoxy_mutex_init(&log_init_mutex);
3587 privoxy_mutex_init(&connection_reuse_mutex);
3588 #ifdef FEATURE_EXTERNAL_FILTERS
3589 privoxy_mutex_init(&external_filter_mutex);
3591 #ifdef FEATURE_CLIENT_TAGS
3592 privoxy_mutex_init(&client_tags_mutex);
3596 * XXX: The assumptions below are a bit naive
3597 * and can cause locks that aren't necessary.
3599 * For example older FreeBSD versions (< 6.x?)
3600 * have no gethostbyname_r, but gethostbyname is
3603 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3604 privoxy_mutex_init(&resolver_mutex);
3605 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3607 * XXX: should we use a single mutex for
3608 * localtime() and gmtime() as well?
3610 #ifndef HAVE_GMTIME_R
3611 privoxy_mutex_init(&gmtime_mutex);
3612 #endif /* ndef HAVE_GMTIME_R */
3614 #ifndef HAVE_LOCALTIME_R
3615 privoxy_mutex_init(&localtime_mutex);
3616 #endif /* ndef HAVE_GMTIME_R */
3618 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
3619 privoxy_mutex_init(&rand_mutex);
3620 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
3622 #endif /* def MUTEX_LOCKS_AVAILABLE */
3625 /*********************************************************************
3629 * Description : Load the config file and start the listen loop.
3630 * This function is a lot more *sane* with the `load_config'
3631 * and `listen_loop' functions; although it stills does
3632 * a *little* too much for my taste.
3635 * 1 : argc = Number of parameters (including $0).
3636 * 2 : argv = Array of (char *)'s to the parameters.
3638 * Returns : 1 if : can't open config file, unrecognized directive,
3639 * stats requested in multi-thread mode, can't open the
3640 * log file, can't open the jar file, listen port is invalid,
3641 * any load fails, and can't bind port.
3643 * Else main never returns, the process must be signaled
3644 * to terminate execution. Or, on Windows, use the
3645 * "File", "Exit" menu option.
3647 *********************************************************************/
3649 int real_main(int argc, char **argv)
3651 int main(int argc, char **argv)
3655 int do_config_test = 0;
3656 #ifndef HAVE_ARC4RANDOM
3657 unsigned int random_seed;
3660 struct passwd *pw = NULL;
3661 struct group *grp = NULL;
3663 char *pre_chroot_nslookup_to_load_resolver = NULL;
3666 char *fuzz_input_type = NULL;
3667 char *fuzz_input_file = NULL;
3674 #if !defined(_WIN32)
3681 /* Prepare mutexes if supported and necessary. */
3682 initialize_mutexes();
3684 /* Enable logging until further notice. */
3688 * Parse the command line arguments
3690 * XXX: simply printing usage information in case of
3691 * invalid arguments isn't particularly user friendly.
3693 while (++argc_pos < argc)
3696 /* Check to see if the service must be installed or uninstalled */
3697 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3699 const char *pName = argv[argc_pos] + 9;
3702 exit((install_service(pName)) ? 0 : 1);
3704 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3706 const char *pName = argv[argc_pos] + 11;
3709 exit((uninstall_service(pName)) ? 0 : 1);
3711 else if (strcmp(argv[argc_pos], "--service") == 0)
3713 bRunAsService = TRUE;
3714 w32_set_service_cwd();
3715 atexit(w32_service_exit_notify);
3718 #endif /* defined(_WIN32) */
3721 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3723 if (strcmp(argv[argc_pos], "--help") == 0)
3728 else if (strcmp(argv[argc_pos], "--version") == 0)
3730 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3736 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3738 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3742 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3744 if (++argc_pos == argc) usage(argv[0]);
3745 pidfile = strdup_or_die(argv[argc_pos]);
3748 else if (strcmp(argv[argc_pos], "--user") == 0)
3753 if (++argc_pos == argc) usage(argv[argc_pos]);
3755 user_arg = strdup_or_die(argv[argc_pos]);
3756 group_name = strchr(user_arg, '.');
3757 if (NULL != group_name)
3759 /* Nul-terminate the user name */
3762 /* Skip the former delimiter to actually reach the group name */
3765 grp = getgrnam(group_name);
3768 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3771 pw = getpwnam(user_arg);
3774 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3780 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3782 if (++argc_pos == argc) usage(argv[0]);
3783 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3786 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3790 #endif /* defined(unix) */
3792 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3797 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
3800 if (argc < argc_pos + 2) usage(argv[0]);
3801 fuzz_input_type = argv[argc_pos];
3803 fuzz_input_file = argv[argc_pos];
3805 else if (strcmp(argv[argc_pos], "--stfu") == 0)
3807 set_debug_level(LOG_LEVEL_STFU);
3810 else if (argc_pos + 1 != argc)
3813 * This is neither the last command line
3814 * option, nor was it recognized before,
3815 * therefore it must be invalid.
3821 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3823 configfile = argv[argc_pos];
3826 } /* -END- while (more arguments) */
3828 show_version(Argv[0]);
3831 if (*configfile != '/')
3833 char cwd[BUFFER_SIZE];
3835 size_t abs_file_size;
3837 /* make config-filename absolute here */
3838 if (NULL == getcwd(cwd, sizeof(cwd)))
3840 perror("failed to get current working directory");
3844 basedir = strdup_or_die(cwd);
3846 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3847 abs_file = malloc_or_die(abs_file_size);
3848 strlcpy(abs_file, basedir, abs_file_size);
3849 strlcat(abs_file, "/", abs_file_size);
3850 strlcat(abs_file, configfile, abs_file_size);
3851 configfile = abs_file;
3853 #endif /* defined unix */
3857 clients->next = NULL;
3859 /* XXX: factor out initialising after the next stable release. */
3864 #ifndef HAVE_ARC4RANDOM
3865 random_seed = (unsigned int)time(NULL);
3867 srandom(random_seed);
3870 #endif /* ifdef HAVE_RANDOM */
3871 #endif /* ifndef HAVE_ARC4RANDOM */
3874 * Unix signal handling
3876 * Catch the abort, interrupt and terminate signals for a graceful exit
3877 * Catch the hangup signal so the errlog can be reopened.
3879 * Ignore the broken pipe signal as connection failures
3880 * are handled when and where they occur without relying
3883 #if !defined(_WIN32) && !defined(__OS2__)
3886 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3888 for (idx = 0; idx < SZ(catched_signals); idx++)
3890 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3891 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3893 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3894 #endif /* ifdef sun */
3896 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3900 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3902 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3906 #else /* ifdef _WIN32 */
3907 # ifdef _WIN_CONSOLE
3909 * We *are* in a windows console app.
3910 * Print a verbose messages about FAQ's and such
3912 printf("%s", win32_blurb);
3913 # endif /* def _WIN_CONSOLE */
3914 #endif /* def _WIN32 */
3917 if (fuzz_input_type != NULL)
3919 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
3921 log_error(LOG_LEVEL_FATAL,
3922 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
3923 "Various data structures are static which is unsafe when using threads.");
3928 exit(NULL == load_config());
3931 /* Initialize the CGI subsystem */
3932 cgi_init_error_messages();
3935 * If running on unix and without the --no-daemon
3936 * option, become a daemon. I.e. fork, detach
3937 * from tty and get process group leadership
3946 if (pid < 0) /* error */
3951 else if (pid != 0) /* parent */
3956 * must check for errors
3957 * child died due to missing files aso
3960 wpid = waitpid(pid, &status, WNOHANG);
3972 * stderr (fd 2) will be closed later on,
3973 * when the config file has been parsed.
3979 * Reserve fd 0 and 1 to prevent abort() and friends
3980 * from sending stuff to the clients or servers.
3982 fd = open("/dev/null", O_RDONLY);
3985 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3989 if (dup2(fd, 0) == -1)
3991 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3995 fd = open("/dev/null", O_WRONLY);
3998 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4002 if (dup2(fd, 1) == -1)
4004 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
4009 #ifdef FEATURE_EXTERNAL_FILTERS
4010 for (fd = 0; fd < 3; fd++)
4012 mark_socket_for_close_on_execute(fd);
4018 } /* -END- if (daemon_mode) */
4021 * As soon as we have written the PID file, we can switch
4022 * to the user and group ID indicated by the --user option
4024 if (pidfile != NULL)
4026 write_pid_file(pidfile);
4030 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
4032 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
4036 if (setgroups(1, &grp->gr_gid))
4038 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
4041 else if (initgroups(pw->pw_name, pw->pw_gid))
4043 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
4049 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
4051 /* Read the time zone file from /etc before doing chroot. */
4053 if (NULL != pre_chroot_nslookup_to_load_resolver
4054 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
4056 /* Initialize resolver library. */
4057 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
4059 if (chroot(pw->pw_dir) < 0)
4061 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
4065 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
4068 if (setuid(pw->pw_uid))
4070 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
4074 char putenv_dummy[64];
4076 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
4077 if (putenv(putenv_dummy) != 0)
4079 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
4082 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
4083 if (putenv(putenv_dummy) != 0)
4085 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
4091 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
4094 #endif /* defined unix */
4097 /* This will be FALSE unless the command line specified --service
4101 /* Yup, so now we must attempt to establish a connection
4102 * with the service dispatcher. This will only work if this
4103 * process was launched by the service control manager to
4104 * actually run as a service. If this isn't the case, i've
4105 * known it take around 30 seconds or so for the call to return.
4108 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
4109 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
4111 /* Service has run, and at this point is now being stopped, so just return */
4116 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
4118 /* An error occurred. Usually it's because --service was wrongly specified
4119 * and we were unable to connect to the Service Control Dispatcher because
4120 * it wasn't expecting us and is therefore not listening.
4122 * For now, just continue below to call the listen_loop function.
4125 #endif /* def _WIN32 */
4135 /*********************************************************************
4137 * Function : bind_port_helper
4139 * Description : Bind the listen port. Handles logging, and aborts
4143 * 1 : haddr = Host address to bind to. Use NULL to bind to
4145 * 2 : hport = Specifies port to bind to.
4146 * 3 : backlog = Listen backlog.
4148 * Returns : Port that was opened.
4150 *********************************************************************/
4151 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
4156 result = bind_port(haddr, hport, backlog, &bfd);
4160 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
4164 log_error(LOG_LEVEL_FATAL,
4165 "can't bind to %s:%d: There may be another Privoxy "
4166 "or some other proxy running on port %d",
4167 bind_address, hport, hport);
4170 log_error(LOG_LEVEL_FATAL,
4171 "can't bind to %s:%d: The hostname is not resolvable",
4172 bind_address, hport);
4175 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
4176 bind_address, hport);
4179 /* shouldn't get here */
4180 return JB_INVALID_SOCKET;
4185 if (bfd >= FD_SETSIZE)
4187 log_error(LOG_LEVEL_FATAL,
4188 "Bind socket number too high to use select(): %d >= %d",
4196 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
4201 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
4209 /*********************************************************************
4211 * Function : bind_ports_helper
4213 * Description : Bind the listen ports. Handles logging, and aborts
4217 * 1 : config = Privoxy configuration. Specifies ports
4219 * 2 : sockets = Preallocated array of opened sockets
4220 * corresponding to specification in config.
4221 * All non-opened sockets will be set to
4222 * JB_INVALID_SOCKET.
4224 * Returns : Nothing. Inspect sockets argument.
4226 *********************************************************************/
4227 static void bind_ports_helper(struct configuration_spec * config,
4228 jb_socket sockets[])
4232 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4234 if (config->hport[i])
4236 sockets[i] = bind_port_helper(config->haddr[i],
4237 config->hport[i], config->listen_backlog);
4238 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
4239 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
4241 struct accept_filter_arg af_options;
4242 bzero(&af_options, sizeof(af_options));
4243 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
4244 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
4245 sizeof(af_options)))
4247 log_error(LOG_LEVEL_ERROR,
4248 "Enabling accept filter for socket %d failed: %E", sockets[i]);
4255 sockets[i] = JB_INVALID_SOCKET;
4258 config->need_bind = 0;
4262 /*********************************************************************
4264 * Function : close_ports_helper
4266 * Description : Close listenings ports.
4269 * 1 : sockets = Array of opened and non-opened sockets to
4270 * close. All sockets will be set to
4271 * JB_INVALID_SOCKET.
4273 * Returns : Nothing.
4275 *********************************************************************/
4276 static void close_ports_helper(jb_socket sockets[])
4280 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4282 if (JB_INVALID_SOCKET != sockets[i])
4284 close_socket(sockets[i]);
4286 sockets[i] = JB_INVALID_SOCKET;
4292 /* Without this simple workaround we get this compiler warning from _beginthread
4293 * warning C4028: formal parameter 1 different from declaration
4295 void w32_service_listen_loop(void *p)
4299 #endif /* def _WIN32 */
4302 /*********************************************************************
4304 * Function : listen_loop
4306 * Description : bind the listen port and enter a "FOREVER" listening loop.
4312 *********************************************************************/
4313 static void listen_loop(void)
4315 struct client_states *csp_list = NULL;
4316 struct client_state *csp = NULL;
4317 jb_socket bfds[MAX_LISTENING_SOCKETS];
4318 struct configuration_spec *config;
4319 unsigned int active_threads = 0;
4320 #if defined(FEATURE_PTHREAD)
4321 pthread_attr_t attrs;
4323 pthread_attr_init(&attrs);
4324 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4327 config = load_config();
4329 #ifdef FEATURE_CONNECTION_SHARING
4331 * XXX: Should be relocated once it no
4332 * longer needs to emit log messages.
4334 initialize_reusable_connections();
4335 #endif /* def FEATURE_CONNECTION_SHARING */
4337 bind_ports_helper(config, bfds);
4339 #ifdef FEATURE_GRACEFUL_TERMINATION
4340 while (!g_terminate)
4345 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
4346 while (waitpid(-1, NULL, WNOHANG) > 0)
4348 /* zombie children */
4350 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
4353 * Free data that was used by died threads
4355 active_threads = sweep();
4359 * Re-open the errlog after HUP signal
4361 if (received_hup_signal)
4363 if (NULL != config->logfile)
4365 init_error_log(Argv[0], config->logfile);
4367 received_hup_signal = 0;
4371 csp_list = zalloc_or_die(sizeof(*csp_list));
4372 csp = &csp_list->csp;
4374 log_error(LOG_LEVEL_CONNECT,
4375 "Waiting for the next client connection. Currently active threads: %d",
4379 * This config may be outdated, but for accept_connection()
4380 * it's fresh enough.
4382 csp->config = config;
4384 if (!accept_connection(csp, bfds))
4386 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
4391 csp->flags |= CSP_FLAG_ACTIVE;
4392 csp->server_connection.sfd = JB_INVALID_SOCKET;
4394 csp->config = config = load_config();
4396 if (config->need_bind)
4399 * Since we were listening to the "old port", we will not see
4400 * a "listen" param change until the next request. So, at
4401 * least 1 more request must be made for us to find the new
4402 * setting. I am simply closing the old socket and binding the
4405 * Which-ever is correct, we will serve 1 more page via the
4406 * old settings. This should probably be a "show-status"
4407 * request. This should not be a so common of an operation
4408 * that this will hurt people's feelings.
4411 close_ports_helper(bfds);
4413 bind_ports_helper(config, bfds);
4416 #ifdef FEATURE_TOGGLE
4417 if (global_toggle_state)
4418 #endif /* def FEATURE_TOGGLE */
4420 csp->flags |= CSP_FLAG_TOGGLED_ON;
4423 if (run_loader(csp))
4425 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
4426 /* Never get here - LOG_LEVEL_FATAL causes program exit */
4430 if (block_acl(NULL,csp))
4432 log_error(LOG_LEVEL_CONNECT,
4433 "Connection from %s on %s (socket %d) dropped due to ACL",
4434 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
4435 close_socket(csp->cfd);
4436 freez(csp->ip_addr_str);
4437 freez(csp->listen_addr_str);
4441 #endif /* def FEATURE_ACL */
4443 if ((0 != config->max_client_connections)
4444 && (active_threads >= config->max_client_connections))
4446 log_error(LOG_LEVEL_CONNECT,
4447 "Rejecting connection from %s. Maximum number of connections reached.",
4449 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4450 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
4451 close_socket(csp->cfd);
4452 freez(csp->ip_addr_str);
4453 freez(csp->listen_addr_str);
4458 /* add it to the list of clients */
4459 csp_list->next = clients->next;
4460 clients->next = csp_list;
4462 if (config->multi_threaded)
4466 /* this is a switch () statement in the C preprocessor - ugh */
4467 #undef SELECTED_ONE_OPTION
4469 /* Use Pthreads in preference to native code */
4470 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
4471 #define SELECTED_ONE_OPTION
4473 pthread_t the_thread;
4475 errno = pthread_create(&the_thread, &attrs,
4476 (void * (*)(void *))serve, csp);
4477 child_id = errno ? -1 : 0;
4481 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
4482 #define SELECTED_ONE_OPTION
4483 child_id = _beginthread(
4484 (void (*)(void *))serve,
4489 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
4490 #define SELECTED_ONE_OPTION
4491 child_id = _beginthread(
4492 (void(* _Optlink)(void*))serve,
4498 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
4499 #define SELECTED_ONE_OPTION
4501 thread_id tid = spawn_thread
4502 (server_thread, "server", B_NORMAL_PRIORITY, csp);
4504 if ((tid >= 0) && (resume_thread(tid) == B_OK))
4506 child_id = (int) tid;
4515 #if !defined(SELECTED_ONE_OPTION)
4518 /* This block is only needed when using fork().
4519 * When using threads, the server thread was
4520 * created and run by the call to _beginthread().
4522 if (child_id == 0) /* child */
4525 #ifdef FEATURE_TOGGLE
4526 int inherited_toggle_state = global_toggle_state;
4527 #endif /* def FEATURE_TOGGLE */
4532 * If we've been toggled or we've blocked the request, tell Mom
4535 #ifdef FEATURE_TOGGLE
4536 if (inherited_toggle_state != global_toggle_state)
4538 rc |= RC_FLAG_TOGGLED;
4540 #endif /* def FEATURE_TOGGLE */
4542 #ifdef FEATURE_STATISTICS
4543 if (csp->flags & CSP_FLAG_REJECTED)
4545 rc |= RC_FLAG_BLOCKED;
4547 #endif /* ndef FEATURE_STATISTICS */
4551 else if (child_id > 0) /* parent */
4553 /* in a fork()'d environment, the parent's
4554 * copy of the client socket and the CSP
4558 #if !defined(_WIN32) && !defined(__CYGWIN__)
4560 wait(&child_status);
4563 * Evaluate child's return code: If the child has
4564 * - been toggled, toggle ourselves
4565 * - blocked its request, bump up the stats counter
4568 #ifdef FEATURE_TOGGLE
4569 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4571 global_toggle_state = !global_toggle_state;
4573 #endif /* def FEATURE_TOGGLE */
4575 #ifdef FEATURE_STATISTICS
4577 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4581 #endif /* def FEATURE_STATISTICS */
4583 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4584 close_socket(csp->cfd);
4585 csp->flags &= ~CSP_FLAG_ACTIVE;
4589 #undef SELECTED_ONE_OPTION
4590 /* end of cpp switch () */
4595 * Spawning the child failed, assume it's because
4596 * there are too many children running already.
4597 * XXX: If you assume ...
4599 log_error(LOG_LEVEL_ERROR,
4600 "Unable to take any additional connections: %E. Active threads: %d",
4602 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4603 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
4604 close_socket(csp->cfd);
4605 csp->flags &= ~CSP_FLAG_ACTIVE;
4614 #if defined(FEATURE_PTHREAD)
4615 pthread_attr_destroy(&attrs);
4618 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4620 /* Clean up. Aim: free all memory (no leaks) */
4621 #ifdef FEATURE_GRACEFUL_TERMINATION
4623 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4625 unload_current_config_file();
4626 unload_current_actions_file();
4627 unload_current_re_filterfile();
4628 #ifdef FEATURE_TRUST
4629 unload_current_trust_file();
4632 if (config->multi_threaded)
4639 } while ((clients->next != NULL) && (--i > 0));
4643 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4653 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4654 /* Cleanup - remove taskbar icon etc. */
4659 #endif /* FEATURE_GRACEFUL_TERMINATION */