1 const char jcc_rcs[] = "$Id: jcc.c,v 1.250 2009/05/16 13:27:20 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 /* XXX: should be a template */
282 static const char CONNECTION_TIMEOUT_RESPONSE[] =
283 "HTTP/1.0 504 Connection timeout\r\n"
284 "Proxy-Agent: Privoxy " VERSION "\r\n"
285 "Content-Type: text/plain\r\n"
286 "Connection: close\r\n\r\n"
287 "The connection timed out.\r\n";
289 /* A function to crunch a response */
290 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
292 /* Crunch function flags */
293 #define CF_NO_FLAGS 0
294 /* Cruncher applies to forced requests as well */
295 #define CF_IGNORE_FORCE 1
296 /* Crunched requests are counted for the block statistics */
297 #define CF_COUNT_AS_REJECT 2
299 /* A crunch function and its flags */
302 const crunch_func_ptr cruncher;
306 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
308 /* Complete list of cruncher functions */
309 static const struct cruncher crunchers_all[] = {
310 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
311 { block_url, CF_COUNT_AS_REJECT },
313 { trust_url, CF_COUNT_AS_REJECT },
314 #endif /* def FEATURE_TRUST */
315 { redirect_url, CF_NO_FLAGS },
316 { dispatch_cgi, CF_IGNORE_FORCE},
320 /* Light version, used after tags are applied */
321 static const struct cruncher crunchers_light[] = {
322 { block_url, CF_COUNT_AS_REJECT },
323 { redirect_url, CF_NO_FLAGS },
329 * XXX: Don't we really mean
335 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
336 /*********************************************************************
338 * Function : sig_handler
340 * Description : Signal handler for different signals.
341 * Exit gracefully on TERM and INT
342 * or set a flag that will cause the errlog
343 * to be reopened by the main thread on HUP.
346 * 1 : the_signal = the signal cause this function to call
350 *********************************************************************/
351 static void sig_handler(int the_signal)
357 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
369 received_hup_signal = 1;
375 * We shouldn't be here, unless we catch signals
376 * in main() that we can't handle here!
378 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
386 /*********************************************************************
388 * Function : client_protocol_is_unsupported
390 * Description : Checks if the client used a known unsupported
391 * protocol and deals with it by sending an error
395 * 1 : csp = Current client state (buffers, headers, etc...)
396 * 2 : req = the first request line send by the client
398 * Returns : TRUE if an error response has been generated, or
399 * FALSE if the request doesn't look invalid.
401 *********************************************************************/
402 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
405 * If it's a FTP or gopher request, we don't support it.
407 * These checks are better than nothing, but they might
408 * not work in all configurations and some clients might
409 * have problems digesting the answer.
411 * They should, however, never cause more problems than
412 * Privoxy's old behaviour (returning the misleading HTML
415 * "Could not resolve http://(ftp|gopher)://example.org").
417 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
419 const char *response = NULL;
420 const char *protocol = NULL;
422 if (!strncmpic(req, "GET ftp://", 10))
424 response = FTP_RESPONSE;
429 response = GOPHER_RESPONSE;
432 log_error(LOG_LEVEL_ERROR,
433 "%s tried to use Privoxy as %s proxy: %s",
434 csp->ip_addr_str, protocol, req);
435 log_error(LOG_LEVEL_CLF,
436 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
438 write_socket(csp->cfd, response, strlen(response));
447 /*********************************************************************
449 * Function : get_request_destination_elsewhere
451 * Description : If the client's request was redirected into
452 * Privoxy without the client's knowledge,
453 * the request line lacks the destination host.
455 * This function tries to get it elsewhere,
456 * provided accept-intercepted-requests is enabled.
458 * "Elsewhere" currently only means "Host: header",
459 * but in the future we may ask the redirecting
460 * packet filter to look the destination up.
462 * If the destination stays unknown, an error
463 * response is send to the client and headers
464 * are freed so that chat() can return directly.
467 * 1 : csp = Current client state (buffers, headers, etc...)
468 * 2 : headers = a header list
470 * Returns : JB_ERR_OK if the destination is now known, or
471 * JB_ERR_PARSE if it isn't.
473 *********************************************************************/
474 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
478 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
480 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
481 " Privoxy isn't configured to accept intercepted requests.",
482 csp->ip_addr_str, csp->http->cmd);
483 /* XXX: Use correct size */
484 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
485 csp->ip_addr_str, csp->http->cmd);
487 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
488 destroy_list(headers);
492 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
494 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
495 /* Split the domain we just got for pattern matching */
496 init_domain_components(csp->http);
503 /* We can't work without destination. Go spread the news.*/
505 req = list_to_text(headers);
507 /* XXX: Use correct size */
508 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
509 csp->ip_addr_str, csp->http->cmd);
510 log_error(LOG_LEVEL_ERROR,
511 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
512 csp->ip_addr_str, csp->http->cmd, req);
515 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
516 destroy_list(headers);
521 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
522 * to get the destination IP address, use it as host directly
523 * or do a reverse DNS lookup first.
528 /*********************************************************************
530 * Function : get_server_headers
532 * Description : Parses server headers in iob and fills them
533 * into csp->headers so that they can later be
537 * 1 : csp = Current client state (buffers, headers, etc...)
539 * Returns : JB_ERR_OK if everything went fine, or
540 * JB_ERR_PARSE if the headers were incomplete.
542 *********************************************************************/
543 static jb_err get_server_headers(struct client_state *csp)
545 int continue_hack_in_da_house = 0;
548 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
553 * continue hack in da house. Ignore the ending of
554 * this head and continue enlisting header lines.
555 * The reason is described below.
557 enlist(csp->headers, "");
558 continue_hack_in_da_house = 0;
561 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
564 * It's a bodyless continue response, don't
565 * stop header parsing after reaching its end.
567 * As a result Privoxy will concatenate the
568 * next response's head and parse and deliver
569 * the headers as if they belonged to one request.
571 * The client will separate them because of the
572 * empty line between them.
574 * XXX: What we're doing here is clearly against
575 * the intended purpose of the continue header,
576 * and under some conditions (HTTP/1.0 client request)
577 * it's a standard violation.
579 * Anyway, "sort of against the spec" is preferable
580 * to "always getting confused by Continue responses"
581 * (Privoxy's behaviour before this hack was added)
583 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
584 continue_hack_in_da_house = 1;
586 else if (*header == '\0')
589 * If the header is empty, but the Continue hack
590 * isn't active, we can assume that we reached the
591 * end of the buffer before we hit the end of the
594 * Inform the caller an let it decide how to handle it.
599 if (JB_ERR_MEMORY == enlist(csp->headers, header))
602 * XXX: Should we quit the request and return a
603 * out of memory error page instead?
605 log_error(LOG_LEVEL_ERROR,
606 "Out of memory while enlisting server headers. %s lost.",
616 /*********************************************************************
618 * Function : crunch_reason
620 * Description : Translates the crunch reason code into a string.
623 * 1 : rsp = a http_response
625 * Returns : A string with the crunch reason or an error description.
627 *********************************************************************/
628 static const char *crunch_reason(const struct http_response *rsp)
630 char * reason = NULL;
635 return "Internal error while searching for crunch reason";
640 case RSP_REASON_UNSUPPORTED:
641 reason = "Unsupported HTTP feature";
643 case RSP_REASON_BLOCKED:
646 case RSP_REASON_UNTRUSTED:
647 reason = "Untrusted";
649 case RSP_REASON_REDIRECTED:
650 reason = "Redirected";
652 case RSP_REASON_CGI_CALL:
655 case RSP_REASON_NO_SUCH_DOMAIN:
656 reason = "DNS failure";
658 case RSP_REASON_FORWARDING_FAILED:
659 reason = "Forwarding failed";
661 case RSP_REASON_CONNECT_FAILED:
662 reason = "Connection failure";
664 case RSP_REASON_OUT_OF_MEMORY:
665 reason = "Out of memory (may mask other reasons)";
668 reason = "No reason recorded";
676 /*********************************************************************
678 * Function : send_crunch_response
680 * Description : Delivers already prepared response for
681 * intercepted requests, logs the interception
682 * and frees the response.
685 * 1 : csp = Current client state (buffers, headers, etc...)
686 * 1 : rsp = Fully prepared response. Will be freed on exit.
690 *********************************************************************/
691 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
693 const struct http_request *http = csp->http;
697 assert(rsp->head != NULL);
702 * Not supposed to happen. If it does
703 * anyway, treat it as an unknown error.
705 cgi_error_unknown(csp, rsp, RSP_REASON_INTERNAL_ERROR);
706 /* return code doesn't matter */
711 /* If rsp is still NULL, we have serious internal problems. */
712 log_error(LOG_LEVEL_FATAL,
713 "NULL response in send_crunch_response and cgi_error_unknown failed as well.");
717 * Extract the status code from the actual head
718 * that was send to the client. It is the only
719 * way to get it right for all requests, including
720 * the fixed ones for out-of-memory problems.
722 * A head starts like this: 'HTTP/1.1 200...'
726 status_code[0] = rsp->head[9];
727 status_code[1] = rsp->head[10];
728 status_code[2] = rsp->head[11];
729 status_code[3] = '\0';
731 /* Write the answer to the client */
732 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
733 || write_socket(csp->cfd, rsp->body, rsp->content_length))
735 /* There is nothing we can do about it. */
736 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
739 /* Log that the request was crunched and why. */
740 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
741 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
742 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
744 /* Clean up and return */
745 if (cgi_error_memory() != rsp)
747 free_http_response(rsp);
754 /*********************************************************************
756 * Function : request_contains_null_bytes
758 * Description : Checks for NULL bytes in the request and sends
759 * an error message to the client if any were found.
761 * XXX: currently not used, see comment in chat().
764 * 1 : csp = Current client state (buffers, headers, etc...)
765 * 2 : buf = Data from the client's request to check.
766 * 3 : len = The data length.
768 * Returns : TRUE if the request contained one or more NULL bytes, or
771 *********************************************************************/
772 static int request_contains_null_bytes(const struct client_state *csp, char *buf, int len)
774 size_t c_len; /* Request lenght when treated as C string */
781 * Null byte(s) found. Log the request,
782 * return an error response and hang up.
784 size_t tmp_len = c_len;
789 * Replace NULL byte(s) with '°' characters
790 * so the request can be logged as string.
791 * XXX: Is there a better replacement character?
794 tmp_len += strlen(buf+tmp_len);
795 } while (tmp_len < len);
797 log_error(LOG_LEVEL_ERROR, "%s\'s request contains at least one NULL byte "
798 "(length=%d, strlen=%u).", csp->ip_addr_str, len, c_len);
799 log_error(LOG_LEVEL_HEADER,
800 "Offending request data with NULL bytes turned into \'°\' characters: %s", buf);
802 write_socket(csp->cfd, NULL_BYTE_RESPONSE, strlen(NULL_BYTE_RESPONSE));
804 /* XXX: Log correct size */
805 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
815 /*********************************************************************
817 * Function : crunch_response_triggered
819 * Description : Checks if the request has to be crunched,
820 * and delivers the crunch response if necessary.
823 * 1 : csp = Current client state (buffers, headers, etc...)
824 * 2 : crunchers = list of cruncher functions to run
826 * Returns : TRUE if the request was answered with a crunch response
829 *********************************************************************/
830 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
832 struct http_response *rsp = NULL;
833 const struct cruncher *c;
836 * If CGI request crunching is disabled,
837 * check the CGI dispatcher out of order to
838 * prevent unintentional blocks or redirects.
840 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
841 && (NULL != (rsp = dispatch_cgi(csp))))
843 /* Deliver, log and free the interception response. */
844 send_crunch_response(csp, rsp);
848 for (c = crunchers; c->cruncher != NULL; c++)
851 * Check the cruncher if either Privoxy is toggled
852 * on and the request isn't forced, or if the cruncher
853 * applies to forced requests as well.
855 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
856 !(csp->flags & CSP_FLAG_FORCED)) ||
857 (c->flags & CF_IGNORE_FORCE))
859 rsp = c->cruncher(csp);
862 /* Deliver, log and free the interception response. */
863 send_crunch_response(csp, rsp);
864 #ifdef FEATURE_STATISTICS
865 if (c->flags & CF_COUNT_AS_REJECT)
867 csp->flags |= CSP_FLAG_REJECTED;
869 #endif /* def FEATURE_STATISTICS */
880 /*********************************************************************
882 * Function : build_request_line
884 * Description : Builds the HTTP request line.
886 * If a HTTP forwarder is used it expects the whole URL,
887 * web servers only get the path.
890 * 1 : csp = Current client state (buffers, headers, etc...)
891 * 2 : fwd = The forwarding spec used for the request
892 * XXX: Should use http->fwd instead.
893 * 3 : request_line = The old request line which will be replaced.
895 * Returns : Nothing. Terminates in case of memory problems.
897 *********************************************************************/
898 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
900 struct http_request *http = csp->http;
902 assert(http->ssl == 0);
905 * Downgrade http version from 1.1 to 1.0
906 * if +downgrade action applies.
908 if ( (csp->action->flags & ACTION_DOWNGRADE)
909 && (!strcmpic(http->ver, "HTTP/1.1")))
912 http->ver = strdup("HTTP/1.0");
914 if (http->ver == NULL)
916 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
921 * Rebuild the request line.
923 freez(*request_line);
924 *request_line = strdup(http->gpc);
925 string_append(request_line, " ");
927 if (fwd->forward_host)
929 string_append(request_line, http->url);
933 string_append(request_line, http->path);
935 string_append(request_line, " ");
936 string_append(request_line, http->ver);
938 if (*request_line == NULL)
940 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
942 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
946 /*********************************************************************
948 * Function : change_request_destination
950 * Description : Parse a (rewritten) request line and regenerate
951 * the http request data.
954 * 1 : csp = Current client state (buffers, headers, etc...)
956 * Returns : Forwards the parse_http_request() return code.
957 * Terminates in case of memory problems.
959 *********************************************************************/
960 static jb_err change_request_destination(struct client_state *csp)
962 struct http_request *http = csp->http;
965 log_error(LOG_LEVEL_INFO, "Rewrite detected: %s", csp->headers->first->str);
966 free_http_request(http);
967 err = parse_http_request(csp->headers->first->str, http);
968 if (JB_ERR_OK != err)
970 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
971 jb_err_to_string(err));
975 /* XXX: ocmd is a misleading name */
976 http->ocmd = strdup(http->cmd);
977 if (http->ocmd == NULL)
979 log_error(LOG_LEVEL_FATAL,
980 "Out of memory copying rewritten HTTP request line");
988 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
989 /*********************************************************************
991 * Function : server_response_is_complete
993 * Description : Determines whether we should stop reading
994 * from the server socket.
997 * 1 : csp = Current client state (buffers, headers, etc...)
998 * 2 : content_length = Length of content received so far.
1000 * Returns : TRUE if the response is complete,
1003 *********************************************************************/
1004 static int server_response_is_complete(struct client_state *csp,
1005 unsigned long long content_length)
1007 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1009 if (!strcmpic(csp->http->gpc, "HEAD"))
1012 * "HEAD" implies no body, we are thus expecting
1013 * no content. XXX: incomplete "list" of methods?
1015 csp->expected_content_length = 0;
1016 content_length_known = TRUE;
1019 if (csp->http->status == 304)
1022 * Expect no body. XXX: incomplete "list" of status codes?
1024 csp->expected_content_length = 0;
1025 content_length_known = TRUE;
1028 return (content_length_known && ((0 == csp->expected_content_length)
1029 || (csp->expected_content_length <= content_length)));
1033 /*********************************************************************
1035 * Function : wait_for_alive_connections
1037 * Description : Waits for alive connections to timeout.
1043 *********************************************************************/
1044 static void wait_for_alive_connections(void)
1046 int connections_alive = close_unusable_connections();
1048 while (0 < connections_alive)
1050 log_error(LOG_LEVEL_CONNECT,
1051 "Waiting for %d connections to timeout.",
1054 connections_alive = close_unusable_connections();
1057 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1062 /*********************************************************************
1064 * Function : save_connection_destination
1066 * Description : Remembers a connection for reuse later on.
1069 * 1 : sfd = Open socket to remember.
1070 * 2 : http = The destination for the connection.
1071 * 3 : fwd = The forwarder settings used.
1072 * 3 : server_connection = storage.
1076 *********************************************************************/
1077 void save_connection_destination(jb_socket sfd,
1078 const struct http_request *http,
1079 const struct forward_spec *fwd,
1080 struct reusable_connection *server_connection)
1082 assert(sfd != JB_INVALID_SOCKET);
1083 assert(NULL != http->host);
1084 server_connection->host = strdup(http->host);
1085 if (NULL == server_connection->host)
1087 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
1089 server_connection->port = http->port;
1091 assert(NULL != fwd);
1092 assert(server_connection->gateway_host == NULL);
1093 assert(server_connection->gateway_port == 0);
1094 assert(server_connection->forwarder_type == 0);
1095 assert(server_connection->forward_host == NULL);
1096 assert(server_connection->forward_port == 0);
1098 server_connection->forwarder_type = fwd->type;
1099 if (NULL != fwd->gateway_host)
1101 server_connection->gateway_host = strdup(fwd->gateway_host);
1102 if (NULL == server_connection->gateway_host)
1104 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
1109 server_connection->gateway_host = NULL;
1111 server_connection->gateway_port = fwd->gateway_port;
1113 if (NULL != fwd->forward_host)
1115 server_connection->forward_host = strdup(fwd->forward_host);
1116 if (NULL == server_connection->forward_host)
1118 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
1123 server_connection->forward_host = NULL;
1125 server_connection->forward_port = fwd->forward_port;
1127 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1130 /*********************************************************************
1132 * Function : mark_server_socket_tainted
1134 * Description : Makes sure we don't reuse a server socket
1135 * (if we didn't read everything the server sent
1136 * us reusing the socket would lead to garbage).
1139 * 1 : csp = Current client state (buffers, headers, etc...)
1143 *********************************************************************/
1144 static void mark_server_socket_tainted(struct client_state *csp)
1146 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE))
1148 log_error(LOG_LEVEL_CONNECT, "Unsetting keep-alive flag.");
1149 csp->flags &= ~CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1153 /*********************************************************************
1155 * Function : get_request_line
1157 * Description : Read the client request line.
1160 * 1 : csp = Current client state (buffers, headers, etc...)
1162 * Returns : Pointer to request line or NULL in case of errors.
1164 *********************************************************************/
1165 static char *get_request_line(struct client_state *csp)
1167 char buf[BUFFER_SIZE];
1168 char *request_line = NULL;
1171 memset(buf, 0, sizeof(buf));
1175 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1177 log_error(LOG_LEVEL_ERROR,
1178 "Stopped waiting for the request line.");
1179 write_socket(csp->cfd, CONNECTION_TIMEOUT_RESPONSE,
1180 strlen(CONNECTION_TIMEOUT_RESPONSE));
1184 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1186 if (len <= 0) return NULL;
1189 * If there is no memory left for buffering the
1190 * request, there is nothing we can do but hang up
1192 if (add_to_iob(csp, buf, len))
1197 request_line = get_header(csp->iob);
1199 } while ((NULL != request_line) && ('\0' == *request_line));
1201 return request_line;
1206 /*********************************************************************
1208 * Function : receive_client_request
1210 * Description : Read the client's request (more precisely the
1211 * client headers) and answer it if necessary.
1213 * Note that since we're not using select() we could get
1214 * blocked here if a client connected, then didn't say
1218 * 1 : csp = Current client state (buffers, headers, etc...)
1220 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1222 *********************************************************************/
1223 static jb_err receive_client_request(struct client_state *csp)
1225 char buf[BUFFER_SIZE];
1228 struct http_request *http;
1232 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1233 struct list header_list;
1234 struct list *headers = &header_list;
1238 memset(buf, 0, sizeof(buf));
1240 req = get_request_line(csp);
1243 return JB_ERR_PARSE;
1245 assert(*req != '\0');
1247 if (client_protocol_is_unsupported(csp, req))
1249 return JB_ERR_PARSE;
1252 #ifdef FEATURE_FORCE_LOAD
1254 * If this request contains the FORCE_PREFIX and blocks
1255 * aren't enforced, get rid of it and set the force flag.
1257 if (strstr(req, FORCE_PREFIX))
1259 if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1261 log_error(LOG_LEVEL_FORCE,
1262 "Ignored force prefix in request: \"%s\".", req);
1266 strclean(req, FORCE_PREFIX);
1267 log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1268 csp->flags |= CSP_FLAG_FORCED;
1271 #endif /* def FEATURE_FORCE_LOAD */
1273 err = parse_http_request(req, http);
1275 if (JB_ERR_OK != err)
1277 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1278 /* XXX: Use correct size */
1279 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1280 log_error(LOG_LEVEL_ERROR,
1281 "Couldn't parse request line received from %s: %s",
1282 csp->ip_addr_str, jb_err_to_string(err));
1284 free_http_request(http);
1285 return JB_ERR_PARSE;
1288 /* grab the rest of the client's headers */
1292 p = get_header(csp->iob);
1296 /* There are no additional headers to read. */
1303 * We didn't receive a complete header
1304 * line yet, get the rest of it.
1306 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1308 log_error(LOG_LEVEL_ERROR,
1309 "Stopped grabbing the client headers.");
1310 return JB_ERR_PARSE;
1313 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1316 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1317 destroy_list(headers);
1318 return JB_ERR_PARSE;
1321 if (add_to_iob(csp, buf, len))
1324 * If there is no memory left for buffering the
1325 * request, there is nothing we can do but hang up
1327 destroy_list(headers);
1328 return JB_ERR_MEMORY;
1334 * We were able to read a complete
1335 * header and can finaly enlist it.
1342 if (http->host == NULL)
1345 * If we still don't know the request destination,
1346 * the request is invalid or the client uses
1347 * Privoxy without its knowledge.
1349 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1352 * Our attempts to get the request destination
1353 * elsewhere failed or Privoxy is configured
1354 * to only accept proxy requests.
1356 * An error response has already been send
1357 * and we're done here.
1359 return JB_ERR_PARSE;
1364 * Determine the actions for this URL
1366 #ifdef FEATURE_TOGGLE
1367 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1369 /* Most compatible set of actions (i.e. none) */
1370 init_current_action(csp->action);
1373 #endif /* ndef FEATURE_TOGGLE */
1375 get_url_actions(csp, http);
1379 * Save a copy of the original request for logging
1381 http->ocmd = strdup(http->cmd);
1382 if (http->ocmd == NULL)
1384 log_error(LOG_LEVEL_FATAL,
1385 "Out of memory copying HTTP request line");
1387 enlist(csp->headers, http->cmd);
1389 /* Append the previously read headers */
1390 list_append_list_unique(csp->headers, headers);
1391 destroy_list(headers);
1398 /*********************************************************************
1400 * Function : parse_client_request
1402 * Description : Parses the client's request and decides what to do
1405 * Note that since we're not using select() we could get
1406 * blocked here if a client connected, then didn't say
1410 * 1 : csp = Current client state (buffers, headers, etc...)
1412 * Returns : JB_ERR_OK or JB_ERR_PARSE
1414 *********************************************************************/
1415 static jb_err parse_client_request(struct client_state *csp)
1417 struct http_request *http = csp->http;
1420 err = sed(csp, FILTER_CLIENT_HEADERS);
1421 if (JB_ERR_OK != err)
1423 /* XXX: Should be handled in sed(). */
1424 assert(err == JB_ERR_PARSE);
1425 log_error(LOG_LEVEL_FATAL, "Failed to parse client headers.");
1427 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1429 /* Check request line for rewrites. */
1430 if ((NULL == csp->headers->first->str)
1431 || (strcmp(http->cmd, csp->headers->first->str) &&
1432 (JB_ERR_OK != change_request_destination(csp))))
1435 * A header filter broke the request line - bail out.
1437 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1438 /* XXX: Use correct size */
1439 log_error(LOG_LEVEL_CLF,
1440 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1441 log_error(LOG_LEVEL_ERROR,
1442 "Invalid request line after applying header filters.");
1443 free_http_request(http);
1445 return JB_ERR_PARSE;
1453 /*********************************************************************
1457 * Description : Once a connection to the client has been accepted,
1458 * this function is called (via serve()) to handle the
1459 * main business of the communication. When this
1460 * function returns, the caller must close the client
1463 * FIXME: chat is nearly thousand lines long.
1467 * 1 : csp = Current client state (buffers, headers, etc...)
1469 * Returns : Nothing.
1471 *********************************************************************/
1472 static void chat(struct client_state *csp)
1474 char buf[BUFFER_SIZE];
1481 int ms_iis5_hack = 0;
1482 unsigned long long byte_count = 0;
1483 int forwarded_connect_retries = 0;
1484 int max_forwarded_connect_retries = csp->config->forwarded_connect_retries;
1485 const struct forward_spec *fwd;
1486 struct http_request *http;
1487 long len = 0; /* for buffer sizes (and negative error codes) */
1489 /* Function that does the content filtering for the current request */
1490 filter_function_ptr content_filter = NULL;
1492 /* Skeleton for HTTP response, if we should intercept the request */
1493 struct http_response *rsp;
1494 struct timeval timeout;
1496 memset(buf, 0, sizeof(buf));
1500 if (receive_client_request(csp) != JB_ERR_OK)
1504 if (parse_client_request(csp) != JB_ERR_OK)
1509 /* decide how to route the HTTP request */
1510 fwd = forward_url(csp, http);
1513 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1514 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1519 * build the http request to send to the server
1520 * we have to do one of the following:
1522 * create = use the original HTTP request to create a new
1523 * HTTP request that has either the path component
1524 * without the http://domainspec (w/path) or the
1525 * full orininal URL (w/url)
1526 * Note that the path and/or the HTTP version may
1527 * have been altered by now.
1529 * connect = Open a socket to the host:port of the server
1530 * and short-circuit server and client socket.
1532 * pass = Pass the request unchanged if forwarding a CONNECT
1533 * request to a parent proxy. Note that we'll be sending
1534 * the CFAIL message ourselves if connecting to the parent
1535 * fails, but we won't send a CSUCCEED message if it works,
1536 * since that would result in a double message (ours and the
1537 * parent's). After sending the request to the parent, we simply
1540 * here's the matrix:
1543 * +--------+--------+
1545 * 0 | create | connect|
1547 * Forwarding +--------+--------+
1549 * 1 | create | pass |
1551 * +--------+--------+
1555 if (http->ssl && connect_port_is_forbidden(csp))
1557 const char *acceptable_connect_ports =
1558 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1559 assert(NULL != acceptable_connect_ports);
1560 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1561 "limit-connect{%s} doesn't allow CONNECT requests to port %d.",
1562 csp->ip_addr_str, acceptable_connect_ports, csp->http->port);
1563 csp->action->flags |= ACTION_BLOCK;
1569 freez(csp->headers->first->str);
1570 build_request_line(csp, fwd, &csp->headers->first->str);
1574 * We have a request. Check if one of the crunchers wants it.
1576 if (crunch_response_triggered(csp, crunchers_all))
1579 * Yes. The client got the crunch response
1580 * and we are done here after cleaning up.
1582 /* XXX: why list_remove_all()? */
1583 list_remove_all(csp->headers);
1588 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1590 if (fwd->forward_host)
1592 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1593 fwd->forward_host, fwd->forward_port, http->hostport);
1597 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1600 /* here we connect to the server, gateway, or the forwarder */
1602 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1603 if ((csp->sfd != JB_INVALID_SOCKET)
1604 && socket_is_still_usable(csp->sfd)
1605 && connection_destination_matches(&csp->server_connection, http, fwd))
1607 log_error(LOG_LEVEL_CONNECT,
1608 "Reusing server socket %u. Opened for %s.",
1609 csp->sfd, csp->server_connection.host);
1613 if (csp->sfd != JB_INVALID_SOCKET)
1615 log_error(LOG_LEVEL_CONNECT,
1616 "Closing server socket %u. Opened for %s.",
1617 csp->sfd, csp->server_connection.host);
1618 close_socket(csp->sfd);
1619 mark_connection_closed(&csp->server_connection);
1621 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1623 while ((csp->sfd = forwarded_connect(fwd, http, csp))
1624 && (errno == EINVAL)
1625 && (forwarded_connect_retries++ < max_forwarded_connect_retries))
1627 log_error(LOG_LEVEL_ERROR,
1628 "failed request #%u to connect to %s. Trying again.",
1629 forwarded_connect_retries, http->hostport);
1632 if (csp->sfd == JB_INVALID_SOCKET)
1634 if (fwd->type != SOCKS_NONE)
1637 rsp = error_response(csp, "forwarding-failed", errno);
1639 else if (errno == EINVAL)
1641 rsp = error_response(csp, "no-such-domain", errno);
1645 rsp = error_response(csp, "connect-failed", errno);
1646 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1650 /* Write the answer to the client */
1653 send_crunch_response(csp, rsp);
1658 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1659 save_connection_destination(csp->sfd, http, fwd, &csp->server_connection);
1660 csp->server_connection.keep_alive_timeout = (unsigned)csp->config->keep_alive_timeout;
1662 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1664 hdr = list_to_text(csp->headers);
1667 /* FIXME Should handle error properly */
1668 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1670 list_remove_all(csp->headers);
1672 if (fwd->forward_host || (http->ssl == 0))
1675 * Write the client's (modified) header to the server
1676 * (along with anything else that may be in the buffer)
1678 if (write_socket(csp->sfd, hdr, strlen(hdr))
1679 || (flush_socket(csp->sfd, csp->iob) < 0))
1681 log_error(LOG_LEVEL_CONNECT,
1682 "write header to: %s failed: %E", http->hostport);
1684 rsp = error_response(csp, "connect-failed", errno);
1687 send_crunch_response(csp, rsp);
1697 * We're running an SSL tunnel and we're not forwarding,
1698 * so just send the "connect succeeded" message to the
1699 * client, flush the rest, and get out of the way.
1701 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
1709 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
1711 /* we're finished with the client's header */
1714 maxfd = (csp->cfd > csp->sfd) ? csp->cfd : csp->sfd;
1716 /* pass data between the client and server
1717 * until one or the other shuts down the connection.
1726 * FD_ZERO here seems to point to an errant macro which crashes.
1727 * So do this by hand for now...
1729 memset(&rfds,0x00,sizeof(fd_set));
1733 FD_SET(csp->cfd, &rfds);
1734 FD_SET(csp->sfd, &rfds);
1736 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1737 if ((csp->flags & CSP_FLAG_CHUNKED)
1738 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
1739 && ((csp->iob->eod - csp->iob->cur) >= 5)
1740 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
1742 log_error(LOG_LEVEL_CONNECT,
1743 "Looks like we read the last chunk together with "
1744 "the server headers. We better stop reading.");
1745 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
1746 csp->expected_content_length = byte_count;
1747 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
1749 if (server_body && server_response_is_complete(csp, byte_count))
1751 log_error(LOG_LEVEL_CONNECT,
1752 "Done reading from server. Expected content length: %llu. "
1753 "Actual content length: %llu. Most recently received: %d.",
1754 csp->expected_content_length, byte_count, len);
1757 * XXX: should not jump around,
1758 * chat() is complicated enough already.
1762 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1764 timeout.tv_sec = csp->config->socket_timeout;
1765 timeout.tv_usec = 0;
1766 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
1770 log_error(LOG_LEVEL_ERROR,
1771 "Didn't receive data in time: %s", http->url);
1772 if ((byte_count == 0) && (http->ssl == 0))
1774 write_socket(csp->cfd, CONNECTION_TIMEOUT_RESPONSE,
1775 strlen(CONNECTION_TIMEOUT_RESPONSE));
1777 mark_server_socket_tainted(csp);
1782 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1783 mark_server_socket_tainted(csp);
1788 * This is the body of the browser's request,
1789 * just read and write it.
1791 * XXX: Make sure the client doesn't use pipelining
1792 * behind Privoxy's back.
1794 if (FD_ISSET(csp->cfd, &rfds))
1796 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1800 /* XXX: not sure if this is necessary. */
1801 mark_server_socket_tainted(csp);
1802 break; /* "game over, man" */
1805 if (write_socket(csp->sfd, buf, (size_t)len))
1807 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1808 mark_server_socket_tainted(csp);
1815 * The server wants to talk. It could be the header or the body.
1816 * If `hdr' is null, then it's the header otherwise it's the body.
1817 * FIXME: Does `hdr' really mean `host'? No.
1819 if (FD_ISSET(csp->sfd, &rfds))
1822 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1826 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1828 if (http->ssl && (fwd->forward_host == NULL))
1831 * Just hang up. We already confirmed the client's CONNECT
1832 * request with status code 200 and unencrypted content is
1833 * no longer welcome.
1835 log_error(LOG_LEVEL_ERROR,
1836 "CONNECT already confirmed. Unable to tell the client about the problem.");
1839 else if (byte_count)
1842 * Just hang up. We already transmitted the original headers
1843 * and parts of the original content and therefore missed the
1844 * chance to send an error message (without risking data corruption).
1846 * XXX: we could retry with a fancy range request here.
1848 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
1849 "Unable to tell the client about the problem.");
1850 mark_server_socket_tainted(csp);
1854 * XXX: Consider handling the cases above the same.
1856 mark_server_socket_tainted(csp);
1860 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1861 if (csp->flags & CSP_FLAG_CHUNKED)
1863 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
1865 /* XXX: this is a temporary hack */
1866 log_error(LOG_LEVEL_CONNECT,
1867 "Looks like we reached the end of the last chunk. "
1868 "We better stop reading.");
1869 csp->expected_content_length = byte_count + (unsigned long long)len;
1870 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
1874 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1877 * Add a trailing zero to let be able to use string operations.
1878 * XXX: do we still need this with filter_popups gone?
1883 * Normally, this would indicate that we've read
1884 * as much as the server has sent us and we can
1885 * close the client connection. However, Microsoft
1886 * in its wisdom has released IIS/5 with a bug that
1887 * prevents it from sending the trailing \r\n in
1888 * a 302 redirect header (and possibly other headers).
1889 * To work around this if we've haven't parsed
1890 * a full header we'll append a trailing \r\n
1891 * and see if this now generates a valid one.
1893 * This hack shouldn't have any impacts. If we've
1894 * already transmitted the header or if this is a
1895 * SSL connection, then we won't bother with this
1896 * hack. So we only work on partially received
1897 * headers. If we append a \r\n and this still
1898 * doesn't generate a valid header, then we won't
1899 * transmit anything to the client.
1904 if (server_body || http->ssl)
1907 * If we have been buffering up the document,
1908 * now is the time to apply content modification
1909 * and send the result to the client.
1913 p = execute_content_filter(csp, content_filter);
1915 * If the content filter fails, use the original
1916 * buffer and length.
1917 * (see p != NULL ? p : csp->iob->cur below)
1921 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
1924 if (JB_ERR_OK != update_server_headers(csp))
1926 log_error(LOG_LEVEL_FATAL,
1927 "Failed to update server headers. after filtering.");
1930 hdr = list_to_text(csp->headers);
1933 /* FIXME Should handle error properly */
1934 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1937 if (write_socket(csp->cfd, hdr, strlen(hdr))
1938 || write_socket(csp->cfd,
1939 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
1941 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1944 mark_server_socket_tainted(csp);
1952 break; /* "game over, man" */
1956 * This is NOT the body, so
1957 * Let's pretend the server just sent us a blank line.
1959 snprintf(buf, sizeof(buf), "\r\n");
1960 len = (int)strlen(buf);
1963 * Now, let the normal header parsing algorithm below do its
1964 * job. If it fails, we'll exit instead of continuing.
1971 * If this is an SSL connection or we're in the body
1972 * of the server document, just write it to the client,
1973 * unless we need to buffer the body for later content-filtering
1975 if (server_body || http->ssl)
1980 * If there is no memory left for buffering the content, or the buffer limit
1981 * has been reached, switch to non-filtering mode, i.e. make & write the
1982 * header, flush the iob and buf, and get out of the way.
1984 if (add_to_iob(csp, buf, len))
1989 log_error(LOG_LEVEL_INFO,
1990 "Flushing header and buffers. Stepping back from filtering.");
1992 hdr = list_to_text(csp->headers);
1996 * Memory is too tight to even generate the header.
1997 * Send our static "Out-of-memory" page.
1999 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2000 rsp = cgi_error_memory();
2001 send_crunch_response(csp, rsp);
2002 mark_server_socket_tainted(csp);
2005 hdrlen = strlen(hdr);
2007 if (write_socket(csp->cfd, hdr, hdrlen)
2008 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2009 || (write_socket(csp->cfd, buf, (size_t)len)))
2011 log_error(LOG_LEVEL_CONNECT,
2012 "Flush header and buffers to client failed: %E");
2014 mark_server_socket_tainted(csp);
2019 * Reset the byte_count to the amount of bytes
2020 * we just flushed. len will be added a few lines below,
2021 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2023 byte_count = (unsigned long long)flushed;
2025 content_filter = NULL;
2031 if (write_socket(csp->cfd, buf, (size_t)len))
2033 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2034 mark_server_socket_tainted(csp);
2038 byte_count += (unsigned long long)len;
2043 const char *header_start;
2045 * We're still looking for the end of the server's header.
2046 * Buffer up the data we just read. If that fails, there's
2047 * little we can do but send our static out-of-memory page.
2049 if (add_to_iob(csp, buf, len))
2051 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2052 rsp = cgi_error_memory();
2053 send_crunch_response(csp, rsp);
2054 mark_server_socket_tainted(csp);
2058 header_start = csp->iob->cur;
2060 /* Convert iob into something sed() can digest */
2061 if (JB_ERR_PARSE == get_server_headers(csp))
2066 * Well, we tried our MS IIS/5 hack and it didn't work.
2067 * The header is incomplete and there isn't anything
2068 * we can do about it.
2070 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2071 "Applying the MS IIS5 hack didn't help.");
2072 log_error(LOG_LEVEL_CLF,
2073 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2074 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2075 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2076 mark_server_socket_tainted(csp);
2082 * Since we have to wait for more from the server before
2083 * we can parse the headers we just continue here.
2085 long header_offset = csp->iob->cur - header_start;
2086 assert(csp->iob->cur >= header_start);
2087 byte_count += (unsigned long long)(len - header_offset);
2088 log_error(LOG_LEVEL_CONNECT, "Continuing buffering headers. "
2089 "byte_count: %llu. header_offset: %d. len: %d.",
2090 byte_count, header_offset, len);
2095 /* Did we actually get anything? */
2096 if (NULL == csp->headers->first)
2098 log_error(LOG_LEVEL_ERROR, "Empty server or forwarder response.");
2099 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2100 write_socket(csp->cfd, NO_SERVER_DATA_RESPONSE, strlen(NO_SERVER_DATA_RESPONSE));
2101 free_http_request(http);
2102 mark_server_socket_tainted(csp);
2106 assert(csp->headers->first->str);
2108 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2109 strncmpic(csp->headers->first->str, "ICY", 3))
2112 * It doesn't look like a HTTP (or Shoutcast) response:
2113 * tell the client and log the problem.
2115 if (strlen(csp->headers->first->str) > 30)
2117 csp->headers->first->str[30] = '\0';
2119 log_error(LOG_LEVEL_ERROR,
2120 "Invalid server or forwarder response. Starts with: %s",
2121 csp->headers->first->str);
2122 log_error(LOG_LEVEL_CLF,
2123 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2124 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2125 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2126 free_http_request(http);
2127 mark_server_socket_tainted(csp);
2132 * We have now received the entire server header,
2133 * filter it and send the result to the client
2135 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2137 log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2139 hdr = list_to_text(csp->headers);
2142 /* FIXME Should handle error properly */
2143 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2146 if (crunch_response_triggered(csp, crunchers_light))
2149 * One of the tags created by a server-header
2150 * tagger triggered a crunch. We already
2151 * delivered the crunch response to the client
2152 * and are done here after cleaning up.
2155 mark_server_socket_tainted(csp);
2158 /* Buffer and pcrs filter this if appropriate. */
2160 if (!http->ssl) /* We talk plaintext */
2162 content_filter = get_filter_function(csp);
2165 * Only write if we're not buffering for content modification
2167 if (!content_filter)
2170 * Write the server's (modified) header to
2171 * the client (along with anything else that
2172 * may be in the buffer)
2175 if (write_socket(csp->cfd, hdr, strlen(hdr))
2176 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2178 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2181 * The write failed, so don't bother mentioning it
2182 * to the client... it probably can't hear us anyway.
2185 mark_server_socket_tainted(csp);
2189 byte_count += (unsigned long long)len;
2194 * XXX: the header lenght should probably
2195 * be calculated by get_server_headers().
2197 long header_length = csp->iob->cur - header_start;
2198 assert(csp->iob->cur > header_start);
2199 byte_count += (unsigned long long)(len - header_length);
2202 /* we're finished with the server's header */
2208 * If this was a MS IIS/5 hack then it means the server
2209 * has already closed the connection. Nothing more to read.
2214 log_error(LOG_LEVEL_ERROR,
2215 "Closed server connection detected. "
2216 "Applying the MS IIS5 hack didn't help.");
2217 log_error(LOG_LEVEL_CLF,
2218 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2219 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2220 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2221 mark_server_socket_tainted(csp);
2227 mark_server_socket_tainted(csp);
2228 return; /* huh? we should never get here */
2231 if (csp->content_length == 0)
2234 * If Privoxy didn't recalculate the Content-Lenght,
2235 * byte_count is still correct.
2237 csp->content_length = byte_count;
2240 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2241 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2242 && (csp->expected_content_length != byte_count))
2244 log_error(LOG_LEVEL_CONNECT,
2245 "Received %llu bytes while expecting %llu.",
2246 byte_count, csp->expected_content_length);
2247 mark_server_socket_tainted(csp);
2251 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2252 csp->ip_addr_str, http->ocmd, csp->content_length);
2256 /*********************************************************************
2260 * Description : This is little more than chat. We only "serve" to
2261 * to close (or remember) any socket that chat may have
2265 * 1 : csp = Current client state (buffers, headers, etc...)
2269 *********************************************************************/
2271 void serve(struct client_state *csp)
2272 #else /* ifndef AMIGA */
2273 static void serve(struct client_state *csp)
2274 #endif /* def AMIGA */
2276 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2277 static int monitor_thread_running = 0;
2278 int continue_chatting = 0;
2283 continue_chatting = (csp->config->feature_flags
2284 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2285 && (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2286 && (csp->cfd != JB_INVALID_SOCKET)
2287 && (csp->sfd != JB_INVALID_SOCKET)
2288 && socket_is_still_usable(csp->sfd);
2290 if (continue_chatting)
2292 log_error(LOG_LEVEL_CONNECT,
2293 "Waiting for the next client request. "
2294 "Keeping the server socket %d to %s open.",
2295 csp->sfd, csp->server_connection.host);
2297 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2298 && data_is_available(csp->cfd, (int)csp->server_connection.keep_alive_timeout)
2299 && socket_is_still_usable(csp->cfd))
2301 log_error(LOG_LEVEL_CONNECT, "Client request arrived in "
2302 "time or the client closed the connection.");
2304 * Get the csp in a mostly vergin state again.
2305 * XXX: Should be done elsewhere.
2307 csp->content_type = 0;
2308 csp->content_length = 0;
2309 csp->expected_content_length = 0;
2310 list_remove_all(csp->headers);
2311 freez(csp->iob->buf);
2312 memset(csp->iob, 0, sizeof(csp->iob));
2313 freez(csp->error_message);
2314 free_http_request(csp->http);
2315 destroy_list(csp->headers);
2316 destroy_list(csp->tags);
2317 free_current_action(csp->action);
2318 if (NULL != csp->fwd)
2320 unload_forward_spec(csp->fwd);
2324 /* XXX: Store per-connection flags someplace else. */
2325 csp->flags = CSP_FLAG_ACTIVE | (csp->flags & CSP_FLAG_TOGGLED_ON);
2329 log_error(LOG_LEVEL_CONNECT,
2330 "No additional client request received in time.");
2331 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
2333 remember_connection(csp->sfd, csp->http,
2334 forward_url(csp, csp->http),
2335 csp->server_connection.keep_alive_timeout);
2336 csp->sfd = JB_INVALID_SOCKET;
2337 close_socket(csp->cfd);
2338 csp->cfd = JB_INVALID_SOCKET;
2339 privoxy_mutex_lock(&connection_reuse_mutex);
2340 if (!monitor_thread_running)
2342 monitor_thread_running = 1;
2343 privoxy_mutex_unlock(&connection_reuse_mutex);
2344 wait_for_alive_connections();
2345 privoxy_mutex_lock(&connection_reuse_mutex);
2346 monitor_thread_running = 0;
2348 privoxy_mutex_unlock(&connection_reuse_mutex);
2353 else if (csp->sfd != JB_INVALID_SOCKET)
2355 log_error(LOG_LEVEL_CONNECT,
2356 "The connection on server socket %d to %s isn't reusable. "
2357 "Closing.", csp->sfd, csp->server_connection.host);
2359 } while (continue_chatting);
2361 mark_connection_closed(&csp->server_connection);
2364 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2366 if (csp->sfd != JB_INVALID_SOCKET)
2368 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2369 forget_connection(csp->sfd);
2370 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2371 close_socket(csp->sfd);
2374 if (csp->cfd != JB_INVALID_SOCKET)
2376 close_socket(csp->cfd);
2379 csp->flags &= ~CSP_FLAG_ACTIVE;
2385 /*********************************************************************
2387 * Function : server_thread
2389 * Description : We only exist to call `serve' in a threaded environment.
2392 * 1 : data = Current client state (buffers, headers, etc...)
2394 * Returns : Always 0.
2396 *********************************************************************/
2397 static int32 server_thread(void *data)
2399 serve((struct client_state *) data);
2406 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2407 /*********************************************************************
2411 * Description : Print usage info & exit.
2413 * Parameters : Pointer to argv[0] for identifying ourselves
2417 *********************************************************************/
2418 static void usage(const char *myname)
2420 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
2424 #endif /* defined(unix) */
2427 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
2428 #endif /* defined(unix) */
2429 "[--version] [configfile]\n"
2430 "Aborting\n", myname);
2435 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
2438 #ifdef MUTEX_LOCKS_AVAILABLE
2439 /*********************************************************************
2441 * Function : privoxy_mutex_lock
2443 * Description : Locks a mutex.
2446 * 1 : mutex = The mutex to lock.
2448 * Returns : Void. May exit in case of errors.
2450 *********************************************************************/
2451 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
2453 #ifdef FEATURE_PTHREAD
2454 int err = pthread_mutex_lock(mutex);
2457 if (mutex != &log_mutex)
2459 log_error(LOG_LEVEL_FATAL,
2460 "Mutex locking failed: %s.\n", strerror(err));
2465 EnterCriticalSection(mutex);
2466 #endif /* def FEATURE_PTHREAD */
2470 /*********************************************************************
2472 * Function : privoxy_mutex_unlock
2474 * Description : Unlocks a mutex.
2477 * 1 : mutex = The mutex to unlock.
2479 * Returns : Void. May exit in case of errors.
2481 *********************************************************************/
2482 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
2484 #ifdef FEATURE_PTHREAD
2485 int err = pthread_mutex_unlock(mutex);
2488 if (mutex != &log_mutex)
2490 log_error(LOG_LEVEL_FATAL,
2491 "Mutex unlocking failed: %s.\n", strerror(err));
2496 LeaveCriticalSection(mutex);
2497 #endif /* def FEATURE_PTHREAD */
2501 /*********************************************************************
2503 * Function : privoxy_mutex_init
2505 * Description : Prepares a mutex.
2508 * 1 : mutex = The mutex to initialize.
2510 * Returns : Void. May exit in case of errors.
2512 *********************************************************************/
2513 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
2515 #ifdef FEATURE_PTHREAD
2516 int err = pthread_mutex_init(mutex, 0);
2519 printf("Fatal error. Mutex initialization failed: %s.\n",
2524 InitializeCriticalSection(mutex);
2525 #endif /* def FEATURE_PTHREAD */
2527 #endif /* def MUTEX_LOCKS_AVAILABLE */
2529 /*********************************************************************
2531 * Function : initialize_mutexes
2533 * Description : Prepares mutexes if mutex support is available.
2537 * Returns : Void, exits in case of errors.
2539 *********************************************************************/
2540 static void initialize_mutexes(void)
2542 #ifdef MUTEX_LOCKS_AVAILABLE
2544 * Prepare global mutex semaphores
2546 privoxy_mutex_init(&log_mutex);
2547 privoxy_mutex_init(&log_init_mutex);
2548 privoxy_mutex_init(&connection_reuse_mutex);
2551 * XXX: The assumptions below are a bit naive
2552 * and can cause locks that aren't necessary.
2554 * For example older FreeBSD versions (< 6.x?)
2555 * have no gethostbyname_r, but gethostbyname is
2558 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
2559 privoxy_mutex_init(&resolver_mutex);
2560 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
2562 * XXX: should we use a single mutex for
2563 * localtime() and gmtime() as well?
2565 #ifndef HAVE_GMTIME_R
2566 privoxy_mutex_init(&gmtime_mutex);
2567 #endif /* ndef HAVE_GMTIME_R */
2569 #ifndef HAVE_LOCALTIME_R
2570 privoxy_mutex_init(&localtime_mutex);
2571 #endif /* ndef HAVE_GMTIME_R */
2574 privoxy_mutex_init(&rand_mutex);
2575 #endif /* ndef HAVE_RANDOM */
2576 #endif /* def MUTEX_LOCKS_AVAILABLE */
2580 /*********************************************************************
2584 * Description : Load the config file and start the listen loop.
2585 * This function is a lot more *sane* with the `load_config'
2586 * and `listen_loop' functions; although it stills does
2587 * a *little* too much for my taste.
2590 * 1 : argc = Number of parameters (including $0).
2591 * 2 : argv = Array of (char *)'s to the parameters.
2593 * Returns : 1 if : can't open config file, unrecognized directive,
2594 * stats requested in multi-thread mode, can't open the
2595 * log file, can't open the jar file, listen port is invalid,
2596 * any load fails, and can't bind port.
2598 * Else main never returns, the process must be signaled
2599 * to terminate execution. Or, on Windows, use the
2600 * "File", "Exit" menu option.
2602 *********************************************************************/
2604 int real_main(int argc, const char *argv[])
2606 int main(int argc, const char *argv[])
2610 unsigned int random_seed;
2612 struct passwd *pw = NULL;
2613 struct group *grp = NULL;
2616 char *pre_chroot_nslookup_to_load_resolver = NULL;
2623 #if !defined(_WIN32)
2630 /* Prepare mutexes if supported and necessary. */
2631 initialize_mutexes();
2633 /* Enable logging until further notice. */
2637 * Parse the command line arguments
2639 * XXX: simply printing usage information in case of
2640 * invalid arguments isn't particularly user friendly.
2642 while (++argc_pos < argc)
2645 /* Check to see if the service must be installed or uninstalled */
2646 if (strncmp(argv[argc_pos], "--install", 9) == 0)
2648 const char *pName = argv[argc_pos] + 9;
2651 exit( (install_service(pName)) ? 0 : 1 );
2653 else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
2655 const char *pName = argv[argc_pos] + 11;
2658 exit((uninstall_service(pName)) ? 0 : 1);
2660 else if (strcmp(argv[argc_pos], "--service" ) == 0)
2662 bRunAsService = TRUE;
2663 w32_set_service_cwd();
2664 atexit(w32_service_exit_notify);
2667 #endif /* defined(_WIN32) */
2670 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2672 if (strcmp(argv[argc_pos], "--help") == 0)
2677 else if(strcmp(argv[argc_pos], "--version") == 0)
2679 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2685 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
2687 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
2691 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
2693 if (++argc_pos == argc) usage(argv[0]);
2694 pidfile = strdup(argv[argc_pos]);
2697 else if (strcmp(argv[argc_pos], "--user" ) == 0)
2699 if (++argc_pos == argc) usage(argv[argc_pos]);
2701 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
2704 if (NULL == (grp = getgrnam(p)))
2706 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
2710 if (NULL == (pw = getpwnam(argv[argc_pos])))
2712 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
2715 if (p != NULL) *--p = '\0';
2718 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup" ) == 0)
2720 if (++argc_pos == argc) usage(argv[0]);
2721 pre_chroot_nslookup_to_load_resolver = strdup(argv[argc_pos]);
2724 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
2728 #endif /* defined(unix) */
2730 else if (argc_pos + 1 != argc)
2733 * This is neither the last command line
2734 * option, nor was it recognized before,
2735 * therefore it must be invalid.
2741 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
2743 configfile = argv[argc_pos];
2746 } /* -END- while (more arguments) */
2748 show_version(Argv[0]);
2751 if ( *configfile != '/' )
2753 char cwd[BUFFER_SIZE];
2755 size_t abs_file_size;
2757 /* make config-filename absolute here */
2758 if (NULL == getcwd(cwd, sizeof(cwd)))
2760 perror("failed to get current working directory");
2765 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
2766 basedir = strdup(cwd);
2768 if (NULL == basedir ||
2769 NULL == (abs_file = malloc(abs_file_size)))
2771 perror("malloc failed");
2774 strlcpy(abs_file, basedir, abs_file_size);
2775 strlcat(abs_file, "/", abs_file_size );
2776 strlcat(abs_file, configfile, abs_file_size);
2777 configfile = abs_file;
2779 #endif /* defined unix */
2783 clients->next = NULL;
2785 /* XXX: factor out initialising after the next stable release. */
2788 #elif defined(_WIN32)
2792 random_seed = (unsigned int)time(NULL);
2794 srandom(random_seed);
2797 #endif /* ifdef HAVE_RANDOM */
2800 * Unix signal handling
2802 * Catch the abort, interrupt and terminate signals for a graceful exit
2803 * Catch the hangup signal so the errlog can be reopened.
2804 * Ignore the broken pipe signals (FIXME: Why?)
2806 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
2809 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP, 0 };
2810 const int ignored_signals[] = { SIGPIPE, 0 };
2812 for (idx = 0; catched_signals[idx] != 0; idx++)
2814 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
2815 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
2817 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
2818 #endif /* ifdef sun */
2820 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
2824 for (idx = 0; ignored_signals[idx] != 0; idx++)
2826 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
2828 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
2833 #else /* ifdef _WIN32 */
2834 # ifdef _WIN_CONSOLE
2836 * We *are* in a windows console app.
2837 * Print a verbose messages about FAQ's and such
2839 printf("%s", win32_blurb);
2840 # endif /* def _WIN_CONSOLE */
2841 #endif /* def _WIN32 */
2844 /* Initialize the CGI subsystem */
2845 cgi_init_error_messages();
2848 * If runnig on unix and without the --nodaemon
2849 * option, become a daemon. I.e. fork, detach
2850 * from tty and get process group leadership
2863 if ( pid < 0 ) /* error */
2868 else if ( pid != 0 ) /* parent */
2873 * must check for errors
2874 * child died due to missing files aso
2877 wpid = waitpid( pid, &status, WNOHANG );
2886 /* Should be more portable, but not as well tested */
2891 #else /* ndef __FreeBSD__ */
2893 #endif /* ndef __FreeBSD__ */
2894 fd = open("/dev/tty", O_RDONLY);
2897 /* no error check here */
2898 ioctl( fd, TIOCNOTTY,0 );
2903 * stderr (fd 2) will be closed later on,
2904 * when the config file has been parsed.
2911 } /* -END- if (!no_daemon) */
2914 * As soon as we have written the PID file, we can switch
2915 * to the user and group ID indicated by the --user option
2921 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
2923 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
2927 if (setgroups(1, &grp->gr_gid))
2929 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
2932 else if (initgroups(pw->pw_name, pw->pw_gid))
2934 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
2940 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
2942 /* Read the time zone file from /etc before doing chroot. */
2944 if (NULL != pre_chroot_nslookup_to_load_resolver
2945 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
2947 /* Initialize resolver library. */
2948 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
2950 if (chroot(pw->pw_dir) < 0)
2952 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
2956 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
2959 if (setuid(pw->pw_uid))
2961 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
2965 char putenv_dummy[64];
2967 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
2968 if (putenv(putenv_dummy) != 0)
2970 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
2973 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
2974 if (putenv(putenv_dummy) != 0)
2976 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
2982 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
2985 #endif /* defined unix */
2988 /* This will be FALSE unless the command line specified --service
2992 /* Yup, so now we must attempt to establish a connection
2993 * with the service dispatcher. This will only work if this
2994 * process was launched by the service control manager to
2995 * actually run as a service. If this isn't the case, i've
2996 * known it take around 30 seconds or so for the call to return.
2999 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3000 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3002 /* Service has run, and at this point is now being stopped, so just return */
3007 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3009 /* An error occurred. Usually it's because --service was wrongly specified
3010 * and we were unable to connect to the Service Control Dispatcher because
3011 * it wasn't expecting us and is therefore not listening.
3013 * For now, just continue below to call the listen_loop function.
3016 #endif /* def _WIN32 */
3026 /*********************************************************************
3028 * Function : bind_port_helper
3030 * Description : Bind the listen port. Handles logging, and aborts
3034 * 1 : config = Privoxy configuration. Specifies port
3037 * Returns : Port that was opened.
3039 *********************************************************************/
3040 static jb_socket bind_port_helper(struct configuration_spec * config)
3045 if (config->haddr == NULL)
3047 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3052 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3053 config->hport, config->haddr);
3056 result = bind_port(config->haddr, config->hport, &bfd);
3063 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
3064 "There may be another Privoxy or some other "
3065 "proxy running on port %d",
3066 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
3067 config->hport, config->hport);
3070 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
3071 "The hostname is not resolvable",
3072 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3075 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
3076 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3079 /* shouldn't get here */
3080 return JB_INVALID_SOCKET;
3083 config->need_bind = 0;
3090 /* Without this simple workaround we get this compiler warning from _beginthread
3091 * warning C4028: formal parameter 1 different from declaration
3093 void w32_service_listen_loop(void *p)
3097 #endif /* def _WIN32 */
3100 /*********************************************************************
3102 * Function : listen_loop
3104 * Description : bind the listen port and enter a "FOREVER" listening loop.
3110 *********************************************************************/
3111 static void listen_loop(void)
3113 struct client_state *csp = NULL;
3115 struct configuration_spec *config;
3116 unsigned int active_threads = 0;
3118 config = load_config();
3120 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3122 * XXX: Should be relocated once it no
3123 * longer needs to emit log messages.
3125 initialize_reusable_connections();
3126 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3128 bfd = bind_port_helper(config);
3130 #ifdef FEATURE_GRACEFUL_TERMINATION
3131 while (!g_terminate)
3136 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3137 while (waitpid(-1, NULL, WNOHANG) > 0)
3139 /* zombie children */
3141 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3144 * Free data that was used by died threads
3146 active_threads = sweep();
3150 * Re-open the errlog after HUP signal
3152 if (received_hup_signal)
3154 if (NULL != config->logfile)
3156 init_error_log(Argv[0], config->logfile);
3158 received_hup_signal = 0;
3162 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
3164 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
3168 csp->flags |= CSP_FLAG_ACTIVE;
3169 csp->sfd = JB_INVALID_SOCKET;
3171 csp->config = config = load_config();
3173 if ( config->need_bind )
3176 * Since we were listening to the "old port", we will not see
3177 * a "listen" param change until the next request. So, at
3178 * least 1 more request must be made for us to find the new
3179 * setting. I am simply closing the old socket and binding the
3182 * Which-ever is correct, we will serve 1 more page via the
3183 * old settings. This should probably be a "show-proxy-args"
3184 * request. This should not be a so common of an operation
3185 * that this will hurt people's feelings.
3190 bfd = bind_port_helper(config);
3193 log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
3195 if (!accept_connection(csp, bfd))
3197 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3210 log_error(LOG_LEVEL_CONNECT, "accepted connection from %s", csp->ip_addr_str);
3213 #ifdef FEATURE_TOGGLE
3214 if (global_toggle_state)
3215 #endif /* def FEATURE_TOGGLE */
3217 csp->flags |= CSP_FLAG_TOGGLED_ON;
3220 if (run_loader(csp))
3222 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3223 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3227 if (block_acl(NULL,csp))
3229 log_error(LOG_LEVEL_CONNECT, "Connection from %s dropped due to ACL", csp->ip_addr_str);
3230 close_socket(csp->cfd);
3231 freez(csp->ip_addr_str);
3235 #endif /* def FEATURE_ACL */
3237 if ((0 != config->max_client_connections)
3238 && (active_threads >= config->max_client_connections))
3240 log_error(LOG_LEVEL_CONNECT,
3241 "Rejecting connection from %s. Maximum number of connections reached.",
3243 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3244 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3245 close_socket(csp->cfd);
3246 freez(csp->ip_addr_str);
3251 /* add it to the list of clients */
3252 csp->next = clients->next;
3253 clients->next = csp;
3255 if (config->multi_threaded)
3259 /* this is a switch () statment in the C preprocessor - ugh */
3260 #undef SELECTED_ONE_OPTION
3262 /* Use Pthreads in preference to native code */
3263 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
3264 #define SELECTED_ONE_OPTION
3266 pthread_t the_thread;
3267 pthread_attr_t attrs;
3269 pthread_attr_init(&attrs);
3270 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
3271 errno = pthread_create(&the_thread, &attrs,
3272 (void * (*)(void *))serve, csp);
3273 child_id = errno ? -1 : 0;
3274 pthread_attr_destroy(&attrs);
3278 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
3279 #define SELECTED_ONE_OPTION
3280 child_id = _beginthread(
3281 (void (*)(void *))serve,
3286 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
3287 #define SELECTED_ONE_OPTION
3288 child_id = _beginthread(
3289 (void(* _Optlink)(void*))serve,
3295 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
3296 #define SELECTED_ONE_OPTION
3298 thread_id tid = spawn_thread
3299 (server_thread, "server", B_NORMAL_PRIORITY, csp);
3301 if ((tid >= 0) && (resume_thread(tid) == B_OK))
3303 child_id = (int) tid;
3312 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
3313 #define SELECTED_ONE_OPTION
3314 csp->cfd = ReleaseSocket(csp->cfd, -1);
3317 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3318 NP_Output, Output(),
3319 NP_CloseOutput, FALSE,
3320 NP_Name, (ULONG)"privoxy child",
3324 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3325 NP_Output, Output(),
3326 NP_CloseOutput, FALSE,
3327 NP_Name, (ULONG)"privoxy child",
3328 NP_StackSize, 200*1024,
3334 ((struct Task *)child_id)->tc_UserData = csp;
3335 Signal((struct Task *)child_id, SIGF_SINGLE);
3340 #if !defined(SELECTED_ONE_OPTION)
3343 /* This block is only needed when using fork().
3344 * When using threads, the server thread was
3345 * created and run by the call to _beginthread().
3347 if (child_id == 0) /* child */
3350 #ifdef FEATURE_TOGGLE
3351 int inherited_toggle_state = global_toggle_state;
3352 #endif /* def FEATURE_TOGGLE */
3357 * If we've been toggled or we've blocked the request, tell Mom
3360 #ifdef FEATURE_TOGGLE
3361 if (inherited_toggle_state != global_toggle_state)
3363 rc |= RC_FLAG_TOGGLED;
3365 #endif /* def FEATURE_TOGGLE */
3367 #ifdef FEATURE_STATISTICS
3368 if (csp->flags & CSP_FLAG_REJECTED)
3370 rc |= RC_FLAG_BLOCKED;
3372 #endif /* ndef FEATURE_STATISTICS */
3376 else if (child_id > 0) /* parent */
3378 /* in a fork()'d environment, the parent's
3379 * copy of the client socket and the CSP
3383 #if !defined(_WIN32) && !defined(__CYGWIN__)
3385 wait( &child_status );
3388 * Evaluate child's return code: If the child has
3389 * - been toggled, toggle ourselves
3390 * - blocked its request, bump up the stats counter
3393 #ifdef FEATURE_TOGGLE
3394 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
3396 global_toggle_state = !global_toggle_state;
3398 #endif /* def FEATURE_TOGGLE */
3400 #ifdef FEATURE_STATISTICS
3402 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
3406 #endif /* def FEATURE_STATISTICS */
3408 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
3409 close_socket(csp->cfd);
3410 csp->flags &= ~CSP_FLAG_ACTIVE;
3414 #undef SELECTED_ONE_OPTION
3415 /* end of cpp switch () */
3420 * Spawning the child failed, assume it's because
3421 * there are too many children running already.
3422 * XXX: If you assume ...
3424 log_error(LOG_LEVEL_ERROR,
3425 "Unable to take any additional connections: %E");
3426 write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3427 strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3428 close_socket(csp->cfd);
3429 csp->flags &= ~CSP_FLAG_ACTIVE;
3438 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
3440 /* Clean up. Aim: free all memory (no leaks) */
3441 #ifdef FEATURE_GRACEFUL_TERMINATION
3443 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
3445 unload_current_config_file();
3446 unload_current_actions_file();
3447 unload_current_re_filterfile();
3448 #ifdef FEATURE_TRUST
3449 unload_current_trust_file();
3452 if (config->multi_threaded)
3459 } while ((clients->next != NULL) && (--i > 0));
3463 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
3474 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
3475 /* Cleanup - remove taskbar icon etc. */
3480 #endif /* FEATURE_GRACEFUL_TERMINATION */