1 const char jcc_rcs[] = "$Id: jcc.c,v 1.435 2015/01/24 16:42:57 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-2014 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
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
65 # if !defined (__OS2__)
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
74 #include <sys/termios.h>
85 # include <socket.h> /* BeOS has select() for sockets only. */
86 # include <OS.h> /* declarations for threads and stuff. */
89 # if defined(__EMX__) || defined(__OS2__)
90 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
95 #define bzero(B,N) memset(B,0x00,n)
110 #include "miscutil.h"
112 #include "jbsockets.h"
117 #include "urlmatch.h"
119 const char jcc_h_rcs[] = JCC_H_VERSION;
120 const char project_h_rcs[] = PROJECT_H_VERSION;
123 struct client_states clients[1];
124 struct file_list files[1];
126 #ifdef FEATURE_STATISTICS
127 int urls_read = 0; /* total nr of urls read inc rejected */
128 int urls_rejected = 0; /* total nr of urls rejected */
129 #endif /* def FEATURE_STATISTICS */
131 #ifdef FEATURE_GRACEFUL_TERMINATION
135 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
136 static void sig_handler(int the_signal);
138 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
139 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
140 static jb_err get_server_headers(struct client_state *csp);
141 static const char *crunch_reason(const struct http_response *rsp);
142 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
143 static char *get_request_line(struct client_state *csp);
144 static jb_err receive_client_request(struct client_state *csp);
145 static jb_err parse_client_request(struct client_state *csp);
146 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
147 static jb_err change_request_destination(struct client_state *csp);
148 static void chat(struct client_state *csp);
149 static void serve(struct client_state *csp);
150 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
151 static void usage(const char *myname);
153 static void initialize_mutexes(void);
154 static jb_socket bind_port_helper(const char *haddr, int hport);
155 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
156 static void close_ports_helper(jb_socket sockets[]);
157 static void listen_loop(void);
160 void serve(struct client_state *csp);
161 #else /* ifndef AMIGA */
162 static void serve(struct client_state *csp);
163 #endif /* def AMIGA */
166 static int32 server_thread(void *data);
167 #endif /* def __BEOS__ */
170 #define sleep(N) Sleep(((N) * 1000))
174 #define sleep(N) DosSleep(((N) * 100))
177 #ifdef MUTEX_LOCKS_AVAILABLE
179 * XXX: Does the locking stuff really belong in this file?
181 privoxy_mutex_t log_mutex;
182 privoxy_mutex_t log_init_mutex;
183 privoxy_mutex_t connection_reuse_mutex;
185 #ifdef FEATURE_EXTERNAL_FILTERS
186 privoxy_mutex_t external_filter_mutex;
189 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
190 privoxy_mutex_t resolver_mutex;
191 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
193 #ifndef HAVE_GMTIME_R
194 privoxy_mutex_t gmtime_mutex;
195 #endif /* ndef HAVE_GMTIME_R */
197 #ifndef HAVE_LOCALTIME_R
198 privoxy_mutex_t localtime_mutex;
199 #endif /* ndef HAVE_GMTIME_R */
202 privoxy_mutex_t rand_mutex;
203 #endif /* ndef HAVE_RANDOM */
205 #endif /* def MUTEX_LOCKS_AVAILABLE */
208 const char *basedir = NULL;
209 const char *pidfile = NULL;
210 static int received_hup_signal = 0;
211 #endif /* defined unix */
213 /* HTTP snipplets. */
214 static const char CSUCCEED[] =
215 "HTTP/1.1 200 Connection established\r\n"
216 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
218 static const char CHEADER[] =
219 "HTTP/1.1 400 Invalid header received from client\r\n"
220 "Proxy-Agent: Privoxy " VERSION "\r\n"
221 "Content-Type: text/plain\r\n"
222 "Connection: close\r\n\r\n"
223 "Invalid header received from client.\r\n";
225 static const char FTP_RESPONSE[] =
226 "HTTP/1.1 400 Invalid request received from client\r\n"
227 "Content-Type: text/plain\r\n"
228 "Connection: close\r\n\r\n"
229 "Invalid request. Privoxy doesn't support FTP.\r\n";
231 static const char GOPHER_RESPONSE[] =
232 "HTTP/1.1 400 Invalid request received from client\r\n"
233 "Content-Type: text/plain\r\n"
234 "Connection: close\r\n\r\n"
235 "Invalid request. Privoxy doesn't support gopher.\r\n";
237 /* XXX: should be a template */
238 static const char MISSING_DESTINATION_RESPONSE[] =
239 "HTTP/1.1 400 Bad request received from client\r\n"
240 "Proxy-Agent: Privoxy " VERSION "\r\n"
241 "Content-Type: text/plain\r\n"
242 "Connection: close\r\n\r\n"
243 "Bad request. Privoxy was unable to extract the destination.\r\n";
245 /* XXX: should be a template */
246 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
247 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
248 "Proxy-Agent: Privoxy " VERSION "\r\n"
249 "Content-Type: text/plain\r\n"
250 "Connection: close\r\n\r\n"
251 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
253 /* XXX: should be a template */
254 static const char MESSED_UP_REQUEST_RESPONSE[] =
255 "HTTP/1.1 400 Malformed request after rewriting\r\n"
256 "Proxy-Agent: Privoxy " VERSION "\r\n"
257 "Content-Type: text/plain\r\n"
258 "Connection: close\r\n\r\n"
259 "Bad request. Messed up with header filters.\r\n";
261 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
262 "HTTP/1.1 503 Too many open connections\r\n"
263 "Proxy-Agent: Privoxy " VERSION "\r\n"
264 "Content-Type: text/plain\r\n"
265 "Connection: close\r\n\r\n"
266 "Maximum number of open connections reached.\r\n";
268 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
269 "HTTP/1.1 504 Connection timeout\r\n"
270 "Proxy-Agent: Privoxy " VERSION "\r\n"
271 "Content-Type: text/plain\r\n"
272 "Connection: close\r\n\r\n"
273 "The connection timed out because the client request didn't arrive in time.\r\n";
275 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
276 "HTTP/1.1 400 Failed reading client body\r\n"
277 "Proxy-Agent: Privoxy " VERSION "\r\n"
278 "Content-Type: text/plain\r\n"
279 "Connection: close\r\n\r\n"
280 "Failed parsing or buffering the chunk-encoded client body.\r\n";
282 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
283 "HTTP/1.1 417 Expecting too much\r\n"
284 "Proxy-Agent: Privoxy " VERSION "\r\n"
285 "Content-Type: text/plain\r\n"
286 "Connection: close\r\n\r\n"
287 "Privoxy detected an unsupported Expect header value.\r\n";
289 /* A function to crunch a response */
290 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
292 /* Crunch function flags */
293 #define CF_NO_FLAGS 0
294 /* Cruncher applies to forced requests as well */
295 #define CF_IGNORE_FORCE 1
296 /* Crunched requests are counted for the block statistics */
297 #define CF_COUNT_AS_REJECT 2
299 /* A crunch function and its flags */
302 const crunch_func_ptr cruncher;
306 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
308 /* Complete list of cruncher functions */
309 static const struct cruncher crunchers_all[] = {
310 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
311 { block_url, CF_COUNT_AS_REJECT },
313 { trust_url, CF_COUNT_AS_REJECT },
314 #endif /* def FEATURE_TRUST */
315 { redirect_url, CF_NO_FLAGS },
316 { dispatch_cgi, CF_IGNORE_FORCE},
320 /* Light version, used after tags are applied */
321 static const struct cruncher crunchers_light[] = {
322 { block_url, CF_COUNT_AS_REJECT },
323 { redirect_url, CF_NO_FLAGS },
329 * XXX: Don't we really mean
335 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
336 /*********************************************************************
338 * Function : sig_handler
340 * Description : Signal handler for different signals.
341 * Exit gracefully on TERM and INT
342 * or set a flag that will cause the errlog
343 * to be reopened by the main thread on HUP.
346 * 1 : the_signal = the signal cause this function to call
350 *********************************************************************/
351 static void sig_handler(int the_signal)
357 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
369 received_hup_signal = 1;
375 * We shouldn't be here, unless we catch signals
376 * in main() that we can't handle here!
378 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
386 /*********************************************************************
388 * Function : client_protocol_is_unsupported
390 * Description : Checks if the client used a known unsupported
391 * protocol and deals with it by sending an error
395 * 1 : csp = Current client state (buffers, headers, etc...)
396 * 2 : req = the first request line send by the client
398 * Returns : TRUE if an error response has been generated, or
399 * FALSE if the request doesn't look invalid.
401 *********************************************************************/
402 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
405 * If it's a FTP or gopher request, we don't support it.
407 * These checks are better than nothing, but they might
408 * not work in all configurations and some clients might
409 * have problems digesting the answer.
411 * They should, however, never cause more problems than
412 * Privoxy's old behaviour (returning the misleading HTML
415 * "Could not resolve http://(ftp|gopher)://example.org").
417 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
419 const char *response = NULL;
420 const char *protocol = NULL;
422 if (!strncmpic(req, "GET ftp://", 10))
424 response = FTP_RESPONSE;
429 response = GOPHER_RESPONSE;
432 log_error(LOG_LEVEL_ERROR,
433 "%s tried to use Privoxy as %s proxy: %s",
434 csp->ip_addr_str, protocol, req);
435 log_error(LOG_LEVEL_CLF,
436 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
438 write_socket(csp->cfd, response, strlen(response));
447 /*********************************************************************
449 * Function : client_has_unsupported_expectations
451 * Description : Checks if the client used an unsupported expectation
452 * in which case an error message is delivered.
455 * 1 : csp = Current client state (buffers, headers, etc...)
457 * Returns : TRUE if an error response has been generated, or
458 * FALSE if the request doesn't look invalid.
460 *********************************************************************/
461 static int client_has_unsupported_expectations(const struct client_state *csp)
463 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
465 log_error(LOG_LEVEL_ERROR,
466 "Rejecting request from client %s with unsupported Expect header value",
468 log_error(LOG_LEVEL_CLF,
469 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
470 write_socket(csp->cfd, UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
471 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE));
481 /*********************************************************************
483 * Function : get_request_destination_elsewhere
485 * Description : If the client's request was redirected into
486 * Privoxy without the client's knowledge,
487 * the request line lacks the destination host.
489 * This function tries to get it elsewhere,
490 * provided accept-intercepted-requests is enabled.
492 * "Elsewhere" currently only means "Host: header",
493 * but in the future we may ask the redirecting
494 * packet filter to look the destination up.
496 * If the destination stays unknown, an error
497 * response is send to the client and headers
498 * are freed so that chat() can return directly.
501 * 1 : csp = Current client state (buffers, headers, etc...)
502 * 2 : headers = a header list
504 * Returns : JB_ERR_OK if the destination is now known, or
505 * JB_ERR_PARSE if it isn't.
507 *********************************************************************/
508 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
512 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
514 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
515 " Privoxy isn't configured to accept intercepted requests.",
516 csp->ip_addr_str, csp->http->cmd);
517 /* XXX: Use correct size */
518 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
519 csp->ip_addr_str, csp->http->cmd);
521 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
522 destroy_list(headers);
526 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
528 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
529 /* Split the domain we just got for pattern matching */
530 init_domain_components(csp->http);
537 /* We can't work without destination. Go spread the news.*/
539 req = list_to_text(headers);
541 /* XXX: Use correct size */
542 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
543 csp->ip_addr_str, csp->http->cmd);
544 log_error(LOG_LEVEL_ERROR,
545 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
546 csp->ip_addr_str, csp->http->cmd, req);
549 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
550 destroy_list(headers);
555 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
556 * to get the destination IP address, use it as host directly
557 * or do a reverse DNS lookup first.
562 /*********************************************************************
564 * Function : get_server_headers
566 * Description : Parses server headers in iob and fills them
567 * into csp->headers so that they can later be
571 * 1 : csp = Current client state (buffers, headers, etc...)
573 * Returns : JB_ERR_OK if everything went fine, or
574 * JB_ERR_PARSE if the headers were incomplete.
576 *********************************************************************/
577 static jb_err get_server_headers(struct client_state *csp)
579 int continue_hack_in_da_house = 0;
582 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
587 * continue hack in da house. Ignore the ending of
588 * this head and continue enlisting header lines.
589 * The reason is described below.
591 enlist(csp->headers, "");
592 continue_hack_in_da_house = 0;
595 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
598 * It's a bodyless continue response, don't
599 * stop header parsing after reaching its end.
601 * As a result Privoxy will concatenate the
602 * next response's head and parse and deliver
603 * the headers as if they belonged to one request.
605 * The client will separate them because of the
606 * empty line between them.
608 * XXX: What we're doing here is clearly against
609 * the intended purpose of the continue header,
610 * and under some conditions (HTTP/1.0 client request)
611 * it's a standard violation.
613 * Anyway, "sort of against the spec" is preferable
614 * to "always getting confused by Continue responses"
615 * (Privoxy's behaviour before this hack was added)
617 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
618 continue_hack_in_da_house = 1;
620 else if (*header == '\0')
623 * If the header is empty, but the Continue hack
624 * isn't active, we can assume that we reached the
625 * end of the buffer before we hit the end of the
628 * Inform the caller an let it decide how to handle it.
633 if (JB_ERR_MEMORY == enlist(csp->headers, header))
636 * XXX: Should we quit the request and return a
637 * out of memory error page instead?
639 log_error(LOG_LEVEL_ERROR,
640 "Out of memory while enlisting server headers. %s lost.",
650 /*********************************************************************
652 * Function : crunch_reason
654 * Description : Translates the crunch reason code into a string.
657 * 1 : rsp = a http_response
659 * Returns : A string with the crunch reason or an error description.
661 *********************************************************************/
662 static const char *crunch_reason(const struct http_response *rsp)
664 char * reason = NULL;
669 return "Internal error while searching for crunch reason";
672 switch (rsp->crunch_reason)
675 reason = "Unsupported HTTP feature";
681 reason = "Untrusted";
684 reason = "Redirected";
690 reason = "DNS failure";
692 case FORWARDING_FAILED:
693 reason = "Forwarding failed";
696 reason = "Connection failure";
699 reason = "Out of memory (may mask other reasons)";
701 case CONNECTION_TIMEOUT:
702 reason = "Connection timeout";
705 reason = "No server data received";
708 reason = "No reason recorded";
716 /*********************************************************************
718 * Function : log_applied_actions
720 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
724 * 1 : actions = Current action spec to log
728 *********************************************************************/
729 static void log_applied_actions(const struct current_action_spec *actions)
732 * The conversion to text requires lots of memory allocations so
733 * we only do the conversion if the user is actually interested.
735 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
737 char *actions_as_text = actions_to_line_of_text(actions);
738 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
739 freez(actions_as_text);
744 /*********************************************************************
746 * Function : send_crunch_response
748 * Description : Delivers already prepared response for
749 * intercepted requests, logs the interception
750 * and frees the response.
753 * 1 : csp = Current client state (buffers, headers, etc...)
754 * 1 : rsp = Fully prepared response. Will be freed on exit.
758 *********************************************************************/
759 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
761 const struct http_request *http = csp->http;
765 assert(rsp->head != NULL);
769 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
773 * Extract the status code from the actual head
774 * that will be send to the client. It is the only
775 * way to get it right for all requests, including
776 * the fixed ones for out-of-memory problems.
778 * A head starts like this: 'HTTP/1.1 200...'
782 status_code[0] = rsp->head[9];
783 status_code[1] = rsp->head[10];
784 status_code[2] = rsp->head[11];
785 status_code[3] = '\0';
787 /* Log that the request was crunched and why. */
788 log_applied_actions(csp->action);
789 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
790 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
791 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
793 /* Write the answer to the client */
794 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
795 || write_socket(csp->cfd, rsp->body, rsp->content_length))
797 /* There is nothing we can do about it. */
798 log_error(LOG_LEVEL_ERROR,
799 "Couldn't deliver the error message through client socket %d: %E",
803 /* Clean up and return */
804 if (cgi_error_memory() != rsp)
806 free_http_response(rsp);
812 /*********************************************************************
814 * Function : crunch_response_triggered
816 * Description : Checks if the request has to be crunched,
817 * and delivers the crunch response if necessary.
820 * 1 : csp = Current client state (buffers, headers, etc...)
821 * 2 : crunchers = list of cruncher functions to run
823 * Returns : TRUE if the request was answered with a crunch response
826 *********************************************************************/
827 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
829 struct http_response *rsp = NULL;
830 const struct cruncher *c;
833 * If CGI request crunching is disabled,
834 * check the CGI dispatcher out of order to
835 * prevent unintentional blocks or redirects.
837 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
838 && (NULL != (rsp = dispatch_cgi(csp))))
840 /* Deliver, log and free the interception response. */
841 send_crunch_response(csp, rsp);
842 csp->flags |= CSP_FLAG_CRUNCHED;
846 for (c = crunchers; c->cruncher != NULL; c++)
849 * Check the cruncher if either Privoxy is toggled
850 * on and the request isn't forced, or if the cruncher
851 * applies to forced requests as well.
853 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
854 !(csp->flags & CSP_FLAG_FORCED)) ||
855 (c->flags & CF_IGNORE_FORCE))
857 rsp = c->cruncher(csp);
860 /* Deliver, log and free the interception response. */
861 send_crunch_response(csp, rsp);
862 csp->flags |= CSP_FLAG_CRUNCHED;
863 #ifdef FEATURE_STATISTICS
864 if (c->flags & CF_COUNT_AS_REJECT)
866 csp->flags |= CSP_FLAG_REJECTED;
868 #endif /* def FEATURE_STATISTICS */
879 /*********************************************************************
881 * Function : build_request_line
883 * Description : Builds the HTTP request line.
885 * If a HTTP forwarder is used it expects the whole URL,
886 * web servers only get the path.
889 * 1 : csp = Current client state (buffers, headers, etc...)
890 * 2 : fwd = The forwarding spec used for the request
891 * XXX: Should use http->fwd instead.
892 * 3 : request_line = The old request line which will be replaced.
894 * Returns : Nothing. Terminates in case of memory problems.
896 *********************************************************************/
897 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
899 struct http_request *http = csp->http;
901 assert(http->ssl == 0);
904 * Downgrade http version from 1.1 to 1.0
905 * if +downgrade action applies.
907 if ((csp->action->flags & ACTION_DOWNGRADE)
908 && (!strcmpic(http->ver, "HTTP/1.1")))
911 http->ver = strdup_or_die("HTTP/1.0");
915 * Rebuild the request line.
917 freez(*request_line);
918 *request_line = strdup(http->gpc);
919 string_append(request_line, " ");
921 if (fwd->forward_host)
923 string_append(request_line, http->url);
927 string_append(request_line, http->path);
929 string_append(request_line, " ");
930 string_append(request_line, http->ver);
932 if (*request_line == NULL)
934 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
936 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
940 /*********************************************************************
942 * Function : change_request_destination
944 * Description : Parse a (rewritten) request line and regenerate
945 * the http request data.
948 * 1 : csp = Current client state (buffers, headers, etc...)
950 * Returns : Forwards the parse_http_request() return code.
951 * Terminates in case of memory problems.
953 *********************************************************************/
954 static jb_err change_request_destination(struct client_state *csp)
956 struct http_request *http = csp->http;
959 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
960 csp->headers->first->str);
961 free_http_request(http);
962 err = parse_http_request(csp->headers->first->str, http);
963 if (JB_ERR_OK != err)
965 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
966 jb_err_to_string(err));
973 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
974 /*********************************************************************
976 * Function : server_response_is_complete
978 * Description : Determines whether we should stop reading
979 * from the server socket.
982 * 1 : csp = Current client state (buffers, headers, etc...)
983 * 2 : content_length = Length of content received so far.
985 * Returns : TRUE if the response is complete,
988 *********************************************************************/
989 static int server_response_is_complete(struct client_state *csp,
990 unsigned long long content_length)
992 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
994 if (!strcmpic(csp->http->gpc, "HEAD"))
997 * "HEAD" implies no body, we are thus expecting
998 * no content. XXX: incomplete "list" of methods?
1000 csp->expected_content_length = 0;
1001 content_length_known = TRUE;
1002 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1005 if (csp->http->status == 204 || csp->http->status == 304)
1008 * Expect no body. XXX: incomplete "list" of status codes?
1010 csp->expected_content_length = 0;
1011 content_length_known = TRUE;
1012 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1015 return (content_length_known && ((0 == csp->expected_content_length)
1016 || (csp->expected_content_length <= content_length)));
1020 #ifdef FEATURE_CONNECTION_SHARING
1021 /*********************************************************************
1023 * Function : wait_for_alive_connections
1025 * Description : Waits for alive connections to timeout.
1031 *********************************************************************/
1032 static void wait_for_alive_connections(void)
1034 int connections_alive = close_unusable_connections();
1036 while (0 < connections_alive)
1038 log_error(LOG_LEVEL_CONNECT,
1039 "Waiting for %d connections to timeout.",
1042 connections_alive = close_unusable_connections();
1045 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1048 #endif /* def FEATURE_CONNECTION_SHARING */
1051 /*********************************************************************
1053 * Function : save_connection_destination
1055 * Description : Remembers a connection for reuse later on.
1058 * 1 : sfd = Open socket to remember.
1059 * 2 : http = The destination for the connection.
1060 * 3 : fwd = The forwarder settings used.
1061 * 3 : server_connection = storage.
1065 *********************************************************************/
1066 void save_connection_destination(jb_socket sfd,
1067 const struct http_request *http,
1068 const struct forward_spec *fwd,
1069 struct reusable_connection *server_connection)
1071 assert(sfd != JB_INVALID_SOCKET);
1072 assert(NULL != http->host);
1074 server_connection->sfd = sfd;
1075 server_connection->host = strdup_or_die(http->host);
1076 server_connection->port = http->port;
1078 assert(NULL != fwd);
1079 assert(server_connection->gateway_host == NULL);
1080 assert(server_connection->gateway_port == 0);
1081 assert(server_connection->forwarder_type == 0);
1082 assert(server_connection->forward_host == NULL);
1083 assert(server_connection->forward_port == 0);
1085 server_connection->forwarder_type = fwd->type;
1086 if (NULL != fwd->gateway_host)
1088 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1092 server_connection->gateway_host = NULL;
1094 server_connection->gateway_port = fwd->gateway_port;
1096 if (NULL != fwd->forward_host)
1098 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1102 server_connection->forward_host = NULL;
1104 server_connection->forward_port = fwd->forward_port;
1108 /*********************************************************************
1110 * Function : verify_request_length
1112 * Description : Checks if we already got the whole client requests
1113 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1116 * Data that doesn't belong to the current request is
1117 * either thrown away to let the client retry on a clean
1118 * socket, or stashed to be dealt with after the current
1119 * request is served.
1122 * 1 : csp = Current client state (buffers, headers, etc...)
1126 *********************************************************************/
1127 static void verify_request_length(struct client_state *csp)
1129 unsigned long long buffered_request_bytes =
1130 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1132 if ((csp->expected_client_content_length != 0)
1133 && (buffered_request_bytes != 0))
1135 if (csp->expected_client_content_length >= buffered_request_bytes)
1137 csp->expected_client_content_length -= buffered_request_bytes;
1138 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1139 "to account for the %llu ones we already got.",
1140 csp->expected_client_content_length, buffered_request_bytes);
1144 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1145 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1146 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1147 "Marking the server socket tainted after throwing %llu bytes away.",
1148 buffered_request_bytes - csp->expected_client_content_length);
1149 csp->expected_client_content_length = 0;
1150 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1153 if (csp->expected_client_content_length == 0)
1155 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1159 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1160 && ((csp->client_iob->cur < csp->client_iob->eod)
1161 || (csp->expected_client_content_length != 0)))
1163 if (strcmpic(csp->http->gpc, "GET")
1164 && strcmpic(csp->http->gpc, "HEAD")
1165 && strcmpic(csp->http->gpc, "TRACE")
1166 && strcmpic(csp->http->gpc, "OPTIONS")
1167 && strcmpic(csp->http->gpc, "DELETE"))
1169 /* XXX: this is an incomplete hack */
1170 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1171 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1175 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1177 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1179 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1180 log_error(LOG_LEVEL_CONNECT,
1181 "Possible pipeline attempt detected. The connection will not "
1182 "be kept alive and we will only serve the first request.");
1183 /* Nuke the pipelined requests from orbit, just to be sure. */
1184 clear_iob(csp->client_iob);
1189 * Keep the pipelined data around for now, we'll deal with
1190 * it once we're done serving the current request.
1192 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1193 assert(csp->client_iob->eod >= csp->client_iob->cur);
1194 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1195 "%d bytes of pipelined data received.",
1196 (int)(csp->client_iob->eod - csp->client_iob->cur));
1202 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1203 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1206 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1209 /*********************************************************************
1211 * Function : mark_server_socket_tainted
1213 * Description : Makes sure we don't reuse a server socket
1214 * (if we didn't read everything the server sent
1215 * us reusing the socket would lead to garbage).
1218 * 1 : csp = Current client state (buffers, headers, etc...)
1222 *********************************************************************/
1223 static void mark_server_socket_tainted(struct client_state *csp)
1226 * For consistency we always mark the server socket
1227 * tainted, however, to reduce the log noise we only
1228 * emit a log message if the server socket could have
1229 * actually been reused.
1231 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1232 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1234 log_error(LOG_LEVEL_CONNECT,
1235 "Marking the server socket %d tainted.",
1236 csp->server_connection.sfd);
1238 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1241 /*********************************************************************
1243 * Function : get_request_line
1245 * Description : Read the client request line.
1248 * 1 : csp = Current client state (buffers, headers, etc...)
1250 * Returns : Pointer to request line or NULL in case of errors.
1252 *********************************************************************/
1253 static char *get_request_line(struct client_state *csp)
1255 char buf[BUFFER_SIZE];
1256 char *request_line = NULL;
1259 memset(buf, 0, sizeof(buf));
1261 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1264 * If there are multiple pipelined requests waiting,
1265 * the flag will be set again once the next request
1268 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1270 request_line = get_header(csp->client_iob);
1271 if ((NULL != request_line) && ('\0' != *request_line))
1273 return request_line;
1277 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1278 "received yet. Continuing reading from %d.", csp->cfd);
1284 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1286 if (socket_is_still_alive(csp->cfd))
1288 log_error(LOG_LEVEL_CONNECT,
1289 "No request line on socket %d received in time. Timeout: %d.",
1290 csp->cfd, csp->config->socket_timeout);
1291 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1292 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1296 log_error(LOG_LEVEL_CONNECT,
1297 "The client side of the connection on socket %d got "
1298 "closed without sending a complete request line.", csp->cfd);
1303 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1305 if (len <= 0) return NULL;
1308 * If there is no memory left for buffering the
1309 * request, there is nothing we can do but hang up
1311 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1316 request_line = get_header(csp->client_iob);
1318 } while ((NULL != request_line) && ('\0' == *request_line));
1320 return request_line;
1326 CHUNK_STATUS_MISSING_DATA,
1327 CHUNK_STATUS_BODY_COMPLETE,
1328 CHUNK_STATUS_PARSE_ERROR
1332 /*********************************************************************
1334 * Function : chunked_body_is_complete
1336 * Description : Figures out whether or not a chunked body is complete.
1338 * Currently it always starts at the beginning of the
1339 * buffer which is somewhat wasteful and prevents Privoxy
1340 * from starting to forward the correctly parsed chunks
1341 * as soon as theoretically possible.
1343 * Should be modified to work with a common buffer,
1344 * and allow the caller to skip already parsed chunks.
1346 * This would allow the function to be used for unbuffered
1347 * response bodies as well.
1350 * 1 : iob = Buffer with the body to check.
1351 * 2 : length = Length of complete body
1353 * Returns : Enum with the result of the check.
1355 *********************************************************************/
1356 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1358 unsigned int chunksize;
1364 * We need at least a single digit, followed by "\r\n",
1365 * followed by an unknown amount of data, followed by "\r\n".
1367 if (p + 5 > iob->eod)
1369 return CHUNK_STATUS_MISSING_DATA;
1371 if (sscanf(p, "%x", &chunksize) != 1)
1373 return CHUNK_STATUS_PARSE_ERROR;
1377 * We want at least a single digit, followed by "\r\n",
1378 * followed by the specified amount of data, followed by "\r\n".
1380 if (p + chunksize + 5 > iob->eod)
1382 return CHUNK_STATUS_MISSING_DATA;
1385 /* Skip chunk-size. */
1386 p = strstr(p, "\r\n");
1389 return CHUNK_STATUS_PARSE_ERROR;
1391 /* Move beyond the chunkdata. */
1394 /* There should be another "\r\n" to skip */
1395 if (memcmp(p, "\r\n", 2))
1397 return CHUNK_STATUS_PARSE_ERROR;
1400 } while (chunksize > 0U);
1402 *length = (size_t)(p - iob->cur);
1403 assert(*length <= (size_t)(iob->eod - iob->cur));
1404 assert(p <= iob->eod);
1406 return CHUNK_STATUS_BODY_COMPLETE;
1411 /*********************************************************************
1413 * Function : receive_chunked_client_request_body
1415 * Description : Read the chunk-encoded client request body.
1416 * Failures are dealt with.
1419 * 1 : csp = Current client state (buffers, headers, etc...)
1421 * Returns : JB_ERR_OK or JB_ERR_PARSE
1423 *********************************************************************/
1424 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1427 enum chunk_status status;
1429 while (CHUNK_STATUS_MISSING_DATA ==
1430 (status = chunked_body_is_complete(csp->client_iob,&body_length)))
1432 char buf[BUFFER_SIZE];
1435 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1437 log_error(LOG_LEVEL_ERROR,
1438 "Timeout while waiting for the client body.");
1441 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1444 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1447 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1452 if (status != CHUNK_STATUS_BODY_COMPLETE)
1454 write_socket(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1455 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE));
1456 log_error(LOG_LEVEL_CLF,
1457 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1458 return JB_ERR_PARSE;
1460 log_error(LOG_LEVEL_CONNECT,
1461 "Chunked client body completely read. Length: %d", body_length);
1462 csp->expected_client_content_length = body_length;
1468 /*********************************************************************
1470 * Function : receive_client_request
1472 * Description : Read the client's request (more precisely the
1473 * client headers) and answer it if necessary.
1476 * 1 : csp = Current client state (buffers, headers, etc...)
1478 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1480 *********************************************************************/
1481 static jb_err receive_client_request(struct client_state *csp)
1483 char buf[BUFFER_SIZE];
1486 struct http_request *http;
1490 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1491 struct list header_list;
1492 struct list *headers = &header_list;
1494 /* We don't care if the arriving data is a valid HTTP request or not. */
1495 csp->requests_received_total++;
1499 memset(buf, 0, sizeof(buf));
1501 req = get_request_line(csp);
1504 mark_server_socket_tainted(csp);
1505 return JB_ERR_PARSE;
1507 assert(*req != '\0');
1509 if (client_protocol_is_unsupported(csp, req))
1511 return JB_ERR_PARSE;
1514 #ifdef FEATURE_FORCE_LOAD
1516 * If this request contains the FORCE_PREFIX and blocks
1517 * aren't enforced, get rid of it and set the force flag.
1519 if (strstr(req, FORCE_PREFIX))
1521 if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1523 log_error(LOG_LEVEL_FORCE,
1524 "Ignored force prefix in request: \"%s\".", req);
1528 strclean(req, FORCE_PREFIX);
1529 log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1530 csp->flags |= CSP_FLAG_FORCED;
1533 #endif /* def FEATURE_FORCE_LOAD */
1535 err = parse_http_request(req, http);
1537 if (JB_ERR_OK != err)
1539 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1540 /* XXX: Use correct size */
1541 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1542 log_error(LOG_LEVEL_ERROR,
1543 "Couldn't parse request line received from %s: %s",
1544 csp->ip_addr_str, jb_err_to_string(err));
1546 free_http_request(http);
1547 return JB_ERR_PARSE;
1550 /* grab the rest of the client's headers */
1554 p = get_header(csp->client_iob);
1558 /* There are no additional headers to read. */
1565 * We didn't receive a complete header
1566 * line yet, get the rest of it.
1568 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1570 log_error(LOG_LEVEL_ERROR,
1571 "Stopped grabbing the client headers.");
1572 destroy_list(headers);
1573 return JB_ERR_PARSE;
1576 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1579 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1580 destroy_list(headers);
1581 return JB_ERR_PARSE;
1584 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1587 * If there is no memory left for buffering the
1588 * request, there is nothing we can do but hang up
1590 destroy_list(headers);
1591 return JB_ERR_MEMORY;
1596 if (!strncmpic(p, "Transfer-Encoding:", 18))
1599 * XXX: should be called through sed()
1600 * but currently can't.
1602 client_transfer_encoding(csp, &p);
1605 * We were able to read a complete
1606 * header and can finally enlist it.
1613 if (http->host == NULL)
1616 * If we still don't know the request destination,
1617 * the request is invalid or the client uses
1618 * Privoxy without its knowledge.
1620 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1623 * Our attempts to get the request destination
1624 * elsewhere failed or Privoxy is configured
1625 * to only accept proxy requests.
1627 * An error response has already been send
1628 * and we're done here.
1630 return JB_ERR_PARSE;
1635 * Determine the actions for this URL
1637 #ifdef FEATURE_TOGGLE
1638 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1640 /* Most compatible set of actions (i.e. none) */
1641 init_current_action(csp->action);
1644 #endif /* ndef FEATURE_TOGGLE */
1646 get_url_actions(csp, http);
1649 enlist(csp->headers, http->cmd);
1651 /* Append the previously read headers */
1652 err = list_append_list_unique(csp->headers, headers);
1653 destroy_list(headers);
1660 /*********************************************************************
1662 * Function : parse_client_request
1664 * Description : Parses the client's request and decides what to do
1667 * Note that since we're not using select() we could get
1668 * blocked here if a client connected, then didn't say
1672 * 1 : csp = Current client state (buffers, headers, etc...)
1674 * Returns : JB_ERR_OK or JB_ERR_PARSE
1676 *********************************************************************/
1677 static jb_err parse_client_request(struct client_state *csp)
1679 struct http_request *http = csp->http;
1682 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1683 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1684 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1685 && (csp->http->ssl == 0))
1687 /* Assume persistence until further notice */
1688 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1691 if (csp->http->ssl == 0)
1694 * This whole block belongs to chat() but currently
1695 * has to be executed before sed().
1697 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1699 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1701 return JB_ERR_PARSE;
1706 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1708 verify_request_length(csp);
1710 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1712 err = sed(csp, FILTER_CLIENT_HEADERS);
1713 if (JB_ERR_OK != err)
1715 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1717 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1718 csp->ip_addr_str, csp->http->cmd);
1719 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1720 return JB_ERR_PARSE;
1722 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1724 /* Check request line for rewrites. */
1725 if ((NULL == csp->headers->first->str)
1726 || (strcmp(http->cmd, csp->headers->first->str) &&
1727 (JB_ERR_OK != change_request_destination(csp))))
1730 * A header filter broke the request line - bail out.
1732 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1733 /* XXX: Use correct size */
1734 log_error(LOG_LEVEL_CLF,
1735 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1736 log_error(LOG_LEVEL_ERROR,
1737 "Invalid request line after applying header filters.");
1738 free_http_request(http);
1740 return JB_ERR_PARSE;
1743 if (client_has_unsupported_expectations(csp))
1745 return JB_ERR_PARSE;
1753 /*********************************************************************
1757 * Description : Once a connection from the client has been accepted,
1758 * this function is called (via serve()) to handle the
1759 * main business of the communication. This function
1760 * returns after dealing with a single request. It can
1761 * be called multiple times with the same client socket
1762 * if the client is keeping the connection alive.
1764 * The decision whether or not a client connection will
1765 * be kept alive is up to the caller which also must
1766 * close the client socket when done.
1768 * FIXME: chat is nearly thousand lines long.
1772 * 1 : csp = Current client state (buffers, headers, etc...)
1774 * Returns : Nothing.
1776 *********************************************************************/
1777 static void chat(struct client_state *csp)
1779 char buf[BUFFER_SIZE];
1786 int ms_iis5_hack = 0;
1787 unsigned long long byte_count = 0;
1788 const struct forward_spec *fwd;
1789 struct http_request *http;
1790 long len = 0; /* for buffer sizes (and negative error codes) */
1791 int buffer_and_filter_content = 0;
1793 /* Skeleton for HTTP response, if we should intercept the request */
1794 struct http_response *rsp;
1795 struct timeval timeout;
1796 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1797 int watch_client_socket;
1800 memset(buf, 0, sizeof(buf));
1804 if (receive_client_request(csp) != JB_ERR_OK)
1808 if (parse_client_request(csp) != JB_ERR_OK)
1813 /* decide how to route the HTTP request */
1814 fwd = forward_url(csp, http);
1817 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1818 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1823 * build the http request to send to the server
1824 * we have to do one of the following:
1826 * create = use the original HTTP request to create a new
1827 * HTTP request that has either the path component
1828 * without the http://domainspec (w/path) or the
1829 * full orininal URL (w/url)
1830 * Note that the path and/or the HTTP version may
1831 * have been altered by now.
1833 * connect = Open a socket to the host:port of the server
1834 * and short-circuit server and client socket.
1836 * pass = Pass the request unchanged if forwarding a CONNECT
1837 * request to a parent proxy. Note that we'll be sending
1838 * the CFAIL message ourselves if connecting to the parent
1839 * fails, but we won't send a CSUCCEED message if it works,
1840 * since that would result in a double message (ours and the
1841 * parent's). After sending the request to the parent, we simply
1844 * here's the matrix:
1847 * +--------+--------+
1849 * 0 | create | connect|
1851 * Forwarding +--------+--------+
1853 * 1 | create | pass |
1855 * +--------+--------+
1859 if (http->ssl && connect_port_is_forbidden(csp))
1861 const char *acceptable_connect_ports =
1862 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1863 assert(NULL != acceptable_connect_ports);
1864 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1865 "limit-connect{%s} doesn't allow CONNECT requests to %s",
1866 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
1867 csp->action->flags |= ACTION_BLOCK;
1873 freez(csp->headers->first->str);
1874 build_request_line(csp, fwd, &csp->headers->first->str);
1878 * We have a request. Check if one of the crunchers wants it.
1880 if (crunch_response_triggered(csp, crunchers_all))
1883 * Yes. The client got the crunch response and we're done here.
1888 log_applied_actions(csp->action);
1889 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1891 if (fwd->forward_host)
1893 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1894 fwd->forward_host, fwd->forward_port, http->hostport);
1898 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1901 /* here we connect to the server, gateway, or the forwarder */
1903 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1904 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
1905 && socket_is_still_alive(csp->server_connection.sfd)
1906 && connection_destination_matches(&csp->server_connection, http, fwd))
1908 log_error(LOG_LEVEL_CONNECT,
1909 "Reusing server socket %d connected to %s. Total requests: %u.",
1910 csp->server_connection.sfd, csp->server_connection.host,
1911 csp->server_connection.requests_sent_total);
1915 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
1917 #ifdef FEATURE_CONNECTION_SHARING
1918 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1920 remember_connection(&csp->server_connection);
1923 #endif /* def FEATURE_CONNECTION_SHARING */
1925 log_error(LOG_LEVEL_CONNECT,
1926 "Closing server socket %d connected to %s. Total requests: %u.",
1927 csp->server_connection.sfd, csp->server_connection.host,
1928 csp->server_connection.requests_sent_total);
1929 close_socket(csp->server_connection.sfd);
1931 mark_connection_closed(&csp->server_connection);
1933 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1935 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
1937 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
1939 if (fwd->type != SOCKS_NONE)
1942 rsp = error_response(csp, "forwarding-failed");
1944 else if (errno == EINVAL)
1946 rsp = error_response(csp, "no-such-domain");
1950 rsp = error_response(csp, "connect-failed");
1953 /* Write the answer to the client */
1956 send_crunch_response(csp, rsp);
1960 * Temporary workaround to prevent already-read client
1961 * bodies from being parsed as new requests. For now we
1962 * err on the safe side and throw all the following
1963 * requests under the bus, even if no client body has been
1964 * buffered. A compliant client will repeat the dropped
1965 * requests on an untainted connection.
1967 * The proper fix is to discard the no longer needed
1968 * client body in the buffer (if there is one) and to
1969 * continue parsing the bytes that follow.
1971 drain_and_close_socket(csp->cfd);
1972 csp->cfd = JB_INVALID_SOCKET;
1976 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1977 save_connection_destination(csp->server_connection.sfd,
1978 http, fwd, &csp->server_connection);
1979 csp->server_connection.keep_alive_timeout =
1980 (unsigned)csp->config->keep_alive_timeout;
1982 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1984 csp->server_connection.requests_sent_total++;
1986 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
1988 /* Client headers have been sent optimistically */
1989 assert(csp->headers->last == NULL);
1991 else if (fwd->forward_host || (http->ssl == 0))
1994 hdr = list_to_text(csp->headers);
1997 /* FIXME Should handle error properly */
1998 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2000 list_remove_all(csp->headers);
2003 * Write the client's (modified) header to the server
2004 * (along with anything else that may be in the buffer)
2006 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2011 log_error(LOG_LEVEL_CONNECT,
2012 "Failed sending request headers to: %s: %E", http->hostport);
2014 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2015 && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
2018 log_error(LOG_LEVEL_CONNECT,
2019 "Failed sending request body to: %s: %E", http->hostport);
2024 rsp = error_response(csp, "connect-failed");
2027 send_crunch_response(csp, rsp);
2035 * We're running an SSL tunnel and we're not forwarding,
2036 * so just ditch the client headers, send the "connect succeeded"
2037 * message to the client, flush the rest, and get out of the way.
2039 list_remove_all(csp->headers);
2040 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
2044 clear_iob(csp->client_iob);
2047 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
2049 /* XXX: should the time start earlier for optimistically sent data? */
2050 csp->server_connection.request_sent = time(NULL);
2052 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2053 csp->cfd : csp->server_connection.sfd;
2055 /* pass data between the client and server
2056 * until one or the other shuts down the connection.
2061 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2062 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2069 * FD_ZERO here seems to point to an errant macro which crashes.
2070 * So do this by hand for now...
2072 memset(&rfds,0x00,sizeof(fd_set));
2076 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2077 if (!watch_client_socket)
2079 maxfd = csp->server_connection.sfd;
2082 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2084 FD_SET(csp->cfd, &rfds);
2087 FD_SET(csp->server_connection.sfd, &rfds);
2089 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2090 if ((csp->flags & CSP_FLAG_CHUNKED)
2091 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2092 && ((csp->iob->eod - csp->iob->cur) >= 5)
2093 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2096 * XXX: This check should be obsolete now,
2097 * but let's wait a while to be sure.
2099 log_error(LOG_LEVEL_CONNECT,
2100 "Looks like we got the last chunk together with "
2101 "the server headers but didn't detect it earlier. "
2102 "We better stop reading.");
2103 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2104 csp->expected_content_length = byte_count;
2105 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2107 if (server_body && server_response_is_complete(csp, byte_count))
2109 if (csp->expected_content_length == byte_count)
2111 log_error(LOG_LEVEL_CONNECT,
2112 "Done reading from server. Content length: %llu as expected. "
2113 "Bytes most recently read: %d.",
2118 log_error(LOG_LEVEL_CONNECT,
2119 "Done reading from server. Expected content length: %llu. "
2120 "Actual content length: %llu. Bytes most recently read: %d.",
2121 csp->expected_content_length, byte_count, len);
2125 * XXX: should not jump around,
2126 * chat() is complicated enough already.
2130 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2132 timeout.tv_sec = csp->config->socket_timeout;
2133 timeout.tv_usec = 0;
2134 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2138 log_error(LOG_LEVEL_ERROR,
2139 "Didn't receive data in time: %s", http->url);
2140 if ((byte_count == 0) && (http->ssl == 0))
2142 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2144 mark_server_socket_tainted(csp);
2149 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2150 mark_server_socket_tainted(csp);
2155 * This is the body of the browser's request,
2156 * just read and write it.
2158 * XXX: Make sure the client doesn't use pipelining
2159 * behind Privoxy's back.
2161 if (FD_ISSET(csp->cfd, &rfds))
2163 int max_bytes_to_read = sizeof(buf) - 1;
2165 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2166 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2168 if (data_is_available(csp->cfd, 0))
2171 * If the next request is already waiting, we have
2172 * to stop select()ing the client socket. Otherwise
2173 * we would always return right away and get nothing
2176 watch_client_socket = 0;
2177 log_error(LOG_LEVEL_CONNECT,
2178 "Stopping to watch the client socket %d. "
2179 "There's already another request waiting.",
2184 * If the client socket is set, but there's no data
2185 * available on the socket, the client went fishing
2186 * and continuing talking to the server makes no sense.
2188 log_error(LOG_LEVEL_CONNECT,
2189 "The client closed socket %d while "
2190 "the server socket %d is still open.",
2191 csp->cfd, csp->server_connection.sfd);
2192 mark_server_socket_tainted(csp);
2195 if (csp->expected_client_content_length != 0)
2197 if (csp->expected_client_content_length < (sizeof(buf) - 1))
2199 max_bytes_to_read = (int)csp->expected_client_content_length;
2201 log_error(LOG_LEVEL_CONNECT,
2202 "Waiting for up to %d bytes from the client.",
2205 assert(max_bytes_to_read < sizeof(buf));
2206 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2208 len = read_socket(csp->cfd, buf, max_bytes_to_read);
2212 /* XXX: not sure if this is necessary. */
2213 mark_server_socket_tainted(csp);
2214 break; /* "game over, man" */
2217 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2218 if (csp->expected_client_content_length != 0)
2220 assert(len <= max_bytes_to_read);
2221 csp->expected_client_content_length -= (unsigned)len;
2222 log_error(LOG_LEVEL_CONNECT,
2223 "Expected client content length set to %llu "
2224 "after reading %d bytes.",
2225 csp->expected_client_content_length, len);
2226 if (csp->expected_client_content_length == 0)
2228 log_error(LOG_LEVEL_CONNECT,
2229 "Done reading from the client.");
2230 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2233 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2235 if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
2237 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2238 mark_server_socket_tainted(csp);
2245 * The server wants to talk. It could be the header or the body.
2246 * If `hdr' is null, then it's the header otherwise it's the body.
2247 * FIXME: Does `hdr' really mean `host'? No.
2249 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2251 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2253 * If we are buffering content, we don't want to eat up to
2254 * buffer-limit bytes if the client no longer cares about them.
2255 * If we aren't buffering, however, a dead client socket will be
2256 * noticed pretty much right away anyway, so we can reduce the
2257 * overhead by skipping the check.
2259 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2262 log_error(LOG_LEVEL_CONNECT,
2263 "The server still wants to talk, but the client may already have hung up on us.");
2265 log_error(LOG_LEVEL_CONNECT,
2266 "The server still wants to talk, but the client hung up on us.");
2267 mark_server_socket_tainted(csp);
2269 #endif /* def _WIN32 */
2271 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2273 len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
2277 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2279 if (http->ssl && (fwd->forward_host == NULL))
2282 * Just hang up. We already confirmed the client's CONNECT
2283 * request with status code 200 and unencrypted content is
2284 * no longer welcome.
2286 log_error(LOG_LEVEL_ERROR,
2287 "CONNECT already confirmed. Unable to tell the client about the problem.");
2290 else if (byte_count)
2293 * Just hang up. We already transmitted the original headers
2294 * and parts of the original content and therefore missed the
2295 * chance to send an error message (without risking data corruption).
2297 * XXX: we could retry with a fancy range request here.
2299 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2300 "Unable to tell the client about the problem.");
2301 mark_server_socket_tainted(csp);
2305 * XXX: Consider handling the cases above the same.
2307 mark_server_socket_tainted(csp);
2311 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2312 if (csp->flags & CSP_FLAG_CHUNKED)
2314 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2316 /* XXX: this is a temporary hack */
2317 log_error(LOG_LEVEL_CONNECT,
2318 "Looks like we reached the end of the last chunk. "
2319 "We better stop reading.");
2320 csp->expected_content_length = byte_count + (unsigned long long)len;
2321 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2325 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2328 * Add a trailing zero to let be able to use string operations.
2329 * XXX: do we still need this with filter_popups gone?
2334 * Normally, this would indicate that we've read
2335 * as much as the server has sent us and we can
2336 * close the client connection. However, Microsoft
2337 * in its wisdom has released IIS/5 with a bug that
2338 * prevents it from sending the trailing \r\n in
2339 * a 302 redirect header (and possibly other headers).
2340 * To work around this if we've haven't parsed
2341 * a full header we'll append a trailing \r\n
2342 * and see if this now generates a valid one.
2344 * This hack shouldn't have any impacts. If we've
2345 * already transmitted the header or if this is a
2346 * SSL connection, then we won't bother with this
2347 * hack. So we only work on partially received
2348 * headers. If we append a \r\n and this still
2349 * doesn't generate a valid header, then we won't
2350 * transmit anything to the client.
2355 if (server_body || http->ssl)
2358 * If we have been buffering up the document,
2359 * now is the time to apply content modification
2360 * and send the result to the client.
2362 if (buffer_and_filter_content)
2364 p = execute_content_filters(csp);
2366 * If content filtering fails, use the original
2367 * buffer and length.
2368 * (see p != NULL ? p : csp->iob->cur below)
2372 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2374 #ifdef FEATURE_COMPRESSION
2375 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2376 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2378 char *compressed_content = compress_buffer(p,
2379 (size_t *)&csp->content_length, csp->config->compression_level);
2380 if (compressed_content != NULL)
2383 p = compressed_content;
2384 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2389 if (JB_ERR_OK != update_server_headers(csp))
2391 log_error(LOG_LEVEL_FATAL,
2392 "Failed to update server headers. after filtering.");
2395 hdr = list_to_text(csp->headers);
2398 /* FIXME Should handle error properly */
2399 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2402 if (write_socket(csp->cfd, hdr, strlen(hdr))
2403 || write_socket(csp->cfd,
2404 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2406 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2409 mark_server_socket_tainted(csp);
2417 break; /* "game over, man" */
2421 * This is NOT the body, so
2422 * Let's pretend the server just sent us a blank line.
2424 snprintf(buf, sizeof(buf), "\r\n");
2425 len = (int)strlen(buf);
2428 * Now, let the normal header parsing algorithm below do its
2429 * job. If it fails, we'll exit instead of continuing.
2436 * If this is an SSL connection or we're in the body
2437 * of the server document, just write it to the client,
2438 * unless we need to buffer the body for later content-filtering
2440 if (server_body || http->ssl)
2442 if (buffer_and_filter_content)
2445 * If there is no memory left for buffering the content, or the buffer limit
2446 * has been reached, switch to non-filtering mode, i.e. make & write the
2447 * header, flush the iob and buf, and get out of the way.
2449 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2454 log_error(LOG_LEVEL_INFO,
2455 "Flushing header and buffers. Stepping back from filtering.");
2457 hdr = list_to_text(csp->headers);
2461 * Memory is too tight to even generate the header.
2462 * Send our static "Out-of-memory" page.
2464 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2465 rsp = cgi_error_memory();
2466 send_crunch_response(csp, rsp);
2467 mark_server_socket_tainted(csp);
2470 hdrlen = strlen(hdr);
2472 if (write_socket(csp->cfd, hdr, hdrlen)
2473 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2474 || (write_socket(csp->cfd, buf, (size_t)len)))
2476 log_error(LOG_LEVEL_CONNECT,
2477 "Flush header and buffers to client failed: %E");
2479 mark_server_socket_tainted(csp);
2484 * Reset the byte_count to the amount of bytes
2485 * we just flushed. len will be added a few lines below,
2486 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2488 byte_count = (unsigned long long)flushed;
2490 buffer_and_filter_content = 0;
2496 if (write_socket(csp->cfd, buf, (size_t)len))
2498 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2499 mark_server_socket_tainted(csp);
2503 byte_count += (unsigned long long)len;
2509 * We're still looking for the end of the server's header.
2510 * Buffer up the data we just read. If that fails, there's
2511 * little we can do but send our static out-of-memory page.
2513 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2515 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2516 rsp = cgi_error_memory();
2517 send_crunch_response(csp, rsp);
2518 mark_server_socket_tainted(csp);
2522 /* Convert iob into something sed() can digest */
2523 if (JB_ERR_PARSE == get_server_headers(csp))
2528 * Well, we tried our MS IIS/5 hack and it didn't work.
2529 * The header is incomplete and there isn't anything
2530 * we can do about it.
2532 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2533 "Applying the MS IIS5 hack didn't help.");
2534 log_error(LOG_LEVEL_CLF,
2535 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2536 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2537 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2538 mark_server_socket_tainted(csp);
2544 * Since we have to wait for more from the server before
2545 * we can parse the headers we just continue here.
2547 log_error(LOG_LEVEL_CONNECT,
2548 "Continuing buffering server headers from socket %d. "
2549 "Bytes most recently read: %d.", csp->cfd, len);
2556 * Account for the content bytes we
2557 * might have gotten with the headers.
2559 assert(csp->iob->eod >= csp->iob->cur);
2560 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2563 /* Did we actually get anything? */
2564 if (NULL == csp->headers->first)
2566 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2568 log_error(LOG_LEVEL_ERROR,
2569 "No server or forwarder response received on socket %d. "
2570 "Closing client socket %d without sending data.",
2571 csp->server_connection.sfd, csp->cfd);
2572 log_error(LOG_LEVEL_CLF,
2573 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2577 log_error(LOG_LEVEL_ERROR,
2578 "No server or forwarder response received on socket %d.",
2579 csp->server_connection.sfd);
2580 send_crunch_response(csp, error_response(csp, "no-server-data"));
2582 free_http_request(http);
2583 mark_server_socket_tainted(csp);
2587 assert(csp->headers->first->str);
2589 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2590 strncmpic(csp->headers->first->str, "ICY", 3))
2593 * It doesn't look like a HTTP (or Shoutcast) response:
2594 * tell the client and log the problem.
2596 if (strlen(csp->headers->first->str) > 30)
2598 csp->headers->first->str[30] = '\0';
2600 log_error(LOG_LEVEL_ERROR,
2601 "Invalid server or forwarder response. Starts with: %s",
2602 csp->headers->first->str);
2603 log_error(LOG_LEVEL_CLF,
2604 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2605 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2606 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2607 free_http_request(http);
2608 mark_server_socket_tainted(csp);
2613 * We have now received the entire server header,
2614 * filter it and send the result to the client
2616 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2618 log_error(LOG_LEVEL_CLF,
2619 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2620 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2621 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2622 free_http_request(http);
2623 mark_server_socket_tainted(csp);
2626 hdr = list_to_text(csp->headers);
2629 /* FIXME Should handle error properly */
2630 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2633 if ((csp->flags & CSP_FLAG_CHUNKED)
2634 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2635 && ((csp->iob->eod - csp->iob->cur) >= 5)
2636 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2638 log_error(LOG_LEVEL_CONNECT,
2639 "Looks like we got the last chunk together with "
2640 "the server headers. We better stop reading.");
2641 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2642 csp->expected_content_length = byte_count;
2643 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2646 csp->server_connection.response_received = time(NULL);
2648 if (crunch_response_triggered(csp, crunchers_light))
2651 * One of the tags created by a server-header
2652 * tagger triggered a crunch. We already
2653 * delivered the crunch response to the client
2654 * and are done here after cleaning up.
2657 mark_server_socket_tainted(csp);
2660 /* Buffer and pcrs filter this if appropriate. */
2662 if (!http->ssl) /* We talk plaintext */
2664 buffer_and_filter_content = content_requires_filtering(csp);
2667 * Only write if we're not buffering for content modification
2669 if (!buffer_and_filter_content)
2672 * Write the server's (modified) header to
2673 * the client (along with anything else that
2674 * may be in the buffer)
2677 if (write_socket(csp->cfd, hdr, strlen(hdr))
2678 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2680 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2683 * The write failed, so don't bother mentioning it
2684 * to the client... it probably can't hear us anyway.
2687 mark_server_socket_tainted(csp);
2692 /* we're finished with the server's header */
2698 * If this was a MS IIS/5 hack then it means the server
2699 * has already closed the connection. Nothing more to read.
2704 log_error(LOG_LEVEL_ERROR,
2705 "Closed server connection detected. "
2706 "Applying the MS IIS5 hack didn't help.");
2707 log_error(LOG_LEVEL_CLF,
2708 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2709 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2710 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2711 mark_server_socket_tainted(csp);
2717 mark_server_socket_tainted(csp);
2718 return; /* huh? we should never get here */
2721 if (csp->content_length == 0)
2724 * If Privoxy didn't recalculate the Content-Length,
2725 * byte_count is still correct.
2727 csp->content_length = byte_count;
2730 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2731 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2732 && (csp->expected_content_length != byte_count))
2734 log_error(LOG_LEVEL_CONNECT,
2735 "Received %llu bytes while expecting %llu.",
2736 byte_count, csp->expected_content_length);
2737 mark_server_socket_tainted(csp);
2741 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2742 csp->ip_addr_str, http->ocmd, csp->content_length);
2744 csp->server_connection.timestamp = time(NULL);
2748 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2749 /*********************************************************************
2751 * Function : prepare_csp_for_next_request
2753 * Description : Put the csp in a mostly vergin state.
2756 * 1 : csp = Current client state (buffers, headers, etc...)
2760 *********************************************************************/
2761 static void prepare_csp_for_next_request(struct client_state *csp)
2763 unsigned int toggled_on_flag_set = (0 != (csp->flags & CSP_FLAG_TOGGLED_ON));
2765 csp->content_type = 0;
2766 csp->content_length = 0;
2767 csp->expected_content_length = 0;
2768 csp->expected_client_content_length = 0;
2769 list_remove_all(csp->headers);
2770 clear_iob(csp->iob);
2771 freez(csp->error_message);
2772 free_http_request(csp->http);
2773 destroy_list(csp->headers);
2774 destroy_list(csp->tags);
2775 free_current_action(csp->action);
2776 if (NULL != csp->fwd)
2778 unload_forward_spec(csp->fwd);
2781 /* XXX: Store per-connection flags someplace else. */
2782 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
2783 if (toggled_on_flag_set)
2785 csp->flags |= CSP_FLAG_TOGGLED_ON;
2788 if (csp->client_iob->eod > csp->client_iob->cur)
2790 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
2791 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2793 assert(bytes_to_shift > 0);
2794 assert(data_length > 0);
2796 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
2797 data_length, bytes_to_shift);
2798 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
2799 csp->client_iob->cur = csp->client_iob->buf;
2800 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
2801 csp->client_iob->eod = csp->client_iob->buf + data_length;
2802 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
2804 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
2809 * We mainly care about resetting client_iob->cur so we don't
2810 * waste buffer space at the beginning and don't mess up the
2811 * request restoration done by cgi_show_request().
2813 * Freeing the buffer itself isn't technically necessary,
2814 * but makes debugging more convenient.
2816 clear_iob(csp->client_iob);
2819 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2822 /*********************************************************************
2826 * Description : This is little more than chat. We only "serve" to
2827 * to close (or remember) any socket that chat may have
2831 * 1 : csp = Current client state (buffers, headers, etc...)
2835 *********************************************************************/
2837 void serve(struct client_state *csp)
2838 #else /* ifndef AMIGA */
2839 static void serve(struct client_state *csp)
2840 #endif /* def AMIGA */
2842 int config_file_change_detected = 0; /* Only used for debugging */
2843 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2844 #ifdef FEATURE_CONNECTION_SHARING
2845 static int monitor_thread_running = 0;
2846 #endif /* def FEATURE_CONNECTION_SHARING */
2847 int continue_chatting = 0;
2849 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
2850 csp->ip_addr_str, csp->cfd);
2854 unsigned int latency;
2859 * If the request has been crunched,
2860 * the calculated latency is zero.
2862 latency = (unsigned)(csp->server_connection.response_received -
2863 csp->server_connection.request_sent) / 2;
2865 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2866 && (csp->flags & CSP_FLAG_CRUNCHED)
2867 && (csp->expected_client_content_length != 0))
2869 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
2870 log_error(LOG_LEVEL_CONNECT,
2871 "Tainting client socket %d due to unread data.", csp->cfd);
2874 continue_chatting = (csp->config->feature_flags
2875 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2876 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2877 && (csp->cfd != JB_INVALID_SOCKET)
2878 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2879 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
2880 || (csp->flags & CSP_FLAG_CHUNKED));
2882 if (!(csp->flags & CSP_FLAG_CRUNCHED)
2883 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
2885 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
2887 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
2889 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2890 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2891 || !socket_is_still_alive(csp->server_connection.sfd)
2892 || !(latency < csp->server_connection.keep_alive_timeout))
2894 log_error(LOG_LEVEL_CONNECT,
2895 "Closing server socket %d connected to %s. "
2896 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
2897 csp->server_connection.sfd, csp->server_connection.host,
2898 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2899 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2900 socket_is_still_alive(csp->server_connection.sfd),
2901 csp->server_connection.keep_alive_timeout);
2902 #ifdef FEATURE_CONNECTION_SHARING
2903 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2905 forget_connection(csp->server_connection.sfd);
2907 #endif /* def FEATURE_CONNECTION_SHARING */
2908 close_socket(csp->server_connection.sfd);
2909 mark_connection_closed(&csp->server_connection);
2913 if (continue_chatting && any_loaded_file_changed(csp))
2915 continue_chatting = 0;
2916 config_file_change_detected = 1;
2919 if (continue_chatting)
2921 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
2922 && socket_is_still_alive(csp->cfd))
2924 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
2925 "pipelined on socket %d and the socket is still alive.",
2926 csp->requests_received_total+1, csp->cfd);
2927 prepare_csp_for_next_request(csp);
2931 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
2933 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2935 log_error(LOG_LEVEL_CONNECT,
2936 "Waiting for the next client request on socket %d. "
2937 "Keeping the server socket %d to %s open.",
2938 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2942 log_error(LOG_LEVEL_CONNECT,
2943 "Waiting for the next client request on socket %d. "
2944 "No server socket to keep open.", csp->cfd);
2948 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2949 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
2950 && socket_is_still_alive(csp->cfd))
2952 log_error(LOG_LEVEL_CONNECT,
2953 "Client request %u arrived in time on socket %d.",
2954 csp->requests_received_total+1, csp->cfd);
2955 prepare_csp_for_next_request(csp);
2959 #ifdef FEATURE_CONNECTION_SHARING
2960 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2961 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
2962 && (socket_is_still_alive(csp->server_connection.sfd)))
2964 time_t time_open = time(NULL) - csp->server_connection.timestamp;
2966 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
2971 remember_connection(&csp->server_connection);
2972 csp->server_connection.sfd = JB_INVALID_SOCKET;
2973 drain_and_close_socket(csp->cfd);
2974 csp->cfd = JB_INVALID_SOCKET;
2975 privoxy_mutex_lock(&connection_reuse_mutex);
2976 if (!monitor_thread_running)
2978 monitor_thread_running = 1;
2979 privoxy_mutex_unlock(&connection_reuse_mutex);
2980 wait_for_alive_connections();
2981 privoxy_mutex_lock(&connection_reuse_mutex);
2982 monitor_thread_running = 0;
2984 privoxy_mutex_unlock(&connection_reuse_mutex);
2986 #endif /* def FEATURE_CONNECTION_SHARING */
2990 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2992 log_error(LOG_LEVEL_CONNECT,
2993 "Closing server socket %d connected to %s. Keep-alive: %u. "
2994 "Tainted: %u. Socket alive: %u. Timeout: %u. "
2995 "Configuration file change detected: %u",
2996 csp->server_connection.sfd, csp->server_connection.host,
2997 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2998 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2999 socket_is_still_alive(csp->server_connection.sfd),
3000 csp->server_connection.keep_alive_timeout,
3001 config_file_change_detected);
3003 } while (continue_chatting);
3007 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3009 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3011 #ifdef FEATURE_CONNECTION_SHARING
3012 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3014 forget_connection(csp->server_connection.sfd);
3016 #endif /* def FEATURE_CONNECTION_SHARING */
3017 close_socket(csp->server_connection.sfd);
3020 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3021 mark_connection_closed(&csp->server_connection);
3024 if (csp->cfd != JB_INVALID_SOCKET)
3026 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3027 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3028 "Configuration file change detected: %u. Requests received: %u.",
3029 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3030 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3031 config_file_change_detected, csp->requests_received_total);
3032 drain_and_close_socket(csp->cfd);
3035 csp->flags &= ~CSP_FLAG_ACTIVE;
3041 /*********************************************************************
3043 * Function : server_thread
3045 * Description : We only exist to call `serve' in a threaded environment.
3048 * 1 : data = Current client state (buffers, headers, etc...)
3050 * Returns : Always 0.
3052 *********************************************************************/
3053 static int32 server_thread(void *data)
3055 serve((struct client_state *) data);
3062 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3063 /*********************************************************************
3067 * Description : Print usage info & exit.
3069 * Parameters : Pointer to argv[0] for identifying ourselves
3073 *********************************************************************/
3074 static void usage(const char *myname)
3076 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3077 "Usage: %s [--config-test] "
3080 #endif /* defined(unix) */
3083 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3084 #endif /* defined(unix) */
3085 "[--version] [configfile]\n"
3086 "Aborting\n", myname);
3091 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3094 #ifdef MUTEX_LOCKS_AVAILABLE
3095 /*********************************************************************
3097 * Function : privoxy_mutex_lock
3099 * Description : Locks a mutex.
3102 * 1 : mutex = The mutex to lock.
3104 * Returns : Void. May exit in case of errors.
3106 *********************************************************************/
3107 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3109 #ifdef FEATURE_PTHREAD
3110 int err = pthread_mutex_lock(mutex);
3113 if (mutex != &log_mutex)
3115 log_error(LOG_LEVEL_FATAL,
3116 "Mutex locking failed: %s.\n", strerror(err));
3121 EnterCriticalSection(mutex);
3122 #endif /* def FEATURE_PTHREAD */
3126 /*********************************************************************
3128 * Function : privoxy_mutex_unlock
3130 * Description : Unlocks a mutex.
3133 * 1 : mutex = The mutex to unlock.
3135 * Returns : Void. May exit in case of errors.
3137 *********************************************************************/
3138 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3140 #ifdef FEATURE_PTHREAD
3141 int err = pthread_mutex_unlock(mutex);
3144 if (mutex != &log_mutex)
3146 log_error(LOG_LEVEL_FATAL,
3147 "Mutex unlocking failed: %s.\n", strerror(err));
3152 LeaveCriticalSection(mutex);
3153 #endif /* def FEATURE_PTHREAD */
3157 /*********************************************************************
3159 * Function : privoxy_mutex_init
3161 * Description : Prepares a mutex.
3164 * 1 : mutex = The mutex to initialize.
3166 * Returns : Void. May exit in case of errors.
3168 *********************************************************************/
3169 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3171 #ifdef FEATURE_PTHREAD
3172 int err = pthread_mutex_init(mutex, 0);
3175 printf("Fatal error. Mutex initialization failed: %s.\n",
3180 InitializeCriticalSection(mutex);
3181 #endif /* def FEATURE_PTHREAD */
3183 #endif /* def MUTEX_LOCKS_AVAILABLE */
3185 /*********************************************************************
3187 * Function : initialize_mutexes
3189 * Description : Prepares mutexes if mutex support is available.
3193 * Returns : Void, exits in case of errors.
3195 *********************************************************************/
3196 static void initialize_mutexes(void)
3198 #ifdef MUTEX_LOCKS_AVAILABLE
3200 * Prepare global mutex semaphores
3202 privoxy_mutex_init(&log_mutex);
3203 privoxy_mutex_init(&log_init_mutex);
3204 privoxy_mutex_init(&connection_reuse_mutex);
3205 #ifdef FEATURE_EXTERNAL_FILTERS
3206 privoxy_mutex_init(&external_filter_mutex);
3210 * XXX: The assumptions below are a bit naive
3211 * and can cause locks that aren't necessary.
3213 * For example older FreeBSD versions (< 6.x?)
3214 * have no gethostbyname_r, but gethostbyname is
3217 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3218 privoxy_mutex_init(&resolver_mutex);
3219 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3221 * XXX: should we use a single mutex for
3222 * localtime() and gmtime() as well?
3224 #ifndef HAVE_GMTIME_R
3225 privoxy_mutex_init(&gmtime_mutex);
3226 #endif /* ndef HAVE_GMTIME_R */
3228 #ifndef HAVE_LOCALTIME_R
3229 privoxy_mutex_init(&localtime_mutex);
3230 #endif /* ndef HAVE_GMTIME_R */
3233 privoxy_mutex_init(&rand_mutex);
3234 #endif /* ndef HAVE_RANDOM */
3236 #endif /* def MUTEX_LOCKS_AVAILABLE */
3240 /*********************************************************************
3244 * Description : Load the config file and start the listen loop.
3245 * This function is a lot more *sane* with the `load_config'
3246 * and `listen_loop' functions; although it stills does
3247 * a *little* too much for my taste.
3250 * 1 : argc = Number of parameters (including $0).
3251 * 2 : argv = Array of (char *)'s to the parameters.
3253 * Returns : 1 if : can't open config file, unrecognized directive,
3254 * stats requested in multi-thread mode, can't open the
3255 * log file, can't open the jar file, listen port is invalid,
3256 * any load fails, and can't bind port.
3258 * Else main never returns, the process must be signaled
3259 * to terminate execution. Or, on Windows, use the
3260 * "File", "Exit" menu option.
3262 *********************************************************************/
3264 int real_main(int argc, char **argv)
3266 int main(int argc, char **argv)
3270 int do_config_test = 0;
3271 unsigned int random_seed;
3273 struct passwd *pw = NULL;
3274 struct group *grp = NULL;
3276 char *pre_chroot_nslookup_to_load_resolver = NULL;
3283 #if !defined(_WIN32)
3290 /* Prepare mutexes if supported and necessary. */
3291 initialize_mutexes();
3293 /* Enable logging until further notice. */
3297 * Parse the command line arguments
3299 * XXX: simply printing usage information in case of
3300 * invalid arguments isn't particularly user friendly.
3302 while (++argc_pos < argc)
3305 /* Check to see if the service must be installed or uninstalled */
3306 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3308 const char *pName = argv[argc_pos] + 9;
3311 exit((install_service(pName)) ? 0 : 1);
3313 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3315 const char *pName = argv[argc_pos] + 11;
3318 exit((uninstall_service(pName)) ? 0 : 1);
3320 else if (strcmp(argv[argc_pos], "--service") == 0)
3322 bRunAsService = TRUE;
3323 w32_set_service_cwd();
3324 atexit(w32_service_exit_notify);
3327 #endif /* defined(_WIN32) */
3330 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3332 if (strcmp(argv[argc_pos], "--help") == 0)
3337 else if (strcmp(argv[argc_pos], "--version") == 0)
3339 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3345 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3347 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3351 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3353 if (++argc_pos == argc) usage(argv[0]);
3354 pidfile = strdup_or_die(argv[argc_pos]);
3357 else if (strcmp(argv[argc_pos], "--user") == 0)
3362 if (++argc_pos == argc) usage(argv[argc_pos]);
3364 user_arg = strdup_or_die(argv[argc_pos]);
3365 group_name = strchr(user_arg, '.');
3366 if (NULL != group_name)
3368 /* Nul-terminate the user name */
3371 /* Skip the former delimiter to actually reach the group name */
3374 grp = getgrnam(group_name);
3377 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3380 pw = getpwnam(user_arg);
3383 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3389 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3391 if (++argc_pos == argc) usage(argv[0]);
3392 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3395 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3399 #endif /* defined(unix) */
3401 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3406 else if (argc_pos + 1 != argc)
3409 * This is neither the last command line
3410 * option, nor was it recognized before,
3411 * therefore it must be invalid.
3417 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3419 configfile = argv[argc_pos];
3422 } /* -END- while (more arguments) */
3424 show_version(Argv[0]);
3427 if (*configfile != '/')
3429 char cwd[BUFFER_SIZE];
3431 size_t abs_file_size;
3433 /* make config-filename absolute here */
3434 if (NULL == getcwd(cwd, sizeof(cwd)))
3436 perror("failed to get current working directory");
3440 basedir = strdup_or_die(cwd);
3442 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3443 abs_file = malloc_or_die(abs_file_size);
3444 strlcpy(abs_file, basedir, abs_file_size);
3445 strlcat(abs_file, "/", abs_file_size);
3446 strlcat(abs_file, configfile, abs_file_size);
3447 configfile = abs_file;
3449 #endif /* defined unix */
3453 clients->next = NULL;
3455 /* XXX: factor out initialising after the next stable release. */
3458 #elif defined(_WIN32)
3462 random_seed = (unsigned int)time(NULL);
3464 srandom(random_seed);
3467 #endif /* ifdef HAVE_RANDOM */
3470 * Unix signal handling
3472 * Catch the abort, interrupt and terminate signals for a graceful exit
3473 * Catch the hangup signal so the errlog can be reopened.
3474 * Ignore the broken pipe signals (FIXME: Why?)
3476 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3479 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3481 for (idx = 0; idx < SZ(catched_signals); idx++)
3483 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3484 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3486 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3487 #endif /* ifdef sun */
3489 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3493 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3495 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3499 #else /* ifdef _WIN32 */
3500 # ifdef _WIN_CONSOLE
3502 * We *are* in a windows console app.
3503 * Print a verbose messages about FAQ's and such
3505 printf("%s", win32_blurb);
3506 # endif /* def _WIN_CONSOLE */
3507 #endif /* def _WIN32 */
3511 exit(NULL == load_config());
3514 /* Initialize the CGI subsystem */
3515 cgi_init_error_messages();
3518 * If running on unix and without the --no-daemon
3519 * option, become a daemon. I.e. fork, detach
3520 * from tty and get process group leadership
3529 if (pid < 0) /* error */
3534 else if (pid != 0) /* parent */
3539 * must check for errors
3540 * child died due to missing files aso
3543 wpid = waitpid(pid, &status, WNOHANG);
3555 * stderr (fd 2) will be closed later on,
3556 * when the config file has been parsed.
3562 * Reserve fd 0 and 1 to prevent abort() and friends
3563 * from sending stuff to the clients or servers.
3565 fd = open("/dev/null", O_RDONLY);
3568 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3572 if (dup2(fd, 0) == -1)
3574 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3578 fd = open("/dev/null", O_WRONLY);
3581 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3585 if (dup2(fd, 1) == -1)
3587 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3592 #ifdef FEATURE_EXTERNAL_FILTERS
3593 for (fd = 0; fd < 3; fd++)
3595 mark_socket_for_close_on_execute(fd);
3601 } /* -END- if (daemon_mode) */
3604 * As soon as we have written the PID file, we can switch
3605 * to the user and group ID indicated by the --user option
3611 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3613 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3617 if (setgroups(1, &grp->gr_gid))
3619 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3622 else if (initgroups(pw->pw_name, pw->pw_gid))
3624 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3630 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3632 /* Read the time zone file from /etc before doing chroot. */
3634 if (NULL != pre_chroot_nslookup_to_load_resolver
3635 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3637 /* Initialize resolver library. */
3638 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3640 if (chroot(pw->pw_dir) < 0)
3642 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3646 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3649 if (setuid(pw->pw_uid))
3651 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3655 char putenv_dummy[64];
3657 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3658 if (putenv(putenv_dummy) != 0)
3660 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3663 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3664 if (putenv(putenv_dummy) != 0)
3666 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3672 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3675 #endif /* defined unix */
3678 /* This will be FALSE unless the command line specified --service
3682 /* Yup, so now we must attempt to establish a connection
3683 * with the service dispatcher. This will only work if this
3684 * process was launched by the service control manager to
3685 * actually run as a service. If this isn't the case, i've
3686 * known it take around 30 seconds or so for the call to return.
3689 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3690 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3692 /* Service has run, and at this point is now being stopped, so just return */
3697 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3699 /* An error occurred. Usually it's because --service was wrongly specified
3700 * and we were unable to connect to the Service Control Dispatcher because
3701 * it wasn't expecting us and is therefore not listening.
3703 * For now, just continue below to call the listen_loop function.
3706 #endif /* def _WIN32 */
3716 /*********************************************************************
3718 * Function : bind_port_helper
3720 * Description : Bind the listen port. Handles logging, and aborts
3724 * 1 : haddr = Host address to bind to. Use NULL to bind to
3726 * 2 : hport = Specifies port to bind to.
3728 * Returns : Port that was opened.
3730 *********************************************************************/
3731 static jb_socket bind_port_helper(const char *haddr, int hport)
3736 result = bind_port(haddr, hport, &bfd);
3740 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
3744 log_error(LOG_LEVEL_FATAL,
3745 "can't bind to %s:%d: There may be another Privoxy "
3746 "or some other proxy running on port %d",
3747 bind_address, hport, hport);
3750 log_error(LOG_LEVEL_FATAL,
3751 "can't bind to %s:%d: The hostname is not resolvable",
3752 bind_address, hport);
3755 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3756 bind_address, hport);
3759 /* shouldn't get here */
3760 return JB_INVALID_SOCKET;
3764 if (bfd >= FD_SETSIZE)
3766 log_error(LOG_LEVEL_FATAL,
3767 "Bind socket number too high to use select(): %d >= %d",
3774 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3779 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3787 /*********************************************************************
3789 * Function : bind_ports_helper
3791 * Description : Bind the listen ports. Handles logging, and aborts
3795 * 1 : config = Privoxy configuration. Specifies ports
3797 * 2 : sockets = Preallocated array of opened sockets
3798 * corresponding to specification in config.
3799 * All non-opened sockets will be set to
3800 * JB_INVALID_SOCKET.
3802 * Returns : Nothing. Inspect sockets argument.
3804 *********************************************************************/
3805 static void bind_ports_helper(struct configuration_spec * config,
3806 jb_socket sockets[])
3810 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3812 if (config->hport[i])
3814 sockets[i] = bind_port_helper(config->haddr[i], config->hport[i]);
3818 sockets[i] = JB_INVALID_SOCKET;
3821 config->need_bind = 0;
3825 /*********************************************************************
3827 * Function : close_ports_helper
3829 * Description : Close listenings ports.
3832 * 1 : sockets = Array of opened and non-opened sockets to
3833 * close. All sockets will be set to
3834 * JB_INVALID_SOCKET.
3836 * Returns : Nothing.
3838 *********************************************************************/
3839 static void close_ports_helper(jb_socket sockets[])
3843 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3845 if (JB_INVALID_SOCKET != sockets[i])
3847 close_socket(sockets[i]);
3849 sockets[i] = JB_INVALID_SOCKET;
3855 /* Without this simple workaround we get this compiler warning from _beginthread
3856 * warning C4028: formal parameter 1 different from declaration
3858 void w32_service_listen_loop(void *p)
3862 #endif /* def _WIN32 */
3865 /*********************************************************************
3867 * Function : listen_loop
3869 * Description : bind the listen port and enter a "FOREVER" listening loop.
3875 *********************************************************************/
3876 static void listen_loop(void)
3878 struct client_states *csp_list = NULL;
3879 struct client_state *csp = NULL;
3880 jb_socket bfds[MAX_LISTENING_SOCKETS];
3881 struct configuration_spec *config;
3882 unsigned int active_threads = 0;
3884 config = load_config();
3886 #ifdef FEATURE_CONNECTION_SHARING
3888 * XXX: Should be relocated once it no
3889 * longer needs to emit log messages.
3891 initialize_reusable_connections();
3892 #endif /* def FEATURE_CONNECTION_SHARING */
3894 bind_ports_helper(config, bfds);
3896 #ifdef FEATURE_GRACEFUL_TERMINATION
3897 while (!g_terminate)
3902 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3903 while (waitpid(-1, NULL, WNOHANG) > 0)
3905 /* zombie children */
3907 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3910 * Free data that was used by died threads
3912 active_threads = sweep();
3916 * Re-open the errlog after HUP signal
3918 if (received_hup_signal)
3920 if (NULL != config->logfile)
3922 init_error_log(Argv[0], config->logfile);
3924 received_hup_signal = 0;
3928 csp_list = (struct client_states *)zalloc(sizeof(*csp_list));
3929 if (NULL == csp_list)
3931 log_error(LOG_LEVEL_FATAL,
3932 "malloc(%d) for csp_list failed: %E", sizeof(*csp_list));
3935 csp = &csp_list->csp;
3937 log_error(LOG_LEVEL_CONNECT,
3938 "Waiting for the next client connection. Currently active threads: %d",
3941 if (!accept_connection(csp, bfds))
3943 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3955 csp->flags |= CSP_FLAG_ACTIVE;
3956 csp->server_connection.sfd = JB_INVALID_SOCKET;
3958 csp->config = config = load_config();
3960 if (config->need_bind)
3963 * Since we were listening to the "old port", we will not see
3964 * a "listen" param change until the next request. So, at
3965 * least 1 more request must be made for us to find the new
3966 * setting. I am simply closing the old socket and binding the
3969 * Which-ever is correct, we will serve 1 more page via the
3970 * old settings. This should probably be a "show-proxy-args"
3971 * request. This should not be a so common of an operation
3972 * that this will hurt people's feelings.
3975 close_ports_helper(bfds);
3977 bind_ports_helper(config, bfds);
3980 #ifdef FEATURE_TOGGLE
3981 if (global_toggle_state)
3982 #endif /* def FEATURE_TOGGLE */
3984 csp->flags |= CSP_FLAG_TOGGLED_ON;
3987 if (run_loader(csp))
3989 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3990 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3994 if (block_acl(NULL,csp))
3996 log_error(LOG_LEVEL_CONNECT,
3997 "Connection from %s on socket %d dropped due to ACL", csp->ip_addr_str, csp->cfd);
3998 close_socket(csp->cfd);
3999 freez(csp->ip_addr_str);
4003 #endif /* def FEATURE_ACL */
4005 if ((0 != config->max_client_connections)
4006 && (active_threads >= config->max_client_connections))
4008 log_error(LOG_LEVEL_CONNECT,
4009 "Rejecting connection from %s. Maximum number of connections reached.",
4011 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4012 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4013 close_socket(csp->cfd);
4014 freez(csp->ip_addr_str);
4019 /* add it to the list of clients */
4020 csp_list->next = clients->next;
4021 clients->next = csp_list;
4023 if (config->multi_threaded)
4027 /* this is a switch () statement in the C preprocessor - ugh */
4028 #undef SELECTED_ONE_OPTION
4030 /* Use Pthreads in preference to native code */
4031 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
4032 #define SELECTED_ONE_OPTION
4034 pthread_t the_thread;
4035 pthread_attr_t attrs;
4037 pthread_attr_init(&attrs);
4038 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4039 errno = pthread_create(&the_thread, &attrs,
4040 (void * (*)(void *))serve, csp);
4041 child_id = errno ? -1 : 0;
4042 pthread_attr_destroy(&attrs);
4046 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
4047 #define SELECTED_ONE_OPTION
4048 child_id = _beginthread(
4049 (void (*)(void *))serve,
4054 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
4055 #define SELECTED_ONE_OPTION
4056 child_id = _beginthread(
4057 (void(* _Optlink)(void*))serve,
4063 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
4064 #define SELECTED_ONE_OPTION
4066 thread_id tid = spawn_thread
4067 (server_thread, "server", B_NORMAL_PRIORITY, csp);
4069 if ((tid >= 0) && (resume_thread(tid) == B_OK))
4071 child_id = (int) tid;
4080 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
4081 #define SELECTED_ONE_OPTION
4082 csp->cfd = ReleaseSocket(csp->cfd, -1);
4085 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4086 NP_Output, Output(),
4087 NP_CloseOutput, FALSE,
4088 NP_Name, (ULONG)"privoxy child",
4092 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4093 NP_Output, Output(),
4094 NP_CloseOutput, FALSE,
4095 NP_Name, (ULONG)"privoxy child",
4096 NP_StackSize, 200*1024,
4102 ((struct Task *)child_id)->tc_UserData = csp;
4103 Signal((struct Task *)child_id, SIGF_SINGLE);
4108 #if !defined(SELECTED_ONE_OPTION)
4111 /* This block is only needed when using fork().
4112 * When using threads, the server thread was
4113 * created and run by the call to _beginthread().
4115 if (child_id == 0) /* child */
4118 #ifdef FEATURE_TOGGLE
4119 int inherited_toggle_state = global_toggle_state;
4120 #endif /* def FEATURE_TOGGLE */
4125 * If we've been toggled or we've blocked the request, tell Mom
4128 #ifdef FEATURE_TOGGLE
4129 if (inherited_toggle_state != global_toggle_state)
4131 rc |= RC_FLAG_TOGGLED;
4133 #endif /* def FEATURE_TOGGLE */
4135 #ifdef FEATURE_STATISTICS
4136 if (csp->flags & CSP_FLAG_REJECTED)
4138 rc |= RC_FLAG_BLOCKED;
4140 #endif /* ndef FEATURE_STATISTICS */
4144 else if (child_id > 0) /* parent */
4146 /* in a fork()'d environment, the parent's
4147 * copy of the client socket and the CSP
4151 #if !defined(_WIN32) && !defined(__CYGWIN__)
4153 wait(&child_status);
4156 * Evaluate child's return code: If the child has
4157 * - been toggled, toggle ourselves
4158 * - blocked its request, bump up the stats counter
4161 #ifdef FEATURE_TOGGLE
4162 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4164 global_toggle_state = !global_toggle_state;
4166 #endif /* def FEATURE_TOGGLE */
4168 #ifdef FEATURE_STATISTICS
4170 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4174 #endif /* def FEATURE_STATISTICS */
4176 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4177 close_socket(csp->cfd);
4178 csp->flags &= ~CSP_FLAG_ACTIVE;
4182 #undef SELECTED_ONE_OPTION
4183 /* end of cpp switch () */
4188 * Spawning the child failed, assume it's because
4189 * there are too many children running already.
4190 * XXX: If you assume ...
4192 log_error(LOG_LEVEL_ERROR,
4193 "Unable to take any additional connections: %E. Active threads: %d",
4195 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4196 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4197 close_socket(csp->cfd);
4198 csp->flags &= ~CSP_FLAG_ACTIVE;
4207 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4209 /* Clean up. Aim: free all memory (no leaks) */
4210 #ifdef FEATURE_GRACEFUL_TERMINATION
4212 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4214 unload_current_config_file();
4215 unload_current_actions_file();
4216 unload_current_re_filterfile();
4217 #ifdef FEATURE_TRUST
4218 unload_current_trust_file();
4221 if (config->multi_threaded)
4228 } while ((clients->next != NULL) && (--i > 0));
4232 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4242 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4243 /* Cleanup - remove taskbar icon etc. */
4248 #endif /* FEATURE_GRACEFUL_TERMINATION */