1 const char jcc_rcs[] = "$Id: jcc.c,v 1.450 2016/12/24 16:01:32 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001-2016 the
10 * Privoxy team. http://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 *********************************************************************/
40 #include <sys/types.h>
49 # ifndef FEATURE_PTHREAD
53 # include <winsock2.h>
56 # endif /* ndef FEATURE_PTHREAD */
61 # endif /* ndef _WIN_CONSOLE */
62 # include "w32svrapi.h"
64 #else /* ifndef _WIN32 */
66 # if !defined (__OS2__)
68 # include <sys/wait.h>
69 # endif /* ndef __OS2__ */
70 # include <sys/time.h>
71 # include <sys/stat.h>
72 # include <sys/ioctl.h>
75 #include <sys/termios.h>
86 # include <socket.h> /* BeOS has select() for sockets only. */
87 # include <OS.h> /* declarations for threads and stuff. */
90 # if defined(__EMX__) || defined(__OS2__)
91 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
96 #define bzero(B,N) memset(B,0x00,n)
111 #include "miscutil.h"
113 #include "jbsockets.h"
118 #include "urlmatch.h"
119 #ifdef FEATURE_CLIENT_TAGS
120 #include "client-tags.h"
123 const char jcc_h_rcs[] = JCC_H_VERSION;
124 const char project_h_rcs[] = PROJECT_H_VERSION;
127 struct client_states clients[1];
128 struct file_list files[1];
130 #ifdef FEATURE_STATISTICS
131 int urls_read = 0; /* total nr of urls read inc rejected */
132 int urls_rejected = 0; /* total nr of urls rejected */
133 #endif /* def FEATURE_STATISTICS */
135 #ifdef FEATURE_GRACEFUL_TERMINATION
139 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
140 static void sig_handler(int the_signal);
142 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
143 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
144 static jb_err get_server_headers(struct client_state *csp);
145 static const char *crunch_reason(const struct http_response *rsp);
146 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
147 static char *get_request_line(struct client_state *csp);
148 static jb_err receive_client_request(struct client_state *csp);
149 static jb_err parse_client_request(struct client_state *csp);
150 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
151 static jb_err change_request_destination(struct client_state *csp);
152 static void chat(struct client_state *csp);
153 static void serve(struct client_state *csp);
154 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
155 static void usage(const char *myname);
157 static void initialize_mutexes(void);
158 static jb_socket bind_port_helper(const char *haddr, int hport);
159 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
160 static void close_ports_helper(jb_socket sockets[]);
161 static void listen_loop(void);
164 void serve(struct client_state *csp);
165 #else /* ifndef AMIGA */
166 static void serve(struct client_state *csp);
167 #endif /* def AMIGA */
170 static int32 server_thread(void *data);
171 #endif /* def __BEOS__ */
174 #define sleep(N) Sleep(((N) * 1000))
178 #define sleep(N) DosSleep(((N) * 100))
182 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
183 void show_fuzz_usage(const char *name);
186 #ifdef MUTEX_LOCKS_AVAILABLE
188 * XXX: Does the locking stuff really belong in this file?
190 privoxy_mutex_t log_mutex;
191 privoxy_mutex_t log_init_mutex;
192 privoxy_mutex_t connection_reuse_mutex;
194 #ifdef FEATURE_EXTERNAL_FILTERS
195 privoxy_mutex_t external_filter_mutex;
197 #ifdef FEATURE_CLIENT_TAGS
198 privoxy_mutex_t client_tags_mutex;
201 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
202 privoxy_mutex_t resolver_mutex;
203 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
205 #ifndef HAVE_GMTIME_R
206 privoxy_mutex_t gmtime_mutex;
207 #endif /* ndef HAVE_GMTIME_R */
209 #ifndef HAVE_LOCALTIME_R
210 privoxy_mutex_t localtime_mutex;
211 #endif /* ndef HAVE_GMTIME_R */
214 privoxy_mutex_t rand_mutex;
215 #endif /* ndef HAVE_RANDOM */
217 #endif /* def MUTEX_LOCKS_AVAILABLE */
220 const char *basedir = NULL;
221 const char *pidfile = NULL;
222 static int received_hup_signal = 0;
223 #endif /* defined unix */
225 /* HTTP snipplets. */
226 static const char CSUCCEED[] =
227 "HTTP/1.1 200 Connection established\r\n\r\n";
229 static const char CHEADER[] =
230 "HTTP/1.1 400 Invalid header received from client\r\n"
231 "Content-Type: text/plain\r\n"
232 "Connection: close\r\n\r\n"
233 "Invalid header received from client.\r\n";
235 static const char FTP_RESPONSE[] =
236 "HTTP/1.1 400 Invalid request received from client\r\n"
237 "Content-Type: text/plain\r\n"
238 "Connection: close\r\n\r\n"
239 "Invalid request. Privoxy doesn't support FTP.\r\n";
241 static const char GOPHER_RESPONSE[] =
242 "HTTP/1.1 400 Invalid request received from client\r\n"
243 "Content-Type: text/plain\r\n"
244 "Connection: close\r\n\r\n"
245 "Invalid request. Privoxy doesn't support gopher.\r\n";
247 /* XXX: should be a template */
248 static const char MISSING_DESTINATION_RESPONSE[] =
249 "HTTP/1.1 400 Bad request received from client\r\n"
250 "Content-Type: text/plain\r\n"
251 "Connection: close\r\n\r\n"
252 "Bad request. Privoxy was unable to extract the destination.\r\n";
254 /* XXX: should be a template */
255 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
256 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
257 "Content-Type: text/plain\r\n"
258 "Connection: close\r\n\r\n"
259 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
261 /* XXX: should be a template */
262 static const char MESSED_UP_REQUEST_RESPONSE[] =
263 "HTTP/1.1 400 Malformed request after rewriting\r\n"
264 "Content-Type: text/plain\r\n"
265 "Connection: close\r\n\r\n"
266 "Bad request. Messed up with header filters.\r\n";
268 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
269 "HTTP/1.1 503 Too many open connections\r\n"
270 "Content-Type: text/plain\r\n"
271 "Connection: close\r\n\r\n"
272 "Maximum number of open connections reached.\r\n";
274 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
275 "HTTP/1.1 504 Connection timeout\r\n"
276 "Content-Type: text/plain\r\n"
277 "Connection: close\r\n\r\n"
278 "The connection timed out because the client request didn't arrive in time.\r\n";
280 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
281 "HTTP/1.1 400 Failed reading client body\r\n"
282 "Content-Type: text/plain\r\n"
283 "Connection: close\r\n\r\n"
284 "Failed parsing or buffering the chunk-encoded client body.\r\n";
286 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
287 "HTTP/1.1 417 Expecting too much\r\n"
288 "Content-Type: text/plain\r\n"
289 "Connection: close\r\n\r\n"
290 "Privoxy detected an unsupported Expect header value.\r\n";
292 /* A function to crunch a response */
293 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
295 /* Crunch function flags */
296 #define CF_NO_FLAGS 0
297 /* Cruncher applies to forced requests as well */
298 #define CF_IGNORE_FORCE 1
299 /* Crunched requests are counted for the block statistics */
300 #define CF_COUNT_AS_REJECT 2
302 /* A crunch function and its flags */
305 const crunch_func_ptr cruncher;
309 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
311 /* Complete list of cruncher functions */
312 static const struct cruncher crunchers_all[] = {
313 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
314 { block_url, CF_COUNT_AS_REJECT },
316 { trust_url, CF_COUNT_AS_REJECT },
317 #endif /* def FEATURE_TRUST */
318 { redirect_url, CF_NO_FLAGS },
319 { dispatch_cgi, CF_IGNORE_FORCE},
323 /* Light version, used after tags are applied */
324 static const struct cruncher crunchers_light[] = {
325 { block_url, CF_COUNT_AS_REJECT },
326 { redirect_url, CF_NO_FLAGS },
332 * XXX: Don't we really mean
338 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
339 /*********************************************************************
341 * Function : sig_handler
343 * Description : Signal handler for different signals.
344 * Exit gracefully on TERM and INT
345 * or set a flag that will cause the errlog
346 * to be reopened by the main thread on HUP.
349 * 1 : the_signal = the signal cause this function to call
353 *********************************************************************/
354 static void sig_handler(int the_signal)
360 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
372 received_hup_signal = 1;
378 * We shouldn't be here, unless we catch signals
379 * in main() that we can't handle here!
381 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
389 /*********************************************************************
391 * Function : client_protocol_is_unsupported
393 * Description : Checks if the client used a known unsupported
394 * protocol and deals with it by sending an error
398 * 1 : csp = Current client state (buffers, headers, etc...)
399 * 2 : req = the first request line send by the client
401 * Returns : TRUE if an error response has been generated, or
402 * FALSE if the request doesn't look invalid.
404 *********************************************************************/
405 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
408 * If it's a FTP or gopher request, we don't support it.
410 * These checks are better than nothing, but they might
411 * not work in all configurations and some clients might
412 * have problems digesting the answer.
414 * They should, however, never cause more problems than
415 * Privoxy's old behaviour (returning the misleading HTML
418 * "Could not resolve http://(ftp|gopher)://example.org").
420 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
422 const char *response = NULL;
423 const char *protocol = NULL;
425 if (!strncmpic(req, "GET ftp://", 10))
427 response = FTP_RESPONSE;
432 response = GOPHER_RESPONSE;
435 log_error(LOG_LEVEL_ERROR,
436 "%s tried to use Privoxy as %s proxy: %s",
437 csp->ip_addr_str, protocol, req);
438 log_error(LOG_LEVEL_CLF,
439 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
441 write_socket(csp->cfd, response, strlen(response));
450 /*********************************************************************
452 * Function : client_has_unsupported_expectations
454 * Description : Checks if the client used an unsupported expectation
455 * in which case an error message is delivered.
458 * 1 : csp = Current client state (buffers, headers, etc...)
460 * Returns : TRUE if an error response has been generated, or
461 * FALSE if the request doesn't look invalid.
463 *********************************************************************/
464 static int client_has_unsupported_expectations(const struct client_state *csp)
466 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
468 log_error(LOG_LEVEL_ERROR,
469 "Rejecting request from client %s with unsupported Expect header value",
471 log_error(LOG_LEVEL_CLF,
472 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
473 write_socket(csp->cfd, UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
474 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE));
484 /*********************************************************************
486 * Function : get_request_destination_elsewhere
488 * Description : If the client's request was redirected into
489 * Privoxy without the client's knowledge,
490 * the request line lacks the destination host.
492 * This function tries to get it elsewhere,
493 * provided accept-intercepted-requests is enabled.
495 * "Elsewhere" currently only means "Host: header",
496 * but in the future we may ask the redirecting
497 * packet filter to look the destination up.
499 * If the destination stays unknown, an error
500 * response is send to the client and headers
501 * are freed so that chat() can return directly.
504 * 1 : csp = Current client state (buffers, headers, etc...)
505 * 2 : headers = a header list
507 * Returns : JB_ERR_OK if the destination is now known, or
508 * JB_ERR_PARSE if it isn't.
510 *********************************************************************/
511 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
515 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
517 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
518 " Privoxy isn't configured to accept intercepted requests.",
519 csp->ip_addr_str, csp->http->cmd);
520 /* XXX: Use correct size */
521 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
522 csp->ip_addr_str, csp->http->cmd);
524 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
525 destroy_list(headers);
529 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
531 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
532 /* Split the domain we just got for pattern matching */
533 init_domain_components(csp->http);
540 /* We can't work without destination. Go spread the news.*/
542 req = list_to_text(headers);
544 /* XXX: Use correct size */
545 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
546 csp->ip_addr_str, csp->http->cmd);
547 log_error(LOG_LEVEL_ERROR,
548 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
549 csp->ip_addr_str, csp->http->cmd, req);
552 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
553 destroy_list(headers);
558 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
559 * to get the destination IP address, use it as host directly
560 * or do a reverse DNS lookup first.
565 /*********************************************************************
567 * Function : get_server_headers
569 * Description : Parses server headers in iob and fills them
570 * into csp->headers so that they can later be
574 * 1 : csp = Current client state (buffers, headers, etc...)
576 * Returns : JB_ERR_OK if everything went fine, or
577 * JB_ERR_PARSE if the headers were incomplete.
579 *********************************************************************/
580 static jb_err get_server_headers(struct client_state *csp)
582 int continue_hack_in_da_house = 0;
585 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
590 * continue hack in da house. Ignore the ending of
591 * this head and continue enlisting header lines.
592 * The reason is described below.
594 enlist(csp->headers, "");
595 continue_hack_in_da_house = 0;
598 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
601 * It's a bodyless continue response, don't
602 * stop header parsing after reaching its end.
604 * As a result Privoxy will concatenate the
605 * next response's head and parse and deliver
606 * the headers as if they belonged to one request.
608 * The client will separate them because of the
609 * empty line between them.
611 * XXX: What we're doing here is clearly against
612 * the intended purpose of the continue header,
613 * and under some conditions (HTTP/1.0 client request)
614 * it's a standard violation.
616 * Anyway, "sort of against the spec" is preferable
617 * to "always getting confused by Continue responses"
618 * (Privoxy's behaviour before this hack was added)
620 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
621 continue_hack_in_da_house = 1;
623 else if (*header == '\0')
626 * If the header is empty, but the Continue hack
627 * isn't active, we can assume that we reached the
628 * end of the buffer before we hit the end of the
631 * Inform the caller an let it decide how to handle it.
636 if (JB_ERR_MEMORY == enlist(csp->headers, header))
639 * XXX: Should we quit the request and return a
640 * out of memory error page instead?
642 log_error(LOG_LEVEL_ERROR,
643 "Out of memory while enlisting server headers. %s lost.",
653 /*********************************************************************
655 * Function : crunch_reason
657 * Description : Translates the crunch reason code into a string.
660 * 1 : rsp = a http_response
662 * Returns : A string with the crunch reason or an error description.
664 *********************************************************************/
665 static const char *crunch_reason(const struct http_response *rsp)
667 char * reason = NULL;
672 return "Internal error while searching for crunch reason";
675 switch (rsp->crunch_reason)
678 reason = "Unsupported HTTP feature";
684 reason = "Untrusted";
687 reason = "Redirected";
693 reason = "DNS failure";
695 case FORWARDING_FAILED:
696 reason = "Forwarding failed";
699 reason = "Connection failure";
702 reason = "Out of memory (may mask other reasons)";
704 case CONNECTION_TIMEOUT:
705 reason = "Connection timeout";
708 reason = "No server data received";
711 reason = "No reason recorded";
719 /*********************************************************************
721 * Function : log_applied_actions
723 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
727 * 1 : actions = Current action spec to log
731 *********************************************************************/
732 static void log_applied_actions(const struct current_action_spec *actions)
735 * The conversion to text requires lots of memory allocations so
736 * we only do the conversion if the user is actually interested.
738 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
740 char *actions_as_text = actions_to_line_of_text(actions);
741 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
742 freez(actions_as_text);
747 /*********************************************************************
749 * Function : send_crunch_response
751 * Description : Delivers already prepared response for
752 * intercepted requests, logs the interception
753 * and frees the response.
756 * 1 : csp = Current client state (buffers, headers, etc...)
757 * 1 : rsp = Fully prepared response. Will be freed on exit.
761 *********************************************************************/
762 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
764 const struct http_request *http = csp->http;
768 assert(rsp->head != NULL);
772 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
776 * Extract the status code from the actual head
777 * that will be send to the client. It is the only
778 * way to get it right for all requests, including
779 * the fixed ones for out-of-memory problems.
781 * A head starts like this: 'HTTP/1.1 200...'
785 status_code[0] = rsp->head[9];
786 status_code[1] = rsp->head[10];
787 status_code[2] = rsp->head[11];
788 status_code[3] = '\0';
790 /* Log that the request was crunched and why. */
791 log_applied_actions(csp->action);
792 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
793 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
794 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
796 /* Write the answer to the client */
797 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
798 || write_socket(csp->cfd, rsp->body, rsp->content_length))
800 /* There is nothing we can do about it. */
801 log_error(LOG_LEVEL_ERROR,
802 "Couldn't deliver the error message through client socket %d: %E",
806 /* Clean up and return */
807 if (cgi_error_memory() != rsp)
809 free_http_response(rsp);
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);
845 csp->flags |= CSP_FLAG_CRUNCHED;
849 for (c = crunchers; c->cruncher != NULL; c++)
852 * Check the cruncher if either Privoxy is toggled
853 * on and the request isn't forced, or if the cruncher
854 * applies to forced requests as well.
856 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
857 !(csp->flags & CSP_FLAG_FORCED)) ||
858 (c->flags & CF_IGNORE_FORCE))
860 rsp = c->cruncher(csp);
863 /* Deliver, log and free the interception response. */
864 send_crunch_response(csp, rsp);
865 csp->flags |= CSP_FLAG_CRUNCHED;
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_or_die("HTTP/1.0");
918 * Rebuild the request line.
920 freez(*request_line);
921 *request_line = strdup(http->gpc);
922 string_append(request_line, " ");
924 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
926 string_append(request_line, http->url);
930 string_append(request_line, http->path);
932 string_append(request_line, " ");
933 string_append(request_line, http->ver);
935 if (*request_line == NULL)
937 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
939 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
943 /*********************************************************************
945 * Function : change_request_destination
947 * Description : Parse a (rewritten) request line and regenerate
948 * the http request data.
951 * 1 : csp = Current client state (buffers, headers, etc...)
953 * Returns : Forwards the parse_http_request() return code.
954 * Terminates in case of memory problems.
956 *********************************************************************/
957 static jb_err change_request_destination(struct client_state *csp)
959 struct http_request *http = csp->http;
962 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
963 csp->headers->first->str);
964 free_http_request(http);
965 err = parse_http_request(csp->headers->first->str, http);
966 if (JB_ERR_OK != err)
968 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
969 jb_err_to_string(err));
976 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
977 /*********************************************************************
979 * Function : server_response_is_complete
981 * Description : Determines whether we should stop reading
982 * from the server socket.
985 * 1 : csp = Current client state (buffers, headers, etc...)
986 * 2 : content_length = Length of content received so far.
988 * Returns : TRUE if the response is complete,
991 *********************************************************************/
992 static int server_response_is_complete(struct client_state *csp,
993 unsigned long long content_length)
995 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
997 if (!strcmpic(csp->http->gpc, "HEAD"))
1000 * "HEAD" implies no body, we are thus expecting
1001 * no content. XXX: incomplete "list" of methods?
1003 csp->expected_content_length = 0;
1004 content_length_known = TRUE;
1005 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1008 if (csp->http->status == 204 || csp->http->status == 304)
1011 * Expect no body. XXX: incomplete "list" of status codes?
1013 csp->expected_content_length = 0;
1014 content_length_known = TRUE;
1015 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1018 return (content_length_known && ((0 == csp->expected_content_length)
1019 || (csp->expected_content_length <= content_length)));
1023 #ifdef FEATURE_CONNECTION_SHARING
1024 /*********************************************************************
1026 * Function : wait_for_alive_connections
1028 * Description : Waits for alive connections to timeout.
1034 *********************************************************************/
1035 static void wait_for_alive_connections(void)
1037 int connections_alive = close_unusable_connections();
1039 while (0 < connections_alive)
1041 log_error(LOG_LEVEL_CONNECT,
1042 "Waiting for %d connections to timeout.",
1045 connections_alive = close_unusable_connections();
1048 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1051 #endif /* def FEATURE_CONNECTION_SHARING */
1054 /*********************************************************************
1056 * Function : save_connection_destination
1058 * Description : Remembers a connection for reuse later on.
1061 * 1 : sfd = Open socket to remember.
1062 * 2 : http = The destination for the connection.
1063 * 3 : fwd = The forwarder settings used.
1064 * 3 : server_connection = storage.
1068 *********************************************************************/
1069 void save_connection_destination(jb_socket sfd,
1070 const struct http_request *http,
1071 const struct forward_spec *fwd,
1072 struct reusable_connection *server_connection)
1074 assert(sfd != JB_INVALID_SOCKET);
1075 assert(NULL != http->host);
1077 server_connection->sfd = sfd;
1078 server_connection->host = strdup_or_die(http->host);
1079 server_connection->port = http->port;
1081 assert(NULL != fwd);
1082 assert(server_connection->gateway_host == NULL);
1083 assert(server_connection->gateway_port == 0);
1084 assert(server_connection->forwarder_type == 0);
1085 assert(server_connection->forward_host == NULL);
1086 assert(server_connection->forward_port == 0);
1088 server_connection->forwarder_type = fwd->type;
1089 if (NULL != fwd->gateway_host)
1091 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1095 server_connection->gateway_host = NULL;
1097 server_connection->gateway_port = fwd->gateway_port;
1099 if (NULL != fwd->forward_host)
1101 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1105 server_connection->forward_host = NULL;
1107 server_connection->forward_port = fwd->forward_port;
1111 /*********************************************************************
1113 * Function : verify_request_length
1115 * Description : Checks if we already got the whole client requests
1116 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1119 * Data that doesn't belong to the current request is
1120 * either thrown away to let the client retry on a clean
1121 * socket, or stashed to be dealt with after the current
1122 * request is served.
1125 * 1 : csp = Current client state (buffers, headers, etc...)
1129 *********************************************************************/
1130 static void verify_request_length(struct client_state *csp)
1132 unsigned long long buffered_request_bytes =
1133 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1135 if ((csp->expected_client_content_length != 0)
1136 && (buffered_request_bytes != 0))
1138 if (csp->expected_client_content_length >= buffered_request_bytes)
1140 csp->expected_client_content_length -= buffered_request_bytes;
1141 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1142 "to account for the %llu ones we already got.",
1143 csp->expected_client_content_length, buffered_request_bytes);
1147 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1148 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1149 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1150 "Marking the server socket tainted after throwing %llu bytes away.",
1151 buffered_request_bytes - csp->expected_client_content_length);
1152 csp->expected_client_content_length = 0;
1153 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1156 if (csp->expected_client_content_length == 0)
1158 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1162 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1163 && ((csp->client_iob->cur < csp->client_iob->eod)
1164 || (csp->expected_client_content_length != 0)))
1166 if (strcmpic(csp->http->gpc, "GET")
1167 && strcmpic(csp->http->gpc, "HEAD")
1168 && strcmpic(csp->http->gpc, "TRACE")
1169 && strcmpic(csp->http->gpc, "OPTIONS")
1170 && strcmpic(csp->http->gpc, "DELETE"))
1172 /* XXX: this is an incomplete hack */
1173 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1174 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1178 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1180 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1182 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1183 log_error(LOG_LEVEL_CONNECT,
1184 "Possible pipeline attempt detected. The connection will not "
1185 "be kept alive and we will only serve the first request.");
1186 /* Nuke the pipelined requests from orbit, just to be sure. */
1187 clear_iob(csp->client_iob);
1192 * Keep the pipelined data around for now, we'll deal with
1193 * it once we're done serving the current request.
1195 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1196 assert(csp->client_iob->eod >= csp->client_iob->cur);
1197 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1198 "%d bytes of pipelined data received.",
1199 (int)(csp->client_iob->eod - csp->client_iob->cur));
1205 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1206 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1209 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1212 /*********************************************************************
1214 * Function : mark_server_socket_tainted
1216 * Description : Makes sure we don't reuse a server socket
1217 * (if we didn't read everything the server sent
1218 * us reusing the socket would lead to garbage).
1221 * 1 : csp = Current client state (buffers, headers, etc...)
1225 *********************************************************************/
1226 static void mark_server_socket_tainted(struct client_state *csp)
1229 * For consistency we always mark the server socket
1230 * tainted, however, to reduce the log noise we only
1231 * emit a log message if the server socket could have
1232 * actually been reused.
1234 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1235 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1237 log_error(LOG_LEVEL_CONNECT,
1238 "Marking the server socket %d tainted.",
1239 csp->server_connection.sfd);
1241 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1244 /*********************************************************************
1246 * Function : get_request_line
1248 * Description : Read the client request line.
1251 * 1 : csp = Current client state (buffers, headers, etc...)
1253 * Returns : Pointer to request line or NULL in case of errors.
1255 *********************************************************************/
1256 static char *get_request_line(struct client_state *csp)
1258 char buf[BUFFER_SIZE];
1259 char *request_line = NULL;
1262 memset(buf, 0, sizeof(buf));
1264 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1267 * If there are multiple pipelined requests waiting,
1268 * the flag will be set again once the next request
1271 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1273 request_line = get_header(csp->client_iob);
1274 if ((NULL != request_line) && ('\0' != *request_line))
1276 return request_line;
1280 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1281 "received yet. Continuing reading from %d.", csp->cfd);
1289 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1291 !data_is_available(csp->cfd, csp->config->socket_timeout)
1294 if (socket_is_still_alive(csp->cfd))
1296 log_error(LOG_LEVEL_CONNECT,
1297 "No request line on socket %d received in time. Timeout: %d.",
1298 csp->cfd, csp->config->socket_timeout);
1299 write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1300 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1304 log_error(LOG_LEVEL_CONNECT,
1305 "The client side of the connection on socket %d got "
1306 "closed without sending a complete request line.", csp->cfd);
1311 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1313 if (len <= 0) return NULL;
1316 * If there is no memory left for buffering the
1317 * request, there is nothing we can do but hang up
1319 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1324 request_line = get_header(csp->client_iob);
1326 } while ((NULL != request_line) && ('\0' == *request_line));
1328 return request_line;
1334 CHUNK_STATUS_MISSING_DATA,
1335 CHUNK_STATUS_BODY_COMPLETE,
1336 CHUNK_STATUS_PARSE_ERROR
1340 /*********************************************************************
1342 * Function : chunked_body_is_complete
1344 * Description : Figures out whether or not a chunked body is complete.
1346 * Currently it always starts at the beginning of the
1347 * buffer which is somewhat wasteful and prevents Privoxy
1348 * from starting to forward the correctly parsed chunks
1349 * as soon as theoretically possible.
1351 * Should be modified to work with a common buffer,
1352 * and allow the caller to skip already parsed chunks.
1354 * This would allow the function to be used for unbuffered
1355 * response bodies as well.
1358 * 1 : iob = Buffer with the body to check.
1359 * 2 : length = Length of complete body
1361 * Returns : Enum with the result of the check.
1363 *********************************************************************/
1364 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1366 unsigned int chunksize;
1372 * We need at least a single digit, followed by "\r\n",
1373 * followed by an unknown amount of data, followed by "\r\n".
1375 if (p + 5 > iob->eod)
1377 return CHUNK_STATUS_MISSING_DATA;
1379 if (sscanf(p, "%x", &chunksize) != 1)
1381 return CHUNK_STATUS_PARSE_ERROR;
1385 * We want at least a single digit, followed by "\r\n",
1386 * followed by the specified amount of data, followed by "\r\n".
1388 if (p + chunksize + 5 > iob->eod)
1390 return CHUNK_STATUS_MISSING_DATA;
1393 /* Skip chunk-size. */
1394 p = strstr(p, "\r\n");
1397 return CHUNK_STATUS_PARSE_ERROR;
1399 /* Move beyond the chunkdata. */
1402 /* There should be another "\r\n" to skip */
1403 if (memcmp(p, "\r\n", 2))
1405 return CHUNK_STATUS_PARSE_ERROR;
1408 } while (chunksize > 0U);
1410 *length = (size_t)(p - iob->cur);
1411 assert(*length <= (size_t)(iob->eod - iob->cur));
1412 assert(p <= iob->eod);
1414 return CHUNK_STATUS_BODY_COMPLETE;
1419 /*********************************************************************
1421 * Function : receive_chunked_client_request_body
1423 * Description : Read the chunk-encoded client request body.
1424 * Failures are dealt with.
1427 * 1 : csp = Current client state (buffers, headers, etc...)
1429 * Returns : JB_ERR_OK or JB_ERR_PARSE
1431 *********************************************************************/
1432 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1435 enum chunk_status status;
1437 while (CHUNK_STATUS_MISSING_DATA ==
1438 (status = chunked_body_is_complete(csp->client_iob,&body_length)))
1440 char buf[BUFFER_SIZE];
1443 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1445 log_error(LOG_LEVEL_ERROR,
1446 "Timeout while waiting for the client body.");
1449 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1452 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1455 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1460 if (status != CHUNK_STATUS_BODY_COMPLETE)
1462 write_socket(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1463 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE));
1464 log_error(LOG_LEVEL_CLF,
1465 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1466 return JB_ERR_PARSE;
1468 log_error(LOG_LEVEL_CONNECT,
1469 "Chunked client body completely read. Length: %d", body_length);
1470 csp->expected_client_content_length = body_length;
1478 /*********************************************************************
1480 * Function : fuzz_chunked_transfer_encoding
1482 * Description : Treat the fuzzed input as chunked transfer encoding
1483 * to check and dechunk.
1486 * 1 : csp = Used to store the data.
1487 * 2 : fuzz_input_file = File to read the input from.
1489 * Returns : Result of dechunking
1491 *********************************************************************/
1492 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1495 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1496 enum chunk_status status;
1498 status = chunked_body_is_complete(csp->iob, &length);
1499 if (CHUNK_STATUS_BODY_COMPLETE != status)
1501 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1504 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1509 /*********************************************************************
1511 * Function : fuzz_client_request
1513 * Description : Try to get a client request from the fuzzed input.
1516 * 1 : csp = Current client state (buffers, headers, etc...)
1517 * 2 : fuzz_input_file = File to read the input from.
1519 * Returns : Result of fuzzing.
1521 *********************************************************************/
1522 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1527 csp->ip_addr_str = "fuzzer";
1529 if (strcmp(fuzz_input_file, "-") != 0)
1531 log_error(LOG_LEVEL_FATAL,
1532 "Fuzzed client requests can currenty only be read from stdin (-).");
1534 err = receive_client_request(csp);
1535 if (err != JB_ERR_OK)
1539 err = parse_client_request(csp);
1540 if (err != JB_ERR_OK)
1548 #endif /* def FUZZ */
1551 #ifdef FEATURE_FORCE_LOAD
1552 /*********************************************************************
1554 * Function : force_required
1556 * Description : Checks a request line to see if it contains
1557 * the FORCE_PREFIX. If it does, it is removed
1558 * unless enforcing requests has beend disabled.
1561 * 1 : request_line = HTTP request line
1563 * Returns : TRUE if force is required, FALSE otherwise.
1565 *********************************************************************/
1566 static int force_required(const struct client_state *csp, char *request_line)
1570 p = strstr(request_line, "http://");
1574 p += strlen("http://");
1578 /* Intercepted request usually don't specify the protocol. */
1582 /* Go to the beginning of the path */
1587 * If the path is missing the request line is invalid and we
1588 * are done here. The client-visible rejection happens later on.
1593 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1595 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1597 /* XXX: Should clean more carefully */
1598 strclean(request_line, FORCE_PREFIX);
1599 log_error(LOG_LEVEL_FORCE,
1600 "Enforcing request: \"%s\".", request_line);
1604 log_error(LOG_LEVEL_FORCE,
1605 "Ignored force prefix in request: \"%s\".", request_line);
1611 #endif /* def FEATURE_FORCE_LOAD */
1614 /*********************************************************************
1616 * Function : receive_client_request
1618 * Description : Read the client's request (more precisely the
1619 * client headers) and answer it if necessary.
1622 * 1 : csp = Current client state (buffers, headers, etc...)
1624 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1626 *********************************************************************/
1627 static jb_err receive_client_request(struct client_state *csp)
1629 char buf[BUFFER_SIZE];
1632 struct http_request *http;
1636 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1637 struct list header_list;
1638 struct list *headers = &header_list;
1640 /* We don't care if the arriving data is a valid HTTP request or not. */
1641 csp->requests_received_total++;
1645 memset(buf, 0, sizeof(buf));
1647 req = get_request_line(csp);
1650 mark_server_socket_tainted(csp);
1651 return JB_ERR_PARSE;
1653 assert(*req != '\0');
1655 if (client_protocol_is_unsupported(csp, req))
1657 return JB_ERR_PARSE;
1660 #ifdef FEATURE_FORCE_LOAD
1661 if (force_required(csp, req))
1663 csp->flags |= CSP_FLAG_FORCED;
1665 #endif /* def FEATURE_FORCE_LOAD */
1667 err = parse_http_request(req, http);
1669 if (JB_ERR_OK != err)
1671 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1672 /* XXX: Use correct size */
1673 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1674 log_error(LOG_LEVEL_ERROR,
1675 "Couldn't parse request line received from %s: %s",
1676 csp->ip_addr_str, jb_err_to_string(err));
1678 free_http_request(http);
1679 return JB_ERR_PARSE;
1682 /* grab the rest of the client's headers */
1686 p = get_header(csp->client_iob);
1690 /* There are no additional headers to read. */
1697 * We didn't receive a complete header
1698 * line yet, get the rest of it.
1700 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1702 log_error(LOG_LEVEL_ERROR,
1703 "Stopped grabbing the client headers.");
1704 destroy_list(headers);
1705 return JB_ERR_PARSE;
1708 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1711 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1712 destroy_list(headers);
1713 return JB_ERR_PARSE;
1716 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1719 * If there is no memory left for buffering the
1720 * request, there is nothing we can do but hang up
1722 destroy_list(headers);
1723 return JB_ERR_MEMORY;
1728 if (!strncmpic(p, "Transfer-Encoding:", 18))
1731 * XXX: should be called through sed()
1732 * but currently can't.
1734 client_transfer_encoding(csp, &p);
1737 * We were able to read a complete
1738 * header and can finally enlist it.
1745 if (http->host == NULL)
1748 * If we still don't know the request destination,
1749 * the request is invalid or the client uses
1750 * Privoxy without its knowledge.
1752 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1755 * Our attempts to get the request destination
1756 * elsewhere failed or Privoxy is configured
1757 * to only accept proxy requests.
1759 * An error response has already been send
1760 * and we're done here.
1762 return JB_ERR_PARSE;
1766 #ifdef FEATURE_CLIENT_TAGS
1767 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1768 set_client_address(csp, headers);
1769 get_tag_list_for_client(csp->client_tags, csp->client_address);
1773 * Determine the actions for this URL
1775 #ifdef FEATURE_TOGGLE
1776 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1778 /* Most compatible set of actions (i.e. none) */
1779 init_current_action(csp->action);
1782 #endif /* ndef FEATURE_TOGGLE */
1784 get_url_actions(csp, http);
1787 enlist(csp->headers, http->cmd);
1789 /* Append the previously read headers */
1790 err = list_append_list_unique(csp->headers, headers);
1791 destroy_list(headers);
1798 /*********************************************************************
1800 * Function : parse_client_request
1802 * Description : Parses the client's request and decides what to do
1805 * Note that since we're not using select() we could get
1806 * blocked here if a client connected, then didn't say
1810 * 1 : csp = Current client state (buffers, headers, etc...)
1812 * Returns : JB_ERR_OK or JB_ERR_PARSE
1814 *********************************************************************/
1815 static jb_err parse_client_request(struct client_state *csp)
1817 struct http_request *http = csp->http;
1820 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1821 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1822 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1823 && (csp->http->ssl == 0))
1825 /* Assume persistence until further notice */
1826 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1829 if (csp->http->ssl == 0)
1832 * This whole block belongs to chat() but currently
1833 * has to be executed before sed().
1835 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1837 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1839 return JB_ERR_PARSE;
1844 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1846 verify_request_length(csp);
1848 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1850 err = sed(csp, FILTER_CLIENT_HEADERS);
1851 if (JB_ERR_OK != err)
1853 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1855 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1856 csp->ip_addr_str, csp->http->cmd);
1857 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1858 return JB_ERR_PARSE;
1860 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1862 /* Check request line for rewrites. */
1863 if ((NULL == csp->headers->first->str)
1864 || (strcmp(http->cmd, csp->headers->first->str) &&
1865 (JB_ERR_OK != change_request_destination(csp))))
1868 * A header filter broke the request line - bail out.
1870 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1871 /* XXX: Use correct size */
1872 log_error(LOG_LEVEL_CLF,
1873 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1874 log_error(LOG_LEVEL_ERROR,
1875 "Invalid request line after applying header filters.");
1876 free_http_request(http);
1878 return JB_ERR_PARSE;
1881 if (client_has_unsupported_expectations(csp))
1883 return JB_ERR_PARSE;
1891 /*********************************************************************
1893 * Function : send_http_request
1895 * Description : Sends the HTTP headers from the client request
1896 * and all the body data that has already been received.
1899 * 1 : csp = Current client state (buffers, headers, etc...)
1901 * Returns : 0 on success, anything else is na error.
1903 *********************************************************************/
1904 static int send_http_request(struct client_state *csp)
1909 hdr = list_to_text(csp->headers);
1912 /* FIXME Should handle error properly */
1913 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1915 list_remove_all(csp->headers);
1918 * Write the client's (modified) header to the server
1919 * (along with anything else that may be in the buffer)
1921 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
1926 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
1927 csp->http->hostport);
1929 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
1930 && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
1933 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
1934 csp->http->hostport);
1937 return write_failure;
1942 /*********************************************************************
1944 * Function : handle_established_connection
1946 * Description : Shuffle data between client and server once the
1947 * connection has been established.
1950 * 1 : csp = Current client state (buffers, headers, etc...)
1952 * Returns : Nothing.
1954 *********************************************************************/
1955 static void handle_established_connection(struct client_state *csp,
1956 const struct forward_spec *fwd)
1958 char buf[BUFFER_SIZE];
1965 int ms_iis5_hack = 0;
1966 unsigned long long byte_count = 0;
1967 struct http_request *http;
1968 long len = 0; /* for buffer sizes (and negative error codes) */
1969 int buffer_and_filter_content = 0;
1971 /* Skeleton for HTTP response, if we should intercept the request */
1972 struct http_response *rsp;
1973 struct timeval timeout;
1974 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1975 int watch_client_socket;
1978 memset(buf, 0, sizeof(buf));
1982 maxfd = (csp->cfd > csp->server_connection.sfd) ?
1983 csp->cfd : csp->server_connection.sfd;
1985 /* pass data between the client and server
1986 * until one or the other shuts down the connection.
1991 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1992 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
1999 * FD_ZERO here seems to point to an errant macro which crashes.
2000 * So do this by hand for now...
2002 memset(&rfds,0x00,sizeof(fd_set));
2006 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2007 if (!watch_client_socket)
2009 maxfd = csp->server_connection.sfd;
2012 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2014 FD_SET(csp->cfd, &rfds);
2017 FD_SET(csp->server_connection.sfd, &rfds);
2019 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2020 if ((csp->flags & CSP_FLAG_CHUNKED)
2021 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2022 && ((csp->iob->eod - csp->iob->cur) >= 5)
2023 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2026 * XXX: This check should be obsolete now,
2027 * but let's wait a while to be sure.
2029 log_error(LOG_LEVEL_CONNECT,
2030 "Looks like we got the last chunk together with "
2031 "the server headers but didn't detect it earlier. "
2032 "We better stop reading.");
2033 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2034 csp->expected_content_length = byte_count;
2035 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2037 if (server_body && server_response_is_complete(csp, byte_count))
2039 if (csp->expected_content_length == byte_count)
2041 log_error(LOG_LEVEL_CONNECT,
2042 "Done reading from server. Content length: %llu as expected. "
2043 "Bytes most recently read: %d.",
2048 log_error(LOG_LEVEL_CONNECT,
2049 "Done reading from server. Expected content length: %llu. "
2050 "Actual content length: %llu. Bytes most recently read: %d.",
2051 csp->expected_content_length, byte_count, len);
2055 * XXX: should not jump around,
2056 * chat() is complicated enough already.
2060 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2062 timeout.tv_sec = csp->config->socket_timeout;
2063 timeout.tv_usec = 0;
2064 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2068 log_error(LOG_LEVEL_ERROR,
2069 "Didn't receive data in time: %s", http->url);
2070 if ((byte_count == 0) && (http->ssl == 0))
2072 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2074 mark_server_socket_tainted(csp);
2079 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2080 mark_server_socket_tainted(csp);
2085 * This is the body of the browser's request,
2086 * just read and write it.
2088 * XXX: Make sure the client doesn't use pipelining
2089 * behind Privoxy's back.
2091 if (FD_ISSET(csp->cfd, &rfds))
2093 int max_bytes_to_read = sizeof(buf) - 1;
2095 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2096 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2098 if (data_is_available(csp->cfd, 0))
2101 * If the next request is already waiting, we have
2102 * to stop select()ing the client socket. Otherwise
2103 * we would always return right away and get nothing
2106 watch_client_socket = 0;
2107 log_error(LOG_LEVEL_CONNECT,
2108 "Stopping to watch the client socket %d. "
2109 "There's already another request waiting.",
2114 * If the client socket is set, but there's no data
2115 * available on the socket, the client went fishing
2116 * and continuing talking to the server makes no sense.
2118 log_error(LOG_LEVEL_CONNECT,
2119 "The client closed socket %d while "
2120 "the server socket %d is still open.",
2121 csp->cfd, csp->server_connection.sfd);
2122 mark_server_socket_tainted(csp);
2125 if (csp->expected_client_content_length != 0)
2127 if (csp->expected_client_content_length < (sizeof(buf) - 1))
2129 max_bytes_to_read = (int)csp->expected_client_content_length;
2131 log_error(LOG_LEVEL_CONNECT,
2132 "Waiting for up to %d bytes from the client.",
2135 assert(max_bytes_to_read < sizeof(buf));
2136 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2138 len = read_socket(csp->cfd, buf, max_bytes_to_read);
2142 /* XXX: not sure if this is necessary. */
2143 mark_server_socket_tainted(csp);
2144 break; /* "game over, man" */
2147 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2148 if (csp->expected_client_content_length != 0)
2150 assert(len <= max_bytes_to_read);
2151 csp->expected_client_content_length -= (unsigned)len;
2152 log_error(LOG_LEVEL_CONNECT,
2153 "Expected client content length set to %llu "
2154 "after reading %d bytes.",
2155 csp->expected_client_content_length, len);
2156 if (csp->expected_client_content_length == 0)
2158 log_error(LOG_LEVEL_CONNECT,
2159 "Done reading from the client.");
2160 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2163 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2165 if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
2167 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2168 mark_server_socket_tainted(csp);
2175 * The server wants to talk. It could be the header or the body.
2176 * If `hdr' is null, then it's the header otherwise it's the body.
2177 * FIXME: Does `hdr' really mean `host'? No.
2179 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2181 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2183 * If we are buffering content, we don't want to eat up to
2184 * buffer-limit bytes if the client no longer cares about them.
2185 * If we aren't buffering, however, a dead client socket will be
2186 * noticed pretty much right away anyway, so we can reduce the
2187 * overhead by skipping the check.
2189 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2192 log_error(LOG_LEVEL_CONNECT,
2193 "The server still wants to talk, but the client may already have hung up on us.");
2195 log_error(LOG_LEVEL_CONNECT,
2196 "The server still wants to talk, but the client hung up on us.");
2197 mark_server_socket_tainted(csp);
2199 #endif /* def _WIN32 */
2201 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2203 len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
2207 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2209 if (http->ssl && (fwd->forward_host == NULL))
2212 * Just hang up. We already confirmed the client's CONNECT
2213 * request with status code 200 and unencrypted content is
2214 * no longer welcome.
2216 log_error(LOG_LEVEL_ERROR,
2217 "CONNECT already confirmed. Unable to tell the client about the problem.");
2220 else if (byte_count)
2223 * Just hang up. We already transmitted the original headers
2224 * and parts of the original content and therefore missed the
2225 * chance to send an error message (without risking data corruption).
2227 * XXX: we could retry with a fancy range request here.
2229 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2230 "Unable to tell the client about the problem.");
2231 mark_server_socket_tainted(csp);
2235 * XXX: Consider handling the cases above the same.
2237 mark_server_socket_tainted(csp);
2241 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2242 if (csp->flags & CSP_FLAG_CHUNKED)
2244 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2246 /* XXX: this is a temporary hack */
2247 log_error(LOG_LEVEL_CONNECT,
2248 "Looks like we reached the end of the last chunk. "
2249 "We better stop reading.");
2250 csp->expected_content_length = byte_count + (unsigned long long)len;
2251 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2255 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2258 * Add a trailing zero to let be able to use string operations.
2259 * XXX: do we still need this with filter_popups gone?
2264 * Normally, this would indicate that we've read
2265 * as much as the server has sent us and we can
2266 * close the client connection. However, Microsoft
2267 * in its wisdom has released IIS/5 with a bug that
2268 * prevents it from sending the trailing \r\n in
2269 * a 302 redirect header (and possibly other headers).
2270 * To work around this if we've haven't parsed
2271 * a full header we'll append a trailing \r\n
2272 * and see if this now generates a valid one.
2274 * This hack shouldn't have any impacts. If we've
2275 * already transmitted the header or if this is a
2276 * SSL connection, then we won't bother with this
2277 * hack. So we only work on partially received
2278 * headers. If we append a \r\n and this still
2279 * doesn't generate a valid header, then we won't
2280 * transmit anything to the client.
2285 if (server_body || http->ssl)
2288 * If we have been buffering up the document,
2289 * now is the time to apply content modification
2290 * and send the result to the client.
2292 if (buffer_and_filter_content)
2294 p = execute_content_filters(csp);
2296 * If content filtering fails, use the original
2297 * buffer and length.
2298 * (see p != NULL ? p : csp->iob->cur below)
2302 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2304 #ifdef FEATURE_COMPRESSION
2305 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2306 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2308 char *compressed_content = compress_buffer(p,
2309 (size_t *)&csp->content_length, csp->config->compression_level);
2310 if (compressed_content != NULL)
2313 p = compressed_content;
2314 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2319 if (JB_ERR_OK != update_server_headers(csp))
2321 log_error(LOG_LEVEL_FATAL,
2322 "Failed to update server headers. after filtering.");
2325 hdr = list_to_text(csp->headers);
2328 /* FIXME Should handle error properly */
2329 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2332 if (write_socket(csp->cfd, hdr, strlen(hdr))
2333 || write_socket(csp->cfd,
2334 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2336 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2339 mark_server_socket_tainted(csp);
2347 break; /* "game over, man" */
2351 * This is NOT the body, so
2352 * Let's pretend the server just sent us a blank line.
2354 snprintf(buf, sizeof(buf), "\r\n");
2355 len = (int)strlen(buf);
2358 * Now, let the normal header parsing algorithm below do its
2359 * job. If it fails, we'll exit instead of continuing.
2366 * If this is an SSL connection or we're in the body
2367 * of the server document, just write it to the client,
2368 * unless we need to buffer the body for later content-filtering
2370 if (server_body || http->ssl)
2372 if (buffer_and_filter_content)
2375 * If there is no memory left for buffering the content, or the buffer limit
2376 * has been reached, switch to non-filtering mode, i.e. make & write the
2377 * header, flush the iob and buf, and get out of the way.
2379 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2384 log_error(LOG_LEVEL_INFO,
2385 "Flushing header and buffers. Stepping back from filtering.");
2387 hdr = list_to_text(csp->headers);
2391 * Memory is too tight to even generate the header.
2392 * Send our static "Out-of-memory" page.
2394 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2395 rsp = cgi_error_memory();
2396 send_crunch_response(csp, rsp);
2397 mark_server_socket_tainted(csp);
2400 hdrlen = strlen(hdr);
2402 if (write_socket(csp->cfd, hdr, hdrlen)
2403 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2404 || (write_socket(csp->cfd, buf, (size_t)len)))
2406 log_error(LOG_LEVEL_CONNECT,
2407 "Flush header and buffers to client failed: %E");
2409 mark_server_socket_tainted(csp);
2414 * Reset the byte_count to the amount of bytes
2415 * we just flushed. len will be added a few lines below,
2416 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2418 byte_count = (unsigned long long)flushed;
2420 buffer_and_filter_content = 0;
2426 if (write_socket(csp->cfd, buf, (size_t)len))
2428 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2429 mark_server_socket_tainted(csp);
2433 byte_count += (unsigned long long)len;
2439 * We're still looking for the end of the server's header.
2440 * Buffer up the data we just read. If that fails, there's
2441 * little we can do but send our static out-of-memory page.
2443 if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2445 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2446 rsp = cgi_error_memory();
2447 send_crunch_response(csp, rsp);
2448 mark_server_socket_tainted(csp);
2452 /* Convert iob into something sed() can digest */
2453 if (JB_ERR_PARSE == get_server_headers(csp))
2458 * Well, we tried our MS IIS/5 hack and it didn't work.
2459 * The header is incomplete and there isn't anything
2460 * we can do about it.
2462 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2463 "Applying the MS IIS5 hack didn't help.");
2464 log_error(LOG_LEVEL_CLF,
2465 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2466 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2467 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2468 mark_server_socket_tainted(csp);
2474 * Since we have to wait for more from the server before
2475 * we can parse the headers we just continue here.
2477 log_error(LOG_LEVEL_CONNECT,
2478 "Continuing buffering server headers from socket %d. "
2479 "Bytes most recently read: %d.", csp->cfd, len);
2486 * Account for the content bytes we
2487 * might have gotten with the headers.
2489 assert(csp->iob->eod >= csp->iob->cur);
2490 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2493 /* Did we actually get anything? */
2494 if (NULL == csp->headers->first)
2496 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2498 log_error(LOG_LEVEL_ERROR,
2499 "No server or forwarder response received on socket %d. "
2500 "Closing client socket %d without sending data.",
2501 csp->server_connection.sfd, csp->cfd);
2502 log_error(LOG_LEVEL_CLF,
2503 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2507 log_error(LOG_LEVEL_ERROR,
2508 "No server or forwarder response received on socket %d.",
2509 csp->server_connection.sfd);
2510 send_crunch_response(csp, error_response(csp, "no-server-data"));
2512 free_http_request(http);
2513 mark_server_socket_tainted(csp);
2517 assert(csp->headers->first->str);
2519 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2520 strncmpic(csp->headers->first->str, "ICY", 3))
2523 * It doesn't look like a HTTP (or Shoutcast) response:
2524 * tell the client and log the problem.
2526 if (strlen(csp->headers->first->str) > 30)
2528 csp->headers->first->str[30] = '\0';
2530 log_error(LOG_LEVEL_ERROR,
2531 "Invalid server or forwarder response. Starts with: %s",
2532 csp->headers->first->str);
2533 log_error(LOG_LEVEL_CLF,
2534 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2535 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2536 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2537 free_http_request(http);
2538 mark_server_socket_tainted(csp);
2543 * We have now received the entire server header,
2544 * filter it and send the result to the client
2546 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2548 log_error(LOG_LEVEL_CLF,
2549 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2550 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2551 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2552 free_http_request(http);
2553 mark_server_socket_tainted(csp);
2556 hdr = list_to_text(csp->headers);
2559 /* FIXME Should handle error properly */
2560 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2563 if ((csp->flags & CSP_FLAG_CHUNKED)
2564 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2565 && ((csp->iob->eod - csp->iob->cur) >= 5)
2566 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2568 log_error(LOG_LEVEL_CONNECT,
2569 "Looks like we got the last chunk together with "
2570 "the server headers. We better stop reading.");
2571 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2572 csp->expected_content_length = byte_count;
2573 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2576 csp->server_connection.response_received = time(NULL);
2578 if (crunch_response_triggered(csp, crunchers_light))
2581 * One of the tags created by a server-header
2582 * tagger triggered a crunch. We already
2583 * delivered the crunch response to the client
2584 * and are done here after cleaning up.
2587 mark_server_socket_tainted(csp);
2590 /* Buffer and pcrs filter this if appropriate. */
2592 if (!http->ssl) /* We talk plaintext */
2594 buffer_and_filter_content = content_requires_filtering(csp);
2597 * Only write if we're not buffering for content modification
2599 if (!buffer_and_filter_content)
2602 * Write the server's (modified) header to
2603 * the client (along with anything else that
2604 * may be in the buffer)
2607 if (write_socket(csp->cfd, hdr, strlen(hdr))
2608 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2610 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2613 * The write failed, so don't bother mentioning it
2614 * to the client... it probably can't hear us anyway.
2617 mark_server_socket_tainted(csp);
2622 /* we're finished with the server's header */
2628 * If this was a MS IIS/5 hack then it means the server
2629 * has already closed the connection. Nothing more to read.
2634 log_error(LOG_LEVEL_ERROR,
2635 "Closed server connection detected. "
2636 "Applying the MS IIS5 hack didn't help.");
2637 log_error(LOG_LEVEL_CLF,
2638 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2639 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2640 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2641 mark_server_socket_tainted(csp);
2647 mark_server_socket_tainted(csp);
2648 return; /* huh? we should never get here */
2651 if (csp->content_length == 0)
2654 * If Privoxy didn't recalculate the Content-Length,
2655 * byte_count is still correct.
2657 csp->content_length = byte_count;
2660 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2661 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2662 && (csp->expected_content_length != byte_count))
2664 log_error(LOG_LEVEL_CONNECT,
2665 "Received %llu bytes while expecting %llu.",
2666 byte_count, csp->expected_content_length);
2667 mark_server_socket_tainted(csp);
2671 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2672 csp->ip_addr_str, http->ocmd, csp->content_length);
2674 csp->server_connection.timestamp = time(NULL);
2678 /*********************************************************************
2682 * Description : Once a connection from the client has been accepted,
2683 * this function is called (via serve()) to handle the
2684 * main business of the communication. This function
2685 * returns after dealing with a single request. It can
2686 * be called multiple times with the same client socket
2687 * if the client is keeping the connection alive.
2689 * The decision whether or not a client connection will
2690 * be kept alive is up to the caller which also must
2691 * close the client socket when done.
2693 * FIXME: chat is nearly thousand lines long.
2697 * 1 : csp = Current client state (buffers, headers, etc...)
2699 * Returns : Nothing.
2701 *********************************************************************/
2702 static void chat(struct client_state *csp)
2704 char buf[BUFFER_SIZE];
2705 const struct forward_spec *fwd;
2706 struct http_request *http;
2707 /* Skeleton for HTTP response, if we should intercept the request */
2708 struct http_response *rsp;
2710 memset(buf, 0, sizeof(buf));
2714 if (receive_client_request(csp) != JB_ERR_OK)
2718 if (parse_client_request(csp) != JB_ERR_OK)
2723 /* decide how to route the HTTP request */
2724 fwd = forward_url(csp, http);
2727 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2728 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2733 * build the http request to send to the server
2734 * we have to do one of the following:
2736 * create = use the original HTTP request to create a new
2737 * HTTP request that has either the path component
2738 * without the http://domainspec (w/path) or the
2739 * full orininal URL (w/url)
2740 * Note that the path and/or the HTTP version may
2741 * have been altered by now.
2743 * connect = Open a socket to the host:port of the server
2744 * and short-circuit server and client socket.
2746 * pass = Pass the request unchanged if forwarding a CONNECT
2747 * request to a parent proxy. Note that we'll be sending
2748 * the CFAIL message ourselves if connecting to the parent
2749 * fails, but we won't send a CSUCCEED message if it works,
2750 * since that would result in a double message (ours and the
2751 * parent's). After sending the request to the parent, we simply
2754 * here's the matrix:
2757 * +--------+--------+
2759 * 0 | create | connect|
2761 * Forwarding +--------+--------+
2763 * 1 | create | pass |
2765 * +--------+--------+
2769 if (http->ssl && connect_port_is_forbidden(csp))
2771 const char *acceptable_connect_ports =
2772 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
2773 assert(NULL != acceptable_connect_ports);
2774 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
2775 "limit-connect{%s} doesn't allow CONNECT requests to %s",
2776 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
2777 csp->action->flags |= ACTION_BLOCK;
2783 freez(csp->headers->first->str);
2784 build_request_line(csp, fwd, &csp->headers->first->str);
2788 * We have a request. Check if one of the crunchers wants it.
2790 if (crunch_response_triggered(csp, crunchers_all))
2793 * Yes. The client got the crunch response and we're done here.
2798 log_applied_actions(csp->action);
2799 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
2801 if (fwd->forward_host)
2803 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
2804 fwd->forward_host, fwd->forward_port, http->hostport);
2808 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
2811 /* here we connect to the server, gateway, or the forwarder */
2813 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2814 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
2815 && socket_is_still_alive(csp->server_connection.sfd)
2816 && connection_destination_matches(&csp->server_connection, http, fwd))
2818 log_error(LOG_LEVEL_CONNECT,
2819 "Reusing server socket %d connected to %s. Total requests: %u.",
2820 csp->server_connection.sfd, csp->server_connection.host,
2821 csp->server_connection.requests_sent_total);
2825 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2827 #ifdef FEATURE_CONNECTION_SHARING
2828 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2830 remember_connection(&csp->server_connection);
2833 #endif /* def FEATURE_CONNECTION_SHARING */
2835 log_error(LOG_LEVEL_CONNECT,
2836 "Closing server socket %d connected to %s. Total requests: %u.",
2837 csp->server_connection.sfd, csp->server_connection.host,
2838 csp->server_connection.requests_sent_total);
2839 close_socket(csp->server_connection.sfd);
2841 mark_connection_closed(&csp->server_connection);
2843 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2845 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
2847 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
2849 if (fwd->type != SOCKS_NONE)
2852 rsp = error_response(csp, "forwarding-failed");
2854 else if (errno == EINVAL)
2856 rsp = error_response(csp, "no-such-domain");
2860 rsp = error_response(csp, "connect-failed");
2863 /* Write the answer to the client */
2866 send_crunch_response(csp, rsp);
2870 * Temporary workaround to prevent already-read client
2871 * bodies from being parsed as new requests. For now we
2872 * err on the safe side and throw all the following
2873 * requests under the bus, even if no client body has been
2874 * buffered. A compliant client will repeat the dropped
2875 * requests on an untainted connection.
2877 * The proper fix is to discard the no longer needed
2878 * client body in the buffer (if there is one) and to
2879 * continue parsing the bytes that follow.
2881 drain_and_close_socket(csp->cfd);
2882 csp->cfd = JB_INVALID_SOCKET;
2886 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2887 save_connection_destination(csp->server_connection.sfd,
2888 http, fwd, &csp->server_connection);
2889 csp->server_connection.keep_alive_timeout =
2890 (unsigned)csp->config->keep_alive_timeout;
2892 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2894 csp->server_connection.requests_sent_total++;
2896 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
2898 /* Client headers have been sent optimistically */
2899 assert(csp->headers->last == NULL);
2901 else if (fwd->forward_host || (http->ssl == 0))
2903 if (send_http_request(csp))
2905 rsp = error_response(csp, "connect-failed");
2908 send_crunch_response(csp, rsp);
2916 * We're running an SSL tunnel and we're not forwarding,
2917 * so just ditch the client headers, send the "connect succeeded"
2918 * message to the client, flush the rest, and get out of the way.
2920 list_remove_all(csp->headers);
2921 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
2925 clear_iob(csp->client_iob);
2928 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
2930 /* XXX: should the time start earlier for optimistically sent data? */
2931 csp->server_connection.request_sent = time(NULL);
2933 handle_established_connection(csp, fwd);
2938 /*********************************************************************
2940 * Function : fuzz_server_response
2942 * Description : Treat the input as a whole server response.
2945 * 1 : csp = Current client state (buffers, headers, etc...)
2946 * 2 : fuzz_input_file = File to read the input from.
2950 *********************************************************************/
2951 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
2953 static struct forward_spec fwd; /* Zero'd due to being static */
2956 if (strcmp(fuzz_input_file, "-") == 0)
2958 /* XXX: Doesn'T work yet. */
2959 csp->server_connection.sfd = 0;
2963 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
2964 if (csp->server_connection.sfd == -1)
2966 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
2970 csp->content_type |= CT_GIF;
2971 csp->action->flags |= ACTION_DEANIMATE;
2972 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
2974 csp->http->path = strdup_or_die("/");
2975 csp->http->host = strdup_or_die("fuzz.example.org");
2976 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
2977 /* Prevent client socket monitoring */
2978 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
2979 csp->flags |= CSP_FLAG_CHUNKED;
2981 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
2982 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2984 csp->content_type |= CT_DECLARED|CT_GIF;
2986 csp->config->socket_timeout = 0;
2988 cgi_init_error_messages();
2990 handle_established_connection(csp, &fwd);
2997 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2998 /*********************************************************************
3000 * Function : prepare_csp_for_next_request
3002 * Description : Put the csp in a mostly vergin state.
3005 * 1 : csp = Current client state (buffers, headers, etc...)
3009 *********************************************************************/
3010 static void prepare_csp_for_next_request(struct client_state *csp)
3012 csp->content_type = 0;
3013 csp->content_length = 0;
3014 csp->expected_content_length = 0;
3015 csp->expected_client_content_length = 0;
3016 list_remove_all(csp->headers);
3017 clear_iob(csp->iob);
3018 freez(csp->error_message);
3019 free_http_request(csp->http);
3020 destroy_list(csp->headers);
3021 destroy_list(csp->tags);
3022 #ifdef FEATURE_CLIENT_TAGS
3023 destroy_list(csp->client_tags);
3024 freez(csp->client_address);
3026 free_current_action(csp->action);
3027 if (NULL != csp->fwd)
3029 unload_forward_spec(csp->fwd);
3032 /* XXX: Store per-connection flags someplace else. */
3033 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
3034 #ifdef FEATURE_TOGGLE
3035 if (global_toggle_state)
3036 #endif /* def FEATURE_TOGGLE */
3038 csp->flags |= CSP_FLAG_TOGGLED_ON;
3041 if (csp->client_iob->eod > csp->client_iob->cur)
3043 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
3044 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
3046 assert(bytes_to_shift > 0);
3047 assert(data_length > 0);
3049 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
3050 data_length, bytes_to_shift);
3051 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
3052 csp->client_iob->cur = csp->client_iob->buf;
3053 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
3054 csp->client_iob->eod = csp->client_iob->buf + data_length;
3055 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
3057 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3062 * We mainly care about resetting client_iob->cur so we don't
3063 * waste buffer space at the beginning and don't mess up the
3064 * request restoration done by cgi_show_request().
3066 * Freeing the buffer itself isn't technically necessary,
3067 * but makes debugging more convenient.
3069 clear_iob(csp->client_iob);
3072 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3075 /*********************************************************************
3079 * Description : This is little more than chat. We only "serve" to
3080 * to close (or remember) any socket that chat may have
3084 * 1 : csp = Current client state (buffers, headers, etc...)
3088 *********************************************************************/
3090 void serve(struct client_state *csp)
3091 #else /* ifndef AMIGA */
3092 static void serve(struct client_state *csp)
3093 #endif /* def AMIGA */
3095 int config_file_change_detected = 0; /* Only used for debugging */
3096 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3097 #ifdef FEATURE_CONNECTION_SHARING
3098 static int monitor_thread_running = 0;
3099 #endif /* def FEATURE_CONNECTION_SHARING */
3100 int continue_chatting = 0;
3102 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
3103 csp->ip_addr_str, csp->cfd);
3107 unsigned int latency;
3112 * If the request has been crunched,
3113 * the calculated latency is zero.
3115 latency = (unsigned)(csp->server_connection.response_received -
3116 csp->server_connection.request_sent) / 2;
3118 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3119 && (csp->flags & CSP_FLAG_CRUNCHED)
3120 && (csp->expected_client_content_length != 0))
3122 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
3123 log_error(LOG_LEVEL_CONNECT,
3124 "Tainting client socket %d due to unread data.", csp->cfd);
3127 continue_chatting = (csp->config->feature_flags
3128 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3129 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3130 && (csp->cfd != JB_INVALID_SOCKET)
3131 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3132 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3133 || (csp->flags & CSP_FLAG_CHUNKED));
3135 if (!(csp->flags & CSP_FLAG_CRUNCHED)
3136 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
3138 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
3140 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
3142 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
3143 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3144 || !socket_is_still_alive(csp->server_connection.sfd)
3145 || !(latency < csp->server_connection.keep_alive_timeout))
3147 log_error(LOG_LEVEL_CONNECT,
3148 "Closing server socket %d connected to %s. "
3149 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
3150 csp->server_connection.sfd, csp->server_connection.host,
3151 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3152 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3153 socket_is_still_alive(csp->server_connection.sfd),
3154 csp->server_connection.keep_alive_timeout);
3155 #ifdef FEATURE_CONNECTION_SHARING
3156 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3158 forget_connection(csp->server_connection.sfd);
3160 #endif /* def FEATURE_CONNECTION_SHARING */
3161 close_socket(csp->server_connection.sfd);
3162 mark_connection_closed(&csp->server_connection);
3166 if (continue_chatting && any_loaded_file_changed(csp))
3168 continue_chatting = 0;
3169 config_file_change_detected = 1;
3172 if (continue_chatting)
3174 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
3175 && socket_is_still_alive(csp->cfd))
3177 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
3178 "pipelined on socket %d and the socket is still alive.",
3179 csp->requests_received_total+1, csp->cfd);
3180 prepare_csp_for_next_request(csp);
3184 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3186 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3188 log_error(LOG_LEVEL_CONNECT,
3189 "Waiting for the next client request on socket %d. "
3190 "Keeping the server socket %d to %s open.",
3191 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
3195 log_error(LOG_LEVEL_CONNECT,
3196 "Waiting for the next client request on socket %d. "
3197 "No server socket to keep open.", csp->cfd);
3201 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3202 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
3203 && socket_is_still_alive(csp->cfd))
3205 log_error(LOG_LEVEL_CONNECT,
3206 "Client request %u arrived in time on socket %d.",
3207 csp->requests_received_total+1, csp->cfd);
3208 prepare_csp_for_next_request(csp);
3212 #ifdef FEATURE_CONNECTION_SHARING
3213 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3214 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3215 && (socket_is_still_alive(csp->server_connection.sfd)))
3217 time_t time_open = time(NULL) - csp->server_connection.timestamp;
3219 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3224 remember_connection(&csp->server_connection);
3225 csp->server_connection.sfd = JB_INVALID_SOCKET;
3226 drain_and_close_socket(csp->cfd);
3227 csp->cfd = JB_INVALID_SOCKET;
3228 privoxy_mutex_lock(&connection_reuse_mutex);
3229 if (!monitor_thread_running)
3231 monitor_thread_running = 1;
3232 privoxy_mutex_unlock(&connection_reuse_mutex);
3233 wait_for_alive_connections();
3234 privoxy_mutex_lock(&connection_reuse_mutex);
3235 monitor_thread_running = 0;
3237 privoxy_mutex_unlock(&connection_reuse_mutex);
3239 #endif /* def FEATURE_CONNECTION_SHARING */
3243 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3245 log_error(LOG_LEVEL_CONNECT,
3246 "Closing server socket %d connected to %s. Keep-alive: %u. "
3247 "Tainted: %u. Socket alive: %u. Timeout: %u. "
3248 "Configuration file change detected: %u",
3249 csp->server_connection.sfd, csp->server_connection.host,
3250 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3251 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3252 socket_is_still_alive(csp->server_connection.sfd),
3253 csp->server_connection.keep_alive_timeout,
3254 config_file_change_detected);
3256 } while (continue_chatting);
3260 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3262 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3264 #ifdef FEATURE_CONNECTION_SHARING
3265 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3267 forget_connection(csp->server_connection.sfd);
3269 #endif /* def FEATURE_CONNECTION_SHARING */
3270 close_socket(csp->server_connection.sfd);
3273 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3274 mark_connection_closed(&csp->server_connection);
3277 if (csp->cfd != JB_INVALID_SOCKET)
3279 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3280 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3281 "Configuration file change detected: %u. Requests received: %u.",
3282 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3283 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3284 config_file_change_detected, csp->requests_received_total);
3285 drain_and_close_socket(csp->cfd);
3288 csp->flags &= ~CSP_FLAG_ACTIVE;
3294 /*********************************************************************
3296 * Function : server_thread
3298 * Description : We only exist to call `serve' in a threaded environment.
3301 * 1 : data = Current client state (buffers, headers, etc...)
3303 * Returns : Always 0.
3305 *********************************************************************/
3306 static int32 server_thread(void *data)
3308 serve((struct client_state *) data);
3315 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3316 /*********************************************************************
3320 * Description : Print usage info & exit.
3322 * Parameters : Pointer to argv[0] for identifying ourselves
3326 *********************************************************************/
3327 static void usage(const char *name)
3329 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3330 "Usage: %s [--config-test] "
3333 #endif /* defined(unix) */
3336 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3337 #endif /* defined(unix) */
3338 "[--version] [configfile]\n",
3342 show_fuzz_usage(name);
3345 printf("Aborting\n");
3350 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3353 #ifdef MUTEX_LOCKS_AVAILABLE
3354 /*********************************************************************
3356 * Function : privoxy_mutex_lock
3358 * Description : Locks a mutex.
3361 * 1 : mutex = The mutex to lock.
3363 * Returns : Void. May exit in case of errors.
3365 *********************************************************************/
3366 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3368 #ifdef FEATURE_PTHREAD
3369 int err = pthread_mutex_lock(mutex);
3372 if (mutex != &log_mutex)
3374 log_error(LOG_LEVEL_FATAL,
3375 "Mutex locking failed: %s.\n", strerror(err));
3380 EnterCriticalSection(mutex);
3381 #endif /* def FEATURE_PTHREAD */
3385 /*********************************************************************
3387 * Function : privoxy_mutex_unlock
3389 * Description : Unlocks a mutex.
3392 * 1 : mutex = The mutex to unlock.
3394 * Returns : Void. May exit in case of errors.
3396 *********************************************************************/
3397 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3399 #ifdef FEATURE_PTHREAD
3400 int err = pthread_mutex_unlock(mutex);
3403 if (mutex != &log_mutex)
3405 log_error(LOG_LEVEL_FATAL,
3406 "Mutex unlocking failed: %s.\n", strerror(err));
3411 LeaveCriticalSection(mutex);
3412 #endif /* def FEATURE_PTHREAD */
3416 /*********************************************************************
3418 * Function : privoxy_mutex_init
3420 * Description : Prepares a mutex.
3423 * 1 : mutex = The mutex to initialize.
3425 * Returns : Void. May exit in case of errors.
3427 *********************************************************************/
3428 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3430 #ifdef FEATURE_PTHREAD
3431 int err = pthread_mutex_init(mutex, 0);
3434 printf("Fatal error. Mutex initialization failed: %s.\n",
3439 InitializeCriticalSection(mutex);
3440 #endif /* def FEATURE_PTHREAD */
3442 #endif /* def MUTEX_LOCKS_AVAILABLE */
3444 /*********************************************************************
3446 * Function : initialize_mutexes
3448 * Description : Prepares mutexes if mutex support is available.
3452 * Returns : Void, exits in case of errors.
3454 *********************************************************************/
3455 static void initialize_mutexes(void)
3457 #ifdef MUTEX_LOCKS_AVAILABLE
3459 * Prepare global mutex semaphores
3461 privoxy_mutex_init(&log_mutex);
3462 privoxy_mutex_init(&log_init_mutex);
3463 privoxy_mutex_init(&connection_reuse_mutex);
3464 #ifdef FEATURE_EXTERNAL_FILTERS
3465 privoxy_mutex_init(&external_filter_mutex);
3467 #ifdef FEATURE_CLIENT_TAGS
3468 privoxy_mutex_init(&client_tags_mutex);
3472 * XXX: The assumptions below are a bit naive
3473 * and can cause locks that aren't necessary.
3475 * For example older FreeBSD versions (< 6.x?)
3476 * have no gethostbyname_r, but gethostbyname is
3479 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3480 privoxy_mutex_init(&resolver_mutex);
3481 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3483 * XXX: should we use a single mutex for
3484 * localtime() and gmtime() as well?
3486 #ifndef HAVE_GMTIME_R
3487 privoxy_mutex_init(&gmtime_mutex);
3488 #endif /* ndef HAVE_GMTIME_R */
3490 #ifndef HAVE_LOCALTIME_R
3491 privoxy_mutex_init(&localtime_mutex);
3492 #endif /* ndef HAVE_GMTIME_R */
3495 privoxy_mutex_init(&rand_mutex);
3496 #endif /* ndef HAVE_RANDOM */
3498 #endif /* def MUTEX_LOCKS_AVAILABLE */
3501 /*********************************************************************
3505 * Description : Load the config file and start the listen loop.
3506 * This function is a lot more *sane* with the `load_config'
3507 * and `listen_loop' functions; although it stills does
3508 * a *little* too much for my taste.
3511 * 1 : argc = Number of parameters (including $0).
3512 * 2 : argv = Array of (char *)'s to the parameters.
3514 * Returns : 1 if : can't open config file, unrecognized directive,
3515 * stats requested in multi-thread mode, can't open the
3516 * log file, can't open the jar file, listen port is invalid,
3517 * any load fails, and can't bind port.
3519 * Else main never returns, the process must be signaled
3520 * to terminate execution. Or, on Windows, use the
3521 * "File", "Exit" menu option.
3523 *********************************************************************/
3525 int real_main(int argc, char **argv)
3527 int main(int argc, char **argv)
3531 int do_config_test = 0;
3532 unsigned int random_seed;
3534 struct passwd *pw = NULL;
3535 struct group *grp = NULL;
3537 char *pre_chroot_nslookup_to_load_resolver = NULL;
3540 char *fuzz_input_type = NULL;
3541 char *fuzz_input_file = NULL;
3548 #if !defined(_WIN32)
3555 /* Prepare mutexes if supported and necessary. */
3556 initialize_mutexes();
3558 /* Enable logging until further notice. */
3562 * Parse the command line arguments
3564 * XXX: simply printing usage information in case of
3565 * invalid arguments isn't particularly user friendly.
3567 while (++argc_pos < argc)
3570 /* Check to see if the service must be installed or uninstalled */
3571 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3573 const char *pName = argv[argc_pos] + 9;
3576 exit((install_service(pName)) ? 0 : 1);
3578 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3580 const char *pName = argv[argc_pos] + 11;
3583 exit((uninstall_service(pName)) ? 0 : 1);
3585 else if (strcmp(argv[argc_pos], "--service") == 0)
3587 bRunAsService = TRUE;
3588 w32_set_service_cwd();
3589 atexit(w32_service_exit_notify);
3592 #endif /* defined(_WIN32) */
3595 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3597 if (strcmp(argv[argc_pos], "--help") == 0)
3602 else if (strcmp(argv[argc_pos], "--version") == 0)
3604 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3610 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3612 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3616 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3618 if (++argc_pos == argc) usage(argv[0]);
3619 pidfile = strdup_or_die(argv[argc_pos]);
3622 else if (strcmp(argv[argc_pos], "--user") == 0)
3627 if (++argc_pos == argc) usage(argv[argc_pos]);
3629 user_arg = strdup_or_die(argv[argc_pos]);
3630 group_name = strchr(user_arg, '.');
3631 if (NULL != group_name)
3633 /* Nul-terminate the user name */
3636 /* Skip the former delimiter to actually reach the group name */
3639 grp = getgrnam(group_name);
3642 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3645 pw = getpwnam(user_arg);
3648 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3654 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3656 if (++argc_pos == argc) usage(argv[0]);
3657 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3660 else if (strcmp(argv[argc_pos], "--chroot") == 0)
3664 #endif /* defined(unix) */
3666 else if (strcmp(argv[argc_pos], "--config-test") == 0)
3671 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
3674 if (argc < argc_pos + 2) usage(argv[0]);
3675 fuzz_input_type = argv[argc_pos];
3677 fuzz_input_file = argv[argc_pos];
3679 else if (strcmp(argv[argc_pos], "--stfu") == 0)
3681 set_debug_level(LOG_LEVEL_STFU);
3684 else if (argc_pos + 1 != argc)
3687 * This is neither the last command line
3688 * option, nor was it recognized before,
3689 * therefore it must be invalid.
3695 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3697 configfile = argv[argc_pos];
3700 } /* -END- while (more arguments) */
3702 show_version(Argv[0]);
3705 if (*configfile != '/')
3707 char cwd[BUFFER_SIZE];
3709 size_t abs_file_size;
3711 /* make config-filename absolute here */
3712 if (NULL == getcwd(cwd, sizeof(cwd)))
3714 perror("failed to get current working directory");
3718 basedir = strdup_or_die(cwd);
3720 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3721 abs_file = malloc_or_die(abs_file_size);
3722 strlcpy(abs_file, basedir, abs_file_size);
3723 strlcat(abs_file, "/", abs_file_size);
3724 strlcat(abs_file, configfile, abs_file_size);
3725 configfile = abs_file;
3727 #endif /* defined unix */
3731 clients->next = NULL;
3733 /* XXX: factor out initialising after the next stable release. */
3736 #elif defined(_WIN32)
3740 random_seed = (unsigned int)time(NULL);
3742 srandom(random_seed);
3745 #endif /* ifdef HAVE_RANDOM */
3748 * Unix signal handling
3750 * Catch the abort, interrupt and terminate signals for a graceful exit
3751 * Catch the hangup signal so the errlog can be reopened.
3753 * Ignore the broken pipe signal as connection failures
3754 * are handled when and where they occur without relying
3757 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3760 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3762 for (idx = 0; idx < SZ(catched_signals); idx++)
3764 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3765 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3767 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3768 #endif /* ifdef sun */
3770 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3774 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3776 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3780 #else /* ifdef _WIN32 */
3781 # ifdef _WIN_CONSOLE
3783 * We *are* in a windows console app.
3784 * Print a verbose messages about FAQ's and such
3786 printf("%s", win32_blurb);
3787 # endif /* def _WIN_CONSOLE */
3788 #endif /* def _WIN32 */
3791 if (fuzz_input_type != NULL)
3793 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
3799 exit(NULL == load_config());
3802 /* Initialize the CGI subsystem */
3803 cgi_init_error_messages();
3806 * If running on unix and without the --no-daemon
3807 * option, become a daemon. I.e. fork, detach
3808 * from tty and get process group leadership
3817 if (pid < 0) /* error */
3822 else if (pid != 0) /* parent */
3827 * must check for errors