1 const char jcc_rcs[] = "$Id: jcc.c,v 1.439 2016/01/16 12:33:03 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001-2016 the
10 * Privoxy team. http://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 *********************************************************************/
40 #include <sys/types.h>
49 # ifndef FEATURE_PTHREAD
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\r\n";
217 static const char CHEADER[] =
218 "HTTP/1.1 400 Invalid header received from client\r\n"
219 "Content-Type: text/plain\r\n"
220 "Connection: close\r\n\r\n"
221 "Invalid header received from client.\r\n";
223 static const char FTP_RESPONSE[] =
224 "HTTP/1.1 400 Invalid request received from client\r\n"
225 "Content-Type: text/plain\r\n"
226 "Connection: close\r\n\r\n"
227 "Invalid request. Privoxy doesn't support FTP.\r\n";
229 static const char GOPHER_RESPONSE[] =
230 "HTTP/1.1 400 Invalid request received from client\r\n"
231 "Content-Type: text/plain\r\n"
232 "Connection: close\r\n\r\n"
233 "Invalid request. Privoxy doesn't support gopher.\r\n";
235 /* XXX: should be a template */
236 static const char MISSING_DESTINATION_RESPONSE[] =
237 "HTTP/1.1 400 Bad request received from client\r\n"
238 "Content-Type: text/plain\r\n"
239 "Connection: close\r\n\r\n"
240 "Bad request. Privoxy was unable to extract the destination.\r\n";
242 /* XXX: should be a template */
243 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
244 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
245 "Content-Type: text/plain\r\n"
246 "Connection: close\r\n\r\n"
247 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
249 /* XXX: should be a template */
250 static const char MESSED_UP_REQUEST_RESPONSE[] =
251 "HTTP/1.1 400 Malformed request after rewriting\r\n"
252 "Content-Type: text/plain\r\n"
253 "Connection: close\r\n\r\n"
254 "Bad request. Messed up with header filters.\r\n";
256 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
257 "HTTP/1.1 503 Too many open connections\r\n"
258 "Content-Type: text/plain\r\n"
259 "Connection: close\r\n\r\n"
260 "Maximum number of open connections reached.\r\n";
262 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
263 "HTTP/1.1 504 Connection timeout\r\n"
264 "Content-Type: text/plain\r\n"
265 "Connection: close\r\n\r\n"
266 "The connection timed out because the client request didn't arrive in time.\r\n";
268 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
269 "HTTP/1.1 400 Failed reading client body\r\n"
270 "Content-Type: text/plain\r\n"
271 "Connection: close\r\n\r\n"
272 "Failed parsing or buffering the chunk-encoded client body.\r\n";
274 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
275 "HTTP/1.1 417 Expecting too much\r\n"
276 "Content-Type: text/plain\r\n"
277 "Connection: close\r\n\r\n"
278 "Privoxy detected an unsupported Expect header value.\r\n";
280 /* A function to crunch a response */
281 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
283 /* Crunch function flags */
284 #define CF_NO_FLAGS 0
285 /* Cruncher applies to forced requests as well */
286 #define CF_IGNORE_FORCE 1
287 /* Crunched requests are counted for the block statistics */
288 #define CF_COUNT_AS_REJECT 2
290 /* A crunch function and its flags */
293 const crunch_func_ptr cruncher;
297 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
299 /* Complete list of cruncher functions */
300 static const struct cruncher crunchers_all[] = {
301 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
302 { block_url, CF_COUNT_AS_REJECT },
304 { trust_url, CF_COUNT_AS_REJECT },
305 #endif /* def FEATURE_TRUST */
306 { redirect_url, CF_NO_FLAGS },
307 { dispatch_cgi, CF_IGNORE_FORCE},
311 /* Light version, used after tags are applied */
312 static const struct cruncher crunchers_light[] = {
313 { block_url, CF_COUNT_AS_REJECT },
314 { redirect_url, CF_NO_FLAGS },
320 * XXX: Don't we really mean
326 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
327 /*********************************************************************
329 * Function : sig_handler
331 * Description : Signal handler for different signals.
332 * Exit gracefully on TERM and INT
333 * or set a flag that will cause the errlog
334 * to be reopened by the main thread on HUP.
337 * 1 : the_signal = the signal cause this function to call
341 *********************************************************************/
342 static void sig_handler(int the_signal)
348 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
360 received_hup_signal = 1;
366 * We shouldn't be here, unless we catch signals
367 * in main() that we can't handle here!
369 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
377 /*********************************************************************
379 * Function : client_protocol_is_unsupported
381 * Description : Checks if the client used a known unsupported
382 * protocol and deals with it by sending an error
386 * 1 : csp = Current client state (buffers, headers, etc...)
387 * 2 : req = the first request line send by the client
389 * Returns : TRUE if an error response has been generated, or
390 * FALSE if the request doesn't look invalid.
392 *********************************************************************/
393 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
396 * If it's a FTP or gopher request, we don't support it.
398 * These checks are better than nothing, but they might
399 * not work in all configurations and some clients might
400 * have problems digesting the answer.
402 * They should, however, never cause more problems than
403 * Privoxy's old behaviour (returning the misleading HTML
406 * "Could not resolve http://(ftp|gopher)://example.org").
408 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
410 const char *response = NULL;
411 const char *protocol = NULL;
413 if (!strncmpic(req, "GET ftp://", 10))
415 response = FTP_RESPONSE;
420 response = GOPHER_RESPONSE;
423 log_error(LOG_LEVEL_ERROR,
424 "%s tried to use Privoxy as %s proxy: %s",
425 csp->ip_addr_str, protocol, req);
426 log_error(LOG_LEVEL_CLF,
427 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
429 write_socket(csp->cfd, response, strlen(response));
438 /*********************************************************************
440 * Function : client_has_unsupported_expectations
442 * Description : Checks if the client used an unsupported expectation
443 * in which case an error message is delivered.
446 * 1 : csp = Current client state (buffers, headers, etc...)
448 * Returns : TRUE if an error response has been generated, or
449 * FALSE if the request doesn't look invalid.
451 *********************************************************************/
452 static int client_has_unsupported_expectations(const struct client_state *csp)
454 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
456 log_error(LOG_LEVEL_ERROR,
457 "Rejecting request from client %s with unsupported Expect header value",
459 log_error(LOG_LEVEL_CLF,
460 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
461 write_socket(csp->cfd, UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
462 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE));
472 /*********************************************************************
474 * Function : get_request_destination_elsewhere
476 * Description : If the client's request was redirected into
477 * Privoxy without the client's knowledge,
478 * the request line lacks the destination host.
480 * This function tries to get it elsewhere,
481 * provided accept-intercepted-requests is enabled.
483 * "Elsewhere" currently only means "Host: header",
484 * but in the future we may ask the redirecting
485 * packet filter to look the destination up.
487 * If the destination stays unknown, an error
488 * response is send to the client and headers
489 * are freed so that chat() can return directly.
492 * 1 : csp = Current client state (buffers, headers, etc...)
493 * 2 : headers = a header list
495 * Returns : JB_ERR_OK if the destination is now known, or
496 * JB_ERR_PARSE if it isn't.
498 *********************************************************************/
499 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
503 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
505 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
506 " Privoxy isn't configured to accept intercepted requests.",
507 csp->ip_addr_str, csp->http->cmd);
508 /* XXX: Use correct size */
509 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
510 csp->ip_addr_str, csp->http->cmd);
512 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
513 destroy_list(headers);
517 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
519 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
520 /* Split the domain we just got for pattern matching */
521 init_domain_components(csp->http);
528 /* We can't work without destination. Go spread the news.*/
530 req = list_to_text(headers);
532 /* XXX: Use correct size */
533 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
534 csp->ip_addr_str, csp->http->cmd);
535 log_error(LOG_LEVEL_ERROR,
536 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
537 csp->ip_addr_str, csp->http->cmd, req);
540 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
541 destroy_list(headers);
546 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
547 * to get the destination IP address, use it as host directly
548 * or do a reverse DNS lookup first.
553 /*********************************************************************
555 * Function : get_server_headers
557 * Description : Parses server headers in iob and fills them
558 * into csp->headers so that they can later be
562 * 1 : csp = Current client state (buffers, headers, etc...)
564 * Returns : JB_ERR_OK if everything went fine, or
565 * JB_ERR_PARSE if the headers were incomplete.
567 *********************************************************************/
568 static jb_err get_server_headers(struct client_state *csp)
570 int continue_hack_in_da_house = 0;
573 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
578 * continue hack in da house. Ignore the ending of
579 * this head and continue enlisting header lines.
580 * The reason is described below.
582 enlist(csp->headers, "");
583 continue_hack_in_da_house = 0;
586 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
589 * It's a bodyless continue response, don't
590 * stop header parsing after reaching its end.
592 * As a result Privoxy will concatenate the
593 * next response's head and parse and deliver
594 * the headers as if they belonged to one request.
596 * The client will separate them because of the
597 * empty line between them.
599 * XXX: What we're doing here is clearly against
600 * the intended purpose of the continue header,
601 * and under some conditions (HTTP/1.0 client request)
602 * it's a standard violation.
604 * Anyway, "sort of against the spec" is preferable
605 * to "always getting confused by Continue responses"
606 * (Privoxy's behaviour before this hack was added)
608 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
609 continue_hack_in_da_house = 1;
611 else if (*header == '\0')
614 * If the header is empty, but the Continue hack
615 * isn't active, we can assume that we reached the
616 * end of the buffer before we hit the end of the
619 * Inform the caller an let it decide how to handle it.
624 if (JB_ERR_MEMORY == enlist(csp->headers, header))
627 * XXX: Should we quit the request and return a
628 * out of memory error page instead?
630 log_error(LOG_LEVEL_ERROR,
631 "Out of memory while enlisting server headers. %s lost.",
641 /*********************************************************************
643 * Function : crunch_reason
645 * Description : Translates the crunch reason code into a string.
648 * 1 : rsp = a http_response
650 * Returns : A string with the crunch reason or an error description.
652 *********************************************************************/
653 static const char *crunch_reason(const struct http_response *rsp)
655 char * reason = NULL;
660 return "Internal error while searching for crunch reason";
663 switch (rsp->crunch_reason)
666 reason = "Unsupported HTTP feature";
672 reason = "Untrusted";
675 reason = "Redirected";
681 reason = "DNS failure";
683 case FORWARDING_FAILED:
684 reason = "Forwarding failed";
687 reason = "Connection failure";
690 reason = "Out of memory (may mask other reasons)";
692 case CONNECTION_TIMEOUT:
693 reason = "Connection timeout";
696 reason = "No server data received";
699 reason = "No reason recorded";
707 /*********************************************************************
709 * Function : log_applied_actions
711 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
715 * 1 : actions = Current action spec to log
719 *********************************************************************/
720 static void log_applied_actions(const struct current_action_spec *actions)
723 * The conversion to text requires lots of memory allocations so
724 * we only do the conversion if the user is actually interested.
726 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
728 char *actions_as_text = actions_to_line_of_text(actions);
729 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
730 freez(actions_as_text);
735 /*********************************************************************
737 * Function : send_crunch_response
739 * Description : Delivers already prepared response for
740 * intercepted requests, logs the interception
741 * and frees the response.
744 * 1 : csp = Current client state (buffers, headers, etc...)
745 * 1 : rsp = Fully prepared response. Will be freed on exit.
749 *********************************************************************/
750 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
752 const struct http_request *http = csp->http;
756 assert(rsp->head != NULL);
760 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
764 * Extract the status code from the actual head
765 * that will be send to the client. It is the only
766 * way to get it right for all requests, including
767 * the fixed ones for out-of-memory problems.
769 * A head starts like this: 'HTTP/1.1 200...'
773 status_code[0] = rsp->head[9];
774 status_code[1] = rsp->head[10];
775 status_code[2] = rsp->head[11];
776 status_code[3] = '\0';
778 /* Log that the request was crunched and why. */
779 log_applied_actions(csp->action);
780 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
781 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
782 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
784 /* Write the answer to the client */
785 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
786 || write_socket(csp->cfd, rsp->body, rsp->content_length))
788 /* There is nothing we can do about it. */
789 log_error(LOG_LEVEL_ERROR,
790 "Couldn't deliver the error message through client socket %d: %E",
794 /* Clean up and return */
795 if (cgi_error_memory() != rsp)
797 free_http_response(rsp);
803 /*********************************************************************
805 * Function : crunch_response_triggered
807 * Description : Checks if the request has to be crunched,
808 * and delivers the crunch response if necessary.
811 * 1 : csp = Current client state (buffers, headers, etc...)
812 * 2 : crunchers = list of cruncher functions to run
814 * Returns : TRUE if the request was answered with a crunch response
817 *********************************************************************/
818 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
820 struct http_response *rsp = NULL;
821 const struct cruncher *c;
824 * If CGI request crunching is disabled,
825 * check the CGI dispatcher out of order to
826 * prevent unintentional blocks or redirects.
828 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
829 && (NULL != (rsp = dispatch_cgi(csp))))
831 /* Deliver, log and free the interception response. */
832 send_crunch_response(csp, rsp);
833 csp->flags |= CSP_FLAG_CRUNCHED;
837 for (c = crunchers; c->cruncher != NULL; c++)
840 * Check the cruncher if either Privoxy is toggled
841 * on and the request isn't forced, or if the cruncher
842 * applies to forced requests as well.
844 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
845 !(csp->flags & CSP_FLAG_FORCED)) ||
846 (c->flags & CF_IGNORE_FORCE))
848 rsp = c->cruncher(csp);
851 /* Deliver, log and free the interception response. */
852 send_crunch_response(csp, rsp);
853 csp->flags |= CSP_FLAG_CRUNCHED;
854 #ifdef FEATURE_STATISTICS
855 if (c->flags & CF_COUNT_AS_REJECT)
857 csp->flags |= CSP_FLAG_REJECTED;
859 #endif /* def FEATURE_STATISTICS */
870 /*********************************************************************
872 * Function : build_request_line
874 * Description : Builds the HTTP request line.
876 * If a HTTP forwarder is used it expects the whole URL,
877 * web servers only get the path.
880 * 1 : csp = Current client state (buffers, headers, etc...)
881 * 2 : fwd = The forwarding spec used for the request
882 * XXX: Should use http->fwd instead.
883 * 3 : request_line = The old request line which will be replaced.
885 * Returns : Nothing. Terminates in case of memory problems.
887 *********************************************************************/
888 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
890 struct http_request *http = csp->http;
892 assert(http->ssl == 0);
895 * Downgrade http version from 1.1 to 1.0
896 * if +downgrade action applies.
898 if ((csp->action->flags & ACTION_DOWNGRADE)
899 && (!strcmpic(http->ver, "HTTP/1.1")))
902 http->ver = strdup_or_die("HTTP/1.0");
906 * Rebuild the request line.
908 freez(*request_line);
909 *request_line = strdup(http->gpc);
910 string_append(request_line, " ");
912 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
914 string_append(request_line, http->url);
918 string_append(request_line, http->path);
920 string_append(request_line, " ");
921 string_append(request_line, http->ver);
923 if (*request_line == NULL)
925 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
927 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
931 /*********************************************************************
933 * Function : change_request_destination
935 * Description : Parse a (rewritten) request line and regenerate
936 * the http request data.
939 * 1 : csp = Current client state (buffers, headers, etc...)
941 * Returns : Forwards the parse_http_request() return code.
942 * Terminates in case of memory problems.
944 *********************************************************************/
945 static jb_err change_request_destination(struct client_state *csp)
947 struct http_request *http = csp->http;
950 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
951 csp->headers->first->str);
952 free_http_request(http);
953 err = parse_http_request(csp->headers->first->str, http);
954 if (JB_ERR_OK != err)
956 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
957 jb_err_to_string(err));
964 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
965 /*********************************************************************
967 * Function : server_response_is_complete
969 * Description : Determines whether we should stop reading
970 * from the server socket.
973 * 1 : csp = Current client state (buffers, headers, etc...)
974 * 2 : content_length = Length of content received so far.
976 * Returns : TRUE if the response is complete,
979 *********************************************************************/
980 static int server_response_is_complete(struct client_state *csp,
981 unsigned long long content_length)
983 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
985 if (!strcmpic(csp->http->gpc, "HEAD"))
988 * "HEAD" implies no body, we are thus expecting
989 * no content. XXX: incomplete "list" of methods?
991 csp->expected_content_length = 0;
992 content_length_known = TRUE;
993 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
996 if (csp->http->status == 204 || csp->http->status == 304)
999 * Expect no body. XXX: incomplete "list" of status codes?
1001 csp->expected_content_length = 0;
1002 content_length_known = TRUE;
1003 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1006 return (content_length_known && ((0 == csp->expected_content_length)
1007 || (csp->expected_content_length <= content_length)));
1011 #ifdef FEATURE_CONNECTION_SHARING
1012 /*********************************************************************
1014 * Function : wait_for_alive_connections
1016 * Description : Waits for alive connections to timeout.
1022 *********************************************************************/
1023 static void wait_for_alive_connections(void)
1025 int connections_alive = close_unusable_connections();
1027 while (0 < connections_alive)
1029 log_error(LOG_LEVEL_CONNECT,
1030 "Waiting for %d connections to timeout.",
1033 connections_alive = close_unusable_connections();
1036 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1039 #endif /* def FEATURE_CONNECTION_SHARING */
1042 /*********************************************************************
1044 * Function : save_connection_destination
1046 * Description : Remembers a connection for reuse later on.
1049 * 1 : sfd = Open socket to remember.
1050 * 2 : http = The destination for the connection.
1051 * 3 : fwd = The forwarder settings used.
1052 * 3 : server_connection = storage.
1056 *********************************************************************/
1057 void save_connection_destination(jb_socket sfd,
1058 const struct http_request *http,
1059 const struct forward_spec *fwd,
1060 struct reusable_connection *server_connection)
1062 assert(sfd != JB_INVALID_SOCKET);
1063 assert(NULL != http->host);
1065 server_connection->sfd = sfd;
1066 server_connection->host = strdup_or_die(http->host);
1067 server_connection->port = http->port;
1069 assert(NULL != fwd);
1070 assert(server_connection->gateway_host == NULL);
1071 assert(server_connection->gateway_port == 0);
1072 assert(server_connection->forwarder_type == 0);
1073 assert(server_connection->forward_host == NULL);
1074 assert(server_connection->forward_port == 0);
1076 server_connection->forwarder_type = fwd->type;
1077 if (NULL != fwd->gateway_host)
1079 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1083 server_connection->gateway_host = NULL;
1085 server_connection->gateway_port = fwd->gateway_port;
1087 if (NULL != fwd->forward_host)
1089 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1093 server_connection->forward_host = NULL;
1095 server_connection->forward_port = fwd->forward_port;
1099 /*********************************************************************
1101 * Function : verify_request_length
1103 * Description : Checks if we already got the whole client requests
1104 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1107 * Data that doesn't belong to the current request is
1108 * either thrown away to let the client retry on a clean
1109 * socket, or stashed to be dealt with after the current
1110 * request is served.
1113 * 1 : csp = Current client state (buffers, headers, etc...)
1117 *********************************************************************/
1118 static void verify_request_length(struct client_state *csp)
1120 unsigned long long buffered_request_bytes =
1121 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1123 if ((csp->expected_client_content_length != 0)
1124 && (buffered_request_bytes != 0))
1126 if (csp->expected_client_content_length >= buffered_request_bytes)
1128 csp->expected_client_content_length -= buffered_request_bytes;
1129 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1130 "to account for the %llu ones we already got.",
1131 csp->expected_client_content_length, buffered_request_bytes);
1135 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1136 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1137 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1138 "Marking the server socket tainted after throwing %llu bytes away.",
1139 buffered_request_bytes - csp->expected_client_content_length);
1140 csp->expected_client_content_length = 0;
1141 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1144 if (csp->expected_client_content_length == 0)
1146 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1150 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1151 && ((csp->client_iob->cur < csp->client_iob->eod)
1152 || (csp->expected_client_content_length != 0)))
1154 if (strcmpic(csp->http->gpc, "GET")
1155 && strcmpic(csp->http->gpc, "HEAD")
1156 && strcmpic(csp->http->gpc, "TRACE")
1157 && strcmpic(csp->http->gpc, "OPTIONS")
1158 && strcmpic(csp->http->gpc, "DELETE"))
1160 /* XXX: this is an incomplete hack */
1161 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1162 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1166 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1168 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1170 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1171 log_error(LOG_LEVEL_CONNECT,
1172 "Possible pipeline attempt detected. The connection will not "
1173 "be kept alive and we will only serve the first request.");
1174 /* Nuke the pipelined requests from orbit, just to be sure. */
1175 clear_iob(csp->client_iob);
1180 * Keep the pipelined data around for now, we'll deal with
1181 * it once we're done serving the current request.
1183 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1184 assert(csp->client_iob->eod >= csp->client_iob->cur);
1185 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1186 "%d bytes of pipelined data received.",
1187 (int)(csp->client_iob->eod - csp->client_iob->cur));
1193 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1194 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1197 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1200 /*********************************************************************
1202 * Function : mark_server_socket_tainted
1204 * Description : Makes sure we don't reuse a server socket
1205 * (if we didn't read everything the server sent
1206 * us reusing the socket would lead to garbage).
1209 * 1 : csp = Current client state (buffers, headers, etc...)
1213 *********************************************************************/
1214 static void mark_server_socket_tainted(struct client_state *csp)
1217 * For consistency we always mark the server socket
1218 * tainted, however, to reduce the log noise we only
1219 * emit a log message if the server socket could have
1220 * actually been reused.
1222 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1223 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1225 log_error(LOG_LEVEL_CONNECT,
1226 "Marking the server socket %d tainted.",
1227 csp->server_connection.sfd);
1229 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1232 /*********************************************************************
1234 * Function : get_request_line
1236 * Description : Read the client request line.
1239 * 1 : csp = Current client state (buffers, headers, etc...)
1241 * Returns : Pointer to request line or NULL in case of errors.
1243 *********************************************************************/
1244 static char *get_request_line(struct client_state *csp)
1246 char buf[BUFFER_SIZE];
1247 char *request_line = NULL;
1250 memset(buf, 0, sizeof(buf));
1252 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1255 * If there are multiple pipelined requests waiting,
1256 * the flag will be set again once the next request
1259 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1261 request_line = get_header(csp->client_iob);
1262 if ((NULL != request_line) && ('\0' != *request_line))
1264 return request_line;
1268 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1269 "received yet. Continuing reading from %d.", csp->cfd);
1275 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1277 if (socket_is_still_alive(csp->cfd))
1279 log_error(LOG_LEVEL_CONNECT,
1280 "No request line on socket %d received in time. Timeout: %d.",
1281 csp->cfd, csp->config->socket_timeout);
1282 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1283 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1287 log_error(LOG_LEVEL_CONNECT,
1288 "The client side of the connection on socket %d got "
1289 "closed without sending a complete request line.", csp->cfd);
1294 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1296 if (len <= 0) return NULL;
1299 * If there is no memory left for buffering the
1300 * request, there is nothing we can do but hang up
1302 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1307 request_line = get_header(csp->client_iob);
1309 } while ((NULL != request_line) && ('\0' == *request_line));
1311 return request_line;
1317 CHUNK_STATUS_MISSING_DATA,
1318 CHUNK_STATUS_BODY_COMPLETE,
1319 CHUNK_STATUS_PARSE_ERROR
1323 /*********************************************************************
1325 * Function : chunked_body_is_complete
1327 * Description : Figures out whether or not a chunked body is complete.
1329 * Currently it always starts at the beginning of the
1330 * buffer which is somewhat wasteful and prevents Privoxy
1331 * from starting to forward the correctly parsed chunks
1332 * as soon as theoretically possible.
1334 * Should be modified to work with a common buffer,
1335 * and allow the caller to skip already parsed chunks.
1337 * This would allow the function to be used for unbuffered
1338 * response bodies as well.
1341 * 1 : iob = Buffer with the body to check.
1342 * 2 : length = Length of complete body
1344 * Returns : Enum with the result of the check.
1346 *********************************************************************/
1347 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1349 unsigned int chunksize;
1355 * We need at least a single digit, followed by "\r\n",
1356 * followed by an unknown amount of data, followed by "\r\n".
1358 if (p + 5 > iob->eod)
1360 return CHUNK_STATUS_MISSING_DATA;
1362 if (sscanf(p, "%x", &chunksize) != 1)
1364 return CHUNK_STATUS_PARSE_ERROR;
1368 * We want at least a single digit, followed by "\r\n",
1369 * followed by the specified amount of data, followed by "\r\n".
1371 if (p + chunksize + 5 > iob->eod)
1373 return CHUNK_STATUS_MISSING_DATA;
1376 /* Skip chunk-size. */
1377 p = strstr(p, "\r\n");
1380 return CHUNK_STATUS_PARSE_ERROR;
1382 /* Move beyond the chunkdata. */
1385 /* There should be another "\r\n" to skip */
1386 if (memcmp(p, "\r\n", 2))
1388 return CHUNK_STATUS_PARSE_ERROR;
1391 } while (chunksize > 0U);
1393 *length = (size_t)(p - iob->cur);
1394 assert(*length <= (size_t)(iob->eod - iob->cur));
1395 assert(p <= iob->eod);
1397 return CHUNK_STATUS_BODY_COMPLETE;
1402 /*********************************************************************
1404 * Function : receive_chunked_client_request_body
1406 * Description : Read the chunk-encoded client request body.
1407 * Failures are dealt with.
1410 * 1 : csp = Current client state (buffers, headers, etc...)
1412 * Returns : JB_ERR_OK or JB_ERR_PARSE
1414 *********************************************************************/
1415 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1418 enum chunk_status status;
1420 while (CHUNK_STATUS_MISSING_DATA ==
1421 (status = chunked_body_is_complete(csp->client_iob,&body_length)))
1423 char buf[BUFFER_SIZE];
1426 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1428 log_error(LOG_LEVEL_ERROR,
1429 "Timeout while waiting for the client body.");
1432 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1435 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1438 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1443 if (status != CHUNK_STATUS_BODY_COMPLETE)
1445 write_socket(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1446 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE));
1447 log_error(LOG_LEVEL_CLF,
1448 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1449 return JB_ERR_PARSE;
1451 log_error(LOG_LEVEL_CONNECT,
1452 "Chunked client body completely read. Length: %d", body_length);
1453 csp->expected_client_content_length = body_length;
1460 #ifdef FEATURE_FORCE_LOAD
1461 /*********************************************************************
1463 * Function : force_required
1465 * Description : Checks a request line to see if it contains
1466 * the FORCE_PREFIX. If it does, it is removed
1467 * unless enforcing requests has beend disabled.
1470 * 1 : request_line = HTTP request line
1472 * Returns : TRUE if force is required, FALSE otherwise.
1474 *********************************************************************/
1475 static int force_required(const struct client_state *csp, char *request_line)
1479 p = strstr(request_line, "http://");
1483 p += strlen("http://");
1487 /* Intercepted request usually don't specify the protocol. */
1491 /* Go to the beginning of the path */
1496 * If the path is missing the request line is invalid and we
1497 * are done here. The client-visible rejection happens later on.
1502 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1504 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1506 /* XXX: Should clean more carefully */
1507 strclean(request_line, FORCE_PREFIX);
1508 log_error(LOG_LEVEL_FORCE,
1509 "Enforcing request: \"%s\".", request_line);
1513 log_error(LOG_LEVEL_FORCE,
1514 "Ignored force prefix in request: \"%s\".", request_line);
1520 #endif /* def FEATURE_FORCE_LOAD */
1523 /*********************************************************************
1525 * Function : receive_client_request
1527 * Description : Read the client's request (more precisely the
1528 * client headers) and answer it if necessary.
1531 * 1 : csp = Current client state (buffers, headers, etc...)
1533 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1535 *********************************************************************/
1536 static jb_err receive_client_request(struct client_state *csp)
1538 char buf[BUFFER_SIZE];
1541 struct http_request *http;
1545 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1546 struct list header_list;
1547 struct list *headers = &header_list;
1549 /* We don't care if the arriving data is a valid HTTP request or not. */
1550 csp->requests_received_total++;
1554 memset(buf, 0, sizeof(buf));
1556 req = get_request_line(csp);
1559 mark_server_socket_tainted(csp);
1560 return JB_ERR_PARSE;
1562 assert(*req != '\0');
1564 if (client_protocol_is_unsupported(csp, req))
1566 return JB_ERR_PARSE;
1569 #ifdef FEATURE_FORCE_LOAD
1570 if (force_required(csp, req))
1572 csp->flags |= CSP_FLAG_FORCED;
1574 #endif /* def FEATURE_FORCE_LOAD */
1576 err = parse_http_request(req, http);
1578 if (JB_ERR_OK != err)
1580 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1581 /* XXX: Use correct size */
1582 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1583 log_error(LOG_LEVEL_ERROR,
1584 "Couldn't parse request line received from %s: %s",
1585 csp->ip_addr_str, jb_err_to_string(err));
1587 free_http_request(http);
1588 return JB_ERR_PARSE;
1591 /* grab the rest of the client's headers */
1595 p = get_header(csp->client_iob);
1599 /* There are no additional headers to read. */
1606 * We didn't receive a complete header
1607 * line yet, get the rest of it.
1609 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1611 log_error(LOG_LEVEL_ERROR,
1612 "Stopped grabbing the client headers.");
1613 destroy_list(headers);
1614 return JB_ERR_PARSE;
1617 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1620 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1621 destroy_list(headers);
1622 return JB_ERR_PARSE;
1625 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1628 * If there is no memory left for buffering the
1629 * request, there is nothing we can do but hang up
1631 destroy_list(headers);
1632 return JB_ERR_MEMORY;
1637 if (!strncmpic(p, "Transfer-Encoding:", 18))
1640 * XXX: should be called through sed()
1641 * but currently can't.
1643 client_transfer_encoding(csp, &p);
1646 * We were able to read a complete
1647 * header and can finally enlist it.
1654 if (http->host == NULL)
1657 * If we still don't know the request destination,
1658 * the request is invalid or the client uses
1659 * Privoxy without its knowledge.
1661 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1664 * Our attempts to get the request destination
1665 * elsewhere failed or Privoxy is configured
1666 * to only accept proxy requests.
1668 * An error response has already been send
1669 * and we're done here.
1671 return JB_ERR_PARSE;
1676 * Determine the actions for this URL
1678 #ifdef FEATURE_TOGGLE
1679 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1681 /* Most compatible set of actions (i.e. none) */
1682 init_current_action(csp->action);
1685 #endif /* ndef FEATURE_TOGGLE */
1687 get_url_actions(csp, http);
1690 enlist(csp->headers, http->cmd);
1692 /* Append the previously read headers */
1693 err = list_append_list_unique(csp->headers, headers);
1694 destroy_list(headers);
1701 /*********************************************************************
1703 * Function : parse_client_request
1705 * Description : Parses the client's request and decides what to do
1708 * Note that since we're not using select() we could get
1709 * blocked here if a client connected, then didn't say
1713 * 1 : csp = Current client state (buffers, headers, etc...)
1715 * Returns : JB_ERR_OK or JB_ERR_PARSE
1717 *********************************************************************/
1718 static jb_err parse_client_request(struct client_state *csp)
1720 struct http_request *http = csp->http;
1723 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1724 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1725 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1726 && (csp->http->ssl == 0))
1728 /* Assume persistence until further notice */
1729 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1732 if (csp->http->ssl == 0)
1735 * This whole block belongs to chat() but currently
1736 * has to be executed before sed().
1738 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1740 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1742 return JB_ERR_PARSE;
1747 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1749 verify_request_length(csp);
1751 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1753 err = sed(csp, FILTER_CLIENT_HEADERS);
1754 if (JB_ERR_OK != err)
1756 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1758 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1759 csp->ip_addr_str, csp->http->cmd);
1760 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1761 return JB_ERR_PARSE;
1763 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1765 /* Check request line for rewrites. */
1766 if ((NULL == csp->headers->first->str)
1767 || (strcmp(http->cmd, csp->headers->first->str) &&
1768 (JB_ERR_OK != change_request_destination(csp))))
1771 * A header filter broke the request line - bail out.
1773 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1774 /* XXX: Use correct size */
1775 log_error(LOG_LEVEL_CLF,
1776 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1777 log_error(LOG_LEVEL_ERROR,
1778 "Invalid request line after applying header filters.");
1779 free_http_request(http);
1781 return JB_ERR_PARSE;
1784 if (client_has_unsupported_expectations(csp))
1786 return JB_ERR_PARSE;
1794 /*********************************************************************
1798 * Description : Once a connection from the client has been accepted,
1799 * this function is called (via serve()) to handle the
1800 * main business of the communication. This function
1801 * returns after dealing with a single request. It can
1802 * be called multiple times with the same client socket
1803 * if the client is keeping the connection alive.
1805 * The decision whether or not a client connection will
1806 * be kept alive is up to the caller which also must
1807 * close the client socket when done.
1809 * FIXME: chat is nearly thousand lines long.
1813 * 1 : csp = Current client state (buffers, headers, etc...)
1815 * Returns : Nothing.
1817 *********************************************************************/
1818 static void chat(struct client_state *csp)
1820 char buf[BUFFER_SIZE];
1827 int ms_iis5_hack = 0;
1828 unsigned long long byte_count = 0;
1829 const struct forward_spec *fwd;
1830 struct http_request *http;
1831 long len = 0; /* for buffer sizes (and negative error codes) */
1832 int buffer_and_filter_content = 0;
1834 /* Skeleton for HTTP response, if we should intercept the request */
1835 struct http_response *rsp;
1836 struct timeval timeout;
1837 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1838 int watch_client_socket;
1841 memset(buf, 0, sizeof(buf));
1845 if (receive_client_request(csp) != JB_ERR_OK)
1849 if (parse_client_request(csp) != JB_ERR_OK)
1854 /* decide how to route the HTTP request */
1855 fwd = forward_url(csp, http);
1858 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1859 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1864 * build the http request to send to the server
1865 * we have to do one of the following:
1867 * create = use the original HTTP request to create a new
1868 * HTTP request that has either the path component
1869 * without the http://domainspec (w/path) or the
1870 * full orininal URL (w/url)
1871 * Note that the path and/or the HTTP version may
1872 * have been altered by now.
1874 * connect = Open a socket to the host:port of the server
1875 * and short-circuit server and client socket.
1877 * pass = Pass the request unchanged if forwarding a CONNECT
1878 * request to a parent proxy. Note that we'll be sending
1879 * the CFAIL message ourselves if connecting to the parent
1880 * fails, but we won't send a CSUCCEED message if it works,
1881 * since that would result in a double message (ours and the
1882 * parent's). After sending the request to the parent, we simply
1885 * here's the matrix:
1888 * +--------+--------+
1890 * 0 | create | connect|
1892 * Forwarding +--------+--------+
1894 * 1 | create | pass |
1896 * +--------+--------+
1900 if (http->ssl && connect_port_is_forbidden(csp))
1902 const char *acceptable_connect_ports =
1903 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1904 assert(NULL != acceptable_connect_ports);
1905 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1906 "limit-connect{%s} doesn't allow CONNECT requests to %s",
1907 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
1908 csp->action->flags |= ACTION_BLOCK;
1914 freez(csp->headers->first->str);
1915 build_request_line(csp, fwd, &csp->headers->first->str);
1919 * We have a request. Check if one of the crunchers wants it.
1921 if (crunch_response_triggered(csp, crunchers_all))
1924 * Yes. The client got the crunch response and we're done here.
1929 log_applied_actions(csp->action);
1930 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1932 if (fwd->forward_host)
1934 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1935 fwd->forward_host, fwd->forward_port, http->hostport);
1939 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1942 /* here we connect to the server, gateway, or the forwarder */
1944 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1945 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
1946 && socket_is_still_alive(csp->server_connection.sfd)
1947 && connection_destination_matches(&csp->server_connection, http, fwd))
1949 log_error(LOG_LEVEL_CONNECT,
1950 "Reusing server socket %d connected to %s. Total requests: %u.",
1951 csp->server_connection.sfd, csp->server_connection.host,
1952 csp->server_connection.requests_sent_total);
1956 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
1958 #ifdef FEATURE_CONNECTION_SHARING
1959 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1961 remember_connection(&csp->server_connection);
1964 #endif /* def FEATURE_CONNECTION_SHARING */
1966 log_error(LOG_LEVEL_CONNECT,
1967 "Closing server socket %d connected to %s. Total requests: %u.",
1968 csp->server_connection.sfd, csp->server_connection.host,
1969 csp->server_connection.requests_sent_total);
1970 close_socket(csp->server_connection.sfd);
1972 mark_connection_closed(&csp->server_connection);
1974 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1976 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
1978 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
1980 if ((fwd->type != SOCKS_NONE) && (fwd->type != FORWARD_WEBSERVER))
1983 rsp = error_response(csp, "forwarding-failed");
1985 else if (errno == EINVAL)
1987 rsp = error_response(csp, "no-such-domain");
1991 rsp = error_response(csp, "connect-failed");
1994 /* Write the answer to the client */
1997 send_crunch_response(csp, rsp);
2001 * Temporary workaround to prevent already-read client
2002 * bodies from being parsed as new requests. For now we
2003 * err on the safe side and throw all the following
2004 * requests under the bus, even if no client body has been
2005 * buffered. A compliant client will repeat the dropped
2006 * requests on an untainted connection.
2008 * The proper fix is to discard the no longer needed
2009 * client body in the buffer (if there is one) and to
2010 * continue parsing the bytes that follow.
2012 drain_and_close_socket(csp->cfd);
2013 csp->cfd = JB_INVALID_SOCKET;
2017 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2018 save_connection_destination(csp->server_connection.sfd,
2019 http, fwd, &csp->server_connection);
2020 csp->server_connection.keep_alive_timeout =
2021 (unsigned)csp->config->keep_alive_timeout;
2023 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2025 csp->server_connection.requests_sent_total++;
2027 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
2029 /* Client headers have been sent optimistically */
2030 assert(csp->headers->last == NULL);
2032 else if (fwd->forward_host || (http->ssl == 0))
2035 hdr = list_to_text(csp->headers);
2038 /* FIXME Should handle error properly */
2039 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2041 list_remove_all(csp->headers);
2044 * Write the client's (modified) header to the server
2045 * (along with anything else that may be in the buffer)
2047 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2052 log_error(LOG_LEVEL_CONNECT,
2053 "Failed sending request headers to: %s: %E", http->hostport);
2055 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2056 && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
2059 log_error(LOG_LEVEL_CONNECT,
2060 "Failed sending request body to: %s: %E", http->hostport);
2065 rsp = error_response(csp, "connect-failed");
2068 send_crunch_response(csp, rsp);
2076 * We're running an SSL tunnel and we're not forwarding,
2077 * so just ditch the client headers, send the "connect succeeded"
2078 * message to the client, flush the rest, and get out of the way.
2080 list_remove_all(csp->headers);
2081 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
2085 clear_iob(csp->client_iob);
2088 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
2090 /* XXX: should the time start earlier for optimistically sent data? */
2091 csp->server_connection.request_sent = time(NULL);
2093 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2094 csp->cfd : csp->server_connection.sfd;
2096 /* pass data between the client and server
2097 * until one or the other shuts down the connection.
2102 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2103 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2110 * FD_ZERO here seems to point to an errant macro which crashes.
2111 * So do this by hand for now...
2113 memset(&rfds,0x00,sizeof(fd_set));
2117 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2118 if (!watch_client_socket)
2120 maxfd = csp->server_connection.sfd;
2123 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2125 FD_SET(csp->cfd, &rfds);
2128 FD_SET(csp->server_connection.sfd, &rfds);
2130 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2131 if ((csp->flags & CSP_FLAG_CHUNKED)
2132 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2133 && ((csp->iob->eod - csp->iob->cur) >= 5)
2134 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2137 * XXX: This check should be obsolete now,
2138 * but let's wait a while to be sure.
2140 log_error(LOG_LEVEL_CONNECT,
2141 "Looks like we got the last chunk together with "
2142 "the server headers but didn't detect it earlier. "
2143 "We better stop reading.");
2144 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2145 csp->expected_content_length = byte_count;
2146 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2148 if (server_body && server_response_is_complete(csp, byte_count))
2150 if (csp->expected_content_length == byte_count)
2152 log_error(LOG_LEVEL_CONNECT,
2153 "Done reading from server. Content length: %llu as expected. "
2154 "Bytes most recently read: %d.",
2159 log_error(LOG_LEVEL_CONNECT,
2160 "Done reading from server. Expected content length: %llu. "
2161 "Actual content length: %llu. Bytes most recently read: %d.",
2162 csp->expected_content_length, byte_count, len);
2166 * XXX: should not jump around,
2167 * chat() is complicated enough already.
2171 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2173 timeout.tv_sec = csp->config->socket_timeout;
2174 timeout.tv_usec = 0;
2175 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2179 log_error(LOG_LEVEL_ERROR,
2180 "Didn't receive data in time: %s", http->url);
2181 if ((byte_count == 0) && (http->ssl == 0))
2183 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2185 mark_server_socket_tainted(csp);
2190 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2191 mark_server_socket_tainted(csp);
2196 * This is the body of the browser's request,
2197 * just read and write it.
2199 * XXX: Make sure the client doesn't use pipelining
2200 * behind Privoxy's back.
2202 if (FD_ISSET(csp->cfd, &rfds))
2204 int max_bytes_to_read = sizeof(buf) - 1;
2206 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2207 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2209 if (data_is_available(csp->cfd, 0))
2212 * If the next request is already waiting, we have
2213 * to stop select()ing the client socket. Otherwise
2214 * we would always return right away and get nothing
2217 watch_client_socket = 0;
2218 log_error(LOG_LEVEL_CONNECT,
2219 "Stopping to watch the client socket %d. "
2220 "There's already another request waiting.",
2225 * If the client socket is set, but there's no data
2226 * available on the socket, the client went fishing
2227 * and continuing talking to the server makes no sense.
2229 log_error(LOG_LEVEL_CONNECT,
2230 "The client closed socket %d while "
2231 "the server socket %d is still open.",
2232 csp->cfd, csp->server_connection.sfd);
2233 mark_server_socket_tainted(csp);
2236 if (csp->expected_client_content_length != 0)
2238 if (csp->expected_client_content_length < (sizeof(buf) - 1))
2240 max_bytes_to_read = (int)csp->expected_client_content_length;
2242 log_error(LOG_LEVEL_CONNECT,
2243 "Waiting for up to %d bytes from the client.",
2246 assert(max_bytes_to_read < sizeof(buf));
2247 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2249 len = read_socket(csp->cfd, buf, max_bytes_to_read);
2253 /* XXX: not sure if this is necessary. */
2254 mark_server_socket_tainted(csp);
2255 break; /* "game over, man" */
2258 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2259 if (csp->expected_client_content_length != 0)
2261 assert(len <= max_bytes_to_read);
2262 csp->expected_client_content_length -= (unsigned)len;
2263 log_error(LOG_LEVEL_CONNECT,
2264 "Expected client content length set to %llu "
2265 "after reading %d bytes.",
2266 csp->expected_client_content_length, len);
2267 if (csp->expected_client_content_length == 0)
2269 log_error(LOG_LEVEL_CONNECT,
2270 "Done reading from the client.");
2271 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2274 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2276 if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
2278 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2279 mark_server_socket_tainted(csp);
2286 * The server wants to talk. It could be the header or the body.
2287 * If `hdr' is null, then it's the header otherwise it's the body.
2288 * FIXME: Does `hdr' really mean `host'? No.
2290 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2292 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2294 * If we are buffering content, we don't want to eat up to
2295 * buffer-limit bytes if the client no longer cares about them.
2296 * If we aren't buffering, however, a dead client socket will be
2297 * noticed pretty much right away anyway, so we can reduce the
2298 * overhead by skipping the check.
2300 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2303 log_error(LOG_LEVEL_CONNECT,
2304 "The server still wants to talk, but the client may already have hung up on us.");
2306 log_error(LOG_LEVEL_CONNECT,
2307 "The server still wants to talk, but the client hung up on us.");
2308 mark_server_socket_tainted(csp);
2310 #endif /* def _WIN32 */
2312 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2314 len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
2318 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2320 if (http->ssl && (fwd->forward_host == NULL))
2323 * Just hang up. We already confirmed the client's CONNECT
2324 * request with status code 200 and unencrypted content is
2325 * no longer welcome.
2327 log_error(LOG_LEVEL_ERROR,
2328 "CONNECT already confirmed. Unable to tell the client about the problem.");
2331 else if (byte_count)
2334 * Just hang up. We already transmitted the original headers
2335 * and parts of the original content and therefore missed the
2336 * chance to send an error message (without risking data corruption).
2338 * XXX: we could retry with a fancy range request here.
2340 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2341 "Unable to tell the client about the problem.");
2342 mark_server_socket_tainted(csp);
2346 * XXX: Consider handling the cases above the same.
2348 mark_server_socket_tainted(csp);
2352 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2353 if (csp->flags & CSP_FLAG_CHUNKED)
2355 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2357 /* XXX: this is a temporary hack */
2358 log_error(LOG_LEVEL_CONNECT,
2359 "Looks like we reached the end of the last chunk. "
2360 "We better stop reading.");
2361 csp->expected_content_length = byte_count + (unsigned long long)len;
2362 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2366 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2369 * Add a trailing zero to let be able to use string operations.
2370 * XXX: do we still need this with filter_popups gone?
2375 * Normally, this would indicate that we've read
2376 * as much as the server has sent us and we can
2377 * close the client connection. However, Microsoft
2378 * in its wisdom has released IIS/5 with a bug that
2379 * prevents it from sending the trailing \r\n in
2380 * a 302 redirect header (and possibly other headers).
2381 * To work around this if we've haven't parsed
2382 * a full header we'll append a trailing \r\n
2383 * and see if this now generates a valid one.
2385 * This hack shouldn't have any impacts. If we've
2386 * already transmitted the header or if this is a
2387 * SSL connection, then we won't bother with this
2388 * hack. So we only work on partially received
2389 * headers. If we append a \r\n and this still
2390 * doesn't generate a valid header, then we won't
2391 * transmit anything to the client.
2396 if (server_body || http->ssl)
2399 * If we have been buffering up the document,
2400 * now is the time to apply content modification
2401 * and send the result to the client.
2403 if (buffer_and_filter_content)
2405 p = execute_content_filters(csp);
2407 * If content filtering fails, use the original
2408 * buffer and length.
2409 * (see p != NULL ? p : csp->iob->cur below)
2413 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2415 #ifdef FEATURE_COMPRESSION
2416 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2417 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2419 char *compressed_content = compress_buffer(p,
2420 (size_t *)&csp->content_length, csp->config->compression_level);
2421 if (compressed_content != NULL)
2424 p = compressed_content;
2425 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2430 if (JB_ERR_OK != update_server_headers(csp))
2432 log_error(LOG_LEVEL_FATAL,
2433 "Failed to update server headers. after filtering.");
2436 hdr = list_to_text(csp->headers);
2439 /* FIXME Should handle error properly */
2440 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2443 if (write_socket(csp->cfd, hdr, strlen(hdr))
2444 || write_socket(csp->cfd,
2445 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2447 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2450 mark_server_socket_tainted(csp);
2458 break; /* "game over, man" */
2462 * This is NOT the body, so
2463 * Let's pretend the server just sent us a blank line.
2465 snprintf(buf, sizeof(buf), "\r\n");
2466 len = (int)strlen(buf);
2469 * Now, let the normal header parsing algorithm below do its
2470 * job. If it fails, we'll exit instead of continuing.
2477 * If this is an SSL connection or we're in the body
2478 * of the server document, just write it to the client,
2479 * unless we need to buffer the body for later content-filtering
2481 if (server_body || http->ssl)
2483 if (buffer_and_filter_content)
2486 * If there is no memory left for buffering the content, or the buffer limit
2487 * has been reached, switch to non-filtering mode, i.e. make & write the
2488 * header, flush the iob and buf, and get out of the way.
2490 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2495 log_error(LOG_LEVEL_INFO,
2496 "Flushing header and buffers. Stepping back from filtering.");
2498 hdr = list_to_text(csp->headers);
2502 * Memory is too tight to even generate the header.
2503 * Send our static "Out-of-memory" page.
2505 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2506 rsp = cgi_error_memory();
2507 send_crunch_response(csp, rsp);
2508 mark_server_socket_tainted(csp);
2511 hdrlen = strlen(hdr);
2513 if (write_socket(csp->cfd, hdr, hdrlen)
2514 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2515 || (write_socket(csp->cfd, buf, (size_t)len)))
2517 log_error(LOG_LEVEL_CONNECT,
2518 "Flush header and buffers to client failed: %E");
2520 mark_server_socket_tainted(csp);
2525 * Reset the byte_count to the amount of bytes
2526 * we just flushed. len will be added a few lines below,
2527 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2529 byte_count = (unsigned long long)flushed;
2531 buffer_and_filter_content = 0;
2537 if (write_socket(csp->cfd, buf, (size_t)len))
2539 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2540 mark_server_socket_tainted(csp);
2544 byte_count += (unsigned long long)len;
2550 * We're still looking for the end of the server's header.
2551 * Buffer up the data we just read. If that fails, there's
2552 * little we can do but send our static out-of-memory page.
2554 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2556 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2557 rsp = cgi_error_memory();
2558 send_crunch_response(csp, rsp);
2559 mark_server_socket_tainted(csp);
2563 /* Convert iob into something sed() can digest */
2564 if (JB_ERR_PARSE == get_server_headers(csp))
2569 * Well, we tried our MS IIS/5 hack and it didn't work.
2570 * The header is incomplete and there isn't anything
2571 * we can do about it.
2573 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2574 "Applying the MS IIS5 hack didn't help.");
2575 log_error(LOG_LEVEL_CLF,
2576 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2577 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2578 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2579 mark_server_socket_tainted(csp);
2585 * Since we have to wait for more from the server before
2586 * we can parse the headers we just continue here.
2588 log_error(LOG_LEVEL_CONNECT,
2589 "Continuing buffering server headers from socket %d. "
2590 "Bytes most recently read: %d.", csp->cfd, len);
2597 * Account for the content bytes we
2598 * might have gotten with the headers.
2600 assert(csp->iob->eod >= csp->iob->cur);
2601 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2604 /* Did we actually get anything? */
2605 if (NULL == csp->headers->first)
2607 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2609 log_error(LOG_LEVEL_ERROR,
2610 "No server or forwarder response received on socket %d. "
2611 "Closing client socket %d without sending data.",
2612 csp->server_connection.sfd, csp->cfd);
2613 log_error(LOG_LEVEL_CLF,
2614 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2618 log_error(LOG_LEVEL_ERROR,
2619 "No server or forwarder response received on socket %d.",
2620 csp->server_connection.sfd);
2621 send_crunch_response(csp, error_response(csp, "no-server-data"));
2623 free_http_request(http);
2624 mark_server_socket_tainted(csp);
2628 assert(csp->headers->first->str);
2630 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2631 strncmpic(csp->headers->first->str, "ICY", 3))
2634 * It doesn't look like a HTTP (or Shoutcast) response:
2635 * tell the client and log the problem.
2637 if (strlen(csp->headers->first->str) > 30)
2639 csp->headers->first->str[30] = '\0';
2641 log_error(LOG_LEVEL_ERROR,
2642 "Invalid server or forwarder response. Starts with: %s",
2643 csp->headers->first->str);
2644 log_error(LOG_LEVEL_CLF,
2645 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2646 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2647 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2648 free_http_request(http);
2649 mark_server_socket_tainted(csp);
2654 * We have now received the entire server header,
2655 * filter it and send the result to the client
2657 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2659 log_error(LOG_LEVEL_CLF,
2660 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2661 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2662 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2663 free_http_request(http);
2664 mark_server_socket_tainted(csp);
2667 hdr = list_to_text(csp->headers);
2670 /* FIXME Should handle error properly */
2671 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2674 if ((csp->flags & CSP_FLAG_CHUNKED)
2675 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2676 && ((csp->iob->eod - csp->iob->cur) >= 5)
2677 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2679 log_error(LOG_LEVEL_CONNECT,
2680 "Looks like we got the last chunk together with "
2681 "the server headers. We better stop reading.");
2682 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2683 csp->expected_content_length = byte_count;
2684 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2687 csp->server_connection.response_received = time(NULL);
2689 if (crunch_response_triggered(csp, crunchers_light))
2692 * One of the tags created by a server-header
2693 * tagger triggered a crunch. We already
2694 * delivered the crunch response to the client
2695 * and are done here after cleaning up.
2698 mark_server_socket_tainted(csp);
2701 /* Buffer and pcrs filter this if appropriate. */
2703 if (!http->ssl) /* We talk plaintext */
2705 buffer_and_filter_content = content_requires_filtering(csp);
2708 * Only write if we're not buffering for content modification
2710 if (!buffer_and_filter_content)
2713 * Write the server's (modified) header to
2714 * the client (along with anything else that
2715 * may be in the buffer)
2718 if (write_socket(csp->cfd, hdr, strlen(hdr))
2719 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2721 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2724 * The write failed, so don't bother mentioning it
2725 * to the client... it probably can't hear us anyway.
2728 mark_server_socket_tainted(csp);
2733 /* we're finished with the server's header */
2739 * If this was a MS IIS/5 hack then it means the server
2740 * has already closed the connection. Nothing more to read.
2745 log_error(LOG_LEVEL_ERROR,
2746 "Closed server connection detected. "
2747 "Applying the MS IIS5 hack didn't help.");
2748 log_error(LOG_LEVEL_CLF,
2749 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2750 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2751 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2752 mark_server_socket_tainted(csp);
2758 mark_server_socket_tainted(csp);
2759 return; /* huh? we should never get here */
2762 if (csp->content_length == 0)
2765 * If Privoxy didn't recalculate the Content-Length,
2766 * byte_count is still correct.
2768 csp->content_length = byte_count;
2771 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2772 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2773 && (csp->expected_content_length != byte_count))
2775 log_error(LOG_LEVEL_CONNECT,
2776 "Received %llu bytes while expecting %llu.",
2777 byte_count, csp->expected_content_length);
2778 mark_server_socket_tainted(csp);
2782 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2783 csp->ip_addr_str, http->ocmd, csp->content_length);
2785 csp->server_connection.timestamp = time(NULL);
2789 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2790 /*********************************************************************
2792 * Function : prepare_csp_for_next_request
2794 * Description : Put the csp in a mostly vergin state.
2797 * 1 : csp = Current client state (buffers, headers, etc...)
2801 *********************************************************************/
2802 static void prepare_csp_for_next_request(struct client_state *csp)
2804 unsigned int toggled_on_flag_set = (0 != (csp->flags & CSP_FLAG_TOGGLED_ON));
2806 csp->content_type = 0;
2807 csp->content_length = 0;
2808 csp->expected_content_length = 0;
2809 csp->expected_client_content_length = 0;
2810 list_remove_all(csp->headers);
2811 clear_iob(csp->iob);
2812 freez(csp->error_message);
2813 free_http_request(csp->http);
2814 destroy_list(csp->headers);
2815 destroy_list(csp->tags);
2816 free_current_action(csp->action);
2817 if (NULL != csp->fwd)
2819 unload_forward_spec(csp->fwd);
2822 /* XXX: Store per-connection flags someplace else. */
2823 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
2824 if (toggled_on_flag_set)
2826 csp->flags |= CSP_FLAG_TOGGLED_ON;
2829 if (csp->client_iob->eod > csp->client_iob->cur)
2831 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
2832 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2834 assert(bytes_to_shift > 0);
2835 assert(data_length > 0);
2837 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
2838 data_length, bytes_to_shift);
2839 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
2840 csp->client_iob->cur = csp->client_iob->buf;
2841 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
2842 csp->client_iob->eod = csp->client_iob->buf + data_length;
2843 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
2845 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
2850 * We mainly care about resetting client_iob->cur so we don't
2851 * waste buffer space at the beginning and don't mess up the
2852 * request restoration done by cgi_show_request().
2854 * Freeing the buffer itself isn't technically necessary,
2855 * but makes debugging more convenient.
2857 clear_iob(csp->client_iob);
2860 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2863 /*********************************************************************
2867 * Description : This is little more than chat. We only "serve" to
2868 * to close (or remember) any socket that chat may have
2872 * 1 : csp = Current client state (buffers, headers, etc...)
2876 *********************************************************************/
2878 void serve(struct client_state *csp)
2879 #else /* ifndef AMIGA */
2880 static void serve(struct client_state *csp)
2881 #endif /* def AMIGA */
2883 int config_file_change_detected = 0; /* Only used for debugging */
2884 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2885 #ifdef FEATURE_CONNECTION_SHARING
2886 static int monitor_thread_running = 0;
2887 #endif /* def FEATURE_CONNECTION_SHARING */
2888 int continue_chatting = 0;
2890 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
2891 csp->ip_addr_str, csp->cfd);
2895 unsigned int latency;
2900 * If the request has been crunched,
2901 * the calculated latency is zero.
2903 latency = (unsigned)(csp->server_connection.response_received -
2904 csp->server_connection.request_sent) / 2;
2906 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2907 && (csp->flags & CSP_FLAG_CRUNCHED)
2908 && (csp->expected_client_content_length != 0))
2910 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
2911 log_error(LOG_LEVEL_CONNECT,
2912 "Tainting client socket %d due to unread data.", csp->cfd);
2915 continue_chatting = (csp->config->feature_flags
2916 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2917 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2918 && (csp->cfd != JB_INVALID_SOCKET)
2919 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2920 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
2921 || (csp->flags & CSP_FLAG_CHUNKED));
2923 if (!(csp->flags & CSP_FLAG_CRUNCHED)
2924 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
2926 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
2928 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
2930 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2931 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2932 || !socket_is_still_alive(csp->server_connection.sfd)
2933 || !(latency < csp->server_connection.keep_alive_timeout))
2935 log_error(LOG_LEVEL_CONNECT,
2936 "Closing server socket %d connected to %s. "
2937 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
2938 csp->server_connection.sfd, csp->server_connection.host,
2939 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2940 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2941 socket_is_still_alive(csp->server_connection.sfd),
2942 csp->server_connection.keep_alive_timeout);
2943 #ifdef FEATURE_CONNECTION_SHARING
2944 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2946 forget_connection(csp->server_connection.sfd);
2948 #endif /* def FEATURE_CONNECTION_SHARING */
2949 close_socket(csp->server_connection.sfd);
2950 mark_connection_closed(&csp->server_connection);
2954 if (continue_chatting && any_loaded_file_changed(csp))
2956 continue_chatting = 0;
2957 config_file_change_detected = 1;
2960 if (continue_chatting)
2962 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
2963 && socket_is_still_alive(csp->cfd))
2965 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
2966 "pipelined on socket %d and the socket is still alive.",
2967 csp->requests_received_total+1, csp->cfd);
2968 prepare_csp_for_next_request(csp);
2972 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
2974 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2976 log_error(LOG_LEVEL_CONNECT,
2977 "Waiting for the next client request on socket %d. "
2978 "Keeping the server socket %d to %s open.",
2979 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2983 log_error(LOG_LEVEL_CONNECT,
2984 "Waiting for the next client request on socket %d. "
2985 "No server socket to keep open.", csp->cfd);
2989 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2990 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
2991 && socket_is_still_alive(csp->cfd))
2993 log_error(LOG_LEVEL_CONNECT,
2994 "Client request %u arrived in time on socket %d.",
2995 csp->requests_received_total+1, csp->cfd);
2996 prepare_csp_for_next_request(csp);
3000 #ifdef FEATURE_CONNECTION_SHARING
3001 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3002 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3003 && (socket_is_still_alive(csp->server_connection.sfd)))
3005 time_t time_open = time(NULL) - csp->server_connection.timestamp;
3007 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3012 remember_connection(&csp->server_connection);
3013 csp->server_connection.sfd = JB_INVALID_SOCKET;
3014 drain_and_close_socket(csp->cfd);
3015 csp->cfd = JB_INVALID_SOCKET;
3016 privoxy_mutex_lock(&connection_reuse_mutex);
3017 if (!monitor_thread_running)
3019 monitor_thread_running = 1;
3020 privoxy_mutex_unlock(&connection_reuse_mutex);
3021 wait_for_alive_connections();
3022 privoxy_mutex_lock(&connection_reuse_mutex);
3023 monitor_thread_running = 0;
3025 privoxy_mutex_unlock(&connection_reuse_mutex);
3027 #endif /* def FEATURE_CONNECTION_SHARING */
3031 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3033 log_error(LOG_LEVEL_CONNECT,
3034 "Closing server socket %d connected to %s. Keep-alive: %u. "
3035 "Tainted: %u. Socket alive: %u. Timeout: %u. "
3036 "Configuration file change detected: %u",
3037 csp->server_connection.sfd, csp->server_connection.host,
3038 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3039 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3040 socket_is_still_alive(csp->server_connection.sfd),
3041 csp->server_connection.keep_alive_timeout,
3042 config_file_change_detected);
3044 } while (continue_chatting);
3048 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3050 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3052 #ifdef FEATURE_CONNECTION_SHARING
3053 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3055 forget_connection(csp->server_connection.sfd);
3057 #endif /* def FEATURE_CONNECTION_SHARING */
3058 close_socket(csp->server_connection.sfd);
3061 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3062 mark_connection_closed(&csp->server_connection);
3065 if (csp->cfd != JB_INVALID_SOCKET)
3067 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3068 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3069 "Configuration file change detected: %u. Requests received: %u.",
3070 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3071 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3072 config_file_change_detected, csp->requests_received_total);
3073 drain_and_close_socket(csp->cfd);
3076 csp->flags &= ~CSP_FLAG_ACTIVE;
3082 /*********************************************************************
3084 * Function : server_thread
3086 * Description : We only exist to call `serve' in a threaded environment.
3089 * 1 : data = Current client state (buffers, headers, etc...)
3091 * Returns : Always 0.
3093 *********************************************************************/
3094 static int32 server_thread(void *data)
3096 serve((struct client_state *) data);
3103 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3104 /*********************************************************************
3108 * Description : Print usage info & exit.
3110 * Parameters : Pointer to argv[0] for identifying ourselves
3114 *********************************************************************/
3115 static void usage(const char *myname)
3117 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3118 "Usage: %s [--config-test] "
3121 #endif /* defined(unix) */
3124 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3125 #endif /* defined(unix) */
3126 "[--version] [configfile]\n"
3127 "Aborting\n", myname);
3132 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3135 #ifdef MUTEX_LOCKS_AVAILABLE
3136 /*********************************************************************
3138 * Function : privoxy_mutex_lock
3140 * Description : Locks a mutex.
3143 * 1 : mutex = The mutex to lock.
3145 * Returns : Void. May exit in case of errors.
3147 *********************************************************************/
3148 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3150 #ifdef FEATURE_PTHREAD
3151 int err = pthread_mutex_lock(mutex);
3154 if (mutex != &log_mutex)
3156 log_error(LOG_LEVEL_FATAL,
3157 "Mutex locking failed: %s.\n", strerror(err));
3162 EnterCriticalSection(mutex);
3163 #endif /* def FEATURE_PTHREAD */
3167 /*********************************************************************
3169 * Function : privoxy_mutex_unlock
3171 * Description : Unlocks a mutex.
3174 * 1 : mutex = The mutex to unlock.
3176 * Returns : Void. May exit in case of errors.
3178 *********************************************************************/
3179 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3181 #ifdef FEATURE_PTHREAD
3182 int err = pthread_mutex_unlock(mutex);
3185 if (mutex != &log_mutex)
3187 log_error(LOG_LEVEL_FATAL,
3188 "Mutex unlocking failed: %s.\n", strerror(err));
3193 LeaveCriticalSection(mutex);
3194 #endif /* def FEATURE_PTHREAD */
3198 /*********************************************************************
3200 * Function : privoxy_mutex_init
3202 * Description : Prepares a mutex.
3205 * 1 : mutex = The mutex to initialize.
3207 * Returns : Void. May exit in case of errors.
3209 *********************************************************************/
3210 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3212 #ifdef FEATURE_PTHREAD
3213 int err = pthread_mutex_init(mutex, 0);
3216 printf("Fatal error. Mutex initialization failed: %s.\n",
3221 InitializeCriticalSection(mutex);
3222 #endif /* def FEATURE_PTHREAD */
3224 #endif /* def MUTEX_LOCKS_AVAILABLE */
3226 /*********************************************************************
3228 * Function : initialize_mutexes
3230 * Description : Prepares mutexes if mutex support is available.
3234 * Returns : Void, exits in case of errors.
3236 *********************************************************************/
3237 static void initialize_mutexes(void)
3239 #ifdef MUTEX_LOCKS_AVAILABLE
3241 * Prepare global mutex semaphores
3243 privoxy_mutex_init(&log_mutex);
3244 privoxy_mutex_init(&log_init_mutex);
3245 privoxy_mutex_init(&connection_reuse_mutex);
3246 #ifdef FEATURE_EXTERNAL_FILTERS
3247 privoxy_mutex_init(&external_filter_mutex);
3251 * XXX: The assumptions below are a bit naive
3252 * and can cause locks that aren't necessary.
3254 * For example older FreeBSD versions (< 6.x?)
3255 * have no gethostbyname_r, but gethostbyname is
3258 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3259 privoxy_mutex_init(&resolver_mutex);
3260 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3262 * XXX: should we use a single mutex for
3263 * localtime() and gmtime() as well?
3265 #ifndef HAVE_GMTIME_R
3266 privoxy_mutex_init(&gmtime_mutex);
3267 #endif /* ndef HAVE_GMTIME_R */
3269 #ifndef HAVE_LOCALTIME_R
3270 privoxy_mutex_init(&localtime_mutex);
3271 #endif /* ndef HAVE_GMTIME_R */
3274 privoxy_mutex_init(&rand_mutex);
3275 #endif /* ndef HAVE_RANDOM */
3277 #endif /* def MUTEX_LOCKS_AVAILABLE */
3281 /*********************************************************************
3285 * Description : Load the config file and start the listen loop.
3286 * This function is a lot more *sane* with the `load_config'
3287 * and `listen_loop' functions; although it stills does
3288 * a *little* too much for my taste.
3291 * 1 : argc = Number of parameters (including $0).
3292 * 2 : argv = Array of (char *)'s to the parameters.
3294 * Returns : 1 if : can't open config file, unrecognized directive,
3295 * stats requested in multi-thread mode, can't open the
3296 * log file, can't open the jar file, listen port is invalid,
3297 * any load fails, and can't bind port.
3299 * Else main never returns, the process must be signaled
3300 * to terminate execution. Or, on Windows, use the
3301 * "File", "Exit" menu option.
3303 *********************************************************************/
3305 int real_main(int argc, char **argv)
3307 int main(int argc, char **argv)
3311 int do_config_test = 0;
3312 unsigned int random_seed;
3314 struct passwd *pw = NULL;
3315 struct group *grp = NULL;
3317 char *pre_chroot_nslookup_to_load_resolver = NULL;
3324 #if !defined(_WIN32)
3331 /* Prepare mutexes if supported and necessary. */
3332 initialize_mutexes();
3334 /* Enable logging until further notice. */
3338 * Parse the command line arguments
3340 * XXX: simply printing usage information in case of
3341 * invalid arguments isn't particularly user friendly.
3343 while (++argc_pos < argc)
3346 /* Check to see if the service must be installed or uninstalled */
3347 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3349 const char *pName = argv[argc_pos] + 9;
3352 exit((install_service(pName)) ? 0 : 1);
3354 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3356 const char *pName = argv[argc_pos] + 11;
3359 exit((uninstall_service(pName)) ? 0 : 1);
3361 else if (strcmp(argv[argc_pos], "--service") == 0)
3363 bRunAsService = TRUE;
3364 w32_set_service_cwd();
3365 atexit(w32_service_exit_notify);
3368 #endif /* defined(_WIN32) */
3371 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3373 if (strcmp(argv[argc_pos], "--help") == 0)
3378 else if (strcmp(argv[argc_pos], "--version") == 0)
3380 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3386 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3388 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3392 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3394 if (++argc_pos == argc) usage(argv[0]);
3395 pidfile = strdup_or_die(argv[argc_pos]);
3398 else if (strcmp(argv[argc_pos], "--user") == 0)
3403 if (++argc_pos == argc) usage(argv[argc_pos]);
3405 user_arg = strdup_or_die(argv[argc_pos]);
3406 group_name = strchr(user_arg, '.');
3407 if (NULL != group_name)
3409 /* Nul-terminate the user name */
3412 /* Skip the former delimiter to actually reach the group name */
3415 grp = getgrnam(group_name);
3418 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3421 pw = getpwnam(user_arg);
3424 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3430 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3432 if (++argc_pos == argc) usage(argv[0]);
3433 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3436 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3440 #endif /* defined(unix) */
3442 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3447 else if (argc_pos + 1 != argc)
3450 * This is neither the last command line
3451 * option, nor was it recognized before,
3452 * therefore it must be invalid.
3458 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3460 configfile = argv[argc_pos];
3463 } /* -END- while (more arguments) */
3465 show_version(Argv[0]);
3468 if (*configfile != '/')
3470 char cwd[BUFFER_SIZE];
3472 size_t abs_file_size;
3474 /* make config-filename absolute here */
3475 if (NULL == getcwd(cwd, sizeof(cwd)))
3477 perror("failed to get current working directory");
3481 basedir = strdup_or_die(cwd);
3483 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3484 abs_file = malloc_or_die(abs_file_size);
3485 strlcpy(abs_file, basedir, abs_file_size);
3486 strlcat(abs_file, "/", abs_file_size);
3487 strlcat(abs_file, configfile, abs_file_size);
3488 configfile = abs_file;
3490 #endif /* defined unix */
3494 clients->next = NULL;
3496 /* XXX: factor out initialising after the next stable release. */
3499 #elif defined(_WIN32)
3503 random_seed = (unsigned int)time(NULL);
3505 srandom(random_seed);
3508 #endif /* ifdef HAVE_RANDOM */
3511 * Unix signal handling
3513 * Catch the abort, interrupt and terminate signals for a graceful exit
3514 * Catch the hangup signal so the errlog can be reopened.
3515 * Ignore the broken pipe signals (FIXME: Why?)
3517 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3520 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3522 for (idx = 0; idx < SZ(catched_signals); idx++)
3524 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3525 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3527 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3528 #endif /* ifdef sun */
3530 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3534 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3536 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3540 #else /* ifdef _WIN32 */
3541 # ifdef _WIN_CONSOLE
3543 * We *are* in a windows console app.
3544 * Print a verbose messages about FAQ's and such
3546 printf("%s", win32_blurb);
3547 # endif /* def _WIN_CONSOLE */
3548 #endif /* def _WIN32 */
3552 exit(NULL == load_config());
3555 /* Initialize the CGI subsystem */
3556 cgi_init_error_messages();
3559 * If running on unix and without the --no-daemon
3560 * option, become a daemon. I.e. fork, detach
3561 * from tty and get process group leadership
3570 if (pid < 0) /* error */
3575 else if (pid != 0) /* parent */
3580 * must check for errors
3581 * child died due to missing files aso
3584 wpid = waitpid(pid, &status, WNOHANG);
3596 * stderr (fd 2) will be closed later on,
3597 * when the config file has been parsed.
3603 * Reserve fd 0 and 1 to prevent abort() and friends
3604 * from sending stuff to the clients or servers.
3606 fd = open("/dev/null", O_RDONLY);
3609 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3613 if (dup2(fd, 0) == -1)
3615 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3619 fd = open("/dev/null", O_WRONLY);
3622 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3626 if (dup2(fd, 1) == -1)
3628 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3633 #ifdef FEATURE_EXTERNAL_FILTERS
3634 for (fd = 0; fd < 3; fd++)
3636 mark_socket_for_close_on_execute(fd);
3642 } /* -END- if (daemon_mode) */
3645 * As soon as we have written the PID file, we can switch
3646 * to the user and group ID indicated by the --user option
3652 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3654 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3658 if (setgroups(1, &grp->gr_gid))
3660 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3663 else if (initgroups(pw->pw_name, pw->pw_gid))
3665 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3671 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3673 /* Read the time zone file from /etc before doing chroot. */
3675 if (NULL != pre_chroot_nslookup_to_load_resolver
3676 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3678 /* Initialize resolver library. */
3679 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3681 if (chroot(pw->pw_dir) < 0)
3683 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3687 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3690 if (setuid(pw->pw_uid))
3692 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3696 char putenv_dummy[64];
3698 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3699 if (putenv(putenv_dummy) != 0)
3701 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3704 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3705 if (putenv(putenv_dummy) != 0)
3707 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3713 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3716 #endif /* defined unix */
3719 /* This will be FALSE unless the command line specified --service
3723 /* Yup, so now we must attempt to establish a connection
3724 * with the service dispatcher. This will only work if this
3725 * process was launched by the service control manager to
3726 * actually run as a service. If this isn't the case, i've
3727 * known it take around 30 seconds or so for the call to return.
3730 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3731 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3733 /* Service has run, and at this point is now being stopped, so just return */
3738 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3740 /* An error occurred. Usually it's because --service was wrongly specified
3741 * and we were unable to connect to the Service Control Dispatcher because
3742 * it wasn't expecting us and is therefore not listening.
3744 * For now, just continue below to call the listen_loop function.
3747 #endif /* def _WIN32 */
3757 /*********************************************************************
3759 * Function : bind_port_helper
3761 * Description : Bind the listen port. Handles logging, and aborts
3765 * 1 : haddr = Host address to bind to. Use NULL to bind to
3767 * 2 : hport = Specifies port to bind to.
3769 * Returns : Port that was opened.
3771 *********************************************************************/
3772 static jb_socket bind_port_helper(const char *haddr, int hport)
3777 result = bind_port(haddr, hport, &bfd);
3781 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
3785 log_error(LOG_LEVEL_FATAL,
3786 "can't bind to %s:%d: There may be another Privoxy "
3787 "or some other proxy running on port %d",
3788 bind_address, hport, hport);
3791 log_error(LOG_LEVEL_FATAL,
3792 "can't bind to %s:%d: The hostname is not resolvable",
3793 bind_address, hport);
3796 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3797 bind_address, hport);
3800 /* shouldn't get here */
3801 return JB_INVALID_SOCKET;
3805 if (bfd >= FD_SETSIZE)
3807 log_error(LOG_LEVEL_FATAL,
3808 "Bind socket number too