1 const char jcc_rcs[] = "$Id: jcc.c,v 1.446 2016/05/25 10:54:01 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001-2016 the
10 * Privoxy team. http://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 *********************************************************************/
40 #include <sys/types.h>
49 # ifndef FEATURE_PTHREAD
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 */
96 #define bzero(B,N) memset(B,0x00,n)
111 #include "miscutil.h"
113 #include "jbsockets.h"
118 #include "urlmatch.h"
119 #ifdef FEATURE_CLIENT_TAGS
120 #include "client-tags.h"
123 const char jcc_h_rcs[] = JCC_H_VERSION;
124 const char project_h_rcs[] = PROJECT_H_VERSION;
127 struct client_states clients[1];
128 struct file_list files[1];
130 #ifdef FEATURE_STATISTICS
131 int urls_read = 0; /* total nr of urls read inc rejected */
132 int urls_rejected = 0; /* total nr of urls rejected */
133 #endif /* def FEATURE_STATISTICS */
135 #ifdef FEATURE_GRACEFUL_TERMINATION
139 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
140 static void sig_handler(int the_signal);
142 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
143 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
144 static jb_err get_server_headers(struct client_state *csp);
145 static const char *crunch_reason(const struct http_response *rsp);
146 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
147 static char *get_request_line(struct client_state *csp);
148 static jb_err receive_client_request(struct client_state *csp);
149 static jb_err parse_client_request(struct client_state *csp);
150 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
151 static jb_err change_request_destination(struct client_state *csp);
152 static void chat(struct client_state *csp);
153 static void serve(struct client_state *csp);
154 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
155 static void usage(const char *myname);
157 static void initialize_mutexes(void);
158 static jb_socket bind_port_helper(const char *haddr, int hport);
159 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
160 static void close_ports_helper(jb_socket sockets[]);
161 static void listen_loop(void);
164 void serve(struct client_state *csp);
165 #else /* ifndef AMIGA */
166 static void serve(struct client_state *csp);
167 #endif /* def AMIGA */
170 static int32 server_thread(void *data);
171 #endif /* def __BEOS__ */
174 #define sleep(N) Sleep(((N) * 1000))
178 #define sleep(N) DosSleep(((N) * 100))
181 #ifdef MUTEX_LOCKS_AVAILABLE
183 * XXX: Does the locking stuff really belong in this file?
185 privoxy_mutex_t log_mutex;
186 privoxy_mutex_t log_init_mutex;
187 privoxy_mutex_t connection_reuse_mutex;
189 #ifdef FEATURE_EXTERNAL_FILTERS
190 privoxy_mutex_t external_filter_mutex;
192 #ifdef FEATURE_CLIENT_TAGS
193 privoxy_mutex_t client_tags_mutex;
196 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
197 privoxy_mutex_t resolver_mutex;
198 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
200 #ifndef HAVE_GMTIME_R
201 privoxy_mutex_t gmtime_mutex;
202 #endif /* ndef HAVE_GMTIME_R */
204 #ifndef HAVE_LOCALTIME_R
205 privoxy_mutex_t localtime_mutex;
206 #endif /* ndef HAVE_GMTIME_R */
209 privoxy_mutex_t rand_mutex;
210 #endif /* ndef HAVE_RANDOM */
212 #endif /* def MUTEX_LOCKS_AVAILABLE */
215 const char *basedir = NULL;
216 const char *pidfile = NULL;
217 static int received_hup_signal = 0;
218 #endif /* defined unix */
220 /* HTTP snipplets. */
221 static const char CSUCCEED[] =
222 "HTTP/1.1 200 Connection established\r\n\r\n";
224 static const char CHEADER[] =
225 "HTTP/1.1 400 Invalid header received from client\r\n"
226 "Content-Type: text/plain\r\n"
227 "Connection: close\r\n\r\n"
228 "Invalid header received from client.\r\n";
230 static const char FTP_RESPONSE[] =
231 "HTTP/1.1 400 Invalid request received from client\r\n"
232 "Content-Type: text/plain\r\n"
233 "Connection: close\r\n\r\n"
234 "Invalid request. Privoxy doesn't support FTP.\r\n";
236 static const char GOPHER_RESPONSE[] =
237 "HTTP/1.1 400 Invalid request received from client\r\n"
238 "Content-Type: text/plain\r\n"
239 "Connection: close\r\n\r\n"
240 "Invalid request. Privoxy doesn't support gopher.\r\n";
242 /* XXX: should be a template */
243 static const char MISSING_DESTINATION_RESPONSE[] =
244 "HTTP/1.1 400 Bad request received from client\r\n"
245 "Content-Type: text/plain\r\n"
246 "Connection: close\r\n\r\n"
247 "Bad request. Privoxy was unable to extract the destination.\r\n";
249 /* XXX: should be a template */
250 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
251 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
252 "Content-Type: text/plain\r\n"
253 "Connection: close\r\n\r\n"
254 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
256 /* XXX: should be a template */
257 static const char MESSED_UP_REQUEST_RESPONSE[] =
258 "HTTP/1.1 400 Malformed request after rewriting\r\n"
259 "Content-Type: text/plain\r\n"
260 "Connection: close\r\n\r\n"
261 "Bad request. Messed up with header filters.\r\n";
263 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
264 "HTTP/1.1 503 Too many open connections\r\n"
265 "Content-Type: text/plain\r\n"
266 "Connection: close\r\n\r\n"
267 "Maximum number of open connections reached.\r\n";
269 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
270 "HTTP/1.1 504 Connection timeout\r\n"
271 "Content-Type: text/plain\r\n"
272 "Connection: close\r\n\r\n"
273 "The connection timed out because the client request didn't arrive in time.\r\n";
275 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
276 "HTTP/1.1 400 Failed reading client body\r\n"
277 "Content-Type: text/plain\r\n"
278 "Connection: close\r\n\r\n"
279 "Failed parsing or buffering the chunk-encoded client body.\r\n";
281 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
282 "HTTP/1.1 417 Expecting too much\r\n"
283 "Content-Type: text/plain\r\n"
284 "Connection: close\r\n\r\n"
285 "Privoxy detected an unsupported Expect header value.\r\n";
287 /* A function to crunch a response */
288 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
290 /* Crunch function flags */
291 #define CF_NO_FLAGS 0
292 /* Cruncher applies to forced requests as well */
293 #define CF_IGNORE_FORCE 1
294 /* Crunched requests are counted for the block statistics */
295 #define CF_COUNT_AS_REJECT 2
297 /* A crunch function and its flags */
300 const crunch_func_ptr cruncher;
304 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
306 /* Complete list of cruncher functions */
307 static const struct cruncher crunchers_all[] = {
308 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
309 { block_url, CF_COUNT_AS_REJECT },
311 { trust_url, CF_COUNT_AS_REJECT },
312 #endif /* def FEATURE_TRUST */
313 { redirect_url, CF_NO_FLAGS },
314 { dispatch_cgi, CF_IGNORE_FORCE},
318 /* Light version, used after tags are applied */
319 static const struct cruncher crunchers_light[] = {
320 { block_url, CF_COUNT_AS_REJECT },
321 { redirect_url, CF_NO_FLAGS },
327 * XXX: Don't we really mean
333 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
334 /*********************************************************************
336 * Function : sig_handler
338 * Description : Signal handler for different signals.
339 * Exit gracefully on TERM and INT
340 * or set a flag that will cause the errlog
341 * to be reopened by the main thread on HUP.
344 * 1 : the_signal = the signal cause this function to call
348 *********************************************************************/
349 static void sig_handler(int the_signal)
355 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
367 received_hup_signal = 1;
373 * We shouldn't be here, unless we catch signals
374 * in main() that we can't handle here!
376 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
384 /*********************************************************************
386 * Function : client_protocol_is_unsupported
388 * Description : Checks if the client used a known unsupported
389 * protocol and deals with it by sending an error
393 * 1 : csp = Current client state (buffers, headers, etc...)
394 * 2 : req = the first request line send by the client
396 * Returns : TRUE if an error response has been generated, or
397 * FALSE if the request doesn't look invalid.
399 *********************************************************************/
400 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
403 * If it's a FTP or gopher request, we don't support it.
405 * These checks are better than nothing, but they might
406 * not work in all configurations and some clients might
407 * have problems digesting the answer.
409 * They should, however, never cause more problems than
410 * Privoxy's old behaviour (returning the misleading HTML
413 * "Could not resolve http://(ftp|gopher)://example.org").
415 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
417 const char *response = NULL;
418 const char *protocol = NULL;
420 if (!strncmpic(req, "GET ftp://", 10))
422 response = FTP_RESPONSE;
427 response = GOPHER_RESPONSE;
430 log_error(LOG_LEVEL_ERROR,
431 "%s tried to use Privoxy as %s proxy: %s",
432 csp->ip_addr_str, protocol, req);
433 log_error(LOG_LEVEL_CLF,
434 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
436 write_socket(csp->cfd, response, strlen(response));
445 /*********************************************************************
447 * Function : client_has_unsupported_expectations
449 * Description : Checks if the client used an unsupported expectation
450 * in which case an error message is delivered.
453 * 1 : csp = Current client state (buffers, headers, etc...)
455 * Returns : TRUE if an error response has been generated, or
456 * FALSE if the request doesn't look invalid.
458 *********************************************************************/
459 static int client_has_unsupported_expectations(const struct client_state *csp)
461 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
463 log_error(LOG_LEVEL_ERROR,
464 "Rejecting request from client %s with unsupported Expect header value",
466 log_error(LOG_LEVEL_CLF,
467 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
468 write_socket(csp->cfd, UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
469 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE));
479 /*********************************************************************
481 * Function : get_request_destination_elsewhere
483 * Description : If the client's request was redirected into
484 * Privoxy without the client's knowledge,
485 * the request line lacks the destination host.
487 * This function tries to get it elsewhere,
488 * provided accept-intercepted-requests is enabled.
490 * "Elsewhere" currently only means "Host: header",
491 * but in the future we may ask the redirecting
492 * packet filter to look the destination up.
494 * If the destination stays unknown, an error
495 * response is send to the client and headers
496 * are freed so that chat() can return directly.
499 * 1 : csp = Current client state (buffers, headers, etc...)
500 * 2 : headers = a header list
502 * Returns : JB_ERR_OK if the destination is now known, or
503 * JB_ERR_PARSE if it isn't.
505 *********************************************************************/
506 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
510 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
512 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
513 " Privoxy isn't configured to accept intercepted requests.",
514 csp->ip_addr_str, csp->http->cmd);
515 /* XXX: Use correct size */
516 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
517 csp->ip_addr_str, csp->http->cmd);
519 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
520 destroy_list(headers);
524 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
526 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
527 /* Split the domain we just got for pattern matching */
528 init_domain_components(csp->http);
535 /* We can't work without destination. Go spread the news.*/
537 req = list_to_text(headers);
539 /* XXX: Use correct size */
540 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
541 csp->ip_addr_str, csp->http->cmd);
542 log_error(LOG_LEVEL_ERROR,
543 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
544 csp->ip_addr_str, csp->http->cmd, req);
547 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
548 destroy_list(headers);
553 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
554 * to get the destination IP address, use it as host directly
555 * or do a reverse DNS lookup first.
560 /*********************************************************************
562 * Function : get_server_headers
564 * Description : Parses server headers in iob and fills them
565 * into csp->headers so that they can later be
569 * 1 : csp = Current client state (buffers, headers, etc...)
571 * Returns : JB_ERR_OK if everything went fine, or
572 * JB_ERR_PARSE if the headers were incomplete.
574 *********************************************************************/
575 static jb_err get_server_headers(struct client_state *csp)
577 int continue_hack_in_da_house = 0;
580 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
585 * continue hack in da house. Ignore the ending of
586 * this head and continue enlisting header lines.
587 * The reason is described below.
589 enlist(csp->headers, "");
590 continue_hack_in_da_house = 0;
593 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
596 * It's a bodyless continue response, don't
597 * stop header parsing after reaching its end.
599 * As a result Privoxy will concatenate the
600 * next response's head and parse and deliver
601 * the headers as if they belonged to one request.
603 * The client will separate them because of the
604 * empty line between them.
606 * XXX: What we're doing here is clearly against
607 * the intended purpose of the continue header,
608 * and under some conditions (HTTP/1.0 client request)
609 * it's a standard violation.
611 * Anyway, "sort of against the spec" is preferable
612 * to "always getting confused by Continue responses"
613 * (Privoxy's behaviour before this hack was added)
615 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
616 continue_hack_in_da_house = 1;
618 else if (*header == '\0')
621 * If the header is empty, but the Continue hack
622 * isn't active, we can assume that we reached the
623 * end of the buffer before we hit the end of the
626 * Inform the caller an let it decide how to handle it.
631 if (JB_ERR_MEMORY == enlist(csp->headers, header))
634 * XXX: Should we quit the request and return a
635 * out of memory error page instead?
637 log_error(LOG_LEVEL_ERROR,
638 "Out of memory while enlisting server headers. %s lost.",
648 /*********************************************************************
650 * Function : crunch_reason
652 * Description : Translates the crunch reason code into a string.
655 * 1 : rsp = a http_response
657 * Returns : A string with the crunch reason or an error description.
659 *********************************************************************/
660 static const char *crunch_reason(const struct http_response *rsp)
662 char * reason = NULL;
667 return "Internal error while searching for crunch reason";
670 switch (rsp->crunch_reason)
673 reason = "Unsupported HTTP feature";
679 reason = "Untrusted";
682 reason = "Redirected";
688 reason = "DNS failure";
690 case FORWARDING_FAILED:
691 reason = "Forwarding failed";
694 reason = "Connection failure";
697 reason = "Out of memory (may mask other reasons)";
699 case CONNECTION_TIMEOUT:
700 reason = "Connection timeout";
703 reason = "No server data received";
706 reason = "No reason recorded";
714 /*********************************************************************
716 * Function : log_applied_actions
718 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
722 * 1 : actions = Current action spec to log
726 *********************************************************************/
727 static void log_applied_actions(const struct current_action_spec *actions)
730 * The conversion to text requires lots of memory allocations so
731 * we only do the conversion if the user is actually interested.
733 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
735 char *actions_as_text = actions_to_line_of_text(actions);
736 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
737 freez(actions_as_text);
742 /*********************************************************************
744 * Function : send_crunch_response
746 * Description : Delivers already prepared response for
747 * intercepted requests, logs the interception
748 * and frees the response.
751 * 1 : csp = Current client state (buffers, headers, etc...)
752 * 1 : rsp = Fully prepared response. Will be freed on exit.
756 *********************************************************************/
757 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
759 const struct http_request *http = csp->http;
763 assert(rsp->head != NULL);
767 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
771 * Extract the status code from the actual head
772 * that will be send to the client. It is the only
773 * way to get it right for all requests, including
774 * the fixed ones for out-of-memory problems.
776 * A head starts like this: 'HTTP/1.1 200...'
780 status_code[0] = rsp->head[9];
781 status_code[1] = rsp->head[10];
782 status_code[2] = rsp->head[11];
783 status_code[3] = '\0';
785 /* Log that the request was crunched and why. */
786 log_applied_actions(csp->action);
787 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
788 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
789 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
791 /* Write the answer to the client */
792 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
793 || write_socket(csp->cfd, rsp->body, rsp->content_length))
795 /* There is nothing we can do about it. */
796 log_error(LOG_LEVEL_ERROR,
797 "Couldn't deliver the error message through client socket %d: %E",
801 /* Clean up and return */
802 if (cgi_error_memory() != rsp)
804 free_http_response(rsp);
810 /*********************************************************************
812 * Function : crunch_response_triggered
814 * Description : Checks if the request has to be crunched,
815 * and delivers the crunch response if necessary.
818 * 1 : csp = Current client state (buffers, headers, etc...)
819 * 2 : crunchers = list of cruncher functions to run
821 * Returns : TRUE if the request was answered with a crunch response
824 *********************************************************************/
825 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
827 struct http_response *rsp = NULL;
828 const struct cruncher *c;
831 * If CGI request crunching is disabled,
832 * check the CGI dispatcher out of order to
833 * prevent unintentional blocks or redirects.
835 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
836 && (NULL != (rsp = dispatch_cgi(csp))))
838 /* Deliver, log and free the interception response. */
839 send_crunch_response(csp, rsp);
840 csp->flags |= CSP_FLAG_CRUNCHED;
844 for (c = crunchers; c->cruncher != NULL; c++)
847 * Check the cruncher if either Privoxy is toggled
848 * on and the request isn't forced, or if the cruncher
849 * applies to forced requests as well.
851 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
852 !(csp->flags & CSP_FLAG_FORCED)) ||
853 (c->flags & CF_IGNORE_FORCE))
855 rsp = c->cruncher(csp);
858 /* Deliver, log and free the interception response. */
859 send_crunch_response(csp, rsp);
860 csp->flags |= CSP_FLAG_CRUNCHED;
861 #ifdef FEATURE_STATISTICS
862 if (c->flags & CF_COUNT_AS_REJECT)
864 csp->flags |= CSP_FLAG_REJECTED;
866 #endif /* def FEATURE_STATISTICS */
877 /*********************************************************************
879 * Function : build_request_line
881 * Description : Builds the HTTP request line.
883 * If a HTTP forwarder is used it expects the whole URL,
884 * web servers only get the path.
887 * 1 : csp = Current client state (buffers, headers, etc...)
888 * 2 : fwd = The forwarding spec used for the request
889 * XXX: Should use http->fwd instead.
890 * 3 : request_line = The old request line which will be replaced.
892 * Returns : Nothing. Terminates in case of memory problems.
894 *********************************************************************/
895 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
897 struct http_request *http = csp->http;
899 assert(http->ssl == 0);
902 * Downgrade http version from 1.1 to 1.0
903 * if +downgrade action applies.
905 if ((csp->action->flags & ACTION_DOWNGRADE)
906 && (!strcmpic(http->ver, "HTTP/1.1")))
909 http->ver = strdup_or_die("HTTP/1.0");
913 * Rebuild the request line.
915 freez(*request_line);
916 *request_line = strdup(http->gpc);
917 string_append(request_line, " ");
919 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
921 string_append(request_line, http->url);
925 string_append(request_line, http->path);
927 string_append(request_line, " ");
928 string_append(request_line, http->ver);
930 if (*request_line == NULL)
932 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
934 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
938 /*********************************************************************
940 * Function : change_request_destination
942 * Description : Parse a (rewritten) request line and regenerate
943 * the http request data.
946 * 1 : csp = Current client state (buffers, headers, etc...)
948 * Returns : Forwards the parse_http_request() return code.
949 * Terminates in case of memory problems.
951 *********************************************************************/
952 static jb_err change_request_destination(struct client_state *csp)
954 struct http_request *http = csp->http;
957 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
958 csp->headers->first->str);
959 free_http_request(http);
960 err = parse_http_request(csp->headers->first->str, http);
961 if (JB_ERR_OK != err)
963 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
964 jb_err_to_string(err));
971 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
972 /*********************************************************************
974 * Function : server_response_is_complete
976 * Description : Determines whether we should stop reading
977 * from the server socket.
980 * 1 : csp = Current client state (buffers, headers, etc...)
981 * 2 : content_length = Length of content received so far.
983 * Returns : TRUE if the response is complete,
986 *********************************************************************/
987 static int server_response_is_complete(struct client_state *csp,
988 unsigned long long content_length)
990 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
992 if (!strcmpic(csp->http->gpc, "HEAD"))
995 * "HEAD" implies no body, we are thus expecting
996 * no content. XXX: incomplete "list" of methods?
998 csp->expected_content_length = 0;
999 content_length_known = TRUE;
1000 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1003 if (csp->http->status == 204 || csp->http->status == 304)
1006 * Expect no body. XXX: incomplete "list" of status codes?
1008 csp->expected_content_length = 0;
1009 content_length_known = TRUE;
1010 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1013 return (content_length_known && ((0 == csp->expected_content_length)
1014 || (csp->expected_content_length <= content_length)));
1018 #ifdef FEATURE_CONNECTION_SHARING
1019 /*********************************************************************
1021 * Function : wait_for_alive_connections
1023 * Description : Waits for alive connections to timeout.
1029 *********************************************************************/
1030 static void wait_for_alive_connections(void)
1032 int connections_alive = close_unusable_connections();
1034 while (0 < connections_alive)
1036 log_error(LOG_LEVEL_CONNECT,
1037 "Waiting for %d connections to timeout.",
1040 connections_alive = close_unusable_connections();
1043 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1046 #endif /* def FEATURE_CONNECTION_SHARING */
1049 /*********************************************************************
1051 * Function : save_connection_destination
1053 * Description : Remembers a connection for reuse later on.
1056 * 1 : sfd = Open socket to remember.
1057 * 2 : http = The destination for the connection.
1058 * 3 : fwd = The forwarder settings used.
1059 * 3 : server_connection = storage.
1063 *********************************************************************/
1064 void save_connection_destination(jb_socket sfd,
1065 const struct http_request *http,
1066 const struct forward_spec *fwd,
1067 struct reusable_connection *server_connection)
1069 assert(sfd != JB_INVALID_SOCKET);
1070 assert(NULL != http->host);
1072 server_connection->sfd = sfd;
1073 server_connection->host = strdup_or_die(http->host);
1074 server_connection->port = http->port;
1076 assert(NULL != fwd);
1077 assert(server_connection->gateway_host == NULL);
1078 assert(server_connection->gateway_port == 0);
1079 assert(server_connection->forwarder_type == 0);
1080 assert(server_connection->forward_host == NULL);
1081 assert(server_connection->forward_port == 0);
1083 server_connection->forwarder_type = fwd->type;
1084 if (NULL != fwd->gateway_host)
1086 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1090 server_connection->gateway_host = NULL;
1092 server_connection->gateway_port = fwd->gateway_port;
1094 if (NULL != fwd->forward_host)
1096 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1100 server_connection->forward_host = NULL;
1102 server_connection->forward_port = fwd->forward_port;
1106 /*********************************************************************
1108 * Function : verify_request_length
1110 * Description : Checks if we already got the whole client requests
1111 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1114 * Data that doesn't belong to the current request is
1115 * either thrown away to let the client retry on a clean
1116 * socket, or stashed to be dealt with after the current
1117 * request is served.
1120 * 1 : csp = Current client state (buffers, headers, etc...)
1124 *********************************************************************/
1125 static void verify_request_length(struct client_state *csp)
1127 unsigned long long buffered_request_bytes =
1128 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1130 if ((csp->expected_client_content_length != 0)
1131 && (buffered_request_bytes != 0))
1133 if (csp->expected_client_content_length >= buffered_request_bytes)
1135 csp->expected_client_content_length -= buffered_request_bytes;
1136 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1137 "to account for the %llu ones we already got.",
1138 csp->expected_client_content_length, buffered_request_bytes);
1142 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1143 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1144 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1145 "Marking the server socket tainted after throwing %llu bytes away.",
1146 buffered_request_bytes - csp->expected_client_content_length);
1147 csp->expected_client_content_length = 0;
1148 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1151 if (csp->expected_client_content_length == 0)
1153 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1157 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1158 && ((csp->client_iob->cur < csp->client_iob->eod)
1159 || (csp->expected_client_content_length != 0)))
1161 if (strcmpic(csp->http->gpc, "GET")
1162 && strcmpic(csp->http->gpc, "HEAD")
1163 && strcmpic(csp->http->gpc, "TRACE")
1164 && strcmpic(csp->http->gpc, "OPTIONS")
1165 && strcmpic(csp->http->gpc, "DELETE"))
1167 /* XXX: this is an incomplete hack */
1168 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1169 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1173 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1175 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1177 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1178 log_error(LOG_LEVEL_CONNECT,
1179 "Possible pipeline attempt detected. The connection will not "
1180 "be kept alive and we will only serve the first request.");
1181 /* Nuke the pipelined requests from orbit, just to be sure. */
1182 clear_iob(csp->client_iob);
1187 * Keep the pipelined data around for now, we'll deal with
1188 * it once we're done serving the current request.
1190 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1191 assert(csp->client_iob->eod >= csp->client_iob->cur);
1192 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1193 "%d bytes of pipelined data received.",
1194 (int)(csp->client_iob->eod - csp->client_iob->cur));
1200 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1201 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1204 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1207 /*********************************************************************
1209 * Function : mark_server_socket_tainted
1211 * Description : Makes sure we don't reuse a server socket
1212 * (if we didn't read everything the server sent
1213 * us reusing the socket would lead to garbage).
1216 * 1 : csp = Current client state (buffers, headers, etc...)
1220 *********************************************************************/
1221 static void mark_server_socket_tainted(struct client_state *csp)
1224 * For consistency we always mark the server socket
1225 * tainted, however, to reduce the log noise we only
1226 * emit a log message if the server socket could have
1227 * actually been reused.
1229 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1230 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1232 log_error(LOG_LEVEL_CONNECT,
1233 "Marking the server socket %d tainted.",
1234 csp->server_connection.sfd);
1236 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1239 /*********************************************************************
1241 * Function : get_request_line
1243 * Description : Read the client request line.
1246 * 1 : csp = Current client state (buffers, headers, etc...)
1248 * Returns : Pointer to request line or NULL in case of errors.
1250 *********************************************************************/
1251 static char *get_request_line(struct client_state *csp)
1253 char buf[BUFFER_SIZE];
1254 char *request_line = NULL;
1257 memset(buf, 0, sizeof(buf));
1259 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1262 * If there are multiple pipelined requests waiting,
1263 * the flag will be set again once the next request
1266 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1268 request_line = get_header(csp->client_iob);
1269 if ((NULL != request_line) && ('\0' != *request_line))
1271 return request_line;
1275 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1276 "received yet. Continuing reading from %d.", csp->cfd);
1282 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1284 if (socket_is_still_alive(csp->cfd))
1286 log_error(LOG_LEVEL_CONNECT,
1287 "No request line on socket %d received in time. Timeout: %d.",
1288 csp->cfd, csp->config->socket_timeout);
1289 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1290 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1294 log_error(LOG_LEVEL_CONNECT,
1295 "The client side of the connection on socket %d got "
1296 "closed without sending a complete request line.", csp->cfd);
1301 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1303 if (len <= 0) return NULL;
1306 * If there is no memory left for buffering the
1307 * request, there is nothing we can do but hang up
1309 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1314 request_line = get_header(csp->client_iob);
1316 } while ((NULL != request_line) && ('\0' == *request_line));
1318 return request_line;
1324 CHUNK_STATUS_MISSING_DATA,
1325 CHUNK_STATUS_BODY_COMPLETE,
1326 CHUNK_STATUS_PARSE_ERROR
1330 /*********************************************************************
1332 * Function : chunked_body_is_complete
1334 * Description : Figures out whether or not a chunked body is complete.
1336 * Currently it always starts at the beginning of the
1337 * buffer which is somewhat wasteful and prevents Privoxy
1338 * from starting to forward the correctly parsed chunks
1339 * as soon as theoretically possible.
1341 * Should be modified to work with a common buffer,
1342 * and allow the caller to skip already parsed chunks.
1344 * This would allow the function to be used for unbuffered
1345 * response bodies as well.
1348 * 1 : iob = Buffer with the body to check.
1349 * 2 : length = Length of complete body
1351 * Returns : Enum with the result of the check.
1353 *********************************************************************/
1354 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1356 unsigned int chunksize;
1362 * We need at least a single digit, followed by "\r\n",
1363 * followed by an unknown amount of data, followed by "\r\n".
1365 if (p + 5 > iob->eod)
1367 return CHUNK_STATUS_MISSING_DATA;
1369 if (sscanf(p, "%x", &chunksize) != 1)
1371 return CHUNK_STATUS_PARSE_ERROR;
1375 * We want at least a single digit, followed by "\r\n",
1376 * followed by the specified amount of data, followed by "\r\n".
1378 if (p + chunksize + 5 > iob->eod)
1380 return CHUNK_STATUS_MISSING_DATA;
1383 /* Skip chunk-size. */
1384 p = strstr(p, "\r\n");
1387 return CHUNK_STATUS_PARSE_ERROR;
1389 /* Move beyond the chunkdata. */
1392 /* There should be another "\r\n" to skip */
1393 if (memcmp(p, "\r\n", 2))
1395 return CHUNK_STATUS_PARSE_ERROR;
1398 } while (chunksize > 0U);
1400 *length = (size_t)(p - iob->cur);
1401 assert(*length <= (size_t)(iob->eod - iob->cur));
1402 assert(p <= iob->eod);
1404 return CHUNK_STATUS_BODY_COMPLETE;
1409 /*********************************************************************
1411 * Function : receive_chunked_client_request_body
1413 * Description : Read the chunk-encoded client request body.
1414 * Failures are dealt with.
1417 * 1 : csp = Current client state (buffers, headers, etc...)
1419 * Returns : JB_ERR_OK or JB_ERR_PARSE
1421 *********************************************************************/
1422 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1425 enum chunk_status status;
1427 while (CHUNK_STATUS_MISSING_DATA ==
1428 (status = chunked_body_is_complete(csp->client_iob,&body_length)))
1430 char buf[BUFFER_SIZE];
1433 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1435 log_error(LOG_LEVEL_ERROR,
1436 "Timeout while waiting for the client body.");
1439 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1442 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1445 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1450 if (status != CHUNK_STATUS_BODY_COMPLETE)
1452 write_socket(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1453 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE));
1454 log_error(LOG_LEVEL_CLF,
1455 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1456 return JB_ERR_PARSE;
1458 log_error(LOG_LEVEL_CONNECT,
1459 "Chunked client body completely read. Length: %d", body_length);
1460 csp->expected_client_content_length = body_length;
1467 #ifdef FEATURE_FORCE_LOAD
1468 /*********************************************************************
1470 * Function : force_required
1472 * Description : Checks a request line to see if it contains
1473 * the FORCE_PREFIX. If it does, it is removed
1474 * unless enforcing requests has beend disabled.
1477 * 1 : request_line = HTTP request line
1479 * Returns : TRUE if force is required, FALSE otherwise.
1481 *********************************************************************/
1482 static int force_required(const struct client_state *csp, char *request_line)
1486 p = strstr(request_line, "http://");
1490 p += strlen("http://");
1494 /* Intercepted request usually don't specify the protocol. */
1498 /* Go to the beginning of the path */
1503 * If the path is missing the request line is invalid and we
1504 * are done here. The client-visible rejection happens later on.
1509 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1511 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1513 /* XXX: Should clean more carefully */
1514 strclean(request_line, FORCE_PREFIX);
1515 log_error(LOG_LEVEL_FORCE,
1516 "Enforcing request: \"%s\".", request_line);
1520 log_error(LOG_LEVEL_FORCE,
1521 "Ignored force prefix in request: \"%s\".", request_line);
1527 #endif /* def FEATURE_FORCE_LOAD */
1530 /*********************************************************************
1532 * Function : receive_client_request
1534 * Description : Read the client's request (more precisely the
1535 * client headers) and answer it if necessary.
1538 * 1 : csp = Current client state (buffers, headers, etc...)
1540 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1542 *********************************************************************/
1543 static jb_err receive_client_request(struct client_state *csp)
1545 char buf[BUFFER_SIZE];
1548 struct http_request *http;
1552 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1553 struct list header_list;
1554 struct list *headers = &header_list;
1556 /* We don't care if the arriving data is a valid HTTP request or not. */
1557 csp->requests_received_total++;
1561 memset(buf, 0, sizeof(buf));
1563 req = get_request_line(csp);
1566 mark_server_socket_tainted(csp);
1567 return JB_ERR_PARSE;
1569 assert(*req != '\0');
1571 if (client_protocol_is_unsupported(csp, req))
1573 return JB_ERR_PARSE;
1576 #ifdef FEATURE_FORCE_LOAD
1577 if (force_required(csp, req))
1579 csp->flags |= CSP_FLAG_FORCED;
1581 #endif /* def FEATURE_FORCE_LOAD */
1583 err = parse_http_request(req, http);
1585 if (JB_ERR_OK != err)
1587 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1588 /* XXX: Use correct size */
1589 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1590 log_error(LOG_LEVEL_ERROR,
1591 "Couldn't parse request line received from %s: %s",
1592 csp->ip_addr_str, jb_err_to_string(err));
1594 free_http_request(http);
1595 return JB_ERR_PARSE;
1598 /* grab the rest of the client's headers */
1602 p = get_header(csp->client_iob);
1606 /* There are no additional headers to read. */
1613 * We didn't receive a complete header
1614 * line yet, get the rest of it.
1616 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1618 log_error(LOG_LEVEL_ERROR,
1619 "Stopped grabbing the client headers.");
1620 destroy_list(headers);
1621 return JB_ERR_PARSE;
1624 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1627 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1628 destroy_list(headers);
1629 return JB_ERR_PARSE;
1632 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1635 * If there is no memory left for buffering the
1636 * request, there is nothing we can do but hang up
1638 destroy_list(headers);
1639 return JB_ERR_MEMORY;
1644 if (!strncmpic(p, "Transfer-Encoding:", 18))
1647 * XXX: should be called through sed()
1648 * but currently can't.
1650 client_transfer_encoding(csp, &p);
1653 * We were able to read a complete
1654 * header and can finally enlist it.
1661 if (http->host == NULL)
1664 * If we still don't know the request destination,
1665 * the request is invalid or the client uses
1666 * Privoxy without its knowledge.
1668 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1671 * Our attempts to get the request destination
1672 * elsewhere failed or Privoxy is configured
1673 * to only accept proxy requests.
1675 * An error response has already been send
1676 * and we're done here.
1678 return JB_ERR_PARSE;
1682 #ifdef FEATURE_CLIENT_TAGS
1683 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1684 set_client_address(csp, headers);
1685 get_tag_list_for_client(csp->client_tags, csp->client_address);
1689 * Determine the actions for this URL
1691 #ifdef FEATURE_TOGGLE
1692 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1694 /* Most compatible set of actions (i.e. none) */
1695 init_current_action(csp->action);
1698 #endif /* ndef FEATURE_TOGGLE */
1700 get_url_actions(csp, http);
1703 enlist(csp->headers, http->cmd);
1705 /* Append the previously read headers */
1706 err = list_append_list_unique(csp->headers, headers);
1707 destroy_list(headers);
1714 /*********************************************************************
1716 * Function : parse_client_request
1718 * Description : Parses the client's request and decides what to do
1721 * Note that since we're not using select() we could get
1722 * blocked here if a client connected, then didn't say
1726 * 1 : csp = Current client state (buffers, headers, etc...)
1728 * Returns : JB_ERR_OK or JB_ERR_PARSE
1730 *********************************************************************/
1731 static jb_err parse_client_request(struct client_state *csp)
1733 struct http_request *http = csp->http;
1736 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1737 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1738 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1739 && (csp->http->ssl == 0))
1741 /* Assume persistence until further notice */
1742 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1745 if (csp->http->ssl == 0)
1748 * This whole block belongs to chat() but currently
1749 * has to be executed before sed().
1751 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1753 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1755 return JB_ERR_PARSE;
1760 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1762 verify_request_length(csp);
1764 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1766 err = sed(csp, FILTER_CLIENT_HEADERS);
1767 if (JB_ERR_OK != err)
1769 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1771 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1772 csp->ip_addr_str, csp->http->cmd);
1773 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1774 return JB_ERR_PARSE;
1776 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1778 /* Check request line for rewrites. */
1779 if ((NULL == csp->headers->first->str)
1780 || (strcmp(http->cmd, csp->headers->first->str) &&
1781 (JB_ERR_OK != change_request_destination(csp))))
1784 * A header filter broke the request line - bail out.
1786 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1787 /* XXX: Use correct size */
1788 log_error(LOG_LEVEL_CLF,
1789 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1790 log_error(LOG_LEVEL_ERROR,
1791 "Invalid request line after applying header filters.");
1792 free_http_request(http);
1794 return JB_ERR_PARSE;
1797 if (client_has_unsupported_expectations(csp))
1799 return JB_ERR_PARSE;
1807 /*********************************************************************
1811 * Description : Once a connection from the client has been accepted,
1812 * this function is called (via serve()) to handle the
1813 * main business of the communication. This function
1814 * returns after dealing with a single request. It can
1815 * be called multiple times with the same client socket
1816 * if the client is keeping the connection alive.
1818 * The decision whether or not a client connection will
1819 * be kept alive is up to the caller which also must
1820 * close the client socket when done.
1822 * FIXME: chat is nearly thousand lines long.
1826 * 1 : csp = Current client state (buffers, headers, etc...)
1828 * Returns : Nothing.
1830 *********************************************************************/
1831 static void chat(struct client_state *csp)
1833 char buf[BUFFER_SIZE];
1840 int ms_iis5_hack = 0;
1841 unsigned long long byte_count = 0;
1842 const struct forward_spec *fwd;
1843 struct http_request *http;
1844 long len = 0; /* for buffer sizes (and negative error codes) */
1845 int buffer_and_filter_content = 0;
1847 /* Skeleton for HTTP response, if we should intercept the request */
1848 struct http_response *rsp;
1849 struct timeval timeout;
1850 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1851 int watch_client_socket;
1854 memset(buf, 0, sizeof(buf));
1858 if (receive_client_request(csp) != JB_ERR_OK)
1862 if (parse_client_request(csp) != JB_ERR_OK)
1867 /* decide how to route the HTTP request */
1868 fwd = forward_url(csp, http);
1871 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1872 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1877 * build the http request to send to the server
1878 * we have to do one of the following:
1880 * create = use the original HTTP request to create a new
1881 * HTTP request that has either the path component
1882 * without the http://domainspec (w/path) or the
1883 * full orininal URL (w/url)
1884 * Note that the path and/or the HTTP version may
1885 * have been altered by now.
1887 * connect = Open a socket to the host:port of the server
1888 * and short-circuit server and client socket.
1890 * pass = Pass the request unchanged if forwarding a CONNECT
1891 * request to a parent proxy. Note that we'll be sending
1892 * the CFAIL message ourselves if connecting to the parent
1893 * fails, but we won't send a CSUCCEED message if it works,
1894 * since that would result in a double message (ours and the
1895 * parent's). After sending the request to the parent, we simply
1898 * here's the matrix:
1901 * +--------+--------+
1903 * 0 | create | connect|
1905 * Forwarding +--------+--------+
1907 * 1 | create | pass |
1909 * +--------+--------+
1913 if (http->ssl && connect_port_is_forbidden(csp))
1915 const char *acceptable_connect_ports =
1916 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1917 assert(NULL != acceptable_connect_ports);
1918 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1919 "limit-connect{%s} doesn't allow CONNECT requests to %s",
1920 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
1921 csp->action->flags |= ACTION_BLOCK;
1927 freez(csp->headers->first->str);
1928 build_request_line(csp, fwd, &csp->headers->first->str);
1932 * We have a request. Check if one of the crunchers wants it.
1934 if (crunch_response_triggered(csp, crunchers_all))
1937 * Yes. The client got the crunch response and we're done here.
1942 log_applied_actions(csp->action);
1943 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1945 if (fwd->forward_host)
1947 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1948 fwd->forward_host, fwd->forward_port, http->hostport);
1952 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1955 /* here we connect to the server, gateway, or the forwarder */
1957 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1958 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
1959 && socket_is_still_alive(csp->server_connection.sfd)
1960 && connection_destination_matches(&csp->server_connection, http, fwd))
1962 log_error(LOG_LEVEL_CONNECT,
1963 "Reusing server socket %d connected to %s. Total requests: %u.",
1964 csp->server_connection.sfd, csp->server_connection.host,
1965 csp->server_connection.requests_sent_total);
1969 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
1971 #ifdef FEATURE_CONNECTION_SHARING
1972 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1974 remember_connection(&csp->server_connection);
1977 #endif /* def FEATURE_CONNECTION_SHARING */
1979 log_error(LOG_LEVEL_CONNECT,
1980 "Closing server socket %d connected to %s. Total requests: %u.",
1981 csp->server_connection.sfd, csp->server_connection.host,
1982 csp->server_connection.requests_sent_total);
1983 close_socket(csp->server_connection.sfd);
1985 mark_connection_closed(&csp->server_connection);
1987 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1989 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
1991 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
1993 if ((fwd->type != SOCKS_NONE) && (fwd->type != FORWARD_WEBSERVER))
1996 rsp = error_response(csp, "forwarding-failed");
1998 else if (errno == EINVAL)
2000 rsp = error_response(csp, "no-such-domain");
2004 rsp = error_response(csp, "connect-failed");
2007 /* Write the answer to the client */
2010 send_crunch_response(csp, rsp);
2014 * Temporary workaround to prevent already-read client
2015 * bodies from being parsed as new requests. For now we
2016 * err on the safe side and throw all the following
2017 * requests under the bus, even if no client body has been
2018 * buffered. A compliant client will repeat the dropped
2019 * requests on an untainted connection.
2021 * The proper fix is to discard the no longer needed
2022 * client body in the buffer (if there is one) and to
2023 * continue parsing the bytes that follow.
2025 drain_and_close_socket(csp->cfd);
2026 csp->cfd = JB_INVALID_SOCKET;
2030 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2031 save_connection_destination(csp->server_connection.sfd,
2032 http, fwd, &csp->server_connection);
2033 csp->server_connection.keep_alive_timeout =
2034 (unsigned)csp->config->keep_alive_timeout;
2036 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2038 csp->server_connection.requests_sent_total++;
2040 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
2042 /* Client headers have been sent optimistically */
2043 assert(csp->headers->last == NULL);
2045 else if (fwd->forward_host || (http->ssl == 0))
2048 hdr = list_to_text(csp->headers);
2051 /* FIXME Should handle error properly */
2052 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2054 list_remove_all(csp->headers);
2057 * Write the client's (modified) header to the server
2058 * (along with anything else that may be in the buffer)
2060 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2065 log_error(LOG_LEVEL_CONNECT,
2066 "Failed sending request headers to: %s: %E", http->hostport);
2068 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2069 && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
2072 log_error(LOG_LEVEL_CONNECT,
2073 "Failed sending request body to: %s: %E", http->hostport);
2078 rsp = error_response(csp, "connect-failed");
2081 send_crunch_response(csp, rsp);
2089 * We're running an SSL tunnel and we're not forwarding,
2090 * so just ditch the client headers, send the "connect succeeded"
2091 * message to the client, flush the rest, and get out of the way.
2093 list_remove_all(csp->headers);
2094 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
2098 clear_iob(csp->client_iob);
2101 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
2103 /* XXX: should the time start earlier for optimistically sent data? */
2104 csp->server_connection.request_sent = time(NULL);
2106 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2107 csp->cfd : csp->server_connection.sfd;
2109 /* pass data between the client and server
2110 * until one or the other shuts down the connection.
2115 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2116 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2123 * FD_ZERO here seems to point to an errant macro which crashes.
2124 * So do this by hand for now...
2126 memset(&rfds,0x00,sizeof(fd_set));
2130 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2131 if (!watch_client_socket)
2133 maxfd = csp->server_connection.sfd;
2136 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2138 FD_SET(csp->cfd, &rfds);
2141 FD_SET(csp->server_connection.sfd, &rfds);
2143 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2144 if ((csp->flags & CSP_FLAG_CHUNKED)
2145 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2146 && ((csp->iob->eod - csp->iob->cur) >= 5)
2147 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2150 * XXX: This check should be obsolete now,
2151 * but let's wait a while to be sure.
2153 log_error(LOG_LEVEL_CONNECT,
2154 "Looks like we got the last chunk together with "
2155 "the server headers but didn't detect it earlier. "
2156 "We better stop reading.");
2157 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2158 csp->expected_content_length = byte_count;
2159 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2161 if (server_body && server_response_is_complete(csp, byte_count))
2163 if (csp->expected_content_length == byte_count)
2165 log_error(LOG_LEVEL_CONNECT,
2166 "Done reading from server. Content length: %llu as expected. "
2167 "Bytes most recently read: %d.",
2172 log_error(LOG_LEVEL_CONNECT,
2173 "Done reading from server. Expected content length: %llu. "
2174 "Actual content length: %llu. Bytes most recently read: %d.",
2175 csp->expected_content_length, byte_count, len);
2179 * XXX: should not jump around,
2180 * chat() is complicated enough already.
2184 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2186 timeout.tv_sec = csp->config->socket_timeout;
2187 timeout.tv_usec = 0;
2188 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2192 log_error(LOG_LEVEL_ERROR,
2193 "Didn't receive data in time: %s", http->url);
2194 if ((byte_count == 0) && (http->ssl == 0))
2196 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2198 mark_server_socket_tainted(csp);
2203 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2204 mark_server_socket_tainted(csp);
2209 * This is the body of the browser's request,
2210 * just read and write it.
2212 * XXX: Make sure the client doesn't use pipelining
2213 * behind Privoxy's back.
2215 if (FD_ISSET(csp->cfd, &rfds))
2217 int max_bytes_to_read = sizeof(buf) - 1;
2219 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2220 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2222 if (data_is_available(csp->cfd, 0))
2225 * If the next request is already waiting, we have
2226 * to stop select()ing the client socket. Otherwise
2227 * we would always return right away and get nothing
2230 watch_client_socket = 0;
2231 log_error(LOG_LEVEL_CONNECT,
2232 "Stopping to watch the client socket %d. "
2233 "There's already another request waiting.",
2238 * If the client socket is set, but there's no data
2239 * available on the socket, the client went fishing
2240 * and continuing talking to the server makes no sense.
2242 log_error(LOG_LEVEL_CONNECT,
2243 "The client closed socket %d while "
2244 "the server socket %d is still open.",
2245 csp->cfd, csp->server_connection.sfd);
2246 mark_server_socket_tainted(csp);
2249 if (csp->expected_client_content_length != 0)
2251 if (csp->expected_client_content_length < (sizeof(buf) - 1))
2253 max_bytes_to_read = (int)csp->expected_client_content_length;
2255 log_error(LOG_LEVEL_CONNECT,
2256 "Waiting for up to %d bytes from the client.",
2259 assert(max_bytes_to_read < sizeof(buf));
2260 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2262 len = read_socket(csp->cfd, buf, max_bytes_to_read);
2266 /* XXX: not sure if this is necessary. */
2267 mark_server_socket_tainted(csp);
2268 break; /* "game over, man" */
2271 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2272 if (csp->expected_client_content_length != 0)
2274 assert(len <= max_bytes_to_read);
2275 csp->expected_client_content_length -= (unsigned)len;
2276 log_error(LOG_LEVEL_CONNECT,
2277 "Expected client content length set to %llu "
2278 "after reading %d bytes.",
2279 csp->expected_client_content_length, len);
2280 if (csp->expected_client_content_length == 0)
2282 log_error(LOG_LEVEL_CONNECT,
2283 "Done reading from the client.");
2284 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2287 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2289 if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
2291 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2292 mark_server_socket_tainted(csp);
2299 * The server wants to talk. It could be the header or the body.
2300 * If `hdr' is null, then it's the header otherwise it's the body.
2301 * FIXME: Does `hdr' really mean `host'? No.
2303 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2305 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2307 * If we are buffering content, we don't want to eat up to
2308 * buffer-limit bytes if the client no longer cares about them.
2309 * If we aren't buffering, however, a dead client socket will be
2310 * noticed pretty much right away anyway, so we can reduce the
2311 * overhead by skipping the check.
2313 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2316 log_error(LOG_LEVEL_CONNECT,
2317 "The server still wants to talk, but the client may already have hung up on us.");
2319 log_error(LOG_LEVEL_CONNECT,
2320 "The server still wants to talk, but the client hung up on us.");
2321 mark_server_socket_tainted(csp);
2323 #endif /* def _WIN32 */
2325 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2327 len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
2331 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2333 if (http->ssl && (fwd->forward_host == NULL))
2336 * Just hang up. We already confirmed the client's CONNECT
2337 * request with status code 200 and unencrypted content is
2338 * no longer welcome.
2340 log_error(LOG_LEVEL_ERROR,
2341 "CONNECT already confirmed. Unable to tell the client about the problem.");
2344 else if (byte_count)
2347 * Just hang up. We already transmitted the original headers
2348 * and parts of the original content and therefore missed the
2349 * chance to send an error message (without risking data corruption).
2351 * XXX: we could retry with a fancy range request here.
2353 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2354 "Unable to tell the client about the problem.");
2355 mark_server_socket_tainted(csp);
2359 * XXX: Consider handling the cases above the same.
2361 mark_server_socket_tainted(csp);
2365 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2366 if (csp->flags & CSP_FLAG_CHUNKED)
2368 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2370 /* XXX: this is a temporary hack */
2371 log_error(LOG_LEVEL_CONNECT,
2372 "Looks like we reached the end of the last chunk. "
2373 "We better stop reading.");
2374 csp->expected_content_length = byte_count + (unsigned long long)len;
2375 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2379 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2382 * Add a trailing zero to let be able to use string operations.
2383 * XXX: do we still need this with filter_popups gone?
2388 * Normally, this would indicate that we've read
2389 * as much as the server has sent us and we can
2390 * close the client connection. However, Microsoft
2391 * in its wisdom has released IIS/5 with a bug that
2392 * prevents it from sending the trailing \r\n in
2393 * a 302 redirect header (and possibly other headers).
2394 * To work around this if we've haven't parsed
2395 * a full header we'll append a trailing \r\n
2396 * and see if this now generates a valid one.
2398 * This hack shouldn't have any impacts. If we've
2399 * already transmitted the header or if this is a
2400 * SSL connection, then we won't bother with this
2401 * hack. So we only work on partially received
2402 * headers. If we append a \r\n and this still
2403 * doesn't generate a valid header, then we won't
2404 * transmit anything to the client.
2409 if (server_body || http->ssl)
2412 * If we have been buffering up the document,
2413 * now is the time to apply content modification
2414 * and send the result to the client.
2416 if (buffer_and_filter_content)
2418 p = execute_content_filters(csp);
2420 * If content filtering fails, use the original
2421 * buffer and length.
2422 * (see p != NULL ? p : csp->iob->cur below)
2426 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2428 #ifdef FEATURE_COMPRESSION
2429 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2430 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2432 char *compressed_content = compress_buffer(p,
2433 (size_t *)&csp->content_length, csp->config->compression_level);
2434 if (compressed_content != NULL)
2437 p = compressed_content;
2438 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2443 if (JB_ERR_OK != update_server_headers(csp))
2445 log_error(LOG_LEVEL_FATAL,
2446 "Failed to update server headers. after filtering.");
2449 hdr = list_to_text(csp->headers);
2452 /* FIXME Should handle error properly */
2453 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2456 if (write_socket(csp->cfd, hdr, strlen(hdr))
2457 || write_socket(csp->cfd,
2458 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2460 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2463 mark_server_socket_tainted(csp);
2471 break; /* "game over, man" */
2475 * This is NOT the body, so
2476 * Let's pretend the server just sent us a blank line.
2478 snprintf(buf, sizeof(buf), "\r\n");
2479 len = (int)strlen(buf);
2482 * Now, let the normal header parsing algorithm below do its
2483 * job. If it fails, we'll exit instead of continuing.
2490 * If this is an SSL connection or we're in the body
2491 * of the server document, just write it to the client,
2492 * unless we need to buffer the body for later content-filtering
2494 if (server_body || http->ssl)
2496 if (buffer_and_filter_content)
2499 * If there is no memory left for buffering the content, or the buffer limit
2500 * has been reached, switch to non-filtering mode, i.e. make & write the
2501 * header, flush the iob and buf, and get out of the way.
2503 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2508 log_error(LOG_LEVEL_INFO,
2509 "Flushing header and buffers. Stepping back from filtering.");
2511 hdr = list_to_text(csp->headers);
2515 * Memory is too tight to even generate the header.
2516 * Send our static "Out-of-memory" page.
2518 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2519 rsp = cgi_error_memory();
2520 send_crunch_response(csp, rsp);
2521 mark_server_socket_tainted(csp);
2524 hdrlen = strlen(hdr);
2526 if (write_socket(csp->cfd, hdr, hdrlen)
2527 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2528 || (write_socket(csp->cfd, buf, (size_t)len)))
2530 log_error(LOG_LEVEL_CONNECT,
2531 "Flush header and buffers to client failed: %E");
2533 mark_server_socket_tainted(csp);
2538 * Reset the byte_count to the amount of bytes
2539 * we just flushed. len will be added a few lines below,
2540 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2542 byte_count = (unsigned long long)flushed;
2544 buffer_and_filter_content = 0;
2550 if (write_socket(csp->cfd, buf, (size_t)len))
2552 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2553 mark_server_socket_tainted(csp);
2557 byte_count += (unsigned long long)len;
2563 * We're still looking for the end of the server's header.
2564 * Buffer up the data we just read. If that fails, there's
2565 * little we can do but send our static out-of-memory page.
2567 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2569 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2570 rsp = cgi_error_memory();
2571 send_crunch_response(csp, rsp);
2572 mark_server_socket_tainted(csp);
2576 /* Convert iob into something sed() can digest */
2577 if (JB_ERR_PARSE == get_server_headers(csp))
2582 * Well, we tried our MS IIS/5 hack and it didn't work.
2583 * The header is incomplete and there isn't anything
2584 * we can do about it.
2586 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2587 "Applying the MS IIS5 hack didn't help.");
2588 log_error(LOG_LEVEL_CLF,
2589 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2590 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2591 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2592 mark_server_socket_tainted(csp);
2598 * Since we have to wait for more from the server before
2599 * we can parse the headers we just continue here.
2601 log_error(LOG_LEVEL_CONNECT,
2602 "Continuing buffering server headers from socket %d. "
2603 "Bytes most recently read: %d.", csp->cfd, len);
2610 * Account for the content bytes we
2611 * might have gotten with the headers.
2613 assert(csp->iob->eod >= csp->iob->cur);
2614 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2617 /* Did we actually get anything? */
2618 if (NULL == csp->headers->first)
2620 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2622 log_error(LOG_LEVEL_ERROR,
2623 "No server or forwarder response received on socket %d. "
2624 "Closing client socket %d without sending data.",
2625 csp->server_connection.sfd, csp->cfd);
2626 log_error(LOG_LEVEL_CLF,
2627 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2631 log_error(LOG_LEVEL_ERROR,
2632 "No server or forwarder response received on socket %d.",
2633 csp->server_connection.sfd);
2634 send_crunch_response(csp, error_response(csp, "no-server-data"));
2636 free_http_request(http);
2637 mark_server_socket_tainted(csp);
2641 assert(csp->headers->first->str);
2643 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2644 strncmpic(csp->headers->first->str, "ICY", 3))
2647 * It doesn't look like a HTTP (or Shoutcast) response:
2648 * tell the client and log the problem.
2650 if (strlen(csp->headers->first->str) > 30)
2652 csp->headers->first->str[30] = '\0';
2654 log_error(LOG_LEVEL_ERROR,
2655 "Invalid server or forwarder response. Starts with: %s",
2656 csp->headers->first->str);
2657 log_error(LOG_LEVEL_CLF,
2658 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2659 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2660 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2661 free_http_request(http);
2662 mark_server_socket_tainted(csp);
2667 * We have now received the entire server header,
2668 * filter it and send the result to the client
2670 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2672 log_error(LOG_LEVEL_CLF,
2673 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2674 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2675 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2676 free_http_request(http);
2677 mark_server_socket_tainted(csp);
2680 hdr = list_to_text(csp->headers);
2683 /* FIXME Should handle error properly */
2684 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2687 if ((csp->flags & CSP_FLAG_CHUNKED)
2688 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2689 && ((csp->iob->eod - csp->iob->cur) >= 5)
2690 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2692 log_error(LOG_LEVEL_CONNECT,
2693 "Looks like we got the last chunk together with "
2694 "the server headers. We better stop reading.");
2695 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2696 csp->expected_content_length = byte_count;
2697 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2700 csp->server_connection.response_received = time(NULL);
2702 if (crunch_response_triggered(csp, crunchers_light))
2705 * One of the tags created by a server-header
2706 * tagger triggered a crunch. We already
2707 * delivered the crunch response to the client
2708 * and are done here after cleaning up.
2711 mark_server_socket_tainted(csp);
2714 /* Buffer and pcrs filter this if appropriate. */
2716 if (!http->ssl) /* We talk plaintext */
2718 buffer_and_filter_content = content_requires_filtering(csp);
2721 * Only write if we're not buffering for content modification
2723 if (!buffer_and_filter_content)
2726 * Write the server's (modified) header to
2727 * the client (along with anything else that
2728 * may be in the buffer)
2731 if (write_socket(csp->cfd, hdr, strlen(hdr))
2732 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2734 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2737 * The write failed, so don't bother mentioning it
2738 * to the client... it probably can't hear us anyway.
2741 mark_server_socket_tainted(csp);
2746 /* we're finished with the server's header */
2752 * If this was a MS IIS/5 hack then it means the server
2753 * has already closed the connection. Nothing more to read.
2758 log_error(LOG_LEVEL_ERROR,
2759 "Closed server connection detected. "
2760 "Applying the MS IIS5 hack didn't help.");
2761 log_error(LOG_LEVEL_CLF,
2762 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2763 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2764 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2765 mark_server_socket_tainted(csp);
2771 mark_server_socket_tainted(csp);
2772 return; /* huh? we should never get here */
2775 if (csp->content_length == 0)
2778 * If Privoxy didn't recalculate the Content-Length,
2779 * byte_count is still correct.
2781 csp->content_length = byte_count;
2784 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2785 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2786 && (csp->expected_content_length != byte_count))
2788 log_error(LOG_LEVEL_CONNECT,
2789 "Received %llu bytes while expecting %llu.",
2790 byte_count, csp->expected_content_length);
2791 mark_server_socket_tainted(csp);
2795 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2796 csp->ip_addr_str, http->ocmd, csp->content_length);
2798 csp->server_connection.timestamp = time(NULL);
2802 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2803 /*********************************************************************
2805 * Function : prepare_csp_for_next_request
2807 * Description : Put the csp in a mostly vergin state.
2810 * 1 : csp = Current client state (buffers, headers, etc...)
2814 *********************************************************************/
2815 static void prepare_csp_for_next_request(struct client_state *csp)
2817 csp->content_type = 0;
2818 csp->content_length = 0;
2819 csp->expected_content_length = 0;
2820 csp->expected_client_content_length = 0;
2821 list_remove_all(csp->headers);
2822 clear_iob(csp->iob);
2823 freez(csp->error_message);
2824 free_http_request(csp->http);
2825 destroy_list(csp->headers);
2826 destroy_list(csp->tags);
2827 #ifdef FEATURE_CLIENT_TAGS
2828 destroy_list(csp->client_tags);
2829 freez(csp->client_address);
2831 free_current_action(csp->action);
2832 if (NULL != csp->fwd)
2834 unload_forward_spec(csp->fwd);
2837 /* XXX: Store per-connection flags someplace else. */
2838 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
2839 #ifdef FEATURE_TOGGLE
2840 if (global_toggle_state)
2841 #endif /* def FEATURE_TOGGLE */
2843 csp->flags |= CSP_FLAG_TOGGLED_ON;
2846 if (csp->client_iob->eod > csp->client_iob->cur)
2848 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
2849 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2851 assert(bytes_to_shift > 0);
2852 assert(data_length > 0);
2854 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
2855 data_length, bytes_to_shift);
2856 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
2857 csp->client_iob->cur = csp->client_iob->buf;
2858 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
2859 csp->client_iob->eod = csp->client_iob->buf + data_length;
2860 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
2862 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
2867 * We mainly care about resetting client_iob->cur so we don't
2868 * waste buffer space at the beginning and don't mess up the
2869 * request restoration done by cgi_show_request().
2871 * Freeing the buffer itself isn't technically necessary,
2872 * but makes debugging more convenient.
2874 clear_iob(csp->client_iob);
2877 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2880 /*********************************************************************
2884 * Description : This is little more than chat. We only "serve" to
2885 * to close (or remember) any socket that chat may have
2889 * 1 : csp = Current client state (buffers, headers, etc...)
2893 *********************************************************************/
2895 void serve(struct client_state *csp)
2896 #else /* ifndef AMIGA */
2897 static void serve(struct client_state *csp)
2898 #endif /* def AMIGA */
2900 int config_file_change_detected = 0; /* Only used for debugging */
2901 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2902 #ifdef FEATURE_CONNECTION_SHARING
2903 static int monitor_thread_running = 0;
2904 #endif /* def FEATURE_CONNECTION_SHARING */
2905 int continue_chatting = 0;
2907 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
2908 csp->ip_addr_str, csp->cfd);
2912 unsigned int latency;
2917 * If the request has been crunched,
2918 * the calculated latency is zero.
2920 latency = (unsigned)(csp->server_connection.response_received -
2921 csp->server_connection.request_sent) / 2;
2923 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2924 && (csp->flags & CSP_FLAG_CRUNCHED)
2925 && (csp->expected_client_content_length != 0))
2927 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
2928 log_error(LOG_LEVEL_CONNECT,
2929 "Tainting client socket %d due to unread data.", csp->cfd);
2932 continue_chatting = (csp->config->feature_flags
2933 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2934 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2935 && (csp->cfd != JB_INVALID_SOCKET)
2936 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2937 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
2938 || (csp->flags & CSP_FLAG_CHUNKED));
2940 if (!(csp->flags & CSP_FLAG_CRUNCHED)
2941 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
2943 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
2945 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
2947 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2948 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2949 || !socket_is_still_alive(csp->server_connection.sfd)
2950 || !(latency < csp->server_connection.keep_alive_timeout))
2952 log_error(LOG_LEVEL_CONNECT,
2953 "Closing server socket %d connected to %s. "
2954 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
2955 csp->server_connection.sfd, csp->server_connection.host,
2956 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2957 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2958 socket_is_still_alive(csp->server_connection.sfd),
2959 csp->server_connection.keep_alive_timeout);
2960 #ifdef FEATURE_CONNECTION_SHARING
2961 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2963 forget_connection(csp->server_connection.sfd);
2965 #endif /* def FEATURE_CONNECTION_SHARING */
2966 close_socket(csp->server_connection.sfd);
2967 mark_connection_closed(&csp->server_connection);
2971 if (continue_chatting && any_loaded_file_changed(csp))
2973 continue_chatting = 0;
2974 config_file_change_detected = 1;
2977 if (continue_chatting)
2979 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
2980 && socket_is_still_alive(csp->cfd))
2982 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
2983 "pipelined on socket %d and the socket is still alive.",
2984 csp->requests_received_total+1, csp->cfd);
2985 prepare_csp_for_next_request(csp);
2989 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
2991 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2993 log_error(LOG_LEVEL_CONNECT,
2994 "Waiting for the next client request on socket %d. "
2995 "Keeping the server socket %d to %s open.",
2996 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
3000 log_error(LOG_LEVEL_CONNECT,
3001 "Waiting for the next client request on socket %d. "
3002 "No server socket to keep open.", csp->cfd);
3006 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3007 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
3008 && socket_is_still_alive(csp->cfd))
3010 log_error(LOG_LEVEL_CONNECT,
3011 "Client request %u arrived in time on socket %d.",
3012 csp->requests_received_total+1, csp->cfd);
3013 prepare_csp_for_next_request(csp);
3017 #ifdef FEATURE_CONNECTION_SHARING
3018 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3019 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3020 && (socket_is_still_alive(csp->server_connection.sfd)))
3022 time_t time_open = time(NULL) - csp->server_connection.timestamp;
3024 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3029 remember_connection(&csp->server_connection);
3030 csp->server_connection.sfd = JB_INVALID_SOCKET;
3031 drain_and_close_socket(csp->cfd);
3032 csp->cfd = JB_INVALID_SOCKET;
3033 privoxy_mutex_lock(&connection_reuse_mutex);
3034 if (!monitor_thread_running)
3036 monitor_thread_running = 1;
3037 privoxy_mutex_unlock(&connection_reuse_mutex);
3038 wait_for_alive_connections();
3039 privoxy_mutex_lock(&connection_reuse_mutex);
3040 monitor_thread_running = 0;
3042 privoxy_mutex_unlock(&connection_reuse_mutex);
3044 #endif /* def FEATURE_CONNECTION_SHARING */
3048 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3050 log_error(LOG_LEVEL_CONNECT,
3051 "Closing server socket %d connected to %s. Keep-alive: %u. "
3052 "Tainted: %u. Socket alive: %u. Timeout: %u. "
3053 "Configuration file change detected: %u",
3054 csp->server_connection.sfd, csp->server_connection.host,
3055 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3056 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3057 socket_is_still_alive(csp->server_connection.sfd),
3058 csp->server_connection.keep_alive_timeout,
3059 config_file_change_detected);
3061 } while (continue_chatting);
3065 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3067 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3069 #ifdef FEATURE_CONNECTION_SHARING
3070 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3072 forget_connection(csp->server_connection.sfd);
3074 #endif /* def FEATURE_CONNECTION_SHARING */
3075 close_socket(csp->server_connection.sfd);
3078 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3079 mark_connection_closed(&csp->server_connection);
3082 if (csp->cfd != JB_INVALID_SOCKET)
3084 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3085 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3086 "Configuration file change detected: %u. Requests received: %u.",
3087 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3088 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3089 config_file_change_detected, csp->requests_received_total);
3090 drain_and_close_socket(csp->cfd);
3093 csp->flags &= ~CSP_FLAG_ACTIVE;
3099 /*********************************************************************
3101 * Function : server_thread
3103 * Description : We only exist to call `serve' in a threaded environment.
3106 * 1 : data = Current client state (buffers, headers, etc...)
3108 * Returns : Always 0.
3110 *********************************************************************/
3111 static int32 server_thread(void *data)
3113 serve((struct client_state *) data);
3120 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3121 /*********************************************************************
3125 * Description : Print usage info & exit.
3127 * Parameters : Pointer to argv[0] for identifying ourselves
3131 *********************************************************************/
3132 static void usage(const char *myname)
3134 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3135 "Usage: %s [--config-test] "
3138 #endif /* defined(unix) */
3141 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3142 #endif /* defined(unix) */
3143 "[--version] [configfile]\n"
3144 "Aborting\n", myname);
3149 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3152 #ifdef MUTEX_LOCKS_AVAILABLE
3153 /*********************************************************************
3155 * Function : privoxy_mutex_lock
3157 * Description : Locks a mutex.
3160 * 1 : mutex = The mutex to lock.
3162 * Returns : Void. May exit in case of errors.
3164 *********************************************************************/
3165 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3167 #ifdef FEATURE_PTHREAD
3168 int err = pthread_mutex_lock(mutex);
3171 if (mutex != &log_mutex)
3173 log_error(LOG_LEVEL_FATAL,
3174 "Mutex locking failed: %s.\n", strerror(err));
3179 EnterCriticalSection(mutex);
3180 #endif /* def FEATURE_PTHREAD */
3184 /*********************************************************************
3186 * Function : privoxy_mutex_unlock
3188 * Description : Unlocks a mutex.
3191 * 1 : mutex = The mutex to unlock.
3193 * Returns : Void. May exit in case of errors.
3195 *********************************************************************/
3196 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3198 #ifdef FEATURE_PTHREAD
3199 int err = pthread_mutex_unlock(mutex);
3202 if (mutex != &log_mutex)
3204 log_error(LOG_LEVEL_FATAL,
3205 "Mutex unlocking failed: %s.\n", strerror(err));
3210 LeaveCriticalSection(mutex);
3211 #endif /* def FEATURE_PTHREAD */
3215 /*********************************************************************
3217 * Function : privoxy_mutex_init
3219 * Description : Prepares a mutex.
3222 * 1 : mutex = The mutex to initialize.
3224 * Returns : Void. May exit in case of errors.
3226 *********************************************************************/
3227 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3229 #ifdef FEATURE_PTHREAD
3230 int err = pthread_mutex_init(mutex, 0);
3233 printf("Fatal error. Mutex initialization failed: %s.\n",
3238 InitializeCriticalSection(mutex);
3239 #endif /* def FEATURE_PTHREAD */
3241 #endif /* def MUTEX_LOCKS_AVAILABLE */
3243 /*********************************************************************
3245 * Function : initialize_mutexes
3247 * Description : Prepares mutexes if mutex support is available.
3251 * Returns : Void, exits in case of errors.
3253 *********************************************************************/
3254 static void initialize_mutexes(void)
3256 #ifdef MUTEX_LOCKS_AVAILABLE
3258 * Prepare global mutex semaphores
3260 privoxy_mutex_init(&log_mutex);
3261 privoxy_mutex_init(&log_init_mutex);
3262 privoxy_mutex_init(&connection_reuse_mutex);
3263 #ifdef FEATURE_EXTERNAL_FILTERS
3264 privoxy_mutex_init(&external_filter_mutex);
3266 #ifdef FEATURE_CLIENT_TAGS
3267 privoxy_mutex_init(&client_tags_mutex);
3271 * XXX: The assumptions below are a bit naive
3272 * and can cause locks that aren't necessary.
3274 * For example older FreeBSD versions (< 6.x?)
3275 * have no gethostbyname_r, but gethostbyname is
3278 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3279 privoxy_mutex_init(&resolver_mutex);
3280 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3282 * XXX: should we use a single mutex for
3283 * localtime() and gmtime() as well?
3285 #ifndef HAVE_GMTIME_R
3286 privoxy_mutex_init(&gmtime_mutex);
3287 #endif /* ndef HAVE_GMTIME_R */
3289 #ifndef HAVE_LOCALTIME_R
3290 privoxy_mutex_init(&localtime_mutex);
3291 #endif /* ndef HAVE_GMTIME_R */
3294 privoxy_mutex_init(&rand_mutex);
3295 #endif /* ndef HAVE_RANDOM */
3297 #endif /* def MUTEX_LOCKS_AVAILABLE */
3301 /*********************************************************************
3305 * Description : Load the config file and start the listen loop.
3306 * This function is a lot more *sane* with the `load_config'
3307 * and `listen_loop' functions; although it stills does
3308 * a *little* too much for my taste.
3311 * 1 : argc = Number of parameters (including $0).
3312 * 2 : argv = Array of (char *)'s to the parameters.
3314 * Returns : 1 if : can't open config file, unrecognized directive,
3315 * stats requested in multi-thread mode, can't open the
3316 * log file, can't open the jar file, listen port is invalid,
3317 * any load fails, and can't bind port.
3319 * Else main never returns, the process must be signaled
3320 * to terminate execution. Or, on Windows, use the
3321 * "File", "Exit" menu option.
3323 *********************************************************************/
3325 int real_main(int argc, char **argv)
3327 int main(int argc, char **argv)
3331 int do_config_test = 0;
3332 unsigned int random_seed;
3334 struct passwd *pw = NULL;
3335 struct group *grp = NULL;
3337 char *pre_chroot_nslookup_to_load_resolver = NULL;
3344 #if !defined(_WIN32)
3351 /* Prepare mutexes if supported and necessary. */
3352 initialize_mutexes();
3354 /* Enable logging until further notice. */
3358 * Parse the command line arguments
3360 * XXX: simply printing usage information in case of
3361 * invalid arguments isn't particularly user friendly.
3363 while (++argc_pos < argc)
3366 /* Check to see if the service must be installed or uninstalled */
3367 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3369 const char *pName = argv[argc_pos] + 9;
3372 exit((install_service(pName)) ? 0 : 1);
3374 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3376 const char *pName = argv[argc_pos] + 11;
3379 exit((uninstall_service(pName)) ? 0 : 1);
3381 else if (strcmp(argv[argc_pos], "--service") == 0)
3383 bRunAsService = TRUE;
3384 w32_set_service_cwd();
3385 atexit(w32_service_exit_notify);
3388 #endif /* defined(_WIN32) */
3391 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3393 if (strcmp(argv[argc_pos], "--help") == 0)
3398 else if (strcmp(argv[argc_pos], "--version") == 0)
3400 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3406 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3408 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3412 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3414 if (++argc_pos == argc) usage(argv[0]);
3415 pidfile = strdup_or_die(argv[argc_pos]);
3418 else if (strcmp(argv[argc_pos], "--user") == 0)
3423 if (++argc_pos == argc) usage(argv[argc_pos]);
3425 user_arg = strdup_or_die(argv[argc_pos]);
3426 group_name = strchr(user_arg, '.');
3427 if (NULL != group_name)
3429 /* Nul-terminate the user name */
3432 /* Skip the former delimiter to actually reach the group name */
3435 grp = getgrnam(group_name);
3438 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3441 pw = getpwnam(user_arg);
3444 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3450 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3452 if (++argc_pos == argc) usage(argv[0]);
3453 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3456 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3460 #endif /* defined(unix) */
3462 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3467 else if (argc_pos + 1 != argc)
3470 * This is neither the last command line
3471 * option, nor was it recognized before,
3472 * therefore it must be invalid.
3478 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3480 configfile = argv[argc_pos];
3483 } /* -END- while (more arguments) */
3485 show_version(Argv[0]);
3488 if (*configfile != '/')
3490 char cwd[BUFFER_SIZE];
3492 size_t abs_file_size;
3494 /* make config-filename absolute here */
3495 if (NULL == getcwd(cwd, sizeof(cwd)))
3497 perror("failed to get current working directory");
3501 basedir = strdup_or_die(cwd);
3503 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3504 abs_file = malloc_or_die(abs_file_size);
3505 strlcpy(abs_file, basedir, abs_file_size);
3506 strlcat(abs_file, "/", abs_file_size);
3507 strlcat(abs_file, configfile, abs_file_size);
3508 configfile = abs_file;
3510 #endif /* defined unix */
3514 clients->next = NULL;
3516 /* XXX: factor out initialising after the next stable release. */
3519 #elif defined(_WIN32)
3523 random_seed = (unsigned int)time(NULL);
3525 srandom(random_seed);
3528 #endif /* ifdef HAVE_RANDOM */
3531 * Unix signal handling
3533 * Catch the abort, interrupt and terminate signals for a graceful exit
3534 * Catch the hangup signal so the errlog can be reopened.
3535 * Ignore the broken pipe signals (FIXME: Why?)
3537 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3540 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3542 for (idx = 0; idx < SZ(catched_signals); idx++)
3544 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3545 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3547 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3548 #endif /* ifdef sun */
3550 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3554 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3556 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3560 #else /* ifdef _WIN32 */
3561 # ifdef _WIN_CONSOLE
3563 * We *are* in a windows console app.
3564 * Print a verbose messages about FAQ's and such
3566 printf("%s", win32_blurb);
3567 # endif /* def _WIN_CONSOLE */
3568 #endif /* def _WIN32 */
3572 exit(NULL == load_config());
3575 /* Initialize the CGI subsystem */
3576 cgi_init_error_messages();
3579 * If running on unix and without the --no-daemon
3580 * option, become a daemon. I.e. fork, detach
3581 * from tty and get process group leadership
3590 if (pid < 0) /* error */
3595 else if (pid != 0) /* parent */
3600 * must check for errors
3601 * child died due to missing files aso
3604 wpid = waitpid(pid, &status, WNOHANG);
3616 * stderr (fd 2) will be closed later on,
3617 * when the config file has been parsed.
3623 * Reserve fd 0 and 1 to prevent abort() and friends
3624 * from sending stuff to the clients or servers.
3626 fd = open("/dev/null", O_RDONLY);
3629 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3633 if (dup2(fd, 0) == -1)
3635 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3639 fd = open("/dev/null", O_WRONLY);
3642 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3646 if (dup2(fd, 1) == -1)
3648 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3653 #ifdef FEATURE_EXTERNAL_FILTERS
3654 for (fd = 0; fd < 3; fd++)
3656 mark_socket_for_close_on_execute(fd);
3662 } /* -END- if (daemon_mode) */
3665 * As soon as we have written the PID file, we can switch
3666 * to the user and group ID indicated by the --user option
3672 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3674 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3678 if (setgroups(1, &grp->gr_gid))
3680 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3683 else if (initgroups(pw->pw_name, pw->pw_gid))
3685 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3691 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3693 /* Read the time zone file from /etc before doing chroot. */
3695 if (NULL != pre_chroot_nslookup_to_load_resolver
3696 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3698 /* Initialize resolver library. */
3699 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3701 if (chroot(pw->pw_dir) < 0)
3703 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3707 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3710 if (setuid(pw->pw_uid))
3712 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3716 char putenv_dummy[64];
3718 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3719 if (putenv(putenv_dummy) != 0)
3721 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3724 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3725 if (putenv(putenv_dummy) != 0)
3727 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3733 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3736 #endif /* defined unix */
3739 /* This will be FALSE unless the command line specified --service
3743 /* Yup, so now we must attempt to establish a connection
3744 * with the service dispatcher. This will only work if this
3745 * process was launched by the service control manager to
3746 * actually run as a service. If this isn't the case, i've
3747 * known it take around 30 seconds or so for the call to return.
3750 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3751 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3753 /* Service has run, and at this point is now being stopped, so just return */
3758 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3760 /* An error occurred. Usually it's because --service was wrongly specified
3761 * and we were unable to connect to the Service Control Dispatcher because
3762 * it wasn't expecting us and is therefore not listening.
3764 * For now, just continue below to call the listen_loop function.
3767 #endif /* def _WIN32 */
3777 /*********************************************************************
3779 * Function : bind_port_helper
3781 * Description : Bind the listen port. Handles logging, and aborts
3785 * 1 : haddr = Host address to bind to. Use NULL to bind to
3787 * 2 : hport = Specifies port to bind to.
3789 * Returns : Port that was opened.
3791 *********************************************************************/
3792 static jb_socket bind_port_helper(const char *haddr, int hport)
3797 result = bind_port(haddr, hport, &bfd);
3801 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
3805 log_error(LOG_LEVEL_FATAL,
3806 "can't bind to %s:%d: There may be another Privoxy "
3807 "or some other proxy running on port %d",
3808 bind_address, hport, hport);
3811 log_error(LOG_LEVEL_FATAL,
3812 "can't bind to %s:%d: The hostname is not resolvable",
3813 bind_address, hport);
3816 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3817 bind_address, hport);
3820 /* shouldn't get here */
3821 return JB_INVALID_SOCKET;
3825 if (bfd >= FD_SETSIZE)
3827 log_error(LOG_LEVEL_FATAL,
3828 "Bind socket number too high to use select(): %d >= %d",
3835 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3840 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3848 /*********************************************************************
3850 * Function : bind_ports_helper
3852 * Description : Bind the listen ports. Handles logging, and aborts
3856 * 1 : config = Privoxy configuration. Specifies ports
3858 * 2 : sockets = Preallocated array of opened sockets
3859 * corresponding to specification in config.
3860 * All non-opened sockets will be set to
3861 * JB_INVALID_SOCKET.
3863 * Returns : Nothing. Inspect sockets argument.
3865 *********************************************************************/
3866 static void bind_ports_helper(struct configuration_spec * config,
3867 jb_socket sockets[])
3871 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3873 if (config->hport[i])
3875 sockets[i] = bind_port_helper(config->haddr[i], config->hport[i]);
3879 sockets[i] = JB_INVALID_SOCKET;
3882 config->need_bind = 0;
3886 /*********************************************************************
3888 * Function : close_ports_helper
3890 * Description : Close listenings ports.
3893 * 1 : sockets = Array of opened and non-opened sockets to
3894 * close. All sockets will be set to
3895 * JB_INVALID_SOCKET.
3897 * Returns : Nothing.
3899 *********************************************************************/
3900 static void close_ports_helper(jb_socket sockets[])
3904 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3906 if (JB_INVALID_SOCKET != sockets[i])
3908 close_socket(sockets[i]);
3910 sockets[i] = JB_INVALID_SOCKET;
3916 /* Without this simple workaround we get this compiler warning from _beginthread
3917 * warning C4028: formal parameter 1 different from declaration
3919 void w32_service_listen_loop(void *p)
3923 #endif /* def _WIN32 */
3926 /*********************************************************************
3928 * Function : listen_loop
3930 * Description : bind the listen port and enter a "FOREVER" listening loop.
3936 *********************************************************************/
3937 static void listen_loop(void)
3939 struct client_states *csp_list = NULL;
3940 struct client_state *csp = NULL;
3941 jb_socket bfds[MAX_LISTENING_SOCKETS];
3942 struct configuration_spec *config;
3943 unsigned int active_threads = 0;
3945 config = load_config();
3947 #ifdef FEATURE_CONNECTION_SHARING
3949 * XXX: Should be relocated once it no
3950 * longer needs to emit log messages.
3952 initialize_reusable_connections();
3953 #endif /* def FEATURE_CONNECTION_SHARING */
3955 bind_ports_helper(config, bfds);
3957 #ifdef FEATURE_GRACEFUL_TERMINATION
3958 while (!g_terminate)
3963 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3964 while (waitpid(-1, NULL, WNOHANG) > 0)
3966 /* zombie children */
3968 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3971 * Free data that was used by died threads
3973 active_threads = sweep();
3977 * Re-open the errlog after HUP signal
3979 if (received_hup_signal)
3981 if (NULL != config->logfile)
3983 init_error_log(Argv[0], config->logfile);
3985 received_hup_signal = 0;
3989 csp_list = zalloc_or_die(sizeof(*csp_list));
3990 csp = &csp_list->csp;
3992 log_error(LOG_LEVEL_CONNECT,
3993 "Waiting for the next client connection. Currently active threads: %d",
3997 * This config may be outdated, but for accept_connection()
3998 * it's fresh enough.
4000 csp->config = config;
4002 if (!accept_connection(csp, bfds))
4004 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
4016 csp->flags |= CSP_FLAG_ACTIVE;
4017 csp->server_connection.sfd = JB_INVALID_SOCKET;
4019 csp->config = config = load_config();
4021 if (config->need_bind)
4024 * Since we were listening to the "old port", we will not see
4025 * a "listen" param change until the next request. So, at
4026 * least 1 more request must be made for us to find the new
4027 * setting. I am simply closing the old socket and binding the
4030 * Which-ever is correct, we will serve 1 more page via the
4031 * old settings. This should probably be a "show-proxy-args"
4032 * request. This should not be a so common of an operation
4033 * that this will hurt people's feelings.
4036 close_ports_helper(bfds);
4038 bind_ports_helper(config, bfds);
4041 #ifdef FEATURE_TOGGLE
4042 if (global_toggle_state)
4043 #endif /* def FEATURE_TOGGLE */
4045 csp->flags |= CSP_FLAG_TOGGLED_ON;
4048 if (run_loader(csp))
4050 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
4051 /* Never get here - LOG_LEVEL_FATAL causes program exit */
4055 if (block_acl(NULL,csp))
4057 log_error(LOG_LEVEL_CONNECT,
4058 "Connection from %s on %s (socket %d) dropped due to ACL",
4059 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
4060 close_socket(csp->cfd);
4061 freez(csp->ip_addr_str);
4062 freez(csp->listen_addr_str);
4066 #endif /* def FEATURE_ACL */
4068 if ((0 != config->max_client_connections)
4069 && (active_threads >= config->max_client_connections))
4071 log_error(LOG_LEVEL_CONNECT,
4072 "Rejecting connection from %s. Maximum number of connections reached.",
4074 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4075 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4076 close_socket(csp->cfd);
4077 freez(csp->ip_addr_str);
4078 freez(csp->listen_addr_str);
4083 /* add it to the list of clients */
4084 csp_list->next = clients->next;
4085 clients->next = csp_list;
4087 if (config->multi_threaded)
4091 /* this is a switch () statement in the C preprocessor - ugh */
4092 #undef SELECTED_ONE_OPTION
4094 /* Use Pthreads in preference to native code */
4095 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
4096 #define SELECTED_ONE_OPTION
4098 pthread_t the_thread;
4099 pthread_attr_t attrs;
4101 pthread_attr_init(&attrs);
4102 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4103 errno = pthread_create(&the_thread, &attrs,
4104 (void * (*)(void *))serve, csp);
4105 child_id = errno ? -1 : 0;
4106 pthread_attr_destroy(&attrs);
4110 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
4111 #define SELECTED_ONE_OPTION
4112 child_id = _beginthread(
4113 (void (*)(void *))serve,
4118 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
4119 #define SELECTED_ONE_OPTION
4120 child_id = _beginthread(
4121 (void(* _Optlink)(void*))serve,
4127 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
4128 #define SELECTED_ONE_OPTION
4130 thread_id tid = spawn_thread
4131 (server_thread, "server", B_NORMAL_PRIORITY, csp);
4133 if ((tid >= 0) && (resume_thread(tid) == B_OK))
4135 child_id = (int) tid;
4144 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
4145 #define SELECTED_ONE_OPTION
4146 csp->cfd = ReleaseSocket(csp->cfd, -1);
4149 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4150 NP_Output, Output(),
4151 NP_CloseOutput, FALSE,
4152 NP_Name, (ULONG)"privoxy child",
4156 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4157 NP_Output, Output(),
4158 NP_CloseOutput, FALSE,
4159 NP_Name, (ULONG)"privoxy child",
4160 NP_StackSize, 200*1024,
4166 ((struct Task *)child_id)->tc_UserData = csp;
4167 Signal((struct Task *)child_id, SIGF_SINGLE);
4172 #if !defined(SELECTED_ONE_OPTION)
4175 /* This block is only needed when using fork().
4176 * When using threads, the server thread was
4177 * created and run by the call to _beginthread().
4179 if (child_id == 0) /* child */
4182 #ifdef FEATURE_TOGGLE
4183 int inherited_toggle_state = global_toggle_state;
4184 #endif /* def FEATURE_TOGGLE */
4189 * If we've been toggled or we've blocked the request, tell Mom
4192 #ifdef FEATURE_TOGGLE
4193 if (inherited_toggle_state != global_toggle_state)
4195 rc |= RC_FLAG_TOGGLED;
4197 #endif /* def FEATURE_TOGGLE */
4199 #ifdef FEATURE_STATISTICS
4200 if (csp->flags & CSP_FLAG_REJECTED)
4202 rc |= RC_FLAG_BLOCKED;
4204 #endif /* ndef FEATURE_STATISTICS */
4208 else if (child_id > 0) /* parent */
4210 /* in a fork()'d environment, the parent's
4211 * copy of the client socket and the CSP
4215 #if !defined(_WIN32) && !defined(__CYGWIN__)
4217 wait(&child_status);
4220 * Evaluate child's return code: If the child has
4221 * - been toggled, toggle ourselves
4222 * - blocked its request, bump up the stats counter
4225 #ifdef FEATURE_TOGGLE
4226 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4228 global_toggle_state = !global_toggle_state;
4230 #endif /* def FEATURE_TOGGLE */
4232 #ifdef FEATURE_STATISTICS
4234 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4238 #endif /* def FEATURE_STATISTICS */
4240 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4241 close_socket(csp->cfd);
4242 csp->flags &= ~CSP_FLAG_ACTIVE;
4246 #undef SELECTED_ONE_OPTION
4247 /* end of cpp switch () */
4252 * Spawning the child failed, assume it's because
4253 * there are too many children running already.
4254 * XXX: If you assume ...
4256 log_error(LOG_LEVEL_ERROR,
4257 "Unable to take any additional connections: %E. Active threads: %d",
4259 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4260 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4261 close_socket(csp->cfd);
4262 csp->flags &= ~CSP_FLAG_ACTIVE;
4271 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4273 /* Clean up. Aim: free all memory (no leaks) */
4274 #ifdef FEATURE_GRACEFUL_TERMINATION
4276 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4278 unload_current_config_file();
4279 unload_current_actions_file();
4280 unload_current_re_filterfile();
4281 #ifdef FEATURE_TRUST
4282 unload_current_trust_file();
4285 if (config->multi_threaded)
4292 } while ((clients->next != NULL) && (--i > 0));
4296 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4306 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4307 /* Cleanup - remove taskbar icon etc. */
4312 #endif /* FEATURE_GRACEFUL_TERMINATION */