1 const char jcc_rcs[] = "$Id: jcc.c,v 1.441 2016/02/26 12:29:38 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001-2016 the
10 * Privoxy team. http://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 *********************************************************************/
40 #include <sys/types.h>
49 # ifndef FEATURE_PTHREAD
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
65 # if !defined (__OS2__)
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
74 #include <sys/termios.h>
85 # include <socket.h> /* BeOS has select() for sockets only. */
86 # include <OS.h> /* declarations for threads and stuff. */
89 # if defined(__EMX__) || defined(__OS2__)
90 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
95 #define bzero(B,N) memset(B,0x00,n)
110 #include "miscutil.h"
112 #include "jbsockets.h"
117 #include "urlmatch.h"
118 #ifdef FEATURE_CLIENT_TAGS
119 #include "client-tags.h"
122 const char jcc_h_rcs[] = JCC_H_VERSION;
123 const char project_h_rcs[] = PROJECT_H_VERSION;
126 struct client_states clients[1];
127 struct file_list files[1];
129 #ifdef FEATURE_STATISTICS
130 int urls_read = 0; /* total nr of urls read inc rejected */
131 int urls_rejected = 0; /* total nr of urls rejected */
132 #endif /* def FEATURE_STATISTICS */
134 #ifdef FEATURE_GRACEFUL_TERMINATION
138 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
139 static void sig_handler(int the_signal);
141 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
142 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
143 static jb_err get_server_headers(struct client_state *csp);
144 static const char *crunch_reason(const struct http_response *rsp);
145 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
146 static char *get_request_line(struct client_state *csp);
147 static jb_err receive_client_request(struct client_state *csp);
148 static jb_err parse_client_request(struct client_state *csp);
149 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
150 static jb_err change_request_destination(struct client_state *csp);
151 static void chat(struct client_state *csp);
152 static void serve(struct client_state *csp);
153 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
154 static void usage(const char *myname);
156 static void initialize_mutexes(void);
157 static jb_socket bind_port_helper(const char *haddr, int hport);
158 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
159 static void close_ports_helper(jb_socket sockets[]);
160 static void listen_loop(void);
163 void serve(struct client_state *csp);
164 #else /* ifndef AMIGA */
165 static void serve(struct client_state *csp);
166 #endif /* def AMIGA */
169 static int32 server_thread(void *data);
170 #endif /* def __BEOS__ */
173 #define sleep(N) Sleep(((N) * 1000))
177 #define sleep(N) DosSleep(((N) * 100))
180 #ifdef MUTEX_LOCKS_AVAILABLE
182 * XXX: Does the locking stuff really belong in this file?
184 privoxy_mutex_t log_mutex;
185 privoxy_mutex_t log_init_mutex;
186 privoxy_mutex_t connection_reuse_mutex;
188 #ifdef FEATURE_EXTERNAL_FILTERS
189 privoxy_mutex_t external_filter_mutex;
191 #ifdef FEATURE_CLIENT_TAGS
192 privoxy_mutex_t client_tags_mutex;
195 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
196 privoxy_mutex_t resolver_mutex;
197 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
199 #ifndef HAVE_GMTIME_R
200 privoxy_mutex_t gmtime_mutex;
201 #endif /* ndef HAVE_GMTIME_R */
203 #ifndef HAVE_LOCALTIME_R
204 privoxy_mutex_t localtime_mutex;
205 #endif /* ndef HAVE_GMTIME_R */
208 privoxy_mutex_t rand_mutex;
209 #endif /* ndef HAVE_RANDOM */
211 #endif /* def MUTEX_LOCKS_AVAILABLE */
214 const char *basedir = NULL;
215 const char *pidfile = NULL;
216 static int received_hup_signal = 0;
217 #endif /* defined unix */
219 /* HTTP snipplets. */
220 static const char CSUCCEED[] =
221 "HTTP/1.1 200 Connection established\r\n\r\n";
223 static const char CHEADER[] =
224 "HTTP/1.1 400 Invalid header received from client\r\n"
225 "Content-Type: text/plain\r\n"
226 "Connection: close\r\n\r\n"
227 "Invalid header received from client.\r\n";
229 static const char FTP_RESPONSE[] =
230 "HTTP/1.1 400 Invalid request received from client\r\n"
231 "Content-Type: text/plain\r\n"
232 "Connection: close\r\n\r\n"
233 "Invalid request. Privoxy doesn't support FTP.\r\n";
235 static const char GOPHER_RESPONSE[] =
236 "HTTP/1.1 400 Invalid request received from client\r\n"
237 "Content-Type: text/plain\r\n"
238 "Connection: close\r\n\r\n"
239 "Invalid request. Privoxy doesn't support gopher.\r\n";
241 /* XXX: should be a template */
242 static const char MISSING_DESTINATION_RESPONSE[] =
243 "HTTP/1.1 400 Bad request received from client\r\n"
244 "Content-Type: text/plain\r\n"
245 "Connection: close\r\n\r\n"
246 "Bad request. Privoxy was unable to extract the destination.\r\n";
248 /* XXX: should be a template */
249 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
250 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
251 "Content-Type: text/plain\r\n"
252 "Connection: close\r\n\r\n"
253 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
255 /* XXX: should be a template */
256 static const char MESSED_UP_REQUEST_RESPONSE[] =
257 "HTTP/1.1 400 Malformed request after rewriting\r\n"
258 "Content-Type: text/plain\r\n"
259 "Connection: close\r\n\r\n"
260 "Bad request. Messed up with header filters.\r\n";
262 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
263 "HTTP/1.1 503 Too many open connections\r\n"
264 "Content-Type: text/plain\r\n"
265 "Connection: close\r\n\r\n"
266 "Maximum number of open connections reached.\r\n";
268 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
269 "HTTP/1.1 504 Connection timeout\r\n"
270 "Content-Type: text/plain\r\n"
271 "Connection: close\r\n\r\n"
272 "The connection timed out because the client request didn't arrive in time.\r\n";
274 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
275 "HTTP/1.1 400 Failed reading client body\r\n"
276 "Content-Type: text/plain\r\n"
277 "Connection: close\r\n\r\n"
278 "Failed parsing or buffering the chunk-encoded client body.\r\n";
280 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
281 "HTTP/1.1 417 Expecting too much\r\n"
282 "Content-Type: text/plain\r\n"
283 "Connection: close\r\n\r\n"
284 "Privoxy detected an unsupported Expect header value.\r\n";
286 /* A function to crunch a response */
287 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
289 /* Crunch function flags */
290 #define CF_NO_FLAGS 0
291 /* Cruncher applies to forced requests as well */
292 #define CF_IGNORE_FORCE 1
293 /* Crunched requests are counted for the block statistics */
294 #define CF_COUNT_AS_REJECT 2
296 /* A crunch function and its flags */
299 const crunch_func_ptr cruncher;
303 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
305 /* Complete list of cruncher functions */
306 static const struct cruncher crunchers_all[] = {
307 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
308 { block_url, CF_COUNT_AS_REJECT },
310 { trust_url, CF_COUNT_AS_REJECT },
311 #endif /* def FEATURE_TRUST */
312 { redirect_url, CF_NO_FLAGS },
313 { dispatch_cgi, CF_IGNORE_FORCE},
317 /* Light version, used after tags are applied */
318 static const struct cruncher crunchers_light[] = {
319 { block_url, CF_COUNT_AS_REJECT },
320 { redirect_url, CF_NO_FLAGS },
326 * XXX: Don't we really mean
332 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
333 /*********************************************************************
335 * Function : sig_handler
337 * Description : Signal handler for different signals.
338 * Exit gracefully on TERM and INT
339 * or set a flag that will cause the errlog
340 * to be reopened by the main thread on HUP.
343 * 1 : the_signal = the signal cause this function to call
347 *********************************************************************/
348 static void sig_handler(int the_signal)
354 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
366 received_hup_signal = 1;
372 * We shouldn't be here, unless we catch signals
373 * in main() that we can't handle here!
375 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
383 /*********************************************************************
385 * Function : client_protocol_is_unsupported
387 * Description : Checks if the client used a known unsupported
388 * protocol and deals with it by sending an error
392 * 1 : csp = Current client state (buffers, headers, etc...)
393 * 2 : req = the first request line send by the client
395 * Returns : TRUE if an error response has been generated, or
396 * FALSE if the request doesn't look invalid.
398 *********************************************************************/
399 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
402 * If it's a FTP or gopher request, we don't support it.
404 * These checks are better than nothing, but they might
405 * not work in all configurations and some clients might
406 * have problems digesting the answer.
408 * They should, however, never cause more problems than
409 * Privoxy's old behaviour (returning the misleading HTML
412 * "Could not resolve http://(ftp|gopher)://example.org").
414 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
416 const char *response = NULL;
417 const char *protocol = NULL;
419 if (!strncmpic(req, "GET ftp://", 10))
421 response = FTP_RESPONSE;
426 response = GOPHER_RESPONSE;
429 log_error(LOG_LEVEL_ERROR,
430 "%s tried to use Privoxy as %s proxy: %s",
431 csp->ip_addr_str, protocol, req);
432 log_error(LOG_LEVEL_CLF,
433 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
435 write_socket(csp->cfd, response, strlen(response));
444 /*********************************************************************
446 * Function : client_has_unsupported_expectations
448 * Description : Checks if the client used an unsupported expectation
449 * in which case an error message is delivered.
452 * 1 : csp = Current client state (buffers, headers, etc...)
454 * Returns : TRUE if an error response has been generated, or
455 * FALSE if the request doesn't look invalid.
457 *********************************************************************/
458 static int client_has_unsupported_expectations(const struct client_state *csp)
460 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
462 log_error(LOG_LEVEL_ERROR,
463 "Rejecting request from client %s with unsupported Expect header value",
465 log_error(LOG_LEVEL_CLF,
466 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
467 write_socket(csp->cfd, UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
468 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE));
478 /*********************************************************************
480 * Function : get_request_destination_elsewhere
482 * Description : If the client's request was redirected into
483 * Privoxy without the client's knowledge,
484 * the request line lacks the destination host.
486 * This function tries to get it elsewhere,
487 * provided accept-intercepted-requests is enabled.
489 * "Elsewhere" currently only means "Host: header",
490 * but in the future we may ask the redirecting
491 * packet filter to look the destination up.
493 * If the destination stays unknown, an error
494 * response is send to the client and headers
495 * are freed so that chat() can return directly.
498 * 1 : csp = Current client state (buffers, headers, etc...)
499 * 2 : headers = a header list
501 * Returns : JB_ERR_OK if the destination is now known, or
502 * JB_ERR_PARSE if it isn't.
504 *********************************************************************/
505 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
509 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
511 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
512 " Privoxy isn't configured to accept intercepted requests.",
513 csp->ip_addr_str, csp->http->cmd);
514 /* XXX: Use correct size */
515 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
516 csp->ip_addr_str, csp->http->cmd);
518 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
519 destroy_list(headers);
523 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
525 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
526 /* Split the domain we just got for pattern matching */
527 init_domain_components(csp->http);
534 /* We can't work without destination. Go spread the news.*/
536 req = list_to_text(headers);
538 /* XXX: Use correct size */
539 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
540 csp->ip_addr_str, csp->http->cmd);
541 log_error(LOG_LEVEL_ERROR,
542 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
543 csp->ip_addr_str, csp->http->cmd, req);
546 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
547 destroy_list(headers);
552 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
553 * to get the destination IP address, use it as host directly
554 * or do a reverse DNS lookup first.
559 /*********************************************************************
561 * Function : get_server_headers
563 * Description : Parses server headers in iob and fills them
564 * into csp->headers so that they can later be
568 * 1 : csp = Current client state (buffers, headers, etc...)
570 * Returns : JB_ERR_OK if everything went fine, or
571 * JB_ERR_PARSE if the headers were incomplete.
573 *********************************************************************/
574 static jb_err get_server_headers(struct client_state *csp)
576 int continue_hack_in_da_house = 0;
579 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
584 * continue hack in da house. Ignore the ending of
585 * this head and continue enlisting header lines.
586 * The reason is described below.
588 enlist(csp->headers, "");
589 continue_hack_in_da_house = 0;
592 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
595 * It's a bodyless continue response, don't
596 * stop header parsing after reaching its end.
598 * As a result Privoxy will concatenate the
599 * next response's head and parse and deliver
600 * the headers as if they belonged to one request.
602 * The client will separate them because of the
603 * empty line between them.
605 * XXX: What we're doing here is clearly against
606 * the intended purpose of the continue header,
607 * and under some conditions (HTTP/1.0 client request)
608 * it's a standard violation.
610 * Anyway, "sort of against the spec" is preferable
611 * to "always getting confused by Continue responses"
612 * (Privoxy's behaviour before this hack was added)
614 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
615 continue_hack_in_da_house = 1;
617 else if (*header == '\0')
620 * If the header is empty, but the Continue hack
621 * isn't active, we can assume that we reached the
622 * end of the buffer before we hit the end of the
625 * Inform the caller an let it decide how to handle it.
630 if (JB_ERR_MEMORY == enlist(csp->headers, header))
633 * XXX: Should we quit the request and return a
634 * out of memory error page instead?
636 log_error(LOG_LEVEL_ERROR,
637 "Out of memory while enlisting server headers. %s lost.",
647 /*********************************************************************
649 * Function : crunch_reason
651 * Description : Translates the crunch reason code into a string.
654 * 1 : rsp = a http_response
656 * Returns : A string with the crunch reason or an error description.
658 *********************************************************************/
659 static const char *crunch_reason(const struct http_response *rsp)
661 char * reason = NULL;
666 return "Internal error while searching for crunch reason";
669 switch (rsp->crunch_reason)
672 reason = "Unsupported HTTP feature";
678 reason = "Untrusted";
681 reason = "Redirected";
687 reason = "DNS failure";
689 case FORWARDING_FAILED:
690 reason = "Forwarding failed";
693 reason = "Connection failure";
696 reason = "Out of memory (may mask other reasons)";
698 case CONNECTION_TIMEOUT:
699 reason = "Connection timeout";
702 reason = "No server data received";
705 reason = "No reason recorded";
713 /*********************************************************************
715 * Function : log_applied_actions
717 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
721 * 1 : actions = Current action spec to log
725 *********************************************************************/
726 static void log_applied_actions(const struct current_action_spec *actions)
729 * The conversion to text requires lots of memory allocations so
730 * we only do the conversion if the user is actually interested.
732 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
734 char *actions_as_text = actions_to_line_of_text(actions);
735 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
736 freez(actions_as_text);
741 /*********************************************************************
743 * Function : send_crunch_response
745 * Description : Delivers already prepared response for
746 * intercepted requests, logs the interception
747 * and frees the response.
750 * 1 : csp = Current client state (buffers, headers, etc...)
751 * 1 : rsp = Fully prepared response. Will be freed on exit.
755 *********************************************************************/
756 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
758 const struct http_request *http = csp->http;
762 assert(rsp->head != NULL);
766 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
770 * Extract the status code from the actual head
771 * that will be send to the client. It is the only
772 * way to get it right for all requests, including
773 * the fixed ones for out-of-memory problems.
775 * A head starts like this: 'HTTP/1.1 200...'
779 status_code[0] = rsp->head[9];
780 status_code[1] = rsp->head[10];
781 status_code[2] = rsp->head[11];
782 status_code[3] = '\0';
784 /* Log that the request was crunched and why. */
785 log_applied_actions(csp->action);
786 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
787 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
788 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
790 /* Write the answer to the client */
791 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
792 || write_socket(csp->cfd, rsp->body, rsp->content_length))
794 /* There is nothing we can do about it. */
795 log_error(LOG_LEVEL_ERROR,
796 "Couldn't deliver the error message through client socket %d: %E",
800 /* Clean up and return */
801 if (cgi_error_memory() != rsp)
803 free_http_response(rsp);
809 /*********************************************************************
811 * Function : crunch_response_triggered
813 * Description : Checks if the request has to be crunched,
814 * and delivers the crunch response if necessary.
817 * 1 : csp = Current client state (buffers, headers, etc...)
818 * 2 : crunchers = list of cruncher functions to run
820 * Returns : TRUE if the request was answered with a crunch response
823 *********************************************************************/
824 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
826 struct http_response *rsp = NULL;
827 const struct cruncher *c;
830 * If CGI request crunching is disabled,
831 * check the CGI dispatcher out of order to
832 * prevent unintentional blocks or redirects.
834 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
835 && (NULL != (rsp = dispatch_cgi(csp))))
837 /* Deliver, log and free the interception response. */
838 send_crunch_response(csp, rsp);
839 csp->flags |= CSP_FLAG_CRUNCHED;
843 for (c = crunchers; c->cruncher != NULL; c++)
846 * Check the cruncher if either Privoxy is toggled
847 * on and the request isn't forced, or if the cruncher
848 * applies to forced requests as well.
850 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
851 !(csp->flags & CSP_FLAG_FORCED)) ||
852 (c->flags & CF_IGNORE_FORCE))
854 rsp = c->cruncher(csp);
857 /* Deliver, log and free the interception response. */
858 send_crunch_response(csp, rsp);
859 csp->flags |= CSP_FLAG_CRUNCHED;
860 #ifdef FEATURE_STATISTICS
861 if (c->flags & CF_COUNT_AS_REJECT)
863 csp->flags |= CSP_FLAG_REJECTED;
865 #endif /* def FEATURE_STATISTICS */
876 /*********************************************************************
878 * Function : build_request_line
880 * Description : Builds the HTTP request line.
882 * If a HTTP forwarder is used it expects the whole URL,
883 * web servers only get the path.
886 * 1 : csp = Current client state (buffers, headers, etc...)
887 * 2 : fwd = The forwarding spec used for the request
888 * XXX: Should use http->fwd instead.
889 * 3 : request_line = The old request line which will be replaced.
891 * Returns : Nothing. Terminates in case of memory problems.
893 *********************************************************************/
894 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
896 struct http_request *http = csp->http;
898 assert(http->ssl == 0);
901 * Downgrade http version from 1.1 to 1.0
902 * if +downgrade action applies.
904 if ((csp->action->flags & ACTION_DOWNGRADE)
905 && (!strcmpic(http->ver, "HTTP/1.1")))
908 http->ver = strdup_or_die("HTTP/1.0");
912 * Rebuild the request line.
914 freez(*request_line);
915 *request_line = strdup(http->gpc);
916 string_append(request_line, " ");
918 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
920 string_append(request_line, http->url);
924 string_append(request_line, http->path);
926 string_append(request_line, " ");
927 string_append(request_line, http->ver);
929 if (*request_line == NULL)
931 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
933 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
937 /*********************************************************************
939 * Function : change_request_destination
941 * Description : Parse a (rewritten) request line and regenerate
942 * the http request data.
945 * 1 : csp = Current client state (buffers, headers, etc...)
947 * Returns : Forwards the parse_http_request() return code.
948 * Terminates in case of memory problems.
950 *********************************************************************/
951 static jb_err change_request_destination(struct client_state *csp)
953 struct http_request *http = csp->http;
956 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
957 csp->headers->first->str);
958 free_http_request(http);
959 err = parse_http_request(csp->headers->first->str, http);
960 if (JB_ERR_OK != err)
962 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
963 jb_err_to_string(err));
970 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
971 /*********************************************************************
973 * Function : server_response_is_complete
975 * Description : Determines whether we should stop reading
976 * from the server socket.
979 * 1 : csp = Current client state (buffers, headers, etc...)
980 * 2 : content_length = Length of content received so far.
982 * Returns : TRUE if the response is complete,
985 *********************************************************************/
986 static int server_response_is_complete(struct client_state *csp,
987 unsigned long long content_length)
989 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
991 if (!strcmpic(csp->http->gpc, "HEAD"))
994 * "HEAD" implies no body, we are thus expecting
995 * no content. XXX: incomplete "list" of methods?
997 csp->expected_content_length = 0;
998 content_length_known = TRUE;
999 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1002 if (csp->http->status == 204 || csp->http->status == 304)
1005 * Expect no body. XXX: incomplete "list" of status codes?
1007 csp->expected_content_length = 0;
1008 content_length_known = TRUE;
1009 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1012 return (content_length_known && ((0 == csp->expected_content_length)
1013 || (csp->expected_content_length <= content_length)));
1017 #ifdef FEATURE_CONNECTION_SHARING
1018 /*********************************************************************
1020 * Function : wait_for_alive_connections
1022 * Description : Waits for alive connections to timeout.
1028 *********************************************************************/
1029 static void wait_for_alive_connections(void)
1031 int connections_alive = close_unusable_connections();
1033 while (0 < connections_alive)
1035 log_error(LOG_LEVEL_CONNECT,
1036 "Waiting for %d connections to timeout.",
1039 connections_alive = close_unusable_connections();
1042 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1045 #endif /* def FEATURE_CONNECTION_SHARING */
1048 /*********************************************************************
1050 * Function : save_connection_destination
1052 * Description : Remembers a connection for reuse later on.
1055 * 1 : sfd = Open socket to remember.
1056 * 2 : http = The destination for the connection.
1057 * 3 : fwd = The forwarder settings used.
1058 * 3 : server_connection = storage.
1062 *********************************************************************/
1063 void save_connection_destination(jb_socket sfd,
1064 const struct http_request *http,
1065 const struct forward_spec *fwd,
1066 struct reusable_connection *server_connection)
1068 assert(sfd != JB_INVALID_SOCKET);
1069 assert(NULL != http->host);
1071 server_connection->sfd = sfd;
1072 server_connection->host = strdup_or_die(http->host);
1073 server_connection->port = http->port;
1075 assert(NULL != fwd);
1076 assert(server_connection->gateway_host == NULL);
1077 assert(server_connection->gateway_port == 0);
1078 assert(server_connection->forwarder_type == 0);
1079 assert(server_connection->forward_host == NULL);
1080 assert(server_connection->forward_port == 0);
1082 server_connection->forwarder_type = fwd->type;
1083 if (NULL != fwd->gateway_host)
1085 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1089 server_connection->gateway_host = NULL;
1091 server_connection->gateway_port = fwd->gateway_port;
1093 if (NULL != fwd->forward_host)
1095 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1099 server_connection->forward_host = NULL;
1101 server_connection->forward_port = fwd->forward_port;
1105 /*********************************************************************
1107 * Function : verify_request_length
1109 * Description : Checks if we already got the whole client requests
1110 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1113 * Data that doesn't belong to the current request is
1114 * either thrown away to let the client retry on a clean
1115 * socket, or stashed to be dealt with after the current
1116 * request is served.
1119 * 1 : csp = Current client state (buffers, headers, etc...)
1123 *********************************************************************/
1124 static void verify_request_length(struct client_state *csp)
1126 unsigned long long buffered_request_bytes =
1127 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1129 if ((csp->expected_client_content_length != 0)
1130 && (buffered_request_bytes != 0))
1132 if (csp->expected_client_content_length >= buffered_request_bytes)
1134 csp->expected_client_content_length -= buffered_request_bytes;
1135 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1136 "to account for the %llu ones we already got.",
1137 csp->expected_client_content_length, buffered_request_bytes);
1141 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1142 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1143 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1144 "Marking the server socket tainted after throwing %llu bytes away.",
1145 buffered_request_bytes - csp->expected_client_content_length);
1146 csp->expected_client_content_length = 0;
1147 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1150 if (csp->expected_client_content_length == 0)
1152 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1156 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1157 && ((csp->client_iob->cur < csp->client_iob->eod)
1158 || (csp->expected_client_content_length != 0)))
1160 if (strcmpic(csp->http->gpc, "GET")
1161 && strcmpic(csp->http->gpc, "HEAD")
1162 && strcmpic(csp->http->gpc, "TRACE")
1163 && strcmpic(csp->http->gpc, "OPTIONS")
1164 && strcmpic(csp->http->gpc, "DELETE"))
1166 /* XXX: this is an incomplete hack */
1167 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1168 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1172 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1174 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1176 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1177 log_error(LOG_LEVEL_CONNECT,
1178 "Possible pipeline attempt detected. The connection will not "
1179 "be kept alive and we will only serve the first request.");
1180 /* Nuke the pipelined requests from orbit, just to be sure. */
1181 clear_iob(csp->client_iob);
1186 * Keep the pipelined data around for now, we'll deal with
1187 * it once we're done serving the current request.
1189 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1190 assert(csp->client_iob->eod >= csp->client_iob->cur);
1191 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1192 "%d bytes of pipelined data received.",
1193 (int)(csp->client_iob->eod - csp->client_iob->cur));
1199 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1200 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1203 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1206 /*********************************************************************
1208 * Function : mark_server_socket_tainted
1210 * Description : Makes sure we don't reuse a server socket
1211 * (if we didn't read everything the server sent
1212 * us reusing the socket would lead to garbage).
1215 * 1 : csp = Current client state (buffers, headers, etc...)
1219 *********************************************************************/
1220 static void mark_server_socket_tainted(struct client_state *csp)
1223 * For consistency we always mark the server socket
1224 * tainted, however, to reduce the log noise we only
1225 * emit a log message if the server socket could have
1226 * actually been reused.
1228 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1229 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1231 log_error(LOG_LEVEL_CONNECT,
1232 "Marking the server socket %d tainted.",
1233 csp->server_connection.sfd);
1235 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1238 /*********************************************************************
1240 * Function : get_request_line
1242 * Description : Read the client request line.
1245 * 1 : csp = Current client state (buffers, headers, etc...)
1247 * Returns : Pointer to request line or NULL in case of errors.
1249 *********************************************************************/
1250 static char *get_request_line(struct client_state *csp)
1252 char buf[BUFFER_SIZE];
1253 char *request_line = NULL;
1256 memset(buf, 0, sizeof(buf));
1258 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1261 * If there are multiple pipelined requests waiting,
1262 * the flag will be set again once the next request
1265 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1267 request_line = get_header(csp->client_iob);
1268 if ((NULL != request_line) && ('\0' != *request_line))
1270 return request_line;
1274 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1275 "received yet. Continuing reading from %d.", csp->cfd);
1281 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1283 if (socket_is_still_alive(csp->cfd))
1285 log_error(LOG_LEVEL_CONNECT,
1286 "No request line on socket %d received in time. Timeout: %d.",
1287 csp->cfd, csp->config->socket_timeout);
1288 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1289 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1293 log_error(LOG_LEVEL_CONNECT,
1294 "The client side of the connection on socket %d got "
1295 "closed without sending a complete request line.", csp->cfd);
1300 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1302 if (len <= 0) return NULL;
1305 * If there is no memory left for buffering the
1306 * request, there is nothing we can do but hang up
1308 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1313 request_line = get_header(csp->client_iob);
1315 } while ((NULL != request_line) && ('\0' == *request_line));
1317 return request_line;
1323 CHUNK_STATUS_MISSING_DATA,
1324 CHUNK_STATUS_BODY_COMPLETE,
1325 CHUNK_STATUS_PARSE_ERROR
1329 /*********************************************************************
1331 * Function : chunked_body_is_complete
1333 * Description : Figures out whether or not a chunked body is complete.
1335 * Currently it always starts at the beginning of the
1336 * buffer which is somewhat wasteful and prevents Privoxy
1337 * from starting to forward the correctly parsed chunks
1338 * as soon as theoretically possible.
1340 * Should be modified to work with a common buffer,
1341 * and allow the caller to skip already parsed chunks.
1343 * This would allow the function to be used for unbuffered
1344 * response bodies as well.
1347 * 1 : iob = Buffer with the body to check.
1348 * 2 : length = Length of complete body
1350 * Returns : Enum with the result of the check.
1352 *********************************************************************/
1353 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1355 unsigned int chunksize;
1361 * We need at least a single digit, followed by "\r\n",
1362 * followed by an unknown amount of data, followed by "\r\n".
1364 if (p + 5 > iob->eod)
1366 return CHUNK_STATUS_MISSING_DATA;
1368 if (sscanf(p, "%x", &chunksize) != 1)
1370 return CHUNK_STATUS_PARSE_ERROR;
1374 * We want at least a single digit, followed by "\r\n",
1375 * followed by the specified amount of data, followed by "\r\n".
1377 if (p + chunksize + 5 > iob->eod)
1379 return CHUNK_STATUS_MISSING_DATA;
1382 /* Skip chunk-size. */
1383 p = strstr(p, "\r\n");
1386 return CHUNK_STATUS_PARSE_ERROR;
1388 /* Move beyond the chunkdata. */
1391 /* There should be another "\r\n" to skip */
1392 if (memcmp(p, "\r\n", 2))
1394 return CHUNK_STATUS_PARSE_ERROR;
1397 } while (chunksize > 0U);
1399 *length = (size_t)(p - iob->cur);
1400 assert(*length <= (size_t)(iob->eod - iob->cur));
1401 assert(p <= iob->eod);
1403 return CHUNK_STATUS_BODY_COMPLETE;
1408 /*********************************************************************
1410 * Function : receive_chunked_client_request_body
1412 * Description : Read the chunk-encoded client request body.
1413 * Failures are dealt with.
1416 * 1 : csp = Current client state (buffers, headers, etc...)
1418 * Returns : JB_ERR_OK or JB_ERR_PARSE
1420 *********************************************************************/
1421 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1424 enum chunk_status status;
1426 while (CHUNK_STATUS_MISSING_DATA ==
1427 (status = chunked_body_is_complete(csp->client_iob,&body_length)))
1429 char buf[BUFFER_SIZE];
1432 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1434 log_error(LOG_LEVEL_ERROR,
1435 "Timeout while waiting for the client body.");
1438 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1441 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1444 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1449 if (status != CHUNK_STATUS_BODY_COMPLETE)
1451 write_socket(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1452 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE));
1453 log_error(LOG_LEVEL_CLF,
1454 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1455 return JB_ERR_PARSE;
1457 log_error(LOG_LEVEL_CONNECT,
1458 "Chunked client body completely read. Length: %d", body_length);
1459 csp->expected_client_content_length = body_length;
1466 #ifdef FEATURE_FORCE_LOAD
1467 /*********************************************************************
1469 * Function : force_required
1471 * Description : Checks a request line to see if it contains
1472 * the FORCE_PREFIX. If it does, it is removed
1473 * unless enforcing requests has beend disabled.
1476 * 1 : request_line = HTTP request line
1478 * Returns : TRUE if force is required, FALSE otherwise.
1480 *********************************************************************/
1481 static int force_required(const struct client_state *csp, char *request_line)
1485 p = strstr(request_line, "http://");
1489 p += strlen("http://");
1493 /* Intercepted request usually don't specify the protocol. */
1497 /* Go to the beginning of the path */
1502 * If the path is missing the request line is invalid and we
1503 * are done here. The client-visible rejection happens later on.
1508 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1510 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1512 /* XXX: Should clean more carefully */
1513 strclean(request_line, FORCE_PREFIX);
1514 log_error(LOG_LEVEL_FORCE,
1515 "Enforcing request: \"%s\".", request_line);
1519 log_error(LOG_LEVEL_FORCE,
1520 "Ignored force prefix in request: \"%s\".", request_line);
1526 #endif /* def FEATURE_FORCE_LOAD */
1529 /*********************************************************************
1531 * Function : receive_client_request
1533 * Description : Read the client's request (more precisely the
1534 * client headers) and answer it if necessary.
1537 * 1 : csp = Current client state (buffers, headers, etc...)
1539 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1541 *********************************************************************/
1542 static jb_err receive_client_request(struct client_state *csp)
1544 char buf[BUFFER_SIZE];
1547 struct http_request *http;
1551 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1552 struct list header_list;
1553 struct list *headers = &header_list;
1555 /* We don't care if the arriving data is a valid HTTP request or not. */
1556 csp->requests_received_total++;
1560 memset(buf, 0, sizeof(buf));
1562 req = get_request_line(csp);
1565 mark_server_socket_tainted(csp);
1566 return JB_ERR_PARSE;
1568 assert(*req != '\0');
1570 if (client_protocol_is_unsupported(csp, req))
1572 return JB_ERR_PARSE;
1575 #ifdef FEATURE_FORCE_LOAD
1576 if (force_required(csp, req))
1578 csp->flags |= CSP_FLAG_FORCED;
1580 #endif /* def FEATURE_FORCE_LOAD */
1582 err = parse_http_request(req, http);
1584 if (JB_ERR_OK != err)
1586 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1587 /* XXX: Use correct size */
1588 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1589 log_error(LOG_LEVEL_ERROR,
1590 "Couldn't parse request line received from %s: %s",
1591 csp->ip_addr_str, jb_err_to_string(err));
1593 free_http_request(http);
1594 return JB_ERR_PARSE;
1597 /* grab the rest of the client's headers */
1601 p = get_header(csp->client_iob);
1605 /* There are no additional headers to read. */
1612 * We didn't receive a complete header
1613 * line yet, get the rest of it.
1615 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1617 log_error(LOG_LEVEL_ERROR,
1618 "Stopped grabbing the client headers.");
1619 destroy_list(headers);
1620 return JB_ERR_PARSE;
1623 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1626 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1627 destroy_list(headers);
1628 return JB_ERR_PARSE;
1631 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1634 * If there is no memory left for buffering the
1635 * request, there is nothing we can do but hang up
1637 destroy_list(headers);
1638 return JB_ERR_MEMORY;
1643 if (!strncmpic(p, "Transfer-Encoding:", 18))
1646 * XXX: should be called through sed()
1647 * but currently can't.
1649 client_transfer_encoding(csp, &p);
1652 * We were able to read a complete
1653 * header and can finally enlist it.
1660 if (http->host == NULL)
1663 * If we still don't know the request destination,
1664 * the request is invalid or the client uses
1665 * Privoxy without its knowledge.
1667 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1670 * Our attempts to get the request destination
1671 * elsewhere failed or Privoxy is configured
1672 * to only accept proxy requests.
1674 * An error response has already been send
1675 * and we're done here.
1677 return JB_ERR_PARSE;
1682 * Determine the actions for this URL
1684 #ifdef FEATURE_TOGGLE
1685 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1687 /* Most compatible set of actions (i.e. none) */
1688 init_current_action(csp->action);
1691 #endif /* ndef FEATURE_TOGGLE */
1693 get_url_actions(csp, http);
1696 enlist(csp->headers, http->cmd);
1698 /* Append the previously read headers */
1699 err = list_append_list_unique(csp->headers, headers);
1700 destroy_list(headers);
1707 /*********************************************************************
1709 * Function : parse_client_request
1711 * Description : Parses the client's request and decides what to do
1714 * Note that since we're not using select() we could get
1715 * blocked here if a client connected, then didn't say
1719 * 1 : csp = Current client state (buffers, headers, etc...)
1721 * Returns : JB_ERR_OK or JB_ERR_PARSE
1723 *********************************************************************/
1724 static jb_err parse_client_request(struct client_state *csp)
1726 struct http_request *http = csp->http;
1729 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1730 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1731 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1732 && (csp->http->ssl == 0))
1734 /* Assume persistence until further notice */
1735 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1738 if (csp->http->ssl == 0)
1741 * This whole block belongs to chat() but currently
1742 * has to be executed before sed().
1744 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1746 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1748 return JB_ERR_PARSE;
1753 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1755 verify_request_length(csp);
1757 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1759 err = sed(csp, FILTER_CLIENT_HEADERS);
1760 if (JB_ERR_OK != err)
1762 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1764 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1765 csp->ip_addr_str, csp->http->cmd);
1766 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1767 return JB_ERR_PARSE;
1769 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1771 /* Check request line for rewrites. */
1772 if ((NULL == csp->headers->first->str)
1773 || (strcmp(http->cmd, csp->headers->first->str) &&
1774 (JB_ERR_OK != change_request_destination(csp))))
1777 * A header filter broke the request line - bail out.
1779 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1780 /* XXX: Use correct size */
1781 log_error(LOG_LEVEL_CLF,
1782 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1783 log_error(LOG_LEVEL_ERROR,
1784 "Invalid request line after applying header filters.");
1785 free_http_request(http);
1787 return JB_ERR_PARSE;
1790 if (client_has_unsupported_expectations(csp))
1792 return JB_ERR_PARSE;
1800 /*********************************************************************
1804 * Description : Once a connection from the client has been accepted,
1805 * this function is called (via serve()) to handle the
1806 * main business of the communication. This function
1807 * returns after dealing with a single request. It can
1808 * be called multiple times with the same client socket
1809 * if the client is keeping the connection alive.
1811 * The decision whether or not a client connection will
1812 * be kept alive is up to the caller which also must
1813 * close the client socket when done.
1815 * FIXME: chat is nearly thousand lines long.
1819 * 1 : csp = Current client state (buffers, headers, etc...)
1821 * Returns : Nothing.
1823 *********************************************************************/
1824 static void chat(struct client_state *csp)
1826 char buf[BUFFER_SIZE];
1833 int ms_iis5_hack = 0;
1834 unsigned long long byte_count = 0;
1835 const struct forward_spec *fwd;
1836 struct http_request *http;
1837 long len = 0; /* for buffer sizes (and negative error codes) */
1838 int buffer_and_filter_content = 0;
1840 /* Skeleton for HTTP response, if we should intercept the request */
1841 struct http_response *rsp;
1842 struct timeval timeout;
1843 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1844 int watch_client_socket;
1847 memset(buf, 0, sizeof(buf));
1851 #if FEATURE_CLIENT_TAGS
1852 get_tag_list_for_client(csp->client_tags, csp->ip_addr_str);
1854 if (receive_client_request(csp) != JB_ERR_OK)
1858 if (parse_client_request(csp) != JB_ERR_OK)
1863 /* decide how to route the HTTP request */
1864 fwd = forward_url(csp, http);
1867 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1868 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1873 * build the http request to send to the server
1874 * we have to do one of the following:
1876 * create = use the original HTTP request to create a new
1877 * HTTP request that has either the path component
1878 * without the http://domainspec (w/path) or the
1879 * full orininal URL (w/url)
1880 * Note that the path and/or the HTTP version may
1881 * have been altered by now.
1883 * connect = Open a socket to the host:port of the server
1884 * and short-circuit server and client socket.
1886 * pass = Pass the request unchanged if forwarding a CONNECT
1887 * request to a parent proxy. Note that we'll be sending
1888 * the CFAIL message ourselves if connecting to the parent
1889 * fails, but we won't send a CSUCCEED message if it works,
1890 * since that would result in a double message (ours and the
1891 * parent's). After sending the request to the parent, we simply
1894 * here's the matrix:
1897 * +--------+--------+
1899 * 0 | create | connect|
1901 * Forwarding +--------+--------+
1903 * 1 | create | pass |
1905 * +--------+--------+
1909 if (http->ssl && connect_port_is_forbidden(csp))
1911 const char *acceptable_connect_ports =
1912 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1913 assert(NULL != acceptable_connect_ports);
1914 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1915 "limit-connect{%s} doesn't allow CONNECT requests to %s",
1916 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
1917 csp->action->flags |= ACTION_BLOCK;
1923 freez(csp->headers->first->str);
1924 build_request_line(csp, fwd, &csp->headers->first->str);
1928 * We have a request. Check if one of the crunchers wants it.
1930 if (crunch_response_triggered(csp, crunchers_all))
1933 * Yes. The client got the crunch response and we're done here.
1938 log_applied_actions(csp->action);
1939 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1941 if (fwd->forward_host)
1943 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1944 fwd->forward_host, fwd->forward_port, http->hostport);
1948 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1951 /* here we connect to the server, gateway, or the forwarder */
1953 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1954 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
1955 && socket_is_still_alive(csp->server_connection.sfd)
1956 && connection_destination_matches(&csp->server_connection, http, fwd))
1958 log_error(LOG_LEVEL_CONNECT,
1959 "Reusing server socket %d connected to %s. Total requests: %u.",
1960 csp->server_connection.sfd, csp->server_connection.host,
1961 csp->server_connection.requests_sent_total);
1965 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
1967 #ifdef FEATURE_CONNECTION_SHARING
1968 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1970 remember_connection(&csp->server_connection);
1973 #endif /* def FEATURE_CONNECTION_SHARING */
1975 log_error(LOG_LEVEL_CONNECT,
1976 "Closing server socket %d connected to %s. Total requests: %u.",
1977 csp->server_connection.sfd, csp->server_connection.host,
1978 csp->server_connection.requests_sent_total);
1979 close_socket(csp->server_connection.sfd);
1981 mark_connection_closed(&csp->server_connection);
1983 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1985 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
1987 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
1989 if ((fwd->type != SOCKS_NONE) && (fwd->type != FORWARD_WEBSERVER))
1992 rsp = error_response(csp, "forwarding-failed");
1994 else if (errno == EINVAL)
1996 rsp = error_response(csp, "no-such-domain");
2000 rsp = error_response(csp, "connect-failed");
2003 /* Write the answer to the client */
2006 send_crunch_response(csp, rsp);
2010 * Temporary workaround to prevent already-read client
2011 * bodies from being parsed as new requests. For now we
2012 * err on the safe side and throw all the following
2013 * requests under the bus, even if no client body has been
2014 * buffered. A compliant client will repeat the dropped
2015 * requests on an untainted connection.
2017 * The proper fix is to discard the no longer needed
2018 * client body in the buffer (if there is one) and to
2019 * continue parsing the bytes that follow.
2021 drain_and_close_socket(csp->cfd);
2022 csp->cfd = JB_INVALID_SOCKET;
2026 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2027 save_connection_destination(csp->server_connection.sfd,
2028 http, fwd, &csp->server_connection);
2029 csp->server_connection.keep_alive_timeout =
2030 (unsigned)csp->config->keep_alive_timeout;
2032 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2034 csp->server_connection.requests_sent_total++;
2036 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
2038 /* Client headers have been sent optimistically */
2039 assert(csp->headers->last == NULL);
2041 else if (fwd->forward_host || (http->ssl == 0))
2044 hdr = list_to_text(csp->headers);
2047 /* FIXME Should handle error properly */
2048 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2050 list_remove_all(csp->headers);
2053 * Write the client's (modified) header to the server
2054 * (along with anything else that may be in the buffer)
2056 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2061 log_error(LOG_LEVEL_CONNECT,
2062 "Failed sending request headers to: %s: %E", http->hostport);
2064 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2065 && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
2068 log_error(LOG_LEVEL_CONNECT,
2069 "Failed sending request body to: %s: %E", http->hostport);
2074 rsp = error_response(csp, "connect-failed");
2077 send_crunch_response(csp, rsp);
2085 * We're running an SSL tunnel and we're not forwarding,
2086 * so just ditch the client headers, send the "connect succeeded"
2087 * message to the client, flush the rest, and get out of the way.
2089 list_remove_all(csp->headers);
2090 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
2094 clear_iob(csp->client_iob);
2097 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
2099 /* XXX: should the time start earlier for optimistically sent data? */
2100 csp->server_connection.request_sent = time(NULL);
2102 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2103 csp->cfd : csp->server_connection.sfd;
2105 /* pass data between the client and server
2106 * until one or the other shuts down the connection.
2111 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2112 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2119 * FD_ZERO here seems to point to an errant macro which crashes.
2120 * So do this by hand for now...
2122 memset(&rfds,0x00,sizeof(fd_set));
2126 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2127 if (!watch_client_socket)
2129 maxfd = csp->server_connection.sfd;
2132 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2134 FD_SET(csp->cfd, &rfds);
2137 FD_SET(csp->server_connection.sfd, &rfds);
2139 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2140 if ((csp->flags & CSP_FLAG_CHUNKED)
2141 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2142 && ((csp->iob->eod - csp->iob->cur) >= 5)
2143 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2146 * XXX: This check should be obsolete now,
2147 * but let's wait a while to be sure.
2149 log_error(LOG_LEVEL_CONNECT,
2150 "Looks like we got the last chunk together with "
2151 "the server headers but didn't detect it earlier. "
2152 "We better stop reading.");
2153 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2154 csp->expected_content_length = byte_count;
2155 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2157 if (server_body && server_response_is_complete(csp, byte_count))
2159 if (csp->expected_content_length == byte_count)
2161 log_error(LOG_LEVEL_CONNECT,
2162 "Done reading from server. Content length: %llu as expected. "
2163 "Bytes most recently read: %d.",
2168 log_error(LOG_LEVEL_CONNECT,
2169 "Done reading from server. Expected content length: %llu. "
2170 "Actual content length: %llu. Bytes most recently read: %d.",
2171 csp->expected_content_length, byte_count, len);
2175 * XXX: should not jump around,
2176 * chat() is complicated enough already.
2180 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2182 timeout.tv_sec = csp->config->socket_timeout;
2183 timeout.tv_usec = 0;
2184 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2188 log_error(LOG_LEVEL_ERROR,
2189 "Didn't receive data in time: %s", http->url);
2190 if ((byte_count == 0) && (http->ssl == 0))
2192 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2194 mark_server_socket_tainted(csp);
2199 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2200 mark_server_socket_tainted(csp);
2205 * This is the body of the browser's request,
2206 * just read and write it.
2208 * XXX: Make sure the client doesn't use pipelining
2209 * behind Privoxy's back.
2211 if (FD_ISSET(csp->cfd, &rfds))
2213 int max_bytes_to_read = sizeof(buf) - 1;
2215 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2216 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2218 if (data_is_available(csp->cfd, 0))
2221 * If the next request is already waiting, we have
2222 * to stop select()ing the client socket. Otherwise
2223 * we would always return right away and get nothing
2226 watch_client_socket = 0;
2227 log_error(LOG_LEVEL_CONNECT,
2228 "Stopping to watch the client socket %d. "
2229 "There's already another request waiting.",
2234 * If the client socket is set, but there's no data
2235 * available on the socket, the client went fishing
2236 * and continuing talking to the server makes no sense.
2238 log_error(LOG_LEVEL_CONNECT,
2239 "The client closed socket %d while "
2240 "the server socket %d is still open.",
2241 csp->cfd, csp->server_connection.sfd);
2242 mark_server_socket_tainted(csp);
2245 if (csp->expected_client_content_length != 0)
2247 if (csp->expected_client_content_length < (sizeof(buf) - 1))
2249 max_bytes_to_read = (int)csp->expected_client_content_length;
2251 log_error(LOG_LEVEL_CONNECT,
2252 "Waiting for up to %d bytes from the client.",
2255 assert(max_bytes_to_read < sizeof(buf));
2256 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2258 len = read_socket(csp->cfd, buf, max_bytes_to_read);
2262 /* XXX: not sure if this is necessary. */
2263 mark_server_socket_tainted(csp);
2264 break; /* "game over, man" */
2267 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2268 if (csp->expected_client_content_length != 0)
2270 assert(len <= max_bytes_to_read);
2271 csp->expected_client_content_length -= (unsigned)len;
2272 log_error(LOG_LEVEL_CONNECT,
2273 "Expected client content length set to %llu "
2274 "after reading %d bytes.",
2275 csp->expected_client_content_length, len);
2276 if (csp->expected_client_content_length == 0)
2278 log_error(LOG_LEVEL_CONNECT,
2279 "Done reading from the client.");
2280 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2283 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2285 if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
2287 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2288 mark_server_socket_tainted(csp);
2295 * The server wants to talk. It could be the header or the body.
2296 * If `hdr' is null, then it's the header otherwise it's the body.
2297 * FIXME: Does `hdr' really mean `host'? No.
2299 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2301 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2303 * If we are buffering content, we don't want to eat up to
2304 * buffer-limit bytes if the client no longer cares about them.
2305 * If we aren't buffering, however, a dead client socket will be
2306 * noticed pretty much right away anyway, so we can reduce the
2307 * overhead by skipping the check.
2309 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2312 log_error(LOG_LEVEL_CONNECT,
2313 "The server still wants to talk, but the client may already have hung up on us.");
2315 log_error(LOG_LEVEL_CONNECT,
2316 "The server still wants to talk, but the client hung up on us.");
2317 mark_server_socket_tainted(csp);
2319 #endif /* def _WIN32 */
2321 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2323 len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
2327 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2329 if (http->ssl && (fwd->forward_host == NULL))
2332 * Just hang up. We already confirmed the client's CONNECT
2333 * request with status code 200 and unencrypted content is
2334 * no longer welcome.
2336 log_error(LOG_LEVEL_ERROR,
2337 "CONNECT already confirmed. Unable to tell the client about the problem.");
2340 else if (byte_count)
2343 * Just hang up. We already transmitted the original headers
2344 * and parts of the original content and therefore missed the
2345 * chance to send an error message (without risking data corruption).
2347 * XXX: we could retry with a fancy range request here.
2349 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2350 "Unable to tell the client about the problem.");
2351 mark_server_socket_tainted(csp);
2355 * XXX: Consider handling the cases above the same.
2357 mark_server_socket_tainted(csp);
2361 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2362 if (csp->flags & CSP_FLAG_CHUNKED)
2364 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2366 /* XXX: this is a temporary hack */
2367 log_error(LOG_LEVEL_CONNECT,
2368 "Looks like we reached the end of the last chunk. "
2369 "We better stop reading.");
2370 csp->expected_content_length = byte_count + (unsigned long long)len;
2371 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2375 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2378 * Add a trailing zero to let be able to use string operations.
2379 * XXX: do we still need this with filter_popups gone?
2384 * Normally, this would indicate that we've read
2385 * as much as the server has sent us and we can
2386 * close the client connection. However, Microsoft
2387 * in its wisdom has released IIS/5 with a bug that
2388 * prevents it from sending the trailing \r\n in
2389 * a 302 redirect header (and possibly other headers).
2390 * To work around this if we've haven't parsed
2391 * a full header we'll append a trailing \r\n
2392 * and see if this now generates a valid one.
2394 * This hack shouldn't have any impacts. If we've
2395 * already transmitted the header or if this is a
2396 * SSL connection, then we won't bother with this
2397 * hack. So we only work on partially received
2398 * headers. If we append a \r\n and this still
2399 * doesn't generate a valid header, then we won't
2400 * transmit anything to the client.
2405 if (server_body || http->ssl)
2408 * If we have been buffering up the document,
2409 * now is the time to apply content modification
2410 * and send the result to the client.
2412 if (buffer_and_filter_content)
2414 p = execute_content_filters(csp);
2416 * If content filtering fails, use the original
2417 * buffer and length.
2418 * (see p != NULL ? p : csp->iob->cur below)
2422 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2424 #ifdef FEATURE_COMPRESSION
2425 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2426 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2428 char *compressed_content = compress_buffer(p,
2429 (size_t *)&csp->content_length, csp->config->compression_level);
2430 if (compressed_content != NULL)
2433 p = compressed_content;
2434 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2439 if (JB_ERR_OK != update_server_headers(csp))
2441 log_error(LOG_LEVEL_FATAL,
2442 "Failed to update server headers. after filtering.");
2445 hdr = list_to_text(csp->headers);
2448 /* FIXME Should handle error properly */
2449 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2452 if (write_socket(csp->cfd, hdr, strlen(hdr))
2453 || write_socket(csp->cfd,
2454 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2456 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2459 mark_server_socket_tainted(csp);
2467 break; /* "game over, man" */
2471 * This is NOT the body, so
2472 * Let's pretend the server just sent us a blank line.
2474 snprintf(buf, sizeof(buf), "\r\n");
2475 len = (int)strlen(buf);
2478 * Now, let the normal header parsing algorithm below do its
2479 * job. If it fails, we'll exit instead of continuing.
2486 * If this is an SSL connection or we're in the body
2487 * of the server document, just write it to the client,
2488 * unless we need to buffer the body for later content-filtering
2490 if (server_body || http->ssl)
2492 if (buffer_and_filter_content)
2495 * If there is no memory left for buffering the content, or the buffer limit
2496 * has been reached, switch to non-filtering mode, i.e. make & write the
2497 * header, flush the iob and buf, and get out of the way.
2499 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2504 log_error(LOG_LEVEL_INFO,
2505 "Flushing header and buffers. Stepping back from filtering.");
2507 hdr = list_to_text(csp->headers);
2511 * Memory is too tight to even generate the header.
2512 * Send our static "Out-of-memory" page.
2514 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2515 rsp = cgi_error_memory();
2516 send_crunch_response(csp, rsp);
2517 mark_server_socket_tainted(csp);
2520 hdrlen = strlen(hdr);
2522 if (write_socket(csp->cfd, hdr, hdrlen)
2523 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2524 || (write_socket(csp->cfd, buf, (size_t)len)))
2526 log_error(LOG_LEVEL_CONNECT,
2527 "Flush header and buffers to client failed: %E");
2529 mark_server_socket_tainted(csp);
2534 * Reset the byte_count to the amount of bytes
2535 * we just flushed. len will be added a few lines below,
2536 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2538 byte_count = (unsigned long long)flushed;
2540 buffer_and_filter_content = 0;
2546 if (write_socket(csp->cfd, buf, (size_t)len))
2548 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2549 mark_server_socket_tainted(csp);
2553 byte_count += (unsigned long long)len;
2559 * We're still looking for the end of the server's header.
2560 * Buffer up the data we just read. If that fails, there's
2561 * little we can do but send our static out-of-memory page.
2563 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2565 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2566 rsp = cgi_error_memory();
2567 send_crunch_response(csp, rsp);
2568 mark_server_socket_tainted(csp);
2572 /* Convert iob into something sed() can digest */
2573 if (JB_ERR_PARSE == get_server_headers(csp))
2578 * Well, we tried our MS IIS/5 hack and it didn't work.
2579 * The header is incomplete and there isn't anything
2580 * we can do about it.
2582 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2583 "Applying the MS IIS5 hack didn't help.");
2584 log_error(LOG_LEVEL_CLF,
2585 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2586 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2587 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2588 mark_server_socket_tainted(csp);
2594 * Since we have to wait for more from the server before
2595 * we can parse the headers we just continue here.
2597 log_error(LOG_LEVEL_CONNECT,
2598 "Continuing buffering server headers from socket %d. "
2599 "Bytes most recently read: %d.", csp->cfd, len);
2606 * Account for the content bytes we
2607 * might have gotten with the headers.
2609 assert(csp->iob->eod >= csp->iob->cur);
2610 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2613 /* Did we actually get anything? */
2614 if (NULL == csp->headers->first)
2616 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2618 log_error(LOG_LEVEL_ERROR,
2619 "No server or forwarder response received on socket %d. "
2620 "Closing client socket %d without sending data.",
2621 csp->server_connection.sfd, csp->cfd);
2622 log_error(LOG_LEVEL_CLF,
2623 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2627 log_error(LOG_LEVEL_ERROR,
2628 "No server or forwarder response received on socket %d.",
2629 csp->server_connection.sfd);
2630 send_crunch_response(csp, error_response(csp, "no-server-data"));
2632 free_http_request(http);
2633 mark_server_socket_tainted(csp);
2637 assert(csp->headers->first->str);
2639 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2640 strncmpic(csp->headers->first->str, "ICY", 3))
2643 * It doesn't look like a HTTP (or Shoutcast) response:
2644 * tell the client and log the problem.
2646 if (strlen(csp->headers->first->str) > 30)
2648 csp->headers->first->str[30] = '\0';
2650 log_error(LOG_LEVEL_ERROR,
2651 "Invalid server or forwarder response. Starts with: %s",
2652 csp->headers->first->str);
2653 log_error(LOG_LEVEL_CLF,
2654 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2655 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2656 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2657 free_http_request(http);
2658 mark_server_socket_tainted(csp);
2663 * We have now received the entire server header,
2664 * filter it and send the result to the client
2666 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2668 log_error(LOG_LEVEL_CLF,
2669 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2670 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2671 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2672 free_http_request(http);
2673 mark_server_socket_tainted(csp);
2676 hdr = list_to_text(csp->headers);
2679 /* FIXME Should handle error properly */
2680 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2683 if ((csp->flags & CSP_FLAG_CHUNKED)
2684 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2685 && ((csp->iob->eod - csp->iob->cur) >= 5)
2686 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2688 log_error(LOG_LEVEL_CONNECT,
2689 "Looks like we got the last chunk together with "
2690 "the server headers. We better stop reading.");
2691 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2692 csp->expected_content_length = byte_count;
2693 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2696 csp->server_connection.response_received = time(NULL);
2698 if (crunch_response_triggered(csp, crunchers_light))
2701 * One of the tags created by a server-header
2702 * tagger triggered a crunch. We already
2703 * delivered the crunch response to the client
2704 * and are done here after cleaning up.
2707 mark_server_socket_tainted(csp);
2710 /* Buffer and pcrs filter this if appropriate. */
2712 if (!http->ssl) /* We talk plaintext */
2714 buffer_and_filter_content = content_requires_filtering(csp);
2717 * Only write if we're not buffering for content modification
2719 if (!buffer_and_filter_content)
2722 * Write the server's (modified) header to
2723 * the client (along with anything else that
2724 * may be in the buffer)
2727 if (write_socket(csp->cfd, hdr, strlen(hdr))
2728 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2730 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2733 * The write failed, so don't bother mentioning it
2734 * to the client... it probably can't hear us anyway.
2737 mark_server_socket_tainted(csp);
2742 /* we're finished with the server's header */
2748 * If this was a MS IIS/5 hack then it means the server
2749 * has already closed the connection. Nothing more to read.
2754 log_error(LOG_LEVEL_ERROR,
2755 "Closed server connection detected. "
2756 "Applying the MS IIS5 hack didn't help.");
2757 log_error(LOG_LEVEL_CLF,
2758 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2759 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2760 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2761 mark_server_socket_tainted(csp);
2767 mark_server_socket_tainted(csp);
2768 return; /* huh? we should never get here */
2771 if (csp->content_length == 0)
2774 * If Privoxy didn't recalculate the Content-Length,
2775 * byte_count is still correct.
2777 csp->content_length = byte_count;
2780 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2781 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2782 && (csp->expected_content_length != byte_count))
2784 log_error(LOG_LEVEL_CONNECT,
2785 "Received %llu bytes while expecting %llu.",
2786 byte_count, csp->expected_content_length);
2787 mark_server_socket_tainted(csp);
2791 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2792 csp->ip_addr_str, http->ocmd, csp->content_length);
2794 csp->server_connection.timestamp = time(NULL);
2798 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2799 /*********************************************************************
2801 * Function : prepare_csp_for_next_request
2803 * Description : Put the csp in a mostly vergin state.
2806 * 1 : csp = Current client state (buffers, headers, etc...)
2810 *********************************************************************/
2811 static void prepare_csp_for_next_request(struct client_state *csp)
2813 unsigned int toggled_on_flag_set = (0 != (csp->flags & CSP_FLAG_TOGGLED_ON));
2815 csp->content_type = 0;
2816 csp->content_length = 0;
2817 csp->expected_content_length = 0;
2818 csp->expected_client_content_length = 0;
2819 list_remove_all(csp->headers);
2820 clear_iob(csp->iob);
2821 freez(csp->error_message);
2822 free_http_request(csp->http);
2823 destroy_list(csp->headers);
2824 destroy_list(csp->tags);
2825 #ifdef FEATURE_CLIENT_TAGS
2826 destroy_list(csp->client_tags);
2828 free_current_action(csp->action);
2829 if (NULL != csp->fwd)
2831 unload_forward_spec(csp->fwd);
2834 /* XXX: Store per-connection flags someplace else. */
2835 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
2836 if (toggled_on_flag_set)
2838 csp->flags |= CSP_FLAG_TOGGLED_ON;
2841 if (csp->client_iob->eod > csp->client_iob->cur)
2843 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
2844 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2846 assert(bytes_to_shift > 0);
2847 assert(data_length > 0);
2849 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
2850 data_length, bytes_to_shift);
2851 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
2852 csp->client_iob->cur = csp->client_iob->buf;
2853 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
2854 csp->client_iob->eod = csp->client_iob->buf + data_length;
2855 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
2857 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
2862 * We mainly care about resetting client_iob->cur so we don't
2863 * waste buffer space at the beginning and don't mess up the
2864 * request restoration done by cgi_show_request().
2866 * Freeing the buffer itself isn't technically necessary,
2867 * but makes debugging more convenient.
2869 clear_iob(csp->client_iob);
2872 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2875 /*********************************************************************
2879 * Description : This is little more than chat. We only "serve" to
2880 * to close (or remember) any socket that chat may have
2884 * 1 : csp = Current client state (buffers, headers, etc...)
2888 *********************************************************************/
2890 void serve(struct client_state *csp)
2891 #else /* ifndef AMIGA */
2892 static void serve(struct client_state *csp)
2893 #endif /* def AMIGA */
2895 int config_file_change_detected = 0; /* Only used for debugging */
2896 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2897 #ifdef FEATURE_CONNECTION_SHARING
2898 static int monitor_thread_running = 0;
2899 #endif /* def FEATURE_CONNECTION_SHARING */
2900 int continue_chatting = 0;
2902 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
2903 csp->ip_addr_str, csp->cfd);
2907 unsigned int latency;
2912 * If the request has been crunched,
2913 * the calculated latency is zero.
2915 latency = (unsigned)(csp->server_connection.response_received -
2916 csp->server_connection.request_sent) / 2;
2918 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2919 && (csp->flags & CSP_FLAG_CRUNCHED)
2920 && (csp->expected_client_content_length != 0))
2922 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
2923 log_error(LOG_LEVEL_CONNECT,
2924 "Tainting client socket %d due to unread data.", csp->cfd);
2927 continue_chatting = (csp->config->feature_flags
2928 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2929 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2930 && (csp->cfd != JB_INVALID_SOCKET)
2931 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2932 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
2933 || (csp->flags & CSP_FLAG_CHUNKED));
2935 if (!(csp->flags & CSP_FLAG_CRUNCHED)
2936 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
2938 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
2940 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
2942 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2943 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2944 || !socket_is_still_alive(csp->server_connection.sfd)
2945 || !(latency < csp->server_connection.keep_alive_timeout))
2947 log_error(LOG_LEVEL_CONNECT,
2948 "Closing server socket %d connected to %s. "
2949 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
2950 csp->server_connection.sfd, csp->server_connection.host,
2951 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2952 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2953 socket_is_still_alive(csp->server_connection.sfd),
2954 csp->server_connection.keep_alive_timeout);
2955 #ifdef FEATURE_CONNECTION_SHARING
2956 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2958 forget_connection(csp->server_connection.sfd);
2960 #endif /* def FEATURE_CONNECTION_SHARING */
2961 close_socket(csp->server_connection.sfd);
2962 mark_connection_closed(&csp->server_connection);
2966 if (continue_chatting && any_loaded_file_changed(csp))
2968 continue_chatting = 0;
2969 config_file_change_detected = 1;
2972 if (continue_chatting)
2974 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
2975 && socket_is_still_alive(csp->cfd))
2977 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
2978 "pipelined on socket %d and the socket is still alive.",
2979 csp->requests_received_total+1, csp->cfd);
2980 prepare_csp_for_next_request(csp);
2984 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
2986 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2988 log_error(LOG_LEVEL_CONNECT,
2989 "Waiting for the next client request on socket %d. "
2990 "Keeping the server socket %d to %s open.",
2991 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2995 log_error(LOG_LEVEL_CONNECT,
2996 "Waiting for the next client request on socket %d. "
2997 "No server socket to keep open.", csp->cfd);
3001 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3002 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
3003 && socket_is_still_alive(csp->cfd))
3005 log_error(LOG_LEVEL_CONNECT,
3006 "Client request %u arrived in time on socket %d.",
3007 csp->requests_received_total+1, csp->cfd);
3008 prepare_csp_for_next_request(csp);
3012 #ifdef FEATURE_CONNECTION_SHARING
3013 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3014 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3015 && (socket_is_still_alive(csp->server_connection.sfd)))
3017 time_t time_open = time(NULL) - csp->server_connection.timestamp;
3019 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3024 remember_connection(&csp->server_connection);
3025 csp->server_connection.sfd = JB_INVALID_SOCKET;
3026 drain_and_close_socket(csp->cfd);
3027 csp->cfd = JB_INVALID_SOCKET;
3028 privoxy_mutex_lock(&connection_reuse_mutex);
3029 if (!monitor_thread_running)
3031 monitor_thread_running = 1;
3032 privoxy_mutex_unlock(&connection_reuse_mutex);
3033 wait_for_alive_connections();
3034 privoxy_mutex_lock(&connection_reuse_mutex);
3035 monitor_thread_running = 0;
3037 privoxy_mutex_unlock(&connection_reuse_mutex);
3039 #endif /* def FEATURE_CONNECTION_SHARING */
3043 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3045 log_error(LOG_LEVEL_CONNECT,
3046 "Closing server socket %d connected to %s. Keep-alive: %u. "
3047 "Tainted: %u. Socket alive: %u. Timeout: %u. "
3048 "Configuration file change detected: %u",
3049 csp->server_connection.sfd, csp->server_connection.host,
3050 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3051 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3052 socket_is_still_alive(csp->server_connection.sfd),
3053 csp->server_connection.keep_alive_timeout,
3054 config_file_change_detected);
3056 } while (continue_chatting);
3060 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3062 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3064 #ifdef FEATURE_CONNECTION_SHARING
3065 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3067 forget_connection(csp->server_connection.sfd);
3069 #endif /* def FEATURE_CONNECTION_SHARING */
3070 close_socket(csp->server_connection.sfd);
3073 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3074 mark_connection_closed(&csp->server_connection);
3077 if (csp->cfd != JB_INVALID_SOCKET)
3079 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3080 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3081 "Configuration file change detected: %u. Requests received: %u.",
3082 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3083 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3084 config_file_change_detected, csp->requests_received_total);
3085 drain_and_close_socket(csp->cfd);
3088 csp->flags &= ~CSP_FLAG_ACTIVE;
3094 /*********************************************************************
3096 * Function : server_thread
3098 * Description : We only exist to call `serve' in a threaded environment.
3101 * 1 : data = Current client state (buffers, headers, etc...)
3103 * Returns : Always 0.
3105 *********************************************************************/
3106 static int32 server_thread(void *data)
3108 serve((struct client_state *) data);
3115 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3116 /*********************************************************************
3120 * Description : Print usage info & exit.
3122 * Parameters : Pointer to argv[0] for identifying ourselves
3126 *********************************************************************/
3127 static void usage(const char *myname)
3129 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3130 "Usage: %s [--config-test] "
3133 #endif /* defined(unix) */
3136 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3137 #endif /* defined(unix) */
3138 "[--version] [configfile]\n"
3139 "Aborting\n", myname);
3144 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3147 #ifdef MUTEX_LOCKS_AVAILABLE
3148 /*********************************************************************
3150 * Function : privoxy_mutex_lock
3152 * Description : Locks a mutex.
3155 * 1 : mutex = The mutex to lock.
3157 * Returns : Void. May exit in case of errors.
3159 *********************************************************************/
3160 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3162 #ifdef FEATURE_PTHREAD
3163 int err = pthread_mutex_lock(mutex);
3166 if (mutex != &log_mutex)
3168 log_error(LOG_LEVEL_FATAL,
3169 "Mutex locking failed: %s.\n", strerror(err));
3174 EnterCriticalSection(mutex);
3175 #endif /* def FEATURE_PTHREAD */
3179 /*********************************************************************
3181 * Function : privoxy_mutex_unlock
3183 * Description : Unlocks a mutex.
3186 * 1 : mutex = The mutex to unlock.
3188 * Returns : Void. May exit in case of errors.
3190 *********************************************************************/
3191 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3193 #ifdef FEATURE_PTHREAD
3194 int err = pthread_mutex_unlock(mutex);
3197 if (mutex != &log_mutex)
3199 log_error(LOG_LEVEL_FATAL,
3200 "Mutex unlocking failed: %s.\n", strerror(err));
3205 LeaveCriticalSection(mutex);
3206 #endif /* def FEATURE_PTHREAD */
3210 /*********************************************************************
3212 * Function : privoxy_mutex_init
3214 * Description : Prepares a mutex.
3217 * 1 : mutex = The mutex to initialize.
3219 * Returns : Void. May exit in case of errors.
3221 *********************************************************************/
3222 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3224 #ifdef FEATURE_PTHREAD
3225 int err = pthread_mutex_init(mutex, 0);
3228 printf("Fatal error. Mutex initialization failed: %s.\n",
3233 InitializeCriticalSection(mutex);
3234 #endif /* def FEATURE_PTHREAD */
3236 #endif /* def MUTEX_LOCKS_AVAILABLE */
3238 /*********************************************************************
3240 * Function : initialize_mutexes
3242 * Description : Prepares mutexes if mutex support is available.
3246 * Returns : Void, exits in case of errors.
3248 *********************************************************************/
3249 static void initialize_mutexes(void)
3251 #ifdef MUTEX_LOCKS_AVAILABLE
3253 * Prepare global mutex semaphores
3255 privoxy_mutex_init(&log_mutex);
3256 privoxy_mutex_init(&log_init_mutex);
3257 privoxy_mutex_init(&connection_reuse_mutex);
3258 #ifdef FEATURE_EXTERNAL_FILTERS
3259 privoxy_mutex_init(&external_filter_mutex);
3261 #ifdef FEATURE_CLIENT_TAGS
3262 privoxy_mutex_init(&client_tags_mutex);
3266 * XXX: The assumptions below are a bit naive
3267 * and can cause locks that aren't necessary.
3269 * For example older FreeBSD versions (< 6.x?)
3270 * have no gethostbyname_r, but gethostbyname is
3273 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3274 privoxy_mutex_init(&resolver_mutex);
3275 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3277 * XXX: should we use a single mutex for
3278 * localtime() and gmtime() as well?
3280 #ifndef HAVE_GMTIME_R
3281 privoxy_mutex_init(&gmtime_mutex);
3282 #endif /* ndef HAVE_GMTIME_R */
3284 #ifndef HAVE_LOCALTIME_R
3285 privoxy_mutex_init(&localtime_mutex);
3286 #endif /* ndef HAVE_GMTIME_R */
3289 privoxy_mutex_init(&rand_mutex);
3290 #endif /* ndef HAVE_RANDOM */
3292 #endif /* def MUTEX_LOCKS_AVAILABLE */
3296 /*********************************************************************
3300 * Description : Load the config file and start the listen loop.
3301 * This function is a lot more *sane* with the `load_config'
3302 * and `listen_loop' functions; although it stills does
3303 * a *little* too much for my taste.
3306 * 1 : argc = Number of parameters (including $0).
3307 * 2 : argv = Array of (char *)'s to the parameters.
3309 * Returns : 1 if : can't open config file, unrecognized directive,
3310 * stats requested in multi-thread mode, can't open the
3311 * log file, can't open the jar file, listen port is invalid,
3312 * any load fails, and can't bind port.
3314 * Else main never returns, the process must be signaled
3315 * to terminate execution. Or, on Windows, use the
3316 * "File", "Exit" menu option.
3318 *********************************************************************/
3320 int real_main(int argc, char **argv)
3322 int main(int argc, char **argv)
3326 int do_config_test = 0;
3327 unsigned int random_seed;
3329 struct passwd *pw = NULL;
3330 struct group *grp = NULL;
3332 char *pre_chroot_nslookup_to_load_resolver = NULL;
3339 #if !defined(_WIN32)
3346 /* Prepare mutexes if supported and necessary. */
3347 initialize_mutexes();
3349 /* Enable logging until further notice. */
3353 * Parse the command line arguments
3355 * XXX: simply printing usage information in case of
3356 * invalid arguments isn't particularly user friendly.
3358 while (++argc_pos < argc)
3361 /* Check to see if the service must be installed or uninstalled */
3362 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3364 const char *pName = argv[argc_pos] + 9;
3367 exit((install_service(pName)) ? 0 : 1);
3369 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3371 const char *pName = argv[argc_pos] + 11;
3374 exit((uninstall_service(pName)) ? 0 : 1);
3376 else if (strcmp(argv[argc_pos], "--service") == 0)
3378 bRunAsService = TRUE;
3379 w32_set_service_cwd();
3380 atexit(w32_service_exit_notify);
3383 #endif /* defined(_WIN32) */
3386 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3388 if (strcmp(argv[argc_pos], "--help") == 0)
3393 else if (strcmp(argv[argc_pos], "--version") == 0)
3395 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3401 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3403 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3407 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3409 if (++argc_pos == argc) usage(argv[0]);
3410 pidfile = strdup_or_die(argv[argc_pos]);
3413 else if (strcmp(argv[argc_pos], "--user") == 0)
3418 if (++argc_pos == argc) usage(argv[argc_pos]);
3420 user_arg = strdup_or_die(argv[argc_pos]);
3421 group_name = strchr(user_arg, '.');
3422 if (NULL != group_name)
3424 /* Nul-terminate the user name */
3427 /* Skip the former delimiter to actually reach the group name */
3430 grp = getgrnam(group_name);
3433 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3436 pw = getpwnam(user_arg);
3439 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3445 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3447 if (++argc_pos == argc) usage(argv[0]);
3448 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3451 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3455 #endif /* defined(unix) */
3457 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3462 else if (argc_pos + 1 != argc)
3465 * This is neither the last command line
3466 * option, nor was it recognized before,
3467 * therefore it must be invalid.
3473 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3475 configfile = argv[argc_pos];
3478 } /* -END- while (more arguments) */
3480 show_version(Argv[0]);
3483 if (*configfile != '/')
3485 char cwd[BUFFER_SIZE];
3487 size_t abs_file_size;
3489 /* make config-filename absolute here */
3490 if (NULL == getcwd(cwd, sizeof(cwd)))
3492 perror("failed to get current working directory");
3496 basedir = strdup_or_die(cwd);
3498 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3499 abs_file = malloc_or_die(abs_file_size);
3500 strlcpy(abs_file, basedir, abs_file_size);
3501 strlcat(abs_file, "/", abs_file_size);
3502 strlcat(abs_file, configfile, abs_file_size);
3503 configfile = abs_file;
3505 #endif /* defined unix */
3509 clients->next = NULL;
3511 /* XXX: factor out initialising after the next stable release. */
3514 #elif defined(_WIN32)
3518 random_seed = (unsigned int)time(NULL);
3520 srandom(random_seed);
3523 #endif /* ifdef HAVE_RANDOM */
3526 * Unix signal handling
3528 * Catch the abort, interrupt and terminate signals for a graceful exit
3529 * Catch the hangup signal so the errlog can be reopened.
3530 * Ignore the broken pipe signals (FIXME: Why?)
3532 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3535 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3537 for (idx = 0; idx < SZ(catched_signals); idx++)
3539 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3540 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3542 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3543 #endif /* ifdef sun */
3545 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3549 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3551 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3555 #else /* ifdef _WIN32 */
3556 # ifdef _WIN_CONSOLE
3558 * We *are* in a windows console app.
3559 * Print a verbose messages about FAQ's and such
3561 printf("%s", win32_blurb);
3562 # endif /* def _WIN_CONSOLE */
3563 #endif /* def _WIN32 */
3567 exit(NULL == load_config());
3570 /* Initialize the CGI subsystem */
3571 cgi_init_error_messages();
3574 * If running on unix and without the --no-daemon
3575 * option, become a daemon. I.e. fork, detach
3576 * from tty and get process group leadership
3585 if (pid < 0) /* error */
3590 else if (pid != 0) /* parent */
3595 * must check for errors
3596 * child died due to missing files aso
3599 wpid = waitpid(pid, &status, WNOHANG);
3611 * stderr (fd 2) will be closed later on,
3612 * when the config file has been parsed.
3618 * Reserve fd 0 and 1 to prevent abort() and friends
3619 * from sending stuff to the clients or servers.
3621 fd = open("/dev/null", O_RDONLY);
3624 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3628 if (dup2(fd, 0) == -1)
3630 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3634 fd = open("/dev/null", O_WRONLY);
3637 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3641 if (dup2(fd, 1) == -1)
3643 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3648 #ifdef FEATURE_EXTERNAL_FILTERS
3649 for (fd = 0; fd < 3; fd++)
3651 mark_socket_for_close_on_execute(fd);
3657 } /* -END- if (daemon_mode) */
3660 * As soon as we have written the PID file, we can switch
3661 * to the user and group ID indicated by the --user option
3667 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3669 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3673 if (setgroups(1, &grp->gr_gid))
3675 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3678 else if (initgroups(pw->pw_name, pw->pw_gid))
3680 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3686 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3688 /* Read the time zone file from /etc before doing chroot. */
3690 if (NULL != pre_chroot_nslookup_to_load_resolver
3691 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3693 /* Initialize resolver library. */
3694 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3696 if (chroot(pw->pw_dir) < 0)
3698 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3702 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3705 if (setuid(pw->pw_uid))
3707 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3711 char putenv_dummy[64];
3713 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3714 if (putenv(putenv_dummy) != 0)
3716 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3719 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3720 if (putenv(putenv_dummy) != 0)
3722 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3728 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3731 #endif /* defined unix */
3734 /* This will be FALSE unless the command line specified --service
3738 /* Yup, so now we must attempt to establish a connection
3739 * with the service dispatcher. This will only work if this
3740 * process was launched by the service control manager to
3741 * actually run as a service. If this isn't the case, i've
3742 * known it take around 30 seconds or so for the call to return.
3745 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3746 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3748 /* Service has run, and at this point is now being stopped, so just return */
3753 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3755 /* An error occurred. Usually it's because --service was wrongly specified
3756 * and we were unable to connect to the Service Control Dispatcher because
3757 * it wasn't expecting us and is therefore not listening.
3759 * For now, just continue below to call the listen_loop function.
3762 #endif /* def _WIN32 */
3772 /*********************************************************************
3774 * Function : bind_port_helper
3776 * Description : Bind the listen port. Handles logging, and aborts
3780 * 1 : haddr = Host address to bind to. Use NULL to bind to
3782 * 2 : hport = Specifies port to bind to.
3784 * Returns : Port that was opened.
3786 *********************************************************************/
3787 static jb_socket bind_port_helper(const char *haddr, int hport)
3792 result = bind_port(haddr, hport, &bfd);
3796 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
3800 log_error(LOG_LEVEL_FATAL,
3801 "can't bind to %s:%d: There may be another Privoxy "
3802 "or some other proxy running on port %d",
3803 bind_address, hport, hport);
3806 log_error(LOG_LEVEL_FATAL,
3807 "can't bind to %s:%d: The hostname is not resolvable",
3808 bind_address, hport);
3811 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3812 bind_address, hport);
3815 /* shouldn't get here */
3816 return JB_INVALID_SOCKET;
3820 if (bfd >= FD_SETSIZE)
3822 log_error(LOG_LEVEL_FATAL,
3823 "Bind socket number too high to use select(): %d >= %d",
3830 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3835 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3843 /*********************************************************************
3845 * Function : bind_ports_helper
3847 * Description : Bind the listen ports. Handles logging, and aborts
3851 * 1 : config = Privoxy configuration. Specifies ports
3853 * 2 : sockets = Preallocated array of opened sockets
3854 * corresponding to specification in config.
3855 * All non-opened sockets will be set to
3856 * JB_INVALID_SOCKET.
3858 * Returns : Nothing. Inspect sockets argument.
3860 *********************************************************************/
3861 static void bind_ports_helper(struct configuration_spec * config,
3862 jb_socket sockets[])
3866 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3868 if (config->hport[i])
3870 sockets[i] = bind_port_helper(config->haddr[i], config->hport[i]);
3874 sockets[i] = JB_INVALID_SOCKET;
3877 config->need_bind = 0;
3881 /*********************************************************************
3883 * Function : close_ports_helper
3885 * Description : Close listenings ports.
3888 * 1 : sockets = Array of opened and non-opened sockets to
3889 * close. All sockets will be set to
3890 * JB_INVALID_SOCKET.
3892 * Returns : Nothing.
3894 *********************************************************************/
3895 static void close_ports_helper(jb_socket sockets[])
3899 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3901 if (JB_INVALID_SOCKET != sockets[i])
3903 close_socket(sockets[i]);
3905 sockets[i] = JB_INVALID_SOCKET;
3911 /* Without this simple workaround we get this compiler warning from _beginthread
3912 * warning C4028: formal parameter 1 different from declaration
3914 void w32_service_listen_loop(void *p)
3918 #endif /* def _WIN32 */
3921 /*********************************************************************
3923 * Function : listen_loop
3925 * Description : bind the listen port and enter a "FOREVER" listening loop.
3931 *********************************************************************/
3932 static void listen_loop(void)
3934 struct client_states *csp_list = NULL;
3935 struct client_state *csp = NULL;
3936 jb_socket bfds[MAX_LISTENING_SOCKETS];
3937 struct configuration_spec *config;
3938 unsigned int active_threads = 0;
3940 config = load_config();
3942 #ifdef FEATURE_CONNECTION_SHARING
3944 * XXX: Should be relocated once it no
3945 * longer needs to emit log messages.
3947 initialize_reusable_connections();
3948 #endif /* def FEATURE_CONNECTION_SHARING */
3950 bind_ports_helper(config, bfds);
3952 #ifdef FEATURE_GRACEFUL_TERMINATION
3953 while (!g_terminate)
3958 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3959 while (waitpid(-1, NULL, WNOHANG) > 0)
3961 /* zombie children */
3963 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3966 * Free data that was used by died threads
3968 active_threads = sweep();
3972 * Re-open the errlog after HUP signal
3974 if (received_hup_signal)
3976 if (NULL != config->logfile)
3978 init_error_log(Argv[0], config->logfile);
3980 received_hup_signal = 0;
3984 csp_list = zalloc_or_die(sizeof(*csp_list));
3985 csp = &csp_list->csp;
3987 log_error(LOG_LEVEL_CONNECT,
3988 "Waiting for the next client connection. Currently active threads: %d",
3991 if (!accept_connection(csp, bfds))
3993 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
4005 csp->flags |= CSP_FLAG_ACTIVE;
4006 csp->server_connection.sfd = JB_INVALID_SOCKET;
4008 csp->config = config = load_config();
4010 if (config->need_bind)
4013 * Since we were listening to the "old port", we will not see
4014 * a "listen" param change until the next request. So, at
4015 * least 1 more request must be made for us to find the new
4016 * setting. I am simply closing the old socket and binding the
4019 * Which-ever is correct, we will serve 1 more page via the
4020 * old settings. This should probably be a "show-proxy-args"
4021 * request. This should not be a so common of an operation
4022 * that this will hurt people's feelings.
4025 close_ports_helper(bfds);
4027 bind_ports_helper(config, bfds);
4030 #ifdef FEATURE_TOGGLE
4031 if (global_toggle_state)
4032 #endif /* def FEATURE_TOGGLE */
4034 csp->flags |= CSP_FLAG_TOGGLED_ON;
4037 if (run_loader(csp))
4039 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
4040 /* Never get here - LOG_LEVEL_FATAL causes program exit */
4044 if (block_acl(NULL,csp))
4046 log_error(LOG_LEVEL_CONNECT,
4047 "Connection from %s on socket %d dropped due to ACL", csp->ip_addr_str, csp->cfd);
4048 close_socket(csp->cfd);
4049 freez(csp->ip_addr_str);
4053 #endif /* def FEATURE_ACL */
4055 if ((0 != config->max_client_connections)
4056 && (active_threads >= config->max_client_connections))
4058 log_error(LOG_LEVEL_CONNECT,
4059 "Rejecting connection from %s. Maximum number of connections reached.",
4061 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4062 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4063 close_socket(csp->cfd);
4064 freez(csp->ip_addr_str);
4069 /* add it to the list of clients */
4070 csp_list->next = clients->next;
4071 clients->next = csp_list;
4073 if (config->multi_threaded)
4077 /* this is a switch () statement in the C preprocessor - ugh */
4078 #undef SELECTED_ONE_OPTION
4080 /* Use Pthreads in preference to native code */
4081 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
4082 #define SELECTED_ONE_OPTION
4084 pthread_t the_thread;
4085 pthread_attr_t attrs;
4087 pthread_attr_init(&attrs);
4088 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4089 errno = pthread_create(&the_thread, &attrs,
4090 (void * (*)(void *))serve, csp);
4091 child_id = errno ? -1 : 0;
4092 pthread_attr_destroy(&attrs);
4096 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
4097 #define SELECTED_ONE_OPTION
4098 child_id = _beginthread(
4099 (void (*)(void *))serve,
4104 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
4105 #define SELECTED_ONE_OPTION
4106 child_id = _beginthread(
4107 (void(* _Optlink)(void*))serve,
4113 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
4114 #define SELECTED_ONE_OPTION
4116 thread_id tid = spawn_thread
4117 (server_thread, "server", B_NORMAL_PRIORITY, csp);
4119 if ((tid >= 0) && (resume_thread(tid) == B_OK))
4121 child_id = (int) tid;
4130 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
4131 #define SELECTED_ONE_OPTION
4132 csp->cfd = ReleaseSocket(csp->cfd, -1);
4135 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4136 NP_Output, Output(),
4137 NP_CloseOutput, FALSE,
4138 NP_Name, (ULONG)"privoxy child",
4142 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4143 NP_Output, Output(),
4144 NP_CloseOutput, FALSE,
4145 NP_Name, (ULONG)"privoxy child",
4146 NP_StackSize, 200*1024,
4152 ((struct Task *)child_id)->tc_UserData = csp;
4153 Signal((struct Task *)child_id, SIGF_SINGLE);
4158 #if !defined(SELECTED_ONE_OPTION)
4161 /* This block is only needed when using fork().
4162 * When using threads, the server thread was
4163 * created and run by the call to _beginthread().
4165 if (child_id == 0) /* child */
4168 #ifdef FEATURE_TOGGLE
4169 int inherited_toggle_state = global_toggle_state;
4170 #endif /* def FEATURE_TOGGLE */
4175 * If we've been toggled or we've blocked the request, tell Mom
4178 #ifdef FEATURE_TOGGLE
4179 if (inherited_toggle_state != global_toggle_state)
4181 rc |= RC_FLAG_TOGGLED;
4183 #endif /* def FEATURE_TOGGLE */
4185 #ifdef FEATURE_STATISTICS
4186 if (csp->flags & CSP_FLAG_REJECTED)
4188 rc |= RC_FLAG_BLOCKED;
4190 #endif /* ndef FEATURE_STATISTICS */
4194 else if (child_id > 0) /* parent */
4196 /* in a fork()'d environment, the parent's
4197 * copy of the client socket and the CSP
4201 #if !defined(_WIN32) && !defined(__CYGWIN__)
4203 wait(&child_status);
4206 * Evaluate child's return code: If the child has
4207 * - been toggled, toggle ourselves
4208 * - blocked its request, bump up the stats counter
4211 #ifdef FEATURE_TOGGLE
4212 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4214 global_toggle_state = !global_toggle_state;
4216 #endif /* def FEATURE_TOGGLE */
4218 #ifdef FEATURE_STATISTICS
4220 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4224 #endif /* def FEATURE_STATISTICS */
4226 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4227 close_socket(csp->cfd);
4228 csp->flags &= ~CSP_FLAG_ACTIVE;
4232 #undef SELECTED_ONE_OPTION
4233 /* end of cpp switch () */
4238 * Spawning the child failed, assume it's because
4239 * there are too many children running already.
4240 * XXX: If you assume ...
4242 log_error(LOG_LEVEL_ERROR,
4243 "Unable to take any additional connections: %E. Active threads: %d",
4245 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4246 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4247 close_socket(csp->cfd);
4248 csp->flags &= ~CSP_FLAG_ACTIVE;
4257 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4259 /* Clean up. Aim: free all memory (no leaks) */
4260 #ifdef FEATURE_GRACEFUL_TERMINATION
4262 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4264 unload_current_config_file();
4265 unload_current_actions_file();
4266 unload_current_re_filterfile();
4267 #ifdef FEATURE_TRUST
4268 unload_current_trust_file();
4271 if (config->multi_threaded)
4278 } while ((clients->next != NULL) && (--i > 0));
4282 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4292 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4293 /* Cleanup - remove taskbar icon etc. */
4298 #endif /* FEATURE_GRACEFUL_TERMINATION */