1 const char jcc_rcs[] = "$Id: jcc.c,v 1.254 2009/06/11 11:44:25 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001-2009 the SourceForge
10 * Privoxy team. http://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 *********************************************************************/
40 #include <sys/types.h>
49 # ifndef FEATURE_PTHREAD
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
65 # if !defined (__OS2__)
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
74 #include <sys/termios.h>
85 # include <socket.h> /* BeOS has select() for sockets only. */
86 # include <OS.h> /* declarations for threads and stuff. */
89 # if defined(__EMX__) || defined(__OS2__)
90 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
95 #define bzero(B,N) memset(B,0x00,n)
110 #include "miscutil.h"
112 #include "jbsockets.h"
117 #include "urlmatch.h"
119 const char jcc_h_rcs[] = JCC_H_VERSION;
120 const char project_h_rcs[] = PROJECT_H_VERSION;
123 struct client_state clients[1];
124 struct file_list files[1];
126 #ifdef FEATURE_STATISTICS
127 int urls_read = 0; /* total nr of urls read inc rejected */
128 int urls_rejected = 0; /* total nr of urls rejected */
129 #endif /* def FEATURE_STATISTICS */
131 #ifdef FEATURE_GRACEFUL_TERMINATION
135 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
136 static void sig_handler(int the_signal);
138 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
139 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
140 static jb_err get_server_headers(struct client_state *csp);
141 static const char *crunch_reason(const struct http_response *rsp);
142 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
143 static char *get_request_line(struct client_state *csp);
144 static jb_err receive_client_request(struct client_state *csp);
145 static jb_err parse_client_request(struct client_state *csp);
146 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
147 static jb_err change_request_destination(struct client_state *csp);
148 static void chat(struct client_state *csp);
149 static void serve(struct client_state *csp);
150 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
151 static void usage(const char *myname);
153 static void initialize_mutexes(void);
154 static jb_socket bind_port_helper(struct configuration_spec *config);
155 static void listen_loop(void);
158 void serve(struct client_state *csp);
159 #else /* ifndef AMIGA */
160 static void serve(struct client_state *csp);
161 #endif /* def AMIGA */
164 static int32 server_thread(void *data);
165 #endif /* def __BEOS__ */
168 #define sleep(N) Sleep(((N) * 1000))
172 #define sleep(N) DosSleep(((N) * 100))
175 #ifdef MUTEX_LOCKS_AVAILABLE
177 * XXX: Does the locking stuff really belong in this file?
179 privoxy_mutex_t log_mutex;
180 privoxy_mutex_t log_init_mutex;
181 privoxy_mutex_t connection_reuse_mutex;
183 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
184 privoxy_mutex_t resolver_mutex;
185 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
187 #ifndef HAVE_GMTIME_R
188 privoxy_mutex_t gmtime_mutex;
189 #endif /* ndef HAVE_GMTIME_R */
191 #ifndef HAVE_LOCALTIME_R
192 privoxy_mutex_t localtime_mutex;
193 #endif /* ndef HAVE_GMTIME_R */
196 privoxy_mutex_t rand_mutex;
197 #endif /* ndef HAVE_RANDOM */
199 #endif /* def MUTEX_LOCKS_AVAILABLE */
202 const char *basedir = NULL;
203 const char *pidfile = NULL;
204 static int received_hup_signal = 0;
205 #endif /* defined unix */
207 /* HTTP snipplets. */
208 static const char CSUCCEED[] =
209 "HTTP/1.0 200 Connection established\r\n"
210 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
212 static const char CHEADER[] =
213 "HTTP/1.0 400 Invalid header received from client\r\n"
214 "Proxy-Agent: Privoxy " VERSION "\r\n"
215 "Content-Type: text/plain\r\n"
216 "Connection: close\r\n\r\n"
217 "Invalid header received from client.\r\n";
219 static const char FTP_RESPONSE[] =
220 "HTTP/1.0 400 Invalid request received from client\r\n"
221 "Content-Type: text/plain\r\n"
222 "Connection: close\r\n\r\n"
223 "Invalid request. Privoxy doesn't support FTP.\r\n";
225 static const char GOPHER_RESPONSE[] =
226 "HTTP/1.0 400 Invalid request received from client\r\n"
227 "Content-Type: text/plain\r\n"
228 "Connection: close\r\n\r\n"
229 "Invalid request. Privoxy doesn't support gopher.\r\n";
231 /* XXX: should be a template */
232 static const char MISSING_DESTINATION_RESPONSE[] =
233 "HTTP/1.0 400 Bad request received from client\r\n"
234 "Proxy-Agent: Privoxy " VERSION "\r\n"
235 "Content-Type: text/plain\r\n"
236 "Connection: close\r\n\r\n"
237 "Bad request. Privoxy was unable to extract the destination.\r\n";
239 /* XXX: should be a template */
240 static const char NO_SERVER_DATA_RESPONSE[] =
241 "HTTP/1.0 502 Server or forwarder response empty\r\n"
242 "Proxy-Agent: Privoxy " VERSION "\r\n"
243 "Content-Type: text/plain\r\n"
244 "Connection: close\r\n\r\n"
245 "Empty server or forwarder response.\r\n"
246 "The connection has been closed but Privoxy didn't receive any data.\r\n";
248 /* XXX: should be a template */
249 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
250 "HTTP/1.0 502 Server or forwarder response invalid\r\n"
251 "Proxy-Agent: Privoxy " VERSION "\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";
257 /* XXX: should be a template */
258 static const char NULL_BYTE_RESPONSE[] =
259 "HTTP/1.0 400 Bad request received from client\r\n"
260 "Proxy-Agent: Privoxy " VERSION "\r\n"
261 "Content-Type: text/plain\r\n"
262 "Connection: close\r\n\r\n"
263 "Bad request. Null byte(s) before end of request.\r\n";
266 /* XXX: should be a template */
267 static const char MESSED_UP_REQUEST_RESPONSE[] =
268 "HTTP/1.0 400 Malformed request after rewriting\r\n"
269 "Proxy-Agent: Privoxy " VERSION "\r\n"
270 "Content-Type: text/plain\r\n"
271 "Connection: close\r\n\r\n"
272 "Bad request. Messed up with header filters.\r\n";
274 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
275 "HTTP/1.0 503 Too many open connections\r\n"
276 "Proxy-Agent: Privoxy " VERSION "\r\n"
277 "Content-Type: text/plain\r\n"
278 "Connection: close\r\n\r\n"
279 "Maximum number of open connections reached.\r\n";
281 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
282 "HTTP/1.0 504 Connection timeout\r\n"
283 "Proxy-Agent: Privoxy " VERSION "\r\n"
284 "Content-Type: text/plain\r\n"
285 "Connection: close\r\n\r\n"
286 "The connection timed out because the client request didn't arrive in time.\r\n";
288 /* A function to crunch a response */
289 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
291 /* Crunch function flags */
292 #define CF_NO_FLAGS 0
293 /* Cruncher applies to forced requests as well */
294 #define CF_IGNORE_FORCE 1
295 /* Crunched requests are counted for the block statistics */
296 #define CF_COUNT_AS_REJECT 2
298 /* A crunch function and its flags */
301 const crunch_func_ptr cruncher;
305 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
307 /* Complete list of cruncher functions */
308 static const struct cruncher crunchers_all[] = {
309 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
310 { block_url, CF_COUNT_AS_REJECT },
312 { trust_url, CF_COUNT_AS_REJECT },
313 #endif /* def FEATURE_TRUST */
314 { redirect_url, CF_NO_FLAGS },
315 { dispatch_cgi, CF_IGNORE_FORCE},
319 /* Light version, used after tags are applied */
320 static const struct cruncher crunchers_light[] = {
321 { block_url, CF_COUNT_AS_REJECT },
322 { redirect_url, CF_NO_FLAGS },
328 * XXX: Don't we really mean
334 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
335 /*********************************************************************
337 * Function : sig_handler
339 * Description : Signal handler for different signals.
340 * Exit gracefully on TERM and INT
341 * or set a flag that will cause the errlog
342 * to be reopened by the main thread on HUP.
345 * 1 : the_signal = the signal cause this function to call
349 *********************************************************************/
350 static void sig_handler(int the_signal)
356 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
368 received_hup_signal = 1;
374 * We shouldn't be here, unless we catch signals
375 * in main() that we can't handle here!
377 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
385 /*********************************************************************
387 * Function : client_protocol_is_unsupported
389 * Description : Checks if the client used a known unsupported
390 * protocol and deals with it by sending an error
394 * 1 : csp = Current client state (buffers, headers, etc...)
395 * 2 : req = the first request line send by the client
397 * Returns : TRUE if an error response has been generated, or
398 * FALSE if the request doesn't look invalid.
400 *********************************************************************/
401 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
404 * If it's a FTP or gopher request, we don't support it.
406 * These checks are better than nothing, but they might
407 * not work in all configurations and some clients might
408 * have problems digesting the answer.
410 * They should, however, never cause more problems than
411 * Privoxy's old behaviour (returning the misleading HTML
414 * "Could not resolve http://(ftp|gopher)://example.org").
416 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
418 const char *response = NULL;
419 const char *protocol = NULL;
421 if (!strncmpic(req, "GET ftp://", 10))
423 response = FTP_RESPONSE;
428 response = GOPHER_RESPONSE;
431 log_error(LOG_LEVEL_ERROR,
432 "%s tried to use Privoxy as %s proxy: %s",
433 csp->ip_addr_str, protocol, req);
434 log_error(LOG_LEVEL_CLF,
435 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
437 write_socket(csp->cfd, response, strlen(response));
446 /*********************************************************************
448 * Function : get_request_destination_elsewhere
450 * Description : If the client's request was redirected into
451 * Privoxy without the client's knowledge,
452 * the request line lacks the destination host.
454 * This function tries to get it elsewhere,
455 * provided accept-intercepted-requests is enabled.
457 * "Elsewhere" currently only means "Host: header",
458 * but in the future we may ask the redirecting
459 * packet filter to look the destination up.
461 * If the destination stays unknown, an error
462 * response is send to the client and headers
463 * are freed so that chat() can return directly.
466 * 1 : csp = Current client state (buffers, headers, etc...)
467 * 2 : headers = a header list
469 * Returns : JB_ERR_OK if the destination is now known, or
470 * JB_ERR_PARSE if it isn't.
472 *********************************************************************/
473 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
477 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
479 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
480 " Privoxy isn't configured to accept intercepted requests.",
481 csp->ip_addr_str, csp->http->cmd);
482 /* XXX: Use correct size */
483 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
484 csp->ip_addr_str, csp->http->cmd);
486 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
487 destroy_list(headers);
491 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
493 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
494 /* Split the domain we just got for pattern matching */
495 init_domain_components(csp->http);
502 /* We can't work without destination. Go spread the news.*/
504 req = list_to_text(headers);
506 /* XXX: Use correct size */
507 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
508 csp->ip_addr_str, csp->http->cmd);
509 log_error(LOG_LEVEL_ERROR,
510 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
511 csp->ip_addr_str, csp->http->cmd, req);
514 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
515 destroy_list(headers);
520 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
521 * to get the destination IP address, use it as host directly
522 * or do a reverse DNS lookup first.
527 /*********************************************************************
529 * Function : get_server_headers
531 * Description : Parses server headers in iob and fills them
532 * into csp->headers so that they can later be
536 * 1 : csp = Current client state (buffers, headers, etc...)
538 * Returns : JB_ERR_OK if everything went fine, or
539 * JB_ERR_PARSE if the headers were incomplete.
541 *********************************************************************/
542 static jb_err get_server_headers(struct client_state *csp)
544 int continue_hack_in_da_house = 0;
547 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
552 * continue hack in da house. Ignore the ending of
553 * this head and continue enlisting header lines.
554 * The reason is described below.
556 enlist(csp->headers, "");
557 continue_hack_in_da_house = 0;
560 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
563 * It's a bodyless continue response, don't
564 * stop header parsing after reaching its end.
566 * As a result Privoxy will concatenate the
567 * next response's head and parse and deliver
568 * the headers as if they belonged to one request.
570 * The client will separate them because of the
571 * empty line between them.
573 * XXX: What we're doing here is clearly against
574 * the intended purpose of the continue header,
575 * and under some conditions (HTTP/1.0 client request)
576 * it's a standard violation.
578 * Anyway, "sort of against the spec" is preferable
579 * to "always getting confused by Continue responses"
580 * (Privoxy's behaviour before this hack was added)
582 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
583 continue_hack_in_da_house = 1;
585 else if (*header == '\0')
588 * If the header is empty, but the Continue hack
589 * isn't active, we can assume that we reached the
590 * end of the buffer before we hit the end of the
593 * Inform the caller an let it decide how to handle it.
598 if (JB_ERR_MEMORY == enlist(csp->headers, header))
601 * XXX: Should we quit the request and return a
602 * out of memory error page instead?
604 log_error(LOG_LEVEL_ERROR,
605 "Out of memory while enlisting server headers. %s lost.",
615 /*********************************************************************
617 * Function : crunch_reason
619 * Description : Translates the crunch reason code into a string.
622 * 1 : rsp = a http_response
624 * Returns : A string with the crunch reason or an error description.
626 *********************************************************************/
627 static const char *crunch_reason(const struct http_response *rsp)
629 char * reason = NULL;
634 return "Internal error while searching for crunch reason";
639 case RSP_REASON_UNSUPPORTED:
640 reason = "Unsupported HTTP feature";
642 case RSP_REASON_BLOCKED:
645 case RSP_REASON_UNTRUSTED:
646 reason = "Untrusted";
648 case RSP_REASON_REDIRECTED:
649 reason = "Redirected";
651 case RSP_REASON_CGI_CALL:
654 case RSP_REASON_NO_SUCH_DOMAIN:
655 reason = "DNS failure";
657 case RSP_REASON_FORWARDING_FAILED:
658 reason = "Forwarding failed";
660 case RSP_REASON_CONNECT_FAILED:
661 reason = "Connection failure";
663 case RSP_REASON_OUT_OF_MEMORY:
664 reason = "Out of memory (may mask other reasons)";
666 case RSP_REASON_CONNECTION_TIMEOUT:
667 reason = "Connection timeout";
670 reason = "No reason recorded";
678 /*********************************************************************
680 * Function : send_crunch_response
682 * Description : Delivers already prepared response for
683 * intercepted requests, logs the interception
684 * and frees the response.
687 * 1 : csp = Current client state (buffers, headers, etc...)
688 * 1 : rsp = Fully prepared response. Will be freed on exit.
692 *********************************************************************/
693 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
695 const struct http_request *http = csp->http;
699 assert(rsp->head != NULL);
704 * Not supposed to happen. If it does
705 * anyway, treat it as an unknown error.
707 cgi_error_unknown(csp, rsp, RSP_REASON_INTERNAL_ERROR);
708 /* return code doesn't matter */
713 /* If rsp is still NULL, we have serious internal problems. */
714 log_error(LOG_LEVEL_FATAL,
715 "NULL response in send_crunch_response and cgi_error_unknown failed as well.");
719 * Extract the status code from the actual head
720 * that was send to the client. It is the only
721 * way to get it right for all requests, including
722 * the fixed ones for out-of-memory problems.
724 * A head starts like this: 'HTTP/1.1 200...'
728 status_code[0] = rsp->head[9];
729 status_code[1] = rsp->head[10];
730 status_code[2] = rsp->head[11];
731 status_code[3] = '\0';
733 /* Write the answer to the client */
734 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
735 || write_socket(csp->cfd, rsp->body, rsp->content_length))
737 /* There is nothing we can do about it. */
738 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
741 /* Log that the request was crunched and why. */
742 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
743 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
744 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
746 /* Clean up and return */
747 if (cgi_error_memory() != rsp)
749 free_http_response(rsp);
756 /*********************************************************************
758 * Function : request_contains_null_bytes
760 * Description : Checks for NULL bytes in the request and sends
761 * an error message to the client if any were found.
763 * XXX: currently not used, see comment in chat().
766 * 1 : csp = Current client state (buffers, headers, etc...)
767 * 2 : buf = Data from the client's request to check.
768 * 3 : len = The data length.
770 * Returns : TRUE if the request contained one or more NULL bytes, or
773 *********************************************************************/
774 static int request_contains_null_bytes(const struct client_state *csp, char *buf, int len)
776 size_t c_len; /* Request lenght when treated as C string */
783 * Null byte(s) found. Log the request,
784 * return an error response and hang up.
786 size_t tmp_len = c_len;
791 * Replace NULL byte(s) with '°' characters
792 * so the request can be logged as string.
793 * XXX: Is there a better replacement character?
796 tmp_len += strlen(buf+tmp_len);
797 } while (tmp_len < len);
799 log_error(LOG_LEVEL_ERROR, "%s\'s request contains at least one NULL byte "
800 "(length=%d, strlen=%u).", csp->ip_addr_str, len, c_len);
801 log_error(LOG_LEVEL_HEADER,
802 "Offending request data with NULL bytes turned into \'°\' characters: %s", buf);
804 write_socket(csp->cfd, NULL_BYTE_RESPONSE, strlen(NULL_BYTE_RESPONSE));
806 /* XXX: Log correct size */
807 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
817 /*********************************************************************
819 * Function : crunch_response_triggered
821 * Description : Checks if the request has to be crunched,
822 * and delivers the crunch response if necessary.
825 * 1 : csp = Current client state (buffers, headers, etc...)
826 * 2 : crunchers = list of cruncher functions to run
828 * Returns : TRUE if the request was answered with a crunch response
831 *********************************************************************/
832 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
834 struct http_response *rsp = NULL;
835 const struct cruncher *c;
838 * If CGI request crunching is disabled,
839 * check the CGI dispatcher out of order to
840 * prevent unintentional blocks or redirects.
842 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
843 && (NULL != (rsp = dispatch_cgi(csp))))
845 /* Deliver, log and free the interception response. */
846 send_crunch_response(csp, rsp);
850 for (c = crunchers; c->cruncher != NULL; c++)
853 * Check the cruncher if either Privoxy is toggled
854 * on and the request isn't forced, or if the cruncher
855 * applies to forced requests as well.
857 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
858 !(csp->flags & CSP_FLAG_FORCED)) ||
859 (c->flags & CF_IGNORE_FORCE))
861 rsp = c->cruncher(csp);
864 /* Deliver, log and free the interception response. */
865 send_crunch_response(csp, rsp);
866 #ifdef FEATURE_STATISTICS
867 if (c->flags & CF_COUNT_AS_REJECT)
869 csp->flags |= CSP_FLAG_REJECTED;
871 #endif /* def FEATURE_STATISTICS */
882 /*********************************************************************
884 * Function : build_request_line
886 * Description : Builds the HTTP request line.
888 * If a HTTP forwarder is used it expects the whole URL,
889 * web servers only get the path.
892 * 1 : csp = Current client state (buffers, headers, etc...)
893 * 2 : fwd = The forwarding spec used for the request
894 * XXX: Should use http->fwd instead.
895 * 3 : request_line = The old request line which will be replaced.
897 * Returns : Nothing. Terminates in case of memory problems.
899 *********************************************************************/
900 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
902 struct http_request *http = csp->http;
904 assert(http->ssl == 0);
907 * Downgrade http version from 1.1 to 1.0
908 * if +downgrade action applies.
910 if ( (csp->action->flags & ACTION_DOWNGRADE)
911 && (!strcmpic(http->ver, "HTTP/1.1")))
914 http->ver = strdup("HTTP/1.0");
916 if (http->ver == NULL)
918 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
923 * Rebuild the request line.
925 freez(*request_line);
926 *request_line = strdup(http->gpc);
927 string_append(request_line, " ");
929 if (fwd->forward_host)
931 string_append(request_line, http->url);
935 string_append(request_line, http->path);
937 string_append(request_line, " ");
938 string_append(request_line, http->ver);
940 if (*request_line == NULL)
942 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
944 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
948 /*********************************************************************
950 * Function : change_request_destination
952 * Description : Parse a (rewritten) request line and regenerate
953 * the http request data.
956 * 1 : csp = Current client state (buffers, headers, etc...)
958 * Returns : Forwards the parse_http_request() return code.
959 * Terminates in case of memory problems.
961 *********************************************************************/
962 static jb_err change_request_destination(struct client_state *csp)
964 struct http_request *http = csp->http;
967 log_error(LOG_LEVEL_INFO, "Rewrite detected: %s", csp->headers->first->str);
968 free_http_request(http);
969 err = parse_http_request(csp->headers->first->str, http);
970 if (JB_ERR_OK != err)
972 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
973 jb_err_to_string(err));
977 /* XXX: ocmd is a misleading name */
978 http->ocmd = strdup(http->cmd);
979 if (http->ocmd == NULL)
981 log_error(LOG_LEVEL_FATAL,
982 "Out of memory copying rewritten HTTP request line");
990 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
991 /*********************************************************************
993 * Function : server_response_is_complete
995 * Description : Determines whether we should stop reading
996 * from the server socket.
999 * 1 : csp = Current client state (buffers, headers, etc...)
1000 * 2 : content_length = Length of content received so far.
1002 * Returns : TRUE if the response is complete,
1005 *********************************************************************/
1006 static int server_response_is_complete(struct client_state *csp,
1007 unsigned long long content_length)
1009 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1011 if (!strcmpic(csp->http->gpc, "HEAD"))
1014 * "HEAD" implies no body, we are thus expecting
1015 * no content. XXX: incomplete "list" of methods?
1017 csp->expected_content_length = 0;
1018 content_length_known = TRUE;
1021 if (csp->http->status == 304)
1024 * Expect no body. XXX: incomplete "list" of status codes?
1026 csp->expected_content_length = 0;
1027 content_length_known = TRUE;
1030 return (content_length_known && ((0 == csp->expected_content_length)
1031 || (csp->expected_content_length <= content_length)));
1035 /*********************************************************************
1037 * Function : wait_for_alive_connections
1039 * Description : Waits for alive connections to timeout.
1045 *********************************************************************/
1046 static void wait_for_alive_connections(void)
1048 int connections_alive = close_unusable_connections();
1050 while (0 < connections_alive)
1052 log_error(LOG_LEVEL_CONNECT,
1053 "Waiting for %d connections to timeout.",
1056 connections_alive = close_unusable_connections();
1059 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1064 /*********************************************************************
1066 * Function : save_connection_destination
1068 * Description : Remembers a connection for reuse later on.
1071 * 1 : sfd = Open socket to remember.
1072 * 2 : http = The destination for the connection.
1073 * 3 : fwd = The forwarder settings used.
1074 * 3 : server_connection = storage.
1078 *********************************************************************/
1079 void save_connection_destination(jb_socket sfd,
1080 const struct http_request *http,
1081 const struct forward_spec *fwd,
1082 struct reusable_connection *server_connection)
1084 assert(sfd != JB_INVALID_SOCKET);
1085 assert(NULL != http->host);
1086 server_connection->host = strdup(http->host);
1087 if (NULL == server_connection->host)
1089 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
1091 server_connection->port = http->port;
1093 assert(NULL != fwd);
1094 assert(server_connection->gateway_host == NULL);
1095 assert(server_connection->gateway_port == 0);
1096 assert(server_connection->forwarder_type == 0);
1097 assert(server_connection->forward_host == NULL);
1098 assert(server_connection->forward_port == 0);
1100 server_connection->forwarder_type = fwd->type;
1101 if (NULL != fwd->gateway_host)
1103 server_connection->gateway_host = strdup(fwd->gateway_host);
1104 if (NULL == server_connection->gateway_host)
1106 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
1111 server_connection->gateway_host = NULL;
1113 server_connection->gateway_port = fwd->gateway_port;
1115 if (NULL != fwd->forward_host)
1117 server_connection->forward_host = strdup(fwd->forward_host);
1118 if (NULL == server_connection->forward_host)
1120 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
1125 server_connection->forward_host = NULL;
1127 server_connection->forward_port = fwd->forward_port;
1129 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1132 /*********************************************************************
1134 * Function : mark_server_socket_tainted
1136 * Description : Makes sure we don't reuse a server socket
1137 * (if we didn't read everything the server sent
1138 * us reusing the socket would lead to garbage).
1141 * 1 : csp = Current client state (buffers, headers, etc...)
1145 *********************************************************************/
1146 static void mark_server_socket_tainted(struct client_state *csp)
1148 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE))
1150 log_error(LOG_LEVEL_CONNECT, "Unsetting keep-alive flag.");
1151 csp->flags &= ~CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1155 /*********************************************************************
1157 * Function : get_request_line
1159 * Description : Read the client request line.
1162 * 1 : csp = Current client state (buffers, headers, etc...)
1164 * Returns : Pointer to request line or NULL in case of errors.
1166 *********************************************************************/
1167 static char *get_request_line(struct client_state *csp)
1169 char buf[BUFFER_SIZE];
1170 char *request_line = NULL;
1173 memset(buf, 0, sizeof(buf));
1177 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1179 log_error(LOG_LEVEL_ERROR,
1180 "Stopped waiting for the request line.");
1181 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1182 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1186 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1188 if (len <= 0) return NULL;
1191 * If there is no memory left for buffering the
1192 * request, there is nothing we can do but hang up
1194 if (add_to_iob(csp, buf, len))
1199 request_line = get_header(csp->iob);
1201 } while ((NULL != request_line) && ('\0' == *request_line));
1203 return request_line;
1208 /*********************************************************************
1210 * Function : receive_client_request
1212 * Description : Read the client's request (more precisely the
1213 * client headers) and answer it if necessary.
1215 * Note that since we're not using select() we could get
1216 * blocked here if a client connected, then didn't say
1220 * 1 : csp = Current client state (buffers, headers, etc...)
1222 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1224 *********************************************************************/
1225 static jb_err receive_client_request(struct client_state *csp)
1227 char buf[BUFFER_SIZE];
1230 struct http_request *http;
1234 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1235 struct list header_list;
1236 struct list *headers = &header_list;
1240 memset(buf, 0, sizeof(buf));
1242 req = get_request_line(csp);
1245 return JB_ERR_PARSE;
1247 assert(*req != '\0');
1249 if (client_protocol_is_unsupported(csp, req))
1251 return JB_ERR_PARSE;
1254 #ifdef FEATURE_FORCE_LOAD
1256 * If this request contains the FORCE_PREFIX and blocks
1257 * aren't enforced, get rid of it and set the force flag.
1259 if (strstr(req, FORCE_PREFIX))
1261 if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1263 log_error(LOG_LEVEL_FORCE,
1264 "Ignored force prefix in request: \"%s\".", req);
1268 strclean(req, FORCE_PREFIX);
1269 log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1270 csp->flags |= CSP_FLAG_FORCED;
1273 #endif /* def FEATURE_FORCE_LOAD */
1275 err = parse_http_request(req, http);
1277 if (JB_ERR_OK != err)
1279 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1280 /* XXX: Use correct size */
1281 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1282 log_error(LOG_LEVEL_ERROR,
1283 "Couldn't parse request line received from %s: %s",
1284 csp->ip_addr_str, jb_err_to_string(err));
1286 free_http_request(http);
1287 return JB_ERR_PARSE;
1290 /* grab the rest of the client's headers */
1294 p = get_header(csp->iob);
1298 /* There are no additional headers to read. */
1305 * We didn't receive a complete header
1306 * line yet, get the rest of it.
1308 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1310 log_error(LOG_LEVEL_ERROR,
1311 "Stopped grabbing the client headers.");
1312 destroy_list(headers);
1313 return JB_ERR_PARSE;
1316 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1319 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1320 destroy_list(headers);
1321 return JB_ERR_PARSE;
1324 if (add_to_iob(csp, buf, len))
1327 * If there is no memory left for buffering the
1328 * request, there is nothing we can do but hang up
1330 destroy_list(headers);
1331 return JB_ERR_MEMORY;
1337 * We were able to read a complete
1338 * header and can finaly enlist it.
1345 if (http->host == NULL)
1348 * If we still don't know the request destination,
1349 * the request is invalid or the client uses
1350 * Privoxy without its knowledge.
1352 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1355 * Our attempts to get the request destination
1356 * elsewhere failed or Privoxy is configured
1357 * to only accept proxy requests.
1359 * An error response has already been send
1360 * and we're done here.
1362 return JB_ERR_PARSE;
1367 * Determine the actions for this URL
1369 #ifdef FEATURE_TOGGLE
1370 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1372 /* Most compatible set of actions (i.e. none) */
1373 init_current_action(csp->action);
1376 #endif /* ndef FEATURE_TOGGLE */
1378 get_url_actions(csp, http);
1382 * Save a copy of the original request for logging
1384 http->ocmd = strdup(http->cmd);
1385 if (http->ocmd == NULL)
1387 log_error(LOG_LEVEL_FATAL,
1388 "Out of memory copying HTTP request line");
1390 enlist(csp->headers, http->cmd);
1392 /* Append the previously read headers */
1393 list_append_list_unique(csp->headers, headers);
1394 destroy_list(headers);
1401 /*********************************************************************
1403 * Function : parse_client_request
1405 * Description : Parses the client's request and decides what to do
1408 * Note that since we're not using select() we could get
1409 * blocked here if a client connected, then didn't say
1413 * 1 : csp = Current client state (buffers, headers, etc...)
1415 * Returns : JB_ERR_OK or JB_ERR_PARSE
1417 *********************************************************************/
1418 static jb_err parse_client_request(struct client_state *csp)
1420 struct http_request *http = csp->http;
1423 err = sed(csp, FILTER_CLIENT_HEADERS);
1424 if (JB_ERR_OK != err)
1426 /* XXX: Should be handled in sed(). */
1427 assert(err == JB_ERR_PARSE);
1428 log_error(LOG_LEVEL_FATAL, "Failed to parse client headers.");
1430 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1432 /* Check request line for rewrites. */
1433 if ((NULL == csp->headers->first->str)
1434 || (strcmp(http->cmd, csp->headers->first->str) &&
1435 (JB_ERR_OK != change_request_destination(csp))))
1438 * A header filter broke the request line - bail out.
1440 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1441 /* XXX: Use correct size */
1442 log_error(LOG_LEVEL_CLF,
1443 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1444 log_error(LOG_LEVEL_ERROR,
1445 "Invalid request line after applying header filters.");
1446 free_http_request(http);
1448 return JB_ERR_PARSE;
1456 /*********************************************************************
1460 * Description : Once a connection to the client has been accepted,
1461 * this function is called (via serve()) to handle the
1462 * main business of the communication. When this
1463 * function returns, the caller must close the client
1466 * FIXME: chat is nearly thousand lines long.
1470 * 1 : csp = Current client state (buffers, headers, etc...)
1472 * Returns : Nothing.
1474 *********************************************************************/
1475 static void chat(struct client_state *csp)
1477 char buf[BUFFER_SIZE];
1484 int ms_iis5_hack = 0;
1485 unsigned long long byte_count = 0;
1486 int forwarded_connect_retries = 0;
1487 int max_forwarded_connect_retries = csp->config->forwarded_connect_retries;
1488 const struct forward_spec *fwd;
1489 struct http_request *http;
1490 long len = 0; /* for buffer sizes (and negative error codes) */
1492 /* Function that does the content filtering for the current request */
1493 filter_function_ptr content_filter = NULL;
1495 /* Skeleton for HTTP response, if we should intercept the request */
1496 struct http_response *rsp;
1497 struct timeval timeout;
1499 memset(buf, 0, sizeof(buf));
1503 if (receive_client_request(csp) != JB_ERR_OK)
1507 if (parse_client_request(csp) != JB_ERR_OK)
1512 /* decide how to route the HTTP request */
1513 fwd = forward_url(csp, http);
1516 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1517 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1522 * build the http request to send to the server
1523 * we have to do one of the following:
1525 * create = use the original HTTP request to create a new
1526 * HTTP request that has either the path component
1527 * without the http://domainspec (w/path) or the
1528 * full orininal URL (w/url)
1529 * Note that the path and/or the HTTP version may
1530 * have been altered by now.
1532 * connect = Open a socket to the host:port of the server
1533 * and short-circuit server and client socket.
1535 * pass = Pass the request unchanged if forwarding a CONNECT
1536 * request to a parent proxy. Note that we'll be sending
1537 * the CFAIL message ourselves if connecting to the parent
1538 * fails, but we won't send a CSUCCEED message if it works,
1539 * since that would result in a double message (ours and the
1540 * parent's). After sending the request to the parent, we simply
1543 * here's the matrix:
1546 * +--------+--------+
1548 * 0 | create | connect|
1550 * Forwarding +--------+--------+
1552 * 1 | create | pass |
1554 * +--------+--------+
1558 if (http->ssl && connect_port_is_forbidden(csp))
1560 const char *acceptable_connect_ports =
1561 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1562 assert(NULL != acceptable_connect_ports);
1563 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1564 "limit-connect{%s} doesn't allow CONNECT requests to port %d.",
1565 csp->ip_addr_str, acceptable_connect_ports, csp->http->port);
1566 csp->action->flags |= ACTION_BLOCK;
1572 freez(csp->headers->first->str);
1573 build_request_line(csp, fwd, &csp->headers->first->str);
1577 * We have a request. Check if one of the crunchers wants it.
1579 if (crunch_response_triggered(csp, crunchers_all))
1582 * Yes. The client got the crunch response
1583 * and we are done here after cleaning up.
1585 /* XXX: why list_remove_all()? */
1586 list_remove_all(csp->headers);
1591 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1593 if (fwd->forward_host)
1595 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1596 fwd->forward_host, fwd->forward_port, http->hostport);
1600 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1603 /* here we connect to the server, gateway, or the forwarder */
1605 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1606 if ((csp->sfd != JB_INVALID_SOCKET)
1607 && socket_is_still_usable(csp->sfd)
1608 && connection_destination_matches(&csp->server_connection, http, fwd))
1610 log_error(LOG_LEVEL_CONNECT,
1611 "Reusing server socket %u. Opened for %s.",
1612 csp->sfd, csp->server_connection.host);
1616 if (csp->sfd != JB_INVALID_SOCKET)
1618 log_error(LOG_LEVEL_CONNECT,
1619 "Closing server socket %u. Opened for %s.",
1620 csp->sfd, csp->server_connection.host);
1621 close_socket(csp->sfd);
1622 mark_connection_closed(&csp->server_connection);
1624 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1626 while ((csp->sfd = forwarded_connect(fwd, http, csp))
1627 && (errno == EINVAL)
1628 && (forwarded_connect_retries++ < max_forwarded_connect_retries))
1630 log_error(LOG_LEVEL_ERROR,
1631 "failed request #%u to connect to %s. Trying again.",
1632 forwarded_connect_retries, http->hostport);
1635 if (csp->sfd == JB_INVALID_SOCKET)
1637 if (fwd->type != SOCKS_NONE)
1640 rsp = error_response(csp, "forwarding-failed");
1642 else if (errno == EINVAL)
1644 rsp = error_response(csp, "no-such-domain");
1648 rsp = error_response(csp, "connect-failed");
1649 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1653 /* Write the answer to the client */
1656 send_crunch_response(csp, rsp);
1661 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1662 save_connection_destination(csp->sfd, http, fwd, &csp->server_connection);
1663 csp->server_connection.keep_alive_timeout = (unsigned)csp->config->keep_alive_timeout;
1665 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1667 hdr = list_to_text(csp->headers);
1670 /* FIXME Should handle error properly */
1671 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1673 list_remove_all(csp->headers);
1675 if (fwd->forward_host || (http->ssl == 0))
1678 * Write the client's (modified) header to the server
1679 * (along with anything else that may be in the buffer)
1681 if (write_socket(csp->sfd, hdr, strlen(hdr))
1682 || (flush_socket(csp->sfd, csp->iob) < 0))
1684 log_error(LOG_LEVEL_CONNECT,
1685 "write header to: %s failed: %E", http->hostport);
1687 rsp = error_response(csp, "connect-failed");
1690 send_crunch_response(csp, rsp);
1700 * We're running an SSL tunnel and we're not forwarding,
1701 * so just send the "connect succeeded" message to the
1702 * client, flush the rest, and get out of the way.
1704 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
1712 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
1714 /* we're finished with the client's header */
1717 maxfd = (csp->cfd > csp->sfd) ? csp->cfd : csp->sfd;
1719 /* pass data between the client and server
1720 * until one or the other shuts down the connection.
1729 * FD_ZERO here seems to point to an errant macro which crashes.
1730 * So do this by hand for now...
1732 memset(&rfds,0x00,sizeof(fd_set));
1736 FD_SET(csp->cfd, &rfds);
1737 FD_SET(csp->sfd, &rfds);
1739 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1740 if ((csp->flags & CSP_FLAG_CHUNKED)
1741 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
1742 && ((csp->iob->eod - csp->iob->cur) >= 5)
1743 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
1745 log_error(LOG_LEVEL_CONNECT,
1746 "Looks like we read the last chunk together with "
1747 "the server headers. We better stop reading.");
1748 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
1749 csp->expected_content_length = byte_count;
1750 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
1752 if (server_body && server_response_is_complete(csp, byte_count))
1754 log_error(LOG_LEVEL_CONNECT,
1755 "Done reading from server. Expected content length: %llu. "
1756 "Actual content length: %llu. Most recently received: %d.",
1757 csp->expected_content_length, byte_count, len);
1760 * XXX: should not jump around,
1761 * chat() is complicated enough already.
1765 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1767 timeout.tv_sec = csp->config->socket_timeout;
1768 timeout.tv_usec = 0;
1769 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
1773 log_error(LOG_LEVEL_ERROR,
1774 "Didn't receive data in time: %s", http->url);
1775 if ((byte_count == 0) && (http->ssl == 0))
1777 send_crunch_response(csp, error_response(csp, "connection-timeout"));
1779 mark_server_socket_tainted(csp);
1784 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1785 mark_server_socket_tainted(csp);
1790 * This is the body of the browser's request,
1791 * just read and write it.
1793 * XXX: Make sure the client doesn't use pipelining
1794 * behind Privoxy's back.
1796 if (FD_ISSET(csp->cfd, &rfds))
1798 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1802 /* XXX: not sure if this is necessary. */
1803 mark_server_socket_tainted(csp);
1804 break; /* "game over, man" */
1807 if (write_socket(csp->sfd, buf, (size_t)len))
1809 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1810 mark_server_socket_tainted(csp);
1817 * The server wants to talk. It could be the header or the body.
1818 * If `hdr' is null, then it's the header otherwise it's the body.
1819 * FIXME: Does `hdr' really mean `host'? No.
1821 if (FD_ISSET(csp->sfd, &rfds))
1824 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1828 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1830 if (http->ssl && (fwd->forward_host == NULL))
1833 * Just hang up. We already confirmed the client's CONNECT
1834 * request with status code 200 and unencrypted content is
1835 * no longer welcome.
1837 log_error(LOG_LEVEL_ERROR,
1838 "CONNECT already confirmed. Unable to tell the client about the problem.");
1841 else if (byte_count)
1844 * Just hang up. We already transmitted the original headers
1845 * and parts of the original content and therefore missed the
1846 * chance to send an error message (without risking data corruption).
1848 * XXX: we could retry with a fancy range request here.
1850 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
1851 "Unable to tell the client about the problem.");
1852 mark_server_socket_tainted(csp);
1856 * XXX: Consider handling the cases above the same.
1858 mark_server_socket_tainted(csp);
1862 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1863 if (csp->flags & CSP_FLAG_CHUNKED)
1865 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
1867 /* XXX: this is a temporary hack */
1868 log_error(LOG_LEVEL_CONNECT,
1869 "Looks like we reached the end of the last chunk. "
1870 "We better stop reading.");
1871 csp->expected_content_length = byte_count + (unsigned long long)len;
1872 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
1876 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1879 * Add a trailing zero to let be able to use string operations.
1880 * XXX: do we still need this with filter_popups gone?
1885 * Normally, this would indicate that we've read
1886 * as much as the server has sent us and we can
1887 * close the client connection. However, Microsoft
1888 * in its wisdom has released IIS/5 with a bug that
1889 * prevents it from sending the trailing \r\n in
1890 * a 302 redirect header (and possibly other headers).
1891 * To work around this if we've haven't parsed
1892 * a full header we'll append a trailing \r\n
1893 * and see if this now generates a valid one.
1895 * This hack shouldn't have any impacts. If we've
1896 * already transmitted the header or if this is a
1897 * SSL connection, then we won't bother with this
1898 * hack. So we only work on partially received
1899 * headers. If we append a \r\n and this still
1900 * doesn't generate a valid header, then we won't
1901 * transmit anything to the client.
1906 if (server_body || http->ssl)
1909 * If we have been buffering up the document,
1910 * now is the time to apply content modification
1911 * and send the result to the client.
1915 p = execute_content_filter(csp, content_filter);
1917 * If the content filter fails, use the original
1918 * buffer and length.
1919 * (see p != NULL ? p : csp->iob->cur below)
1923 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
1926 if (JB_ERR_OK != update_server_headers(csp))
1928 log_error(LOG_LEVEL_FATAL,
1929 "Failed to update server headers. after filtering.");
1932 hdr = list_to_text(csp->headers);
1935 /* FIXME Should handle error properly */
1936 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1939 if (write_socket(csp->cfd, hdr, strlen(hdr))
1940 || write_socket(csp->cfd,
1941 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
1943 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1946 mark_server_socket_tainted(csp);
1954 break; /* "game over, man" */
1958 * This is NOT the body, so
1959 * Let's pretend the server just sent us a blank line.
1961 snprintf(buf, sizeof(buf), "\r\n");
1962 len = (int)strlen(buf);
1965 * Now, let the normal header parsing algorithm below do its
1966 * job. If it fails, we'll exit instead of continuing.
1973 * If this is an SSL connection or we're in the body
1974 * of the server document, just write it to the client,
1975 * unless we need to buffer the body for later content-filtering
1977 if (server_body || http->ssl)
1982 * If there is no memory left for buffering the content, or the buffer limit
1983 * has been reached, switch to non-filtering mode, i.e. make & write the
1984 * header, flush the iob and buf, and get out of the way.
1986 if (add_to_iob(csp, buf, len))
1991 log_error(LOG_LEVEL_INFO,
1992 "Flushing header and buffers. Stepping back from filtering.");
1994 hdr = list_to_text(csp->headers);
1998 * Memory is too tight to even generate the header.
1999 * Send our static "Out-of-memory" page.
2001 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2002 rsp = cgi_error_memory();
2003 send_crunch_response(csp, rsp);
2004 mark_server_socket_tainted(csp);
2007 hdrlen = strlen(hdr);
2009 if (write_socket(csp->cfd, hdr, hdrlen)
2010 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2011 || (write_socket(csp->cfd, buf, (size_t)len)))
2013 log_error(LOG_LEVEL_CONNECT,
2014 "Flush header and buffers to client failed: %E");
2016 mark_server_socket_tainted(csp);
2021 * Reset the byte_count to the amount of bytes
2022 * we just flushed. len will be added a few lines below,
2023 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2025 byte_count = (unsigned long long)flushed;
2027 content_filter = NULL;
2033 if (write_socket(csp->cfd, buf, (size_t)len))
2035 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2036 mark_server_socket_tainted(csp);
2040 byte_count += (unsigned long long)len;
2045 const char *header_start;
2047 * We're still looking for the end of the server's header.
2048 * Buffer up the data we just read. If that fails, there's
2049 * little we can do but send our static out-of-memory page.
2051 if (add_to_iob(csp, buf, len))
2053 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2054 rsp = cgi_error_memory();
2055 send_crunch_response(csp, rsp);
2056 mark_server_socket_tainted(csp);
2060 header_start = csp->iob->cur;
2062 /* Convert iob into something sed() can digest */
2063 if (JB_ERR_PARSE == get_server_headers(csp))
2068 * Well, we tried our MS IIS/5 hack and it didn't work.
2069 * The header is incomplete and there isn't anything
2070 * we can do about it.
2072 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2073 "Applying the MS IIS5 hack didn't help.");
2074 log_error(LOG_LEVEL_CLF,
2075 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2076 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2077 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2078 mark_server_socket_tainted(csp);
2084 * Since we have to wait for more from the server before
2085 * we can parse the headers we just continue here.
2087 long header_offset = csp->iob->cur - header_start;
2088 assert(csp->iob->cur >= header_start);
2089 byte_count += (unsigned long long)(len - header_offset);
2090 log_error(LOG_LEVEL_CONNECT, "Continuing buffering headers. "
2091 "byte_count: %llu. header_offset: %d. len: %d.",
2092 byte_count, header_offset, len);
2097 /* Did we actually get anything? */
2098 if (NULL == csp->headers->first)
2100 log_error(LOG_LEVEL_ERROR, "Empty server or forwarder response.");
2101 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2102 write_socket(csp->cfd, NO_SERVER_DATA_RESPONSE, strlen(NO_SERVER_DATA_RESPONSE));
2103 free_http_request(http);
2104 mark_server_socket_tainted(csp);
2108 assert(csp->headers->first->str);
2110 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2111 strncmpic(csp->headers->first->str, "ICY", 3))
2114 * It doesn't look like a HTTP (or Shoutcast) response:
2115 * tell the client and log the problem.
2117 if (strlen(csp->headers->first->str) > 30)
2119 csp->headers->first->str[30] = '\0';
2121 log_error(LOG_LEVEL_ERROR,
2122 "Invalid server or forwarder response. Starts with: %s",
2123 csp->headers->first->str);
2124 log_error(LOG_LEVEL_CLF,
2125 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2126 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2127 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2128 free_http_request(http);
2129 mark_server_socket_tainted(csp);
2134 * We have now received the entire server header,
2135 * filter it and send the result to the client
2137 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2139 log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2141 hdr = list_to_text(csp->headers);
2144 /* FIXME Should handle error properly */
2145 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2148 if (crunch_response_triggered(csp, crunchers_light))
2151 * One of the tags created by a server-header
2152 * tagger triggered a crunch. We already
2153 * delivered the crunch response to the client
2154 * and are done here after cleaning up.
2157 mark_server_socket_tainted(csp);
2160 /* Buffer and pcrs filter this if appropriate. */
2162 if (!http->ssl) /* We talk plaintext */
2164 content_filter = get_filter_function(csp);
2167 * Only write if we're not buffering for content modification
2169 if (!content_filter)
2172 * Write the server's (modified) header to
2173 * the client (along with anything else that
2174 * may be in the buffer)
2177 if (write_socket(csp->cfd, hdr, strlen(hdr))
2178 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2180 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2183 * The write failed, so don't bother mentioning it
2184 * to the client... it probably can't hear us anyway.
2187 mark_server_socket_tainted(csp);
2191 byte_count += (unsigned long long)len;
2196 * XXX: the header lenght should probably
2197 * be calculated by get_server_headers().
2199 long header_length = csp->iob->cur - header_start;
2200 assert(csp->iob->cur > header_start);
2201 byte_count += (unsigned long long)(len - header_length);
2204 /* we're finished with the server's header */
2210 * If this was a MS IIS/5 hack then it means the server
2211 * has already closed the connection. Nothing more to read.
2216 log_error(LOG_LEVEL_ERROR,
2217 "Closed server connection detected. "
2218 "Applying the MS IIS5 hack didn't help.");
2219 log_error(LOG_LEVEL_CLF,
2220 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2221 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2222 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2223 mark_server_socket_tainted(csp);
2229 mark_server_socket_tainted(csp);
2230 return; /* huh? we should never get here */
2233 if (csp->content_length == 0)
2236 * If Privoxy didn't recalculate the Content-Lenght,
2237 * byte_count is still correct.
2239 csp->content_length = byte_count;
2242 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2243 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2244 && (csp->expected_content_length != byte_count))
2246 log_error(LOG_LEVEL_CONNECT,
2247 "Received %llu bytes while expecting %llu.",
2248 byte_count, csp->expected_content_length);
2249 mark_server_socket_tainted(csp);
2253 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2254 csp->ip_addr_str, http->ocmd, csp->content_length);
2258 /*********************************************************************
2262 * Description : This is little more than chat. We only "serve" to
2263 * to close (or remember) any socket that chat may have
2267 * 1 : csp = Current client state (buffers, headers, etc...)
2271 *********************************************************************/
2273 void serve(struct client_state *csp)
2274 #else /* ifndef AMIGA */
2275 static void serve(struct client_state *csp)
2276 #endif /* def AMIGA */
2278 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2279 static int monitor_thread_running = 0;
2280 int continue_chatting = 0;
2285 continue_chatting = (csp->config->feature_flags
2286 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2287 && (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2288 && (csp->cfd != JB_INVALID_SOCKET)
2289 && (csp->sfd != JB_INVALID_SOCKET)
2290 && socket_is_still_usable(csp->sfd);
2292 if (continue_chatting)
2294 log_error(LOG_LEVEL_CONNECT,
2295 "Waiting for the next client request. "
2296 "Keeping the server socket %d to %s open.",
2297 csp->sfd, csp->server_connection.host);
2299 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2300 && data_is_available(csp->cfd, (int)csp->server_connection.keep_alive_timeout)
2301 && socket_is_still_usable(csp->cfd))
2303 log_error(LOG_LEVEL_CONNECT, "Client request arrived in "
2304 "time or the client closed the connection.");
2306 * Get the csp in a mostly vergin state again.
2307 * XXX: Should be done elsewhere.
2309 csp->content_type = 0;
2310 csp->content_length = 0;
2311 csp->expected_content_length = 0;
2312 list_remove_all(csp->headers);
2313 freez(csp->iob->buf);
2314 memset(csp->iob, 0, sizeof(csp->iob));
2315 freez(csp->error_message);
2316 free_http_request(csp->http);
2317 destroy_list(csp->headers);
2318 destroy_list(csp->tags);
2319 free_current_action(csp->action);
2320 if (NULL != csp->fwd)
2322 unload_forward_spec(csp->fwd);
2326 /* XXX: Store per-connection flags someplace else. */
2327 csp->flags = CSP_FLAG_ACTIVE | (csp->flags & CSP_FLAG_TOGGLED_ON);
2331 log_error(LOG_LEVEL_CONNECT,
2332 "No additional client request received in time.");
2333 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
2335 remember_connection(csp->sfd, csp->http,
2336 forward_url(csp, csp->http),
2337 csp->server_connection.keep_alive_timeout);
2338 csp->sfd = JB_INVALID_SOCKET;
2339 close_socket(csp->cfd);
2340 csp->cfd = JB_INVALID_SOCKET;
2341 privoxy_mutex_lock(&connection_reuse_mutex);
2342 if (!monitor_thread_running)
2344 monitor_thread_running = 1;
2345 privoxy_mutex_unlock(&connection_reuse_mutex);
2346 wait_for_alive_connections();
2347 privoxy_mutex_lock(&connection_reuse_mutex);
2348 monitor_thread_running = 0;
2350 privoxy_mutex_unlock(&connection_reuse_mutex);
2355 else if (csp->sfd != JB_INVALID_SOCKET)
2357 log_error(LOG_LEVEL_CONNECT,
2358 "The connection on server socket %d to %s isn't reusable. "
2359 "Closing.", csp->sfd, csp->server_connection.host);
2361 } while (continue_chatting);
2363 mark_connection_closed(&csp->server_connection);
2366 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2368 if (csp->sfd != JB_INVALID_SOCKET)
2370 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2371 forget_connection(csp->sfd);
2372 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2373 close_socket(csp->sfd);
2376 if (csp->cfd != JB_INVALID_SOCKET)
2378 close_socket(csp->cfd);
2381 csp->flags &= ~CSP_FLAG_ACTIVE;
2387 /*********************************************************************
2389 * Function : server_thread
2391 * Description : We only exist to call `serve' in a threaded environment.
2394 * 1 : data = Current client state (buffers, headers, etc...)
2396 * Returns : Always 0.
2398 *********************************************************************/
2399 static int32 server_thread(void *data)
2401 serve((struct client_state *) data);
2408 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2409 /*********************************************************************
2413 * Description : Print usage info & exit.
2415 * Parameters : Pointer to argv[0] for identifying ourselves
2419 *********************************************************************/
2420 static void usage(const char *myname)
2422 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
2426 #endif /* defined(unix) */
2429 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
2430 #endif /* defined(unix) */
2431 "[--version] [configfile]\n"
2432 "Aborting\n", myname);
2437 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
2440 #ifdef MUTEX_LOCKS_AVAILABLE
2441 /*********************************************************************
2443 * Function : privoxy_mutex_lock
2445 * Description : Locks a mutex.
2448 * 1 : mutex = The mutex to lock.
2450 * Returns : Void. May exit in case of errors.
2452 *********************************************************************/
2453 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
2455 #ifdef FEATURE_PTHREAD
2456 int err = pthread_mutex_lock(mutex);
2459 if (mutex != &log_mutex)
2461 log_error(LOG_LEVEL_FATAL,
2462 "Mutex locking failed: %s.\n", strerror(err));
2467 EnterCriticalSection(mutex);
2468 #endif /* def FEATURE_PTHREAD */
2472 /*********************************************************************
2474 * Function : privoxy_mutex_unlock
2476 * Description : Unlocks a mutex.
2479 * 1 : mutex = The mutex to unlock.
2481 * Returns : Void. May exit in case of errors.
2483 *********************************************************************/
2484 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
2486 #ifdef FEATURE_PTHREAD
2487 int err = pthread_mutex_unlock(mutex);
2490 if (mutex != &log_mutex)
2492 log_error(LOG_LEVEL_FATAL,
2493 "Mutex unlocking failed: %s.\n", strerror(err));
2498 LeaveCriticalSection(mutex);
2499 #endif /* def FEATURE_PTHREAD */
2503 /*********************************************************************
2505 * Function : privoxy_mutex_init
2507 * Description : Prepares a mutex.
2510 * 1 : mutex = The mutex to initialize.
2512 * Returns : Void. May exit in case of errors.
2514 *********************************************************************/
2515 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
2517 #ifdef FEATURE_PTHREAD
2518 int err = pthread_mutex_init(mutex, 0);
2521 printf("Fatal error. Mutex initialization failed: %s.\n",
2526 InitializeCriticalSection(mutex);
2527 #endif /* def FEATURE_PTHREAD */
2529 #endif /* def MUTEX_LOCKS_AVAILABLE */
2531 /*********************************************************************
2533 * Function : initialize_mutexes
2535 * Description : Prepares mutexes if mutex support is available.
2539 * Returns : Void, exits in case of errors.
2541 *********************************************************************/
2542 static void initialize_mutexes(void)
2544 #ifdef MUTEX_LOCKS_AVAILABLE
2546 * Prepare global mutex semaphores
2548 privoxy_mutex_init(&log_mutex);
2549 privoxy_mutex_init(&log_init_mutex);
2550 privoxy_mutex_init(&connection_reuse_mutex);
2553 * XXX: The assumptions below are a bit naive
2554 * and can cause locks that aren't necessary.
2556 * For example older FreeBSD versions (< 6.x?)
2557 * have no gethostbyname_r, but gethostbyname is
2560 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
2561 privoxy_mutex_init(&resolver_mutex);
2562 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
2564 * XXX: should we use a single mutex for
2565 * localtime() and gmtime() as well?
2567 #ifndef HAVE_GMTIME_R
2568 privoxy_mutex_init(&gmtime_mutex);
2569 #endif /* ndef HAVE_GMTIME_R */
2571 #ifndef HAVE_LOCALTIME_R
2572 privoxy_mutex_init(&localtime_mutex);
2573 #endif /* ndef HAVE_GMTIME_R */
2576 privoxy_mutex_init(&rand_mutex);
2577 #endif /* ndef HAVE_RANDOM */
2578 #endif /* def MUTEX_LOCKS_AVAILABLE */
2582 /*********************************************************************
2586 * Description : Load the config file and start the listen loop.
2587 * This function is a lot more *sane* with the `load_config'
2588 * and `listen_loop' functions; although it stills does
2589 * a *little* too much for my taste.
2592 * 1 : argc = Number of parameters (including $0).
2593 * 2 : argv = Array of (char *)'s to the parameters.
2595 * Returns : 1 if : can't open config file, unrecognized directive,
2596 * stats requested in multi-thread mode, can't open the
2597 * log file, can't open the jar file, listen port is invalid,
2598 * any load fails, and can't bind port.
2600 * Else main never returns, the process must be signaled
2601 * to terminate execution. Or, on Windows, use the
2602 * "File", "Exit" menu option.
2604 *********************************************************************/
2606 int real_main(int argc, const char *argv[])
2608 int main(int argc, const char *argv[])
2612 unsigned int random_seed;
2614 struct passwd *pw = NULL;
2615 struct group *grp = NULL;
2618 char *pre_chroot_nslookup_to_load_resolver = NULL;
2625 #if !defined(_WIN32)
2632 /* Prepare mutexes if supported and necessary. */
2633 initialize_mutexes();
2635 /* Enable logging until further notice. */
2639 * Parse the command line arguments
2641 * XXX: simply printing usage information in case of
2642 * invalid arguments isn't particularly user friendly.
2644 while (++argc_pos < argc)
2647 /* Check to see if the service must be installed or uninstalled */
2648 if (strncmp(argv[argc_pos], "--install", 9) == 0)
2650 const char *pName = argv[argc_pos] + 9;
2653 exit( (install_service(pName)) ? 0 : 1 );
2655 else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
2657 const char *pName = argv[argc_pos] + 11;
2660 exit((uninstall_service(pName)) ? 0 : 1);
2662 else if (strcmp(argv[argc_pos], "--service" ) == 0)
2664 bRunAsService = TRUE;
2665 w32_set_service_cwd();
2666 atexit(w32_service_exit_notify);
2669 #endif /* defined(_WIN32) */
2672 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2674 if (strcmp(argv[argc_pos], "--help") == 0)
2679 else if(strcmp(argv[argc_pos], "--version") == 0)
2681 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2687 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
2689 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
2693 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
2695 if (++argc_pos == argc) usage(argv[0]);
2696 pidfile = strdup(argv[argc_pos]);
2699 else if (strcmp(argv[argc_pos], "--user" ) == 0)
2701 if (++argc_pos == argc) usage(argv[argc_pos]);
2703 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
2706 if (NULL == (grp = getgrnam(p)))
2708 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
2712 if (NULL == (pw = getpwnam(argv[argc_pos])))
2714 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
2717 if (p != NULL) *--p = '\0';
2720 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup" ) == 0)
2722 if (++argc_pos == argc) usage(argv[0]);
2723 pre_chroot_nslookup_to_load_resolver = strdup(argv[argc_pos]);
2726 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
2730 #endif /* defined(unix) */
2732 else if (argc_pos + 1 != argc)
2735 * This is neither the last command line
2736 * option, nor was it recognized before,
2737 * therefore it must be invalid.
2743 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
2745 configfile = argv[argc_pos];
2748 } /* -END- while (more arguments) */
2750 show_version(Argv[0]);
2753 if ( *configfile != '/' )
2755 char cwd[BUFFER_SIZE];
2757 size_t abs_file_size;
2759 /* make config-filename absolute here */
2760 if (NULL == getcwd(cwd, sizeof(cwd)))
2762 perror("failed to get current working directory");
2767 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
2768 basedir = strdup(cwd);
2770 if (NULL == basedir ||
2771 NULL == (abs_file = malloc(abs_file_size)))
2773 perror("malloc failed");
2776 strlcpy(abs_file, basedir, abs_file_size);
2777 strlcat(abs_file, "/", abs_file_size );
2778 strlcat(abs_file, configfile, abs_file_size);
2779 configfile = abs_file;
2781 #endif /* defined unix */
2785 clients->next = NULL;
2787 /* XXX: factor out initialising after the next stable release. */
2790 #elif defined(_WIN32)
2794 random_seed = (unsigned int)time(NULL);
2796 srandom(random_seed);
2799 #endif /* ifdef HAVE_RANDOM */
2802 * Unix signal handling
2804 * Catch the abort, interrupt and terminate signals for a graceful exit
2805 * Catch the hangup signal so the errlog can be reopened.
2806 * Ignore the broken pipe signals (FIXME: Why?)
2808 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
2811 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP, 0 };
2812 const int ignored_signals[] = { SIGPIPE, 0 };
2814 for (idx = 0; catched_signals[idx] != 0; idx++)
2816 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
2817 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
2819 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
2820 #endif /* ifdef sun */
2822 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
2826 for (idx = 0; ignored_signals[idx] != 0; idx++)
2828 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
2830 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
2835 #else /* ifdef _WIN32 */
2836 # ifdef _WIN_CONSOLE
2838 * We *are* in a windows console app.
2839 * Print a verbose messages about FAQ's and such
2841 printf("%s", win32_blurb);
2842 # endif /* def _WIN_CONSOLE */
2843 #endif /* def _WIN32 */
2846 /* Initialize the CGI subsystem */
2847 cgi_init_error_messages();
2850 * If runnig on unix and without the --nodaemon
2851 * option, become a daemon. I.e. fork, detach
2852 * from tty and get process group leadership
2865 if ( pid < 0 ) /* error */
2870 else if ( pid != 0 ) /* parent */
2875 * must check for errors
2876 * child died due to missing files aso
2879 wpid = waitpid( pid, &status, WNOHANG );
2888 /* Should be more portable, but not as well tested */
2893 #else /* ndef __FreeBSD__ */
2895 #endif /* ndef __FreeBSD__ */
2896 fd = open("/dev/tty", O_RDONLY);
2899 /* no error check here */
2900 ioctl( fd, TIOCNOTTY,0 );
2905 * stderr (fd 2) will be closed later on,
2906 * when the config file has been parsed.
2913 } /* -END- if (!no_daemon) */
2916 * As soon as we have written the PID file, we can switch
2917 * to the user and group ID indicated by the --user option
2923 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
2925 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
2929 if (setgroups(1, &grp->gr_gid))
2931 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
2934 else if (initgroups(pw->pw_name, pw->pw_gid))
2936 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
2942 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
2944 /* Read the time zone file from /etc before doing chroot. */
2946 if (NULL != pre_chroot_nslookup_to_load_resolver
2947 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
2949 /* Initialize resolver library. */
2950 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
2952 if (chroot(pw->pw_dir) < 0)
2954 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
2958 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
2961 if (setuid(pw->pw_uid))
2963 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
2967 char putenv_dummy[64];
2969 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
2970 if (putenv(putenv_dummy) != 0)
2972 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
2975 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
2976 if (putenv(putenv_dummy) != 0)
2978 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
2984 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
2987 #endif /* defined unix */
2990 /* This will be FALSE unless the command line specified --service
2994 /* Yup, so now we must attempt to establish a connection
2995 * with the service dispatcher. This will only work if this
2996 * process was launched by the service control manager to
2997 * actually run as a service. If this isn't the case, i've
2998 * known it take around 30 seconds or so for the call to return.
3001 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3002 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3004 /* Service has run, and at this point is now being stopped, so just return */
3009 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3011 /* An error occurred. Usually it's because --service was wrongly specified
3012 * and we were unable to connect to the Service Control Dispatcher because
3013 * it wasn't expecting us and is therefore not listening.
3015 * For now, just continue below to call the listen_loop function.
3018 #endif /* def _WIN32 */
3028 /*********************************************************************
3030 * Function : bind_port_helper
3032 * Description : Bind the listen port. Handles logging, and aborts
3036 * 1 : config = Privoxy configuration. Specifies port
3039 * Returns : Port that was opened.
3041 *********************************************************************/
3042 static jb_socket bind_port_helper(struct configuration_spec * config)
3047 if (config->haddr == NULL)
3049 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3054 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3055 config->hport, config->haddr);
3058 result = bind_port(config->haddr, config->hport, &bfd);
3065 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
3066 "There may be another Privoxy or some other "
3067 "proxy running on port %d",
3068 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
3069 config->hport, config->hport);
3072 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
3073 "The hostname is not resolvable",
3074 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3077 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
3078 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3081 /* shouldn't get here */
3082 return JB_INVALID_SOCKET;
3085 config->need_bind = 0;
3092 /* Without this simple workaround we get this compiler warning from _beginthread
3093 * warning C4028: formal parameter 1 different from declaration
3095 void w32_service_listen_loop(void *p)
3099 #endif /* def _WIN32 */
3102 /*********************************************************************
3104 * Function : listen_loop
3106 * Description : bind the listen port and enter a "FOREVER" listening loop.
3112 *********************************************************************/
3113 static void listen_loop(void)
3115 struct client_state *csp = NULL;
3117 struct configuration_spec *config;
3118 unsigned int active_threads = 0;
3120 config = load_config();
3122 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3124 * XXX: Should be relocated once it no
3125 * longer needs to emit log messages.
3127 initialize_reusable_connections();
3128 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3130 bfd = bind_port_helper(config);
3132 #ifdef FEATURE_GRACEFUL_TERMINATION
3133 while (!g_terminate)
3138 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3139 while (waitpid(-1, NULL, WNOHANG) > 0)
3141 /* zombie children */
3143 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3146 * Free data that was used by died threads
3148 active_threads = sweep();
3152 * Re-open the errlog after HUP signal
3154 if (received_hup_signal)
3156 if (NULL != config->logfile)
3158 init_error_log(Argv[0], config->logfile);
3160 received_hup_signal = 0;
3164 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
3166 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
3170 csp->flags |= CSP_FLAG_ACTIVE;
3171 csp->sfd = JB_INVALID_SOCKET;
3173 csp->config = config = load_config();
3175 if ( config->need_bind )
3178 * Since we were listening to the "old port", we will not see
3179 * a "listen" param change until the next request. So, at
3180 * least 1 more request must be made for us to find the new
3181 * setting. I am simply closing the old socket and binding the
3184 * Which-ever is correct, we will serve 1 more page via the
3185 * old settings. This should probably be a "show-proxy-args"
3186 * request. This should not be a so common of an operation
3187 * that this will hurt people's feelings.
3192 bfd = bind_port_helper(config);
3195 log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
3197 if (!accept_connection(csp, bfd))
3199 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3212 log_error(LOG_LEVEL_CONNECT, "accepted connection from %s", csp->ip_addr_str);
3215 #ifdef FEATURE_TOGGLE
3216 if (global_toggle_state)
3217 #endif /* def FEATURE_TOGGLE */
3219 csp->flags |= CSP_FLAG_TOGGLED_ON;
3222 if (run_loader(csp))
3224 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3225 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3229 if (block_acl(NULL,csp))
3231 log_error(LOG_LEVEL_CONNECT, "Connection from %s dropped due to ACL", csp->ip_addr_str);
3232 close_socket(csp->cfd);
3233 freez(csp->ip_addr_str);
3237 #endif /* def FEATURE_ACL */
3239 if ((0 != config->max_client_connections)
3240 && (active_threads >= config->max_client_connections))
3242 log_error(LOG_LEVEL_CONNECT,
3243 "Rejecting connection from %s. Maximum number of connections reached.",
3245 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3246 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3247 close_socket(csp->cfd);
3248 freez(csp->ip_addr_str);
3253 /* add it to the list of clients */
3254 csp->next = clients->next;
3255 clients->next = csp;
3257 if (config->multi_threaded)
3261 /* this is a switch () statment in the C preprocessor - ugh */
3262 #undef SELECTED_ONE_OPTION
3264 /* Use Pthreads in preference to native code */
3265 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
3266 #define SELECTED_ONE_OPTION
3268 pthread_t the_thread;
3269 pthread_attr_t attrs;
3271 pthread_attr_init(&attrs);
3272 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
3273 errno = pthread_create(&the_thread, &attrs,
3274 (void * (*)(void *))serve, csp);
3275 child_id = errno ? -1 : 0;
3276 pthread_attr_destroy(&attrs);
3280 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
3281 #define SELECTED_ONE_OPTION
3282 child_id = _beginthread(
3283 (void (*)(void *))serve,
3288 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
3289 #define SELECTED_ONE_OPTION
3290 child_id = _beginthread(
3291 (void(* _Optlink)(void*))serve,
3297 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
3298 #define SELECTED_ONE_OPTION
3300 thread_id tid = spawn_thread
3301 (server_thread, "server", B_NORMAL_PRIORITY, csp);
3303 if ((tid >= 0) && (resume_thread(tid) == B_OK))
3305 child_id = (int) tid;
3314 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
3315 #define SELECTED_ONE_OPTION
3316 csp->cfd = ReleaseSocket(csp->cfd, -1);
3319 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3320 NP_Output, Output(),
3321 NP_CloseOutput, FALSE,
3322 NP_Name, (ULONG)"privoxy child",
3326 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3327 NP_Output, Output(),
3328 NP_CloseOutput, FALSE,
3329 NP_Name, (ULONG)"privoxy child",
3330 NP_StackSize, 200*1024,
3336 ((struct Task *)child_id)->tc_UserData = csp;
3337 Signal((struct Task *)child_id, SIGF_SINGLE);
3342 #if !defined(SELECTED_ONE_OPTION)
3345 /* This block is only needed when using fork().
3346 * When using threads, the server thread was
3347 * created and run by the call to _beginthread().
3349 if (child_id == 0) /* child */
3352 #ifdef FEATURE_TOGGLE
3353 int inherited_toggle_state = global_toggle_state;
3354 #endif /* def FEATURE_TOGGLE */
3359 * If we've been toggled or we've blocked the request, tell Mom
3362 #ifdef FEATURE_TOGGLE
3363 if (inherited_toggle_state != global_toggle_state)
3365 rc |= RC_FLAG_TOGGLED;
3367 #endif /* def FEATURE_TOGGLE */
3369 #ifdef FEATURE_STATISTICS
3370 if (csp->flags & CSP_FLAG_REJECTED)
3372 rc |= RC_FLAG_BLOCKED;
3374 #endif /* ndef FEATURE_STATISTICS */
3378 else if (child_id > 0) /* parent */
3380 /* in a fork()'d environment, the parent's
3381 * copy of the client socket and the CSP
3385 #if !defined(_WIN32) && !defined(__CYGWIN__)
3387 wait( &child_status );
3390 * Evaluate child's return code: If the child has
3391 * - been toggled, toggle ourselves
3392 * - blocked its request, bump up the stats counter
3395 #ifdef FEATURE_TOGGLE
3396 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
3398 global_toggle_state = !global_toggle_state;
3400 #endif /* def FEATURE_TOGGLE */
3402 #ifdef FEATURE_STATISTICS
3404 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
3408 #endif /* def FEATURE_STATISTICS */
3410 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
3411 close_socket(csp->cfd);
3412 csp->flags &= ~CSP_FLAG_ACTIVE;
3416 #undef SELECTED_ONE_OPTION
3417 /* end of cpp switch () */
3422 * Spawning the child failed, assume it's because
3423 * there are too many children running already.
3424 * XXX: If you assume ...
3426 log_error(LOG_LEVEL_ERROR,
3427 "Unable to take any additional connections: %E");
3428 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3429 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3430 close_socket(csp->cfd);
3431 csp->flags &= ~CSP_FLAG_ACTIVE;
3440 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
3442 /* Clean up. Aim: free all memory (no leaks) */
3443 #ifdef FEATURE_GRACEFUL_TERMINATION
3445 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
3447 unload_current_config_file();
3448 unload_current_actions_file();
3449 unload_current_re_filterfile();
3450 #ifdef FEATURE_TRUST
3451 unload_current_trust_file();
3454 if (config->multi_threaded)
3461 } while ((clients->next != NULL) && (--i > 0));
3465 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
3476 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
3477 /* Cleanup - remove taskbar icon etc. */
3482 #endif /* FEATURE_GRACEFUL_TERMINATION */