1 const char jcc_rcs[] = "$Id: jcc.c,v 1.468 2017/08/12 09:33:25 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-2017 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
53 # include <winsock2.h>
56 # endif /* ndef FEATURE_PTHREAD */
61 # endif /* ndef _WIN_CONSOLE */
62 # include "w32svrapi.h"
64 #else /* ifndef _WIN32 */
66 # if !defined (__OS2__)
68 # include <sys/wait.h>
69 # endif /* ndef __OS2__ */
70 # include <sys/time.h>
71 # include <sys/stat.h>
72 # include <sys/ioctl.h>
75 #include <sys/termios.h>
86 # include <socket.h> /* BeOS has select() for sockets only. */
87 # include <OS.h> /* declarations for threads and stuff. */
90 # if defined(__EMX__) || defined(__OS2__)
91 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
100 #include <sys/poll.h>
103 #endif /* def __GLIBC__ */
108 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
109 #endif /* HAVE_POLL */
119 #include "miscutil.h"
121 #include "jbsockets.h"
126 #include "urlmatch.h"
127 #ifdef FEATURE_CLIENT_TAGS
128 #include "client-tags.h"
131 const char jcc_h_rcs[] = JCC_H_VERSION;
132 const char project_h_rcs[] = PROJECT_H_VERSION;
135 struct client_states clients[1];
136 struct file_list files[1];
138 #ifdef FEATURE_STATISTICS
139 int urls_read = 0; /* total nr of urls read inc rejected */
140 int urls_rejected = 0; /* total nr of urls rejected */
141 #endif /* def FEATURE_STATISTICS */
143 #ifdef FEATURE_GRACEFUL_TERMINATION
147 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
148 static void sig_handler(int the_signal);
150 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
151 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
152 static jb_err get_server_headers(struct client_state *csp);
153 static const char *crunch_reason(const struct http_response *rsp);
154 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
155 static char *get_request_line(struct client_state *csp);
156 static jb_err receive_client_request(struct client_state *csp);
157 static jb_err parse_client_request(struct client_state *csp);
158 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
159 static jb_err change_request_destination(struct client_state *csp);
160 static void chat(struct client_state *csp);
161 static void serve(struct client_state *csp);
162 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
163 static void usage(const char *myname);
165 static void initialize_mutexes(void);
166 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
167 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
168 static void close_ports_helper(jb_socket sockets[]);
169 static void listen_loop(void);
172 void serve(struct client_state *csp);
173 #else /* ifndef AMIGA */
174 static void serve(struct client_state *csp);
175 #endif /* def AMIGA */
178 static int32 server_thread(void *data);
179 #endif /* def __BEOS__ */
182 #define sleep(N) Sleep(((N) * 1000))
186 #define sleep(N) DosSleep(((N) * 100))
190 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
191 void show_fuzz_usage(const char *name);
194 #ifdef MUTEX_LOCKS_AVAILABLE
196 * XXX: Does the locking stuff really belong in this file?
198 privoxy_mutex_t log_mutex;
199 privoxy_mutex_t log_init_mutex;
200 privoxy_mutex_t connection_reuse_mutex;
202 #ifdef FEATURE_EXTERNAL_FILTERS
203 privoxy_mutex_t external_filter_mutex;
205 #ifdef FEATURE_CLIENT_TAGS
206 privoxy_mutex_t client_tags_mutex;
209 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
210 privoxy_mutex_t resolver_mutex;
211 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
213 #ifndef HAVE_GMTIME_R
214 privoxy_mutex_t gmtime_mutex;
215 #endif /* ndef HAVE_GMTIME_R */
217 #ifndef HAVE_LOCALTIME_R
218 privoxy_mutex_t localtime_mutex;
219 #endif /* ndef HAVE_GMTIME_R */
221 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
222 privoxy_mutex_t rand_mutex;
223 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
225 #endif /* def MUTEX_LOCKS_AVAILABLE */
228 const char *basedir = NULL;
229 const char *pidfile = NULL;
230 static int received_hup_signal = 0;
231 #endif /* defined unix */
233 /* HTTP snipplets. */
234 static const char CSUCCEED[] =
235 "HTTP/1.1 200 Connection established\r\n\r\n";
237 static const char CHEADER[] =
238 "HTTP/1.1 400 Invalid header received from client\r\n"
239 "Content-Type: text/plain\r\n"
240 "Connection: close\r\n\r\n"
241 "Invalid header received from client.\r\n";
243 static const char FTP_RESPONSE[] =
244 "HTTP/1.1 400 Invalid request received from client\r\n"
245 "Content-Type: text/plain\r\n"
246 "Connection: close\r\n\r\n"
247 "Invalid request. Privoxy doesn't support FTP.\r\n";
249 static const char GOPHER_RESPONSE[] =
250 "HTTP/1.1 400 Invalid request received from client\r\n"
251 "Content-Type: text/plain\r\n"
252 "Connection: close\r\n\r\n"
253 "Invalid request. Privoxy doesn't support gopher.\r\n";
255 /* XXX: should be a template */
256 static const char MISSING_DESTINATION_RESPONSE[] =
257 "HTTP/1.1 400 Bad request received from client\r\n"
258 "Content-Type: text/plain\r\n"
259 "Connection: close\r\n\r\n"
260 "Bad request. Privoxy was unable to extract the destination.\r\n";
262 /* XXX: should be a template */
263 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
264 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
265 "Content-Type: text/plain\r\n"
266 "Connection: close\r\n\r\n"
267 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
269 /* XXX: should be a template */
270 static const char MESSED_UP_REQUEST_RESPONSE[] =
271 "HTTP/1.1 400 Malformed request after rewriting\r\n"
272 "Content-Type: text/plain\r\n"
273 "Connection: close\r\n\r\n"
274 "Bad request. Messed up with header filters.\r\n";
276 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
277 "HTTP/1.1 503 Too many open connections\r\n"
278 "Content-Type: text/plain\r\n"
279 "Connection: close\r\n\r\n"
280 "Maximum number of open connections reached.\r\n";
282 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
283 "HTTP/1.1 504 Connection timeout\r\n"
284 "Content-Type: text/plain\r\n"
285 "Connection: close\r\n\r\n"
286 "The connection timed out because the client request didn't arrive in time.\r\n";
288 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
289 "HTTP/1.1 400 Failed reading client body\r\n"
290 "Content-Type: text/plain\r\n"
291 "Connection: close\r\n\r\n"
292 "Failed parsing or buffering the chunk-encoded client body.\r\n";
294 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
295 "HTTP/1.1 417 Expecting too much\r\n"
296 "Content-Type: text/plain\r\n"
297 "Connection: close\r\n\r\n"
298 "Privoxy detected an unsupported Expect header value.\r\n";
300 /* A function to crunch a response */
301 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
303 /* Crunch function flags */
304 #define CF_NO_FLAGS 0
305 /* Cruncher applies to forced requests as well */
306 #define CF_IGNORE_FORCE 1
307 /* Crunched requests are counted for the block statistics */
308 #define CF_COUNT_AS_REJECT 2
310 /* A crunch function and its flags */
313 const crunch_func_ptr cruncher;
317 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
319 /* Complete list of cruncher functions */
320 static const struct cruncher crunchers_all[] = {
321 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
322 { block_url, CF_COUNT_AS_REJECT },
324 { trust_url, CF_COUNT_AS_REJECT },
325 #endif /* def FEATURE_TRUST */
326 { redirect_url, CF_NO_FLAGS },
327 { dispatch_cgi, CF_IGNORE_FORCE},
331 /* Light version, used after tags are applied */
332 static const struct cruncher crunchers_light[] = {
333 { block_url, CF_COUNT_AS_REJECT },
334 { redirect_url, CF_NO_FLAGS },
340 * XXX: Don't we really mean
346 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
347 /*********************************************************************
349 * Function : sig_handler
351 * Description : Signal handler for different signals.
352 * Exit gracefully on TERM and INT
353 * or set a flag that will cause the errlog
354 * to be reopened by the main thread on HUP.
357 * 1 : the_signal = the signal cause this function to call
361 *********************************************************************/
362 static void sig_handler(int the_signal)
368 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
380 received_hup_signal = 1;
386 * We shouldn't be here, unless we catch signals
387 * in main() that we can't handle here!
389 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
397 /*********************************************************************
399 * Function : client_protocol_is_unsupported
401 * Description : Checks if the client used a known unsupported
402 * protocol and deals with it by sending an error
406 * 1 : csp = Current client state (buffers, headers, etc...)
407 * 2 : req = the first request line send by the client
409 * Returns : TRUE if an error response has been generated, or
410 * FALSE if the request doesn't look invalid.
412 *********************************************************************/
413 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
416 * If it's a FTP or gopher request, we don't support it.
418 * These checks are better than nothing, but they might
419 * not work in all configurations and some clients might
420 * have problems digesting the answer.
422 * They should, however, never cause more problems than
423 * Privoxy's old behaviour (returning the misleading HTML
426 * "Could not resolve http://(ftp|gopher)://example.org").
428 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
430 const char *response = NULL;
431 const char *protocol = NULL;
433 if (!strncmpic(req, "GET ftp://", 10))
435 response = FTP_RESPONSE;
440 response = GOPHER_RESPONSE;
443 log_error(LOG_LEVEL_ERROR,
444 "%s tried to use Privoxy as %s proxy: %s",
445 csp->ip_addr_str, protocol, req);
446 log_error(LOG_LEVEL_CLF,
447 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
449 write_socket(csp->cfd, response, strlen(response));
458 /*********************************************************************
460 * Function : client_has_unsupported_expectations
462 * Description : Checks if the client used an unsupported expectation
463 * in which case an error message is delivered.
466 * 1 : csp = Current client state (buffers, headers, etc...)
468 * Returns : TRUE if an error response has been generated, or
469 * FALSE if the request doesn't look invalid.
471 *********************************************************************/
472 static int client_has_unsupported_expectations(const struct client_state *csp)
474 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
476 log_error(LOG_LEVEL_ERROR,
477 "Rejecting request from client %s with unsupported Expect header value",
479 log_error(LOG_LEVEL_CLF,
480 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
481 write_socket(csp->cfd, UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
482 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE));
492 /*********************************************************************
494 * Function : get_request_destination_elsewhere
496 * Description : If the client's request was redirected into
497 * Privoxy without the client's knowledge,
498 * the request line lacks the destination host.
500 * This function tries to get it elsewhere,
501 * provided accept-intercepted-requests is enabled.
503 * "Elsewhere" currently only means "Host: header",
504 * but in the future we may ask the redirecting
505 * packet filter to look the destination up.
507 * If the destination stays unknown, an error
508 * response is send to the client and headers
509 * are freed so that chat() can return directly.
512 * 1 : csp = Current client state (buffers, headers, etc...)
513 * 2 : headers = a header list
515 * Returns : JB_ERR_OK if the destination is now known, or
516 * JB_ERR_PARSE if it isn't.
518 *********************************************************************/
519 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
523 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
525 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
526 " Privoxy isn't configured to accept intercepted requests.",
527 csp->ip_addr_str, csp->http->cmd);
528 /* XXX: Use correct size */
529 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
530 csp->ip_addr_str, csp->http->cmd);
532 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
533 destroy_list(headers);
537 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
539 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
540 /* Split the domain we just got for pattern matching */
541 init_domain_components(csp->http);
548 /* We can't work without destination. Go spread the news.*/
550 req = list_to_text(headers);
552 /* XXX: Use correct size */
553 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
554 csp->ip_addr_str, csp->http->cmd);
555 log_error(LOG_LEVEL_ERROR,
556 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
557 csp->ip_addr_str, csp->http->cmd, req);
560 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
561 destroy_list(headers);
566 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
567 * to get the destination IP address, use it as host directly
568 * or do a reverse DNS lookup first.
573 /*********************************************************************
575 * Function : get_server_headers
577 * Description : Parses server headers in iob and fills them
578 * into csp->headers so that they can later be
582 * 1 : csp = Current client state (buffers, headers, etc...)
584 * Returns : JB_ERR_OK if everything went fine, or
585 * JB_ERR_PARSE if the headers were incomplete.
587 *********************************************************************/
588 static jb_err get_server_headers(struct client_state *csp)
590 int continue_hack_in_da_house = 0;
593 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
598 * continue hack in da house. Ignore the ending of
599 * this head and continue enlisting header lines.
600 * The reason is described below.
602 enlist(csp->headers, "");
603 continue_hack_in_da_house = 0;
606 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
609 * It's a bodyless continue response, don't
610 * stop header parsing after reaching its end.
612 * As a result Privoxy will concatenate the
613 * next response's head and parse and deliver
614 * the headers as if they belonged to one request.
616 * The client will separate them because of the
617 * empty line between them.
619 * XXX: What we're doing here is clearly against
620 * the intended purpose of the continue header,
621 * and under some conditions (HTTP/1.0 client request)
622 * it's a standard violation.
624 * Anyway, "sort of against the spec" is preferable
625 * to "always getting confused by Continue responses"
626 * (Privoxy's behaviour before this hack was added)
628 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
629 continue_hack_in_da_house = 1;
631 else if (*header == '\0')
634 * If the header is empty, but the Continue hack
635 * isn't active, we can assume that we reached the
636 * end of the buffer before we hit the end of the
639 * Inform the caller an let it decide how to handle it.
644 if (JB_ERR_MEMORY == enlist(csp->headers, header))
647 * XXX: Should we quit the request and return a
648 * out of memory error page instead?
650 log_error(LOG_LEVEL_ERROR,
651 "Out of memory while enlisting server headers. %s lost.",
661 /*********************************************************************
663 * Function : crunch_reason
665 * Description : Translates the crunch reason code into a string.
668 * 1 : rsp = a http_response
670 * Returns : A string with the crunch reason or an error description.
672 *********************************************************************/
673 static const char *crunch_reason(const struct http_response *rsp)
675 char * reason = NULL;
680 return "Internal error while searching for crunch reason";
683 switch (rsp->crunch_reason)
686 reason = "Unsupported HTTP feature";
692 reason = "Untrusted";
695 reason = "Redirected";
701 reason = "DNS failure";
703 case FORWARDING_FAILED:
704 reason = "Forwarding failed";
707 reason = "Connection failure";
710 reason = "Out of memory (may mask other reasons)";
712 case CONNECTION_TIMEOUT:
713 reason = "Connection timeout";
716 reason = "No server data received";
719 reason = "No reason recorded";
727 /*********************************************************************
729 * Function : log_applied_actions
731 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
735 * 1 : actions = Current action spec to log
739 *********************************************************************/
740 static void log_applied_actions(const struct current_action_spec *actions)
743 * The conversion to text requires lots of memory allocations so
744 * we only do the conversion if the user is actually interested.
746 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
748 char *actions_as_text = actions_to_line_of_text(actions);
749 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
750 freez(actions_as_text);
755 /*********************************************************************
757 * Function : send_crunch_response
759 * Description : Delivers already prepared response for
760 * intercepted requests, logs the interception
761 * and frees the response.
764 * 1 : csp = Current client state (buffers, headers, etc...)
765 * 1 : rsp = Fully prepared response. Will be freed on exit.
769 *********************************************************************/
770 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
772 const struct http_request *http = csp->http;
776 assert(rsp->head != NULL);
780 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
784 * Extract the status code from the actual head
785 * that will be send to the client. It is the only
786 * way to get it right for all requests, including
787 * the fixed ones for out-of-memory problems.
789 * A head starts like this: 'HTTP/1.1 200...'
793 status_code[0] = rsp->head[9];
794 status_code[1] = rsp->head[10];
795 status_code[2] = rsp->head[11];
796 status_code[3] = '\0';
798 /* Log that the request was crunched and why. */
799 log_applied_actions(csp->action);
800 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
801 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
802 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
804 /* Write the answer to the client */
805 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
806 || write_socket(csp->cfd, rsp->body, rsp->content_length))
808 /* There is nothing we can do about it. */
809 log_error(LOG_LEVEL_ERROR,
810 "Couldn't deliver the error message through client socket %d: %E",
814 /* Clean up and return */
815 if (cgi_error_memory() != rsp)
817 free_http_response(rsp);
823 /*********************************************************************
825 * Function : crunch_response_triggered
827 * Description : Checks if the request has to be crunched,
828 * and delivers the crunch response if necessary.
831 * 1 : csp = Current client state (buffers, headers, etc...)
832 * 2 : crunchers = list of cruncher functions to run
834 * Returns : TRUE if the request was answered with a crunch response
837 *********************************************************************/
838 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
840 struct http_response *rsp = NULL;
841 const struct cruncher *c;
844 * If CGI request crunching is disabled,
845 * check the CGI dispatcher out of order to
846 * prevent unintentional blocks or redirects.
848 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
849 && (NULL != (rsp = dispatch_cgi(csp))))
851 /* Deliver, log and free the interception response. */
852 send_crunch_response(csp, rsp);
853 csp->flags |= CSP_FLAG_CRUNCHED;
857 for (c = crunchers; c->cruncher != NULL; c++)
860 * Check the cruncher if either Privoxy is toggled
861 * on and the request isn't forced, or if the cruncher
862 * applies to forced requests as well.
864 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
865 !(csp->flags & CSP_FLAG_FORCED)) ||
866 (c->flags & CF_IGNORE_FORCE))
868 rsp = c->cruncher(csp);
871 /* Deliver, log and free the interception response. */
872 send_crunch_response(csp, rsp);
873 csp->flags |= CSP_FLAG_CRUNCHED;
874 #ifdef FEATURE_STATISTICS
875 if (c->flags & CF_COUNT_AS_REJECT)
877 csp->flags |= CSP_FLAG_REJECTED;
879 #endif /* def FEATURE_STATISTICS */
890 /*********************************************************************
892 * Function : build_request_line
894 * Description : Builds the HTTP request line.
896 * If a HTTP forwarder is used it expects the whole URL,
897 * web servers only get the path.
900 * 1 : csp = Current client state (buffers, headers, etc...)
901 * 2 : fwd = The forwarding spec used for the request
902 * XXX: Should use http->fwd instead.
903 * 3 : request_line = The old request line which will be replaced.
905 * Returns : Nothing. Terminates in case of memory problems.
907 *********************************************************************/
908 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
910 struct http_request *http = csp->http;
912 assert(http->ssl == 0);
915 * Downgrade http version from 1.1 to 1.0
916 * if +downgrade action applies.
918 if ((csp->action->flags & ACTION_DOWNGRADE)
919 && (!strcmpic(http->ver, "HTTP/1.1")))
922 http->ver = strdup_or_die("HTTP/1.0");
926 * Rebuild the request line.
928 freez(*request_line);
929 *request_line = strdup(http->gpc);
930 string_append(request_line, " ");
932 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
934 string_append(request_line, http->url);
938 string_append(request_line, http->path);
940 string_append(request_line, " ");
941 string_append(request_line, http->ver);
943 if (*request_line == NULL)
945 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
947 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
951 /*********************************************************************
953 * Function : change_request_destination
955 * Description : Parse a (rewritten) request line and regenerate
956 * the http request data.
959 * 1 : csp = Current client state (buffers, headers, etc...)
961 * Returns : Forwards the parse_http_request() return code.
962 * Terminates in case of memory problems.
964 *********************************************************************/
965 static jb_err change_request_destination(struct client_state *csp)
967 struct http_request *http = csp->http;
970 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
971 csp->headers->first->str);
972 free_http_request(http);
973 err = parse_http_request(csp->headers->first->str, http);
974 if (JB_ERR_OK != err)
976 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
977 jb_err_to_string(err));
984 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
985 /*********************************************************************
987 * Function : server_response_is_complete
989 * Description : Determines whether we should stop reading
990 * from the server socket.
993 * 1 : csp = Current client state (buffers, headers, etc...)
994 * 2 : content_length = Length of content received so far.
996 * Returns : TRUE if the response is complete,
999 *********************************************************************/
1000 static int server_response_is_complete(struct client_state *csp,
1001 unsigned long long content_length)
1003 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1005 if (!strcmpic(csp->http->gpc, "HEAD"))
1008 * "HEAD" implies no body, we are thus expecting
1009 * no content. XXX: incomplete "list" of methods?
1011 csp->expected_content_length = 0;
1012 content_length_known = TRUE;
1013 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1016 if (csp->http->status == 204 || csp->http->status == 304)
1019 * Expect no body. XXX: incomplete "list" of status codes?
1021 csp->expected_content_length = 0;
1022 content_length_known = TRUE;
1023 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1026 return (content_length_known && ((0 == csp->expected_content_length)
1027 || (csp->expected_content_length <= content_length)));
1031 #ifdef FEATURE_CONNECTION_SHARING
1032 /*********************************************************************
1034 * Function : wait_for_alive_connections
1036 * Description : Waits for alive connections to timeout.
1042 *********************************************************************/
1043 static void wait_for_alive_connections(void)
1045 int connections_alive = close_unusable_connections();
1047 while (0 < connections_alive)
1049 log_error(LOG_LEVEL_CONNECT,
1050 "Waiting for %d connections to timeout.",
1053 connections_alive = close_unusable_connections();
1056 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1059 #endif /* def FEATURE_CONNECTION_SHARING */
1062 /*********************************************************************
1064 * Function : save_connection_destination
1066 * Description : Remembers a connection for reuse later on.
1069 * 1 : sfd = Open socket to remember.
1070 * 2 : http = The destination for the connection.
1071 * 3 : fwd = The forwarder settings used.
1072 * 3 : server_connection = storage.
1076 *********************************************************************/
1077 void save_connection_destination(jb_socket sfd,
1078 const struct http_request *http,
1079 const struct forward_spec *fwd,
1080 struct reusable_connection *server_connection)
1082 assert(sfd != JB_INVALID_SOCKET);
1083 assert(NULL != http->host);
1085 server_connection->sfd = sfd;
1086 server_connection->host = strdup_or_die(http->host);
1087 server_connection->port = http->port;
1089 assert(NULL != fwd);
1090 assert(server_connection->gateway_host == NULL);
1091 assert(server_connection->gateway_port == 0);
1092 assert(server_connection->forwarder_type == 0);
1093 assert(server_connection->forward_host == NULL);
1094 assert(server_connection->forward_port == 0);
1096 server_connection->forwarder_type = fwd->type;
1097 if (NULL != fwd->gateway_host)
1099 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1103 server_connection->gateway_host = NULL;
1105 server_connection->gateway_port = fwd->gateway_port;
1107 if (NULL != fwd->forward_host)
1109 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1113 server_connection->forward_host = NULL;
1115 server_connection->forward_port = fwd->forward_port;
1119 /*********************************************************************
1121 * Function : verify_request_length
1123 * Description : Checks if we already got the whole client requests
1124 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1127 * Data that doesn't belong to the current request is
1128 * either thrown away to let the client retry on a clean
1129 * socket, or stashed to be dealt with after the current
1130 * request is served.
1133 * 1 : csp = Current client state (buffers, headers, etc...)
1137 *********************************************************************/
1138 static void verify_request_length(struct client_state *csp)
1140 unsigned long long buffered_request_bytes =
1141 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1143 if ((csp->expected_client_content_length != 0)
1144 && (buffered_request_bytes != 0))
1146 if (csp->expected_client_content_length >= buffered_request_bytes)
1148 csp->expected_client_content_length -= buffered_request_bytes;
1149 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1150 "to account for the %llu ones we already got.",
1151 csp->expected_client_content_length, buffered_request_bytes);
1155 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1156 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1157 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1158 "Marking the server socket tainted after throwing %llu bytes away.",
1159 buffered_request_bytes - csp->expected_client_content_length);
1160 csp->expected_client_content_length = 0;
1161 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1164 if (csp->expected_client_content_length == 0)
1166 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1170 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1171 && ((csp->client_iob->cur < csp->client_iob->eod)
1172 || (csp->expected_client_content_length != 0)))
1174 if (strcmpic(csp->http->gpc, "GET")
1175 && strcmpic(csp->http->gpc, "HEAD")
1176 && strcmpic(csp->http->gpc, "TRACE")
1177 && strcmpic(csp->http->gpc, "OPTIONS")
1178 && strcmpic(csp->http->gpc, "DELETE"))
1180 /* XXX: this is an incomplete hack */
1181 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1182 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1186 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1188 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1190 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1191 log_error(LOG_LEVEL_CONNECT,
1192 "Possible pipeline attempt detected. The connection will not "
1193 "be kept alive and we will only serve the first request.");
1194 /* Nuke the pipelined requests from orbit, just to be sure. */
1195 clear_iob(csp->client_iob);
1200 * Keep the pipelined data around for now, we'll deal with
1201 * it once we're done serving the current request.
1203 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1204 assert(csp->client_iob->eod >= csp->client_iob->cur);
1205 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1206 "%d bytes of pipelined data received.",
1207 (int)(csp->client_iob->eod - csp->client_iob->cur));
1213 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1214 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1217 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1220 /*********************************************************************
1222 * Function : mark_server_socket_tainted
1224 * Description : Makes sure we don't reuse a server socket
1225 * (if we didn't read everything the server sent
1226 * us reusing the socket would lead to garbage).
1229 * 1 : csp = Current client state (buffers, headers, etc...)
1233 *********************************************************************/
1234 static void mark_server_socket_tainted(struct client_state *csp)
1237 * For consistency we always mark the server socket
1238 * tainted, however, to reduce the log noise we only
1239 * emit a log message if the server socket could have
1240 * actually been reused.
1242 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1243 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1245 log_error(LOG_LEVEL_CONNECT,
1246 "Marking the server socket %d tainted.",
1247 csp->server_connection.sfd);
1249 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1252 /*********************************************************************
1254 * Function : get_request_line
1256 * Description : Read the client request line.
1259 * 1 : csp = Current client state (buffers, headers, etc...)
1261 * Returns : Pointer to request line or NULL in case of errors.
1263 *********************************************************************/
1264 static char *get_request_line(struct client_state *csp)
1266 char buf[BUFFER_SIZE];
1267 char *request_line = NULL;
1270 memset(buf, 0, sizeof(buf));
1272 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1275 * If there are multiple pipelined requests waiting,
1276 * the flag will be set again once the next request
1279 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1281 request_line = get_header(csp->client_iob);
1282 if ((NULL != request_line) && ('\0' != *request_line))
1284 return request_line;
1288 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1289 "received yet. Continuing reading from %d.", csp->cfd);
1297 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1299 !data_is_available(csp->cfd, csp->config->socket_timeout)
1302 if (socket_is_still_alive(csp->cfd))
1304 log_error(LOG_LEVEL_CONNECT,
1305 "No request line on socket %d received in time. Timeout: %d.",
1306 csp->cfd, csp->config->socket_timeout);
1307 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1308 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1312 log_error(LOG_LEVEL_CONNECT,
1313 "The client side of the connection on socket %d got "
1314 "closed without sending a complete request line.", csp->cfd);
1319 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1321 if (len <= 0) return NULL;
1324 * If there is no memory left for buffering the
1325 * request, there is nothing we can do but hang up
1327 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1332 request_line = get_header(csp->client_iob);
1334 } while ((NULL != request_line) && ('\0' == *request_line));
1336 return request_line;
1342 CHUNK_STATUS_MISSING_DATA,
1343 CHUNK_STATUS_BODY_COMPLETE,
1344 CHUNK_STATUS_PARSE_ERROR
1348 /*********************************************************************
1350 * Function : chunked_body_is_complete
1352 * Description : Figures out whether or not a chunked body is complete.
1354 * Currently it always starts at the beginning of the
1355 * buffer which is somewhat wasteful and prevents Privoxy
1356 * from starting to forward the correctly parsed chunks
1357 * as soon as theoretically possible.
1359 * Should be modified to work with a common buffer,
1360 * and allow the caller to skip already parsed chunks.
1362 * This would allow the function to be used for unbuffered
1363 * response bodies as well.
1366 * 1 : iob = Buffer with the body to check.
1367 * 2 : length = Length of complete body
1369 * Returns : Enum with the result of the check.
1371 *********************************************************************/
1372 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1374 unsigned int chunksize;
1380 * We need at least a single digit, followed by "\r\n",
1381 * followed by an unknown amount of data, followed by "\r\n".
1383 if (p + 5 > iob->eod)
1385 return CHUNK_STATUS_MISSING_DATA;
1387 if (sscanf(p, "%x", &chunksize) != 1)
1389 return CHUNK_STATUS_PARSE_ERROR;
1393 * We want at least a single digit, followed by "\r\n",
1394 * followed by the specified amount of data, followed by "\r\n".
1396 if (p + chunksize + 5 > iob->eod)
1398 return CHUNK_STATUS_MISSING_DATA;
1401 /* Skip chunk-size. */
1402 p = strstr(p, "\r\n");
1405 return CHUNK_STATUS_PARSE_ERROR;
1407 /* Move beyond the chunkdata. */
1410 /* There should be another "\r\n" to skip */
1411 if (memcmp(p, "\r\n", 2))
1413 return CHUNK_STATUS_PARSE_ERROR;
1416 } while (chunksize > 0U);
1418 *length = (size_t)(p - iob->cur);
1419 assert(*length <= (size_t)(iob->eod - iob->cur));
1420 assert(p <= iob->eod);
1422 return CHUNK_STATUS_BODY_COMPLETE;
1427 /*********************************************************************
1429 * Function : receive_chunked_client_request_body
1431 * Description : Read the chunk-encoded client request body.
1432 * Failures are dealt with.
1435 * 1 : csp = Current client state (buffers, headers, etc...)
1437 * Returns : JB_ERR_OK or JB_ERR_PARSE
1439 *********************************************************************/
1440 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1443 enum chunk_status status;
1445 while (CHUNK_STATUS_MISSING_DATA ==
1446 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1448 char buf[BUFFER_SIZE];
1451 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1453 log_error(LOG_LEVEL_ERROR,
1454 "Timeout while waiting for the client body.");
1457 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1460 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1463 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1468 if (status != CHUNK_STATUS_BODY_COMPLETE)
1470 write_socket(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1471 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE));
1472 log_error(LOG_LEVEL_CLF,
1473 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1474 return JB_ERR_PARSE;
1476 log_error(LOG_LEVEL_CONNECT,
1477 "Chunked client body completely read. Length: %d", body_length);
1478 csp->expected_client_content_length = body_length;
1486 /*********************************************************************
1488 * Function : fuzz_chunked_transfer_encoding
1490 * Description : Treat the fuzzed input as chunked transfer encoding
1491 * to check and dechunk.
1494 * 1 : csp = Used to store the data.
1495 * 2 : fuzz_input_file = File to read the input from.
1497 * Returns : Result of dechunking
1499 *********************************************************************/
1500 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1503 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1504 enum chunk_status status;
1506 status = chunked_body_is_complete(csp->iob, &length);
1507 if (CHUNK_STATUS_BODY_COMPLETE != status)
1509 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1512 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1517 /*********************************************************************
1519 * Function : fuzz_client_request
1521 * Description : Try to get a client request from the fuzzed input.
1524 * 1 : csp = Current client state (buffers, headers, etc...)
1525 * 2 : fuzz_input_file = File to read the input from.
1527 * Returns : Result of fuzzing.
1529 *********************************************************************/
1530 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1535 csp->ip_addr_str = "fuzzer";
1537 if (strcmp(fuzz_input_file, "-") != 0)
1539 log_error(LOG_LEVEL_FATAL,
1540 "Fuzzed client requests can currenty only be read from stdin (-).");
1542 err = receive_client_request(csp);
1543 if (err != JB_ERR_OK)
1547 err = parse_client_request(csp);
1548 if (err != JB_ERR_OK)
1556 #endif /* def FUZZ */
1559 #ifdef FEATURE_FORCE_LOAD
1560 /*********************************************************************
1562 * Function : force_required
1564 * Description : Checks a request line to see if it contains
1565 * the FORCE_PREFIX. If it does, it is removed
1566 * unless enforcing requests has beend disabled.
1569 * 1 : request_line = HTTP request line
1571 * Returns : TRUE if force is required, FALSE otherwise.
1573 *********************************************************************/
1574 static int force_required(const struct client_state *csp, char *request_line)
1578 p = strstr(request_line, "http://");
1582 p += strlen("http://");
1586 /* Intercepted request usually don't specify the protocol. */
1590 /* Go to the beginning of the path */
1595 * If the path is missing the request line is invalid and we
1596 * are done here. The client-visible rejection happens later on.
1601 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1603 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1605 /* XXX: Should clean more carefully */
1606 strclean(request_line, FORCE_PREFIX);
1607 log_error(LOG_LEVEL_FORCE,
1608 "Enforcing request: \"%s\".", request_line);
1612 log_error(LOG_LEVEL_FORCE,
1613 "Ignored force prefix in request: \"%s\".", request_line);
1619 #endif /* def FEATURE_FORCE_LOAD */
1622 /*********************************************************************
1624 * Function : receive_client_request
1626 * Description : Read the client's request (more precisely the
1627 * client headers) and answer it if necessary.
1630 * 1 : csp = Current client state (buffers, headers, etc...)
1632 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1634 *********************************************************************/
1635 static jb_err receive_client_request(struct client_state *csp)
1637 char buf[BUFFER_SIZE];
1640 struct http_request *http;
1644 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1645 struct list header_list;
1646 struct list *headers = &header_list;
1648 /* We don't care if the arriving data is a valid HTTP request or not. */
1649 csp->requests_received_total++;
1653 memset(buf, 0, sizeof(buf));
1655 req = get_request_line(csp);
1658 mark_server_socket_tainted(csp);
1659 return JB_ERR_PARSE;
1661 assert(*req != '\0');
1663 if (client_protocol_is_unsupported(csp, req))
1665 return JB_ERR_PARSE;
1668 #ifdef FEATURE_FORCE_LOAD
1669 if (force_required(csp, req))
1671 csp->flags |= CSP_FLAG_FORCED;
1673 #endif /* def FEATURE_FORCE_LOAD */
1675 err = parse_http_request(req, http);
1677 if (JB_ERR_OK != err)
1679 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1680 /* XXX: Use correct size */
1681 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1682 log_error(LOG_LEVEL_ERROR,
1683 "Couldn't parse request line received from %s: %s",
1684 csp->ip_addr_str, jb_err_to_string(err));
1686 free_http_request(http);
1687 return JB_ERR_PARSE;
1690 /* grab the rest of the client's headers */
1694 p = get_header(csp->client_iob);
1698 /* There are no additional headers to read. */
1705 * We didn't receive a complete header
1706 * line yet, get the rest of it.
1708 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1710 log_error(LOG_LEVEL_ERROR,
1711 "Stopped grabbing the client headers.");
1712 destroy_list(headers);
1713 return JB_ERR_PARSE;
1716 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1719 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1720 destroy_list(headers);
1721 return JB_ERR_PARSE;
1724 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1727 * If there is no memory left for buffering the
1728 * request, there is nothing we can do but hang up
1730 destroy_list(headers);
1731 return JB_ERR_MEMORY;
1736 if (!strncmpic(p, "Transfer-Encoding:", 18))
1739 * XXX: should be called through sed()
1740 * but currently can't.
1742 client_transfer_encoding(csp, &p);
1745 * We were able to read a complete
1746 * header and can finally enlist it.
1753 if (http->host == NULL)
1756 * If we still don't know the request destination,
1757 * the request is invalid or the client uses
1758 * Privoxy without its knowledge.
1760 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1763 * Our attempts to get the request destination
1764 * elsewhere failed or Privoxy is configured
1765 * to only accept proxy requests.
1767 * An error response has already been send
1768 * and we're done here.
1770 return JB_ERR_PARSE;
1774 #ifdef FEATURE_CLIENT_TAGS
1775 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1776 set_client_address(csp, headers);
1777 get_tag_list_for_client(csp->client_tags, csp->client_address);
1781 * Determine the actions for this URL
1783 #ifdef FEATURE_TOGGLE
1784 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1786 /* Most compatible set of actions (i.e. none) */
1787 init_current_action(csp->action);
1790 #endif /* ndef FEATURE_TOGGLE */
1792 get_url_actions(csp, http);
1795 enlist(csp->headers, http->cmd);
1797 /* Append the previously read headers */
1798 err = list_append_list_unique(csp->headers, headers);
1799 destroy_list(headers);
1806 /*********************************************************************
1808 * Function : parse_client_request
1810 * Description : Parses the client's request and decides what to do
1813 * Note that since we're not using select() we could get
1814 * blocked here if a client connected, then didn't say
1818 * 1 : csp = Current client state (buffers, headers, etc...)
1820 * Returns : JB_ERR_OK or JB_ERR_PARSE
1822 *********************************************************************/
1823 static jb_err parse_client_request(struct client_state *csp)
1825 struct http_request *http = csp->http;
1828 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1829 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1830 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1831 && (csp->http->ssl == 0))
1833 /* Assume persistence until further notice */
1834 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1837 if (csp->http->ssl == 0)
1840 * This whole block belongs to chat() but currently
1841 * has to be executed before sed().
1843 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1845 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1847 return JB_ERR_PARSE;
1852 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1854 verify_request_length(csp);
1858 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1860 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1862 err = sed(csp, FILTER_CLIENT_HEADERS);
1863 if (JB_ERR_OK != err)
1865 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1867 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1868 csp->ip_addr_str, csp->http->cmd);
1869 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1870 return JB_ERR_PARSE;
1872 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1874 /* Check request line for rewrites. */
1875 if ((NULL == csp->headers->first->str)
1876 || (strcmp(http->cmd, csp->headers->first->str) &&
1877 (JB_ERR_OK != change_request_destination(csp))))
1880 * A header filter broke the request line - bail out.
1882 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1883 /* XXX: Use correct size */
1884 log_error(LOG_LEVEL_CLF,
1885 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1886 log_error(LOG_LEVEL_ERROR,
1887 "Invalid request line after applying header filters.");
1888 free_http_request(http);
1890 return JB_ERR_PARSE;
1893 if (client_has_unsupported_expectations(csp))
1895 return JB_ERR_PARSE;
1903 /*********************************************************************
1905 * Function : send_http_request
1907 * Description : Sends the HTTP headers from the client request
1908 * and all the body data that has already been received.
1911 * 1 : csp = Current client state (buffers, headers, etc...)
1913 * Returns : 0 on success, anything else is na error.
1915 *********************************************************************/
1916 static int send_http_request(struct client_state *csp)
1921 hdr = list_to_text(csp->headers);
1924 /* FIXME Should handle error properly */
1925 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1927 list_remove_all(csp->headers);
1930 * Write the client's (modified) header to the server
1931 * (along with anything else that may be in the buffer)
1933 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
1938 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
1939 csp->http->hostport);
1941 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
1942 && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
1945 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
1946 csp->http->hostport);
1949 return write_failure;
1954 /*********************************************************************
1956 * Function : handle_established_connection
1958 * Description : Shuffle data between client and server once the
1959 * connection has been established.
1962 * 1 : csp = Current client state (buffers, headers, etc...)
1964 * Returns : Nothing.
1966 *********************************************************************/
1967 static void handle_established_connection(struct client_state *csp)
1969 char *receive_buffer;
1974 struct pollfd poll_fds[2];
1978 struct timeval timeout;
1981 int ms_iis5_hack = 0;
1982 unsigned long long byte_count = 0;
1983 struct http_request *http;
1984 long len = 0; /* for buffer sizes (and negative error codes) */
1985 int buffer_and_filter_content = 0;
1987 /* Skeleton for HTTP response, if we should intercept the request */
1988 struct http_response *rsp;
1989 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1990 int watch_client_socket;
1992 const size_t receive_buffer_size = csp->config->receive_buffer_size;
1994 receive_buffer = zalloc(receive_buffer_size + 1);
1995 if (receive_buffer == NULL)
1997 log_error(LOG_LEVEL_ERROR,
1998 "Out of memory. Failed to allocate the receive buffer.");
1999 rsp = cgi_error_memory();
2000 send_crunch_response(csp, rsp);
2007 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2008 csp->cfd : csp->server_connection.sfd;
2011 /* pass data between the client and server
2012 * until one or the other shuts down the connection.
2017 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2018 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2026 * FD_ZERO here seems to point to an errant macro which crashes.
2027 * So do this by hand for now...
2029 memset(&rfds,0x00,sizeof(fd_set));
2033 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2034 if (!watch_client_socket)
2036 maxfd = csp->server_connection.sfd;
2039 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2041 FD_SET(csp->cfd, &rfds);
2044 FD_SET(csp->server_connection.sfd, &rfds);
2045 #endif /* ndef HAVE_POLL */
2047 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2048 if ((csp->flags & CSP_FLAG_CHUNKED)
2049 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2050 && ((csp->iob->eod - csp->iob->cur) >= 5)
2051 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2054 * XXX: This check should be obsolete now,
2055 * but let's wait a while to be sure.
2057 log_error(LOG_LEVEL_CONNECT,
2058 "Looks like we got the last chunk together with "
2059 "the server headers but didn't detect it earlier. "
2060 "We better stop reading.");
2061 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2062 csp->expected_content_length = byte_count;
2063 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2065 if (server_body && server_response_is_complete(csp, byte_count))
2067 if (csp->expected_content_length == byte_count)
2069 log_error(LOG_LEVEL_CONNECT,
2070 "Done reading from server. Content length: %llu as expected. "
2071 "Bytes most recently read: %d.",
2076 log_error(LOG_LEVEL_CONNECT,
2077 "Done reading from server. Expected content length: %llu. "
2078 "Actual content length: %llu. Bytes most recently read: %d.",
2079 csp->expected_content_length, byte_count, len);
2083 * XXX: should not jump around,
2084 * chat() is complicated enough already.
2088 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2091 poll_fds[0].fd = csp->cfd;
2092 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2093 if (!watch_client_socket)
2096 * Ignore incoming data, but still watch out
2097 * for disconnects etc. These flags are always
2098 * implied anyway but explicitly setting them
2101 poll_fds[0].events = POLLERR|POLLHUP;
2106 poll_fds[0].events = POLLIN;
2108 poll_fds[1].fd = csp->server_connection.sfd;
2109 poll_fds[1].events = POLLIN;
2110 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2112 timeout.tv_sec = csp->config->socket_timeout;
2113 timeout.tv_usec = 0;
2114 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2115 #endif /* def HAVE_POLL */
2119 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2120 csp->config->socket_timeout, http->url);
2121 if ((byte_count == 0) && (http->ssl == 0))
2123 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2125 mark_server_socket_tainted(csp);
2126 freez(receive_buffer);
2132 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2134 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2136 mark_server_socket_tainted(csp);
2137 freez(receive_buffer);
2142 * This is the body of the browser's request,
2143 * just read and write it.
2145 * XXX: Make sure the client doesn't use pipelining
2146 * behind Privoxy's back.
2149 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2151 log_error(LOG_LEVEL_CONNECT,
2152 "The client socket %d has become unusable while "
2153 "the server socket %d is still open.",
2154 csp->cfd, csp->server_connection.sfd);
2155 mark_server_socket_tainted(csp);
2159 if (poll_fds[0].revents != 0)
2161 if (FD_ISSET(csp->cfd, &rfds))
2162 #endif /* def HAVE_POLL*/
2164 int max_bytes_to_read = (int)receive_buffer_size;
2166 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2167 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2169 if (data_is_available(csp->cfd, 0))
2172 * If the next request is already waiting, we have
2173 * to stop select()ing the client socket. Otherwise
2174 * we would always return right away and get nothing
2177 watch_client_socket = 0;
2178 log_error(LOG_LEVEL_CONNECT,
2179 "Stopping to watch the client socket %d. "
2180 "There's already another request waiting.",
2185 * If the client socket is set, but there's no data
2186 * available on the socket, the client went fishing
2187 * and continuing talking to the server makes no sense.
2189 log_error(LOG_LEVEL_CONNECT,
2190 "The client closed socket %d while "
2191 "the server socket %d is still open.",
2192 csp->cfd, csp->server_connection.sfd);
2193 mark_server_socket_tainted(csp);
2196 if (csp->expected_client_content_length != 0)
2198 if (csp->expected_client_content_length < receive_buffer_size)
2200 max_bytes_to_read = (int)csp->expected_client_content_length;
2202 log_error(LOG_LEVEL_CONNECT,
2203 "Waiting for up to %d bytes from the client.",
2206 assert(max_bytes_to_read <= receive_buffer_size);
2207 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2209 len = read_socket(csp->cfd, receive_buffer, max_bytes_to_read);
2213 /* XXX: not sure if this is necessary. */
2214 mark_server_socket_tainted(csp);
2215 break; /* "game over, man" */
2218 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2219 if (csp->expected_client_content_length != 0)
2221 assert(len <= max_bytes_to_read);
2222 csp->expected_client_content_length -= (unsigned)len;
2223 log_error(LOG_LEVEL_CONNECT,
2224 "Expected client content length set to %llu "
2225 "after reading %d bytes.",
2226 csp->expected_client_content_length, len);
2227 if (csp->expected_client_content_length == 0)
2229 log_error(LOG_LEVEL_CONNECT,
2230 "Done reading from the client.");
2231 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2234 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2236 if (write_socket(csp->server_connection.sfd, receive_buffer, (size_t)len))
2238 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2239 mark_server_socket_tainted(csp);
2240 freez(receive_buffer);
2247 * The server wants to talk. It could be the header or the body.
2248 * If `hdr' is null, then it's the header otherwise it's the body.
2249 * FIXME: Does `hdr' really mean `host'? No.
2252 if (poll_fds[1].revents != 0)
2254 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2255 #endif /* HAVE_POLL */
2257 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2259 * If we are buffering content, we don't want to eat up to
2260 * buffer-limit bytes if the client no longer cares about them.
2261 * If we aren't buffering, however, a dead client socket will be
2262 * noticed pretty much right away anyway, so we can reduce the
2263 * overhead by skipping the check.
2265 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2268 log_error(LOG_LEVEL_CONNECT,
2269 "The server still wants to talk, but the client may already have hung up on us.");
2271 log_error(LOG_LEVEL_CONNECT,
2272 "The server still wants to talk, but the client hung up on us.");
2273 mark_server_socket_tainted(csp);
2274 freez(receive_buffer);
2276 #endif /* def _WIN32 */
2278 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2280 len = read_socket(csp->server_connection.sfd, receive_buffer, (int)receive_buffer_size);
2284 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2286 if (http->ssl && (csp->fwd == NULL))
2289 * Just hang up. We already confirmed the client's CONNECT
2290 * request with status code 200 and unencrypted content is
2291 * no longer welcome.
2293 log_error(LOG_LEVEL_ERROR,
2294 "CONNECT already confirmed. Unable to tell the client about the problem.");
2295 freez(receive_buffer);
2298 else if (byte_count)
2301 * Just hang up. We already transmitted the original headers
2302 * and parts of the original content and therefore missed the
2303 * chance to send an error message (without risking data corruption).
2305 * XXX: we could retry with a fancy range request here.
2307 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2308 "Unable to tell the client about the problem.");
2309 mark_server_socket_tainted(csp);
2310 freez(receive_buffer);
2314 * XXX: Consider handling the cases above the same.
2316 mark_server_socket_tainted(csp);
2320 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2321 if (csp->flags & CSP_FLAG_CHUNKED)
2323 if ((len >= 5) && !memcmp(receive_buffer+len-5, "0\r\n\r\n", 5))
2325 /* XXX: this is a temporary hack */
2326 log_error(LOG_LEVEL_CONNECT,
2327 "Looks like we reached the end of the last chunk. "
2328 "We better stop reading.");
2329 csp->expected_content_length = byte_count + (unsigned long long)len;
2330 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2334 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2337 * This is guaranteed by allocating with zalloc_or_die()
2338 * and never (intentionally) writing to the last byte.
2340 * receive_buffer_size is the size of the part of the
2341 * buffer we intentionally write to, but we actually
2342 * allocated receive_buffer_size+1 bytes so the assertion
2343 * stays within the allocated range.
2345 assert(receive_buffer[receive_buffer_size] == '\0');
2348 * Add a trailing zero to let be able to use string operations.
2349 * XXX: do we still need this with filter_popups gone?
2351 assert(len <= receive_buffer_size);
2352 receive_buffer[len] = '\0';
2355 * Normally, this would indicate that we've read
2356 * as much as the server has sent us and we can
2357 * close the client connection. However, Microsoft
2358 * in its wisdom has released IIS/5 with a bug that
2359 * prevents it from sending the trailing \r\n in
2360 * a 302 redirect header (and possibly other headers).
2361 * To work around this if we've haven't parsed
2362 * a full header we'll append a trailing \r\n
2363 * and see if this now generates a valid one.
2365 * This hack shouldn't have any impacts. If we've
2366 * already transmitted the header or if this is a
2367 * SSL connection, then we won't bother with this
2368 * hack. So we only work on partially received
2369 * headers. If we append a \r\n and this still
2370 * doesn't generate a valid header, then we won't
2371 * transmit anything to the client.
2376 if (server_body || http->ssl)
2379 * If we have been buffering up the document,
2380 * now is the time to apply content modification
2381 * and send the result to the client.
2383 if (buffer_and_filter_content)
2385 p = execute_content_filters(csp);
2387 * If content filtering fails, use the original
2388 * buffer and length.
2389 * (see p != NULL ? p : csp->iob->cur below)
2393 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2395 #ifdef FEATURE_COMPRESSION
2396 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2397 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2399 char *compressed_content = compress_buffer(p,
2400 (size_t *)&csp->content_length, csp->config->compression_level);
2401 if (compressed_content != NULL)
2404 p = compressed_content;
2405 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2410 if (JB_ERR_OK != update_server_headers(csp))
2412 log_error(LOG_LEVEL_FATAL,
2413 "Failed to update server headers. after filtering.");
2416 hdr = list_to_text(csp->headers);
2419 /* FIXME Should handle error properly */
2420 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2423 if (write_socket(csp->cfd, hdr, strlen(hdr))
2424 || write_socket(csp->cfd,
2425 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2427 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2430 mark_server_socket_tainted(csp);
2431 freez(receive_buffer);
2439 break; /* "game over, man" */
2443 * This is NOT the body, so
2444 * Let's pretend the server just sent us a blank line.
2446 snprintf(receive_buffer, receive_buffer_size, "\r\n");
2447 len = (int)strlen(receive_buffer);
2450 * Now, let the normal header parsing algorithm below do its
2451 * job. If it fails, we'll exit instead of continuing.
2458 * If this is an SSL connection or we're in the body
2459 * of the server document, just write it to the client,
2460 * unless we need to buffer the body for later content-filtering
2462 if (server_body || http->ssl)
2464 if (buffer_and_filter_content)
2467 * If there is no memory left for buffering the content, or the buffer limit
2468 * has been reached, switch to non-filtering mode, i.e. make & write the
2469 * header, flush the iob and buf, and get out of the way.
2471 if (add_to_iob(csp->iob, csp->config->buffer_limit, receive_buffer, len))
2476 log_error(LOG_LEVEL_INFO,
2477 "Flushing header and buffers. Stepping back from filtering.");
2479 hdr = list_to_text(csp->headers);
2483 * Memory is too tight to even generate the header.
2484 * Send our static "Out-of-memory" page.
2486 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2487 rsp = cgi_error_memory();
2488 send_crunch_response(csp, rsp);
2489 mark_server_socket_tainted(csp);
2490 freez(receive_buffer);
2493 hdrlen = strlen(hdr);
2495 if (write_socket(csp->cfd, hdr, hdrlen)
2496 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2497 || (write_socket(csp->cfd, receive_buffer, (size_t)len)))
2499 log_error(LOG_LEVEL_CONNECT,
2500 "Flush header and buffers to client failed: %E");
2502 mark_server_socket_tainted(csp);
2503 freez(receive_buffer);
2508 * Reset the byte_count to the amount of bytes
2509 * we just flushed. len will be added a few lines below,
2510 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2512 byte_count = (unsigned long long)flushed;
2514 buffer_and_filter_content = 0;
2520 if (write_socket(csp->cfd, receive_buffer, (size_t)len))
2522 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2523 mark_server_socket_tainted(csp);
2524 freez(receive_buffer);
2528 byte_count += (unsigned long long)len;
2534 * We're still looking for the end of the server's header.
2535 * Buffer up the data we just read. If that fails, there's
2536 * little we can do but send our static out-of-memory page.
2538 if (add_to_iob(csp->iob, csp->config->buffer_limit, receive_buffer, len))
2540 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2541 rsp = cgi_error_memory();
2542 send_crunch_response(csp, rsp);
2543 mark_server_socket_tainted(csp);
2544 freez(receive_buffer);
2548 /* Convert iob into something sed() can digest */
2549 if (JB_ERR_PARSE == get_server_headers(csp))
2554 * Well, we tried our MS IIS/5 hack and it didn't work.
2555 * The header is incomplete and there isn't anything
2556 * we can do about it.
2558 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2559 "Applying the MS IIS5 hack didn't help.");
2560 log_error(LOG_LEVEL_CLF,
2561 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2562 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2563 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2564 mark_server_socket_tainted(csp);
2565 freez(receive_buffer);
2571 * Since we have to wait for more from the server before
2572 * we can parse the headers we just continue here.
2574 log_error(LOG_LEVEL_CONNECT,
2575 "Continuing buffering server headers from socket %d. "
2576 "Bytes most recently read: %d.", csp->cfd, len);
2583 * Account for the content bytes we
2584 * might have gotten with the headers.
2586 assert(csp->iob->eod >= csp->iob->cur);
2587 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2590 /* Did we actually get anything? */
2591 if (NULL == csp->headers->first)
2593 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2595 log_error(LOG_LEVEL_ERROR,
2596 "No server or forwarder response received on socket %d. "
2597 "Closing client socket %d without sending data.",
2598 csp->server_connection.sfd, csp->cfd);
2599 log_error(LOG_LEVEL_CLF,
2600 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2604 log_error(LOG_LEVEL_ERROR,
2605 "No server or forwarder response received on socket %d.",
2606 csp->server_connection.sfd);
2607 send_crunch_response(csp, error_response(csp, "no-server-data"));
2609 free_http_request(http);
2610 mark_server_socket_tainted(csp);
2611 freez(receive_buffer);
2615 assert(csp->headers->first->str);
2617 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2618 strncmpic(csp->headers->first->str, "ICY", 3))
2621 * It doesn't look like a HTTP (or Shoutcast) response:
2622 * tell the client and log the problem.
2624 if (strlen(csp->headers->first->str) > 30)
2626 csp->headers->first->str[30] = '\0';
2628 log_error(LOG_LEVEL_ERROR,
2629 "Invalid server or forwarder response. Starts with: %s",
2630 csp->headers->first->str);
2631 log_error(LOG_LEVEL_CLF,
2632 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2633 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2634 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2635 free_http_request(http);
2636 mark_server_socket_tainted(csp);
2641 * We have now received the entire server header,
2642 * filter it and send the result to the client
2644 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2646 log_error(LOG_LEVEL_CLF,
2647 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2648 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2649 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2650 free_http_request(http);
2651 mark_server_socket_tainted(csp);
2652 freez(receive_buffer);
2655 hdr = list_to_text(csp->headers);
2658 /* FIXME Should handle error properly */
2659 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2662 if ((csp->flags & CSP_FLAG_CHUNKED)
2663 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2664 && ((csp->iob->eod - csp->iob->cur) >= 5)
2665 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2667 log_error(LOG_LEVEL_CONNECT,
2668 "Looks like we got the last chunk together with "
2669 "the server headers. We better stop reading.");
2670 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2671 csp->expected_content_length = byte_count;
2672 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2675 csp->server_connection.response_received = time(NULL);
2677 if (crunch_response_triggered(csp, crunchers_light))
2680 * One of the tags created by a server-header
2681 * tagger triggered a crunch. We already
2682 * delivered the crunch response to the client
2683 * and are done here after cleaning up.
2686 mark_server_socket_tainted(csp);
2687 freez(receive_buffer);
2690 /* Buffer and pcrs filter this if appropriate. */
2692 if (!http->ssl) /* We talk plaintext */
2694 buffer_and_filter_content = content_requires_filtering(csp);
2697 * Only write if we're not buffering for content modification
2699 if (!buffer_and_filter_content)
2702 * Write the server's (modified) header to
2703 * the client (along with anything else that
2704 * may be in the buffer)
2707 if (write_socket(csp->cfd, hdr, strlen(hdr))
2708 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2710 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2713 * The write failed, so don't bother mentioning it
2714 * to the client... it probably can't hear us anyway.
2717 mark_server_socket_tainted(csp);
2718 freez(receive_buffer);
2723 /* we're finished with the server's header */
2729 * If this was a MS IIS/5 hack then it means the server
2730 * has already closed the connection. Nothing more to read.
2735 log_error(LOG_LEVEL_ERROR,
2736 "Closed server connection detected. "
2737 "Applying the MS IIS5 hack didn't help.");
2738 log_error(LOG_LEVEL_CLF,
2739 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2740 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2741 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2742 mark_server_socket_tainted(csp);
2743 freez(receive_buffer);
2749 mark_server_socket_tainted(csp);
2750 freez(receive_buffer);
2751 return; /* huh? we should never get here */
2753 freez(receive_buffer);
2755 if (csp->content_length == 0)
2758 * If Privoxy didn't recalculate the Content-Length,
2759 * byte_count is still correct.
2761 csp->content_length = byte_count;
2764 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2765 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2766 && (csp->expected_content_length != byte_count))
2768 log_error(LOG_LEVEL_CONNECT,
2769 "Received %llu bytes while expecting %llu.",
2770 byte_count, csp->expected_content_length);
2771 mark_server_socket_tainted(csp);
2775 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2776 csp->ip_addr_str, http->ocmd, csp->content_length);
2778 csp->server_connection.timestamp = time(NULL);
2782 /*********************************************************************
2786 * Description : Once a connection from the client has been accepted,
2787 * this function is called (via serve()) to handle the
2788 * main business of the communication. This function
2789 * returns after dealing with a single request. It can
2790 * be called multiple times with the same client socket
2791 * if the client is keeping the connection alive.
2793 * The decision whether or not a client connection will
2794 * be kept alive is up to the caller which also must
2795 * close the client socket when done.
2797 * FIXME: chat is nearly thousand lines long.
2801 * 1 : csp = Current client state (buffers, headers, etc...)
2803 * Returns : Nothing.
2805 *********************************************************************/
2806 static void chat(struct client_state *csp)
2808 const struct forward_spec *fwd;
2809 struct http_request *http;
2810 /* Skeleton for HTTP response, if we should intercept the request */
2811 struct http_response *rsp;
2815 if (receive_client_request(csp) != JB_ERR_OK)
2819 if (parse_client_request(csp) != JB_ERR_OK)
2824 /* decide how to route the HTTP request */
2825 fwd = forward_url(csp, http);
2828 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2829 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2834 * build the http request to send to the server
2835 * we have to do one of the following:
2837 * create = use the original HTTP request to create a new
2838 * HTTP request that has either the path component
2839 * without the http://domainspec (w/path) or the
2840 * full orininal URL (w/url)
2841 * Note that the path and/or the HTTP version may
2842 * have been altered by now.
2844 * connect = Open a socket to the host:port of the server
2845 * and short-circuit server and client socket.
2847 * pass = Pass the request unchanged if forwarding a CONNECT
2848 * request to a parent proxy. Note that we'll be sending
2849 * the CFAIL message ourselves if connecting to the parent
2850 * fails, but we won't send a CSUCCEED message if it works,
2851 * since that would result in a double message (ours and the
2852 * parent's). After sending the request to the parent, we simply
2855 * here's the matrix:
2858 * +--------+--------+
2860 * 0 | create | connect|
2862 * Forwarding +--------+--------+
2864 * 1 | create | pass |
2866 * +--------+--------+
2870 if (http->ssl && connect_port_is_forbidden(csp))
2872 const char *acceptable_connect_ports =
2873 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
2874 assert(NULL != acceptable_connect_ports);
2875 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
2876 "limit-connect{%s} doesn't allow CONNECT requests to %s",
2877 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
2878 csp->action->flags |= ACTION_BLOCK;
2884 freez(csp->headers->first->str);
2885 build_request_line(csp, fwd, &csp->headers->first->str);
2889 * We have a request. Check if one of the crunchers wants it.
2891 if (crunch_response_triggered(csp, crunchers_all))
2894 * Yes. The client got the crunch response and we're done here.
2899 log_applied_actions(csp->action);
2900 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
2902 if (fwd->forward_host)
2904 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
2905 fwd->forward_host, fwd->forward_port, http->hostport);
2909 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
2912 /* here we connect to the server, gateway, or the forwarder */
2914 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2915 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
2916 && socket_is_still_alive(csp->server_connection.sfd)
2917 && connection_destination_matches(&csp->server_connection, http, fwd))
2919 log_error(LOG_LEVEL_CONNECT,
2920 "Reusing server socket %d connected to %s. Total requests: %u.",
2921 csp->server_connection.sfd, csp->server_connection.host,
2922 csp->server_connection.requests_sent_total);
2926 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2928 #ifdef FEATURE_CONNECTION_SHARING
2929 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2931 remember_connection(&csp->server_connection);
2934 #endif /* def FEATURE_CONNECTION_SHARING */
2936 log_error(LOG_LEVEL_CONNECT,
2937 "Closing server socket %d connected to %s. Total requests: %u.",
2938 csp->server_connection.sfd, csp->server_connection.host,
2939 csp->server_connection.requests_sent_total);
2940 close_socket(csp->server_connection.sfd);
2942 mark_connection_closed(&csp->server_connection);
2944 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2946 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
2948 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
2950 if (fwd->type != SOCKS_NONE)
2953 rsp = error_response(csp, "forwarding-failed");
2955 else if (errno == EINVAL)
2957 rsp = error_response(csp, "no-such-domain");
2961 rsp = error_response(csp, "connect-failed");
2964 /* Write the answer to the client */
2967 send_crunch_response(csp, rsp);
2971 * Temporary workaround to prevent already-read client
2972 * bodies from being parsed as new requests. For now we
2973 * err on the safe side and throw all the following
2974 * requests under the bus, even if no client body has been
2975 * buffered. A compliant client will repeat the dropped
2976 * requests on an untainted connection.
2978 * The proper fix is to discard the no longer needed
2979 * client body in the buffer (if there is one) and to
2980 * continue parsing the bytes that follow.
2982 drain_and_close_socket(csp->cfd);
2983 csp->cfd = JB_INVALID_SOCKET;
2987 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2988 save_connection_destination(csp->server_connection.sfd,
2989 http, fwd, &csp->server_connection);
2990 csp->server_connection.keep_alive_timeout =
2991 (unsigned)csp->config->keep_alive_timeout;
2993 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2995 csp->server_connection.requests_sent_total++;
2997 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
2999 /* Client headers have been sent optimistically */
3000 assert(csp->headers->last == NULL);
3002 else if (fwd->forward_host || (http->ssl == 0))
3004 if (send_http_request(csp))
3006 rsp = error_response(csp, "connect-failed");
3009 send_crunch_response(csp, rsp);
3017 * We're running an SSL tunnel and we're not forwarding,
3018 * so just ditch the client headers, send the "connect succeeded"
3019 * message to the client, flush the rest, and get out of the way.
3021 list_remove_all(csp->headers);
3022 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
3026 clear_iob(csp->client_iob);
3029 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
3031 /* XXX: should the time start earlier for optimistically sent data? */
3032 csp->server_connection.request_sent = time(NULL);
3034 handle_established_connection(csp);
3039 /*********************************************************************
3041 * Function : fuzz_server_response
3043 * Description : Treat the input as a whole server response.
3046 * 1 : csp = Current client state (buffers, headers, etc...)
3047 * 2 : fuzz_input_file = File to read the input from.
3051 *********************************************************************/
3052 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
3054 static struct forward_spec fwd; /* Zero'd due to being static */
3057 if (strcmp(fuzz_input_file, "-") == 0)
3059 /* XXX: Doesn'T work yet. */
3060 csp->server_connection.sfd = 0;
3064 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
3065 if (csp->server_connection.sfd == -1)
3067 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
3072 csp->content_type |= CT_GIF;
3073 csp->action->flags |= ACTION_DEANIMATE;
3074 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
3076 csp->http->path = strdup_or_die("/");
3077 csp->http->host = strdup_or_die("fuzz.example.org");
3078 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
3079 /* Prevent client socket monitoring */
3080 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3081 csp->flags |= CSP_FLAG_CHUNKED;
3083 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
3084 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3086 csp->content_type |= CT_DECLARED|CT_GIF;
3088 csp->config->socket_timeout = 0;
3090 cgi_init_error_messages();
3092 handle_established_connection(csp);
3099 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3100 /*********************************************************************
3102 * Function : prepare_csp_for_next_request
3104 * Description : Put the csp in a mostly vergin state.
3107 * 1 : csp = Current client state (buffers, headers, etc...)
3111 *********************************************************************/
3112 static void prepare_csp_for_next_request(struct client_state *csp)
3114 csp->content_type = 0;
3115 csp->content_length = 0;
3116 csp->expected_content_length = 0;
3117 csp->expected_client_content_length = 0;
3118 list_remove_all(csp->headers);
3119 clear_iob(csp->iob);
3120 freez(csp->error_message);
3121 free_http_request(csp->http);
3122 destroy_list(csp->headers);
3123 destroy_list(csp->tags);
3124 #ifdef FEATURE_CLIENT_TAGS
3125 destroy_list(csp->client_tags);
3126 freez(csp->client_address);
3128 free_current_action(csp->action);
3129 if (NULL != csp->fwd)
3131 unload_forward_spec(csp->fwd);
3134 /* XXX: Store per-connection flags someplace else. */
3135 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
3136 #ifdef FEATURE_TOGGLE
3137 if (global_toggle_state)
3138 #endif /* def FEATURE_TOGGLE */
3140 csp->flags |= CSP_FLAG_TOGGLED_ON;
3143 if (csp->client_iob->eod > csp->client_iob->cur)
3145 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
3146 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
3148 assert(bytes_to_shift > 0);
3149 assert(data_length > 0);
3151 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
3152 data_length, bytes_to_shift);
3153 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
3154 csp->client_iob->cur = csp->client_iob->buf;
3155 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
3156 csp->client_iob->eod = csp->client_iob->buf + data_length;
3157 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
3159 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3164 * We mainly care about resetting client_iob->cur so we don't
3165 * waste buffer space at the beginning and don't mess up the
3166 * request restoration done by cgi_show_request().
3168 * Freeing the buffer itself isn't technically necessary,
3169 * but makes debugging more convenient.
3171 clear_iob(csp->client_iob);
3174 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3177 /*********************************************************************
3181 * Description : This is little more than chat. We only "serve" to
3182 * to close (or remember) any socket that chat may have
3186 * 1 : csp = Current client state (buffers, headers, etc...)
3190 *********************************************************************/
3192 void serve(struct client_state *csp)
3193 #else /* ifndef AMIGA */
3194 static void serve(struct client_state *csp)
3195 #endif /* def AMIGA */
3197 int config_file_change_detected = 0; /* Only used for debugging */
3198 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3199 #ifdef FEATURE_CONNECTION_SHARING
3200 static int monitor_thread_running = 0;
3201 #endif /* def FEATURE_CONNECTION_SHARING */
3202 int continue_chatting = 0;
3204 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
3205 csp->ip_addr_str, csp->cfd);
3209 unsigned int latency;
3214 * If the request has been crunched,
3215 * the calculated latency is zero.
3217 latency = (unsigned)(csp->server_connection.response_received -
3218 csp->server_connection.request_sent) / 2;
3220 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3221 && (csp->flags & CSP_FLAG_CRUNCHED)
3222 && (csp->expected_client_content_length != 0))
3224 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
3225 log_error(LOG_LEVEL_CONNECT,
3226 "Tainting client socket %d due to unread data.", csp->cfd);
3229 continue_chatting = (csp->config->feature_flags
3230 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3231 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3232 && (csp->cfd != JB_INVALID_SOCKET)
3233 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3234 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3235 || (csp->flags & CSP_FLAG_CHUNKED));
3237 if (!(csp->flags & CSP_FLAG_CRUNCHED)
3238 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
3240 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
3242 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
3244 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
3245 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3246 || !socket_is_still_alive(csp->server_connection.sfd)
3247 || !(latency < csp->server_connection.keep_alive_timeout))
3249 log_error(LOG_LEVEL_CONNECT,
3250 "Closing server socket %d connected to %s. "
3251 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
3252 csp->server_connection.sfd, csp->server_connection.host,
3253 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3254 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3255 socket_is_still_alive(csp->server_connection.sfd),
3256 csp->server_connection.keep_alive_timeout);
3257 #ifdef FEATURE_CONNECTION_SHARING
3258 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3260 forget_connection(csp->server_connection.sfd);
3262 #endif /* def FEATURE_CONNECTION_SHARING */
3263 close_socket(csp->server_connection.sfd);
3264 mark_connection_closed(&csp->server_connection);
3268 if (continue_chatting && any_loaded_file_changed(csp))
3270 continue_chatting = 0;
3271 config_file_change_detected = 1;
3274 if (continue_chatting)
3276 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
3277 && socket_is_still_alive(csp->cfd))
3279 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
3280 "pipelined on socket %d and the socket is still alive.",
3281 csp->requests_received_total+1, csp->cfd);
3282 prepare_csp_for_next_request(csp);
3286 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3288 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3290 log_error(LOG_LEVEL_CONNECT,
3291 "Waiting for the next client request on socket %d. "
3292 "Keeping the server socket %d to %s open.",
3293 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
3297 log_error(LOG_LEVEL_CONNECT,
3298 "Waiting for the next client request on socket %d. "
3299 "No server socket to keep open.", csp->cfd);
3303 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3304 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
3305 && socket_is_still_alive(csp->cfd))
3307 log_error(LOG_LEVEL_CONNECT,
3308 "Client request %u arrived in time on socket %d.",
3309 csp->requests_received_total+1, csp->cfd);
3310 prepare_csp_for_next_request(csp);
3314 #ifdef FEATURE_CONNECTION_SHARING
3315 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3316 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3317 && (socket_is_still_alive(csp->server_connection.sfd)))
3319 time_t time_open = time(NULL) - csp->server_connection.timestamp;
3321 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3326 remember_connection(&csp->server_connection);
3327 csp->server_connection.sfd = JB_INVALID_SOCKET;
3328 drain_and_close_socket(csp->cfd);
3329 csp->cfd = JB_INVALID_SOCKET;
3330 privoxy_mutex_lock(&connection_reuse_mutex);
3331 if (!monitor_thread_running)
3333 monitor_thread_running = 1;
3334 privoxy_mutex_unlock(&connection_reuse_mutex);
3335 wait_for_alive_connections();
3336 privoxy_mutex_lock(&connection_reuse_mutex);
3337 monitor_thread_running = 0;
3339 privoxy_mutex_unlock(&connection_reuse_mutex);
3341 #endif /* def FEATURE_CONNECTION_SHARING */
3345 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3347 log_error(LOG_LEVEL_CONNECT,
3348 "Closing server socket %d connected to %s. Keep-alive: %u. "
3349 "Tainted: %u. Socket alive: %u. Timeout: %u. "
3350 "Configuration file change detected: %u",
3351 csp->server_connection.sfd, csp->server_connection.host,
3352 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3353 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3354 socket_is_still_alive(csp->server_connection.sfd),
3355 csp->server_connection.keep_alive_timeout,
3356 config_file_change_detected);
3358 } while (continue_chatting);
3362 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3364 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3366 #ifdef FEATURE_CONNECTION_SHARING
3367 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3369 forget_connection(csp->server_connection.sfd);
3371 #endif /* def FEATURE_CONNECTION_SHARING */
3372 close_socket(csp->server_connection.sfd);
3375 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3376 mark_connection_closed(&csp->server_connection);
3379 if (csp->cfd != JB_INVALID_SOCKET)
3381 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3382 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3383 "Configuration file change detected: %u. Requests received: %u.",
3384 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3385 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3386 config_file_change_detected, csp->requests_received_total);
3387 drain_and_close_socket(csp->cfd);
3390 free_csp_resources(csp);
3392 csp->flags &= ~CSP_FLAG_ACTIVE;
3398 /*********************************************************************
3400 * Function : server_thread
3402 * Description : We only exist to call `serve' in a threaded environment.
3405 * 1 : data = Current client state (buffers, headers, etc...)
3407 * Returns : Always 0.
3409 *********************************************************************/
3410 static int32 server_thread(void *data)
3412 serve((struct client_state *) data);
3419 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3420 /*********************************************************************
3424 * Description : Print usage info & exit.
3426 * Parameters : Pointer to argv[0] for identifying ourselves
3430 *********************************************************************/
3431 static void usage(const char *name)
3433 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3434 "Usage: %s [--config-test] "
3437 #endif /* defined(unix) */
3440 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3441 #endif /* defined(unix) */
3442 "[--version] [configfile]\n",
3446 show_fuzz_usage(name);
3449 printf("Aborting\n");
3454 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3457 #ifdef MUTEX_LOCKS_AVAILABLE
3458 /*********************************************************************
3460 * Function : privoxy_mutex_lock
3462 * Description : Locks a mutex.
3465 * 1 : mutex = The mutex to lock.
3467 * Returns : Void. May exit in case of errors.
3469 *********************************************************************/
3470 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3472 #ifdef FEATURE_PTHREAD
3473 int err = pthread_mutex_lock(mutex);
3476 if (mutex != &log_mutex)
3478 log_error(LOG_LEVEL_FATAL,
3479 "Mutex locking failed: %s.\n", strerror(err));
3484 EnterCriticalSection(mutex);
3485 #endif /* def FEATURE_PTHREAD */
3489 /*********************************************************************
3491 * Function : privoxy_mutex_unlock
3493 * Description : Unlocks a mutex.
3496 * 1 : mutex = The mutex to unlock.
3498 * Returns : Void. May exit in case of errors.
3500 *********************************************************************/
3501 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3503 #ifdef FEATURE_PTHREAD
3504 int err = pthread_mutex_unlock(mutex);
3507 if (mutex != &log_mutex)
3509 log_error(LOG_LEVEL_FATAL,
3510 "Mutex unlocking failed: %s.\n", strerror(err));
3515 LeaveCriticalSection(mutex);
3516 #endif /* def FEATURE_PTHREAD */
3520 /*********************************************************************
3522 * Function : privoxy_mutex_init
3524 * Description : Prepares a mutex.
3527 * 1 : mutex = The mutex to initialize.
3529 * Returns : Void. May exit in case of errors.
3531 *********************************************************************/
3532 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3534 #ifdef FEATURE_PTHREAD
3535 int err = pthread_mutex_init(mutex, 0);
3538 printf("Fatal error. Mutex initialization failed: %s.\n",
3543 InitializeCriticalSection(mutex);
3544 #endif /* def FEATURE_PTHREAD */
3546 #endif /* def MUTEX_LOCKS_AVAILABLE */
3548 /*********************************************************************
3550 * Function : initialize_mutexes
3552 * Description : Prepares mutexes if mutex support is available.
3556 * Returns : Void, exits in case of errors.
3558 *********************************************************************/
3559 static void initialize_mutexes(void)
3561 #ifdef MUTEX_LOCKS_AVAILABLE
3563 * Prepare global mutex semaphores
3565 privoxy_mutex_init(&log_mutex);
3566 privoxy_mutex_init(&log_init_mutex);
3567 privoxy_mutex_init(&connection_reuse_mutex);
3568 #ifdef FEATURE_EXTERNAL_FILTERS
3569 privoxy_mutex_init(&external_filter_mutex);
3571 #ifdef FEATURE_CLIENT_TAGS
3572 privoxy_mutex_init(&client_tags_mutex);
3576 * XXX: The assumptions below are a bit naive
3577 * and can cause locks that aren't necessary.
3579 * For example older FreeBSD versions (< 6.x?)
3580 * have no gethostbyname_r, but gethostbyname is
3583 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3584 privoxy_mutex_init(&resolver_mutex);
3585 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3587 * XXX: should we use a single mutex for
3588 * localtime() and gmtime() as well?
3590 #ifndef HAVE_GMTIME_R
3591 privoxy_mutex_init(&gmtime_mutex);
3592 #endif /* ndef HAVE_GMTIME_R */
3594 #ifndef HAVE_LOCALTIME_R
3595 privoxy_mutex_init(&localtime_mutex);
3596 #endif /* ndef HAVE_GMTIME_R */
3598 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
3599 privoxy_mutex_init(&rand_mutex);
3600 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
3602 #endif /* def MUTEX_LOCKS_AVAILABLE */
3605 /*********************************************************************
3609 * Description : Load the config file and start the listen loop.
3610 * This function is a lot more *sane* with the `load_config'
3611 * and `listen_loop' functions; although it stills does
3612 * a *little* too much for my taste.
3615 * 1 : argc = Number of parameters (including $0).
3616 * 2 : argv = Array of (char *)'s to the parameters.
3618 * Returns : 1 if : can't open config file, unrecognized directive,
3619 * stats requested in multi-thread mode, can't open the
3620 * log file, can't open the jar file, listen port is invalid,
3621 * any load fails, and can't bind port.
3623 * Else main never returns, the process must be signaled
3624 * to terminate execution. Or, on Windows, use the
3625 * "File", "Exit" menu option.
3627 *********************************************************************/
3629 int real_main(int argc, char **argv)
3631 int main(int argc, char **argv)
3635 int do_config_test = 0;
3636 #ifndef HAVE_ARC4RANDOM
3637 unsigned int random_seed;
3640 struct passwd *pw = NULL;
3641 struct group *grp = NULL;
3643 char *pre_chroot_nslookup_to_load_resolver = NULL;
3646 char *fuzz_input_type = NULL;
3647 char *fuzz_input_file = NULL;
3654 #if !defined(_WIN32)
3661 /* Prepare mutexes if supported and necessary. */
3662 initialize_mutexes();
3664 /* Enable logging until further notice. */
3668 * Parse the command line arguments
3670 * XXX: simply printing usage information in case of
3671 * invalid arguments isn't particularly user friendly.
3673 while (++argc_pos < argc)
3676 /* Check to see if the service must be installed or uninstalled */
3677 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3679 const char *pName = argv[argc_pos] + 9;
3682 exit((install_service(pName)) ? 0 : 1);
3684 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3686 const char *pName = argv[argc_pos] + 11;
3689 exit((uninstall_service(pName)) ? 0 : 1);
3691 else if (strcmp(argv[argc_pos], "--service") == 0)
3693 bRunAsService = TRUE;
3694 w32_set_service_cwd();
3695 atexit(w32_service_exit_notify);
3698 #endif /* defined(_WIN32) */
3701 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3703 if (strcmp(argv[argc_pos], "--help") == 0)
3708 else if (strcmp(argv[argc_pos], "--version") == 0)
3710 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3716 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3718 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3722 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3724 if (++argc_pos == argc) usage(argv[0]);
3725 pidfile = strdup_or_die(argv[argc_pos]);
3728 else if (strcmp(argv[argc_pos], "--user") == 0)
3733 if (++argc_pos == argc) usage(argv[argc_pos]);
3735 user_arg = strdup_or_die(argv[argc_pos]);
3736 group_name = strchr(user_arg, '.');
3737 if (NULL != group_name)
3739 /* Nul-terminate the user name */
3742 /* Skip the former delimiter to actually reach the group name */
3745 grp = getgrnam(group_name);
3748 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3751 pw = getpwnam(user_arg);
3754 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3760 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3762 if (++argc_pos == argc) usage(argv[0]);
3763 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3766 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3770 #endif /* defined(unix) */
3772 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3777 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
3780 if (argc < argc_pos + 2) usage(argv[0]);
3781 fuzz_input_type = argv[argc_pos];
3783 fuzz_input_file = argv[argc_pos];
3785 else if (strcmp(argv[argc_pos], "--stfu") == 0)
3787 set_debug_level(LOG_LEVEL_STFU);
3790 else if (argc_pos + 1 != argc)
3793 * This is neither the last command line
3794 * option, nor was it recognized before,
3795 * therefore it must be invalid.
3801 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3803 configfile = argv[argc_pos];
3806 } /* -END- while (more arguments) */
3808 show_version(Argv[0]);
3811 if (*configfile != '/')
3813 char cwd[BUFFER_SIZE];
3815 size_t abs_file_size;
3817 /* make config-filename absolute here */
3818 if (NULL == getcwd(cwd, sizeof(cwd)))