1 const char jcc_rcs[] = "$Id: jcc.c,v 1.452 2017/05/04 14:34:18 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001-2016 the
10 * Privoxy team. http://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 *********************************************************************/
40 #include <sys/types.h>
49 # ifndef FEATURE_PTHREAD
53 # include <winsock2.h>
56 # endif /* ndef FEATURE_PTHREAD */
61 # endif /* ndef _WIN_CONSOLE */
62 # include "w32svrapi.h"
64 #else /* ifndef _WIN32 */
66 # if !defined (__OS2__)
68 # include <sys/wait.h>
69 # endif /* ndef __OS2__ */
70 # include <sys/time.h>
71 # include <sys/stat.h>
72 # include <sys/ioctl.h>
75 #include <sys/termios.h>
86 # include <socket.h> /* BeOS has select() for sockets only. */
87 # include <OS.h> /* declarations for threads and stuff. */
90 # if defined(__EMX__) || defined(__OS2__)
91 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
110 #include "miscutil.h"
112 #include "jbsockets.h"
117 #include "urlmatch.h"
118 #ifdef FEATURE_CLIENT_TAGS
119 #include "client-tags.h"
122 const char jcc_h_rcs[] = JCC_H_VERSION;
123 const char project_h_rcs[] = PROJECT_H_VERSION;
126 struct client_states clients[1];
127 struct file_list files[1];
129 #ifdef FEATURE_STATISTICS
130 int urls_read = 0; /* total nr of urls read inc rejected */
131 int urls_rejected = 0; /* total nr of urls rejected */
132 #endif /* def FEATURE_STATISTICS */
134 #ifdef FEATURE_GRACEFUL_TERMINATION
138 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
139 static void sig_handler(int the_signal);
141 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
142 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
143 static jb_err get_server_headers(struct client_state *csp);
144 static const char *crunch_reason(const struct http_response *rsp);
145 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
146 static char *get_request_line(struct client_state *csp);
147 static jb_err receive_client_request(struct client_state *csp);
148 static jb_err parse_client_request(struct client_state *csp);
149 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
150 static jb_err change_request_destination(struct client_state *csp);
151 static void chat(struct client_state *csp);
152 static void serve(struct client_state *csp);
153 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
154 static void usage(const char *myname);
156 static void initialize_mutexes(void);
157 static jb_socket bind_port_helper(const char *haddr, int hport);
158 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
159 static void close_ports_helper(jb_socket sockets[]);
160 static void listen_loop(void);
163 void serve(struct client_state *csp);
164 #else /* ifndef AMIGA */
165 static void serve(struct client_state *csp);
166 #endif /* def AMIGA */
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__) && !defined(AMIGA)
338 /*********************************************************************
340 * Function : sig_handler
342 * Description : Signal handler for different signals.
343 * Exit gracefully on TERM and INT
344 * or set a flag that will cause the errlog
345 * to be reopened by the main thread on HUP.
348 * 1 : the_signal = the signal cause this function to call
352 *********************************************************************/
353 static void sig_handler(int the_signal)
359 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
371 received_hup_signal = 1;
377 * We shouldn't be here, unless we catch signals
378 * in main() that we can't handle here!
380 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
388 /*********************************************************************
390 * Function : client_protocol_is_unsupported
392 * Description : Checks if the client used a known unsupported
393 * protocol and deals with it by sending an error
397 * 1 : csp = Current client state (buffers, headers, etc...)
398 * 2 : req = the first request line send by the client
400 * Returns : TRUE if an error response has been generated, or
401 * FALSE if the request doesn't look invalid.
403 *********************************************************************/
404 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
407 * If it's a FTP or gopher request, we don't support it.
409 * These checks are better than nothing, but they might
410 * not work in all configurations and some clients might
411 * have problems digesting the answer.
413 * They should, however, never cause more problems than
414 * Privoxy's old behaviour (returning the misleading HTML
417 * "Could not resolve http://(ftp|gopher)://example.org").
419 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
421 const char *response = NULL;
422 const char *protocol = NULL;
424 if (!strncmpic(req, "GET ftp://", 10))
426 response = FTP_RESPONSE;
431 response = GOPHER_RESPONSE;
434 log_error(LOG_LEVEL_ERROR,
435 "%s tried to use Privoxy as %s proxy: %s",
436 csp->ip_addr_str, protocol, req);
437 log_error(LOG_LEVEL_CLF,
438 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
440 write_socket(csp->cfd, response, strlen(response));
449 /*********************************************************************
451 * Function : client_has_unsupported_expectations
453 * Description : Checks if the client used an unsupported expectation
454 * in which case an error message is delivered.
457 * 1 : csp = Current client state (buffers, headers, etc...)
459 * Returns : TRUE if an error response has been generated, or
460 * FALSE if the request doesn't look invalid.
462 *********************************************************************/
463 static int client_has_unsupported_expectations(const struct client_state *csp)
465 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
467 log_error(LOG_LEVEL_ERROR,
468 "Rejecting request from client %s with unsupported Expect header value",
470 log_error(LOG_LEVEL_CLF,
471 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
472 write_socket(csp->cfd, UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
473 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE));
483 /*********************************************************************
485 * Function : get_request_destination_elsewhere
487 * Description : If the client's request was redirected into
488 * Privoxy without the client's knowledge,
489 * the request line lacks the destination host.
491 * This function tries to get it elsewhere,
492 * provided accept-intercepted-requests is enabled.
494 * "Elsewhere" currently only means "Host: header",
495 * but in the future we may ask the redirecting
496 * packet filter to look the destination up.
498 * If the destination stays unknown, an error
499 * response is send to the client and headers
500 * are freed so that chat() can return directly.
503 * 1 : csp = Current client state (buffers, headers, etc...)
504 * 2 : headers = a header list
506 * Returns : JB_ERR_OK if the destination is now known, or
507 * JB_ERR_PARSE if it isn't.
509 *********************************************************************/
510 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
514 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
516 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
517 " Privoxy isn't configured to accept intercepted requests.",
518 csp->ip_addr_str, csp->http->cmd);
519 /* XXX: Use correct size */
520 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
521 csp->ip_addr_str, csp->http->cmd);
523 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
524 destroy_list(headers);
528 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
530 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
531 /* Split the domain we just got for pattern matching */
532 init_domain_components(csp->http);
539 /* We can't work without destination. Go spread the news.*/
541 req = list_to_text(headers);
543 /* XXX: Use correct size */
544 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
545 csp->ip_addr_str, csp->http->cmd);
546 log_error(LOG_LEVEL_ERROR,
547 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
548 csp->ip_addr_str, csp->http->cmd, req);
551 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
552 destroy_list(headers);
557 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
558 * to get the destination IP address, use it as host directly
559 * or do a reverse DNS lookup first.
564 /*********************************************************************
566 * Function : get_server_headers
568 * Description : Parses server headers in iob and fills them
569 * into csp->headers so that they can later be
573 * 1 : csp = Current client state (buffers, headers, etc...)
575 * Returns : JB_ERR_OK if everything went fine, or
576 * JB_ERR_PARSE if the headers were incomplete.
578 *********************************************************************/
579 static jb_err get_server_headers(struct client_state *csp)
581 int continue_hack_in_da_house = 0;
584 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
589 * continue hack in da house. Ignore the ending of
590 * this head and continue enlisting header lines.
591 * The reason is described below.
593 enlist(csp->headers, "");
594 continue_hack_in_da_house = 0;
597 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
600 * It's a bodyless continue response, don't
601 * stop header parsing after reaching its end.
603 * As a result Privoxy will concatenate the
604 * next response's head and parse and deliver
605 * the headers as if they belonged to one request.
607 * The client will separate them because of the
608 * empty line between them.
610 * XXX: What we're doing here is clearly against
611 * the intended purpose of the continue header,
612 * and under some conditions (HTTP/1.0 client request)
613 * it's a standard violation.
615 * Anyway, "sort of against the spec" is preferable
616 * to "always getting confused by Continue responses"
617 * (Privoxy's behaviour before this hack was added)
619 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
620 continue_hack_in_da_house = 1;
622 else if (*header == '\0')
625 * If the header is empty, but the Continue hack
626 * isn't active, we can assume that we reached the
627 * end of the buffer before we hit the end of the
630 * Inform the caller an let it decide how to handle it.
635 if (JB_ERR_MEMORY == enlist(csp->headers, header))
638 * XXX: Should we quit the request and return a
639 * out of memory error page instead?
641 log_error(LOG_LEVEL_ERROR,
642 "Out of memory while enlisting server headers. %s lost.",
652 /*********************************************************************
654 * Function : crunch_reason
656 * Description : Translates the crunch reason code into a string.
659 * 1 : rsp = a http_response
661 * Returns : A string with the crunch reason or an error description.
663 *********************************************************************/
664 static const char *crunch_reason(const struct http_response *rsp)
666 char * reason = NULL;
671 return "Internal error while searching for crunch reason";
674 switch (rsp->crunch_reason)
677 reason = "Unsupported HTTP feature";
683 reason = "Untrusted";
686 reason = "Redirected";
692 reason = "DNS failure";
694 case FORWARDING_FAILED:
695 reason = "Forwarding failed";
698 reason = "Connection failure";
701 reason = "Out of memory (may mask other reasons)";
703 case CONNECTION_TIMEOUT:
704 reason = "Connection timeout";
707 reason = "No server data received";
710 reason = "No reason recorded";
718 /*********************************************************************
720 * Function : log_applied_actions
722 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
726 * 1 : actions = Current action spec to log
730 *********************************************************************/
731 static void log_applied_actions(const struct current_action_spec *actions)
734 * The conversion to text requires lots of memory allocations so
735 * we only do the conversion if the user is actually interested.
737 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
739 char *actions_as_text = actions_to_line_of_text(actions);
740 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
741 freez(actions_as_text);
746 /*********************************************************************
748 * Function : send_crunch_response
750 * Description : Delivers already prepared response for
751 * intercepted requests, logs the interception
752 * and frees the response.
755 * 1 : csp = Current client state (buffers, headers, etc...)
756 * 1 : rsp = Fully prepared response. Will be freed on exit.
760 *********************************************************************/
761 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
763 const struct http_request *http = csp->http;
767 assert(rsp->head != NULL);
771 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
775 * Extract the status code from the actual head
776 * that will be send to the client. It is the only
777 * way to get it right for all requests, including
778 * the fixed ones for out-of-memory problems.
780 * A head starts like this: 'HTTP/1.1 200...'
784 status_code[0] = rsp->head[9];
785 status_code[1] = rsp->head[10];
786 status_code[2] = rsp->head[11];
787 status_code[3] = '\0';
789 /* Log that the request was crunched and why. */
790 log_applied_actions(csp->action);
791 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
792 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
793 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
795 /* Write the answer to the client */
796 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
797 || write_socket(csp->cfd, rsp->body, rsp->content_length))
799 /* There is nothing we can do about it. */
800 log_error(LOG_LEVEL_ERROR,
801 "Couldn't deliver the error message through client socket %d: %E",
805 /* Clean up and return */
806 if (cgi_error_memory() != rsp)
808 free_http_response(rsp);
814 /*********************************************************************
816 * Function : crunch_response_triggered
818 * Description : Checks if the request has to be crunched,
819 * and delivers the crunch response if necessary.
822 * 1 : csp = Current client state (buffers, headers, etc...)
823 * 2 : crunchers = list of cruncher functions to run
825 * Returns : TRUE if the request was answered with a crunch response
828 *********************************************************************/
829 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
831 struct http_response *rsp = NULL;
832 const struct cruncher *c;
835 * If CGI request crunching is disabled,
836 * check the CGI dispatcher out of order to
837 * prevent unintentional blocks or redirects.
839 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
840 && (NULL != (rsp = dispatch_cgi(csp))))
842 /* Deliver, log and free the interception response. */
843 send_crunch_response(csp, rsp);
844 csp->flags |= CSP_FLAG_CRUNCHED;
848 for (c = crunchers; c->cruncher != NULL; c++)
851 * Check the cruncher if either Privoxy is toggled
852 * on and the request isn't forced, or if the cruncher
853 * applies to forced requests as well.
855 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
856 !(csp->flags & CSP_FLAG_FORCED)) ||
857 (c->flags & CF_IGNORE_FORCE))
859 rsp = c->cruncher(csp);
862 /* Deliver, log and free the interception response. */
863 send_crunch_response(csp, rsp);
864 csp->flags |= CSP_FLAG_CRUNCHED;
865 #ifdef FEATURE_STATISTICS
866 if (c->flags & CF_COUNT_AS_REJECT)
868 csp->flags |= CSP_FLAG_REJECTED;
870 #endif /* def FEATURE_STATISTICS */
881 /*********************************************************************
883 * Function : build_request_line
885 * Description : Builds the HTTP request line.
887 * If a HTTP forwarder is used it expects the whole URL,
888 * web servers only get the path.
891 * 1 : csp = Current client state (buffers, headers, etc...)
892 * 2 : fwd = The forwarding spec used for the request
893 * XXX: Should use http->fwd instead.
894 * 3 : request_line = The old request line which will be replaced.
896 * Returns : Nothing. Terminates in case of memory problems.
898 *********************************************************************/
899 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
901 struct http_request *http = csp->http;
903 assert(http->ssl == 0);
906 * Downgrade http version from 1.1 to 1.0
907 * if +downgrade action applies.
909 if ((csp->action->flags & ACTION_DOWNGRADE)
910 && (!strcmpic(http->ver, "HTTP/1.1")))
913 http->ver = strdup_or_die("HTTP/1.0");
917 * Rebuild the request line.
919 freez(*request_line);
920 *request_line = strdup(http->gpc);
921 string_append(request_line, " ");
923 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
925 string_append(request_line, http->url);
929 string_append(request_line, http->path);
931 string_append(request_line, " ");
932 string_append(request_line, http->ver);
934 if (*request_line == NULL)
936 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
938 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
942 /*********************************************************************
944 * Function : change_request_destination
946 * Description : Parse a (rewritten) request line and regenerate
947 * the http request data.
950 * 1 : csp = Current client state (buffers, headers, etc...)
952 * Returns : Forwards the parse_http_request() return code.
953 * Terminates in case of memory problems.
955 *********************************************************************/
956 static jb_err change_request_destination(struct client_state *csp)
958 struct http_request *http = csp->http;
961 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
962 csp->headers->first->str);
963 free_http_request(http);
964 err = parse_http_request(csp->headers->first->str, http);
965 if (JB_ERR_OK != err)
967 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
968 jb_err_to_string(err));
975 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
976 /*********************************************************************
978 * Function : server_response_is_complete
980 * Description : Determines whether we should stop reading
981 * from the server socket.
984 * 1 : csp = Current client state (buffers, headers, etc...)
985 * 2 : content_length = Length of content received so far.
987 * Returns : TRUE if the response is complete,
990 *********************************************************************/
991 static int server_response_is_complete(struct client_state *csp,
992 unsigned long long content_length)
994 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
996 if (!strcmpic(csp->http->gpc, "HEAD"))
999 * "HEAD" implies no body, we are thus expecting
1000 * no content. XXX: incomplete "list" of methods?
1002 csp->expected_content_length = 0;
1003 content_length_known = TRUE;
1004 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1007 if (csp->http->status == 204 || csp->http->status == 304)
1010 * Expect no body. XXX: incomplete "list" of status codes?
1012 csp->expected_content_length = 0;
1013 content_length_known = TRUE;
1014 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1017 return (content_length_known && ((0 == csp->expected_content_length)
1018 || (csp->expected_content_length <= content_length)));
1022 #ifdef FEATURE_CONNECTION_SHARING
1023 /*********************************************************************
1025 * Function : wait_for_alive_connections
1027 * Description : Waits for alive connections to timeout.
1033 *********************************************************************/
1034 static void wait_for_alive_connections(void)
1036 int connections_alive = close_unusable_connections();
1038 while (0 < connections_alive)
1040 log_error(LOG_LEVEL_CONNECT,
1041 "Waiting for %d connections to timeout.",
1044 connections_alive = close_unusable_connections();
1047 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1050 #endif /* def FEATURE_CONNECTION_SHARING */
1053 /*********************************************************************
1055 * Function : save_connection_destination
1057 * Description : Remembers a connection for reuse later on.
1060 * 1 : sfd = Open socket to remember.
1061 * 2 : http = The destination for the connection.
1062 * 3 : fwd = The forwarder settings used.
1063 * 3 : server_connection = storage.
1067 *********************************************************************/
1068 void save_connection_destination(jb_socket sfd,
1069 const struct http_request *http,
1070 const struct forward_spec *fwd,
1071 struct reusable_connection *server_connection)
1073 assert(sfd != JB_INVALID_SOCKET);
1074 assert(NULL != http->host);
1076 server_connection->sfd = sfd;
1077 server_connection->host = strdup_or_die(http->host);
1078 server_connection->port = http->port;
1080 assert(NULL != fwd);
1081 assert(server_connection->gateway_host == NULL);
1082 assert(server_connection->gateway_port == 0);
1083 assert(server_connection->forwarder_type == 0);
1084 assert(server_connection->forward_host == NULL);
1085 assert(server_connection->forward_port == 0);
1087 server_connection->forwarder_type = fwd->type;
1088 if (NULL != fwd->gateway_host)
1090 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1094 server_connection->gateway_host = NULL;
1096 server_connection->gateway_port = fwd->gateway_port;
1098 if (NULL != fwd->forward_host)
1100 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1104 server_connection->forward_host = NULL;
1106 server_connection->forward_port = fwd->forward_port;
1110 /*********************************************************************
1112 * Function : verify_request_length
1114 * Description : Checks if we already got the whole client requests
1115 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1118 * Data that doesn't belong to the current request is
1119 * either thrown away to let the client retry on a clean
1120 * socket, or stashed to be dealt with after the current
1121 * request is served.
1124 * 1 : csp = Current client state (buffers, headers, etc...)
1128 *********************************************************************/
1129 static void verify_request_length(struct client_state *csp)
1131 unsigned long long buffered_request_bytes =
1132 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1134 if ((csp->expected_client_content_length != 0)
1135 && (buffered_request_bytes != 0))
1137 if (csp->expected_client_content_length >= buffered_request_bytes)
1139 csp->expected_client_content_length -= buffered_request_bytes;
1140 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1141 "to account for the %llu ones we already got.",
1142 csp->expected_client_content_length, buffered_request_bytes);
1146 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1147 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1148 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1149 "Marking the server socket tainted after throwing %llu bytes away.",
1150 buffered_request_bytes - csp->expected_client_content_length);
1151 csp->expected_client_content_length = 0;
1152 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1155 if (csp->expected_client_content_length == 0)
1157 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1161 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1162 && ((csp->client_iob->cur < csp->client_iob->eod)
1163 || (csp->expected_client_content_length != 0)))
1165 if (strcmpic(csp->http->gpc, "GET")
1166 && strcmpic(csp->http->gpc, "HEAD")
1167 && strcmpic(csp->http->gpc, "TRACE")
1168 && strcmpic(csp->http->gpc, "OPTIONS")
1169 && strcmpic(csp->http->gpc, "DELETE"))
1171 /* XXX: this is an incomplete hack */
1172 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1173 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1177 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1179 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1181 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1182 log_error(LOG_LEVEL_CONNECT,
1183 "Possible pipeline attempt detected. The connection will not "
1184 "be kept alive and we will only serve the first request.");
1185 /* Nuke the pipelined requests from orbit, just to be sure. */
1186 clear_iob(csp->client_iob);
1191 * Keep the pipelined data around for now, we'll deal with
1192 * it once we're done serving the current request.
1194 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1195 assert(csp->client_iob->eod >= csp->client_iob->cur);
1196 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1197 "%d bytes of pipelined data received.",
1198 (int)(csp->client_iob->eod - csp->client_iob->cur));
1204 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1205 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1208 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1211 /*********************************************************************
1213 * Function : mark_server_socket_tainted
1215 * Description : Makes sure we don't reuse a server socket
1216 * (if we didn't read everything the server sent
1217 * us reusing the socket would lead to garbage).
1220 * 1 : csp = Current client state (buffers, headers, etc...)
1224 *********************************************************************/
1225 static void mark_server_socket_tainted(struct client_state *csp)
1228 * For consistency we always mark the server socket
1229 * tainted, however, to reduce the log noise we only
1230 * emit a log message if the server socket could have
1231 * actually been reused.
1233 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1234 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1236 log_error(LOG_LEVEL_CONNECT,
1237 "Marking the server socket %d tainted.",
1238 csp->server_connection.sfd);
1240 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1243 /*********************************************************************
1245 * Function : get_request_line
1247 * Description : Read the client request line.
1250 * 1 : csp = Current client state (buffers, headers, etc...)
1252 * Returns : Pointer to request line or NULL in case of errors.
1254 *********************************************************************/
1255 static char *get_request_line(struct client_state *csp)
1257 char buf[BUFFER_SIZE];
1258 char *request_line = NULL;
1261 memset(buf, 0, sizeof(buf));
1263 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1266 * If there are multiple pipelined requests waiting,
1267 * the flag will be set again once the next request
1270 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1272 request_line = get_header(csp->client_iob);
1273 if ((NULL != request_line) && ('\0' != *request_line))
1275 return request_line;
1279 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1280 "received yet. Continuing reading from %d.", csp->cfd);
1288 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1290 !data_is_available(csp->cfd, csp->config->socket_timeout)
1293 if (socket_is_still_alive(csp->cfd))
1295 log_error(LOG_LEVEL_CONNECT,
1296 "No request line on socket %d received in time. Timeout: %d.",
1297 csp->cfd, csp->config->socket_timeout);
1298 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1299 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1303 log_error(LOG_LEVEL_CONNECT,
1304 "The client side of the connection on socket %d got "
1305 "closed without sending a complete request line.", csp->cfd);
1310 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1312 if (len <= 0) return NULL;
1315 * If there is no memory left for buffering the
1316 * request, there is nothing we can do but hang up
1318 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1323 request_line = get_header(csp->client_iob);
1325 } while ((NULL != request_line) && ('\0' == *request_line));
1327 return request_line;
1333 CHUNK_STATUS_MISSING_DATA,
1334 CHUNK_STATUS_BODY_COMPLETE,
1335 CHUNK_STATUS_PARSE_ERROR
1339 /*********************************************************************
1341 * Function : chunked_body_is_complete
1343 * Description : Figures out whether or not a chunked body is complete.
1345 * Currently it always starts at the beginning of the
1346 * buffer which is somewhat wasteful and prevents Privoxy
1347 * from starting to forward the correctly parsed chunks
1348 * as soon as theoretically possible.
1350 * Should be modified to work with a common buffer,
1351 * and allow the caller to skip already parsed chunks.
1353 * This would allow the function to be used for unbuffered
1354 * response bodies as well.
1357 * 1 : iob = Buffer with the body to check.
1358 * 2 : length = Length of complete body
1360 * Returns : Enum with the result of the check.
1362 *********************************************************************/
1363 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1365 unsigned int chunksize;
1371 * We need at least a single digit, followed by "\r\n",
1372 * followed by an unknown amount of data, followed by "\r\n".
1374 if (p + 5 > iob->eod)
1376 return CHUNK_STATUS_MISSING_DATA;
1378 if (sscanf(p, "%x", &chunksize) != 1)
1380 return CHUNK_STATUS_PARSE_ERROR;
1384 * We want at least a single digit, followed by "\r\n",
1385 * followed by the specified amount of data, followed by "\r\n".
1387 if (p + chunksize + 5 > iob->eod)
1389 return CHUNK_STATUS_MISSING_DATA;
1392 /* Skip chunk-size. */
1393 p = strstr(p, "\r\n");
1396 return CHUNK_STATUS_PARSE_ERROR;
1398 /* Move beyond the chunkdata. */
1401 /* There should be another "\r\n" to skip */
1402 if (memcmp(p, "\r\n", 2))
1404 return CHUNK_STATUS_PARSE_ERROR;
1407 } while (chunksize > 0U);
1409 *length = (size_t)(p - iob->cur);
1410 assert(*length <= (size_t)(iob->eod - iob->cur));
1411 assert(p <= iob->eod);
1413 return CHUNK_STATUS_BODY_COMPLETE;
1418 /*********************************************************************
1420 * Function : receive_chunked_client_request_body
1422 * Description : Read the chunk-encoded client request body.
1423 * Failures are dealt with.
1426 * 1 : csp = Current client state (buffers, headers, etc...)
1428 * Returns : JB_ERR_OK or JB_ERR_PARSE
1430 *********************************************************************/
1431 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1434 enum chunk_status status;
1436 while (CHUNK_STATUS_MISSING_DATA ==
1437 (status = chunked_body_is_complete(csp->client_iob,&body_length)))
1439 char buf[BUFFER_SIZE];
1442 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1444 log_error(LOG_LEVEL_ERROR,
1445 "Timeout while waiting for the client body.");
1448 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1451 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1454 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1459 if (status != CHUNK_STATUS_BODY_COMPLETE)
1461 write_socket(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1462 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE));
1463 log_error(LOG_LEVEL_CLF,
1464 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1465 return JB_ERR_PARSE;
1467 log_error(LOG_LEVEL_CONNECT,
1468 "Chunked client body completely read. Length: %d", body_length);
1469 csp->expected_client_content_length = body_length;
1477 /*********************************************************************
1479 * Function : fuzz_chunked_transfer_encoding
1481 * Description : Treat the fuzzed input as chunked transfer encoding
1482 * to check and dechunk.
1485 * 1 : csp = Used to store the data.
1486 * 2 : fuzz_input_file = File to read the input from.
1488 * Returns : Result of dechunking
1490 *********************************************************************/
1491 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1494 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1495 enum chunk_status status;
1497 status = chunked_body_is_complete(csp->iob, &length);
1498 if (CHUNK_STATUS_BODY_COMPLETE != status)
1500 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1503 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1508 /*********************************************************************
1510 * Function : fuzz_client_request
1512 * Description : Try to get a client request from the fuzzed input.
1515 * 1 : csp = Current client state (buffers, headers, etc...)
1516 * 2 : fuzz_input_file = File to read the input from.
1518 * Returns : Result of fuzzing.
1520 *********************************************************************/
1521 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1526 csp->ip_addr_str = "fuzzer";
1528 if (strcmp(fuzz_input_file, "-") != 0)
1530 log_error(LOG_LEVEL_FATAL,
1531 "Fuzzed client requests can currenty only be read from stdin (-).");
1533 err = receive_client_request(csp);
1534 if (err != JB_ERR_OK)
1538 err = parse_client_request(csp);
1539 if (err != JB_ERR_OK)
1547 #endif /* def FUZZ */
1550 #ifdef FEATURE_FORCE_LOAD
1551 /*********************************************************************
1553 * Function : force_required
1555 * Description : Checks a request line to see if it contains
1556 * the FORCE_PREFIX. If it does, it is removed
1557 * unless enforcing requests has beend disabled.
1560 * 1 : request_line = HTTP request line
1562 * Returns : TRUE if force is required, FALSE otherwise.
1564 *********************************************************************/
1565 static int force_required(const struct client_state *csp, char *request_line)
1569 p = strstr(request_line, "http://");
1573 p += strlen("http://");
1577 /* Intercepted request usually don't specify the protocol. */
1581 /* Go to the beginning of the path */
1586 * If the path is missing the request line is invalid and we
1587 * are done here. The client-visible rejection happens later on.
1592 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1594 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1596 /* XXX: Should clean more carefully */
1597 strclean(request_line, FORCE_PREFIX);
1598 log_error(LOG_LEVEL_FORCE,
1599 "Enforcing request: \"%s\".", request_line);
1603 log_error(LOG_LEVEL_FORCE,
1604 "Ignored force prefix in request: \"%s\".", request_line);
1610 #endif /* def FEATURE_FORCE_LOAD */
1613 /*********************************************************************
1615 * Function : receive_client_request
1617 * Description : Read the client's request (more precisely the
1618 * client headers) and answer it if necessary.
1621 * 1 : csp = Current client state (buffers, headers, etc...)
1623 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1625 *********************************************************************/
1626 static jb_err receive_client_request(struct client_state *csp)
1628 char buf[BUFFER_SIZE];
1631 struct http_request *http;
1635 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1636 struct list header_list;
1637 struct list *headers = &header_list;
1639 /* We don't care if the arriving data is a valid HTTP request or not. */
1640 csp->requests_received_total++;
1644 memset(buf, 0, sizeof(buf));
1646 req = get_request_line(csp);
1649 mark_server_socket_tainted(csp);
1650 return JB_ERR_PARSE;
1652 assert(*req != '\0');
1654 if (client_protocol_is_unsupported(csp, req))
1656 return JB_ERR_PARSE;
1659 #ifdef FEATURE_FORCE_LOAD
1660 if (force_required(csp, req))
1662 csp->flags |= CSP_FLAG_FORCED;
1664 #endif /* def FEATURE_FORCE_LOAD */
1666 err = parse_http_request(req, http);
1668 if (JB_ERR_OK != err)
1670 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1671 /* XXX: Use correct size */
1672 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1673 log_error(LOG_LEVEL_ERROR,
1674 "Couldn't parse request line received from %s: %s",
1675 csp->ip_addr_str, jb_err_to_string(err));
1677 free_http_request(http);
1678 return JB_ERR_PARSE;
1681 /* grab the rest of the client's headers */
1685 p = get_header(csp->client_iob);
1689 /* There are no additional headers to read. */
1696 * We didn't receive a complete header
1697 * line yet, get the rest of it.
1699 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1701 log_error(LOG_LEVEL_ERROR,
1702 "Stopped grabbing the client headers.");
1703 destroy_list(headers);
1704 return JB_ERR_PARSE;
1707 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1710 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1711 destroy_list(headers);
1712 return JB_ERR_PARSE;
1715 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1718 * If there is no memory left for buffering the
1719 * request, there is nothing we can do but hang up
1721 destroy_list(headers);
1722 return JB_ERR_MEMORY;
1727 if (!strncmpic(p, "Transfer-Encoding:", 18))
1730 * XXX: should be called through sed()
1731 * but currently can't.
1733 client_transfer_encoding(csp, &p);
1736 * We were able to read a complete
1737 * header and can finally enlist it.
1744 if (http->host == NULL)
1747 * If we still don't know the request destination,
1748 * the request is invalid or the client uses
1749 * Privoxy without its knowledge.
1751 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1754 * Our attempts to get the request destination
1755 * elsewhere failed or Privoxy is configured
1756 * to only accept proxy requests.
1758 * An error response has already been send
1759 * and we're done here.
1761 return JB_ERR_PARSE;
1765 #ifdef FEATURE_CLIENT_TAGS
1766 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1767 set_client_address(csp, headers);
1768 get_tag_list_for_client(csp->client_tags, csp->client_address);
1772 * Determine the actions for this URL
1774 #ifdef FEATURE_TOGGLE
1775 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1777 /* Most compatible set of actions (i.e. none) */
1778 init_current_action(csp->action);
1781 #endif /* ndef FEATURE_TOGGLE */
1783 get_url_actions(csp, http);
1786 enlist(csp->headers, http->cmd);
1788 /* Append the previously read headers */
1789 err = list_append_list_unique(csp->headers, headers);
1790 destroy_list(headers);
1797 /*********************************************************************
1799 * Function : parse_client_request
1801 * Description : Parses the client's request and decides what to do
1804 * Note that since we're not using select() we could get
1805 * blocked here if a client connected, then didn't say
1809 * 1 : csp = Current client state (buffers, headers, etc...)
1811 * Returns : JB_ERR_OK or JB_ERR_PARSE
1813 *********************************************************************/
1814 static jb_err parse_client_request(struct client_state *csp)
1816 struct http_request *http = csp->http;
1819 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1820 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1821 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1822 && (csp->http->ssl == 0))
1824 /* Assume persistence until further notice */
1825 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1828 if (csp->http->ssl == 0)
1831 * This whole block belongs to chat() but currently
1832 * has to be executed before sed().
1834 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1836 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1838 return JB_ERR_PARSE;
1843 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1845 verify_request_length(csp);
1847 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1849 err = sed(csp, FILTER_CLIENT_HEADERS);
1850 if (JB_ERR_OK != err)
1852 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1854 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1855 csp->ip_addr_str, csp->http->cmd);
1856 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1857 return JB_ERR_PARSE;
1859 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1861 /* Check request line for rewrites. */
1862 if ((NULL == csp->headers->first->str)
1863 || (strcmp(http->cmd, csp->headers->first->str) &&
1864 (JB_ERR_OK != change_request_destination(csp))))
1867 * A header filter broke the request line - bail out.
1869 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1870 /* XXX: Use correct size */
1871 log_error(LOG_LEVEL_CLF,
1872 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1873 log_error(LOG_LEVEL_ERROR,
1874 "Invalid request line after applying header filters.");
1875 free_http_request(http);
1877 return JB_ERR_PARSE;
1880 if (client_has_unsupported_expectations(csp))
1882 return JB_ERR_PARSE;
1890 /*********************************************************************
1892 * Function : send_http_request
1894 * Description : Sends the HTTP headers from the client request
1895 * and all the body data that has already been received.
1898 * 1 : csp = Current client state (buffers, headers, etc...)
1900 * Returns : 0 on success, anything else is na error.
1902 *********************************************************************/
1903 static int send_http_request(struct client_state *csp)
1908 hdr = list_to_text(csp->headers);
1911 /* FIXME Should handle error properly */
1912 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1914 list_remove_all(csp->headers);
1917 * Write the client's (modified) header to the server
1918 * (along with anything else that may be in the buffer)
1920 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
1925 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
1926 csp->http->hostport);
1928 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
1929 && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
1932 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
1933 csp->http->hostport);
1936 return write_failure;
1941 /*********************************************************************
1943 * Function : handle_established_connection
1945 * Description : Shuffle data between client and server once the
1946 * connection has been established.
1949 * 1 : csp = Current client state (buffers, headers, etc...)
1951 * Returns : Nothing.
1953 *********************************************************************/
1954 static void handle_established_connection(struct client_state *csp,
1955 const struct forward_spec *fwd)
1957 char buf[BUFFER_SIZE];
1964 int ms_iis5_hack = 0;
1965 unsigned long long byte_count = 0;
1966 struct http_request *http;
1967 long len = 0; /* for buffer sizes (and negative error codes) */
1968 int buffer_and_filter_content = 0;
1970 /* Skeleton for HTTP response, if we should intercept the request */
1971 struct http_response *rsp;
1972 struct timeval timeout;
1973 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1974 int watch_client_socket;
1977 memset(buf, 0, sizeof(buf));
1981 maxfd = (csp->cfd > csp->server_connection.sfd) ?
1982 csp->cfd : csp->server_connection.sfd;
1984 /* pass data between the client and server
1985 * until one or the other shuts down the connection.
1990 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1991 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
1998 * FD_ZERO here seems to point to an errant macro which crashes.
1999 * So do this by hand for now...
2001 memset(&rfds,0x00,sizeof(fd_set));
2005 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2006 if (!watch_client_socket)
2008 maxfd = csp->server_connection.sfd;
2011 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2013 FD_SET(csp->cfd, &rfds);
2016 FD_SET(csp->server_connection.sfd, &rfds);
2018 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2019 if ((csp->flags & CSP_FLAG_CHUNKED)
2020 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2021 && ((csp->iob->eod - csp->iob->cur) >= 5)
2022 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2025 * XXX: This check should be obsolete now,
2026 * but let's wait a while to be sure.
2028 log_error(LOG_LEVEL_CONNECT,
2029 "Looks like we got the last chunk together with "
2030 "the server headers but didn't detect it earlier. "
2031 "We better stop reading.");
2032 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2033 csp->expected_content_length = byte_count;
2034 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2036 if (server_body && server_response_is_complete(csp, byte_count))
2038 if (csp->expected_content_length == byte_count)
2040 log_error(LOG_LEVEL_CONNECT,
2041 "Done reading from server. Content length: %llu as expected. "
2042 "Bytes most recently read: %d.",
2047 log_error(LOG_LEVEL_CONNECT,
2048 "Done reading from server. Expected content length: %llu. "
2049 "Actual content length: %llu. Bytes most recently read: %d.",
2050 csp->expected_content_length, byte_count, len);
2054 * XXX: should not jump around,
2055 * chat() is complicated enough already.
2059 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2061 timeout.tv_sec = csp->config->socket_timeout;
2062 timeout.tv_usec = 0;
2063 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2067 log_error(LOG_LEVEL_ERROR,
2068 "Didn't receive data in time: %s", http->url);
2069 if ((byte_count == 0) && (http->ssl == 0))
2071 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2073 mark_server_socket_tainted(csp);
2078 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2079 mark_server_socket_tainted(csp);
2084 * This is the body of the browser's request,
2085 * just read and write it.
2087 * XXX: Make sure the client doesn't use pipelining
2088 * behind Privoxy's back.
2090 if (FD_ISSET(csp->cfd, &rfds))
2092 int max_bytes_to_read = sizeof(buf) - 1;
2094 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2095 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2097 if (data_is_available(csp->cfd, 0))
2100 * If the next request is already waiting, we have
2101 * to stop select()ing the client socket. Otherwise
2102 * we would always return right away and get nothing
2105 watch_client_socket = 0;
2106 log_error(LOG_LEVEL_CONNECT,
2107 "Stopping to watch the client socket %d. "
2108 "There's already another request waiting.",
2113 * If the client socket is set, but there's no data
2114 * available on the socket, the client went fishing
2115 * and continuing talking to the server makes no sense.
2117 log_error(LOG_LEVEL_CONNECT,
2118 "The client closed socket %d while "
2119 "the server socket %d is still open.",
2120 csp->cfd, csp->server_connection.sfd);
2121 mark_server_socket_tainted(csp);
2124 if (csp->expected_client_content_length != 0)
2126 if (csp->expected_client_content_length < (sizeof(buf) - 1))
2128 max_bytes_to_read = (int)csp->expected_client_content_length;
2130 log_error(LOG_LEVEL_CONNECT,
2131 "Waiting for up to %d bytes from the client.",
2134 assert(max_bytes_to_read < sizeof(buf));
2135 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2137 len = read_socket(csp->cfd, buf, max_bytes_to_read);
2141 /* XXX: not sure if this is necessary. */
2142 mark_server_socket_tainted(csp);
2143 break; /* "game over, man" */
2146 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2147 if (csp->expected_client_content_length != 0)
2149 assert(len <= max_bytes_to_read);
2150 csp->expected_client_content_length -= (unsigned)len;
2151 log_error(LOG_LEVEL_CONNECT,
2152 "Expected client content length set to %llu "
2153 "after reading %d bytes.",
2154 csp->expected_client_content_length, len);
2155 if (csp->expected_client_content_length == 0)
2157 log_error(LOG_LEVEL_CONNECT,
2158 "Done reading from the client.");
2159 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2162 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2164 if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
2166 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2167 mark_server_socket_tainted(csp);
2174 * The server wants to talk. It could be the header or the body.
2175 * If `hdr' is null, then it's the header otherwise it's the body.
2176 * FIXME: Does `hdr' really mean `host'? No.
2178 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2180 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2182 * If we are buffering content, we don't want to eat up to
2183 * buffer-limit bytes if the client no longer cares about them.
2184 * If we aren't buffering, however, a dead client socket will be
2185 * noticed pretty much right away anyway, so we can reduce the
2186 * overhead by skipping the check.
2188 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2191 log_error(LOG_LEVEL_CONNECT,
2192 "The server still wants to talk, but the client may already have hung up on us.");
2194 log_error(LOG_LEVEL_CONNECT,
2195 "The server still wants to talk, but the client hung up on us.");
2196 mark_server_socket_tainted(csp);
2198 #endif /* def _WIN32 */
2200 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2202 len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
2206 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2208 if (http->ssl && (fwd->forward_host == NULL))
2211 * Just hang up. We already confirmed the client's CONNECT
2212 * request with status code 200 and unencrypted content is
2213 * no longer welcome.
2215 log_error(LOG_LEVEL_ERROR,
2216 "CONNECT already confirmed. Unable to tell the client about the problem.");
2219 else if (byte_count)
2222 * Just hang up. We already transmitted the original headers
2223 * and parts of the original content and therefore missed the
2224 * chance to send an error message (without risking data corruption).
2226 * XXX: we could retry with a fancy range request here.
2228 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2229 "Unable to tell the client about the problem.");
2230 mark_server_socket_tainted(csp);
2234 * XXX: Consider handling the cases above the same.
2236 mark_server_socket_tainted(csp);
2240 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2241 if (csp->flags & CSP_FLAG_CHUNKED)
2243 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2245 /* XXX: this is a temporary hack */
2246 log_error(LOG_LEVEL_CONNECT,
2247 "Looks like we reached the end of the last chunk. "
2248 "We better stop reading.");
2249 csp->expected_content_length = byte_count + (unsigned long long)len;
2250 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2254 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2257 * Add a trailing zero to let be able to use string operations.
2258 * XXX: do we still need this with filter_popups gone?
2263 * Normally, this would indicate that we've read
2264 * as much as the server has sent us and we can
2265 * close the client connection. However, Microsoft
2266 * in its wisdom has released IIS/5 with a bug that
2267 * prevents it from sending the trailing \r\n in
2268 * a 302 redirect header (and possibly other headers).
2269 * To work around this if we've haven't parsed
2270 * a full header we'll append a trailing \r\n
2271 * and see if this now generates a valid one.
2273 * This hack shouldn't have any impacts. If we've
2274 * already transmitted the header or if this is a
2275 * SSL connection, then we won't bother with this
2276 * hack. So we only work on partially received
2277 * headers. If we append a \r\n and this still
2278 * doesn't generate a valid header, then we won't
2279 * transmit anything to the client.
2284 if (server_body || http->ssl)
2287 * If we have been buffering up the document,
2288 * now is the time to apply content modification
2289 * and send the result to the client.
2291 if (buffer_and_filter_content)
2293 p = execute_content_filters(csp);
2295 * If content filtering fails, use the original
2296 * buffer and length.
2297 * (see p != NULL ? p : csp->iob->cur below)
2301 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2303 #ifdef FEATURE_COMPRESSION
2304 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2305 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2307 char *compressed_content = compress_buffer(p,
2308 (size_t *)&csp->content_length, csp->config->compression_level);
2309 if (compressed_content != NULL)
2312 p = compressed_content;
2313 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2318 if (JB_ERR_OK != update_server_headers(csp))
2320 log_error(LOG_LEVEL_FATAL,
2321 "Failed to update server headers. after filtering.");
2324 hdr = list_to_text(csp->headers);
2327 /* FIXME Should handle error properly */
2328 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2331 if (write_socket(csp->cfd, hdr, strlen(hdr))
2332 || write_socket(csp->cfd,
2333 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2335 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2338 mark_server_socket_tainted(csp);
2346 break; /* "game over, man" */
2350 * This is NOT the body, so
2351 * Let's pretend the server just sent us a blank line.
2353 snprintf(buf, sizeof(buf), "\r\n");
2354 len = (int)strlen(buf);
2357 * Now, let the normal header parsing algorithm below do its
2358 * job. If it fails, we'll exit instead of continuing.
2365 * If this is an SSL connection or we're in the body
2366 * of the server document, just write it to the client,
2367 * unless we need to buffer the body for later content-filtering
2369 if (server_body || http->ssl)
2371 if (buffer_and_filter_content)
2374 * If there is no memory left for buffering the content, or the buffer limit
2375 * has been reached, switch to non-filtering mode, i.e. make & write the
2376 * header, flush the iob and buf, and get out of the way.
2378 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2383 log_error(LOG_LEVEL_INFO,
2384 "Flushing header and buffers. Stepping back from filtering.");
2386 hdr = list_to_text(csp->headers);
2390 * Memory is too tight to even generate the header.
2391 * Send our static "Out-of-memory" page.
2393 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2394 rsp = cgi_error_memory();
2395 send_crunch_response(csp, rsp);
2396 mark_server_socket_tainted(csp);
2399 hdrlen = strlen(hdr);
2401 if (write_socket(csp->cfd, hdr, hdrlen)
2402 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2403 || (write_socket(csp->cfd, buf, (size_t)len)))
2405 log_error(LOG_LEVEL_CONNECT,
2406 "Flush header and buffers to client failed: %E");
2408 mark_server_socket_tainted(csp);
2413 * Reset the byte_count to the amount of bytes
2414 * we just flushed. len will be added a few lines below,
2415 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2417 byte_count = (unsigned long long)flushed;
2419 buffer_and_filter_content = 0;
2425 if (write_socket(csp->cfd, buf, (size_t)len))
2427 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2428 mark_server_socket_tainted(csp);
2432 byte_count += (unsigned long long)len;
2438 * We're still looking for the end of the server's header.
2439 * Buffer up the data we just read. If that fails, there's
2440 * little we can do but send our static out-of-memory page.
2442 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2444 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2445 rsp = cgi_error_memory();
2446 send_crunch_response(csp, rsp);
2447 mark_server_socket_tainted(csp);
2451 /* Convert iob into something sed() can digest */
2452 if (JB_ERR_PARSE == get_server_headers(csp))
2457 * Well, we tried our MS IIS/5 hack and it didn't work.
2458 * The header is incomplete and there isn't anything
2459 * we can do about it.
2461 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2462 "Applying the MS IIS5 hack didn't help.");
2463 log_error(LOG_LEVEL_CLF,
2464 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2465 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2466 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2467 mark_server_socket_tainted(csp);
2473 * Since we have to wait for more from the server before
2474 * we can parse the headers we just continue here.
2476 log_error(LOG_LEVEL_CONNECT,
2477 "Continuing buffering server headers from socket %d. "
2478 "Bytes most recently read: %d.", csp->cfd, len);
2485 * Account for the content bytes we
2486 * might have gotten with the headers.
2488 assert(csp->iob->eod >= csp->iob->cur);
2489 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2492 /* Did we actually get anything? */
2493 if (NULL == csp->headers->first)
2495 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2497 log_error(LOG_LEVEL_ERROR,
2498 "No server or forwarder response received on socket %d. "
2499 "Closing client socket %d without sending data.",
2500 csp->server_connection.sfd, csp->cfd);
2501 log_error(LOG_LEVEL_CLF,
2502 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2506 log_error(LOG_LEVEL_ERROR,
2507 "No server or forwarder response received on socket %d.",
2508 csp->server_connection.sfd);
2509 send_crunch_response(csp, error_response(csp, "no-server-data"));
2511 free_http_request(http);
2512 mark_server_socket_tainted(csp);
2516 assert(csp->headers->first->str);
2518 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2519 strncmpic(csp->headers->first->str, "ICY", 3))
2522 * It doesn't look like a HTTP (or Shoutcast) response:
2523 * tell the client and log the problem.
2525 if (strlen(csp->headers->first->str) > 30)
2527 csp->headers->first->str[30] = '\0';
2529 log_error(LOG_LEVEL_ERROR,
2530 "Invalid server or forwarder response. Starts with: %s",
2531 csp->headers->first->str);
2532 log_error(LOG_LEVEL_CLF,
2533 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2534 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2535 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2536 free_http_request(http);
2537 mark_server_socket_tainted(csp);
2542 * We have now received the entire server header,
2543 * filter it and send the result to the client
2545 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2547 log_error(LOG_LEVEL_CLF,
2548 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2549 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2550 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2551 free_http_request(http);
2552 mark_server_socket_tainted(csp);
2555 hdr = list_to_text(csp->headers);
2558 /* FIXME Should handle error properly */
2559 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2562 if ((csp->flags & CSP_FLAG_CHUNKED)
2563 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2564 && ((csp->iob->eod - csp->iob->cur) >= 5)
2565 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2567 log_error(LOG_LEVEL_CONNECT,
2568 "Looks like we got the last chunk together with "
2569 "the server headers. We better stop reading.");
2570 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2571 csp->expected_content_length = byte_count;
2572 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2575 csp->server_connection.response_received = time(NULL);
2577 if (crunch_response_triggered(csp, crunchers_light))
2580 * One of the tags created by a server-header
2581 * tagger triggered a crunch. We already
2582 * delivered the crunch response to the client
2583 * and are done here after cleaning up.
2586 mark_server_socket_tainted(csp);
2589 /* Buffer and pcrs filter this if appropriate. */
2591 if (!http->ssl) /* We talk plaintext */
2593 buffer_and_filter_content = content_requires_filtering(csp);
2596 * Only write if we're not buffering for content modification
2598 if (!buffer_and_filter_content)
2601 * Write the server's (modified) header to
2602 * the client (along with anything else that
2603 * may be in the buffer)
2606 if (write_socket(csp->cfd, hdr, strlen(hdr))
2607 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2609 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2612 * The write failed, so don't bother mentioning it
2613 * to the client... it probably can't hear us anyway.
2616 mark_server_socket_tainted(csp);
2621 /* we're finished with the server's header */
2627 * If this was a MS IIS/5 hack then it means the server
2628 * has already closed the connection. Nothing more to read.
2633 log_error(LOG_LEVEL_ERROR,
2634 "Closed server connection detected. "
2635 "Applying the MS IIS5 hack didn't help.");
2636 log_error(LOG_LEVEL_CLF,
2637 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2638 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2639 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2640 mark_server_socket_tainted(csp);
2646 mark_server_socket_tainted(csp);
2647 return; /* huh? we should never get here */
2650 if (csp->content_length == 0)
2653 * If Privoxy didn't recalculate the Content-Length,
2654 * byte_count is still correct.
2656 csp->content_length = byte_count;
2659 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2660 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2661 && (csp->expected_content_length != byte_count))
2663 log_error(LOG_LEVEL_CONNECT,
2664 "Received %llu bytes while expecting %llu.",
2665 byte_count, csp->expected_content_length);
2666 mark_server_socket_tainted(csp);
2670 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2671 csp->ip_addr_str, http->ocmd, csp->content_length);
2673 csp->server_connection.timestamp = time(NULL);
2677 /*********************************************************************
2681 * Description : Once a connection from the client has been accepted,
2682 * this function is called (via serve()) to handle the
2683 * main business of the communication. This function
2684 * returns after dealing with a single request. It can
2685 * be called multiple times with the same client socket
2686 * if the client is keeping the connection alive.
2688 * The decision whether or not a client connection will
2689 * be kept alive is up to the caller which also must
2690 * close the client socket when done.
2692 * FIXME: chat is nearly thousand lines long.
2696 * 1 : csp = Current client state (buffers, headers, etc...)
2698 * Returns : Nothing.
2700 *********************************************************************/
2701 static void chat(struct client_state *csp)
2703 char buf[BUFFER_SIZE];
2704 const struct forward_spec *fwd;
2705 struct http_request *http;
2706 /* Skeleton for HTTP response, if we should intercept the request */
2707 struct http_response *rsp;
2709 memset(buf, 0, sizeof(buf));
2713 if (receive_client_request(csp) != JB_ERR_OK)
2717 if (parse_client_request(csp) != JB_ERR_OK)
2722 /* decide how to route the HTTP request */
2723 fwd = forward_url(csp, http);
2726 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2727 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2732 * build the http request to send to the server
2733 * we have to do one of the following:
2735 * create = use the original HTTP request to create a new
2736 * HTTP request that has either the path component
2737 * without the http://domainspec (w/path) or the
2738 * full orininal URL (w/url)
2739 * Note that the path and/or the HTTP version may
2740 * have been altered by now.
2742 * connect = Open a socket to the host:port of the server
2743 * and short-circuit server and client socket.
2745 * pass = Pass the request unchanged if forwarding a CONNECT
2746 * request to a parent proxy. Note that we'll be sending
2747 * the CFAIL message ourselves if connecting to the parent
2748 * fails, but we won't send a CSUCCEED message if it works,
2749 * since that would result in a double message (ours and the
2750 * parent's). After sending the request to the parent, we simply
2753 * here's the matrix:
2756 * +--------+--------+
2758 * 0 | create | connect|
2760 * Forwarding +--------+--------+
2762 * 1 | create | pass |
2764 * +--------+--------+
2768 if (http->ssl && connect_port_is_forbidden(csp))
2770 const char *acceptable_connect_ports =
2771 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
2772 assert(NULL != acceptable_connect_ports);
2773 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
2774 "limit-connect{%s} doesn't allow CONNECT requests to %s",
2775 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
2776 csp->action->flags |= ACTION_BLOCK;
2782 freez(csp->headers->first->str);
2783 build_request_line(csp, fwd, &csp->headers->first->str);
2787 * We have a request. Check if one of the crunchers wants it.
2789 if (crunch_response_triggered(csp, crunchers_all))
2792 * Yes. The client got the crunch response and we're done here.
2797 log_applied_actions(csp->action);
2798 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
2800 if (fwd->forward_host)
2802 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
2803 fwd->forward_host, fwd->forward_port, http->hostport);
2807 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
2810 /* here we connect to the server, gateway, or the forwarder */
2812 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2813 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
2814 && socket_is_still_alive(csp->server_connection.sfd)
2815 && connection_destination_matches(&csp->server_connection, http, fwd))
2817 log_error(LOG_LEVEL_CONNECT,
2818 "Reusing server socket %d connected to %s. Total requests: %u.",
2819 csp->server_connection.sfd, csp->server_connection.host,
2820 csp->server_connection.requests_sent_total);
2824 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2826 #ifdef FEATURE_CONNECTION_SHARING
2827 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2829 remember_connection(&csp->server_connection);
2832 #endif /* def FEATURE_CONNECTION_SHARING */
2834 log_error(LOG_LEVEL_CONNECT,
2835 "Closing server socket %d connected to %s. Total requests: %u.",
2836 csp->server_connection.sfd, csp->server_connection.host,
2837 csp->server_connection.requests_sent_total);
2838 close_socket(csp->server_connection.sfd);
2840 mark_connection_closed(&csp->server_connection);
2842 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2844 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
2846 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
2848 if (fwd->type != SOCKS_NONE)
2851 rsp = error_response(csp, "forwarding-failed");
2853 else if (errno == EINVAL)
2855 rsp = error_response(csp, "no-such-domain");
2859 rsp = error_response(csp, "connect-failed");
2862 /* Write the answer to the client */
2865 send_crunch_response(csp, rsp);
2869 * Temporary workaround to prevent already-read client
2870 * bodies from being parsed as new requests. For now we
2871 * err on the safe side and throw all the following
2872 * requests under the bus, even if no client body has been
2873 * buffered. A compliant client will repeat the dropped
2874 * requests on an untainted connection.
2876 * The proper fix is to discard the no longer needed
2877 * client body in the buffer (if there is one) and to
2878 * continue parsing the bytes that follow.
2880 drain_and_close_socket(csp->cfd);
2881 csp->cfd = JB_INVALID_SOCKET;
2885 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2886 save_connection_destination(csp->server_connection.sfd,
2887 http, fwd, &csp->server_connection);
2888 csp->server_connection.keep_alive_timeout =
2889 (unsigned)csp->config->keep_alive_timeout;
2891 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2893 csp->server_connection.requests_sent_total++;
2895 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
2897 /* Client headers have been sent optimistically */
2898 assert(csp->headers->last == NULL);
2900 else if (fwd->forward_host || (http->ssl == 0))
2902 if (send_http_request(csp))
2904 rsp = error_response(csp, "connect-failed");
2907 send_crunch_response(csp, rsp);
2915 * We're running an SSL tunnel and we're not forwarding,
2916 * so just ditch the client headers, send the "connect succeeded"
2917 * message to the client, flush the rest, and get out of the way.
2919 list_remove_all(csp->headers);
2920 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
2924 clear_iob(csp->client_iob);
2927 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
2929 /* XXX: should the time start earlier for optimistically sent data? */
2930 csp->server_connection.request_sent = time(NULL);
2932 handle_established_connection(csp, fwd);
2937 /*********************************************************************
2939 * Function : fuzz_server_response
2941 * Description : Treat the input as a whole server response.
2944 * 1 : csp = Current client state (buffers, headers, etc...)
2945 * 2 : fuzz_input_file = File to read the input from.
2949 *********************************************************************/
2950 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
2952 static struct forward_spec fwd; /* Zero'd due to being static */
2955 if (strcmp(fuzz_input_file, "-") == 0)
2957 /* XXX: Doesn'T work yet. */
2958 csp->server_connection.sfd = 0;
2962 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
2963 if (csp->server_connection.sfd == -1)
2965 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
2969 csp->content_type |= CT_GIF;
2970 csp->action->flags |= ACTION_DEANIMATE;
2971 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
2973 csp->http->path = strdup_or_die("/");
2974 csp->http->host = strdup_or_die("fuzz.example.org");
2975 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
2976 /* Prevent client socket monitoring */
2977 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
2978 csp->flags |= CSP_FLAG_CHUNKED;
2980 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
2981 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2983 csp->content_type |= CT_DECLARED|CT_GIF;
2985 csp->config->socket_timeout = 0;
2987 cgi_init_error_messages();
2989 handle_established_connection(csp, &fwd);
2996 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2997 /*********************************************************************
2999 * Function : prepare_csp_for_next_request
3001 * Description : Put the csp in a mostly vergin state.
3004 * 1 : csp = Current client state (buffers, headers, etc...)
3008 *********************************************************************/
3009 static void prepare_csp_for_next_request(struct client_state *csp)
3011 csp->content_type = 0;
3012 csp->content_length = 0;
3013 csp->expected_content_length = 0;
3014 csp->expected_client_content_length = 0;
3015 list_remove_all(csp->headers);
3016 clear_iob(csp->iob);
3017 freez(csp->error_message);
3018 free_http_request(csp->http);
3019 destroy_list(csp->headers);
3020 destroy_list(csp->tags);
3021 #ifdef FEATURE_CLIENT_TAGS
3022 destroy_list(csp->client_tags);
3023 freez(csp->client_address);
3025 free_current_action(csp->action);
3026 if (NULL != csp->fwd)
3028 unload_forward_spec(csp->fwd);
3031 /* XXX: Store per-connection flags someplace else. */
3032 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
3033 #ifdef FEATURE_TOGGLE
3034 if (global_toggle_state)
3035 #endif /* def FEATURE_TOGGLE */
3037 csp->flags |= CSP_FLAG_TOGGLED_ON;
3040 if (csp->client_iob->eod > csp->client_iob->cur)
3042 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
3043 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
3045 assert(bytes_to_shift > 0);
3046 assert(data_length > 0);
3048 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
3049 data_length, bytes_to_shift);
3050 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
3051 csp->client_iob->cur = csp->client_iob->buf;
3052 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
3053 csp->client_iob->eod = csp->client_iob->buf + data_length;
3054 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
3056 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3061 * We mainly care about resetting client_iob->cur so we don't
3062 * waste buffer space at the beginning and don't mess up the
3063 * request restoration done by cgi_show_request().
3065 * Freeing the buffer itself isn't technically necessary,
3066 * but makes debugging more convenient.
3068 clear_iob(csp->client_iob);
3071 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3074 /*********************************************************************
3078 * Description : This is little more than chat. We only "serve" to
3079 * to close (or remember) any socket that chat may have
3083 * 1 : csp = Current client state (buffers, headers, etc...)
3087 *********************************************************************/
3089 void serve(struct client_state *csp)
3090 #else /* ifndef AMIGA */
3091 static void serve(struct client_state *csp)
3092 #endif /* def AMIGA */
3094 int config_file_change_detected = 0; /* Only used for debugging */
3095 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3096 #ifdef FEATURE_CONNECTION_SHARING
3097 static int monitor_thread_running = 0;
3098 #endif /* def FEATURE_CONNECTION_SHARING */
3099 int continue_chatting = 0;
3101 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
3102 csp->ip_addr_str, csp->cfd);
3106 unsigned int latency;
3111 * If the request has been crunched,
3112 * the calculated latency is zero.
3114 latency = (unsigned)(csp->server_connection.response_received -
3115 csp->server_connection.request_sent) / 2;
3117 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3118 && (csp->flags & CSP_FLAG_CRUNCHED)
3119 && (csp->expected_client_content_length != 0))
3121 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
3122 log_error(LOG_LEVEL_CONNECT,
3123 "Tainting client socket %d due to unread data.", csp->cfd);
3126 continue_chatting = (csp->config->feature_flags
3127 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3128 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3129 && (csp->cfd != JB_INVALID_SOCKET)
3130 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3131 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3132 || (csp->flags & CSP_FLAG_CHUNKED));
3134 if (!(csp->flags & CSP_FLAG_CRUNCHED)
3135 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
3137 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
3139 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
3141 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
3142 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3143 || !socket_is_still_alive(csp->server_connection.sfd)
3144 || !(latency < csp->server_connection.keep_alive_timeout))
3146 log_error(LOG_LEVEL_CONNECT,
3147 "Closing server socket %d connected to %s. "
3148 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
3149 csp->server_connection.sfd, csp->server_connection.host,
3150 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3151 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3152 socket_is_still_alive(csp->server_connection.sfd),
3153 csp->server_connection.keep_alive_timeout);
3154 #ifdef FEATURE_CONNECTION_SHARING
3155 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3157 forget_connection(csp->server_connection.sfd);
3159 #endif /* def FEATURE_CONNECTION_SHARING */
3160 close_socket(csp->server_connection.sfd);
3161 mark_connection_closed(&csp->server_connection);
3165 if (continue_chatting && any_loaded_file_changed(csp))
3167 continue_chatting = 0;
3168 config_file_change_detected = 1;
3171 if (continue_chatting)
3173 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
3174 && socket_is_still_alive(csp->cfd))
3176 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
3177 "pipelined on socket %d and the socket is still alive.",
3178 csp->requests_received_total+1, csp->cfd);
3179 prepare_csp_for_next_request(csp);
3183 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3185 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3187 log_error(LOG_LEVEL_CONNECT,
3188 "Waiting for the next client request on socket %d. "
3189 "Keeping the server socket %d to %s open.",
3190 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
3194 log_error(LOG_LEVEL_CONNECT,
3195 "Waiting for the next client request on socket %d. "
3196 "No server socket to keep open.", csp->cfd);
3200 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3201 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
3202 && socket_is_still_alive(csp->cfd))
3204 log_error(LOG_LEVEL_CONNECT,
3205 "Client request %u arrived in time on socket %d.",
3206 csp->requests_received_total+1, csp->cfd);
3207 prepare_csp_for_next_request(csp);
3211 #ifdef FEATURE_CONNECTION_SHARING
3212 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3213 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3214 && (socket_is_still_alive(csp->server_connection.sfd)))
3216 time_t time_open = time(NULL) - csp->server_connection.timestamp;
3218 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3223 remember_connection(&csp->server_connection);
3224 csp->server_connection.sfd = JB_INVALID_SOCKET;
3225 drain_and_close_socket(csp->cfd);
3226 csp->cfd = JB_INVALID_SOCKET;
3227 privoxy_mutex_lock(&connection_reuse_mutex);
3228 if (!monitor_thread_running)
3230 monitor_thread_running = 1;
3231 privoxy_mutex_unlock(&connection_reuse_mutex);
3232 wait_for_alive_connections();
3233 privoxy_mutex_lock(&connection_reuse_mutex);
3234 monitor_thread_running = 0;
3236 privoxy_mutex_unlock(&connection_reuse_mutex);
3238 #endif /* def FEATURE_CONNECTION_SHARING */
3242 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3244 log_error(LOG_LEVEL_CONNECT,
3245 "Closing server socket %d connected to %s. Keep-alive: %u. "
3246 "Tainted: %u. Socket alive: %u. Timeout: %u. "
3247 "Configuration file change detected: %u",
3248 csp->server_connection.sfd, csp->server_connection.host,
3249 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3250 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3251 socket_is_still_alive(csp->server_connection.sfd),
3252 csp->server_connection.keep_alive_timeout,
3253 config_file_change_detected);
3255 } while (continue_chatting);
3259 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3261 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3263 #ifdef FEATURE_CONNECTION_SHARING
3264 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3266 forget_connection(csp->server_connection.sfd);
3268 #endif /* def FEATURE_CONNECTION_SHARING */
3269 close_socket(csp->server_connection.sfd);
3272 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3273 mark_connection_closed(&csp->server_connection);
3276 if (csp->cfd != JB_INVALID_SOCKET)
3278 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3279 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3280 "Configuration file change detected: %u. Requests received: %u.",
3281 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3282 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3283 config_file_change_detected, csp->requests_received_total);
3284 drain_and_close_socket(csp->cfd);
3287 csp->flags &= ~CSP_FLAG_ACTIVE;
3293 /*********************************************************************
3295 * Function : server_thread
3297 * Description : We only exist to call `serve' in a threaded environment.
3300 * 1 : data = Current client state (buffers, headers, etc...)
3302 * Returns : Always 0.
3304 *********************************************************************/
3305 static int32 server_thread(void *data)
3307 serve((struct client_state *) data);
3314 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3315 /*********************************************************************
3319 * Description : Print usage info & exit.
3321 * Parameters : Pointer to argv[0] for identifying ourselves
3325 *********************************************************************/
3326 static void usage(const char *name)
3328 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3329 "Usage: %s [--config-test] "
3332 #endif /* defined(unix) */
3335 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3336 #endif /* defined(unix) */
3337 "[--version] [configfile]\n",
3341 show_fuzz_usage(name);
3344 printf("Aborting\n");
3349 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3352 #ifdef MUTEX_LOCKS_AVAILABLE
3353 /*********************************************************************
3355 * Function : privoxy_mutex_lock
3357 * Description : Locks a mutex.
3360 * 1 : mutex = The mutex to lock.
3362 * Returns : Void. May exit in case of errors.
3364 *********************************************************************/
3365 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3367 #ifdef FEATURE_PTHREAD
3368 int err = pthread_mutex_lock(mutex);
3371 if (mutex != &log_mutex)
3373 log_error(LOG_LEVEL_FATAL,
3374 "Mutex locking failed: %s.\n", strerror(err));
3379 EnterCriticalSection(mutex);
3380 #endif /* def FEATURE_PTHREAD */
3384 /*********************************************************************
3386 * Function : privoxy_mutex_unlock
3388 * Description : Unlocks a mutex.
3391 * 1 : mutex = The mutex to unlock.
3393 * Returns : Void. May exit in case of errors.
3395 *********************************************************************/
3396 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3398 #ifdef FEATURE_PTHREAD
3399 int err = pthread_mutex_unlock(mutex);
3402 if (mutex != &log_mutex)
3404 log_error(LOG_LEVEL_FATAL,
3405 "Mutex unlocking failed: %s.\n", strerror(err));
3410 LeaveCriticalSection(mutex);
3411 #endif /* def FEATURE_PTHREAD */
3415 /*********************************************************************
3417 * Function : privoxy_mutex_init
3419 * Description : Prepares a mutex.
3422 * 1 : mutex = The mutex to initialize.
3424 * Returns : Void. May exit in case of errors.
3426 *********************************************************************/
3427 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3429 #ifdef FEATURE_PTHREAD
3430 int err = pthread_mutex_init(mutex, 0);
3433 printf("Fatal error. Mutex initialization failed: %s.\n",
3438 InitializeCriticalSection(mutex);
3439 #endif /* def FEATURE_PTHREAD */
3441 #endif /* def MUTEX_LOCKS_AVAILABLE */
3443 /*********************************************************************
3445 * Function : initialize_mutexes
3447 * Description : Prepares mutexes if mutex support is available.
3451 * Returns : Void, exits in case of errors.
3453 *********************************************************************/
3454 static void initialize_mutexes(void)
3456 #ifdef MUTEX_LOCKS_AVAILABLE
3458 * Prepare global mutex semaphores
3460 privoxy_mutex_init(&log_mutex);
3461 privoxy_mutex_init(&log_init_mutex);
3462 privoxy_mutex_init(&connection_reuse_mutex);
3463 #ifdef FEATURE_EXTERNAL_FILTERS
3464 privoxy_mutex_init(&external_filter_mutex);
3466 #ifdef FEATURE_CLIENT_TAGS
3467 privoxy_mutex_init(&client_tags_mutex);
3471 * XXX: The assumptions below are a bit naive
3472 * and can cause locks that aren't necessary.
3474 * For example older FreeBSD versions (< 6.x?)
3475 * have no gethostbyname_r, but gethostbyname is
3478 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3479 privoxy_mutex_init(&resolver_mutex);
3480 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3482 * XXX: should we use a single mutex for
3483 * localtime() and gmtime() as well?
3485 #ifndef HAVE_GMTIME_R
3486 privoxy_mutex_init(&gmtime_mutex);
3487 #endif /* ndef HAVE_GMTIME_R */
3489 #ifndef HAVE_LOCALTIME_R
3490 privoxy_mutex_init(&localtime_mutex);
3491 #endif /* ndef HAVE_GMTIME_R */
3493 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
3494 privoxy_mutex_init(&rand_mutex);
3495 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
3497 #endif /* def MUTEX_LOCKS_AVAILABLE */
3500 /*********************************************************************
3504 * Description : Load the config file and start the listen loop.
3505 * This function is a lot more *sane* with the `load_config'
3506 * and `listen_loop' functions; although it stills does
3507 * a *little* too much for my taste.
3510 * 1 : argc = Number of parameters (including $0).
3511 * 2 : argv = Array of (char *)'s to the parameters.
3513 * Returns : 1 if : can't open config file, unrecognized directive,
3514 * stats requested in multi-thread mode, can't open the
3515 * log file, can't open the jar file, listen port is invalid,
3516 * any load fails, and can't bind port.
3518 * Else main never returns, the process must be signaled
3519 * to terminate execution. Or, on Windows, use the
3520 * "File", "Exit" menu option.
3522 *********************************************************************/
3524 int real_main(int argc, char **argv)
3526 int main(int argc, char **argv)
3530 int do_config_test = 0;
3531 #ifndef HAVE_ARC4RANDOM
3532 unsigned int random_seed;
3535 struct passwd *pw = NULL;
3536 struct group *grp = NULL;
3538 char *pre_chroot_nslookup_to_load_resolver = NULL;
3541 char *fuzz_input_type = NULL;
3542 char *fuzz_input_file = NULL;
3549 #if !defined(_WIN32)
3556 /* Prepare mutexes if supported and necessary. */
3557 initialize_mutexes();
3559 /* Enable logging until further notice. */
3563 * Parse the command line arguments
3565 * XXX: simply printing usage information in case of
3566 * invalid arguments isn't particularly user friendly.
3568 while (++argc_pos < argc)
3571 /* Check to see if the service must be installed or uninstalled */
3572 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3574 const char *pName = argv[argc_pos] + 9;
3577 exit((install_service(pName)) ? 0 : 1);
3579 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3581 const char *pName = argv[argc_pos] + 11;
3584 exit((uninstall_service(pName)) ? 0 : 1);
3586 else if (strcmp(argv[argc_pos], "--service") == 0)
3588 bRunAsService = TRUE;
3589 w32_set_service_cwd();
3590 atexit(w32_service_exit_notify);
3593 #endif /* defined(_WIN32) */
3596 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3598 if (strcmp(argv[argc_pos], "--help") == 0)
3603 else if (strcmp(argv[argc_pos], "--version") == 0)
3605 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3611 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3613 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3617 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3619 if (++argc_pos == argc) usage(argv[0]);
3620 pidfile = strdup_or_die(argv[argc_pos]);
3623 else if (strcmp(argv[argc_pos], "--user") == 0)
3628 if (++argc_pos == argc) usage(argv[argc_pos]);
3630 user_arg = strdup_or_die(argv[argc_pos]);
3631 group_name = strchr(user_arg, '.');
3632 if (NULL != group_name)
3634 /* Nul-terminate the user name */
3637 /* Skip the former delimiter to actually reach the group name */
3640 grp = getgrnam(group_name);
3643 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3646 pw = getpwnam(user_arg);
3649 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3655 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3657 if (++argc_pos == argc) usage(argv[0]);
3658 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3661 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3665 #endif /* defined(unix) */
3667 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3672 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
3675 if (argc < argc_pos + 2) usage(argv[0]);
3676 fuzz_input_type = argv[argc_pos];
3678 fuzz_input_file = argv[argc_pos];
3680 else if (strcmp(argv[argc_pos], "--stfu") == 0)
3682 set_debug_level(LOG_LEVEL_STFU);
3685 else if (argc_pos + 1 != argc)
3688 * This is neither the last command line
3689 * option, nor was it recognized before,
3690 * therefore it must be invalid.
3696 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3698 configfile = argv[argc_pos];
3701 } /* -END- while (more arguments) */
3703 show_version(Argv[0]);
3706 if (*configfile != '/')
3708 char cwd[BUFFER_SIZE];
3710 size_t abs_file_size;
3712 /* make config-filename absolute here */
3713 if (NULL == getcwd(cwd, sizeof(cwd)))
3715 perror("failed to get current working directory");
3719 basedir = strdup_or_die(cwd);
3721 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3722 abs_file = malloc_or_die(abs_file_size);
3723 strlcpy(abs_file, basedir, abs_file_size);
3724 strlcat(abs_file, "/", abs_file_size);
3725 strlcat(abs_file, configfile, abs_file_size);
3726 configfile = abs_file;
3728 #endif /* defined unix */
3732 clients->next = NULL;
3734 /* XXX: factor out initialising after the next stable release. */
3737 #elif defined(_WIN32)
3741 #ifndef HAVE_ARC4RANDOM
3742 random_seed = (unsigned int)time(NULL);
3744 srandom(random_seed);
3747 #endif /* ifdef HAVE_RANDOM */
3748 #endif /* ifndef HAVE_ARC4RANDOM */
3751 * Unix signal handling
3753 * Catch the abort, interrupt and terminate signals for a graceful exit
3754 * Catch the hangup signal so the errlog can be reopened.
3756 * Ignore the broken pipe signal as connection failures
3757 * are handled when and where they occur without relying
3760 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3763 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3765 for (idx = 0; idx < SZ(catched_signals); idx++)
3767 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3768 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3770 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3771 #endif /* ifdef sun */
3773 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3777 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3779 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3783 #else /* ifdef _WIN32 */
3784 # ifdef _WIN_CONSOLE
3786 * We *are* in a windows console app.
3787 * Print a verbose messages about FAQ's and such
3789 printf("%s", win32_blurb);
3790 # endif /* def _WIN_CONSOLE */
3791 #endif /* def _WIN32 */
3794 if (fuzz_input_type != NULL)
3796 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
3802 exit(NULL == load_config());
3805 /* Initialize the CGI subsystem */
3806 cgi_init_error_messages();
3809 * If running on unix and without the --no-daemon
3810 * option, become a daemon. I.e. fork, detach
3811 * from tty and get process group leadership
3820 if (pid < 0) /* error */
3825 else if (pid != 0) /* parent */
3830 * must check for errors
3831 * child died due to missing files aso
3834 wpid = waitpid(pid, &status, WNOHANG);
3846 * stderr (fd 2) will be closed later on,
3847 * when the config file has been parsed.
3853 * Reserve fd 0 and 1 to prevent abort() and friends
3854 * from sending stuff to the clients or servers.
3856 fd = open("/dev/null", O_RDONLY);
3859 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3863 if (dup2(fd, 0) == -1)
3865 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3869 fd = open("/dev/null", O_WRONLY);
3872 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3876 if (dup2(fd, 1) == -1)
3878 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3883 #ifdef FEATURE_EXTERNAL_FILTERS
3884 for (fd = 0; fd < 3; fd++)
3886 mark_socket_for_close_on_execute(fd);
3892 } /* -END- if (daemon_mode) */
3895 * As soon as we have written the PID file, we can switch
3896 * to the user and group ID indicated by the --user option
3902 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3904 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3908 if (setgroups(1, &grp->gr_gid))
3910 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3913 else if (initgroups(pw->pw_name, pw->pw_gid))
3915 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3921 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3923 /* Read the time zone file from /etc before doing chroot. */
3925 if (NULL != pre_chroot_nslookup_to_load_resolver
3926 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3928 /* Initialize resolver library. */
3929 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3931 if (chroot(pw->pw_dir) < 0)
3933 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3937 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3940 if (setuid(pw->pw_uid))
3942 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3946 char putenv_dummy[64];
3948 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3949 if (putenv(putenv_dummy) != 0)
3951 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3954 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3955 if (putenv(putenv_dummy) != 0)
3957 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3963 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3966 #endif /* defined unix */
3969 /* This will be FALSE unless the command line specified --service
3973 /* Yup, so now we must attempt to establish a connection
3974 * with the service dispatcher. This will only work if this
3975 * process was launched by the service control manager to
3976 * actually run as a service. If this isn't the case, i've
3977 * known it take around 30 seconds or so for the call to return.
3980 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3981 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3983 /* Service has run, and at this point is now being stopped, so just return */
3988 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3990 /* An error occurred. Usually it's because --service was wrongly specified
3991 * and we were unable to connect to the Service Control Dispatcher because
3992 * it wasn't expecting us and is therefore not listening.
3994 * For now, just continue below to call the listen_loop function.
3997 #endif /* def _WIN32 */
4007 /*********************************************************************
4009 * Function : bind_port_helper
4011 * Description : Bind the listen port. Handles logging, and aborts
4015 * 1 : haddr = Host address to bind to. Use NULL to bind to
4017 * 2 : hport = Specifies port to bind to.
4019 * Returns : Port that was opened.
4021 *********************************************************************/
4022 static jb_socket bind_port_helper(const char *haddr, int hport)
4027 result = bind_port(haddr, hport, &bfd);
4031 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
4035 log_error(LOG_LEVEL_FATAL,
4036 "can't bind to %s:%d: There may be another Privoxy "
4037 "or some other proxy running on port %d",
4038 bind_address, hport, hport);
4041 log_error(LOG_LEVEL_FATAL,
4042 "can't bind to %s:%d: The hostname is not resolvable",
4043 bind_address, hport);
4046 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
4047 bind_address, hport);
4050 /* shouldn't get here */
4051 return JB_INVALID_SOCKET;
4055 if (bfd >= FD_SETSIZE)
4057 log_error(LOG_LEVEL_FATAL,
4058 "Bind socket number too high to use select(): %d >= %d",
4065 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
4070 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
4078 /*********************************************************************
4080 * Function : bind_ports_helper
4082 * Description : Bind the listen ports. Handles logging, and aborts
4086 * 1 : config = Privoxy configuration. Specifies ports
4088 * 2 : sockets = Preallocated array of opened sockets
4089 * corresponding to specification in config.
4090 * All non-opened sockets will be set to
4091 * JB_INVALID_SOCKET.
4093 * Returns : Nothing. Inspect sockets argument.
4095 *********************************************************************/
4096 static void bind_ports_helper(struct configuration_spec * config,
4097 jb_socket sockets[])
4101 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4103 if (config->hport[i])
4105 sockets[i] = bind_port_helper(config->haddr[i], config->hport[i]);
4109 sockets[i] = JB_INVALID_SOCKET;
4112 config->need_bind = 0;
4116 /*********************************************************************
4118 * Function : close_ports_helper
4120 * Description : Close listenings ports.
4123 * 1 : sockets = Array of opened and non-opened sockets to
4124 * close. All sockets will be set to
4125 * JB_INVALID_SOCKET.
4127 * Returns : Nothing.
4129 *********************************************************************/
4130 static void close_ports_helper(jb_socket sockets[])
4134 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4136 if (JB_INVALID_SOCKET != sockets[i])
4138 close_socket(sockets[i]);
4140 sockets[i] = JB_INVALID_SOCKET;
4146 /* Without this simple workaround we get this compiler warning from _beginthread
4147 * warning C4028: formal parameter 1 different from declaration
4149 void w32_service_listen_loop(void *p)
4153 #endif /* def _WIN32 */
4156 /*********************************************************************
4158 * Function : listen_loop
4160 * Description : bind the listen port and enter a "FOREVER" listening loop.
4166 *********************************************************************/
4167 static void listen_loop(void)
4169 struct client_states *csp_list = NULL;
4170 struct client_state *csp = NULL;
4171 jb_socket bfds[MAX_LISTENING_SOCKETS];
4172 struct configuration_spec *config;
4173 unsigned int active_threads = 0;
4175 config = load_config();
4177 #ifdef FEATURE_CONNECTION_SHARING
4179 * XXX: Should be relocated once it no
4180 * longer needs to emit log messages.
4182 initialize_reusable_connections();
4183 #endif /* def FEATURE_CONNECTION_SHARING */
4185 bind_ports_helper(config, bfds);
4187 #ifdef FEATURE_GRACEFUL_TERMINATION
4188 while (!g_terminate)
4193 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
4194 while (waitpid(-1, NULL, WNOHANG) > 0)
4196 /* zombie children */
4198 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
4201 * Free data that was used by died threads
4203 active_threads = sweep();
4207 * Re-open the errlog after HUP signal
4209 if (received_hup_signal)
4211 if (NULL != config->logfile)
4213 init_error_log(Argv[0], config->logfile);
4215 received_hup_signal = 0;
4219 csp_list = zalloc_or_die(sizeof(*csp_list));
4220 csp = &csp_list->csp;
4222 log_error(LOG_LEVEL_CONNECT,
4223 "Waiting for the next client connection. Currently active threads: %d",
4227 * This config may be outdated, but for accept_connection()
4228 * it's fresh enough.
4230 csp->config = config;
4232 if (!accept_connection(csp, bfds))
4234 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
4246 csp->flags |= CSP_FLAG_ACTIVE;
4247 csp->server_connection.sfd = JB_INVALID_SOCKET;
4249 csp->config = config = load_config();
4251 if (config->need_bind)
4254 * Since we were listening to the "old port", we will not see
4255 * a "listen" param change until the next request. So, at
4256 * least 1 more request must be made for us to find the new
4257 * setting. I am simply closing the old socket and binding the
4260 * Which-ever is correct, we will serve 1 more page via the
4261 * old settings. This should probably be a "show-proxy-args"
4262 * request. This should not be a so common of an operation
4263 * that this will hurt people's feelings.
4266 close_ports_helper(bfds);
4268 bind_ports_helper(config, bfds);
4271 #ifdef FEATURE_TOGGLE
4272 if (global_toggle_state)
4273 #endif /* def FEATURE_TOGGLE */
4275 csp->flags |= CSP_FLAG_TOGGLED_ON;
4278 if (run_loader(csp))
4280 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
4281 /* Never get here - LOG_LEVEL_FATAL causes program exit */
4285 if (block_acl(NULL,csp))
4287 log_error(LOG_LEVEL_CONNECT,
4288 "Connection from %s on %s (socket %d) dropped due to ACL",
4289 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
4290 close_socket(csp->cfd);
4291 freez(csp->ip_addr_str);
4292 freez(csp->listen_addr_str);
4296 #endif /* def FEATURE_ACL */
4298 if ((0 != config->max_client_connections)
4299 && (active_threads >= config->max_client_connections))
4301 log_error(LOG_LEVEL_CONNECT,
4302 "Rejecting connection from %s. Maximum number of connections reached.",
4304 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4305 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4306 close_socket(csp->cfd);
4307 freez(csp->ip_addr_str);
4308 freez(csp->listen_addr_str);
4313 /* add it to the list of clients */
4314 csp_list->next = clients->next;
4315 clients->next = csp_list;
4317 if (config->multi_threaded)
4321 /* this is a switch () statement in the C preprocessor - ugh */
4322 #undef SELECTED_ONE_OPTION
4324 /* Use Pthreads in preference to native code */
4325 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
4326 #define SELECTED_ONE_OPTION
4328 pthread_t the_thread;
4329 pthread_attr_t attrs;
4331 pthread_attr_init(&attrs);
4332 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4333 errno = pthread_create(&the_thread, &attrs,
4334 (void * (*)(void *))serve, csp);
4335 child_id = errno ? -1 : 0;
4336 pthread_attr_destroy(&attrs);
4340 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
4341 #define SELECTED_ONE_OPTION
4342 child_id = _beginthread(
4343 (void (*)(void *))serve,
4348 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
4349 #define SELECTED_ONE_OPTION
4350 child_id = _beginthread(
4351 (void(* _Optlink)(void*))serve,
4357 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
4358 #define SELECTED_ONE_OPTION
4360 thread_id tid = spawn_thread
4361 (server_thread, "server", B_NORMAL_PRIORITY, csp);
4363 if ((tid >= 0) && (resume_thread(tid) == B_OK))
4365 child_id = (int) tid;
4374 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
4375 #define SELECTED_ONE_OPTION
4376 csp->cfd = ReleaseSocket(csp->cfd, -1);
4379 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4380 NP_Output, Output(),
4381 NP_CloseOutput, FALSE,
4382 NP_Name, (ULONG)"privoxy child",
4386 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4387 NP_Output, Output(),
4388 NP_CloseOutput, FALSE,
4389 NP_Name, (ULONG)"privoxy child",
4390 NP_StackSize, 200*1024,
4396 ((struct Task *)child_id)->tc_UserData = csp;
4397 Signal((struct Task *)child_id, SIGF_SINGLE);
4402 #if !defined(SELECTED_ONE_OPTION)
4405 /* This block is only needed when using fork().
4406 * When using threads, the server thread was
4407 * created and run by the call to _beginthread().
4409 if (child_id == 0) /* child */
4412 #ifdef FEATURE_TOGGLE
4413 int inherited_toggle_state = global_toggle_state;
4414 #endif /* def FEATURE_TOGGLE */
4419 * If we've been toggled or we've blocked the request, tell Mom
4422 #ifdef FEATURE_TOGGLE
4423 if (inherited_toggle_state != global_toggle_state)
4425 rc |= RC_FLAG_TOGGLED;
4427 #endif /* def FEATURE_TOGGLE */
4429 #ifdef FEATURE_STATISTICS
4430 if (csp->flags & CSP_FLAG_REJECTED)
4432 rc |= RC_FLAG_BLOCKED;
4434 #endif /* ndef FEATURE_STATISTICS */
4438 else if (child_id > 0) /* parent */
4440 /* in a fork()'d environment, the parent's
4441 * copy of the client socket and the CSP
4445 #if !defined(_WIN32) && !defined(__CYGWIN__)
4447 wait(&child_status);
4450 * Evaluate child's return code: If the child has
4451 * - been toggled, toggle ourselves
4452 * - blocked its request, bump up the stats counter
4455 #ifdef FEATURE_TOGGLE
4456 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4458 global_toggle_state = !global_toggle_state;
4460 #endif /* def FEATURE_TOGGLE */
4462 #ifdef FEATURE_STATISTICS
4464 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4468 #endif /* def FEATURE_STATISTICS */
4470 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4471 close_socket(csp->cfd);
4472 csp->flags &= ~CSP_FLAG_ACTIVE;
4476 #undef SELECTED_ONE_OPTION
4477 /* end of cpp switch () */
4482 * Spawning the child failed, assume it's because
4483 * there are too many children running already.
4484 * XXX: If you assume ...
4486 log_error(LOG_LEVEL_ERROR,
4487 "Unable to take any additional connections: %E. Active threads: %d",
4489 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4490 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4491 close_socket(csp->cfd);
4492 csp->flags &= ~CSP_FLAG_ACTIVE;
4501 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4503 /* Clean up. Aim: free all memory (no leaks) */
4504 #ifdef FEATURE_GRACEFUL_TERMINATION
4506 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4508 unload_current_config_file();
4509 unload_current_actions_file();
4510 unload_current_re_filterfile();
4511 #ifdef FEATURE_TRUST
4512 unload_current_trust_file();
4515 if (config->multi_threaded)
4522 } while ((clients->next != NULL) && (--i > 0));
4526 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4536 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4537 /* Cleanup - remove taskbar icon etc. */
4542 #endif /* FEATURE_GRACEFUL_TERMINATION */