1 const char jcc_rcs[] = "$Id: jcc.c,v 1.426 2014/06/02 06:19:06 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 /* A function to crunch a response */
283 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
285 /* Crunch function flags */
286 #define CF_NO_FLAGS 0
287 /* Cruncher applies to forced requests as well */
288 #define CF_IGNORE_FORCE 1
289 /* Crunched requests are counted for the block statistics */
290 #define CF_COUNT_AS_REJECT 2
292 /* A crunch function and its flags */
295 const crunch_func_ptr cruncher;
299 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
301 /* Complete list of cruncher functions */
302 static const struct cruncher crunchers_all[] = {
303 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
304 { block_url, CF_COUNT_AS_REJECT },
306 { trust_url, CF_COUNT_AS_REJECT },
307 #endif /* def FEATURE_TRUST */
308 { redirect_url, CF_NO_FLAGS },
309 { dispatch_cgi, CF_IGNORE_FORCE},
313 /* Light version, used after tags are applied */
314 static const struct cruncher crunchers_light[] = {
315 { block_url, CF_COUNT_AS_REJECT },
316 { redirect_url, CF_NO_FLAGS },
322 * XXX: Don't we really mean
328 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
329 /*********************************************************************
331 * Function : sig_handler
333 * Description : Signal handler for different signals.
334 * Exit gracefully on TERM and INT
335 * or set a flag that will cause the errlog
336 * to be reopened by the main thread on HUP.
339 * 1 : the_signal = the signal cause this function to call
343 *********************************************************************/
344 static void sig_handler(int the_signal)
350 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
362 received_hup_signal = 1;
368 * We shouldn't be here, unless we catch signals
369 * in main() that we can't handle here!
371 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
379 /*********************************************************************
381 * Function : client_protocol_is_unsupported
383 * Description : Checks if the client used a known unsupported
384 * protocol and deals with it by sending an error
388 * 1 : csp = Current client state (buffers, headers, etc...)
389 * 2 : req = the first request line send by the client
391 * Returns : TRUE if an error response has been generated, or
392 * FALSE if the request doesn't look invalid.
394 *********************************************************************/
395 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
398 * If it's a FTP or gopher request, we don't support it.
400 * These checks are better than nothing, but they might
401 * not work in all configurations and some clients might
402 * have problems digesting the answer.
404 * They should, however, never cause more problems than
405 * Privoxy's old behaviour (returning the misleading HTML
408 * "Could not resolve http://(ftp|gopher)://example.org").
410 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
412 const char *response = NULL;
413 const char *protocol = NULL;
415 if (!strncmpic(req, "GET ftp://", 10))
417 response = FTP_RESPONSE;
422 response = GOPHER_RESPONSE;
425 log_error(LOG_LEVEL_ERROR,
426 "%s tried to use Privoxy as %s proxy: %s",
427 csp->ip_addr_str, protocol, req);
428 log_error(LOG_LEVEL_CLF,
429 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
431 write_socket(csp->cfd, response, strlen(response));
440 /*********************************************************************
442 * Function : get_request_destination_elsewhere
444 * Description : If the client's request was redirected into
445 * Privoxy without the client's knowledge,
446 * the request line lacks the destination host.
448 * This function tries to get it elsewhere,
449 * provided accept-intercepted-requests is enabled.
451 * "Elsewhere" currently only means "Host: header",
452 * but in the future we may ask the redirecting
453 * packet filter to look the destination up.
455 * If the destination stays unknown, an error
456 * response is send to the client and headers
457 * are freed so that chat() can return directly.
460 * 1 : csp = Current client state (buffers, headers, etc...)
461 * 2 : headers = a header list
463 * Returns : JB_ERR_OK if the destination is now known, or
464 * JB_ERR_PARSE if it isn't.
466 *********************************************************************/
467 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
471 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
473 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
474 " Privoxy isn't configured to accept intercepted requests.",
475 csp->ip_addr_str, csp->http->cmd);
476 /* XXX: Use correct size */
477 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
478 csp->ip_addr_str, csp->http->cmd);
480 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
481 destroy_list(headers);
485 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
487 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
488 /* Split the domain we just got for pattern matching */
489 init_domain_components(csp->http);
496 /* We can't work without destination. Go spread the news.*/
498 req = list_to_text(headers);
500 /* XXX: Use correct size */
501 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
502 csp->ip_addr_str, csp->http->cmd);
503 log_error(LOG_LEVEL_ERROR,
504 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
505 csp->ip_addr_str, csp->http->cmd, req);
508 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
509 destroy_list(headers);
514 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
515 * to get the destination IP address, use it as host directly
516 * or do a reverse DNS lookup first.
521 /*********************************************************************
523 * Function : get_server_headers
525 * Description : Parses server headers in iob and fills them
526 * into csp->headers so that they can later be
530 * 1 : csp = Current client state (buffers, headers, etc...)
532 * Returns : JB_ERR_OK if everything went fine, or
533 * JB_ERR_PARSE if the headers were incomplete.
535 *********************************************************************/
536 static jb_err get_server_headers(struct client_state *csp)
538 int continue_hack_in_da_house = 0;
541 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
546 * continue hack in da house. Ignore the ending of
547 * this head and continue enlisting header lines.
548 * The reason is described below.
550 enlist(csp->headers, "");
551 continue_hack_in_da_house = 0;
554 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
557 * It's a bodyless continue response, don't
558 * stop header parsing after reaching its end.
560 * As a result Privoxy will concatenate the
561 * next response's head and parse and deliver
562 * the headers as if they belonged to one request.
564 * The client will separate them because of the
565 * empty line between them.
567 * XXX: What we're doing here is clearly against
568 * the intended purpose of the continue header,
569 * and under some conditions (HTTP/1.0 client request)
570 * it's a standard violation.
572 * Anyway, "sort of against the spec" is preferable
573 * to "always getting confused by Continue responses"
574 * (Privoxy's behaviour before this hack was added)
576 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
577 continue_hack_in_da_house = 1;
579 else if (*header == '\0')
582 * If the header is empty, but the Continue hack
583 * isn't active, we can assume that we reached the
584 * end of the buffer before we hit the end of the
587 * Inform the caller an let it decide how to handle it.
592 if (JB_ERR_MEMORY == enlist(csp->headers, header))
595 * XXX: Should we quit the request and return a
596 * out of memory error page instead?
598 log_error(LOG_LEVEL_ERROR,
599 "Out of memory while enlisting server headers. %s lost.",
609 /*********************************************************************
611 * Function : crunch_reason
613 * Description : Translates the crunch reason code into a string.
616 * 1 : rsp = a http_response
618 * Returns : A string with the crunch reason or an error description.
620 *********************************************************************/
621 static const char *crunch_reason(const struct http_response *rsp)
623 char * reason = NULL;
628 return "Internal error while searching for crunch reason";
631 switch (rsp->crunch_reason)
634 reason = "Unsupported HTTP feature";
640 reason = "Untrusted";
643 reason = "Redirected";
649 reason = "DNS failure";
651 case FORWARDING_FAILED:
652 reason = "Forwarding failed";
655 reason = "Connection failure";
658 reason = "Out of memory (may mask other reasons)";
660 case CONNECTION_TIMEOUT:
661 reason = "Connection timeout";
664 reason = "No server data received";
667 reason = "No reason recorded";
675 /*********************************************************************
677 * Function : log_applied_actions
679 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
683 * 1 : actions = Current action spec to log
687 *********************************************************************/
688 static void log_applied_actions(const struct current_action_spec *actions)
691 * The conversion to text requires lots of memory allocations so
692 * we only do the conversion if the user is actually interested.
694 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
696 char *actions_as_text = actions_to_line_of_text(actions);
697 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
698 freez(actions_as_text);
703 /*********************************************************************
705 * Function : send_crunch_response
707 * Description : Delivers already prepared response for
708 * intercepted requests, logs the interception
709 * and frees the response.
712 * 1 : csp = Current client state (buffers, headers, etc...)
713 * 1 : rsp = Fully prepared response. Will be freed on exit.
717 *********************************************************************/
718 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
720 const struct http_request *http = csp->http;
724 assert(rsp->head != NULL);
728 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
732 * Extract the status code from the actual head
733 * that will be send to the client. It is the only
734 * way to get it right for all requests, including
735 * the fixed ones for out-of-memory problems.
737 * A head starts like this: 'HTTP/1.1 200...'
741 status_code[0] = rsp->head[9];
742 status_code[1] = rsp->head[10];
743 status_code[2] = rsp->head[11];
744 status_code[3] = '\0';
746 /* Log that the request was crunched and why. */
747 log_applied_actions(csp->action);
748 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
749 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
750 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
752 /* Write the answer to the client */
753 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
754 || write_socket(csp->cfd, rsp->body, rsp->content_length))
756 /* There is nothing we can do about it. */
757 log_error(LOG_LEVEL_ERROR,
758 "Couldn't deliver the error message through client socket %d: %E",
762 /* Clean up and return */
763 if (cgi_error_memory() != rsp)
765 free_http_response(rsp);
771 /*********************************************************************
773 * Function : crunch_response_triggered
775 * Description : Checks if the request has to be crunched,
776 * and delivers the crunch response if necessary.
779 * 1 : csp = Current client state (buffers, headers, etc...)
780 * 2 : crunchers = list of cruncher functions to run
782 * Returns : TRUE if the request was answered with a crunch response
785 *********************************************************************/
786 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
788 struct http_response *rsp = NULL;
789 const struct cruncher *c;
792 * If CGI request crunching is disabled,
793 * check the CGI dispatcher out of order to
794 * prevent unintentional blocks or redirects.
796 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
797 && (NULL != (rsp = dispatch_cgi(csp))))
799 /* Deliver, log and free the interception response. */
800 send_crunch_response(csp, rsp);
801 csp->flags |= CSP_FLAG_CRUNCHED;
805 for (c = crunchers; c->cruncher != NULL; c++)
808 * Check the cruncher if either Privoxy is toggled
809 * on and the request isn't forced, or if the cruncher
810 * applies to forced requests as well.
812 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
813 !(csp->flags & CSP_FLAG_FORCED)) ||
814 (c->flags & CF_IGNORE_FORCE))
816 rsp = c->cruncher(csp);
819 /* Deliver, log and free the interception response. */
820 send_crunch_response(csp, rsp);
821 csp->flags |= CSP_FLAG_CRUNCHED;
822 #ifdef FEATURE_STATISTICS
823 if (c->flags & CF_COUNT_AS_REJECT)
825 csp->flags |= CSP_FLAG_REJECTED;
827 #endif /* def FEATURE_STATISTICS */
838 /*********************************************************************
840 * Function : build_request_line
842 * Description : Builds the HTTP request line.
844 * If a HTTP forwarder is used it expects the whole URL,
845 * web servers only get the path.
848 * 1 : csp = Current client state (buffers, headers, etc...)
849 * 2 : fwd = The forwarding spec used for the request
850 * XXX: Should use http->fwd instead.
851 * 3 : request_line = The old request line which will be replaced.
853 * Returns : Nothing. Terminates in case of memory problems.
855 *********************************************************************/
856 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
858 struct http_request *http = csp->http;
860 assert(http->ssl == 0);
863 * Downgrade http version from 1.1 to 1.0
864 * if +downgrade action applies.
866 if ((csp->action->flags & ACTION_DOWNGRADE)
867 && (!strcmpic(http->ver, "HTTP/1.1")))
870 http->ver = strdup_or_die("HTTP/1.0");
874 * Rebuild the request line.
876 freez(*request_line);
877 *request_line = strdup(http->gpc);
878 string_append(request_line, " ");
880 if (fwd->forward_host)
882 string_append(request_line, http->url);
886 string_append(request_line, http->path);
888 string_append(request_line, " ");
889 string_append(request_line, http->ver);
891 if (*request_line == NULL)
893 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
895 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
899 /*********************************************************************
901 * Function : change_request_destination
903 * Description : Parse a (rewritten) request line and regenerate
904 * the http request data.
907 * 1 : csp = Current client state (buffers, headers, etc...)
909 * Returns : Forwards the parse_http_request() return code.
910 * Terminates in case of memory problems.
912 *********************************************************************/
913 static jb_err change_request_destination(struct client_state *csp)
915 struct http_request *http = csp->http;
918 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
919 csp->headers->first->str);
920 free_http_request(http);
921 err = parse_http_request(csp->headers->first->str, http);
922 if (JB_ERR_OK != err)
924 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
925 jb_err_to_string(err));
929 /* XXX: ocmd is a misleading name */
930 http->ocmd = strdup_or_die(http->cmd);
937 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
938 /*********************************************************************
940 * Function : server_response_is_complete
942 * Description : Determines whether we should stop reading
943 * from the server socket.
946 * 1 : csp = Current client state (buffers, headers, etc...)
947 * 2 : content_length = Length of content received so far.
949 * Returns : TRUE if the response is complete,
952 *********************************************************************/
953 static int server_response_is_complete(struct client_state *csp,
954 unsigned long long content_length)
956 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
958 if (!strcmpic(csp->http->gpc, "HEAD"))
961 * "HEAD" implies no body, we are thus expecting
962 * no content. XXX: incomplete "list" of methods?
964 csp->expected_content_length = 0;
965 content_length_known = TRUE;
966 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
969 if (csp->http->status == 204 || csp->http->status == 304)
972 * Expect no body. XXX: incomplete "list" of status codes?
974 csp->expected_content_length = 0;
975 content_length_known = TRUE;
976 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
979 return (content_length_known && ((0 == csp->expected_content_length)
980 || (csp->expected_content_length <= content_length)));
984 #ifdef FEATURE_CONNECTION_SHARING
985 /*********************************************************************
987 * Function : wait_for_alive_connections
989 * Description : Waits for alive connections to timeout.
995 *********************************************************************/
996 static void wait_for_alive_connections(void)
998 int connections_alive = close_unusable_connections();
1000 while (0 < connections_alive)
1002 log_error(LOG_LEVEL_CONNECT,
1003 "Waiting for %d connections to timeout.",
1006 connections_alive = close_unusable_connections();
1009 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1012 #endif /* def FEATURE_CONNECTION_SHARING */
1015 /*********************************************************************
1017 * Function : save_connection_destination
1019 * Description : Remembers a connection for reuse later on.
1022 * 1 : sfd = Open socket to remember.
1023 * 2 : http = The destination for the connection.
1024 * 3 : fwd = The forwarder settings used.
1025 * 3 : server_connection = storage.
1029 *********************************************************************/
1030 void save_connection_destination(jb_socket sfd,
1031 const struct http_request *http,
1032 const struct forward_spec *fwd,
1033 struct reusable_connection *server_connection)
1035 assert(sfd != JB_INVALID_SOCKET);
1036 assert(NULL != http->host);
1038 server_connection->sfd = sfd;
1039 server_connection->host = strdup_or_die(http->host);
1040 server_connection->port = http->port;
1042 assert(NULL != fwd);
1043 assert(server_connection->gateway_host == NULL);
1044 assert(server_connection->gateway_port == 0);
1045 assert(server_connection->forwarder_type == 0);
1046 assert(server_connection->forward_host == NULL);
1047 assert(server_connection->forward_port == 0);
1049 server_connection->forwarder_type = fwd->type;
1050 if (NULL != fwd->gateway_host)
1052 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1056 server_connection->gateway_host = NULL;
1058 server_connection->gateway_port = fwd->gateway_port;
1060 if (NULL != fwd->forward_host)
1062 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1066 server_connection->forward_host = NULL;
1068 server_connection->forward_port = fwd->forward_port;
1072 /*********************************************************************
1074 * Function : verify_request_length
1076 * Description : Checks if we already got the whole client requests
1077 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1080 * Data that doesn't belong to the current request is
1081 * either thrown away to let the client retry on a clean
1082 * socket, or stashed to be dealt with after the current
1083 * request is served.
1086 * 1 : csp = Current client state (buffers, headers, etc...)
1090 *********************************************************************/
1091 static void verify_request_length(struct client_state *csp)
1093 unsigned long long buffered_request_bytes =
1094 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1096 if ((csp->expected_client_content_length != 0)
1097 && (buffered_request_bytes != 0))
1099 if (csp->expected_client_content_length >= buffered_request_bytes)
1101 csp->expected_client_content_length -= buffered_request_bytes;
1102 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1103 "to account for the %llu ones we already got.",
1104 csp->expected_client_content_length, buffered_request_bytes);
1108 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1109 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1110 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1111 "Marking the server socket tainted after throwing %llu bytes away.",
1112 buffered_request_bytes - csp->expected_client_content_length);
1113 csp->expected_client_content_length = 0;
1114 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1117 if (csp->expected_client_content_length == 0)
1119 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1123 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1124 && ((csp->client_iob->cur < csp->client_iob->eod)
1125 || (csp->expected_client_content_length != 0)))
1127 if (strcmpic(csp->http->gpc, "GET")
1128 && strcmpic(csp->http->gpc, "HEAD")
1129 && strcmpic(csp->http->gpc, "TRACE")
1130 && strcmpic(csp->http->gpc, "OPTIONS")
1131 && strcmpic(csp->http->gpc, "DELETE"))
1133 /* XXX: this is an incomplete hack */
1134 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1135 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1139 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1141 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1143 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1144 log_error(LOG_LEVEL_CONNECT,
1145 "Possible pipeline attempt detected. The connection will not "
1146 "be kept alive and we will only serve the first request.");
1147 /* Nuke the pipelined requests from orbit, just to be sure. */
1148 clear_iob(csp->client_iob);
1153 * Keep the pipelined data around for now, we'll deal with
1154 * it once we're done serving the current request.
1156 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1157 assert(csp->client_iob->eod >= csp->client_iob->cur);
1158 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1159 "%d bytes of pipelined data received.",
1160 (int)(csp->client_iob->eod - csp->client_iob->cur));
1166 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1167 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1170 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1173 /*********************************************************************
1175 * Function : mark_server_socket_tainted
1177 * Description : Makes sure we don't reuse a server socket
1178 * (if we didn't read everything the server sent
1179 * us reusing the socket would lead to garbage).
1182 * 1 : csp = Current client state (buffers, headers, etc...)
1186 *********************************************************************/
1187 static void mark_server_socket_tainted(struct client_state *csp)
1190 * For consistency we always mark the server socket
1191 * tainted, however, to reduce the log noise we only
1192 * emit a log message if the server socket could have
1193 * actually been reused.
1195 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1196 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1198 log_error(LOG_LEVEL_CONNECT,
1199 "Marking the server socket %d tainted.",
1200 csp->server_connection.sfd);
1202 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1205 /*********************************************************************
1207 * Function : get_request_line
1209 * Description : Read the client request line.
1212 * 1 : csp = Current client state (buffers, headers, etc...)
1214 * Returns : Pointer to request line or NULL in case of errors.
1216 *********************************************************************/
1217 static char *get_request_line(struct client_state *csp)
1219 char buf[BUFFER_SIZE];
1220 char *request_line = NULL;
1223 memset(buf, 0, sizeof(buf));
1225 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1228 * If there are multiple pipelined requests waiting,
1229 * the flag will be set again once the next request
1232 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1234 request_line = get_header(csp->client_iob);
1235 if ((NULL != request_line) && ('\0' != *request_line))
1237 return request_line;
1241 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1242 "received yet. Continuing reading from %d.", csp->cfd);
1248 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1250 if (socket_is_still_alive(csp->cfd))
1252 log_error(LOG_LEVEL_CONNECT,
1253 "No request line on socket %d received in time. Timeout: %d.",
1254 csp->cfd, csp->config->socket_timeout);
1255 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1256 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1260 log_error(LOG_LEVEL_CONNECT,
1261 "The client side of the connection on socket %d got "
1262 "closed without sending a complete request line.", csp->cfd);
1267 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1269 if (len <= 0) return NULL;
1272 * If there is no memory left for buffering the
1273 * request, there is nothing we can do but hang up
1275 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1280 request_line = get_header(csp->client_iob);
1282 } while ((NULL != request_line) && ('\0' == *request_line));
1284 return request_line;
1290 CHUNK_STATUS_MISSING_DATA,
1291 CHUNK_STATUS_BODY_COMPLETE,
1292 CHUNK_STATUS_PARSE_ERROR
1296 /*********************************************************************
1298 * Function : chunked_body_is_complete
1300 * Description : Figures out wheter or not a chunked body is complete.
1302 * Currently it always starts at the beginning of the
1303 * buffer which is somewhat wasteful and prevents Privoxy
1304 * from starting to forward the correctly parsed chunks
1305 * as soon as theoretically possible.
1307 * Should be modified to work with a common buffer,
1308 * and allow the caller to skip already parsed chunks.
1310 * This would allow the function to be used for unbuffered
1311 * response bodies as well.
1314 * 1 : iob = Buffer with the body to check.
1315 * 2 : length = Length of complete body
1317 * Returns : Enum with the result of the check.
1319 *********************************************************************/
1320 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1322 unsigned int chunksize;
1328 * We need at least a single digit, followed by "\r\n",
1329 * followed by an unknown amount of data, followed by "\r\n".
1331 if (p + 5 > iob->eod)
1333 return CHUNK_STATUS_MISSING_DATA;
1335 if (sscanf(p, "%x", &chunksize) != 1)
1337 return CHUNK_STATUS_PARSE_ERROR;
1341 * We want at least a single digit, followed by "\r\n",
1342 * followed by the specified amount of data, followed by "\r\n".
1344 if (p + chunksize + 5 > iob->eod)
1346 return CHUNK_STATUS_MISSING_DATA;
1349 /* Skip chunk-size. */
1350 p = strstr(p, "\r\n");
1353 return CHUNK_STATUS_PARSE_ERROR;
1356 * Skip "\r\n", the chunk data and another "\r\n".
1357 * Moving p to either the beginning of the next chunk-size
1358 * or one byte beyond the end of the chunked data.
1360 p += 2 + chunksize + 2;
1361 } while (chunksize > 0U);
1363 *length = (size_t)(p - iob->cur);
1364 assert(*length <= (size_t)(iob->eod - iob->cur));
1365 assert(p <= iob->eod);
1367 return CHUNK_STATUS_BODY_COMPLETE;
1372 /*********************************************************************
1374 * Function : receive_chunked_client_request_body
1376 * Description : Read the chunk-encoded client request body.
1377 * Failures are dealt with.
1380 * 1 : csp = Current client state (buffers, headers, etc...)
1382 * Returns : JB_ERR_OK or JB_ERR_PARSE
1384 *********************************************************************/
1385 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1388 enum chunk_status status;
1390 while (CHUNK_STATUS_MISSING_DATA ==
1391 (status = chunked_body_is_complete(csp->client_iob,&body_length)))
1393 char buf[BUFFER_SIZE];
1396 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1398 log_error(LOG_LEVEL_ERROR,
1399 "Timeout while waiting for the client body.");
1402 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1405 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1408 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1413 if (status != CHUNK_STATUS_BODY_COMPLETE)
1415 write_socket(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1416 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE));
1417 log_error(LOG_LEVEL_CLF,
1418 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1419 return JB_ERR_PARSE;
1421 log_error(LOG_LEVEL_CONNECT,
1422 "Chunked client body completely read. Length: %d", body_length);
1423 csp->expected_client_content_length = body_length;
1429 /*********************************************************************
1431 * Function : receive_client_request
1433 * Description : Read the client's request (more precisely the
1434 * client headers) and answer it if necessary.
1437 * 1 : csp = Current client state (buffers, headers, etc...)
1439 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1441 *********************************************************************/
1442 static jb_err receive_client_request(struct client_state *csp)
1444 char buf[BUFFER_SIZE];
1447 struct http_request *http;
1451 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1452 struct list header_list;
1453 struct list *headers = &header_list;
1455 /* We don't care if the arriving data is a valid HTTP request or not. */
1456 csp->requests_received_total++;
1460 memset(buf, 0, sizeof(buf));
1462 req = get_request_line(csp);
1465 mark_server_socket_tainted(csp);
1466 return JB_ERR_PARSE;
1468 assert(*req != '\0');
1470 if (client_protocol_is_unsupported(csp, req))
1472 return JB_ERR_PARSE;
1475 #ifdef FEATURE_FORCE_LOAD
1477 * If this request contains the FORCE_PREFIX and blocks
1478 * aren't enforced, get rid of it and set the force flag.
1480 if (strstr(req, FORCE_PREFIX))
1482 if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1484 log_error(LOG_LEVEL_FORCE,
1485 "Ignored force prefix in request: \"%s\".", req);
1489 strclean(req, FORCE_PREFIX);
1490 log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1491 csp->flags |= CSP_FLAG_FORCED;
1494 #endif /* def FEATURE_FORCE_LOAD */
1496 err = parse_http_request(req, http);
1498 if (JB_ERR_OK != err)
1500 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1501 /* XXX: Use correct size */
1502 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1503 log_error(LOG_LEVEL_ERROR,
1504 "Couldn't parse request line received from %s: %s",
1505 csp->ip_addr_str, jb_err_to_string(err));
1507 free_http_request(http);
1508 return JB_ERR_PARSE;
1511 /* grab the rest of the client's headers */
1515 p = get_header(csp->client_iob);
1519 /* There are no additional headers to read. */
1526 * We didn't receive a complete header
1527 * line yet, get the rest of it.
1529 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1531 log_error(LOG_LEVEL_ERROR,
1532 "Stopped grabbing the client headers.");
1533 destroy_list(headers);
1534 return JB_ERR_PARSE;
1537 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1540 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1541 destroy_list(headers);
1542 return JB_ERR_PARSE;
1545 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1548 * If there is no memory left for buffering the
1549 * request, there is nothing we can do but hang up
1551 destroy_list(headers);
1552 return JB_ERR_MEMORY;
1557 if (!strncmpic(p, "Transfer-Encoding:", 18))
1560 * XXX: should be called through sed()
1561 * but currently can't.
1563 client_transfer_encoding(csp, &p);
1566 * We were able to read a complete
1567 * header and can finally enlist it.
1574 if (http->host == NULL)
1577 * If we still don't know the request destination,
1578 * the request is invalid or the client uses
1579 * Privoxy without its knowledge.
1581 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1584 * Our attempts to get the request destination
1585 * elsewhere failed or Privoxy is configured
1586 * to only accept proxy requests.
1588 * An error response has already been send
1589 * and we're done here.
1591 return JB_ERR_PARSE;
1596 * Determine the actions for this URL
1598 #ifdef FEATURE_TOGGLE
1599 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1601 /* Most compatible set of actions (i.e. none) */
1602 init_current_action(csp->action);
1605 #endif /* ndef FEATURE_TOGGLE */
1607 get_url_actions(csp, http);
1611 * Save a copy of the original request for logging
1613 http->ocmd = strdup_or_die(http->cmd);
1614 enlist(csp->headers, http->cmd);
1616 /* Append the previously read headers */
1617 list_append_list_unique(csp->headers, headers);
1618 destroy_list(headers);
1625 /*********************************************************************
1627 * Function : parse_client_request
1629 * Description : Parses the client's request and decides what to do
1632 * Note that since we're not using select() we could get
1633 * blocked here if a client connected, then didn't say
1637 * 1 : csp = Current client state (buffers, headers, etc...)
1639 * Returns : JB_ERR_OK or JB_ERR_PARSE
1641 *********************************************************************/
1642 static jb_err parse_client_request(struct client_state *csp)
1644 struct http_request *http = csp->http;
1647 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1648 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1649 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1650 && (csp->http->ssl == 0))
1652 /* Assume persistence until further notice */
1653 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1656 if (csp->http->ssl == 0)
1659 * This whole block belongs to chat() but currently
1660 * has to be executed before sed().
1662 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1664 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1666 return JB_ERR_PARSE;
1671 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1673 verify_request_length(csp);
1675 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1677 err = sed(csp, FILTER_CLIENT_HEADERS);
1678 if (JB_ERR_OK != err)
1680 /* XXX: Should be handled in sed(). */
1681 assert(err == JB_ERR_PARSE);
1682 log_error(LOG_LEVEL_FATAL, "Failed to parse client headers.");
1684 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1686 /* Check request line for rewrites. */
1687 if ((NULL == csp->headers->first->str)
1688 || (strcmp(http->cmd, csp->headers->first->str) &&
1689 (JB_ERR_OK != change_request_destination(csp))))
1692 * A header filter broke the request line - bail out.
1694 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1695 /* XXX: Use correct size */
1696 log_error(LOG_LEVEL_CLF,
1697 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1698 log_error(LOG_LEVEL_ERROR,
1699 "Invalid request line after applying header filters.");
1700 free_http_request(http);
1702 return JB_ERR_PARSE;
1710 /*********************************************************************
1714 * Description : Once a connection from the client has been accepted,
1715 * this function is called (via serve()) to handle the
1716 * main business of the communication. This function
1717 * returns after dealing with a single request. It can
1718 * be called multiple times with the same client socket
1719 * if the client is keeping the connection alive.
1721 * The decision whether or not a client connection will
1722 * be kept alive is up to the caller which also must
1723 * close the client socket when done.
1725 * FIXME: chat is nearly thousand lines long.
1729 * 1 : csp = Current client state (buffers, headers, etc...)
1731 * Returns : Nothing.
1733 *********************************************************************/
1734 static void chat(struct client_state *csp)
1736 char buf[BUFFER_SIZE];
1743 int ms_iis5_hack = 0;
1744 unsigned long long byte_count = 0;
1745 const struct forward_spec *fwd;
1746 struct http_request *http;
1747 long len = 0; /* for buffer sizes (and negative error codes) */
1748 int buffer_and_filter_content = 0;
1750 /* Skeleton for HTTP response, if we should intercept the request */
1751 struct http_response *rsp;
1752 struct timeval timeout;
1753 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1754 int watch_client_socket;
1757 memset(buf, 0, sizeof(buf));
1761 if (receive_client_request(csp) != JB_ERR_OK)
1765 if (parse_client_request(csp) != JB_ERR_OK)
1770 /* decide how to route the HTTP request */
1771 fwd = forward_url(csp, http);
1774 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1775 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1780 * build the http request to send to the server
1781 * we have to do one of the following:
1783 * create = use the original HTTP request to create a new
1784 * HTTP request that has either the path component
1785 * without the http://domainspec (w/path) or the
1786 * full orininal URL (w/url)
1787 * Note that the path and/or the HTTP version may
1788 * have been altered by now.
1790 * connect = Open a socket to the host:port of the server
1791 * and short-circuit server and client socket.
1793 * pass = Pass the request unchanged if forwarding a CONNECT
1794 * request to a parent proxy. Note that we'll be sending
1795 * the CFAIL message ourselves if connecting to the parent
1796 * fails, but we won't send a CSUCCEED message if it works,
1797 * since that would result in a double message (ours and the
1798 * parent's). After sending the request to the parent, we simply
1801 * here's the matrix:
1804 * +--------+--------+
1806 * 0 | create | connect|
1808 * Forwarding +--------+--------+
1810 * 1 | create | pass |
1812 * +--------+--------+
1816 if (http->ssl && connect_port_is_forbidden(csp))
1818 const char *acceptable_connect_ports =
1819 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1820 assert(NULL != acceptable_connect_ports);
1821 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1822 "limit-connect{%s} doesn't allow CONNECT requests to %s",
1823 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
1824 csp->action->flags |= ACTION_BLOCK;
1830 freez(csp->headers->first->str);
1831 build_request_line(csp, fwd, &csp->headers->first->str);
1835 * We have a request. Check if one of the crunchers wants it.
1837 if (crunch_response_triggered(csp, crunchers_all))
1840 * Yes. The client got the crunch response and we're done here.
1845 log_applied_actions(csp->action);
1846 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1848 if (fwd->forward_host)
1850 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1851 fwd->forward_host, fwd->forward_port, http->hostport);
1855 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1858 /* here we connect to the server, gateway, or the forwarder */
1860 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1861 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
1862 && socket_is_still_alive(csp->server_connection.sfd)
1863 && connection_destination_matches(&csp->server_connection, http, fwd))
1865 log_error(LOG_LEVEL_CONNECT,
1866 "Reusing server socket %d connected to %s. Total requests: %u.",
1867 csp->server_connection.sfd, csp->server_connection.host,
1868 csp->server_connection.requests_sent_total);
1872 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
1874 #ifdef FEATURE_CONNECTION_SHARING
1875 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1877 remember_connection(&csp->server_connection);
1880 #endif /* def FEATURE_CONNECTION_SHARING */
1882 log_error(LOG_LEVEL_CONNECT,
1883 "Closing server socket %d connected to %s. Total requests: %u.",
1884 csp->server_connection.sfd, csp->server_connection.host,
1885 csp->server_connection.requests_sent_total);
1886 close_socket(csp->server_connection.sfd);
1888 mark_connection_closed(&csp->server_connection);
1890 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1892 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
1894 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
1896 if (fwd->type != SOCKS_NONE)
1899 rsp = error_response(csp, "forwarding-failed");
1901 else if (errno == EINVAL)
1903 rsp = error_response(csp, "no-such-domain");
1907 rsp = error_response(csp, "connect-failed");
1910 /* Write the answer to the client */
1913 send_crunch_response(csp, rsp);
1918 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1919 save_connection_destination(csp->server_connection.sfd,
1920 http, fwd, &csp->server_connection);
1921 csp->server_connection.keep_alive_timeout =
1922 (unsigned)csp->config->keep_alive_timeout;
1924 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1926 csp->server_connection.requests_sent_total++;
1928 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
1930 /* Client headers have been sent optimistically */
1931 assert(csp->headers->last == NULL);
1933 else if (fwd->forward_host || (http->ssl == 0))
1936 hdr = list_to_text(csp->headers);
1939 /* FIXME Should handle error properly */
1940 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1942 list_remove_all(csp->headers);
1945 * Write the client's (modified) header to the server
1946 * (along with anything else that may be in the buffer)
1948 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
1953 log_error(LOG_LEVEL_CONNECT,
1954 "Failed sending request headers to: %s: %E", http->hostport);
1956 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
1957 && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
1960 log_error(LOG_LEVEL_CONNECT,
1961 "Failed sending request body to: %s: %E", http->hostport);
1966 rsp = error_response(csp, "connect-failed");
1969 send_crunch_response(csp, rsp);
1977 * We're running an SSL tunnel and we're not forwarding,
1978 * so just ditch the client headers, send the "connect succeeded"
1979 * message to the client, flush the rest, and get out of the way.
1981 list_remove_all(csp->headers);
1982 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
1986 clear_iob(csp->client_iob);
1989 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
1991 /* XXX: should the time start earlier for optimistically sent data? */
1992 csp->server_connection.request_sent = time(NULL);
1994 maxfd = (csp->cfd > csp->server_connection.sfd) ?
1995 csp->cfd : csp->server_connection.sfd;
1997 /* pass data between the client and server
1998 * until one or the other shuts down the connection.
2003 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2004 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2011 * FD_ZERO here seems to point to an errant macro which crashes.
2012 * So do this by hand for now...
2014 memset(&rfds,0x00,sizeof(fd_set));
2018 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2019 if (!watch_client_socket)
2021 maxfd = csp->server_connection.sfd;
2024 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2026 FD_SET(csp->cfd, &rfds);
2029 FD_SET(csp->server_connection.sfd, &rfds);
2031 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2032 if ((csp->flags & CSP_FLAG_CHUNKED)
2033 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2034 && ((csp->iob->eod - csp->iob->cur) >= 5)
2035 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2038 * XXX: This check should be obsolete now,
2039 * but let's wait a while to be sure.
2041 log_error(LOG_LEVEL_CONNECT,
2042 "Looks like we got the last chunk together with "
2043 "the server headers but didn't detect it earlier. "
2044 "We better stop reading.");
2045 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2046 csp->expected_content_length = byte_count;
2047 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2049 if (server_body && server_response_is_complete(csp, byte_count))
2051 if (csp->expected_content_length == byte_count)
2053 log_error(LOG_LEVEL_CONNECT,
2054 "Done reading from server. Content length: %llu as expected. "
2055 "Bytes most recently read: %d.",
2060 log_error(LOG_LEVEL_CONNECT,
2061 "Done reading from server. Expected content length: %llu. "
2062 "Actual content length: %llu. Bytes most recently read: %d.",
2063 csp->expected_content_length, byte_count, len);
2067 * XXX: should not jump around,
2068 * chat() is complicated enough already.
2072 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2074 timeout.tv_sec = csp->config->socket_timeout;
2075 timeout.tv_usec = 0;
2076 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2080 log_error(LOG_LEVEL_ERROR,
2081 "Didn't receive data in time: %s", http->url);
2082 if ((byte_count == 0) && (http->ssl == 0))
2084 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2086 mark_server_socket_tainted(csp);
2091 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2092 mark_server_socket_tainted(csp);
2097 * This is the body of the browser's request,
2098 * just read and write it.
2100 * XXX: Make sure the client doesn't use pipelining
2101 * behind Privoxy's back.
2103 if (FD_ISSET(csp->cfd, &rfds))
2105 int max_bytes_to_read = sizeof(buf) - 1;
2107 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2108 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2110 if (data_is_available(csp->cfd, 0))
2113 * If the next request is already waiting, we have
2114 * to stop select()ing the client socket. Otherwise
2115 * we would always return right away and get nothing
2118 watch_client_socket = 0;
2119 log_error(LOG_LEVEL_CONNECT,
2120 "Stopping to watch the client socket %d. "
2121 "There's already another request waiting.",
2126 * If the client socket is set, but there's no data
2127 * available on the socket, the client went fishing
2128 * and continuing talking to the server makes no sense.
2130 log_error(LOG_LEVEL_CONNECT,
2131 "The client closed socket %d while "
2132 "the server socket %d is still open.",
2133 csp->cfd, csp->server_connection.sfd);
2134 mark_server_socket_tainted(csp);
2137 if (csp->expected_client_content_length != 0)
2139 if (csp->expected_client_content_length < (sizeof(buf) - 1))
2141 max_bytes_to_read = (int)csp->expected_client_content_length;
2143 log_error(LOG_LEVEL_CONNECT,
2144 "Waiting for up to %d bytes from the client.",
2147 assert(max_bytes_to_read < sizeof(buf));
2148 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2150 len = read_socket(csp->cfd, buf, max_bytes_to_read);
2154 /* XXX: not sure if this is necessary. */
2155 mark_server_socket_tainted(csp);
2156 break; /* "game over, man" */
2159 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2160 if (csp->expected_client_content_length != 0)
2162 assert(len <= max_bytes_to_read);
2163 csp->expected_client_content_length -= (unsigned)len;
2164 log_error(LOG_LEVEL_CONNECT,
2165 "Expected client content length set to %llu "
2166 "after reading %d bytes.",
2167 csp->expected_client_content_length, len);
2168 if (csp->expected_client_content_length == 0)
2170 log_error(LOG_LEVEL_CONNECT,
2171 "Done reading from the client.");
2172 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2175 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2177 if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
2179 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2180 mark_server_socket_tainted(csp);
2187 * The server wants to talk. It could be the header or the body.
2188 * If `hdr' is null, then it's the header otherwise it's the body.
2189 * FIXME: Does `hdr' really mean `host'? No.
2191 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2193 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2195 * If we are buffering content, we don't want to eat up to
2196 * buffer-limit bytes if the client no longer cares about them.
2197 * If we aren't buffering, however, a dead client socket will be
2198 * noticed pretty much right away anyway, so we can reduce the
2199 * overhead by skipping the check.
2201 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2204 log_error(LOG_LEVEL_CONNECT,
2205 "The server still wants to talk, but the client may already have hung up on us.");
2207 log_error(LOG_LEVEL_CONNECT,
2208 "The server still wants to talk, but the client hung up on us.");
2209 mark_server_socket_tainted(csp);
2211 #endif /* def _WIN32 */
2213 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2215 len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
2219 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2221 if (http->ssl && (fwd->forward_host == NULL))
2224 * Just hang up. We already confirmed the client's CONNECT
2225 * request with status code 200 and unencrypted content is
2226 * no longer welcome.
2228 log_error(LOG_LEVEL_ERROR,
2229 "CONNECT already confirmed. Unable to tell the client about the problem.");
2232 else if (byte_count)
2235 * Just hang up. We already transmitted the original headers
2236 * and parts of the original content and therefore missed the
2237 * chance to send an error message (without risking data corruption).
2239 * XXX: we could retry with a fancy range request here.
2241 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2242 "Unable to tell the client about the problem.");
2243 mark_server_socket_tainted(csp);
2247 * XXX: Consider handling the cases above the same.
2249 mark_server_socket_tainted(csp);
2253 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2254 if (csp->flags & CSP_FLAG_CHUNKED)
2256 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2258 /* XXX: this is a temporary hack */
2259 log_error(LOG_LEVEL_CONNECT,
2260 "Looks like we reached the end of the last chunk. "
2261 "We better stop reading.");
2262 csp->expected_content_length = byte_count + (unsigned long long)len;
2263 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2267 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2270 * Add a trailing zero to let be able to use string operations.
2271 * XXX: do we still need this with filter_popups gone?
2276 * Normally, this would indicate that we've read
2277 * as much as the server has sent us and we can
2278 * close the client connection. However, Microsoft
2279 * in its wisdom has released IIS/5 with a bug that
2280 * prevents it from sending the trailing \r\n in
2281 * a 302 redirect header (and possibly other headers).
2282 * To work around this if we've haven't parsed
2283 * a full header we'll append a trailing \r\n
2284 * and see if this now generates a valid one.
2286 * This hack shouldn't have any impacts. If we've
2287 * already transmitted the header or if this is a
2288 * SSL connection, then we won't bother with this
2289 * hack. So we only work on partially received
2290 * headers. If we append a \r\n and this still
2291 * doesn't generate a valid header, then we won't
2292 * transmit anything to the client.
2297 if (server_body || http->ssl)
2300 * If we have been buffering up the document,
2301 * now is the time to apply content modification
2302 * and send the result to the client.
2304 if (buffer_and_filter_content)
2306 p = execute_content_filters(csp);
2308 * If content filtering fails, use the original
2309 * buffer and length.
2310 * (see p != NULL ? p : csp->iob->cur below)
2314 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2316 #ifdef FEATURE_COMPRESSION
2317 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2318 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2320 char *compressed_content = compress_buffer(p,
2321 (size_t *)&csp->content_length, csp->config->compression_level);
2322 if (compressed_content != NULL)
2325 p = compressed_content;
2326 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2331 if (JB_ERR_OK != update_server_headers(csp))
2333 log_error(LOG_LEVEL_FATAL,
2334 "Failed to update server headers. after filtering.");
2337 hdr = list_to_text(csp->headers);
2340 /* FIXME Should handle error properly */
2341 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2344 if (write_socket(csp->cfd, hdr, strlen(hdr))
2345 || write_socket(csp->cfd,
2346 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2348 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2351 mark_server_socket_tainted(csp);
2359 break; /* "game over, man" */
2363 * This is NOT the body, so
2364 * Let's pretend the server just sent us a blank line.
2366 snprintf(buf, sizeof(buf), "\r\n");
2367 len = (int)strlen(buf);
2370 * Now, let the normal header parsing algorithm below do its
2371 * job. If it fails, we'll exit instead of continuing.
2378 * If this is an SSL connection or we're in the body
2379 * of the server document, just write it to the client,
2380 * unless we need to buffer the body for later content-filtering
2382 if (server_body || http->ssl)
2384 if (buffer_and_filter_content)
2387 * If there is no memory left for buffering the content, or the buffer limit
2388 * has been reached, switch to non-filtering mode, i.e. make & write the
2389 * header, flush the iob and buf, and get out of the way.
2391 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2396 log_error(LOG_LEVEL_INFO,
2397 "Flushing header and buffers. Stepping back from filtering.");
2399 hdr = list_to_text(csp->headers);
2403 * Memory is too tight to even generate the header.
2404 * Send our static "Out-of-memory" page.
2406 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2407 rsp = cgi_error_memory();
2408 send_crunch_response(csp, rsp);
2409 mark_server_socket_tainted(csp);
2412 hdrlen = strlen(hdr);
2414 if (write_socket(csp->cfd, hdr, hdrlen)
2415 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2416 || (write_socket(csp->cfd, buf, (size_t)len)))
2418 log_error(LOG_LEVEL_CONNECT,
2419 "Flush header and buffers to client failed: %E");
2421 mark_server_socket_tainted(csp);
2426 * Reset the byte_count to the amount of bytes
2427 * we just flushed. len will be added a few lines below,
2428 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2430 byte_count = (unsigned long long)flushed;
2432 buffer_and_filter_content = 0;
2438 if (write_socket(csp->cfd, buf, (size_t)len))
2440 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2441 mark_server_socket_tainted(csp);
2445 byte_count += (unsigned long long)len;
2451 * We're still looking for the end of the server's header.
2452 * Buffer up the data we just read. If that fails, there's
2453 * little we can do but send our static out-of-memory page.
2455 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2457 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2458 rsp = cgi_error_memory();
2459 send_crunch_response(csp, rsp);
2460 mark_server_socket_tainted(csp);
2464 /* Convert iob into something sed() can digest */
2465 if (JB_ERR_PARSE == get_server_headers(csp))
2470 * Well, we tried our MS IIS/5 hack and it didn't work.
2471 * The header is incomplete and there isn't anything
2472 * we can do about it.
2474 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2475 "Applying the MS IIS5 hack didn't help.");
2476 log_error(LOG_LEVEL_CLF,
2477 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2478 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2479 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2480 mark_server_socket_tainted(csp);
2486 * Since we have to wait for more from the server before
2487 * we can parse the headers we just continue here.
2489 log_error(LOG_LEVEL_CONNECT,
2490 "Continuing buffering server headers from socket %d. "
2491 "Bytes most recently read: %d.", csp->cfd, len);
2498 * Account for the content bytes we
2499 * might have gotten with the headers.
2501 assert(csp->iob->eod >= csp->iob->cur);
2502 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2505 /* Did we actually get anything? */
2506 if (NULL == csp->headers->first)
2508 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2510 log_error(LOG_LEVEL_ERROR,
2511 "No server or forwarder response received on socket %d. "
2512 "Closing client socket %d without sending data.",
2513 csp->server_connection.sfd, csp->cfd);
2514 log_error(LOG_LEVEL_CLF,
2515 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2519 log_error(LOG_LEVEL_ERROR,
2520 "No server or forwarder response received on socket %d.",
2521 csp->server_connection.sfd);
2522 send_crunch_response(csp, error_response(csp, "no-server-data"));
2524 free_http_request(http);
2525 mark_server_socket_tainted(csp);
2529 assert(csp->headers->first->str);
2531 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2532 strncmpic(csp->headers->first->str, "ICY", 3))
2535 * It doesn't look like a HTTP (or Shoutcast) response:
2536 * tell the client and log the problem.
2538 if (strlen(csp->headers->first->str) > 30)
2540 csp->headers->first->str[30] = '\0';
2542 log_error(LOG_LEVEL_ERROR,
2543 "Invalid server or forwarder response. Starts with: %s",
2544 csp->headers->first->str);
2545 log_error(LOG_LEVEL_CLF,
2546 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2547 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2548 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2549 free_http_request(http);
2550 mark_server_socket_tainted(csp);
2555 * We have now received the entire server header,
2556 * filter it and send the result to the client
2558 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2560 log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2562 hdr = list_to_text(csp->headers);
2565 /* FIXME Should handle error properly */
2566 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2569 if ((csp->flags & CSP_FLAG_CHUNKED)
2570 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2571 && ((csp->iob->eod - csp->iob->cur) >= 5)
2572 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2574 log_error(LOG_LEVEL_CONNECT,
2575 "Looks like we got the last chunk together with "
2576 "the server headers. We better stop reading.");
2577 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2578 csp->expected_content_length = byte_count;
2579 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2582 csp->server_connection.response_received = time(NULL);
2584 if (crunch_response_triggered(csp, crunchers_light))
2587 * One of the tags created by a server-header
2588 * tagger triggered a crunch. We already
2589 * delivered the crunch response to the client
2590 * and are done here after cleaning up.
2593 mark_server_socket_tainted(csp);
2596 /* Buffer and pcrs filter this if appropriate. */
2598 if (!http->ssl) /* We talk plaintext */
2600 buffer_and_filter_content = content_requires_filtering(csp);
2603 * Only write if we're not buffering for content modification
2605 if (!buffer_and_filter_content)
2608 * Write the server's (modified) header to
2609 * the client (along with anything else that
2610 * may be in the buffer)
2613 if (write_socket(csp->cfd, hdr, strlen(hdr))
2614 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2616 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2619 * The write failed, so don't bother mentioning it
2620 * to the client... it probably can't hear us anyway.
2623 mark_server_socket_tainted(csp);
2628 /* we're finished with the server's header */
2634 * If this was a MS IIS/5 hack then it means the server
2635 * has already closed the connection. Nothing more to read.
2640 log_error(LOG_LEVEL_ERROR,
2641 "Closed server connection detected. "
2642 "Applying the MS IIS5 hack didn't help.");
2643 log_error(LOG_LEVEL_CLF,
2644 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2645 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2646 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2647 mark_server_socket_tainted(csp);
2653 mark_server_socket_tainted(csp);
2654 return; /* huh? we should never get here */
2657 if (csp->content_length == 0)
2660 * If Privoxy didn't recalculate the Content-Length,
2661 * byte_count is still correct.
2663 csp->content_length = byte_count;
2666 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2667 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2668 && (csp->expected_content_length != byte_count))
2670 log_error(LOG_LEVEL_CONNECT,
2671 "Received %llu bytes while expecting %llu.",
2672 byte_count, csp->expected_content_length);
2673 mark_server_socket_tainted(csp);
2677 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2678 csp->ip_addr_str, http->ocmd, csp->content_length);
2680 csp->server_connection.timestamp = time(NULL);
2684 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2685 /*********************************************************************
2687 * Function : prepare_csp_for_next_request
2689 * Description : Put the csp in a mostly vergin state.
2692 * 1 : csp = Current client state (buffers, headers, etc...)
2696 *********************************************************************/
2697 static void prepare_csp_for_next_request(struct client_state *csp)
2699 unsigned int toggled_on_flag_set = (0 != (csp->flags & CSP_FLAG_TOGGLED_ON));
2701 csp->content_type = 0;
2702 csp->content_length = 0;
2703 csp->expected_content_length = 0;
2704 csp->expected_client_content_length = 0;
2705 list_remove_all(csp->headers);
2706 clear_iob(csp->iob);
2707 freez(csp->error_message);
2708 free_http_request(csp->http);
2709 destroy_list(csp->headers);
2710 destroy_list(csp->tags);
2711 free_current_action(csp->action);
2712 if (NULL != csp->fwd)
2714 unload_forward_spec(csp->fwd);
2717 /* XXX: Store per-connection flags someplace else. */
2718 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
2719 if (toggled_on_flag_set)
2721 csp->flags |= CSP_FLAG_TOGGLED_ON;
2724 if (csp->client_iob->eod > csp->client_iob->cur)
2726 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
2727 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2729 assert(bytes_to_shift > 0);
2730 assert(data_length > 0);
2732 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
2733 data_length, bytes_to_shift);
2734 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
2735 csp->client_iob->cur = csp->client_iob->buf;
2736 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
2737 csp->client_iob->eod = csp->client_iob->buf + data_length;
2738 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
2740 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
2745 * We mainly care about resetting client_iob->cur so we don't
2746 * waste buffer space at the beginning and don't mess up the
2747 * request restoration done by cgi_show_request().
2749 * Freeing the buffer itself isn't technically necessary,
2750 * but makes debugging more convenient.
2752 clear_iob(csp->client_iob);
2755 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2758 /*********************************************************************
2762 * Description : This is little more than chat. We only "serve" to
2763 * to close (or remember) any socket that chat may have
2767 * 1 : csp = Current client state (buffers, headers, etc...)
2771 *********************************************************************/
2773 void serve(struct client_state *csp)
2774 #else /* ifndef AMIGA */
2775 static void serve(struct client_state *csp)
2776 #endif /* def AMIGA */
2778 int config_file_change_detected = 0; /* Only used for debugging */
2779 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2780 #ifdef FEATURE_CONNECTION_SHARING
2781 static int monitor_thread_running = 0;
2782 #endif /* def FEATURE_CONNECTION_SHARING */
2783 int continue_chatting = 0;
2785 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
2786 csp->ip_addr_str, csp->cfd);
2790 unsigned int latency;
2795 * If the request has been crunched,
2796 * the calculated latency is zero.
2798 latency = (unsigned)(csp->server_connection.response_received -
2799 csp->server_connection.request_sent) / 2;
2801 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2802 && (csp->flags & CSP_FLAG_CRUNCHED)
2803 && (csp->expected_client_content_length != 0))
2805 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
2806 log_error(LOG_LEVEL_CONNECT,
2807 "Tainting client socket %d due to unread data.", csp->cfd);
2810 continue_chatting = (csp->config->feature_flags
2811 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2812 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2813 && (csp->cfd != JB_INVALID_SOCKET)
2814 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2815 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
2816 || (csp->flags & CSP_FLAG_CHUNKED));
2818 if (!(csp->flags & CSP_FLAG_CRUNCHED)
2819 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
2821 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
2823 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
2825 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2826 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2827 || !socket_is_still_alive(csp->server_connection.sfd)
2828 || !(latency < csp->server_connection.keep_alive_timeout))
2830 log_error(LOG_LEVEL_CONNECT,
2831 "Closing server socket %d connected to %s. "
2832 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
2833 csp->server_connection.sfd, csp->server_connection.host,
2834 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2835 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2836 socket_is_still_alive(csp->server_connection.sfd),
2837 csp->server_connection.keep_alive_timeout);
2838 #ifdef FEATURE_CONNECTION_SHARING
2839 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2841 forget_connection(csp->server_connection.sfd);
2843 #endif /* def FEATURE_CONNECTION_SHARING */
2844 close_socket(csp->server_connection.sfd);
2845 mark_connection_closed(&csp->server_connection);
2849 if (continue_chatting && any_loaded_file_changed(csp))
2851 continue_chatting = 0;
2852 config_file_change_detected = 1;
2855 if (continue_chatting)
2857 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
2858 && socket_is_still_alive(csp->cfd))
2860 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
2861 "pipelined on socket %d and the socket is still alive.",
2862 csp->requests_received_total+1, csp->cfd);
2863 prepare_csp_for_next_request(csp);
2867 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
2869 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2871 log_error(LOG_LEVEL_CONNECT,
2872 "Waiting for the next client request on socket %d. "
2873 "Keeping the server socket %d to %s open.",
2874 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2878 log_error(LOG_LEVEL_CONNECT,
2879 "Waiting for the next client request on socket %d. "
2880 "No server socket to keep open.", csp->cfd);
2884 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2885 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
2886 && socket_is_still_alive(csp->cfd))
2888 log_error(LOG_LEVEL_CONNECT,
2889 "Client request %u arrived in time on socket %d.",
2890 csp->requests_received_total+1, csp->cfd);
2891 prepare_csp_for_next_request(csp);
2895 #ifdef FEATURE_CONNECTION_SHARING
2896 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2897 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
2898 && (socket_is_still_alive(csp->server_connection.sfd)))
2900 time_t time_open = time(NULL) - csp->server_connection.timestamp;
2902 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
2907 remember_connection(&csp->server_connection);
2908 csp->server_connection.sfd = JB_INVALID_SOCKET;
2909 drain_and_close_socket(csp->cfd);
2910 csp->cfd = JB_INVALID_SOCKET;
2911 privoxy_mutex_lock(&connection_reuse_mutex);
2912 if (!monitor_thread_running)
2914 monitor_thread_running = 1;
2915 privoxy_mutex_unlock(&connection_reuse_mutex);
2916 wait_for_alive_connections();
2917 privoxy_mutex_lock(&connection_reuse_mutex);
2918 monitor_thread_running = 0;
2920 privoxy_mutex_unlock(&connection_reuse_mutex);
2922 #endif /* def FEATURE_CONNECTION_SHARING */
2926 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2928 log_error(LOG_LEVEL_CONNECT,
2929 "Closing server socket %d connected to %s. Keep-alive: %u. "
2930 "Tainted: %u. Socket alive: %u. Timeout: %u. "
2931 "Configuration file change detected: %u",
2932 csp->server_connection.sfd, csp->server_connection.host,
2933 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2934 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2935 socket_is_still_alive(csp->server_connection.sfd),
2936 csp->server_connection.keep_alive_timeout,
2937 config_file_change_detected);
2939 } while (continue_chatting);
2943 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2945 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2947 #ifdef FEATURE_CONNECTION_SHARING
2948 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2950 forget_connection(csp->server_connection.sfd);
2952 #endif /* def FEATURE_CONNECTION_SHARING */
2953 close_socket(csp->server_connection.sfd);
2956 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2957 mark_connection_closed(&csp->server_connection);
2960 if (csp->cfd != JB_INVALID_SOCKET)
2962 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
2963 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
2964 "Configuration file change detected: %u. Requests received: %u.",
2965 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
2966 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
2967 config_file_change_detected, csp->requests_received_total);
2968 drain_and_close_socket(csp->cfd);
2971 csp->flags &= ~CSP_FLAG_ACTIVE;
2977 /*********************************************************************
2979 * Function : server_thread
2981 * Description : We only exist to call `serve' in a threaded environment.
2984 * 1 : data = Current client state (buffers, headers, etc...)
2986 * Returns : Always 0.
2988 *********************************************************************/
2989 static int32 server_thread(void *data)
2991 serve((struct client_state *) data);
2998 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2999 /*********************************************************************
3003 * Description : Print usage info & exit.
3005 * Parameters : Pointer to argv[0] for identifying ourselves
3009 *********************************************************************/
3010 static void usage(const char *myname)
3012 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3013 "Usage: %s [--config-test] "
3016 #endif /* defined(unix) */
3019 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3020 #endif /* defined(unix) */
3021 "[--version] [configfile]\n"
3022 "Aborting\n", myname);
3027 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3030 #ifdef MUTEX_LOCKS_AVAILABLE
3031 /*********************************************************************
3033 * Function : privoxy_mutex_lock
3035 * Description : Locks a mutex.
3038 * 1 : mutex = The mutex to lock.
3040 * Returns : Void. May exit in case of errors.
3042 *********************************************************************/
3043 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3045 #ifdef FEATURE_PTHREAD
3046 int err = pthread_mutex_lock(mutex);
3049 if (mutex != &log_mutex)
3051 log_error(LOG_LEVEL_FATAL,
3052 "Mutex locking failed: %s.\n", strerror(err));
3057 EnterCriticalSection(mutex);
3058 #endif /* def FEATURE_PTHREAD */
3062 /*********************************************************************
3064 * Function : privoxy_mutex_unlock
3066 * Description : Unlocks a mutex.
3069 * 1 : mutex = The mutex to unlock.
3071 * Returns : Void. May exit in case of errors.
3073 *********************************************************************/
3074 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3076 #ifdef FEATURE_PTHREAD
3077 int err = pthread_mutex_unlock(mutex);
3080 if (mutex != &log_mutex)
3082 log_error(LOG_LEVEL_FATAL,
3083 "Mutex unlocking failed: %s.\n", strerror(err));
3088 LeaveCriticalSection(mutex);
3089 #endif /* def FEATURE_PTHREAD */
3093 /*********************************************************************
3095 * Function : privoxy_mutex_init
3097 * Description : Prepares a mutex.
3100 * 1 : mutex = The mutex to initialize.
3102 * Returns : Void. May exit in case of errors.
3104 *********************************************************************/
3105 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3107 #ifdef FEATURE_PTHREAD
3108 int err = pthread_mutex_init(mutex, 0);
3111 printf("Fatal error. Mutex initialization failed: %s.\n",
3116 InitializeCriticalSection(mutex);
3117 #endif /* def FEATURE_PTHREAD */
3119 #endif /* def MUTEX_LOCKS_AVAILABLE */
3121 /*********************************************************************
3123 * Function : initialize_mutexes
3125 * Description : Prepares mutexes if mutex support is available.
3129 * Returns : Void, exits in case of errors.
3131 *********************************************************************/
3132 static void initialize_mutexes(void)
3134 #ifdef MUTEX_LOCKS_AVAILABLE
3136 * Prepare global mutex semaphores
3138 privoxy_mutex_init(&log_mutex);
3139 privoxy_mutex_init(&log_init_mutex);
3140 privoxy_mutex_init(&connection_reuse_mutex);
3141 #ifdef FEATURE_EXTERNAL_FILTERS
3142 privoxy_mutex_init(&external_filter_mutex);
3146 * XXX: The assumptions below are a bit naive
3147 * and can cause locks that aren't necessary.
3149 * For example older FreeBSD versions (< 6.x?)
3150 * have no gethostbyname_r, but gethostbyname is
3153 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3154 privoxy_mutex_init(&resolver_mutex);
3155 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3157 * XXX: should we use a single mutex for
3158 * localtime() and gmtime() as well?
3160 #ifndef HAVE_GMTIME_R
3161 privoxy_mutex_init(&gmtime_mutex);
3162 #endif /* ndef HAVE_GMTIME_R */
3164 #ifndef HAVE_LOCALTIME_R
3165 privoxy_mutex_init(&localtime_mutex);
3166 #endif /* ndef HAVE_GMTIME_R */
3169 privoxy_mutex_init(&rand_mutex);
3170 #endif /* ndef HAVE_RANDOM */
3172 #endif /* def MUTEX_LOCKS_AVAILABLE */
3176 /*********************************************************************
3180 * Description : Load the config file and start the listen loop.
3181 * This function is a lot more *sane* with the `load_config'
3182 * and `listen_loop' functions; although it stills does
3183 * a *little* too much for my taste.
3186 * 1 : argc = Number of parameters (including $0).
3187 * 2 : argv = Array of (char *)'s to the parameters.
3189 * Returns : 1 if : can't open config file, unrecognized directive,
3190 * stats requested in multi-thread mode, can't open the
3191 * log file, can't open the jar file, listen port is invalid,
3192 * any load fails, and can't bind port.
3194 * Else main never returns, the process must be signaled
3195 * to terminate execution. Or, on Windows, use the
3196 * "File", "Exit" menu option.
3198 *********************************************************************/
3200 int real_main(int argc, char **argv)
3202 int main(int argc, char **argv)
3206 int do_config_test = 0;
3207 unsigned int random_seed;
3209 struct passwd *pw = NULL;
3210 struct group *grp = NULL;
3212 char *pre_chroot_nslookup_to_load_resolver = NULL;
3219 #if !defined(_WIN32)
3226 /* Prepare mutexes if supported and necessary. */
3227 initialize_mutexes();
3229 /* Enable logging until further notice. */
3233 * Parse the command line arguments
3235 * XXX: simply printing usage information in case of
3236 * invalid arguments isn't particularly user friendly.
3238 while (++argc_pos < argc)
3241 /* Check to see if the service must be installed or uninstalled */
3242 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3244 const char *pName = argv[argc_pos] + 9;
3247 exit((install_service(pName)) ? 0 : 1);
3249 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3251 const char *pName = argv[argc_pos] + 11;
3254 exit((uninstall_service(pName)) ? 0 : 1);
3256 else if (strcmp(argv[argc_pos], "--service") == 0)
3258 bRunAsService = TRUE;
3259 w32_set_service_cwd();
3260 atexit(w32_service_exit_notify);
3263 #endif /* defined(_WIN32) */
3266 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3268 if (strcmp(argv[argc_pos], "--help") == 0)
3273 else if (strcmp(argv[argc_pos], "--version") == 0)
3275 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3281 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3283 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3287 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3289 if (++argc_pos == argc) usage(argv[0]);
3290 pidfile = strdup_or_die(argv[argc_pos]);
3293 else if (strcmp(argv[argc_pos], "--user") == 0)
3298 if (++argc_pos == argc) usage(argv[argc_pos]);
3300 user_arg = strdup_or_die(argv[argc_pos]);
3301 group_name = strchr(user_arg, '.');
3302 if (NULL != group_name)
3304 /* Nul-terminate the user name */
3307 /* Skip the former delimiter to actually reach the group name */
3310 grp = getgrnam(group_name);
3313 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3316 pw = getpwnam(user_arg);
3319 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3325 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3327 if (++argc_pos == argc) usage(argv[0]);
3328 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3331 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3335 #endif /* defined(unix) */
3337 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3342 else if (argc_pos + 1 != argc)
3345 * This is neither the last command line
3346 * option, nor was it recognized before,
3347 * therefore it must be invalid.
3353 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3355 configfile = argv[argc_pos];
3358 } /* -END- while (more arguments) */
3360 show_version(Argv[0]);
3363 if (*configfile != '/')
3365 char cwd[BUFFER_SIZE];
3367 size_t abs_file_size;
3369 /* make config-filename absolute here */
3370 if (NULL == getcwd(cwd, sizeof(cwd)))
3372 perror("failed to get current working directory");
3376 basedir = strdup_or_die(cwd);
3378 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3379 abs_file = malloc_or_die(abs_file_size);
3380 strlcpy(abs_file, basedir, abs_file_size);
3381 strlcat(abs_file, "/", abs_file_size);
3382 strlcat(abs_file, configfile, abs_file_size);
3383 configfile = abs_file;
3385 #endif /* defined unix */
3389 clients->next = NULL;
3391 /* XXX: factor out initialising after the next stable release. */
3394 #elif defined(_WIN32)
3398 random_seed = (unsigned int)time(NULL);
3400 srandom(random_seed);
3403 #endif /* ifdef HAVE_RANDOM */
3406 * Unix signal handling
3408 * Catch the abort, interrupt and terminate signals for a graceful exit
3409 * Catch the hangup signal so the errlog can be reopened.
3410 * Ignore the broken pipe signals (FIXME: Why?)
3412 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3415 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3417 for (idx = 0; idx < SZ(catched_signals); idx++)
3419 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3420 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3422 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3423 #endif /* ifdef sun */
3425 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3429 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3431 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3435 #else /* ifdef _WIN32 */
3436 # ifdef _WIN_CONSOLE
3438 * We *are* in a windows console app.
3439 * Print a verbose messages about FAQ's and such
3441 printf("%s", win32_blurb);
3442 # endif /* def _WIN_CONSOLE */
3443 #endif /* def _WIN32 */
3447 exit(NULL == load_config());
3450 /* Initialize the CGI subsystem */
3451 cgi_init_error_messages();
3454 * If runnig on unix and without the --nodaemon
3455 * option, become a daemon. I.e. fork, detach
3456 * from tty and get process group leadership
3465 if (pid < 0) /* error */
3470 else if (pid != 0) /* parent */
3475 * must check for errors
3476 * child died due to missing files aso
3479 wpid = waitpid(pid, &status, WNOHANG);
3491 * stderr (fd 2) will be closed later on,
3492 * when the config file has been parsed.
3498 * Reserve fd 0 and 1 to prevent abort() and friends
3499 * from sending stuff to the clients or servers.
3501 fd = open("/dev/null", O_RDONLY);
3504 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3508 if (dup2(fd, 0) == -1)
3510 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3514 fd = open("/dev/null", O_WRONLY);
3517 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3521 if (dup2(fd, 1) == -1)
3523 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3528 #ifdef FEATURE_EXTERNAL_FILTERS
3529 for (fd = 0; fd < 3; fd++)
3531 mark_socket_for_close_on_execute(fd);
3537 } /* -END- if (daemon_mode) */
3540 * As soon as we have written the PID file, we can switch
3541 * to the user and group ID indicated by the --user option
3547 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3549 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3553 if (setgroups(1, &grp->gr_gid))
3555 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3558 else if (initgroups(pw->pw_name, pw->pw_gid))
3560 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3566 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3568 /* Read the time zone file from /etc before doing chroot. */
3570 if (NULL != pre_chroot_nslookup_to_load_resolver
3571 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3573 /* Initialize resolver library. */
3574 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3576 if (chroot(pw->pw_dir) < 0)
3578 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3582 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3585 if (setuid(pw->pw_uid))
3587 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3591 char putenv_dummy[64];
3593 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3594 if (putenv(putenv_dummy) != 0)
3596 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3599 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3600 if (putenv(putenv_dummy) != 0)
3602 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3608 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3611 #endif /* defined unix */
3614 /* This will be FALSE unless the command line specified --service
3618 /* Yup, so now we must attempt to establish a connection
3619 * with the service dispatcher. This will only work if this
3620 * process was launched by the service control manager to
3621 * actually run as a service. If this isn't the case, i've
3622 * known it take around 30 seconds or so for the call to return.
3625 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3626 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3628 /* Service has run, and at this point is now being stopped, so just return */
3633 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3635 /* An error occurred. Usually it's because --service was wrongly specified
3636 * and we were unable to connect to the Service Control Dispatcher because
3637 * it wasn't expecting us and is therefore not listening.
3639 * For now, just continue below to call the listen_loop function.
3642 #endif /* def _WIN32 */
3652 /*********************************************************************
3654 * Function : bind_port_helper
3656 * Description : Bind the listen port. Handles logging, and aborts
3660 * 1 : haddr = Host address to bind to. Use NULL to bind to
3662 * 2 : hport = Specifies port to bind to.
3664 * Returns : Port that was opened.
3666 *********************************************************************/
3667 static jb_socket bind_port_helper(const char *haddr, int hport)
3672 result = bind_port(haddr, hport, &bfd);
3676 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
3680 log_error(LOG_LEVEL_FATAL,
3681 "can't bind to %s:%d: There may be another Privoxy "
3682 "or some other proxy running on port %d",
3683 bind_address, hport, hport);
3686 log_error(LOG_LEVEL_FATAL,
3687 "can't bind to %s:%d: The hostname is not resolvable",
3688 bind_address, hport);
3691 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3692 bind_address, hport);
3695 /* shouldn't get here */
3696 return JB_INVALID_SOCKET;
3700 if (bfd >= FD_SETSIZE)
3702 log_error(LOG_LEVEL_FATAL,
3703 "Bind socket number too high to use select(): %d >= %d",
3710 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3715 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3723 /*********************************************************************
3725 * Function : bind_ports_helper
3727 * Description : Bind the listen ports. Handles logging, and aborts
3731 * 1 : config = Privoxy configuration. Specifies ports
3733 * 2 : sockets = Preallocated array of opened sockets
3734 * corresponding to specification in config.
3735 * All non-opened sockets will be set to
3736 * JB_INVALID_SOCKET.
3738 * Returns : Nothing. Inspect sockets argument.
3740 *********************************************************************/
3741 static void bind_ports_helper(struct configuration_spec * config,
3742 jb_socket sockets[])
3746 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3748 if (config->hport[i])
3750 sockets[i] = bind_port_helper(config->haddr[i], config->hport[i]);
3754 sockets[i] = JB_INVALID_SOCKET;
3757 config->need_bind = 0;
3761 /*********************************************************************
3763 * Function : close_ports_helper
3765 * Description : Close listenings ports.
3768 * 1 : sockets = Array of opened and non-opened sockets to
3769 * close. All sockets will be set to
3770 * JB_INVALID_SOCKET.
3772 * Returns : Nothing.
3774 *********************************************************************/
3775 static void close_ports_helper(jb_socket sockets[])
3779 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3781 if (JB_INVALID_SOCKET != sockets[i])
3783 close_socket(sockets[i]);
3785 sockets[i] = JB_INVALID_SOCKET;
3791 /* Without this simple workaround we get this compiler warning from _beginthread
3792 * warning C4028: formal parameter 1 different from declaration
3794 void w32_service_listen_loop(void *p)
3798 #endif /* def _WIN32 */
3801 /*********************************************************************
3803 * Function : listen_loop
3805 * Description : bind the listen port and enter a "FOREVER" listening loop.
3811 *********************************************************************/
3812 static void listen_loop(void)
3814 struct client_states *csp_list = NULL;
3815 struct client_state *csp = NULL;
3816 jb_socket bfds[MAX_LISTENING_SOCKETS];
3817 struct configuration_spec *config;
3818 unsigned int active_threads = 0;
3820 config = load_config();
3822 #ifdef FEATURE_CONNECTION_SHARING
3824 * XXX: Should be relocated once it no
3825 * longer needs to emit log messages.
3827 initialize_reusable_connections();
3828 #endif /* def FEATURE_CONNECTION_SHARING */
3830 bind_ports_helper(config, bfds);
3832 #ifdef FEATURE_GRACEFUL_TERMINATION
3833 while (!g_terminate)
3838 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3839 while (waitpid(-1, NULL, WNOHANG) > 0)
3841 /* zombie children */
3843 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3846 * Free data that was used by died threads
3848 active_threads = sweep();
3852 * Re-open the errlog after HUP signal
3854 if (received_hup_signal)
3856 if (NULL != config->logfile)
3858 init_error_log(Argv[0], config->logfile);
3860 received_hup_signal = 0;
3864 csp_list = (struct client_states *)zalloc(sizeof(*csp_list));
3865 if (NULL == csp_list)
3867 log_error(LOG_LEVEL_FATAL,
3868 "malloc(%d) for csp_list failed: %E", sizeof(*csp_list));
3871 csp = &csp_list->csp;
3873 log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
3875 if (!accept_connection(csp, bfds))
3877 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3889 csp->flags |= CSP_FLAG_ACTIVE;
3890 csp->server_connection.sfd = JB_INVALID_SOCKET;
3892 csp->config = config = load_config();
3894 if (config->need_bind)
3897 * Since we were listening to the "old port", we will not see
3898 * a "listen" param change until the next request. So, at
3899 * least 1 more request must be made for us to find the new
3900 * setting. I am simply closing the old socket and binding the
3903 * Which-ever is correct, we will serve 1 more page via the
3904 * old settings. This should probably be a "show-proxy-args"
3905 * request. This should not be a so common of an operation
3906 * that this will hurt people's feelings.
3909 close_ports_helper(bfds);
3911 bind_ports_helper(config, bfds);
3914 #ifdef FEATURE_TOGGLE
3915 if (global_toggle_state)
3916 #endif /* def FEATURE_TOGGLE */
3918 csp->flags |= CSP_FLAG_TOGGLED_ON;
3921 if (run_loader(csp))
3923 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3924 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3928 if (block_acl(NULL,csp))
3930 log_error(LOG_LEVEL_CONNECT,
3931 "Connection from %s on socket %d dropped due to ACL", csp->ip_addr_str, csp->cfd);
3932 close_socket(csp->cfd);
3933 freez(csp->ip_addr_str);
3937 #endif /* def FEATURE_ACL */
3939 if ((0 != config->max_client_connections)
3940 && (active_threads >= config->max_client_connections))
3942 log_error(LOG_LEVEL_CONNECT,
3943 "Rejecting connection from %s. Maximum number of connections reached.",
3945 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3946 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3947 close_socket(csp->cfd);
3948 freez(csp->ip_addr_str);
3953 /* add it to the list of clients */
3954 csp_list->next = clients->next;
3955 clients->next = csp_list;
3957 if (config->multi_threaded)
3961 /* this is a switch () statement in the C preprocessor - ugh */
3962 #undef SELECTED_ONE_OPTION
3964 /* Use Pthreads in preference to native code */
3965 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
3966 #define SELECTED_ONE_OPTION
3968 pthread_t the_thread;
3969 pthread_attr_t attrs;
3971 pthread_attr_init(&attrs);
3972 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
3973 errno = pthread_create(&the_thread, &attrs,
3974 (void * (*)(void *))serve, csp);
3975 child_id = errno ? -1 : 0;
3976 pthread_attr_destroy(&attrs);
3980 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
3981 #define SELECTED_ONE_OPTION
3982 child_id = _beginthread(
3983 (void (*)(void *))serve,
3988 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
3989 #define SELECTED_ONE_OPTION
3990 child_id = _beginthread(
3991 (void(* _Optlink)(void*))serve,
3997 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
3998 #define SELECTED_ONE_OPTION
4000 thread_id tid = spawn_thread
4001 (server_thread, "server", B_NORMAL_PRIORITY, csp);
4003 if ((tid >= 0) && (resume_thread(tid) == B_OK))
4005 child_id = (int) tid;
4014 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
4015 #define SELECTED_ONE_OPTION
4016 csp->cfd = ReleaseSocket(csp->cfd, -1);
4019 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4020 NP_Output, Output(),
4021 NP_CloseOutput, FALSE,
4022 NP_Name, (ULONG)"privoxy child",
4026 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4027 NP_Output, Output(),
4028 NP_CloseOutput, FALSE,
4029 NP_Name, (ULONG)"privoxy child",
4030 NP_StackSize, 200*1024,
4036 ((struct Task *)child_id)->tc_UserData = csp;
4037 Signal((struct Task *)child_id, SIGF_SINGLE);
4042 #if !defined(SELECTED_ONE_OPTION)
4045 /* This block is only needed when using fork().
4046 * When using threads, the server thread was
4047 * created and run by the call to _beginthread().
4049 if (child_id == 0) /* child */
4052 #ifdef FEATURE_TOGGLE
4053 int inherited_toggle_state = global_toggle_state;
4054 #endif /* def FEATURE_TOGGLE */
4059 * If we've been toggled or we've blocked the request, tell Mom
4062 #ifdef FEATURE_TOGGLE
4063 if (inherited_toggle_state != global_toggle_state)
4065 rc |= RC_FLAG_TOGGLED;
4067 #endif /* def FEATURE_TOGGLE */
4069 #ifdef FEATURE_STATISTICS
4070 if (csp->flags & CSP_FLAG_REJECTED)
4072 rc |= RC_FLAG_BLOCKED;
4074 #endif /* ndef FEATURE_STATISTICS */
4078 else if (child_id > 0) /* parent */
4080 /* in a fork()'d environment, the parent's
4081 * copy of the client socket and the CSP
4085 #if !defined(_WIN32) && !defined(__CYGWIN__)
4087 wait(&child_status);
4090 * Evaluate child's return code: If the child has
4091 * - been toggled, toggle ourselves
4092 * - blocked its request, bump up the stats counter
4095 #ifdef FEATURE_TOGGLE
4096 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4098 global_toggle_state = !global_toggle_state;
4100 #endif /* def FEATURE_TOGGLE */
4102 #ifdef FEATURE_STATISTICS
4104 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4108 #endif /* def FEATURE_STATISTICS */
4110 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4111 close_socket(csp->cfd);
4112 csp->flags &= ~CSP_FLAG_ACTIVE;
4116 #undef SELECTED_ONE_OPTION
4117 /* end of cpp switch () */
4122 * Spawning the child failed, assume it's because
4123 * there are too many children running already.
4124 * XXX: If you assume ...
4126 log_error(LOG_LEVEL_ERROR,
4127 "Unable to take any additional connections: %E");
4128 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4129 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4130 close_socket(csp->cfd);
4131 csp->flags &= ~CSP_FLAG_ACTIVE;
4140 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4142 /* Clean up. Aim: free all memory (no leaks) */
4143 #ifdef FEATURE_GRACEFUL_TERMINATION
4145 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4147 unload_current_config_file();
4148 unload_current_actions_file();
4149 unload_current_re_filterfile();
4150 #ifdef FEATURE_TRUST
4151 unload_current_trust_file();
4154 if (config->multi_threaded)
4161 } while ((clients->next != NULL) && (--i > 0));
4165 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4175 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4176 /* Cleanup - remove taskbar icon etc. */
4181 #endif /* FEATURE_GRACEFUL_TERMINATION */