1 const char jcc_rcs[] = "$Id: jcc.c,v 1.419 2012/12/07 12:43:55 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-2012 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 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
186 privoxy_mutex_t resolver_mutex;
187 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
189 #ifndef HAVE_GMTIME_R
190 privoxy_mutex_t gmtime_mutex;
191 #endif /* ndef HAVE_GMTIME_R */
193 #ifndef HAVE_LOCALTIME_R
194 privoxy_mutex_t localtime_mutex;
195 #endif /* ndef HAVE_GMTIME_R */
198 privoxy_mutex_t rand_mutex;
199 #endif /* ndef HAVE_RANDOM */
201 #endif /* def MUTEX_LOCKS_AVAILABLE */
204 const char *basedir = NULL;
205 const char *pidfile = NULL;
206 static int received_hup_signal = 0;
207 #endif /* defined unix */
209 /* HTTP snipplets. */
210 static const char CSUCCEED[] =
211 "HTTP/1.1 200 Connection established\r\n"
212 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
214 static const char CHEADER[] =
215 "HTTP/1.1 400 Invalid header received from client\r\n"
216 "Proxy-Agent: Privoxy " VERSION "\r\n"
217 "Content-Type: text/plain\r\n"
218 "Connection: close\r\n\r\n"
219 "Invalid header received from client.\r\n";
221 static const char FTP_RESPONSE[] =
222 "HTTP/1.1 400 Invalid request received from client\r\n"
223 "Content-Type: text/plain\r\n"
224 "Connection: close\r\n\r\n"
225 "Invalid request. Privoxy doesn't support FTP.\r\n";
227 static const char GOPHER_RESPONSE[] =
228 "HTTP/1.1 400 Invalid request received from client\r\n"
229 "Content-Type: text/plain\r\n"
230 "Connection: close\r\n\r\n"
231 "Invalid request. Privoxy doesn't support gopher.\r\n";
233 /* XXX: should be a template */
234 static const char MISSING_DESTINATION_RESPONSE[] =
235 "HTTP/1.1 400 Bad request received from client\r\n"
236 "Proxy-Agent: Privoxy " VERSION "\r\n"
237 "Content-Type: text/plain\r\n"
238 "Connection: close\r\n\r\n"
239 "Bad request. Privoxy was unable to extract the destination.\r\n";
241 /* XXX: should be a template */
242 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
243 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
244 "Proxy-Agent: Privoxy " VERSION "\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 "Proxy-Agent: Privoxy " VERSION "\r\n"
253 "Content-Type: text/plain\r\n"
254 "Connection: close\r\n\r\n"
255 "Bad request. Messed up with header filters.\r\n";
257 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
258 "HTTP/1.1 503 Too many open connections\r\n"
259 "Proxy-Agent: Privoxy " VERSION "\r\n"
260 "Content-Type: text/plain\r\n"
261 "Connection: close\r\n\r\n"
262 "Maximum number of open connections reached.\r\n";
264 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
265 "HTTP/1.1 504 Connection timeout\r\n"
266 "Proxy-Agent: Privoxy " VERSION "\r\n"
267 "Content-Type: text/plain\r\n"
268 "Connection: close\r\n\r\n"
269 "The connection timed out because the client request didn't arrive in time.\r\n";
271 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
272 "HTTP/1.1 400 Failed reading client body\r\n"
273 "Proxy-Agent: Privoxy " VERSION "\r\n"
274 "Content-Type: text/plain\r\n"
275 "Connection: close\r\n\r\n"
276 "Failed parsing or buffering the chunk-encoded client body.\r\n";
278 /* A function to crunch a response */
279 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
281 /* Crunch function flags */
282 #define CF_NO_FLAGS 0
283 /* Cruncher applies to forced requests as well */
284 #define CF_IGNORE_FORCE 1
285 /* Crunched requests are counted for the block statistics */
286 #define CF_COUNT_AS_REJECT 2
288 /* A crunch function and its flags */
291 const crunch_func_ptr cruncher;
295 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
297 /* Complete list of cruncher functions */
298 static const struct cruncher crunchers_all[] = {
299 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
300 { block_url, CF_COUNT_AS_REJECT },
302 { trust_url, CF_COUNT_AS_REJECT },
303 #endif /* def FEATURE_TRUST */
304 { redirect_url, CF_NO_FLAGS },
305 { dispatch_cgi, CF_IGNORE_FORCE},
309 /* Light version, used after tags are applied */
310 static const struct cruncher crunchers_light[] = {
311 { block_url, CF_COUNT_AS_REJECT },
312 { redirect_url, CF_NO_FLAGS },
318 * XXX: Don't we really mean
324 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
325 /*********************************************************************
327 * Function : sig_handler
329 * Description : Signal handler for different signals.
330 * Exit gracefully on TERM and INT
331 * or set a flag that will cause the errlog
332 * to be reopened by the main thread on HUP.
335 * 1 : the_signal = the signal cause this function to call
339 *********************************************************************/
340 static void sig_handler(int the_signal)
346 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
358 received_hup_signal = 1;
364 * We shouldn't be here, unless we catch signals
365 * in main() that we can't handle here!
367 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
375 /*********************************************************************
377 * Function : client_protocol_is_unsupported
379 * Description : Checks if the client used a known unsupported
380 * protocol and deals with it by sending an error
384 * 1 : csp = Current client state (buffers, headers, etc...)
385 * 2 : req = the first request line send by the client
387 * Returns : TRUE if an error response has been generated, or
388 * FALSE if the request doesn't look invalid.
390 *********************************************************************/
391 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
394 * If it's a FTP or gopher request, we don't support it.
396 * These checks are better than nothing, but they might
397 * not work in all configurations and some clients might
398 * have problems digesting the answer.
400 * They should, however, never cause more problems than
401 * Privoxy's old behaviour (returning the misleading HTML
404 * "Could not resolve http://(ftp|gopher)://example.org").
406 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
408 const char *response = NULL;
409 const char *protocol = NULL;
411 if (!strncmpic(req, "GET ftp://", 10))
413 response = FTP_RESPONSE;
418 response = GOPHER_RESPONSE;
421 log_error(LOG_LEVEL_ERROR,
422 "%s tried to use Privoxy as %s proxy: %s",
423 csp->ip_addr_str, protocol, req);
424 log_error(LOG_LEVEL_CLF,
425 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
427 write_socket(csp->cfd, response, strlen(response));
436 /*********************************************************************
438 * Function : get_request_destination_elsewhere
440 * Description : If the client's request was redirected into
441 * Privoxy without the client's knowledge,
442 * the request line lacks the destination host.
444 * This function tries to get it elsewhere,
445 * provided accept-intercepted-requests is enabled.
447 * "Elsewhere" currently only means "Host: header",
448 * but in the future we may ask the redirecting
449 * packet filter to look the destination up.
451 * If the destination stays unknown, an error
452 * response is send to the client and headers
453 * are freed so that chat() can return directly.
456 * 1 : csp = Current client state (buffers, headers, etc...)
457 * 2 : headers = a header list
459 * Returns : JB_ERR_OK if the destination is now known, or
460 * JB_ERR_PARSE if it isn't.
462 *********************************************************************/
463 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
467 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
469 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
470 " Privoxy isn't configured to accept intercepted requests.",
471 csp->ip_addr_str, csp->http->cmd);
472 /* XXX: Use correct size */
473 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
474 csp->ip_addr_str, csp->http->cmd);
476 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
477 destroy_list(headers);
481 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
483 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
484 /* Split the domain we just got for pattern matching */
485 init_domain_components(csp->http);
492 /* We can't work without destination. Go spread the news.*/
494 req = list_to_text(headers);
496 /* XXX: Use correct size */
497 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
498 csp->ip_addr_str, csp->http->cmd);
499 log_error(LOG_LEVEL_ERROR,
500 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
501 csp->ip_addr_str, csp->http->cmd, req);
504 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
505 destroy_list(headers);
510 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
511 * to get the destination IP address, use it as host directly
512 * or do a reverse DNS lookup first.
517 /*********************************************************************
519 * Function : get_server_headers
521 * Description : Parses server headers in iob and fills them
522 * into csp->headers so that they can later be
526 * 1 : csp = Current client state (buffers, headers, etc...)
528 * Returns : JB_ERR_OK if everything went fine, or
529 * JB_ERR_PARSE if the headers were incomplete.
531 *********************************************************************/
532 static jb_err get_server_headers(struct client_state *csp)
534 int continue_hack_in_da_house = 0;
537 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
542 * continue hack in da house. Ignore the ending of
543 * this head and continue enlisting header lines.
544 * The reason is described below.
546 enlist(csp->headers, "");
547 continue_hack_in_da_house = 0;
550 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
553 * It's a bodyless continue response, don't
554 * stop header parsing after reaching its end.
556 * As a result Privoxy will concatenate the
557 * next response's head and parse and deliver
558 * the headers as if they belonged to one request.
560 * The client will separate them because of the
561 * empty line between them.
563 * XXX: What we're doing here is clearly against
564 * the intended purpose of the continue header,
565 * and under some conditions (HTTP/1.0 client request)
566 * it's a standard violation.
568 * Anyway, "sort of against the spec" is preferable
569 * to "always getting confused by Continue responses"
570 * (Privoxy's behaviour before this hack was added)
572 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
573 continue_hack_in_da_house = 1;
575 else if (*header == '\0')
578 * If the header is empty, but the Continue hack
579 * isn't active, we can assume that we reached the
580 * end of the buffer before we hit the end of the
583 * Inform the caller an let it decide how to handle it.
588 if (JB_ERR_MEMORY == enlist(csp->headers, header))
591 * XXX: Should we quit the request and return a
592 * out of memory error page instead?
594 log_error(LOG_LEVEL_ERROR,
595 "Out of memory while enlisting server headers. %s lost.",
605 /*********************************************************************
607 * Function : crunch_reason
609 * Description : Translates the crunch reason code into a string.
612 * 1 : rsp = a http_response
614 * Returns : A string with the crunch reason or an error description.
616 *********************************************************************/
617 static const char *crunch_reason(const struct http_response *rsp)
619 char * reason = NULL;
624 return "Internal error while searching for crunch reason";
627 switch (rsp->crunch_reason)
630 reason = "Unsupported HTTP feature";
636 reason = "Untrusted";
639 reason = "Redirected";
645 reason = "DNS failure";
647 case FORWARDING_FAILED:
648 reason = "Forwarding failed";
651 reason = "Connection failure";
654 reason = "Out of memory (may mask other reasons)";
656 case CONNECTION_TIMEOUT:
657 reason = "Connection timeout";
660 reason = "No server data received";
663 reason = "No reason recorded";
671 /*********************************************************************
673 * Function : log_applied_actions
675 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
679 * 1 : actions = Current action spec to log
683 *********************************************************************/
684 static void log_applied_actions(const struct current_action_spec *actions)
687 * The conversion to text requires lots of memory allocations so
688 * we only do the conversion if the user is actually interested.
690 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
692 char *actions_as_text = actions_to_line_of_text(actions);
693 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
694 freez(actions_as_text);
699 /*********************************************************************
701 * Function : send_crunch_response
703 * Description : Delivers already prepared response for
704 * intercepted requests, logs the interception
705 * and frees the response.
708 * 1 : csp = Current client state (buffers, headers, etc...)
709 * 1 : rsp = Fully prepared response. Will be freed on exit.
713 *********************************************************************/
714 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
716 const struct http_request *http = csp->http;
720 assert(rsp->head != NULL);
724 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
728 * Extract the status code from the actual head
729 * that will be send to the client. It is the only
730 * way to get it right for all requests, including
731 * the fixed ones for out-of-memory problems.
733 * A head starts like this: 'HTTP/1.1 200...'
737 status_code[0] = rsp->head[9];
738 status_code[1] = rsp->head[10];
739 status_code[2] = rsp->head[11];
740 status_code[3] = '\0';
742 /* Log that the request was crunched and why. */
743 log_applied_actions(csp->action);
744 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
745 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
746 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
748 /* Write the answer to the client */
749 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
750 || write_socket(csp->cfd, rsp->body, rsp->content_length))
752 /* There is nothing we can do about it. */
753 log_error(LOG_LEVEL_ERROR,
754 "Couldn't deliver the error message through client socket %d: %E",
758 /* Clean up and return */
759 if (cgi_error_memory() != rsp)
761 free_http_response(rsp);
767 /*********************************************************************
769 * Function : crunch_response_triggered
771 * Description : Checks if the request has to be crunched,
772 * and delivers the crunch response if necessary.
775 * 1 : csp = Current client state (buffers, headers, etc...)
776 * 2 : crunchers = list of cruncher functions to run
778 * Returns : TRUE if the request was answered with a crunch response
781 *********************************************************************/
782 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
784 struct http_response *rsp = NULL;
785 const struct cruncher *c;
788 * If CGI request crunching is disabled,
789 * check the CGI dispatcher out of order to
790 * prevent unintentional blocks or redirects.
792 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
793 && (NULL != (rsp = dispatch_cgi(csp))))
795 /* Deliver, log and free the interception response. */
796 send_crunch_response(csp, rsp);
797 csp->flags |= CSP_FLAG_CRUNCHED;
801 for (c = crunchers; c->cruncher != NULL; c++)
804 * Check the cruncher if either Privoxy is toggled
805 * on and the request isn't forced, or if the cruncher
806 * applies to forced requests as well.
808 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
809 !(csp->flags & CSP_FLAG_FORCED)) ||
810 (c->flags & CF_IGNORE_FORCE))
812 rsp = c->cruncher(csp);
815 /* Deliver, log and free the interception response. */
816 send_crunch_response(csp, rsp);
817 csp->flags |= CSP_FLAG_CRUNCHED;
818 #ifdef FEATURE_STATISTICS
819 if (c->flags & CF_COUNT_AS_REJECT)
821 csp->flags |= CSP_FLAG_REJECTED;
823 #endif /* def FEATURE_STATISTICS */
834 /*********************************************************************
836 * Function : build_request_line
838 * Description : Builds the HTTP request line.
840 * If a HTTP forwarder is used it expects the whole URL,
841 * web servers only get the path.
844 * 1 : csp = Current client state (buffers, headers, etc...)
845 * 2 : fwd = The forwarding spec used for the request
846 * XXX: Should use http->fwd instead.
847 * 3 : request_line = The old request line which will be replaced.
849 * Returns : Nothing. Terminates in case of memory problems.
851 *********************************************************************/
852 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
854 struct http_request *http = csp->http;
856 assert(http->ssl == 0);
859 * Downgrade http version from 1.1 to 1.0
860 * if +downgrade action applies.
862 if ((csp->action->flags & ACTION_DOWNGRADE)
863 && (!strcmpic(http->ver, "HTTP/1.1")))
866 http->ver = strdup_or_die("HTTP/1.0");
870 * Rebuild the request line.
872 freez(*request_line);
873 *request_line = strdup(http->gpc);
874 string_append(request_line, " ");
876 if (fwd->forward_host)
878 string_append(request_line, http->url);
882 string_append(request_line, http->path);
884 string_append(request_line, " ");
885 string_append(request_line, http->ver);
887 if (*request_line == NULL)
889 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
891 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
895 /*********************************************************************
897 * Function : change_request_destination
899 * Description : Parse a (rewritten) request line and regenerate
900 * the http request data.
903 * 1 : csp = Current client state (buffers, headers, etc...)
905 * Returns : Forwards the parse_http_request() return code.
906 * Terminates in case of memory problems.
908 *********************************************************************/
909 static jb_err change_request_destination(struct client_state *csp)
911 struct http_request *http = csp->http;
914 log_error(LOG_LEVEL_INFO, "Rewrite detected: %s", csp->headers->first->str);
915 free_http_request(http);
916 err = parse_http_request(csp->headers->first->str, http);
917 if (JB_ERR_OK != err)
919 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
920 jb_err_to_string(err));
924 /* XXX: ocmd is a misleading name */
925 http->ocmd = strdup_or_die(http->cmd);
932 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
933 /*********************************************************************
935 * Function : server_response_is_complete
937 * Description : Determines whether we should stop reading
938 * from the server socket.
941 * 1 : csp = Current client state (buffers, headers, etc...)
942 * 2 : content_length = Length of content received so far.
944 * Returns : TRUE if the response is complete,
947 *********************************************************************/
948 static int server_response_is_complete(struct client_state *csp,
949 unsigned long long content_length)
951 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
953 if (!strcmpic(csp->http->gpc, "HEAD"))
956 * "HEAD" implies no body, we are thus expecting
957 * no content. XXX: incomplete "list" of methods?
959 csp->expected_content_length = 0;
960 content_length_known = TRUE;
961 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
964 if (csp->http->status == 204 || csp->http->status == 304)
967 * Expect no body. XXX: incomplete "list" of status codes?
969 csp->expected_content_length = 0;
970 content_length_known = TRUE;
971 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
974 return (content_length_known && ((0 == csp->expected_content_length)
975 || (csp->expected_content_length <= content_length)));
979 #ifdef FEATURE_CONNECTION_SHARING
980 /*********************************************************************
982 * Function : wait_for_alive_connections
984 * Description : Waits for alive connections to timeout.
990 *********************************************************************/
991 static void wait_for_alive_connections(void)
993 int connections_alive = close_unusable_connections();
995 while (0 < connections_alive)
997 log_error(LOG_LEVEL_CONNECT,
998 "Waiting for %d connections to timeout.",
1001 connections_alive = close_unusable_connections();
1004 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1007 #endif /* def FEATURE_CONNECTION_SHARING */
1010 /*********************************************************************
1012 * Function : save_connection_destination
1014 * Description : Remembers a connection for reuse later on.
1017 * 1 : sfd = Open socket to remember.
1018 * 2 : http = The destination for the connection.
1019 * 3 : fwd = The forwarder settings used.
1020 * 3 : server_connection = storage.
1024 *********************************************************************/
1025 void save_connection_destination(jb_socket sfd,
1026 const struct http_request *http,
1027 const struct forward_spec *fwd,
1028 struct reusable_connection *server_connection)
1030 assert(sfd != JB_INVALID_SOCKET);
1031 assert(NULL != http->host);
1033 server_connection->sfd = sfd;
1034 server_connection->host = strdup_or_die(http->host);
1035 server_connection->port = http->port;
1037 assert(NULL != fwd);
1038 assert(server_connection->gateway_host == NULL);
1039 assert(server_connection->gateway_port == 0);
1040 assert(server_connection->forwarder_type == 0);
1041 assert(server_connection->forward_host == NULL);
1042 assert(server_connection->forward_port == 0);
1044 server_connection->forwarder_type = fwd->type;
1045 if (NULL != fwd->gateway_host)
1047 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1051 server_connection->gateway_host = NULL;
1053 server_connection->gateway_port = fwd->gateway_port;
1055 if (NULL != fwd->forward_host)
1057 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1061 server_connection->forward_host = NULL;
1063 server_connection->forward_port = fwd->forward_port;
1067 /*********************************************************************
1069 * Function : verify_request_length
1071 * Description : Checks if we already got the whole client requests
1072 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1075 * Data that doesn't belong to the current request is
1076 * either thrown away to let the client retry on a clean
1077 * socket, or stashed to be dealt with after the current
1078 * request is served.
1081 * 1 : csp = Current client state (buffers, headers, etc...)
1085 *********************************************************************/
1086 static void verify_request_length(struct client_state *csp)
1088 unsigned long long buffered_request_bytes =
1089 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1091 if ((csp->expected_client_content_length != 0)
1092 && (buffered_request_bytes != 0))
1094 if (csp->expected_client_content_length >= buffered_request_bytes)
1096 csp->expected_client_content_length -= buffered_request_bytes;
1097 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1098 "to account for the %llu ones we already got.",
1099 csp->expected_client_content_length, buffered_request_bytes);
1103 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1104 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1105 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1106 "Marking the server socket tainted after throwing %llu bytes away.",
1107 buffered_request_bytes - csp->expected_client_content_length);
1108 csp->expected_client_content_length = 0;
1109 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1112 if (csp->expected_client_content_length == 0)
1114 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1118 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1119 && ((csp->client_iob->cur < csp->client_iob->eod)
1120 || (csp->expected_client_content_length != 0)))
1122 if (strcmpic(csp->http->gpc, "GET")
1123 && strcmpic(csp->http->gpc, "HEAD")
1124 && strcmpic(csp->http->gpc, "TRACE")
1125 && strcmpic(csp->http->gpc, "OPTIONS")
1126 && strcmpic(csp->http->gpc, "DELETE"))
1128 /* XXX: this is an incomplete hack */
1129 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1130 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1134 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1136 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1138 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1139 log_error(LOG_LEVEL_CONNECT,
1140 "Possible pipeline attempt detected. The connection will not "
1141 "be kept alive and we will only serve the first request.");
1142 /* Nuke the pipelined requests from orbit, just to be sure. */
1143 clear_iob(csp->client_iob);
1148 * Keep the pipelined data around for now, we'll deal with
1149 * it once we're done serving the current request.
1151 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1152 assert(csp->client_iob->eod >= csp->client_iob->cur);
1153 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1154 "%d bytes of pipelined data received.",
1155 (int)(csp->client_iob->eod - csp->client_iob->cur));
1161 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1162 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1165 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1168 /*********************************************************************
1170 * Function : mark_server_socket_tainted
1172 * Description : Makes sure we don't reuse a server socket
1173 * (if we didn't read everything the server sent
1174 * us reusing the socket would lead to garbage).
1177 * 1 : csp = Current client state (buffers, headers, etc...)
1181 *********************************************************************/
1182 static void mark_server_socket_tainted(struct client_state *csp)
1185 * For consistency we always mark the server socket
1186 * tainted, however, to reduce the log noise we only
1187 * emit a log message if the server socket could have
1188 * actually been reused.
1190 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1191 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1193 log_error(LOG_LEVEL_CONNECT,
1194 "Marking the server socket %d tainted.",
1195 csp->server_connection.sfd);
1197 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1200 /*********************************************************************
1202 * Function : get_request_line
1204 * Description : Read the client request line.
1207 * 1 : csp = Current client state (buffers, headers, etc...)
1209 * Returns : Pointer to request line or NULL in case of errors.
1211 *********************************************************************/
1212 static char *get_request_line(struct client_state *csp)
1214 char buf[BUFFER_SIZE];
1215 char *request_line = NULL;
1218 memset(buf, 0, sizeof(buf));
1220 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1223 * If there are multiple pipelined requests waiting,
1224 * the flag will be set again once the next request
1227 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1229 request_line = get_header(csp->client_iob);
1230 if ((NULL != request_line) && ('\0' != *request_line))
1232 return request_line;
1236 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1237 "received yet. Continuing reading from %d.", csp->cfd);
1243 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1245 if (socket_is_still_alive(csp->cfd))
1247 log_error(LOG_LEVEL_CONNECT,
1248 "No request line on socket %d received in time. Timeout: %d.",
1249 csp->cfd, csp->config->socket_timeout);
1250 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1251 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1255 log_error(LOG_LEVEL_CONNECT,
1256 "The client side of the connection on socket %d got "
1257 "closed without sending a complete request line.", csp->cfd);
1262 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1264 if (len <= 0) return NULL;
1267 * If there is no memory left for buffering the
1268 * request, there is nothing we can do but hang up
1270 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1275 request_line = get_header(csp->client_iob);
1277 } while ((NULL != request_line) && ('\0' == *request_line));
1279 return request_line;
1285 CHUNK_STATUS_MISSING_DATA,
1286 CHUNK_STATUS_BODY_COMPLETE,
1287 CHUNK_STATUS_PARSE_ERROR
1291 /*********************************************************************
1293 * Function : chunked_body_is_complete
1295 * Description : Figures out wheter or not a chunked body is complete.
1297 * Currently it always starts at the beginning of the
1298 * buffer which is somewhat wasteful and prevents Privoxy
1299 * from starting to forward the correctly parsed chunks
1300 * as soon as theoretically possible.
1302 * Should be modified to work with a common buffer,
1303 * and allow the caller to skip already parsed chunks.
1305 * This would allow the function to be used for unbuffered
1306 * response bodies as well.
1309 * 1 : iob = Buffer with the body to check.
1310 * 2 : length = Length of complete body
1312 * Returns : Enum with the result of the check.
1314 *********************************************************************/
1315 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1317 unsigned int chunksize;
1323 * We need at least a single digit, followed by "\r\n",
1324 * followed by an unknown amount of data, followed by "\r\n".
1326 if (p + 5 > iob->eod)
1328 return CHUNK_STATUS_MISSING_DATA;
1330 if (sscanf(p, "%x", &chunksize) != 1)
1332 return CHUNK_STATUS_PARSE_ERROR;
1336 * We want at least a single digit, followed by "\r\n",
1337 * followed by the specified amount of data, followed by "\r\n".
1339 if (p + chunksize + 5 > iob->eod)
1341 return CHUNK_STATUS_MISSING_DATA;
1344 /* Skip chunk-size. */
1345 p = strstr(p, "\r\n");
1348 return CHUNK_STATUS_PARSE_ERROR;
1351 * Skip "\r\n", the chunk data and another "\r\n".
1352 * Moving p to either the beginning of the next chunk-size
1353 * or one byte beyond the end of the chunked data.
1355 p += 2 + chunksize + 2;
1356 } while (chunksize > 0U);
1358 *length = (size_t)(p - iob->cur);
1359 assert(*length <= (size_t)(iob->eod - iob->cur));
1360 assert(p <= iob->eod);
1362 return CHUNK_STATUS_BODY_COMPLETE;
1367 /*********************************************************************
1369 * Function : receive_chunked_client_request_body
1371 * Description : Read the chunk-encoded client request body.
1372 * Failures are dealt with.
1375 * 1 : csp = Current client state (buffers, headers, etc...)
1377 * Returns : JB_ERR_OK or JB_ERR_PARSE
1379 *********************************************************************/
1380 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1383 enum chunk_status status;
1385 while (CHUNK_STATUS_MISSING_DATA ==
1386 (status = chunked_body_is_complete(csp->client_iob,&body_length)))
1388 char buf[BUFFER_SIZE];
1391 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1393 log_error(LOG_LEVEL_ERROR,
1394 "Timeout while waiting for the client body.");
1397 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1400 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1403 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1408 if (status != CHUNK_STATUS_BODY_COMPLETE)
1410 write_socket(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1411 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE));
1412 log_error(LOG_LEVEL_CLF,
1413 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1414 return JB_ERR_PARSE;
1416 log_error(LOG_LEVEL_CONNECT,
1417 "Chunked client body completely read. Length: %d", body_length);
1418 csp->expected_client_content_length = body_length;
1424 /*********************************************************************
1426 * Function : receive_client_request
1428 * Description : Read the client's request (more precisely the
1429 * client headers) and answer it if necessary.
1432 * 1 : csp = Current client state (buffers, headers, etc...)
1434 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1436 *********************************************************************/
1437 static jb_err receive_client_request(struct client_state *csp)
1439 char buf[BUFFER_SIZE];
1442 struct http_request *http;
1446 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1447 struct list header_list;
1448 struct list *headers = &header_list;
1450 /* We don't care if the arriving data is a valid HTTP request or not. */
1451 csp->requests_received_total++;
1455 memset(buf, 0, sizeof(buf));
1457 req = get_request_line(csp);
1460 mark_server_socket_tainted(csp);
1461 return JB_ERR_PARSE;
1463 assert(*req != '\0');
1465 if (client_protocol_is_unsupported(csp, req))
1467 return JB_ERR_PARSE;
1470 #ifdef FEATURE_FORCE_LOAD
1472 * If this request contains the FORCE_PREFIX and blocks
1473 * aren't enforced, get rid of it and set the force flag.
1475 if (strstr(req, FORCE_PREFIX))
1477 if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1479 log_error(LOG_LEVEL_FORCE,
1480 "Ignored force prefix in request: \"%s\".", req);
1484 strclean(req, FORCE_PREFIX);
1485 log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1486 csp->flags |= CSP_FLAG_FORCED;
1489 #endif /* def FEATURE_FORCE_LOAD */
1491 err = parse_http_request(req, http);
1493 if (JB_ERR_OK != err)
1495 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1496 /* XXX: Use correct size */
1497 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1498 log_error(LOG_LEVEL_ERROR,
1499 "Couldn't parse request line received from %s: %s",
1500 csp->ip_addr_str, jb_err_to_string(err));
1502 free_http_request(http);
1503 return JB_ERR_PARSE;
1506 /* grab the rest of the client's headers */
1510 p = get_header(csp->client_iob);
1514 /* There are no additional headers to read. */
1521 * We didn't receive a complete header
1522 * line yet, get the rest of it.
1524 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1526 log_error(LOG_LEVEL_ERROR,
1527 "Stopped grabbing the client headers.");
1528 destroy_list(headers);
1529 return JB_ERR_PARSE;
1532 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1535 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1536 destroy_list(headers);
1537 return JB_ERR_PARSE;
1540 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1543 * If there is no memory left for buffering the
1544 * request, there is nothing we can do but hang up
1546 destroy_list(headers);
1547 return JB_ERR_MEMORY;
1552 if (!strncmpic(p, "Transfer-Encoding:", 18))
1555 * XXX: should be called through sed()
1556 * but currently can't.
1558 client_transfer_encoding(csp, &p);
1561 * We were able to read a complete
1562 * header and can finally enlist it.
1569 if (http->host == NULL)
1572 * If we still don't know the request destination,
1573 * the request is invalid or the client uses
1574 * Privoxy without its knowledge.
1576 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1579 * Our attempts to get the request destination
1580 * elsewhere failed or Privoxy is configured
1581 * to only accept proxy requests.
1583 * An error response has already been send
1584 * and we're done here.
1586 return JB_ERR_PARSE;
1591 * Determine the actions for this URL
1593 #ifdef FEATURE_TOGGLE
1594 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1596 /* Most compatible set of actions (i.e. none) */
1597 init_current_action(csp->action);
1600 #endif /* ndef FEATURE_TOGGLE */
1602 get_url_actions(csp, http);
1606 * Save a copy of the original request for logging
1608 http->ocmd = strdup_or_die(http->cmd);
1609 enlist(csp->headers, http->cmd);
1611 /* Append the previously read headers */
1612 list_append_list_unique(csp->headers, headers);
1613 destroy_list(headers);
1620 /*********************************************************************
1622 * Function : parse_client_request
1624 * Description : Parses the client's request and decides what to do
1627 * Note that since we're not using select() we could get
1628 * blocked here if a client connected, then didn't say
1632 * 1 : csp = Current client state (buffers, headers, etc...)
1634 * Returns : JB_ERR_OK or JB_ERR_PARSE
1636 *********************************************************************/
1637 static jb_err parse_client_request(struct client_state *csp)
1639 struct http_request *http = csp->http;
1642 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1643 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1644 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1645 && (csp->http->ssl == 0))
1647 /* Assume persistence until further notice */
1648 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1651 if (csp->http->ssl == 0)
1654 * This whole block belongs to chat() but currently
1655 * has to be executed before sed().
1657 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1659 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1661 return JB_ERR_PARSE;
1666 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1668 verify_request_length(csp);
1670 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1672 err = sed(csp, FILTER_CLIENT_HEADERS);
1673 if (JB_ERR_OK != err)
1675 /* XXX: Should be handled in sed(). */
1676 assert(err == JB_ERR_PARSE);
1677 log_error(LOG_LEVEL_FATAL, "Failed to parse client headers.");
1679 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1681 /* Check request line for rewrites. */
1682 if ((NULL == csp->headers->first->str)
1683 || (strcmp(http->cmd, csp->headers->first->str) &&
1684 (JB_ERR_OK != change_request_destination(csp))))
1687 * A header filter broke the request line - bail out.
1689 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1690 /* XXX: Use correct size */
1691 log_error(LOG_LEVEL_CLF,
1692 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1693 log_error(LOG_LEVEL_ERROR,
1694 "Invalid request line after applying header filters.");
1695 free_http_request(http);
1697 return JB_ERR_PARSE;
1705 /*********************************************************************
1709 * Description : Once a connection from the client has been accepted,
1710 * this function is called (via serve()) to handle the
1711 * main business of the communication. This function
1712 * returns after dealing with a single request. It can
1713 * be called multiple times with the same client socket
1714 * if the client is keeping the connection alive.
1716 * The decision whether or not a client connection will
1717 * be kept alive is up to the caller which also must
1718 * close the client socket when done.
1720 * FIXME: chat is nearly thousand lines long.
1724 * 1 : csp = Current client state (buffers, headers, etc...)
1726 * Returns : Nothing.
1728 *********************************************************************/
1729 static void chat(struct client_state *csp)
1731 char buf[BUFFER_SIZE];
1738 int ms_iis5_hack = 0;
1739 unsigned long long byte_count = 0;
1740 const struct forward_spec *fwd;
1741 struct http_request *http;
1742 long len = 0; /* for buffer sizes (and negative error codes) */
1743 int buffer_and_filter_content = 0;
1745 /* Skeleton for HTTP response, if we should intercept the request */
1746 struct http_response *rsp;
1747 struct timeval timeout;
1748 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1749 int watch_client_socket;
1752 memset(buf, 0, sizeof(buf));
1756 if (receive_client_request(csp) != JB_ERR_OK)
1760 if (parse_client_request(csp) != JB_ERR_OK)
1765 /* decide how to route the HTTP request */
1766 fwd = forward_url(csp, http);
1769 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1770 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1775 * build the http request to send to the server
1776 * we have to do one of the following:
1778 * create = use the original HTTP request to create a new
1779 * HTTP request that has either the path component
1780 * without the http://domainspec (w/path) or the
1781 * full orininal URL (w/url)
1782 * Note that the path and/or the HTTP version may
1783 * have been altered by now.
1785 * connect = Open a socket to the host:port of the server
1786 * and short-circuit server and client socket.
1788 * pass = Pass the request unchanged if forwarding a CONNECT
1789 * request to a parent proxy. Note that we'll be sending
1790 * the CFAIL message ourselves if connecting to the parent
1791 * fails, but we won't send a CSUCCEED message if it works,
1792 * since that would result in a double message (ours and the
1793 * parent's). After sending the request to the parent, we simply
1796 * here's the matrix:
1799 * +--------+--------+
1801 * 0 | create | connect|
1803 * Forwarding +--------+--------+
1805 * 1 | create | pass |
1807 * +--------+--------+
1811 if (http->ssl && connect_port_is_forbidden(csp))
1813 const char *acceptable_connect_ports =
1814 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1815 assert(NULL != acceptable_connect_ports);
1816 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1817 "limit-connect{%s} doesn't allow CONNECT requests to %s",
1818 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
1819 csp->action->flags |= ACTION_BLOCK;
1825 freez(csp->headers->first->str);
1826 build_request_line(csp, fwd, &csp->headers->first->str);
1830 * We have a request. Check if one of the crunchers wants it.
1832 if (crunch_response_triggered(csp, crunchers_all))
1835 * Yes. The client got the crunch response and we're done here.
1840 log_applied_actions(csp->action);
1841 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1843 if (fwd->forward_host)
1845 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1846 fwd->forward_host, fwd->forward_port, http->hostport);
1850 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1853 /* here we connect to the server, gateway, or the forwarder */
1855 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1856 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
1857 && socket_is_still_alive(csp->server_connection.sfd)
1858 && connection_destination_matches(&csp->server_connection, http, fwd))
1860 log_error(LOG_LEVEL_CONNECT,
1861 "Reusing server socket %d connected to %s. Total requests: %u.",
1862 csp->server_connection.sfd, csp->server_connection.host,
1863 csp->server_connection.requests_sent_total);
1867 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
1869 #ifdef FEATURE_CONNECTION_SHARING
1870 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1872 remember_connection(&csp->server_connection);
1875 #endif /* def FEATURE_CONNECTION_SHARING */
1877 log_error(LOG_LEVEL_CONNECT,
1878 "Closing server socket %d connected to %s. Total requests: %u.",
1879 csp->server_connection.sfd, csp->server_connection.host,
1880 csp->server_connection.requests_sent_total);
1881 close_socket(csp->server_connection.sfd);
1883 mark_connection_closed(&csp->server_connection);
1885 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1887 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
1889 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
1891 if (fwd->type != SOCKS_NONE)
1894 rsp = error_response(csp, "forwarding-failed");
1896 else if (errno == EINVAL)
1898 rsp = error_response(csp, "no-such-domain");
1902 rsp = error_response(csp, "connect-failed");
1905 /* Write the answer to the client */
1908 send_crunch_response(csp, rsp);
1913 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1914 save_connection_destination(csp->server_connection.sfd,
1915 http, fwd, &csp->server_connection);
1916 csp->server_connection.keep_alive_timeout =
1917 (unsigned)csp->config->keep_alive_timeout;
1919 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1921 csp->server_connection.requests_sent_total++;
1923 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
1925 /* Client headers have been sent optimistically */
1926 assert(csp->headers->last == NULL);
1928 else if (fwd->forward_host || (http->ssl == 0))
1931 hdr = list_to_text(csp->headers);
1934 /* FIXME Should handle error properly */
1935 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1937 list_remove_all(csp->headers);
1940 * Write the client's (modified) header to the server
1941 * (along with anything else that may be in the buffer)
1943 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
1948 log_error(LOG_LEVEL_CONNECT,
1949 "Failed sending request headers to: %s: %E", http->hostport);
1951 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
1952 && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
1955 log_error(LOG_LEVEL_CONNECT,
1956 "Failed sending request body to: %s: %E", http->hostport);
1961 rsp = error_response(csp, "connect-failed");
1964 send_crunch_response(csp, rsp);
1972 * We're running an SSL tunnel and we're not forwarding,
1973 * so just ditch the client headers, send the "connect succeeded"
1974 * message to the client, flush the rest, and get out of the way.
1976 list_remove_all(csp->headers);
1977 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
1981 clear_iob(csp->client_iob);
1984 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
1986 /* XXX: should the time start earlier for optimistically sent data? */
1987 csp->server_connection.request_sent = time(NULL);
1989 maxfd = (csp->cfd > csp->server_connection.sfd) ?
1990 csp->cfd : csp->server_connection.sfd;
1992 /* pass data between the client and server
1993 * until one or the other shuts down the connection.
1998 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1999 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2006 * FD_ZERO here seems to point to an errant macro which crashes.
2007 * So do this by hand for now...
2009 memset(&rfds,0x00,sizeof(fd_set));
2013 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2014 if (!watch_client_socket)
2016 maxfd = csp->server_connection.sfd;
2019 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2021 FD_SET(csp->cfd, &rfds);
2024 FD_SET(csp->server_connection.sfd, &rfds);
2026 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2027 if ((csp->flags & CSP_FLAG_CHUNKED)
2028 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2029 && ((csp->iob->eod - csp->iob->cur) >= 5)
2030 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2033 * XXX: This check should be obsolete now,
2034 * but let's wait a while to be sure.
2036 log_error(LOG_LEVEL_CONNECT,
2037 "Looks like we got the last chunk together with "
2038 "the server headers but didn't detect it earlier. "
2039 "We better stop reading.");
2040 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2041 csp->expected_content_length = byte_count;
2042 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2044 if (server_body && server_response_is_complete(csp, byte_count))
2046 if (csp->expected_content_length == byte_count)
2048 log_error(LOG_LEVEL_CONNECT,
2049 "Done reading from server. Content length: %llu as expected. "
2050 "Bytes most recently read: %d.",
2055 log_error(LOG_LEVEL_CONNECT,
2056 "Done reading from server. Expected content length: %llu. "
2057 "Actual content length: %llu. Bytes most recently read: %d.",
2058 csp->expected_content_length, byte_count, len);
2062 * XXX: should not jump around,
2063 * chat() is complicated enough already.
2067 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2069 timeout.tv_sec = csp->config->socket_timeout;
2070 timeout.tv_usec = 0;
2071 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2075 log_error(LOG_LEVEL_ERROR,
2076 "Didn't receive data in time: %s", http->url);
2077 if ((byte_count == 0) && (http->ssl == 0))
2079 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2081 mark_server_socket_tainted(csp);
2086 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2087 mark_server_socket_tainted(csp);
2092 * This is the body of the browser's request,
2093 * just read and write it.
2095 * XXX: Make sure the client doesn't use pipelining
2096 * behind Privoxy's back.
2098 if (FD_ISSET(csp->cfd, &rfds))
2100 int max_bytes_to_read = sizeof(buf) - 1;
2102 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2103 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2105 if (data_is_available(csp->cfd, 0))
2108 * If the next request is already waiting, we have
2109 * to stop select()ing the client socket. Otherwise
2110 * we would always return right away and get nothing
2113 watch_client_socket = 0;
2114 log_error(LOG_LEVEL_CONNECT,
2115 "Stopping to watch the client socket %d. "
2116 "There's already another request waiting.",
2121 * If the client socket is set, but there's no data
2122 * available on the socket, the client went fishing
2123 * and continuing talking to the server makes no sense.
2125 log_error(LOG_LEVEL_CONNECT,
2126 "The client closed socket %d while "
2127 "the server socket %d is still open.",
2128 csp->cfd, csp->server_connection.sfd);
2129 mark_server_socket_tainted(csp);
2132 if (csp->expected_client_content_length != 0)
2134 if (csp->expected_client_content_length < (sizeof(buf) - 1))
2136 max_bytes_to_read = (int)csp->expected_client_content_length;
2138 log_error(LOG_LEVEL_CONNECT,
2139 "Waiting for up to %d bytes from the client.",
2142 assert(max_bytes_to_read < sizeof(buf));
2143 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2145 len = read_socket(csp->cfd, buf, max_bytes_to_read);
2149 /* XXX: not sure if this is necessary. */
2150 mark_server_socket_tainted(csp);
2151 break; /* "game over, man" */
2154 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2155 if (csp->expected_client_content_length != 0)
2157 assert(len <= max_bytes_to_read);
2158 csp->expected_client_content_length -= (unsigned)len;
2159 log_error(LOG_LEVEL_CONNECT,
2160 "Expected client content length set to %llu "
2161 "after reading %d bytes.",
2162 csp->expected_client_content_length, len);
2163 if (csp->expected_client_content_length == 0)
2165 log_error(LOG_LEVEL_CONNECT,
2166 "Done reading from the client.");
2167 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2170 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2172 if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
2174 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2175 mark_server_socket_tainted(csp);
2182 * The server wants to talk. It could be the header or the body.
2183 * If `hdr' is null, then it's the header otherwise it's the body.
2184 * FIXME: Does `hdr' really mean `host'? No.
2186 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2188 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2190 * If we are buffering content, we don't want to eat up to
2191 * buffer-limit bytes if the client no longer cares about them.
2192 * If we aren't buffering, however, a dead client socket will be
2193 * noticed pretty much right away anyway, so we can reduce the
2194 * overhead by skipping the check.
2196 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2199 log_error(LOG_LEVEL_CONNECT,
2200 "The server still wants to talk, but the client may already have hung up on us.");
2202 log_error(LOG_LEVEL_CONNECT,
2203 "The server still wants to talk, but the client hung up on us.");
2204 mark_server_socket_tainted(csp);
2206 #endif /* def _WIN32 */
2208 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2210 len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
2214 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2216 if (http->ssl && (fwd->forward_host == NULL))
2219 * Just hang up. We already confirmed the client's CONNECT
2220 * request with status code 200 and unencrypted content is
2221 * no longer welcome.
2223 log_error(LOG_LEVEL_ERROR,
2224 "CONNECT already confirmed. Unable to tell the client about the problem.");
2227 else if (byte_count)
2230 * Just hang up. We already transmitted the original headers
2231 * and parts of the original content and therefore missed the
2232 * chance to send an error message (without risking data corruption).
2234 * XXX: we could retry with a fancy range request here.
2236 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2237 "Unable to tell the client about the problem.");
2238 mark_server_socket_tainted(csp);
2242 * XXX: Consider handling the cases above the same.
2244 mark_server_socket_tainted(csp);
2248 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2249 if (csp->flags & CSP_FLAG_CHUNKED)
2251 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2253 /* XXX: this is a temporary hack */
2254 log_error(LOG_LEVEL_CONNECT,
2255 "Looks like we reached the end of the last chunk. "
2256 "We better stop reading.");
2257 csp->expected_content_length = byte_count + (unsigned long long)len;
2258 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2262 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2265 * Add a trailing zero to let be able to use string operations.
2266 * XXX: do we still need this with filter_popups gone?
2271 * Normally, this would indicate that we've read
2272 * as much as the server has sent us and we can
2273 * close the client connection. However, Microsoft
2274 * in its wisdom has released IIS/5 with a bug that
2275 * prevents it from sending the trailing \r\n in
2276 * a 302 redirect header (and possibly other headers).
2277 * To work around this if we've haven't parsed
2278 * a full header we'll append a trailing \r\n
2279 * and see if this now generates a valid one.
2281 * This hack shouldn't have any impacts. If we've
2282 * already transmitted the header or if this is a
2283 * SSL connection, then we won't bother with this
2284 * hack. So we only work on partially received
2285 * headers. If we append a \r\n and this still
2286 * doesn't generate a valid header, then we won't
2287 * transmit anything to the client.
2292 if (server_body || http->ssl)
2295 * If we have been buffering up the document,
2296 * now is the time to apply content modification
2297 * and send the result to the client.
2299 if (buffer_and_filter_content)
2301 p = execute_content_filters(csp);
2303 * If content filtering fails, use the original
2304 * buffer and length.
2305 * (see p != NULL ? p : csp->iob->cur below)
2309 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2311 #ifdef FEATURE_COMPRESSION
2312 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2313 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2315 char *compressed_content = compress_buffer(p,
2316 (size_t *)&csp->content_length, csp->config->compression_level);
2317 if (compressed_content != NULL)
2320 p = compressed_content;
2321 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2326 if (JB_ERR_OK != update_server_headers(csp))
2328 log_error(LOG_LEVEL_FATAL,
2329 "Failed to update server headers. after filtering.");
2332 hdr = list_to_text(csp->headers);
2335 /* FIXME Should handle error properly */
2336 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2339 if (write_socket(csp->cfd, hdr, strlen(hdr))
2340 || write_socket(csp->cfd,
2341 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2343 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2346 mark_server_socket_tainted(csp);
2354 break; /* "game over, man" */
2358 * This is NOT the body, so
2359 * Let's pretend the server just sent us a blank line.
2361 snprintf(buf, sizeof(buf), "\r\n");
2362 len = (int)strlen(buf);
2365 * Now, let the normal header parsing algorithm below do its
2366 * job. If it fails, we'll exit instead of continuing.
2373 * If this is an SSL connection or we're in the body
2374 * of the server document, just write it to the client,
2375 * unless we need to buffer the body for later content-filtering
2377 if (server_body || http->ssl)
2379 if (buffer_and_filter_content)
2382 * If there is no memory left for buffering the content, or the buffer limit
2383 * has been reached, switch to non-filtering mode, i.e. make & write the
2384 * header, flush the iob and buf, and get out of the way.
2386 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2391 log_error(LOG_LEVEL_INFO,
2392 "Flushing header and buffers. Stepping back from filtering.");
2394 hdr = list_to_text(csp->headers);
2398 * Memory is too tight to even generate the header.
2399 * Send our static "Out-of-memory" page.
2401 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2402 rsp = cgi_error_memory();
2403 send_crunch_response(csp, rsp);
2404 mark_server_socket_tainted(csp);
2407 hdrlen = strlen(hdr);
2409 if (write_socket(csp->cfd, hdr, hdrlen)
2410 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2411 || (write_socket(csp->cfd, buf, (size_t)len)))
2413 log_error(LOG_LEVEL_CONNECT,
2414 "Flush header and buffers to client failed: %E");
2416 mark_server_socket_tainted(csp);
2421 * Reset the byte_count to the amount of bytes
2422 * we just flushed. len will be added a few lines below,
2423 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2425 byte_count = (unsigned long long)flushed;
2427 buffer_and_filter_content = 0;
2433 if (write_socket(csp->cfd, buf, (size_t)len))
2435 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2436 mark_server_socket_tainted(csp);
2440 byte_count += (unsigned long long)len;
2446 * We're still looking for the end of the server's header.
2447 * Buffer up the data we just read. If that fails, there's
2448 * little we can do but send our static out-of-memory page.
2450 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2452 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2453 rsp = cgi_error_memory();
2454 send_crunch_response(csp, rsp);
2455 mark_server_socket_tainted(csp);
2459 /* Convert iob into something sed() can digest */
2460 if (JB_ERR_PARSE == get_server_headers(csp))
2465 * Well, we tried our MS IIS/5 hack and it didn't work.
2466 * The header is incomplete and there isn't anything
2467 * we can do about it.
2469 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2470 "Applying the MS IIS5 hack didn't help.");
2471 log_error(LOG_LEVEL_CLF,
2472 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2473 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2474 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2475 mark_server_socket_tainted(csp);
2481 * Since we have to wait for more from the server before
2482 * we can parse the headers we just continue here.
2484 log_error(LOG_LEVEL_CONNECT,
2485 "Continuing buffering server headers from socket %d. "
2486 "Bytes most recently read: %d.", csp->cfd, len);
2493 * Account for the content bytes we
2494 * might have gotten with the headers.
2496 assert(csp->iob->eod >= csp->iob->cur);
2497 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2500 /* Did we actually get anything? */
2501 if (NULL == csp->headers->first)
2503 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2505 log_error(LOG_LEVEL_ERROR,
2506 "No server or forwarder response received on socket %d. "
2507 "Closing client socket %d without sending data.",
2508 csp->server_connection.sfd, csp->cfd);
2509 log_error(LOG_LEVEL_CLF,
2510 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2514 log_error(LOG_LEVEL_ERROR,
2515 "No server or forwarder response received on socket %d.",
2516 csp->server_connection.sfd);
2517 send_crunch_response(csp, error_response(csp, "no-server-data"));
2519 free_http_request(http);
2520 mark_server_socket_tainted(csp);
2524 assert(csp->headers->first->str);
2526 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2527 strncmpic(csp->headers->first->str, "ICY", 3))
2530 * It doesn't look like a HTTP (or Shoutcast) response:
2531 * tell the client and log the problem.
2533 if (strlen(csp->headers->first->str) > 30)
2535 csp->headers->first->str[30] = '\0';
2537 log_error(LOG_LEVEL_ERROR,
2538 "Invalid server or forwarder response. Starts with: %s",
2539 csp->headers->first->str);
2540 log_error(LOG_LEVEL_CLF,
2541 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2542 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2543 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2544 free_http_request(http);
2545 mark_server_socket_tainted(csp);
2550 * We have now received the entire server header,
2551 * filter it and send the result to the client
2553 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2555 log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2557 hdr = list_to_text(csp->headers);
2560 /* FIXME Should handle error properly */
2561 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2564 if ((csp->flags & CSP_FLAG_CHUNKED)
2565 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2566 && ((csp->iob->eod - csp->iob->cur) >= 5)
2567 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2569 log_error(LOG_LEVEL_CONNECT,
2570 "Looks like we got the last chunk together with "
2571 "the server headers. We better stop reading.");
2572 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2573 csp->expected_content_length = byte_count;
2574 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2577 csp->server_connection.response_received = time(NULL);
2579 if (crunch_response_triggered(csp, crunchers_light))
2582 * One of the tags created by a server-header
2583 * tagger triggered a crunch. We already
2584 * delivered the crunch response to the client
2585 * and are done here after cleaning up.
2588 mark_server_socket_tainted(csp);
2591 /* Buffer and pcrs filter this if appropriate. */
2593 if (!http->ssl) /* We talk plaintext */
2595 buffer_and_filter_content = content_requires_filtering(csp);
2598 * Only write if we're not buffering for content modification
2600 if (!buffer_and_filter_content)
2603 * Write the server's (modified) header to
2604 * the client (along with anything else that
2605 * may be in the buffer)
2608 if (write_socket(csp->cfd, hdr, strlen(hdr))
2609 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2611 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2614 * The write failed, so don't bother mentioning it
2615 * to the client... it probably can't hear us anyway.
2618 mark_server_socket_tainted(csp);
2623 /* we're finished with the server's header */
2629 * If this was a MS IIS/5 hack then it means the server
2630 * has already closed the connection. Nothing more to read.
2635 log_error(LOG_LEVEL_ERROR,
2636 "Closed server connection detected. "
2637 "Applying the MS IIS5 hack didn't help.");
2638 log_error(LOG_LEVEL_CLF,
2639 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2640 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2641 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2642 mark_server_socket_tainted(csp);
2648 mark_server_socket_tainted(csp);
2649 return; /* huh? we should never get here */
2652 if (csp->content_length == 0)
2655 * If Privoxy didn't recalculate the Content-Length,
2656 * byte_count is still correct.
2658 csp->content_length = byte_count;
2661 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2662 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2663 && (csp->expected_content_length != byte_count))
2665 log_error(LOG_LEVEL_CONNECT,
2666 "Received %llu bytes while expecting %llu.",
2667 byte_count, csp->expected_content_length);
2668 mark_server_socket_tainted(csp);
2672 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2673 csp->ip_addr_str, http->ocmd, csp->content_length);
2675 csp->server_connection.timestamp = time(NULL);
2679 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2680 /*********************************************************************
2682 * Function : prepare_csp_for_next_request
2684 * Description : Put the csp in a mostly vergin state.
2687 * 1 : csp = Current client state (buffers, headers, etc...)
2691 *********************************************************************/
2692 static void prepare_csp_for_next_request(struct client_state *csp)
2694 unsigned int toggled_on_flag_set = (0 != (csp->flags & CSP_FLAG_TOGGLED_ON));
2696 csp->content_type = 0;
2697 csp->content_length = 0;
2698 csp->expected_content_length = 0;
2699 csp->expected_client_content_length = 0;
2700 list_remove_all(csp->headers);
2701 clear_iob(csp->iob);
2702 freez(csp->error_message);
2703 free_http_request(csp->http);
2704 destroy_list(csp->headers);
2705 destroy_list(csp->tags);
2706 free_current_action(csp->action);
2707 if (NULL != csp->fwd)
2709 unload_forward_spec(csp->fwd);
2712 /* XXX: Store per-connection flags someplace else. */
2713 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
2714 if (toggled_on_flag_set)
2716 csp->flags |= CSP_FLAG_TOGGLED_ON;
2719 if (csp->client_iob->eod > csp->client_iob->cur)
2721 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
2722 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2724 assert(bytes_to_shift > 0);
2725 assert(data_length > 0);
2727 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
2728 data_length, bytes_to_shift);
2729 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
2730 csp->client_iob->cur = csp->client_iob->buf;
2731 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
2732 csp->client_iob->eod = csp->client_iob->buf + data_length;
2733 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
2735 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
2740 * We mainly care about resetting client_iob->cur so we don't
2741 * waste buffer space at the beginning and don't mess up the
2742 * request restoration done by cgi_show_request().
2744 * Freeing the buffer itself isn't technically necessary,
2745 * but makes debugging more convenient.
2747 clear_iob(csp->client_iob);
2750 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2753 /*********************************************************************
2757 * Description : This is little more than chat. We only "serve" to
2758 * to close (or remember) any socket that chat may have
2762 * 1 : csp = Current client state (buffers, headers, etc...)
2766 *********************************************************************/
2768 void serve(struct client_state *csp)
2769 #else /* ifndef AMIGA */
2770 static void serve(struct client_state *csp)
2771 #endif /* def AMIGA */
2773 int config_file_change_detected = 0; /* Only used for debugging */
2774 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2775 #ifdef FEATURE_CONNECTION_SHARING
2776 static int monitor_thread_running = 0;
2777 #endif /* def FEATURE_CONNECTION_SHARING */
2778 int continue_chatting = 0;
2780 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
2781 csp->ip_addr_str, csp->cfd);
2785 unsigned int latency;
2790 * If the request has been crunched,
2791 * the calculated latency is zero.
2793 latency = (unsigned)(csp->server_connection.response_received -
2794 csp->server_connection.request_sent) / 2;
2796 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2797 && (csp->flags & CSP_FLAG_CRUNCHED)
2798 && (csp->expected_client_content_length != 0))
2800 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
2801 log_error(LOG_LEVEL_CONNECT,
2802 "Tainting client socket %d due to unread data.", csp->cfd);
2805 continue_chatting = (csp->config->feature_flags
2806 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2807 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2808 && (csp->cfd != JB_INVALID_SOCKET)
2809 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2810 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
2811 || (csp->flags & CSP_FLAG_CHUNKED));
2813 if (!(csp->flags & CSP_FLAG_CRUNCHED)
2814 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
2816 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
2818 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
2820 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2821 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2822 || !socket_is_still_alive(csp->server_connection.sfd)
2823 || !(latency < csp->server_connection.keep_alive_timeout))
2825 log_error(LOG_LEVEL_CONNECT,
2826 "Closing server socket %d connected to %s. "
2827 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
2828 csp->server_connection.sfd, csp->server_connection.host,
2829 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2830 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2831 socket_is_still_alive(csp->server_connection.sfd),
2832 csp->server_connection.keep_alive_timeout);
2833 #ifdef FEATURE_CONNECTION_SHARING
2834 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2836 forget_connection(csp->server_connection.sfd);
2838 #endif /* def FEATURE_CONNECTION_SHARING */
2839 close_socket(csp->server_connection.sfd);
2840 mark_connection_closed(&csp->server_connection);
2844 if (continue_chatting && any_loaded_file_changed(csp))
2846 continue_chatting = 0;
2847 config_file_change_detected = 1;
2850 if (continue_chatting)
2852 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
2853 && socket_is_still_alive(csp->cfd))
2855 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
2856 "pipelined on socket %d and the socket is still alive.",
2857 csp->requests_received_total+1, csp->cfd);
2858 prepare_csp_for_next_request(csp);
2862 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
2864 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2866 log_error(LOG_LEVEL_CONNECT,
2867 "Waiting for the next client request on socket %d. "
2868 "Keeping the server socket %d to %s open.",
2869 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2873 log_error(LOG_LEVEL_CONNECT,
2874 "Waiting for the next client request on socket %d. "
2875 "No server socket to keep open.", csp->cfd);
2879 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2880 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
2881 && socket_is_still_alive(csp->cfd))
2883 log_error(LOG_LEVEL_CONNECT,
2884 "Client request %u arrived in time on socket %d.",
2885 csp->requests_received_total+1, csp->cfd);
2886 prepare_csp_for_next_request(csp);
2890 #ifdef FEATURE_CONNECTION_SHARING
2891 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2892 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
2893 && (socket_is_still_alive(csp->server_connection.sfd)))
2895 time_t time_open = time(NULL) - csp->server_connection.timestamp;
2897 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
2902 remember_connection(&csp->server_connection);
2903 csp->server_connection.sfd = JB_INVALID_SOCKET;
2904 drain_and_close_socket(csp->cfd);
2905 csp->cfd = JB_INVALID_SOCKET;
2906 privoxy_mutex_lock(&connection_reuse_mutex);
2907 if (!monitor_thread_running)
2909 monitor_thread_running = 1;
2910 privoxy_mutex_unlock(&connection_reuse_mutex);
2911 wait_for_alive_connections();
2912 privoxy_mutex_lock(&connection_reuse_mutex);
2913 monitor_thread_running = 0;
2915 privoxy_mutex_unlock(&connection_reuse_mutex);
2917 #endif /* def FEATURE_CONNECTION_SHARING */
2921 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2923 log_error(LOG_LEVEL_CONNECT,
2924 "Closing server socket %d connected to %s. Keep-alive: %u. "
2925 "Tainted: %u. Socket alive: %u. Timeout: %u. "
2926 "Configuration file change detected: %u",
2927 csp->server_connection.sfd, csp->server_connection.host,
2928 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2929 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2930 socket_is_still_alive(csp->server_connection.sfd),
2931 csp->server_connection.keep_alive_timeout,
2932 config_file_change_detected);
2934 } while (continue_chatting);
2938 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2940 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2942 #ifdef FEATURE_CONNECTION_SHARING
2943 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2945 forget_connection(csp->server_connection.sfd);
2947 #endif /* def FEATURE_CONNECTION_SHARING */
2948 close_socket(csp->server_connection.sfd);
2951 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2952 mark_connection_closed(&csp->server_connection);
2955 if (csp->cfd != JB_INVALID_SOCKET)
2957 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
2958 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
2959 "Configuration file change detected: %u. Requests received: %u.",
2960 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
2961 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
2962 config_file_change_detected, csp->requests_received_total);
2963 drain_and_close_socket(csp->cfd);
2966 csp->flags &= ~CSP_FLAG_ACTIVE;
2972 /*********************************************************************
2974 * Function : server_thread
2976 * Description : We only exist to call `serve' in a threaded environment.
2979 * 1 : data = Current client state (buffers, headers, etc...)
2981 * Returns : Always 0.
2983 *********************************************************************/
2984 static int32 server_thread(void *data)
2986 serve((struct client_state *) data);
2993 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2994 /*********************************************************************
2998 * Description : Print usage info & exit.
3000 * Parameters : Pointer to argv[0] for identifying ourselves
3004 *********************************************************************/
3005 static void usage(const char *myname)
3007 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3008 "Usage: %s [--config-test] "
3011 #endif /* defined(unix) */
3014 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3015 #endif /* defined(unix) */
3016 "[--version] [configfile]\n"
3017 "Aborting\n", myname);
3022 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3025 #ifdef MUTEX_LOCKS_AVAILABLE
3026 /*********************************************************************
3028 * Function : privoxy_mutex_lock
3030 * Description : Locks a mutex.
3033 * 1 : mutex = The mutex to lock.
3035 * Returns : Void. May exit in case of errors.
3037 *********************************************************************/
3038 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3040 #ifdef FEATURE_PTHREAD
3041 int err = pthread_mutex_lock(mutex);
3044 if (mutex != &log_mutex)
3046 log_error(LOG_LEVEL_FATAL,
3047 "Mutex locking failed: %s.\n", strerror(err));
3052 EnterCriticalSection(mutex);
3053 #endif /* def FEATURE_PTHREAD */
3057 /*********************************************************************
3059 * Function : privoxy_mutex_unlock
3061 * Description : Unlocks a mutex.
3064 * 1 : mutex = The mutex to unlock.
3066 * Returns : Void. May exit in case of errors.
3068 *********************************************************************/
3069 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3071 #ifdef FEATURE_PTHREAD
3072 int err = pthread_mutex_unlock(mutex);
3075 if (mutex != &log_mutex)
3077 log_error(LOG_LEVEL_FATAL,
3078 "Mutex unlocking failed: %s.\n", strerror(err));
3083 LeaveCriticalSection(mutex);
3084 #endif /* def FEATURE_PTHREAD */
3088 /*********************************************************************
3090 * Function : privoxy_mutex_init
3092 * Description : Prepares a mutex.
3095 * 1 : mutex = The mutex to initialize.
3097 * Returns : Void. May exit in case of errors.
3099 *********************************************************************/
3100 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3102 #ifdef FEATURE_PTHREAD
3103 int err = pthread_mutex_init(mutex, 0);
3106 printf("Fatal error. Mutex initialization failed: %s.\n",
3111 InitializeCriticalSection(mutex);
3112 #endif /* def FEATURE_PTHREAD */
3114 #endif /* def MUTEX_LOCKS_AVAILABLE */
3116 /*********************************************************************
3118 * Function : initialize_mutexes
3120 * Description : Prepares mutexes if mutex support is available.
3124 * Returns : Void, exits in case of errors.
3126 *********************************************************************/
3127 static void initialize_mutexes(void)
3129 #ifdef MUTEX_LOCKS_AVAILABLE
3131 * Prepare global mutex semaphores
3133 privoxy_mutex_init(&log_mutex);
3134 privoxy_mutex_init(&log_init_mutex);
3135 privoxy_mutex_init(&connection_reuse_mutex);
3138 * XXX: The assumptions below are a bit naive
3139 * and can cause locks that aren't necessary.
3141 * For example older FreeBSD versions (< 6.x?)
3142 * have no gethostbyname_r, but gethostbyname is
3145 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3146 privoxy_mutex_init(&resolver_mutex);
3147 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3149 * XXX: should we use a single mutex for
3150 * localtime() and gmtime() as well?
3152 #ifndef HAVE_GMTIME_R
3153 privoxy_mutex_init(&gmtime_mutex);
3154 #endif /* ndef HAVE_GMTIME_R */
3156 #ifndef HAVE_LOCALTIME_R
3157 privoxy_mutex_init(&localtime_mutex);
3158 #endif /* ndef HAVE_GMTIME_R */
3161 privoxy_mutex_init(&rand_mutex);
3162 #endif /* ndef HAVE_RANDOM */
3164 #endif /* def MUTEX_LOCKS_AVAILABLE */
3168 /*********************************************************************
3172 * Description : Load the config file and start the listen loop.
3173 * This function is a lot more *sane* with the `load_config'
3174 * and `listen_loop' functions; although it stills does
3175 * a *little* too much for my taste.
3178 * 1 : argc = Number of parameters (including $0).
3179 * 2 : argv = Array of (char *)'s to the parameters.
3181 * Returns : 1 if : can't open config file, unrecognized directive,
3182 * stats requested in multi-thread mode, can't open the
3183 * log file, can't open the jar file, listen port is invalid,
3184 * any load fails, and can't bind port.
3186 * Else main never returns, the process must be signaled
3187 * to terminate execution. Or, on Windows, use the
3188 * "File", "Exit" menu option.
3190 *********************************************************************/
3192 int real_main(int argc, char **argv)
3194 int main(int argc, char **argv)
3198 int do_config_test = 0;
3199 unsigned int random_seed;
3201 struct passwd *pw = NULL;
3202 struct group *grp = NULL;
3204 char *pre_chroot_nslookup_to_load_resolver = NULL;
3211 #if !defined(_WIN32)
3218 /* Prepare mutexes if supported and necessary. */
3219 initialize_mutexes();
3221 /* Enable logging until further notice. */
3225 * Parse the command line arguments
3227 * XXX: simply printing usage information in case of
3228 * invalid arguments isn't particularly user friendly.
3230 while (++argc_pos < argc)
3233 /* Check to see if the service must be installed or uninstalled */
3234 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3236 const char *pName = argv[argc_pos] + 9;
3239 exit((install_service(pName)) ? 0 : 1);
3241 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3243 const char *pName = argv[argc_pos] + 11;
3246 exit((uninstall_service(pName)) ? 0 : 1);
3248 else if (strcmp(argv[argc_pos], "--service") == 0)
3250 bRunAsService = TRUE;
3251 w32_set_service_cwd();
3252 atexit(w32_service_exit_notify);
3255 #endif /* defined(_WIN32) */
3258 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3260 if (strcmp(argv[argc_pos], "--help") == 0)
3265 else if (strcmp(argv[argc_pos], "--version") == 0)
3267 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3273 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3275 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3279 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3281 if (++argc_pos == argc) usage(argv[0]);
3282 pidfile = strdup_or_die(argv[argc_pos]);
3285 else if (strcmp(argv[argc_pos], "--user") == 0)
3290 if (++argc_pos == argc) usage(argv[argc_pos]);
3292 user_arg = strdup_or_die(argv[argc_pos]);
3293 group_name = strchr(user_arg, '.');
3294 if (NULL != group_name)
3296 /* Nul-terminate the user name */
3299 /* Skip the former delimiter to actually reach the group name */
3302 grp = getgrnam(group_name);
3305 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3308 pw = getpwnam(user_arg);
3311 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3317 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3319 if (++argc_pos == argc) usage(argv[0]);
3320 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3323 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3327 #endif /* defined(unix) */
3329 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3334 else if (argc_pos + 1 != argc)
3337 * This is neither the last command line
3338 * option, nor was it recognized before,
3339 * therefore it must be invalid.
3345 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3347 configfile = argv[argc_pos];
3350 } /* -END- while (more arguments) */
3352 show_version(Argv[0]);
3355 if (*configfile != '/')
3357 char cwd[BUFFER_SIZE];
3359 size_t abs_file_size;
3361 /* make config-filename absolute here */
3362 if (NULL == getcwd(cwd, sizeof(cwd)))
3364 perror("failed to get current working directory");
3368 basedir = strdup_or_die(cwd);
3370 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3371 abs_file = malloc_or_die(abs_file_size);
3372 strlcpy(abs_file, basedir, abs_file_size);
3373 strlcat(abs_file, "/", abs_file_size);
3374 strlcat(abs_file, configfile, abs_file_size);
3375 configfile = abs_file;
3377 #endif /* defined unix */
3381 clients->next = NULL;
3383 /* XXX: factor out initialising after the next stable release. */
3386 #elif defined(_WIN32)
3390 random_seed = (unsigned int)time(NULL);
3392 srandom(random_seed);
3395 #endif /* ifdef HAVE_RANDOM */
3398 * Unix signal handling
3400 * Catch the abort, interrupt and terminate signals for a graceful exit
3401 * Catch the hangup signal so the errlog can be reopened.
3402 * Ignore the broken pipe signals (FIXME: Why?)
3404 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3407 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3409 for (idx = 0; idx < SZ(catched_signals); idx++)
3411 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3412 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3414 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3415 #endif /* ifdef sun */
3417 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3421 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3423 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3427 #else /* ifdef _WIN32 */
3428 # ifdef _WIN_CONSOLE
3430 * We *are* in a windows console app.
3431 * Print a verbose messages about FAQ's and such
3433 printf("%s", win32_blurb);
3434 # endif /* def _WIN_CONSOLE */
3435 #endif /* def _WIN32 */
3439 exit(NULL == load_config());
3442 /* Initialize the CGI subsystem */
3443 cgi_init_error_messages();
3446 * If runnig on unix and without the --nodaemon
3447 * option, become a daemon. I.e. fork, detach
3448 * from tty and get process group leadership
3457 if (pid < 0) /* error */
3462 else if (pid != 0) /* parent */
3467 * must check for errors
3468 * child died due to missing files aso
3471 wpid = waitpid(pid, &status, WNOHANG);
3483 * stderr (fd 2) will be closed later on,
3484 * when the config file has been parsed.
3490 * Reserve fd 0 and 1 to prevent abort() and friends
3491 * from sending stuff to the clients or servers.
3493 fd = open("/dev/null", O_RDONLY);
3496 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3500 if (dup2(fd, 0) == -1)
3502 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3506 fd = open("/dev/null", O_WRONLY);
3509 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3513 if (dup2(fd, 1) == -1)
3515 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3522 } /* -END- if (daemon_mode) */
3525 * As soon as we have written the PID file, we can switch
3526 * to the user and group ID indicated by the --user option
3532 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3534 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3538 if (setgroups(1, &grp->gr_gid))
3540 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3543 else if (initgroups(pw->pw_name, pw->pw_gid))
3545 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3551 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3553 /* Read the time zone file from /etc before doing chroot. */
3555 if (NULL != pre_chroot_nslookup_to_load_resolver
3556 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3558 /* Initialize resolver library. */
3559 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3561 if (chroot(pw->pw_dir) < 0)
3563 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3567 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3570 if (setuid(pw->pw_uid))
3572 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3576 char putenv_dummy[64];
3578 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3579 if (putenv(putenv_dummy) != 0)
3581 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3584 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3585 if (putenv(putenv_dummy) != 0)
3587 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3593 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3596 #endif /* defined unix */
3599 /* This will be FALSE unless the command line specified --service
3603 /* Yup, so now we must attempt to establish a connection
3604 * with the service dispatcher. This will only work if this
3605 * process was launched by the service control manager to
3606 * actually run as a service. If this isn't the case, i've
3607 * known it take around 30 seconds or so for the call to return.
3610 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3611 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3613 /* Service has run, and at this point is now being stopped, so just return */
3618 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3620 /* An error occurred. Usually it's because --service was wrongly specified
3621 * and we were unable to connect to the Service Control Dispatcher because
3622 * it wasn't expecting us and is therefore not listening.
3624 * For now, just continue below to call the listen_loop function.
3627 #endif /* def _WIN32 */
3637 /*********************************************************************
3639 * Function : bind_port_helper
3641 * Description : Bind the listen port. Handles logging, and aborts
3645 * 1 : haddr = Host addres to bind to. Use NULL to bind to
3647 * 2 : hport = Specifies port to bind to.
3649 * Returns : Port that was opened.
3651 *********************************************************************/
3652 static jb_socket bind_port_helper(const char *haddr, int hport)
3657 result = bind_port(haddr, hport, &bfd);
3661 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
3665 log_error(LOG_LEVEL_FATAL,
3666 "can't bind to %s:%d: There may be another Privoxy "
3667 "or some other proxy running on port %d",
3668 bind_address, hport, hport);
3671 log_error(LOG_LEVEL_FATAL,
3672 "can't bind to %s:%d: The hostname is not resolvable",
3673 bind_address, hport);
3676 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3677 bind_address, hport);
3680 /* shouldn't get here */
3681 return JB_INVALID_SOCKET;
3686 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3691 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3699 /*********************************************************************
3701 * Function : bind_ports_helper
3703 * Description : Bind the listen ports. Handles logging, and aborts
3707 * 1 : config = Privoxy configuration. Specifies ports
3709 * 2 : sockets = Preallocated array of opened sockets
3710 * corresponding to specification in config.
3711 * All non-opened sockets will be set to
3712 * JB_INVALID_SOCKET.
3714 * Returns : Nothing. Inspect sockets argument.
3716 *********************************************************************/
3717 static void bind_ports_helper(struct configuration_spec * config,
3718 jb_socket sockets[])
3722 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3724 if (config->hport[i])
3726 sockets[i] = bind_port_helper(config->haddr[i], config->hport[i]);
3730 sockets[i] = JB_INVALID_SOCKET;
3733 config->need_bind = 0;
3737 /*********************************************************************
3739 * Function : close_ports_helper
3741 * Description : Close listenings ports.
3744 * 1 : sockets = Array of opened and non-opened sockets to
3745 * close. All sockets will be set to
3746 * JB_INVALID_SOCKET.
3748 * Returns : Nothing.
3750 *********************************************************************/
3751 static void close_ports_helper(jb_socket sockets[])
3755 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3757 if (JB_INVALID_SOCKET != sockets[i])
3759 close_socket(sockets[i]);
3761 sockets[i] = JB_INVALID_SOCKET;
3767 /* Without this simple workaround we get this compiler warning from _beginthread
3768 * warning C4028: formal parameter 1 different from declaration
3770 void w32_service_listen_loop(void *p)
3774 #endif /* def _WIN32 */
3777 /*********************************************************************
3779 * Function : listen_loop
3781 * Description : bind the listen port and enter a "FOREVER" listening loop.
3787 *********************************************************************/
3788 static void listen_loop(void)
3790 struct client_states *csp_list = NULL;
3791 struct client_state *csp = NULL;
3792 jb_socket bfds[MAX_LISTENING_SOCKETS];
3793 struct configuration_spec *config;
3794 unsigned int active_threads = 0;
3796 config = load_config();
3798 #ifdef FEATURE_CONNECTION_SHARING
3800 * XXX: Should be relocated once it no
3801 * longer needs to emit log messages.
3803 initialize_reusable_connections();
3804 #endif /* def FEATURE_CONNECTION_SHARING */
3806 bind_ports_helper(config, bfds);
3808 #ifdef FEATURE_GRACEFUL_TERMINATION
3809 while (!g_terminate)
3814 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3815 while (waitpid(-1, NULL, WNOHANG) > 0)
3817 /* zombie children */
3819 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3822 * Free data that was used by died threads
3824 active_threads = sweep();
3828 * Re-open the errlog after HUP signal
3830 if (received_hup_signal)
3832 if (NULL != config->logfile)
3834 init_error_log(Argv[0], config->logfile);
3836 received_hup_signal = 0;
3840 csp_list = (struct client_states *)zalloc(sizeof(*csp_list));
3841 if (NULL == csp_list)
3843 log_error(LOG_LEVEL_FATAL,
3844 "malloc(%d) for csp_list failed: %E", sizeof(*csp_list));
3847 csp = &csp_list->csp;
3849 log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
3851 if (!accept_connection(csp, bfds))
3853 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3865 csp->flags |= CSP_FLAG_ACTIVE;
3866 csp->server_connection.sfd = JB_INVALID_SOCKET;
3868 csp->config = config = load_config();
3870 if (config->need_bind)
3873 * Since we were listening to the "old port", we will not see
3874 * a "listen" param change until the next request. So, at
3875 * least 1 more request must be made for us to find the new
3876 * setting. I am simply closing the old socket and binding the
3879 * Which-ever is correct, we will serve 1 more page via the
3880 * old settings. This should probably be a "show-proxy-args"
3881 * request. This should not be a so common of an operation
3882 * that this will hurt people's feelings.
3885 close_ports_helper(bfds);
3887 bind_ports_helper(config, bfds);
3890 #ifdef FEATURE_TOGGLE
3891 if (global_toggle_state)
3892 #endif /* def FEATURE_TOGGLE */
3894 csp->flags |= CSP_FLAG_TOGGLED_ON;
3897 if (run_loader(csp))
3899 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3900 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3904 if (block_acl(NULL,csp))
3906 log_error(LOG_LEVEL_CONNECT,
3907 "Connection from %s on socket %d dropped due to ACL", csp->ip_addr_str, csp->cfd);
3908 close_socket(csp->cfd);
3909 freez(csp->ip_addr_str);
3913 #endif /* def FEATURE_ACL */
3915 if ((0 != config->max_client_connections)
3916 && (active_threads >= config->max_client_connections))
3918 log_error(LOG_LEVEL_CONNECT,
3919 "Rejecting connection from %s. Maximum number of connections reached.",
3921 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3922 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3923 close_socket(csp->cfd);
3924 freez(csp->ip_addr_str);
3929 /* add it to the list of clients */
3930 csp_list->next = clients->next;
3931 clients->next = csp_list;
3933 if (config->multi_threaded)
3937 /* this is a switch () statement in the C preprocessor - ugh */
3938 #undef SELECTED_ONE_OPTION
3940 /* Use Pthreads in preference to native code */
3941 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
3942 #define SELECTED_ONE_OPTION
3944 pthread_t the_thread;
3945 pthread_attr_t attrs;
3947 pthread_attr_init(&attrs);
3948 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
3949 errno = pthread_create(&the_thread, &attrs,
3950 (void * (*)(void *))serve, csp);
3951 child_id = errno ? -1 : 0;
3952 pthread_attr_destroy(&attrs);
3956 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
3957 #define SELECTED_ONE_OPTION
3958 child_id = _beginthread(
3959 (void (*)(void *))serve,
3964 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
3965 #define SELECTED_ONE_OPTION
3966 child_id = _beginthread(
3967 (void(* _Optlink)(void*))serve,
3973 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
3974 #define SELECTED_ONE_OPTION
3976 thread_id tid = spawn_thread
3977 (server_thread, "server", B_NORMAL_PRIORITY, csp);
3979 if ((tid >= 0) && (resume_thread(tid) == B_OK))
3981 child_id = (int) tid;
3990 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
3991 #define SELECTED_ONE_OPTION
3992 csp->cfd = ReleaseSocket(csp->cfd, -1);
3995 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3996 NP_Output, Output(),
3997 NP_CloseOutput, FALSE,
3998 NP_Name, (ULONG)"privoxy child",
4002 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4003 NP_Output, Output(),
4004 NP_CloseOutput, FALSE,
4005 NP_Name, (ULONG)"privoxy child",
4006 NP_StackSize, 200*1024,
4012 ((struct Task *)child_id)->tc_UserData = csp;
4013 Signal((struct Task *)child_id, SIGF_SINGLE);
4018 #if !defined(SELECTED_ONE_OPTION)
4021 /* This block is only needed when using fork().
4022 * When using threads, the server thread was
4023 * created and run by the call to _beginthread().
4025 if (child_id == 0) /* child */
4028 #ifdef FEATURE_TOGGLE
4029 int inherited_toggle_state = global_toggle_state;
4030 #endif /* def FEATURE_TOGGLE */
4035 * If we've been toggled or we've blocked the request, tell Mom
4038 #ifdef FEATURE_TOGGLE
4039 if (inherited_toggle_state != global_toggle_state)
4041 rc |= RC_FLAG_TOGGLED;
4043 #endif /* def FEATURE_TOGGLE */
4045 #ifdef FEATURE_STATISTICS
4046 if (csp->flags & CSP_FLAG_REJECTED)
4048 rc |= RC_FLAG_BLOCKED;
4050 #endif /* ndef FEATURE_STATISTICS */
4054 else if (child_id > 0) /* parent */
4056 /* in a fork()'d environment, the parent's
4057 * copy of the client socket and the CSP
4061 #if !defined(_WIN32) && !defined(__CYGWIN__)
4063 wait(&child_status);
4066 * Evaluate child's return code: If the child has
4067 * - been toggled, toggle ourselves
4068 * - blocked its request, bump up the stats counter
4071 #ifdef FEATURE_TOGGLE
4072 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4074 global_toggle_state = !global_toggle_state;
4076 #endif /* def FEATURE_TOGGLE */
4078 #ifdef FEATURE_STATISTICS
4080 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4084 #endif /* def FEATURE_STATISTICS */
4086 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4087 close_socket(csp->cfd);
4088 csp->flags &= ~CSP_FLAG_ACTIVE;
4092 #undef SELECTED_ONE_OPTION
4093 /* end of cpp switch () */
4098 * Spawning the child failed, assume it's because
4099 * there are too many children running already.
4100 * XXX: If you assume ...
4102 log_error(LOG_LEVEL_ERROR,
4103 "Unable to take any additional connections: %E");
4104 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4105 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4106 close_socket(csp->cfd);
4107 csp->flags &= ~CSP_FLAG_ACTIVE;
4116 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4118 /* Clean up. Aim: free all memory (no leaks) */
4119 #ifdef FEATURE_GRACEFUL_TERMINATION
4121 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4123 unload_current_config_file();
4124 unload_current_actions_file();
4125 unload_current_re_filterfile();
4126 #ifdef FEATURE_TRUST
4127 unload_current_trust_file();
4130 if (config->multi_threaded)
4137 } while ((clients->next != NULL) && (--i > 0));
4141 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4151 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4152 /* Cleanup - remove taskbar icon etc. */
4157 #endif /* FEATURE_GRACEFUL_TERMINATION */