1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
5 * Purpose : Main file. Contains main() method, main loop, and
6 * the main connection-handling function.
8 * Copyright : Written by and Copyright (C) 2001-2020 the
9 * Privoxy team. https://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 # ifndef FEATURE_PTHREAD
52 # include <winsock2.h>
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
65 # if !defined (__OS2__)
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
74 #include <sys/termios.h>
85 # include <socket.h> /* BeOS has select() for sockets only. */
86 # include <OS.h> /* declarations for threads and stuff. */
89 # if defined(__EMX__) || defined(__OS2__)
90 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
102 #endif /* def __GLIBC__ */
107 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
108 #endif /* HAVE_POLL */
115 #ifdef FEATURE_HTTPS_INSPECTION
121 #include "miscutil.h"
123 #include "jbsockets.h"
128 #include "urlmatch.h"
129 #ifdef FEATURE_CLIENT_TAGS
130 #include "client-tags.h"
134 struct client_states clients[1];
135 struct file_list files[1];
137 #ifdef FEATURE_STATISTICS
138 int urls_read = 0; /* total nr of urls read inc rejected */
139 int urls_rejected = 0; /* total nr of urls rejected */
140 #endif /* def FEATURE_STATISTICS */
142 #ifdef FEATURE_GRACEFUL_TERMINATION
146 #if !defined(_WIN32) && !defined(__OS2__)
147 static void sig_handler(int the_signal);
149 static int client_protocol_is_unsupported(struct client_state *csp, char *req);
150 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
151 static jb_err get_server_headers(struct client_state *csp);
152 static const char *crunch_reason(const struct http_response *rsp);
153 static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
154 static char *get_request_line(struct client_state *csp);
155 static jb_err receive_client_request(struct client_state *csp);
156 static jb_err parse_client_request(struct client_state *csp);
157 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
158 static jb_err change_request_destination(struct client_state *csp);
159 static void chat(struct client_state *csp);
160 static void serve(struct client_state *csp);
161 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
162 static void usage(const char *myname);
164 static void initialize_mutexes(void);
165 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
166 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
167 static void close_ports_helper(jb_socket sockets[]);
168 static void listen_loop(void);
169 static void serve(struct client_state *csp);
172 static int32 server_thread(void *data);
173 #endif /* def __BEOS__ */
176 #define sleep(N) Sleep(((N) * 1000))
180 #define sleep(N) DosSleep(((N) * 100))
184 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
185 void show_fuzz_usage(const char *name);
188 #ifdef MUTEX_LOCKS_AVAILABLE
190 * XXX: Does the locking stuff really belong in this file?
192 privoxy_mutex_t log_mutex;
193 privoxy_mutex_t log_init_mutex;
194 privoxy_mutex_t connection_reuse_mutex;
196 #ifdef FEATURE_HTTPS_INSPECTION
197 privoxy_mutex_t certificate_mutex;
198 privoxy_mutex_t ssl_init_mutex;
201 #ifdef FEATURE_EXTERNAL_FILTERS
202 privoxy_mutex_t external_filter_mutex;
204 #ifdef FEATURE_CLIENT_TAGS
205 privoxy_mutex_t client_tags_mutex;
207 #ifdef FEATURE_EXTENDED_STATISTICS
208 privoxy_mutex_t filter_statistics_mutex;
209 privoxy_mutex_t block_statistics_mutex;
212 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
213 privoxy_mutex_t resolver_mutex;
214 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
216 #ifndef HAVE_GMTIME_R
217 privoxy_mutex_t gmtime_mutex;
218 #endif /* ndef HAVE_GMTIME_R */
220 #ifndef HAVE_LOCALTIME_R
221 privoxy_mutex_t localtime_mutex;
222 #endif /* ndef HAVE_GMTIME_R */
224 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
225 privoxy_mutex_t rand_mutex;
226 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
228 #endif /* def MUTEX_LOCKS_AVAILABLE */
231 const char *basedir = NULL;
232 const char *pidfile = NULL;
233 static int received_hup_signal = 0;
234 #endif /* defined unix */
236 /* HTTP snipplets. */
237 static const char CSUCCEED[] =
238 "HTTP/1.1 200 Connection established\r\n\r\n";
240 static const char CHEADER[] =
241 "HTTP/1.1 400 Invalid header received from client\r\n"
242 "Content-Type: text/plain\r\n"
243 "Connection: close\r\n\r\n"
244 "Invalid header received from client.\r\n";
246 static const char FTP_RESPONSE[] =
247 "HTTP/1.1 400 Invalid request received from client\r\n"
248 "Content-Type: text/plain\r\n"
249 "Connection: close\r\n\r\n"
250 "Invalid request. Privoxy doesn't support FTP.\r\n";
252 static const char GOPHER_RESPONSE[] =
253 "HTTP/1.1 400 Invalid request received from client\r\n"
254 "Content-Type: text/plain\r\n"
255 "Connection: close\r\n\r\n"
256 "Invalid request. Privoxy doesn't support gopher.\r\n";
258 /* XXX: should be a template */
259 static const char MISSING_DESTINATION_RESPONSE[] =
260 "HTTP/1.1 400 Bad request received from client\r\n"
261 "Content-Type: text/plain\r\n"
262 "Connection: close\r\n\r\n"
263 "Bad request. Privoxy was unable to extract the destination.\r\n";
265 /* XXX: should be a template */
266 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
267 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
268 "Content-Type: text/plain\r\n"
269 "Connection: close\r\n\r\n"
270 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
272 /* XXX: should be a template */
273 static const char MESSED_UP_REQUEST_RESPONSE[] =
274 "HTTP/1.1 400 Malformed request after rewriting\r\n"
275 "Content-Type: text/plain\r\n"
276 "Connection: close\r\n\r\n"
277 "Bad request. Messed up with header filters.\r\n";
279 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
280 "HTTP/1.1 503 Too many open connections\r\n"
281 "Content-Type: text/plain\r\n"
282 "Connection: close\r\n\r\n"
283 "Maximum number of open connections reached.\r\n";
285 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
286 "HTTP/1.1 504 Connection timeout\r\n"
287 "Content-Type: text/plain\r\n"
288 "Connection: close\r\n\r\n"
289 "The connection timed out because the client request didn't arrive in time.\r\n";
291 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
292 "HTTP/1.1 400 Failed reading client body\r\n"
293 "Content-Type: text/plain\r\n"
294 "Connection: close\r\n\r\n"
295 "Failed parsing or buffering the chunk-encoded client body.\r\n";
297 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
298 "HTTP/1.1 417 Expecting too much\r\n"
299 "Content-Type: text/plain\r\n"
300 "Connection: close\r\n\r\n"
301 "Privoxy detected an unsupported Expect header value.\r\n";
303 /* A function to crunch a response */
304 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
306 /* Crunch function flags */
307 #define CF_NO_FLAGS 0
308 /* Cruncher applies to forced requests as well */
309 #define CF_IGNORE_FORCE 1
310 /* Crunched requests are counted for the block statistics */
311 #define CF_COUNT_AS_REJECT 2
313 /* A crunch function and its flags */
316 const crunch_func_ptr cruncher;
320 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
322 /* Complete list of cruncher functions */
323 static const struct cruncher crunchers_all[] = {
324 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
325 { block_url, CF_COUNT_AS_REJECT },
327 { trust_url, CF_COUNT_AS_REJECT },
328 #endif /* def FEATURE_TRUST */
329 { redirect_url, CF_NO_FLAGS },
330 { dispatch_cgi, CF_IGNORE_FORCE},
334 /* Light version, used after tags are applied */
335 static const struct cruncher crunchers_light[] = {
336 { block_url, CF_COUNT_AS_REJECT },
337 { redirect_url, CF_NO_FLAGS },
343 * XXX: Don't we really mean
349 #if !defined(_WIN32) && !defined(__OS2__)
350 /*********************************************************************
352 * Function : sig_handler
354 * Description : Signal handler for different signals.
355 * Exit gracefully on TERM and INT
356 * or set a flag that will cause the errlog
357 * to be reopened by the main thread on HUP.
360 * 1 : the_signal = the signal cause this function to call
364 *********************************************************************/
365 static void sig_handler(int the_signal)
371 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
383 received_hup_signal = 1;
389 * We shouldn't be here, unless we catch signals
390 * in main() that we can't handle here!
392 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
400 /*********************************************************************
402 * Function : get_write_delay
404 * Description : Parse the delay-response parameter.
407 * 1 : csp = Current client state (buffers, headers, etc...)
409 * Returns : Number of milliseconds to delay writes.
411 *********************************************************************/
412 static unsigned int get_write_delay(const struct client_state *csp)
418 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
422 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
424 delay = (unsigned)strtol(newval, &endptr, 0);
427 log_error(LOG_LEVEL_FATAL,
428 "Invalid delay-response{} parameter: '%s'", newval);
436 /*********************************************************************
438 * Function : client_protocol_is_unsupported
440 * Description : Checks if the client used a known unsupported
441 * protocol and deals with it by sending an error
445 * 1 : csp = Current client state (buffers, headers, etc...)
446 * 2 : req = the first request line send by the client
448 * Returns : TRUE if an error response has been generated, or
449 * FALSE if the request doesn't look invalid.
451 *********************************************************************/
452 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
455 * If it's a FTP or gopher request, we don't support it.
457 * These checks are better than nothing, but they might
458 * not work in all configurations and some clients might
459 * have problems digesting the answer.
461 * They should, however, never cause more problems than
462 * Privoxy's old behaviour (returning the misleading HTML
465 * "Could not resolve http://(ftp|gopher)://example.org").
467 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
469 const char *response = NULL;
470 const char *protocol = NULL;
472 if (!strncmpic(req, "GET ftp://", 10))
474 response = FTP_RESPONSE;
479 response = GOPHER_RESPONSE;
482 log_error(LOG_LEVEL_ERROR,
483 "%s tried to use Privoxy as %s proxy: %s",
484 csp->ip_addr_str, protocol, req);
485 log_error(LOG_LEVEL_CLF,
486 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
489 #ifdef FEATURE_HTTPS_INSPECTION
490 if (client_use_ssl(csp))
492 ssl_send_data_delayed(&(csp->ssl_client_attr),
493 (const unsigned char *)response, strlen(response),
494 get_write_delay(csp));
499 write_socket_delayed(csp->cfd, response, strlen(response),
500 get_write_delay(csp));
510 /*********************************************************************
512 * Function : client_has_unsupported_expectations
514 * Description : Checks if the client used an unsupported expectation
515 * in which case an error message is delivered.
518 * 1 : csp = Current client state (buffers, headers, etc...)
520 * Returns : TRUE if an error response has been generated, or
521 * FALSE if the request doesn't look invalid.
523 *********************************************************************/
524 static int client_has_unsupported_expectations(const struct client_state *csp)
526 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
528 log_error(LOG_LEVEL_ERROR,
529 "Rejecting request from client %s with unsupported Expect header value",
531 log_error(LOG_LEVEL_CLF,
532 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
533 write_socket_delayed(csp->cfd,
534 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
535 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
536 get_write_delay(csp));
546 /*********************************************************************
548 * Function : get_request_destination_elsewhere
550 * Description : If the client's request was redirected into
551 * Privoxy without the client's knowledge,
552 * the request line lacks the destination host.
554 * This function tries to get it elsewhere,
555 * provided accept-intercepted-requests is enabled.
557 * "Elsewhere" currently only means "Host: header",
558 * but in the future we may ask the redirecting
559 * packet filter to look the destination up.
561 * If the destination stays unknown, an error
562 * response is send to the client and headers
563 * are freed so that chat() can return directly.
566 * 1 : csp = Current client state (buffers, headers, etc...)
567 * 2 : headers = a header list
569 * Returns : JB_ERR_OK if the destination is now known, or
570 * JB_ERR_PARSE if it isn't.
572 *********************************************************************/
573 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
577 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
579 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
580 " Privoxy isn't configured to accept intercepted requests.",
581 csp->ip_addr_str, csp->http->cmd);
582 /* XXX: Use correct size */
583 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
584 csp->ip_addr_str, csp->http->cmd);
586 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
587 get_write_delay(csp));
588 destroy_list(headers);
592 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
594 /* Split the domain we just got for pattern matching */
595 init_domain_components(csp->http);
601 /* We can't work without destination. Go spread the news.*/
603 req = list_to_text(headers);
605 /* XXX: Use correct size */
606 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
607 csp->ip_addr_str, csp->http->cmd);
608 log_error(LOG_LEVEL_ERROR,
609 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
610 csp->ip_addr_str, csp->http->cmd, req);
613 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
614 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
615 destroy_list(headers);
620 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
621 * to get the destination IP address, use it as host directly
622 * or do a reverse DNS lookup first.
627 /*********************************************************************
629 * Function : get_server_headers
631 * Description : Parses server headers in iob and fills them
632 * into csp->headers so that they can later be
636 * 1 : csp = Current client state (buffers, headers, etc...)
638 * Returns : JB_ERR_OK if everything went fine, or
639 * JB_ERR_PARSE if the headers were incomplete.
641 *********************************************************************/
642 static jb_err get_server_headers(struct client_state *csp)
644 int continue_hack_in_da_house = 0;
647 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
652 * continue hack in da house. Ignore the ending of
653 * this head and continue enlisting header lines.
654 * The reason is described below.
656 enlist(csp->headers, "");
657 continue_hack_in_da_house = 0;
660 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
663 * It's a bodyless continue response, don't
664 * stop header parsing after reaching its end.
666 * As a result Privoxy will concatenate the
667 * next response's head and parse and deliver
668 * the headers as if they belonged to one request.
670 * The client will separate them because of the
671 * empty line between them.
673 * XXX: What we're doing here is clearly against
674 * the intended purpose of the continue header,
675 * and under some conditions (HTTP/1.0 client request)
676 * it's a standard violation.
678 * Anyway, "sort of against the spec" is preferable
679 * to "always getting confused by Continue responses"
680 * (Privoxy's behaviour before this hack was added)
682 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
683 continue_hack_in_da_house = 1;
685 else if (*header == '\0')
688 * If the header is empty, but the Continue hack
689 * isn't active, we can assume that we reached the
690 * end of the buffer before we hit the end of the
693 * Inform the caller an let it decide how to handle it.
698 if (JB_ERR_MEMORY == enlist(csp->headers, header))
701 * XXX: Should we quit the request and return a
702 * out of memory error page instead?
704 log_error(LOG_LEVEL_ERROR,
705 "Out of memory while enlisting server headers. %s lost.",
715 /*********************************************************************
717 * Function : crunch_reason
719 * Description : Translates the crunch reason code into a string.
722 * 1 : rsp = a http_response
724 * Returns : A string with the crunch reason or an error description.
726 *********************************************************************/
727 static const char *crunch_reason(const struct http_response *rsp)
729 char * reason = NULL;
734 return "Internal error while searching for crunch reason";
737 switch (rsp->crunch_reason)
740 reason = "Unsupported HTTP feature";
746 reason = "Untrusted";
749 reason = "Redirected";
755 reason = "DNS failure";
757 case FORWARDING_FAILED:
758 reason = "Forwarding failed";
761 reason = "Connection failure";
764 reason = "Out of memory (may mask other reasons)";
766 case CONNECTION_TIMEOUT:
767 reason = "Connection timeout";
770 reason = "No server data received";
773 reason = "No reason recorded";
781 /*********************************************************************
783 * Function : log_applied_actions
785 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
789 * 1 : actions = Current action spec to log
793 *********************************************************************/
794 static void log_applied_actions(const struct current_action_spec *actions)
797 * The conversion to text requires lots of memory allocations so
798 * we only do the conversion if the user is actually interested.
800 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
802 char *actions_as_text = actions_to_line_of_text(actions);
803 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
804 freez(actions_as_text);
809 /*********************************************************************
811 * Function : send_crunch_response
813 * Description : Delivers already prepared response for
814 * intercepted requests, logs the interception
815 * and frees the response.
818 * 1 : csp = Current client state (buffers, headers, etc...)
819 * 2 : rsp = Fully prepared response. Will be freed on exit.
823 *********************************************************************/
824 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
826 const struct http_request *http = csp->http;
830 assert(rsp->head != NULL);
834 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
838 * Extract the status code from the actual head
839 * that will be send to the client. It is the only
840 * way to get it right for all requests, including
841 * the fixed ones for out-of-memory problems.
843 * A head starts like this: 'HTTP/1.1 200...'
847 status_code[0] = rsp->head[9];
848 status_code[1] = rsp->head[10];
849 status_code[2] = rsp->head[11];
850 status_code[3] = '\0';
852 /* Log that the request was crunched and why. */
853 log_applied_actions(csp->action);
854 #ifdef FEATURE_HTTPS_INSPECTION
855 if (client_use_ssl(csp))
857 log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
858 http->hostport, http->path);
859 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %llu",
860 csp->ip_addr_str, http->gpc, http->hostport, http->path,
861 http->version, status_code, rsp->content_length);
866 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
867 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
868 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
870 /* Write the answer to the client */
871 #ifdef FEATURE_HTTPS_INSPECTION
872 if (client_use_ssl(csp))
874 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
875 (const unsigned char *)rsp->head, rsp->head_length,
876 get_write_delay(csp)) < 0)
877 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
878 (const unsigned char *)rsp->body, rsp->content_length,
879 get_write_delay(csp)) < 0))
881 /* There is nothing we can do about it. */
882 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
883 "for %s through client socket %d using TLS/SSL",
884 http->url, csp->cfd);
890 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
891 get_write_delay(csp))
892 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
893 get_write_delay(csp)))
895 /* There is nothing we can do about it. */
896 log_error(LOG_LEVEL_CONNECT,
897 "Couldn't deliver the error message for %s through client socket %d: %E",
898 http->url, csp->cfd);
902 /* Clean up and return */
903 if (cgi_error_memory() != rsp)
905 free_http_response(rsp);
911 /*********************************************************************
913 * Function : crunch_response_triggered
915 * Description : Checks if the request has to be crunched,
916 * and delivers the crunch response if necessary.
919 * 1 : csp = Current client state (buffers, headers, etc...)
920 * 2 : crunchers = list of cruncher functions to run
922 * Returns : TRUE if the request was answered with a crunch response
925 *********************************************************************/
926 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
928 struct http_response *rsp = NULL;
929 const struct cruncher *c;
932 * If CGI request crunching is disabled,
933 * check the CGI dispatcher out of order to
934 * prevent unintentional blocks or redirects.
936 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
937 && (NULL != (rsp = dispatch_cgi(csp))))
939 /* Deliver, log and free the interception response. */
940 send_crunch_response(csp, rsp);
941 csp->flags |= CSP_FLAG_CRUNCHED;
945 for (c = crunchers; c->cruncher != NULL; c++)
948 * Check the cruncher if either Privoxy is toggled
949 * on and the request isn't forced, or if the cruncher
950 * applies to forced requests as well.
952 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
953 !(csp->flags & CSP_FLAG_FORCED)) ||
954 (c->flags & CF_IGNORE_FORCE))
956 rsp = c->cruncher(csp);
959 /* Deliver, log and free the interception response. */
960 send_crunch_response(csp, rsp);
961 csp->flags |= CSP_FLAG_CRUNCHED;
962 #ifdef FEATURE_STATISTICS
963 if (c->flags & CF_COUNT_AS_REJECT)
965 csp->flags |= CSP_FLAG_REJECTED;
967 #endif /* def FEATURE_STATISTICS */
978 /*********************************************************************
980 * Function : build_request_line
982 * Description : Builds the HTTP request line.
984 * If a HTTP forwarder is used it expects the whole URL,
985 * web servers only get the path.
988 * 1 : csp = Current client state (buffers, headers, etc...)
989 * 2 : fwd = The forwarding spec used for the request
990 * XXX: Should use http->fwd instead.
991 * 3 : request_line = The old request line which will be replaced.
993 * Returns : Nothing. Terminates in case of memory problems.
995 *********************************************************************/
996 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
998 struct http_request *http = csp->http;
1001 * Downgrade http version from 1.1 to 1.0
1002 * if +downgrade action applies.
1004 if ((csp->action->flags & ACTION_DOWNGRADE)
1005 && (!strcmpic(http->version, "HTTP/1.1")))
1007 freez(http->version);
1008 http->version = strdup_or_die("HTTP/1.0");
1012 * Rebuild the request line.
1014 freez(*request_line);
1015 *request_line = strdup(http->gpc);
1016 string_append(request_line, " ");
1018 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1020 string_append(request_line, http->url);
1024 string_append(request_line, http->path);
1026 string_append(request_line, " ");
1027 string_append(request_line, http->version);
1029 if (*request_line == NULL)
1031 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1033 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1037 /*********************************************************************
1039 * Function : change_request_destination
1041 * Description : Parse a (rewritten) request line and regenerate
1042 * the http request data.
1045 * 1 : csp = Current client state (buffers, headers, etc...)
1047 * Returns : Forwards the parse_http_request() return code.
1048 * Terminates in case of memory problems.
1050 *********************************************************************/
1051 static jb_err change_request_destination(struct client_state *csp)
1053 struct http_request *http = csp->http;
1056 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1057 csp->headers->first->str);
1058 free_http_request(http);
1059 err = parse_http_request(csp->headers->first->str, http);
1060 if (JB_ERR_OK != err)
1062 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1063 jb_err_to_string(err));
1070 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1071 /*********************************************************************
1073 * Function : server_response_is_complete
1075 * Description : Determines whether we should stop reading
1076 * from the server socket.
1079 * 1 : csp = Current client state (buffers, headers, etc...)
1080 * 2 : content_length = Length of content received so far.
1082 * Returns : TRUE if the response is complete,
1085 *********************************************************************/
1086 static int server_response_is_complete(struct client_state *csp,
1087 unsigned long long content_length)
1089 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1091 if (!strcmpic(csp->http->gpc, "HEAD"))
1094 * "HEAD" implies no body, we are thus expecting
1095 * no content. XXX: incomplete "list" of methods?
1097 csp->expected_content_length = 0;
1098 content_length_known = TRUE;
1099 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1102 if (csp->http->status == 204 || csp->http->status == 304)
1105 * Expect no body. XXX: incomplete "list" of status codes?
1107 csp->expected_content_length = 0;
1108 content_length_known = TRUE;
1109 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1112 return (content_length_known && ((0 == csp->expected_content_length)
1113 || (csp->expected_content_length <= content_length)));
1117 #ifdef FEATURE_CONNECTION_SHARING
1118 /*********************************************************************
1120 * Function : wait_for_alive_connections
1122 * Description : Waits for alive connections to timeout.
1128 *********************************************************************/
1129 static void wait_for_alive_connections(void)
1131 int connections_alive = close_unusable_connections();
1133 while (0 < connections_alive)
1135 log_error(LOG_LEVEL_CONNECT,
1136 "Waiting for %d connections to timeout.",
1139 connections_alive = close_unusable_connections();
1142 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1145 #endif /* def FEATURE_CONNECTION_SHARING */
1148 /*********************************************************************
1150 * Function : save_connection_destination
1152 * Description : Remembers a connection for reuse later on.
1155 * 1 : sfd = Open socket to remember.
1156 * 2 : http = The destination for the connection.
1157 * 3 : fwd = The forwarder settings used.
1158 * 4 : server_connection = storage.
1162 *********************************************************************/
1163 void save_connection_destination(jb_socket sfd,
1164 const struct http_request *http,
1165 const struct forward_spec *fwd,
1166 struct reusable_connection *server_connection)
1168 assert(sfd != JB_INVALID_SOCKET);
1169 assert(NULL != http->host);
1171 server_connection->sfd = sfd;
1172 server_connection->host = strdup_or_die(http->host);
1173 server_connection->port = http->port;
1175 assert(NULL != fwd);
1176 assert(server_connection->gateway_host == NULL);
1177 assert(server_connection->gateway_port == 0);
1178 assert(server_connection->forwarder_type == 0);
1179 assert(server_connection->forward_host == NULL);
1180 assert(server_connection->forward_port == 0);
1182 server_connection->forwarder_type = fwd->type;
1183 if (NULL != fwd->gateway_host)
1185 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1189 server_connection->gateway_host = NULL;
1191 server_connection->gateway_port = fwd->gateway_port;
1193 if (NULL != fwd->forward_host)
1195 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1199 server_connection->forward_host = NULL;
1201 server_connection->forward_port = fwd->forward_port;
1205 /*********************************************************************
1207 * Function : verify_request_length
1209 * Description : Checks if we already got the whole client requests
1210 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1213 * Data that doesn't belong to the current request is
1214 * either thrown away to let the client retry on a clean
1215 * socket, or stashed to be dealt with after the current
1216 * request is served.
1219 * 1 : csp = Current client state (buffers, headers, etc...)
1223 *********************************************************************/
1224 static void verify_request_length(struct client_state *csp)
1226 unsigned long long buffered_request_bytes =
1227 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1229 if ((csp->expected_client_content_length != 0)
1230 && (buffered_request_bytes != 0))
1232 if (csp->expected_client_content_length >= buffered_request_bytes)
1234 csp->expected_client_content_length -= buffered_request_bytes;
1235 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1236 "to account for the %llu ones we already got.",
1237 csp->expected_client_content_length, buffered_request_bytes);
1241 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1242 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1243 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1244 "Marking the server socket tainted after throwing %llu bytes away.",
1245 buffered_request_bytes - csp->expected_client_content_length);
1246 csp->expected_client_content_length = 0;
1247 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1250 if (csp->expected_client_content_length == 0)
1252 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1256 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1257 && ((csp->client_iob->cur < csp->client_iob->eod)
1258 || (csp->expected_client_content_length != 0)))
1260 if (strcmpic(csp->http->gpc, "GET")
1261 && strcmpic(csp->http->gpc, "HEAD")
1262 && strcmpic(csp->http->gpc, "TRACE")
1263 && strcmpic(csp->http->gpc, "OPTIONS")
1264 && strcmpic(csp->http->gpc, "DELETE"))
1266 /* XXX: this is an incomplete hack */
1267 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1268 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1272 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1274 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1276 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1277 log_error(LOG_LEVEL_CONNECT,
1278 "Possible pipeline attempt detected. The connection will not "
1279 "be kept alive and we will only serve the first request.");
1280 /* Nuke the pipelined requests from orbit, just to be sure. */
1281 clear_iob(csp->client_iob);
1286 * Keep the pipelined data around for now, we'll deal with
1287 * it once we're done serving the current request.
1289 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1290 assert(csp->client_iob->eod >= csp->client_iob->cur);
1291 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1292 "%d bytes of pipelined data received.",
1293 (int)(csp->client_iob->eod - csp->client_iob->cur));
1299 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1300 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1303 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1306 /*********************************************************************
1308 * Function : mark_server_socket_tainted
1310 * Description : Makes sure we don't reuse a server socket
1311 * (if we didn't read everything the server sent
1312 * us reusing the socket would lead to garbage).
1315 * 1 : csp = Current client state (buffers, headers, etc...)
1319 *********************************************************************/
1320 static void mark_server_socket_tainted(struct client_state *csp)
1323 * For consistency we always mark the server socket
1324 * tainted, however, to reduce the log noise we only
1325 * emit a log message if the server socket could have
1326 * actually been reused.
1328 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1329 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1331 log_error(LOG_LEVEL_CONNECT,
1332 "Marking the server socket %d tainted.",
1333 csp->server_connection.sfd);
1335 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1338 /*********************************************************************
1340 * Function : get_request_line
1342 * Description : Read the client request line.
1345 * 1 : csp = Current client state (buffers, headers, etc...)
1347 * Returns : Pointer to request line or NULL in case of errors.
1349 *********************************************************************/
1350 static char *get_request_line(struct client_state *csp)
1352 char buf[BUFFER_SIZE];
1353 char *request_line = NULL;
1356 memset(buf, 0, sizeof(buf));
1358 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1361 * If there are multiple pipelined requests waiting,
1362 * the flag will be set again once the next request
1365 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1367 request_line = get_header(csp->client_iob);
1368 if ((NULL != request_line) && ('\0' != *request_line))
1370 return request_line;
1374 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1375 "received yet. Continuing reading from %d.", csp->cfd);
1383 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1385 !data_is_available(csp->cfd, csp->config->socket_timeout)
1388 if (socket_is_still_alive(csp->cfd))
1390 log_error(LOG_LEVEL_CONNECT,
1391 "No request line on socket %d received in time. Timeout: %d.",
1392 csp->cfd, csp->config->socket_timeout);
1393 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1394 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1395 get_write_delay(csp));
1399 log_error(LOG_LEVEL_CONNECT,
1400 "The client side of the connection on socket %d got "
1401 "closed without sending a complete request line.", csp->cfd);
1406 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1408 if (len <= 0) return NULL;
1411 * If there is no memory left for buffering the
1412 * request, there is nothing we can do but hang up
1414 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1419 request_line = get_header(csp->client_iob);
1421 } while ((NULL != request_line) && ('\0' == *request_line));
1423 return request_line;
1429 CHUNK_STATUS_MISSING_DATA,
1430 CHUNK_STATUS_BODY_COMPLETE,
1431 CHUNK_STATUS_PARSE_ERROR
1435 /*********************************************************************
1437 * Function : chunked_body_is_complete
1439 * Description : Figures out whether or not a chunked body is complete.
1441 * Currently it always starts at the beginning of the
1442 * buffer which is somewhat wasteful and prevents Privoxy
1443 * from starting to forward the correctly parsed chunks
1444 * as soon as theoretically possible.
1446 * Should be modified to work with a common buffer,
1447 * and allow the caller to skip already parsed chunks.
1449 * This would allow the function to be used for unbuffered
1450 * response bodies as well.
1453 * 1 : iob = Buffer with the body to check.
1454 * 2 : length = Length of complete body
1456 * Returns : Enum with the result of the check.
1458 *********************************************************************/
1459 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1461 unsigned int chunksize;
1467 * We need at least a single digit, followed by "\r\n",
1468 * followed by an unknown amount of data, followed by "\r\n".
1470 if (p + 5 > iob->eod)
1472 return CHUNK_STATUS_MISSING_DATA;
1474 if (sscanf(p, "%x", &chunksize) != 1)
1476 return CHUNK_STATUS_PARSE_ERROR;
1480 * We want at least a single digit, followed by "\r\n",
1481 * followed by the specified amount of data, followed by "\r\n".
1483 if (p + chunksize + 5 > iob->eod)
1485 return CHUNK_STATUS_MISSING_DATA;
1488 /* Skip chunk-size. */
1489 p = strstr(p, "\r\n");
1492 return CHUNK_STATUS_PARSE_ERROR;
1494 /* Move beyond the chunkdata. */
1497 /* There should be another "\r\n" to skip */
1498 if (memcmp(p, "\r\n", 2))
1500 return CHUNK_STATUS_PARSE_ERROR;
1503 } while (chunksize > 0U);
1505 *length = (size_t)(p - iob->cur);
1506 assert(*length <= (size_t)(iob->eod - iob->cur));
1507 assert(p <= iob->eod);
1509 return CHUNK_STATUS_BODY_COMPLETE;
1514 /*********************************************************************
1516 * Function : receive_chunked_client_request_body
1518 * Description : Read the chunk-encoded client request body.
1519 * Failures are dealt with.
1522 * 1 : csp = Current client state (buffers, headers, etc...)
1524 * Returns : JB_ERR_OK or JB_ERR_PARSE
1526 *********************************************************************/
1527 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1530 enum chunk_status status;
1532 while (CHUNK_STATUS_MISSING_DATA ==
1533 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1535 char buf[BUFFER_SIZE];
1538 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1540 log_error(LOG_LEVEL_ERROR,
1541 "Timeout while waiting for the client body.");
1544 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1547 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1550 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1555 if (status != CHUNK_STATUS_BODY_COMPLETE)
1557 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1558 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1559 log_error(LOG_LEVEL_CLF,
1560 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1561 return JB_ERR_PARSE;
1563 log_error(LOG_LEVEL_CONNECT,
1564 "Chunked client body completely read. Length: %d", body_length);
1565 csp->expected_client_content_length = body_length;
1573 /*********************************************************************
1575 * Function : fuzz_chunked_transfer_encoding
1577 * Description : Treat the fuzzed input as chunked transfer encoding
1578 * to check and dechunk.
1581 * 1 : csp = Used to store the data.
1582 * 2 : fuzz_input_file = File to read the input from.
1584 * Returns : Result of dechunking
1586 *********************************************************************/
1587 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1590 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1591 enum chunk_status status;
1593 status = chunked_body_is_complete(csp->iob, &length);
1594 if (CHUNK_STATUS_BODY_COMPLETE != status)
1596 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1599 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1604 /*********************************************************************
1606 * Function : fuzz_client_request
1608 * Description : Try to get a client request from the fuzzed input.
1611 * 1 : csp = Current client state (buffers, headers, etc...)
1612 * 2 : fuzz_input_file = File to read the input from.
1614 * Returns : Result of fuzzing.
1616 *********************************************************************/
1617 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1622 csp->ip_addr_str = "fuzzer";
1624 if (strcmp(fuzz_input_file, "-") != 0)
1626 log_error(LOG_LEVEL_FATAL,
1627 "Fuzzed client requests can currently only be read from stdin (-).");
1629 err = receive_client_request(csp);
1630 if (err != JB_ERR_OK)
1634 err = parse_client_request(csp);
1635 if (err != JB_ERR_OK)
1643 #endif /* def FUZZ */
1646 #ifdef FEATURE_FORCE_LOAD
1647 /*********************************************************************
1649 * Function : force_required
1651 * Description : Checks a request line to see if it contains
1652 * the FORCE_PREFIX. If it does, it is removed
1653 * unless enforcing requests has beend disabled.
1656 * 1 : request_line = HTTP request line
1658 * Returns : TRUE if force is required, FALSE otherwise.
1660 *********************************************************************/
1661 static int force_required(const struct client_state *csp, char *request_line)
1665 p = strstr(request_line, "http://");
1669 p += strlen("http://");
1673 /* Intercepted request usually don't specify the protocol. */
1677 /* Go to the beginning of the path */
1682 * If the path is missing the request line is invalid and we
1683 * are done here. The client-visible rejection happens later on.
1688 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1690 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1692 /* XXX: Should clean more carefully */
1693 strclean(request_line, FORCE_PREFIX);
1694 log_error(LOG_LEVEL_FORCE,
1695 "Enforcing request: \"%s\".", request_line);
1699 log_error(LOG_LEVEL_FORCE,
1700 "Ignored force prefix in request: \"%s\".", request_line);
1706 #endif /* def FEATURE_FORCE_LOAD */
1709 /*********************************************************************
1711 * Function : receive_client_request
1713 * Description : Read the client's request (more precisely the
1714 * client headers) and answer it if necessary.
1717 * 1 : csp = Current client state (buffers, headers, etc...)
1719 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1721 *********************************************************************/
1722 static jb_err receive_client_request(struct client_state *csp)
1724 char buf[BUFFER_SIZE];
1727 struct http_request *http;
1731 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1732 struct list header_list;
1733 struct list *headers = &header_list;
1735 /* We don't care if the arriving data is a valid HTTP request or not. */
1736 csp->requests_received_total++;
1740 memset(buf, 0, sizeof(buf));
1742 req = get_request_line(csp);
1745 mark_server_socket_tainted(csp);
1746 return JB_ERR_PARSE;
1748 assert(*req != '\0');
1750 if (client_protocol_is_unsupported(csp, req))
1752 return JB_ERR_PARSE;
1755 #ifdef FEATURE_FORCE_LOAD
1756 if (force_required(csp, req))
1758 csp->flags |= CSP_FLAG_FORCED;
1760 #endif /* def FEATURE_FORCE_LOAD */
1762 err = parse_http_request(req, http);
1764 if (JB_ERR_OK != err)
1766 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1767 get_write_delay(csp));
1768 /* XXX: Use correct size */
1769 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1770 log_error(LOG_LEVEL_ERROR,
1771 "Couldn't parse request line received from %s: %s",
1772 csp->ip_addr_str, jb_err_to_string(err));
1774 free_http_request(http);
1775 return JB_ERR_PARSE;
1778 /* grab the rest of the client's headers */
1782 p = get_header(csp->client_iob);
1786 /* There are no additional headers to read. */
1793 * We didn't receive a complete header
1794 * line yet, get the rest of it.
1796 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1798 log_error(LOG_LEVEL_ERROR,
1799 "Stopped grabbing the client headers.");
1800 destroy_list(headers);
1801 return JB_ERR_PARSE;
1804 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1807 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1808 destroy_list(headers);
1809 return JB_ERR_PARSE;
1812 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1815 * If there is no memory left for buffering the
1816 * request, there is nothing we can do but hang up
1818 destroy_list(headers);
1819 return JB_ERR_MEMORY;
1824 if (!strncmpic(p, "Transfer-Encoding:", 18))
1827 * XXX: should be called through sed()
1828 * but currently can't.
1830 client_transfer_encoding(csp, &p);
1833 * We were able to read a complete
1834 * header and can finally enlist it.
1841 if (http->host == NULL)
1844 * If we still don't know the request destination,
1845 * the request is invalid or the client uses
1846 * Privoxy without its knowledge.
1848 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1851 * Our attempts to get the request destination
1852 * elsewhere failed or Privoxy is configured
1853 * to only accept proxy requests.
1855 * An error response has already been send
1856 * and we're done here.
1858 return JB_ERR_PARSE;
1862 #ifdef FEATURE_CLIENT_TAGS
1863 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1864 set_client_address(csp, headers);
1865 get_tag_list_for_client(csp->client_tags, csp->client_address);
1869 * Determine the actions for this URL
1871 #ifdef FEATURE_TOGGLE
1872 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1874 /* Most compatible set of actions (i.e. none) */
1875 init_current_action(csp->action);
1878 #endif /* ndef FEATURE_TOGGLE */
1880 get_url_actions(csp, http);
1883 enlist(csp->headers, http->cmd);
1885 /* Append the previously read headers */
1886 err = list_append_list_unique(csp->headers, headers);
1887 destroy_list(headers);
1894 /*********************************************************************
1896 * Function : parse_client_request
1898 * Description : Parses the client's request and decides what to do
1901 * Note that since we're not using select() we could get
1902 * blocked here if a client connected, then didn't say
1906 * 1 : csp = Current client state (buffers, headers, etc...)
1908 * Returns : JB_ERR_OK or JB_ERR_PARSE
1910 *********************************************************************/
1911 static jb_err parse_client_request(struct client_state *csp)
1913 struct http_request *http = csp->http;
1916 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1917 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1918 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1919 && (csp->http->ssl == 0))
1921 /* Assume persistence until further notice */
1922 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1925 if (csp->http->ssl == 0)
1928 * This whole block belongs to chat() but currently
1929 * has to be executed before sed().
1931 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1933 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1935 return JB_ERR_PARSE;
1940 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1942 verify_request_length(csp);
1946 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1948 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1950 err = sed(csp, FILTER_CLIENT_HEADERS);
1951 if (JB_ERR_OK != err)
1953 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1955 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1956 csp->ip_addr_str, csp->http->cmd);
1957 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1958 return JB_ERR_PARSE;
1960 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1962 /* Check request line for rewrites. */
1963 if ((NULL == csp->headers->first->str)
1964 || (strcmp(http->cmd, csp->headers->first->str) &&
1965 (JB_ERR_OK != change_request_destination(csp))))
1968 * A header filter broke the request line - bail out.
1970 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1971 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1972 /* XXX: Use correct size */
1973 log_error(LOG_LEVEL_CLF,
1974 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1975 log_error(LOG_LEVEL_ERROR,
1976 "Invalid request line after applying header filters.");
1977 free_http_request(http);
1979 return JB_ERR_PARSE;
1982 if (client_has_unsupported_expectations(csp))
1984 return JB_ERR_PARSE;
1992 /*********************************************************************
1994 * Function : send_http_request
1996 * Description : Sends the HTTP headers from the client request
1997 * and all the body data that has already been received.
2000 * 1 : csp = Current client state (buffers, headers, etc...)
2002 * Returns : 0 on success, anything else is an error.
2004 *********************************************************************/
2005 static int send_http_request(struct client_state *csp)
2010 hdr = list_to_text(csp->headers);
2013 /* FIXME Should handle error properly */
2014 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2016 list_remove_all(csp->headers);
2019 * Write the client's (modified) header to the server
2020 * (along with anything else that may be in the buffer)
2022 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2027 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2028 csp->http->hostport);
2030 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2031 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2034 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2035 csp->http->hostport);
2038 return write_failure;
2043 #ifdef FEATURE_HTTPS_INSPECTION
2044 /*********************************************************************
2046 * Function : receive_and_send_encrypted_post_data
2048 * Description : Reads remaining POST data from the client and sends
2052 * 1 : csp = Current client state (buffers, headers, etc...)
2054 * Returns : 0 on success, anything else is an error.
2056 *********************************************************************/
2057 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2059 int content_length_known = csp->expected_client_content_length != 0;
2061 while (is_ssl_pending(&(csp->ssl_client_attr))
2062 || (content_length_known && csp->expected_client_content_length != 0))
2064 unsigned char buf[BUFFER_SIZE];
2066 int max_bytes_to_read = sizeof(buf);
2068 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2070 max_bytes_to_read = (int)csp->expected_client_content_length;
2072 log_error(LOG_LEVEL_CONNECT,
2073 "Waiting for up to %d bytes of POST data from the client.",
2075 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2076 (unsigned)max_bytes_to_read);
2083 /* XXX: Does this actually happen? */
2086 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted POST data",
2088 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2093 if (csp->expected_client_content_length != 0)
2095 if (csp->expected_client_content_length >= len)
2097 csp->expected_client_content_length -= (unsigned)len;
2099 if (csp->expected_client_content_length == 0)
2101 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2107 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted POST data");
2114 /*********************************************************************
2116 * Function : send_https_request
2118 * Description : Sends the HTTP headers from the client request
2119 * and all the body data that has already been received.
2122 * 1 : csp = Current client state (buffers, headers, etc...)
2124 * Returns : 0 on success, anything else is an error.
2126 *********************************************************************/
2127 static int send_https_request(struct client_state *csp)
2133 hdr = list_to_text(csp->https_headers);
2136 /* FIXME Should handle error properly */
2137 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2139 list_remove_all(csp->https_headers);
2142 * Write the client's (modified) header to the server
2143 * (along with anything else that may be in the buffer)
2145 ret = ssl_send_data(&(csp->ssl_server_attr),
2146 (const unsigned char *)hdr, strlen(hdr));
2151 log_error(LOG_LEVEL_CONNECT,
2152 "Failed sending encrypted request headers to: %s: %E",
2153 csp->http->hostport);
2154 mark_server_socket_tainted(csp);
2158 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2159 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2160 csp->client_iob)) < 0))
2162 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2163 csp->http->hostport);
2168 if (csp->expected_client_content_length != 0)
2170 if (csp->expected_client_content_length < flushed)
2172 log_error(LOG_LEVEL_ERROR,
2173 "Flushed %d bytes of request body while only expecting %llu",
2174 flushed, csp->expected_client_content_length);
2175 csp->expected_client_content_length = 0;
2179 log_error(LOG_LEVEL_CONNECT,
2180 "Flushed %d bytes of request body while expecting %llu",
2181 flushed, csp->expected_client_content_length);
2182 csp->expected_client_content_length -= (unsigned)flushed;
2183 if (receive_and_send_encrypted_post_data(csp))
2191 log_error(LOG_LEVEL_CONNECT,
2192 "Flushed %d bytes of request body", flushed);
2196 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2203 /*********************************************************************
2205 * Function : receive_encrypted_request
2207 * Description : Receives an encrypted request.
2210 * 1 : csp = Current client state (buffers, headers, etc...)
2212 * Returns : JB_ERR_OK on success,
2213 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2215 *********************************************************************/
2216 static jb_err receive_encrypted_request(struct client_state *csp)
2218 char buf[BUFFER_SIZE];
2224 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2225 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2226 !data_is_available(csp->cfd, csp->config->socket_timeout))
2228 log_error(LOG_LEVEL_CONNECT,
2229 "Socket %d timed out while waiting for client headers", csp->cfd);
2230 return JB_ERR_PARSE;
2232 len = ssl_recv_data(&(csp->ssl_client_attr),
2233 (unsigned char *)buf, sizeof(buf));
2236 return JB_ERR_PARSE;
2238 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2240 return JB_ERR_MEMORY;
2242 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2243 } while (p == NULL);
2245 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2251 /*********************************************************************
2253 * Function : process_encrypted_request
2255 * Description : Receives and parses an encrypted request.
2258 * 1 : csp = Current client state (buffers, headers, etc...)
2260 * Returns : JB_ERR_OK on success,
2261 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2263 *********************************************************************/
2264 static jb_err process_encrypted_request(struct client_state *csp)
2269 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2270 struct list header_list;
2271 struct list *headers = &header_list;
2273 err = receive_encrypted_request(csp);
2274 if (err != JB_ERR_OK)
2276 /* XXX: Also used for JB_ERR_MEMORY */
2277 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2278 jb_err_to_string(err));
2279 ssl_send_data_delayed(&(csp->ssl_client_attr),
2280 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2284 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2285 request_line = get_header(csp->client_iob);
2286 if (request_line == NULL)
2288 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2289 ssl_send_data_delayed(&(csp->ssl_client_attr),
2290 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2291 return JB_ERR_PARSE;
2293 assert(*request_line != '\0');
2295 if (client_protocol_is_unsupported(csp, request_line))
2298 * If the protocol is unsupported we're done here.
2299 * client_protocol_is_unsupported() took care of sending
2300 * the error response and logging the error message.
2302 return JB_ERR_PARSE;
2305 #ifdef FEATURE_FORCE_LOAD
2306 if (force_required(csp, request_line))
2308 csp->flags |= CSP_FLAG_FORCED;
2310 #endif /* def FEATURE_FORCE_LOAD */
2312 free_http_request(csp->http);
2314 err = parse_http_request(request_line, csp->http);
2315 /* XXX: Restore ssl setting. This is ugly */
2316 csp->http->client_ssl = 1;
2317 csp->http->server_ssl = 1;
2319 freez(request_line);
2320 if (JB_ERR_OK != err)
2322 ssl_send_data_delayed(&(csp->ssl_client_attr),
2323 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2324 /* XXX: Use correct size */
2325 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2326 log_error(LOG_LEVEL_ERROR,
2327 "Couldn't parse request line received from %s: %s",
2328 csp->ip_addr_str, jb_err_to_string(err));
2330 free_http_request(csp->http);
2331 return JB_ERR_PARSE;
2334 /* Parse the rest of the client's headers. */
2338 p = get_header(csp->client_iob);
2342 /* There are no additional headers to read. */
2349 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2352 * Our attempts to get the request destination
2355 log_error(LOG_LEVEL_ERROR,
2356 "Failed to get the encrypted request destination");
2357 ssl_send_data_delayed(&(csp->ssl_client_attr),
2358 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2359 return JB_ERR_PARSE;
2362 /* Split the domain we just got for pattern matching */
2363 init_domain_components(csp->http);
2365 #ifdef FEATURE_TOGGLE
2366 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2369 /* Determine the actions for this URL */
2370 get_url_actions(csp, csp->http);
2373 enlist(csp->https_headers, csp->http->cmd);
2375 /* Append the previously read headers */
2376 err = list_append_list_unique(csp->https_headers, headers);
2377 destroy_list(headers);
2378 if (JB_ERR_OK != err)
2380 /* XXX: Send error message */
2384 /* XXX: Work around crash */
2385 csp->error_message = NULL;
2387 /* XXX: Why do this here? */
2390 err = sed_https(csp);
2391 if (JB_ERR_OK != err)
2393 ssl_send_data_delayed(&(csp->ssl_client_attr),
2394 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2395 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2397 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2398 csp->ip_addr_str, csp->http->cmd);
2399 return JB_ERR_PARSE;
2402 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2403 log_applied_actions(csp->action);
2404 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2411 /*********************************************************************
2413 * Function : cgi_page_requested
2415 * Description : Checks if a request is for an internal CGI page.
2418 * 1 : host = The host requested by the client.
2420 * Returns : 1 if a CGI page has been requested, 0 otherwise
2422 *********************************************************************/
2423 static int cgi_page_requested(const char *host)
2425 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2426 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2427 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2428 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2440 /*********************************************************************
2442 * Function : handle_established_connection
2444 * Description : Shuffle data between client and server once the
2445 * connection has been established.
2448 * 1 : csp = Current client state (buffers, headers, etc...)
2450 * Returns : Nothing.
2452 *********************************************************************/
2453 static void handle_established_connection(struct client_state *csp)
2459 struct pollfd poll_fds[2];
2463 struct timeval timeout;
2466 int ms_iis5_hack = 0;
2467 unsigned long long byte_count = 0;
2468 struct http_request *http;
2469 long len = 0; /* for buffer sizes (and negative error codes) */
2470 int buffer_and_filter_content = 0;
2471 unsigned int write_delay;
2472 #ifdef FEATURE_HTTPS_INSPECTION
2474 int use_ssl_tunnel = 0;
2475 csp->dont_verify_certificate = 0;
2477 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2479 /* Pass encrypted content without filtering. */
2484 /* Skeleton for HTTP response, if we should intercept the request */
2485 struct http_response *rsp;
2486 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2487 int watch_client_socket;
2490 csp->receive_buffer_size = csp->config->receive_buffer_size;
2491 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2492 if (csp->receive_buffer == NULL)
2494 log_error(LOG_LEVEL_ERROR,
2495 "Out of memory. Failed to allocate the receive buffer.");
2496 rsp = cgi_error_memory();
2497 send_crunch_response(csp, rsp);
2504 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2505 csp->cfd : csp->server_connection.sfd;
2508 /* pass data between the client and server
2509 * until one or the other shuts down the connection.
2514 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2515 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2517 write_delay = get_write_delay(csp);
2524 * FD_ZERO here seems to point to an errant macro which crashes.
2525 * So do this by hand for now...
2527 memset(&rfds,0x00,sizeof(fd_set));
2531 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2532 if (!watch_client_socket)
2534 maxfd = csp->server_connection.sfd;
2537 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2539 FD_SET(csp->cfd, &rfds);
2542 FD_SET(csp->server_connection.sfd, &rfds);
2543 #endif /* ndef HAVE_POLL */
2545 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2546 if ((csp->flags & CSP_FLAG_CHUNKED)
2547 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2548 && ((csp->iob->eod - csp->iob->cur) >= 5)
2549 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2552 * XXX: This check should be obsolete now,
2553 * but let's wait a while to be sure.
2555 log_error(LOG_LEVEL_CONNECT,
2556 "Looks like we got the last chunk together with "
2557 "the server headers but didn't detect it earlier. "
2558 "We better stop reading.");
2559 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2560 csp->expected_content_length = byte_count;
2561 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2563 if (server_body && server_response_is_complete(csp, byte_count))
2565 if (csp->expected_content_length == byte_count)
2567 log_error(LOG_LEVEL_CONNECT,
2568 "Done reading from server. Content length: %llu as expected. "
2569 "Bytes most recently read: %d.",
2574 log_error(LOG_LEVEL_CONNECT,
2575 "Done reading from server. Expected content length: %llu. "
2576 "Actual content length: %llu. Bytes most recently read: %d.",
2577 csp->expected_content_length, byte_count, len);
2581 * XXX: Should not jump around, handle_established_connection()
2582 * is complicated enough already.
2586 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2589 poll_fds[0].fd = csp->cfd;
2590 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2591 if (!watch_client_socket)
2594 * Ignore incoming data, but still watch out
2595 * for disconnects etc. These flags are always
2596 * implied anyway but explicitly setting them
2599 poll_fds[0].events = POLLERR|POLLHUP;
2604 poll_fds[0].events = POLLIN;
2606 poll_fds[1].fd = csp->server_connection.sfd;
2607 poll_fds[1].events = POLLIN;
2608 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2610 timeout.tv_sec = csp->config->socket_timeout;
2611 timeout.tv_usec = 0;
2612 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
2613 #endif /* def HAVE_POLL */
2615 /*server or client not responding in timeout */
2618 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2619 csp->config->socket_timeout, http->url);
2620 if ((byte_count == 0) && (http->ssl == 0))
2622 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2624 mark_server_socket_tainted(csp);
2625 #ifdef FEATURE_HTTPS_INSPECTION
2626 close_client_and_server_ssl_connections(csp);
2633 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2635 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2637 mark_server_socket_tainted(csp);
2638 #ifdef FEATURE_HTTPS_INSPECTION
2639 close_client_and_server_ssl_connections(csp);
2645 * This is the body of the browser's request,
2646 * just read and write it.
2648 * Receives data from browser and sends it to server
2650 * XXX: Make sure the client doesn't use pipelining
2651 * behind Privoxy's back.
2654 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2656 log_error(LOG_LEVEL_CONNECT,
2657 "The client socket %d has become unusable while "
2658 "the server socket %d is still open.",
2659 csp->cfd, csp->server_connection.sfd);
2660 mark_server_socket_tainted(csp);
2664 if (poll_fds[0].revents != 0)
2666 if (FD_ISSET(csp->cfd, &rfds))
2667 #endif /* def HAVE_POLL*/
2669 int max_bytes_to_read = (int)csp->receive_buffer_size;
2671 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2672 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2674 if (data_is_available(csp->cfd, 0))
2677 * If the next request is already waiting, we have
2678 * to stop select()ing the client socket. Otherwise
2679 * we would always return right away and get nothing
2682 watch_client_socket = 0;
2683 log_error(LOG_LEVEL_CONNECT,
2684 "Stop watching client socket %d. "
2685 "There's already another request waiting.",
2690 * If the client socket is set, but there's no data
2691 * available on the socket, the client went fishing
2692 * and continuing talking to the server makes no sense.
2694 log_error(LOG_LEVEL_CONNECT,
2695 "The client closed socket %d while "
2696 "the server socket %d is still open.",
2697 csp->cfd, csp->server_connection.sfd);
2698 mark_server_socket_tainted(csp);
2701 if (csp->expected_client_content_length != 0)
2703 if (csp->expected_client_content_length < csp->receive_buffer_size)
2705 max_bytes_to_read = (int)csp->expected_client_content_length;
2707 log_error(LOG_LEVEL_CONNECT,
2708 "Waiting for up to %d bytes from the client.",
2711 assert(max_bytes_to_read <= csp->receive_buffer_size);
2712 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2714 #ifdef FEATURE_HTTPS_INSPECTION
2715 if (client_use_ssl(csp))
2717 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
2721 #endif /* def FEATURE_HTTPS_INSPECTION */
2723 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2727 /* XXX: not sure if this is necessary. */
2728 mark_server_socket_tainted(csp);
2729 break; /* "game over, man" */
2732 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2733 if (csp->expected_client_content_length != 0)
2735 assert(len <= max_bytes_to_read);
2736 csp->expected_client_content_length -= (unsigned)len;
2737 log_error(LOG_LEVEL_CONNECT,
2738 "Expected client content length set to %llu "
2739 "after reading %d bytes.",
2740 csp->expected_client_content_length, len);
2741 if (csp->expected_client_content_length == 0)
2743 log_error(LOG_LEVEL_CONNECT,
2744 "Done reading from the client.");
2745 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2748 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2750 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2752 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2753 mark_server_socket_tainted(csp);
2761 * The server wants to talk. It could be the header or the body.
2762 * If `hdr' is null, then it's the header otherwise it's the body.
2763 * FIXME: Does `hdr' really mean `host'? No.
2766 if (poll_fds[1].revents != 0)
2768 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2769 #endif /* HAVE_POLL */
2771 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2773 * If we are buffering content, we don't want to eat up to
2774 * buffer-limit bytes if the client no longer cares about them.
2775 * If we aren't buffering, however, a dead client socket will be
2776 * noticed pretty much right away anyway, so we can reduce the
2777 * overhead by skipping the check.
2779 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2782 log_error(LOG_LEVEL_CONNECT,
2783 "The server still wants to talk, but the client may already have hung up on us.");
2785 log_error(LOG_LEVEL_CONNECT,
2786 "The server still wants to talk, but the client hung up on us.");
2787 mark_server_socket_tainted(csp);
2788 #ifdef FEATURE_HTTPS_INSPECTION
2789 close_client_and_server_ssl_connections(csp);
2792 #endif /* def _WIN32 */
2794 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2796 #ifdef FEATURE_HTTPS_INSPECTION
2798 * Reading data from standard or secured connection (HTTP/HTTPS)
2800 if (server_use_ssl(csp))
2802 len = ssl_recv_data(&(csp->ssl_server_attr),
2803 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
2808 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
2809 (int)csp->receive_buffer_size);
2814 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2816 if ((http->ssl && (csp->fwd == NULL))
2817 #ifdef FEATURE_HTTPS_INSPECTION
2823 * Just hang up. We already confirmed the client's CONNECT
2824 * request with status code 200 and unencrypted content is
2825 * no longer welcome.
2827 log_error(LOG_LEVEL_ERROR,
2828 "CONNECT already confirmed. Unable to tell the client about the problem.");
2831 else if (byte_count)
2834 * Just hang up. We already transmitted the original headers
2835 * and parts of the original content and therefore missed the
2836 * chance to send an error message (without risking data corruption).
2838 * XXX: we could retry with a fancy range request here.
2840 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2841 "Unable to tell the client about the problem.");
2842 mark_server_socket_tainted(csp);
2843 #ifdef FEATURE_HTTPS_INSPECTION
2844 close_client_and_server_ssl_connections(csp);
2849 * XXX: Consider handling the cases above the same.
2851 mark_server_socket_tainted(csp);
2855 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2856 if (csp->flags & CSP_FLAG_CHUNKED)
2858 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2860 /* XXX: this is a temporary hack */
2861 log_error(LOG_LEVEL_CONNECT,
2862 "Looks like we reached the end of the last chunk. "
2863 "We better stop reading.");
2864 csp->expected_content_length = byte_count + (unsigned long long)len;
2865 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2869 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2872 * This is guaranteed by allocating with zalloc_or_die()
2873 * and never (intentionally) writing to the last byte.
2875 * csp->receive_buffer_size is the size of the part of the
2876 * buffer we intentionally write to, but we actually
2877 * allocated csp->receive_buffer_size+1 bytes so the assertion
2878 * stays within the allocated range.
2880 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2883 * Add a trailing zero to let be able to use string operations.
2884 * XXX: do we still need this with filter_popups gone?
2886 assert(len <= csp->receive_buffer_size);
2887 csp->receive_buffer[len] = '\0';
2890 * Normally, this would indicate that we've read
2891 * as much as the server has sent us and we can
2892 * close the client connection. However, Microsoft
2893 * in its wisdom has released IIS/5 with a bug that
2894 * prevents it from sending the trailing \r\n in
2895 * a 302 redirect header (and possibly other headers).
2896 * To work around this if we've haven't parsed
2897 * a full header we'll append a trailing \r\n
2898 * and see if this now generates a valid one.
2900 * This hack shouldn't have any impacts. If we've
2901 * already transmitted the header or if this is a
2902 * SSL connection, then we won't bother with this
2903 * hack. So we only work on partially received
2904 * headers. If we append a \r\n and this still
2905 * doesn't generate a valid header, then we won't
2906 * transmit anything to the client.
2911 if (server_body || (http->ssl
2912 #ifdef FEATURE_HTTPS_INSPECTION
2918 * If we have been buffering up the document,
2919 * now is the time to apply content modification
2920 * and send the result to the client.
2922 if (buffer_and_filter_content)
2924 p = execute_content_filters(csp);
2926 * If content filtering fails, use the original
2927 * buffer and length.
2928 * (see p != NULL ? p : csp->iob->cur below)
2932 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2934 #ifdef FEATURE_COMPRESSION
2935 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2936 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2938 char *compressed_content = compress_buffer(p,
2939 (size_t *)&csp->content_length, csp->config->compression_level);
2940 if (compressed_content != NULL)
2943 p = compressed_content;
2944 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2949 if (JB_ERR_OK != update_server_headers(csp))
2951 log_error(LOG_LEVEL_FATAL,
2952 "Failed to update server headers. after filtering.");
2955 hdr = list_to_text(csp->headers);
2958 /* FIXME Should handle error properly */
2959 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2962 #ifdef FEATURE_HTTPS_INSPECTION
2964 * Sending data with standard or secured connection (HTTP/HTTPS)
2966 if (client_use_ssl(csp))
2968 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
2969 (const unsigned char *)hdr, strlen(hdr),
2970 get_write_delay(csp)) < 0)
2971 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
2972 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
2973 csp->content_length, get_write_delay(csp)) < 0))
2975 log_error(LOG_LEVEL_ERROR, "write modified content to "
2976 "client over TLS/SSL failed");
2979 mark_server_socket_tainted(csp);
2980 close_client_and_server_ssl_connections(csp);
2985 #endif /* def FEATURE_HTTPS_INSPECTION */
2987 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
2988 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
2989 (size_t)csp->content_length, write_delay))
2991 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2994 mark_server_socket_tainted(csp);
3003 break; /* "game over, man" */
3007 * This is NOT the body, so
3008 * Let's pretend the server just sent us a blank line.
3010 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3011 len = (int)strlen(csp->receive_buffer);
3014 * Now, let the normal header parsing algorithm below do its
3015 * job. If it fails, we'll exit instead of continuing.
3022 * If we're in the body of the server document, just write it to
3023 * the client, unless we need to buffer the body for later
3024 * content-filtering.
3026 if (server_body || (http->ssl
3027 #ifdef FEATURE_HTTPS_INSPECTION
3032 if (buffer_and_filter_content)
3035 * If there is no memory left for buffering the content, or the buffer limit
3036 * has been reached, switch to non-filtering mode, i.e. make & write the
3037 * header, flush the iob and buf, and get out of the way.
3039 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3044 log_error(LOG_LEVEL_INFO,
3045 "Flushing header and buffers. Stepping back from filtering.");
3047 hdr = list_to_text(csp->headers);
3051 * Memory is too tight to even generate the header.
3052 * Send our static "Out-of-memory" page.
3054 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3055 rsp = cgi_error_memory();
3056 send_crunch_response(csp, rsp);
3057 mark_server_socket_tainted(csp);
3058 #ifdef FEATURE_HTTPS_INSPECTION
3059 close_client_and_server_ssl_connections(csp);
3063 hdrlen = strlen(hdr);
3065 #ifdef FEATURE_HTTPS_INSPECTION
3067 * Sending data with standard or secured connection (HTTP/HTTPS)
3069 if (client_use_ssl(csp))
3071 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3072 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3073 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3075 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3076 (const unsigned char *)csp->receive_buffer, (size_t)len,
3077 get_write_delay(csp)) < 0))
3079 log_error(LOG_LEVEL_CONNECT,
3080 "Flush header and buffers to client failed");
3082 mark_server_socket_tainted(csp);
3083 close_client_and_server_ssl_connections(csp);
3088 #endif /* def FEATURE_HTTPS_INSPECTION */
3090 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3091 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3092 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3095 log_error(LOG_LEVEL_CONNECT,
3096 "Flush header and buffers to client failed: %E");
3098 mark_server_socket_tainted(csp);
3104 * Reset the byte_count to the amount of bytes
3105 * we just flushed. len will be added a few lines below,
3106 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3108 byte_count = (unsigned long long)flushed;
3110 buffer_and_filter_content = 0;
3116 #ifdef FEATURE_HTTPS_INSPECTION
3118 * Sending data with standard or secured connection (HTTP/HTTPS)
3120 if (client_use_ssl(csp))
3122 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3123 (const unsigned char *)csp->receive_buffer, (size_t)len,
3124 get_write_delay(csp));
3127 log_error(LOG_LEVEL_ERROR,
3128 "Sending data to client failed");
3129 mark_server_socket_tainted(csp);
3130 close_client_and_server_ssl_connections(csp);
3135 #endif /* def FEATURE_HTTPS_INSPECTION */
3137 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3138 (size_t)len, write_delay))
3140 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3141 mark_server_socket_tainted(csp);
3146 byte_count += (unsigned long long)len;
3152 * We're still looking for the end of the server's header.
3153 * Buffer up the data we just read. If that fails, there's
3154 * little we can do but send our static out-of-memory page.
3156 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3158 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3159 rsp = cgi_error_memory();
3160 send_crunch_response(csp, rsp);
3161 mark_server_socket_tainted(csp);
3162 #ifdef FEATURE_HTTPS_INSPECTION
3163 close_client_and_server_ssl_connections(csp);
3168 /* Convert iob into something sed() can digest */
3169 if (JB_ERR_PARSE == get_server_headers(csp))
3174 * Well, we tried our MS IIS/5 hack and it didn't work.
3175 * The header is incomplete and there isn't anything
3176 * we can do about it.
3178 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3179 "Applying the MS IIS5 hack didn't help.");
3180 log_error(LOG_LEVEL_CLF,
3181 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3182 #ifdef FEATURE_HTTPS_INSPECTION
3184 * Sending data with standard or secured connection (HTTP/HTTPS)
3186 if (client_use_ssl(csp))
3188 ssl_send_data_delayed(&(csp->ssl_client_attr),
3189 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3190 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3193 #endif /* def FEATURE_HTTPS_INSPECTION */
3195 write_socket_delayed(csp->cfd,
3196 INVALID_SERVER_HEADERS_RESPONSE,
3197 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3199 mark_server_socket_tainted(csp);
3200 #ifdef FEATURE_HTTPS_INSPECTION
3201 close_client_and_server_ssl_connections(csp);
3208 * Since we have to wait for more from the server before
3209 * we can parse the headers we just continue here.
3211 log_error(LOG_LEVEL_CONNECT,
3212 "Continuing buffering server headers from socket %d. "
3213 "Bytes most recently read: %d.", csp->cfd, len);
3220 * Account for the content bytes we
3221 * might have gotten with the headers.
3223 assert(csp->iob->eod >= csp->iob->cur);
3224 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3227 /* Did we actually get anything? */
3228 if (NULL == csp->headers->first)
3230 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3232 log_error(LOG_LEVEL_ERROR,
3233 "No server or forwarder response received on socket %d. "
3234 "Closing client socket %d without sending data.",
3235 csp->server_connection.sfd, csp->cfd);
3236 log_error(LOG_LEVEL_CLF,
3237 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3241 log_error(LOG_LEVEL_ERROR,
3242 "No server or forwarder response received on socket %d.",
3243 csp->server_connection.sfd);
3244 send_crunch_response(csp, error_response(csp, "no-server-data"));
3246 free_http_request(http);
3247 mark_server_socket_tainted(csp);
3248 #ifdef FEATURE_HTTPS_INSPECTION
3249 close_client_and_server_ssl_connections(csp);
3254 if (!csp->headers->first->str)
3256 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3258 assert(csp->headers->first->str);
3260 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3261 strncmpic(csp->headers->first->str, "ICY", 3))
3264 * It doesn't look like a HTTP (or Shoutcast) response:
3265 * tell the client and log the problem.
3267 if (strlen(csp->headers->first->str) > 30)
3269 csp->headers->first->str[30] = '\0';
3271 log_error(LOG_LEVEL_ERROR,
3272 "Invalid server or forwarder response. Starts with: %s",
3273 csp->headers->first->str);
3274 log_error(LOG_LEVEL_CLF,
3275 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3276 #ifdef FEATURE_HTTPS_INSPECTION
3278 * Sending data with standard or secured connection (HTTP/HTTPS)
3280 if (client_use_ssl(csp))
3282 ssl_send_data_delayed(&(csp->ssl_client_attr),
3283 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3284 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3285 get_write_delay(csp));
3288 #endif /* def FEATURE_HTTPS_INSPECTION */
3290 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3291 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3293 free_http_request(http);
3294 mark_server_socket_tainted(csp);
3295 #ifdef FEATURE_HTTPS_INSPECTION
3296 close_client_and_server_ssl_connections(csp);
3302 * We have now received the entire server header,
3303 * filter it and send the result to the client
3305 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3307 log_error(LOG_LEVEL_CLF,
3308 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3309 #ifdef FEATURE_HTTPS_INSPECTION
3311 * Sending data with standard or secured connection (HTTP/HTTPS)
3313 if (client_use_ssl(csp))
3315 ssl_send_data_delayed(&(csp->ssl_client_attr),
3316 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3317 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3318 get_write_delay(csp));
3323 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3324 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3326 free_http_request(http);
3327 mark_server_socket_tainted(csp);
3328 #ifdef FEATURE_HTTPS_INSPECTION
3329 close_client_and_server_ssl_connections(csp);
3333 hdr = list_to_text(csp->headers);
3336 /* FIXME Should handle error properly */
3337 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3340 if ((csp->flags & CSP_FLAG_CHUNKED)
3341 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3342 && ((csp->iob->eod - csp->iob->cur) >= 5)
3343 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3345 log_error(LOG_LEVEL_CONNECT,
3346 "Looks like we got the last chunk together with "
3347 "the server headers. We better stop reading.");
3348 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3349 csp->expected_content_length = byte_count;
3350 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3353 csp->server_connection.response_received = time(NULL);
3355 if (crunch_response_triggered(csp, crunchers_light))
3358 * One of the tags created by a server-header
3359 * tagger triggered a crunch. We already
3360 * delivered the crunch response to the client
3361 * and are done here after cleaning up.
3364 mark_server_socket_tainted(csp);
3365 #ifdef FEATURE_HTTPS_INSPECTION
3366 close_client_and_server_ssl_connections(csp);
3371 /* Buffer and pcrs filter this if appropriate. */
3372 buffer_and_filter_content = content_requires_filtering(csp);
3374 if (!buffer_and_filter_content)
3377 * Write the server's (modified) header to
3378 * the client (along with anything else that
3379 * may be in the buffer). Use standard or secured
3382 #ifdef FEATURE_HTTPS_INSPECTION
3383 if (client_use_ssl(csp))
3385 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3386 (const unsigned char *)hdr, strlen(hdr),
3387 get_write_delay(csp)) < 0)
3388 || (len = ssl_flush_socket(&(csp->ssl_client_attr),
3391 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3394 * The write failed, so don't bother mentioning it
3395 * to the client... it probably can't hear us anyway.
3398 mark_server_socket_tainted(csp);
3399 #ifdef FEATURE_HTTPS_INSPECTION
3400 close_client_and_server_ssl_connections(csp);
3406 #endif /* def FEATURE_HTTPS_INSPECTION */
3408 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3409 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3411 log_error(LOG_LEVEL_ERROR,
3412 "write header to client failed");
3414 * The write failed, so don't bother mentioning it
3415 * to the client... it probably can't hear us anyway.
3418 mark_server_socket_tainted(csp);
3424 /* we're finished with the server's header */
3430 * If this was a MS IIS/5 hack then it means the server
3431 * has already closed the connection. Nothing more to read.
3436 log_error(LOG_LEVEL_ERROR,
3437 "Closed server connection detected. "
3438 "Applying the MS IIS5 hack didn't help.");
3439 log_error(LOG_LEVEL_CLF,
3440 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3441 #ifdef FEATURE_HTTPS_INSPECTION
3443 * Sending data with standard or secured connection (HTTP/HTTPS)
3445 if (client_use_ssl(csp))
3447 ssl_send_data_delayed(&(csp->ssl_client_attr),
3448 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3449 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3450 get_write_delay(csp));
3453 #endif /* def FEATURE_HTTPS_INSPECTION */
3455 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3456 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3458 mark_server_socket_tainted(csp);
3459 #ifdef FEATURE_HTTPS_INSPECTION
3460 close_client_and_server_ssl_connections(csp);
3467 mark_server_socket_tainted(csp);
3468 #ifdef FEATURE_HTTPS_INSPECTION
3469 close_client_and_server_ssl_connections(csp);
3471 return; /* huh? we should never get here */
3473 #ifdef FEATURE_HTTPS_INSPECTION
3474 close_client_and_server_ssl_connections(csp);
3476 if (csp->content_length == 0)
3479 * If Privoxy didn't recalculate the Content-Length,
3480 * byte_count is still correct.
3482 csp->content_length = byte_count;
3485 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3486 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3487 && (csp->expected_content_length != byte_count))
3489 log_error(LOG_LEVEL_CONNECT,
3490 "Received %llu bytes while expecting %llu.",
3491 byte_count, csp->expected_content_length);
3492 mark_server_socket_tainted(csp);
3496 #ifdef FEATURE_HTTPS_INSPECTION
3497 if (client_use_ssl(csp))
3499 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
3500 csp->ip_addr_str, http->gpc, http->hostport, http->path,
3501 http->version, csp->content_length);
3506 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3507 csp->ip_addr_str, http->ocmd, csp->content_length);
3509 csp->server_connection.timestamp = time(NULL);
3513 /*********************************************************************
3517 * Description : Once a connection from the client has been accepted,
3518 * this function is called (via serve()) to handle the
3519 * main business of the communication. This function
3520 * returns after dealing with a single request. It can
3521 * be called multiple times with the same client socket
3522 * if the client is keeping the connection alive.
3524 * The decision whether or not a client connection will
3525 * be kept alive is up to the caller which also must
3526 * close the client socket when done.
3528 * FIXME: chat is nearly thousand lines long.
3532 * 1 : csp = Current client state (buffers, headers, etc...)
3534 * Returns : Nothing.
3536 *********************************************************************/
3537 static void chat(struct client_state *csp)
3539 const struct forward_spec *fwd;
3540 struct http_request *http;
3541 /* Skeleton for HTTP response, if we should intercept the request */
3542 struct http_response *rsp;
3543 #ifdef FEATURE_HTTPS_INSPECTION
3544 int use_ssl_tunnel = 0;
3549 if (receive_client_request(csp) != JB_ERR_OK)
3553 if (parse_client_request(csp) != JB_ERR_OK)
3558 /* decide how to route the HTTP request */
3559 fwd = forward_url(csp, http);
3562 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
3563 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3567 #ifdef FEATURE_HTTPS_INSPECTION
3569 * Setting flags to use old solution with SSL tunnel and to disable
3570 * certificate verification.
3572 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
3573 && !cgi_page_requested(csp->http->host))
3578 if (http->ssl && csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS)
3580 csp->dont_verify_certificate = 1;
3585 * build the http request to send to the server
3586 * we have to do one of the following:
3588 * create = use the original HTTP request to create a new
3589 * HTTP request that has either the path component
3590 * without the http://domainspec (w/path) or the
3591 * full orininal URL (w/url)
3592 * Note that the path and/or the HTTP version may
3593 * have been altered by now.
3595 * SSL proxy = Open a socket to the host:port of the server
3596 * and create TLS/SSL connection with server and
3597 * with client. Then behave like mediator between
3598 * client and server over TLS/SSL.
3600 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
3601 * with request to a parent proxy. Note that we'll be sending
3602 * forwarding the CFAIL message ourselves if connecting to the parent
3603 * fails, but we won't send a CSUCCEED message if it works,
3604 * since that would result in a double message (ours and the
3605 * parent's). After sending the request to the parent, we
3606 * must parse answer and send it to client. If connection
3607 * with server is established, we do TLS/SSL proxy. Otherwise
3608 * we send parent response to client and close connections.
3610 * here's the matrix:
3613 * +--------+--------+
3615 * 0 | create | SSL |
3616 * | w/path | proxy |
3617 * Forwarding +--------+--------+
3619 * 1 | create | proxy |
3620 * | w/url |+forward|
3621 * +--------+--------+
3625 #ifdef FEATURE_HTTPS_INSPECTION
3627 * Presetting SSL client and server flags
3629 if (http->ssl && !use_ssl_tunnel)
3631 http->client_ssl = 1;
3632 http->server_ssl = 1;
3636 http->client_ssl = 0;
3637 http->server_ssl = 0;
3641 #ifdef FEATURE_HTTPS_INSPECTION
3643 * Log the request unless we're https inspecting
3644 * in which case we don't have the path yet and
3645 * will log the request later.
3647 if (!client_use_ssl(csp))
3650 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
3653 if (http->ssl && connect_port_is_forbidden(csp))
3655 const char *acceptable_connect_ports =
3656 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
3657 assert(NULL != acceptable_connect_ports);
3658 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
3659 "limit-connect{%s} doesn't allow CONNECT requests to %s",
3660 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
3661 csp->action->flags |= ACTION_BLOCK;
3663 #ifdef FEATURE_HTTPS_INSPECTION
3664 http->client_ssl = 0;
3665 http->server_ssl = 0;
3670 freez(csp->headers->first->str);
3671 build_request_line(csp, fwd, &csp->headers->first->str);
3674 * We have a request. Check if one of the crunchers wants it
3675 * unless the client wants to use TLS/SSL in which case we
3676 * haven't setup the TLS context yet and will send the crunch
3680 #ifdef FEATURE_HTTPS_INSPECTION
3681 !client_use_ssl(csp) &&
3683 crunch_response_triggered(csp, crunchers_all))
3686 * Yes. The client got the crunch response and we're done here.
3691 log_applied_actions(csp->action);
3692 if (fwd->forward_host)
3694 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
3695 fwd->forward_host, fwd->forward_port, http->hostport);
3699 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
3702 /* here we connect to the server, gateway, or the forwarder */
3704 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3705 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
3706 && socket_is_still_alive(csp->server_connection.sfd)
3707 && connection_destination_matches(&csp->server_connection, http, fwd))
3709 log_error(LOG_LEVEL_CONNECT,
3710 "Reusing server socket %d connected to %s. Total requests: %u.",
3711 csp->server_connection.sfd, csp->server_connection.host,
3712 csp->server_connection.requests_sent_total);
3716 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3718 #ifdef FEATURE_CONNECTION_SHARING
3719 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3721 remember_connection(&csp->server_connection);
3724 #endif /* def FEATURE_CONNECTION_SHARING */
3726 log_error(LOG_LEVEL_CONNECT,
3727 "Closing server socket %d connected to %s. Total requests: %u.",
3728 csp->server_connection.sfd, csp->server_connection.host,
3729 csp->server_connection.requests_sent_total);
3730 close_socket(csp->server_connection.sfd);
3732 mark_connection_closed(&csp->server_connection);
3734 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3735 #ifdef FEATURE_HTTPS_INSPECTION
3736 if (http->ssl && !use_ssl_tunnel)
3740 * Creating a SSL proxy.
3742 * By sending the CSUCCEED message we're lying to the client as
3743 * the connection hasn't actually been established yet. We don't
3744 * establish the connection until we have seen and parsed the
3745 * encrypted client headers.
3747 if (write_socket_delayed(csp->cfd, CSUCCEED,
3748 strlen(CSUCCEED), get_write_delay(csp)) != 0)
3750 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
3754 ret = create_client_ssl_connection(csp);
3757 log_error(LOG_LEVEL_ERROR,
3758 "Failed to open a secure connection with the client");
3761 if (JB_ERR_OK != process_encrypted_request(csp))
3763 log_error(LOG_LEVEL_ERROR, "Failed to parse encrypted request.");
3764 close_client_ssl_connection(csp);
3768 * We have an encrypted request. Check if one of the crunchers now
3769 * wants it (for example because the previously invisible path was
3770 * required to match).
3772 if (crunch_response_triggered(csp, crunchers_all))
3775 * Yes. The client got the crunch response and we're done here.
3777 close_client_ssl_connection(csp);
3783 * Connecting to destination server
3785 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
3787 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
3789 if (fwd->type != SOCKS_NONE)
3792 rsp = error_response(csp, "forwarding-failed");
3794 else if (errno == EINVAL)
3796 rsp = error_response(csp, "no-such-domain");
3800 rsp = error_response(csp, "connect-failed");
3803 /* Write the answer to the client */
3806 send_crunch_response(csp, rsp);
3810 * Temporary workaround to prevent already-read client
3811 * bodies from being parsed as new requests. For now we
3812 * err on the safe side and throw all the following
3813 * requests under the bus, even if no client body has been
3814 * buffered. A compliant client will repeat the dropped
3815 * requests on an untainted connection.
3817 * The proper fix is to discard the no longer needed
3818 * client body in the buffer (if there is one) and to
3819 * continue parsing the bytes that follow.
3821 #ifdef FEATURE_HTTPS_INSPECTION
3822 close_client_ssl_connection(csp);
3824 drain_and_close_socket(csp->cfd);
3825 csp->cfd = JB_INVALID_SOCKET;
3830 #ifdef FEATURE_HTTPS_INSPECTION
3832 * Creating TLS/SSL connections with destination server or parent
3833 * proxy. If forwarding is enabled, we must send client request to
3834 * parent proxy and receive, parse and resend parent proxy answer.
3836 if (http->ssl && !use_ssl_tunnel)
3838 if (fwd->forward_host != NULL)
3840 char server_response[BUFFER_SIZE];
3843 char *hdr = list_to_text(csp->headers);
3844 memset(server_response, 0, sizeof(server_response));
3848 log_error(LOG_LEVEL_FATAL,
3849 "Out of memory parsing client header");
3851 list_remove_all(csp->headers);
3854 * Sending client's CONNECT request to the parent proxy
3856 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
3862 log_error(LOG_LEVEL_CONNECT,
3863 "Sending request headers to: %s failed", http->hostport);
3864 mark_server_socket_tainted(csp);
3865 close_client_ssl_connection(csp);
3869 /* Waiting for parent proxy server response */
3870 len = read_socket(csp->server_connection.sfd, server_response,
3871 sizeof(server_response)-1);
3875 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
3876 "server on socket %d.", csp->server_connection.sfd);
3878 rsp = error_response(csp, "no-server-data");
3881 send_crunch_response(csp, rsp);
3883 mark_server_socket_tainted(csp);
3884 close_client_ssl_connection(csp);
3889 * Test if the connection to the destination server was
3890 * established successfully by the parent proxy.
3892 if (!tunnel_established_successfully(server_response, (unsigned int)len))
3894 log_error(LOG_LEVEL_ERROR,
3895 "The forwarder %s failed to establish a connection with %s",
3896 fwd->forward_host, http->host);
3897 rsp = error_response(csp, "connect-failed");
3900 send_crunch_response(csp, rsp);
3902 mark_server_socket_tainted(csp);
3903 close_client_ssl_connection(csp);
3906 } /* -END- if (fwd->forward_host != NULL) */
3909 * We can now create the TLS/SSL connection with the destination server.
3911 int ret = create_server_ssl_connection(csp);
3914 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
3915 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
3918 * If the server certificate is invalid, we must inform
3919 * the client and then close connection to the client.
3921 ssl_send_certificate_error(csp);
3922 close_client_and_server_ssl_connections(csp);
3925 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
3926 || csp->server_cert_verification_result == SSL_CERT_VALID)
3929 * The TLS/SSL connection wasn't created but an invalid
3930 * certificate wasn't detected. Report it as connection
3933 rsp = error_response(csp, "connect-failed");
3936 send_crunch_response(csp, rsp);
3938 close_client_and_server_ssl_connections(csp);
3942 }/* -END- if (http->ssl) */
3943 #endif /* def FEATURE_HTTPS_INSPECTION */
3945 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3946 save_connection_destination(csp->server_connection.sfd,
3947 http, fwd, &csp->server_connection);
3948 csp->server_connection.keep_alive_timeout =
3949 (unsigned)csp->config->keep_alive_timeout;
3951 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3953 csp->server_connection.requests_sent_total++;
3955 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
3957 /* Client headers have been sent optimistically */
3958 assert(csp->headers->last == NULL);
3960 else if (http->ssl == 0 || (fwd->forward_host
3961 #ifdef FEATURE_HTTPS_INSPECTION
3966 if (send_http_request(csp))
3968 rsp = error_response(csp, "connect-failed");
3971 send_crunch_response(csp, rsp);
3979 * Using old solution with SSL tunnel or new solution with SSL proxy
3981 list_remove_all(csp->headers);
3982 #ifdef FEATURE_HTTPS_INSPECTION
3987 * We're running an SSL tunnel and we're not forwarding,
3988 * so just ditch the client headers, send the "connect succeeded"
3989 * message to the client, flush the rest, and get out of the way.
3991 if (write_socket_delayed(csp->cfd, CSUCCEED,
3992 strlen(CSUCCEED), get_write_delay(csp)))
3997 #ifdef FEATURE_HTTPS_INSPECTION
4001 * If server certificate is invalid, we must inform client and then
4002 * close connection with client.
4004 if (csp->server_cert_verification_result != SSL_CERT_VALID)
4006 ssl_send_certificate_error(csp);
4007 close_client_and_server_ssl_connections(csp);
4010 if (send_https_request(csp))
4012 rsp = error_response(csp, "connect-failed");
4015 send_crunch_response(csp, rsp);
4017 close_client_and_server_ssl_connections(csp);
4021 #endif /* def FEATURE_HTTPS_INSPECTION */
4022 clear_iob(csp->client_iob);
4023 }/* -END- else ... if (http->ssl == 1) */
4025 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4027 /* XXX: should the time start earlier for optimistically sent data? */
4028 csp->server_connection.request_sent = time(NULL);
4030 handle_established_connection(csp);
4031 freez(csp->receive_buffer);
4036 /*********************************************************************
4038 * Function : fuzz_server_response
4040 * Description : Treat the input as a whole server response.
4043 * 1 : csp = Current client state (buffers, headers, etc...)
4044 * 2 : fuzz_input_file = File to read the input from.
4048 *********************************************************************/
4049 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4051 static struct forward_spec fwd; /* Zero'd due to being static */
4054 if (strcmp(fuzz_input_file, "-") == 0)
4056 /* XXX: Doesn'T work yet. */
4057 csp->server_connection.sfd = 0;
4061 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4062 if (csp->server_connection.sfd == -1)
4064 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4069 csp->content_type |= CT_GIF;
4070 csp->action->flags |= ACTION_DEANIMATE;
4071 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4073 csp->http->path = strdup_or_die("/");
4074 csp->http->host = strdup_or_die("fuzz.example.org");
4075 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4076 /* Prevent client socket monitoring */
4077 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4078 csp->flags |= CSP_FLAG_CHUNKED;
4080 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4081 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4083 csp->content_type |= CT_DECLARED|CT_GIF;
4085 csp->config->socket_timeout = 0;
4087 cgi_init_error_messages();
4089 handle_established_connection(csp);
4090 freez(csp->receive_buffer);
4097 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4098 /*********************************************************************
4100 * Function : prepare_csp_for_next_request
4102 * Description : Put the csp in a mostly vergin state.
4105 * 1 : csp = Current client state (buffers, headers, etc...)
4109 *********************************************************************/
4110 static void prepare_csp_for_next_request(struct client_state *csp)
4112 csp->content_type = 0;
4113 csp->content_length = 0;
4114 csp->expected_content_length = 0;
4115 csp->expected_client_content_length = 0;
4116 list_remove_all(csp->headers);
4117 clear_iob(csp->iob);
4118 freez(csp->error_message);
4119 free_http_request(csp->http);
4120 destroy_list(csp->headers);
4121 destroy_list(csp->tags);
4122 #ifdef FEATURE_CLIENT_TAGS
4123 destroy_list(csp->client_tags);
4124 freez(csp->client_address);
4126 free_current_action(csp->action);
4127 if (NULL != csp->fwd)
4129 unload_forward_spec(csp->fwd);
4132 /* XXX: Store per-connection flags someplace else. */
4133 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4134 #ifdef FEATURE_TOGGLE
4135 if (global_toggle_state)
4136 #endif /* def FEATURE_TOGGLE */
4138 csp->flags |= CSP_FLAG_TOGGLED_ON;
4141 if (csp->client_iob->eod > csp->client_iob->cur)
4143 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4144 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4146 assert(bytes_to_shift > 0);
4147 assert(data_length > 0);
4149 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
4150 data_length, bytes_to_shift);
4151 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4152 csp->client_iob->cur = csp->client_iob->buf;
4153 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4154 csp->client_iob->eod = csp->client_iob->buf + data_length;
4155 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4157 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4162 * We mainly care about resetting client_iob->cur so we don't
4163 * waste buffer space at the beginning and don't mess up the
4164 * request restoration done by cgi_show_request().
4166 * Freeing the buffer itself isn't technically necessary,
4167 * but makes debugging more convenient.
4169 clear_iob(csp->client_iob);
4172 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4175 /*********************************************************************
4179 * Description : This is little more than chat. We only "serve" to
4180 * to close (or remember) any socket that chat may have
4184 * 1 : csp = Current client state (buffers, headers, etc...)
4188 *********************************************************************/
4189 static void serve(struct client_state *csp)
4191 int config_file_change_detected = 0; /* Only used for debugging */
4192 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4193 #ifdef FEATURE_CONNECTION_SHARING
4194 static int monitor_thread_running = 0;
4195 #endif /* def FEATURE_CONNECTION_SHARING */
4196 int continue_chatting = 0;
4198 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4199 csp->ip_addr_str, csp->cfd);
4203 unsigned int latency;
4208 * If the request has been crunched,
4209 * the calculated latency is zero.
4211 latency = (unsigned)(csp->server_connection.response_received -
4212 csp->server_connection.request_sent) / 2;
4214 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4215 && (csp->flags & CSP_FLAG_CRUNCHED)
4216 && (csp->expected_client_content_length != 0))
4218 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4219 log_error(LOG_LEVEL_CONNECT,
4220 "Tainting client socket %d due to unread data.", csp->cfd);
4223 continue_chatting = (csp->config->feature_flags
4224 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4225 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4226 && (csp->cfd != JB_INVALID_SOCKET)
4227 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4228 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4229 || (csp->flags & CSP_FLAG_CHUNKED));
4231 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4232 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4234 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4236 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4238 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4239 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4240 || !socket_is_still_alive(csp->server_connection.sfd)
4241 || !(latency < csp->server_connection.keep_alive_timeout))
4243 log_error(LOG_LEVEL_CONNECT,
4244 "Closing server socket %d connected to %s. "
4245 "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4246 csp->server_connection.sfd, csp->server_connection.host,
4247 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4248 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4249 socket_is_still_alive(csp->server_connection.sfd),
4250 csp->server_connection.keep_alive_timeout);
4251 #ifdef FEATURE_CONNECTION_SHARING
4252 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4254 forget_connection(csp->server_connection.sfd);
4256 #endif /* def FEATURE_CONNECTION_SHARING */
4257 close_socket(csp->server_connection.sfd);
4258 mark_connection_closed(&csp->server_connection);
4262 if (continue_chatting && any_loaded_file_changed(csp))
4264 continue_chatting = 0;
4265 config_file_change_detected = 1;
4268 if (continue_chatting)
4270 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4271 && socket_is_still_alive(csp->cfd))
4273 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4274 "pipelined on socket %d and the socket is still alive.",
4275 csp->requests_received_total+1, csp->cfd);
4276 prepare_csp_for_next_request(csp);
4280 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4282 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4284 log_error(LOG_LEVEL_CONNECT,
4285 "Waiting for the next client request on socket %d. "
4286 "Keeping the server socket %d to %s open.",
4287 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4291 log_error(LOG_LEVEL_CONNECT,
4292 "Waiting for the next client request on socket %d. "
4293 "No server socket to keep open.", csp->cfd);
4297 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4298 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4299 && socket_is_still_alive(csp->cfd))
4301 log_error(LOG_LEVEL_CONNECT,
4302 "Client request %u arrived in time on socket %d.",
4303 csp->requests_received_total+1, csp->cfd);
4304 prepare_csp_for_next_request(csp);
4308 #ifdef FEATURE_CONNECTION_SHARING
4309 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4310 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4311 && (socket_is_still_alive(csp->server_connection.sfd)))
4313 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4315 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4320 remember_connection(&csp->server_connection);
4321 csp->server_connection.sfd = JB_INVALID_SOCKET;
4322 drain_and_close_socket(csp->cfd);
4323 csp->cfd = JB_INVALID_SOCKET;
4324 privoxy_mutex_lock(&connection_reuse_mutex);
4325 if (!monitor_thread_running)
4327 monitor_thread_running = 1;
4328 privoxy_mutex_unlock(&connection_reuse_mutex);
4329 wait_for_alive_connections();
4330 privoxy_mutex_lock(&connection_reuse_mutex);
4331 monitor_thread_running = 0;
4333 privoxy_mutex_unlock(&connection_reuse_mutex);
4335 #endif /* def FEATURE_CONNECTION_SHARING */
4339 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4341 log_error(LOG_LEVEL_CONNECT,
4342 "Closing server socket %d connected to %s. Keep-alive: %u. "
4343 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4344 "Configuration file change detected: %u",
4345 csp->server_connection.sfd, csp->server_connection.host,
4346 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4347 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4348 socket_is_still_alive(csp->server_connection.sfd),
4349 csp->server_connection.keep_alive_timeout,
4350 config_file_change_detected);
4352 } while (continue_chatting);
4356 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4358 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4360 #ifdef FEATURE_CONNECTION_SHARING
4361 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4363 forget_connection(csp->server_connection.sfd);
4365 #endif /* def FEATURE_CONNECTION_SHARING */
4366 close_socket(csp->server_connection.sfd);
4369 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4370 mark_connection_closed(&csp->server_connection);
4373 if (csp->cfd != JB_INVALID_SOCKET)
4375 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4376 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4377 "Configuration file change detected: %u. Requests received: %u.",
4378 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4379 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4380 config_file_change_detected, csp->requests_received_total);
4381 drain_and_close_socket(csp->cfd);
4384 free_csp_resources(csp);
4386 csp->flags &= ~CSP_FLAG_ACTIVE;
4392 /*********************************************************************
4394 * Function : server_thread
4396 * Description : We only exist to call `serve' in a threaded environment.
4399 * 1 : data = Current client state (buffers, headers, etc...)
4401 * Returns : Always 0.
4403 *********************************************************************/
4404 static int32 server_thread(void *data)
4406 serve((struct client_state *) data);
4413 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4414 /*********************************************************************
4418 * Description : Print usage info & exit.
4420 * Parameters : Pointer to argv[0] for identifying ourselves
4424 *********************************************************************/
4425 static void usage(const char *name)
4427 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
4428 "Usage: %s [--config-test] "
4431 #endif /* defined(unix) */
4434 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
4435 #endif /* defined(unix) */
4436 "[--version] [configfile]\n",
4440 show_fuzz_usage(name);
4443 printf("Aborting\n");
4448 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
4451 #ifdef MUTEX_LOCKS_AVAILABLE
4452 /*********************************************************************
4454 * Function : privoxy_mutex_lock
4456 * Description : Locks a mutex.
4459 * 1 : mutex = The mutex to lock.
4461 * Returns : Void. May exit in case of errors.
4463 *********************************************************************/
4464 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
4466 #ifdef FEATURE_PTHREAD
4467 int err = pthread_mutex_lock(mutex);
4470 if (mutex != &log_mutex)
4472 log_error(LOG_LEVEL_FATAL,
4473 "Mutex locking failed: %s.\n", strerror(err));
4478 EnterCriticalSection(mutex);
4479 #endif /* def FEATURE_PTHREAD */
4483 /*********************************************************************
4485 * Function : privoxy_mutex_unlock
4487 * Description : Unlocks a mutex.
4490 * 1 : mutex = The mutex to unlock.
4492 * Returns : Void. May exit in case of errors.
4494 *********************************************************************/
4495 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
4497 #ifdef FEATURE_PTHREAD
4498 int err = pthread_mutex_unlock(mutex);
4501 if (mutex != &log_mutex)
4503 log_error(LOG_LEVEL_FATAL,
4504 "Mutex unlocking failed: %s.\n", strerror(err));
4509 LeaveCriticalSection(mutex);
4510 #endif /* def FEATURE_PTHREAD */
4514 /*********************************************************************
4516 * Function : privoxy_mutex_init
4518 * Description : Prepares a mutex.
4521 * 1 : mutex = The mutex to initialize.
4523 * Returns : Void. May exit in case of errors.
4525 *********************************************************************/
4526 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
4528 #ifdef FEATURE_PTHREAD
4529 int err = pthread_mutex_init(mutex, 0);
4532 printf("Fatal error. Mutex initialization failed: %s.\n",
4537 InitializeCriticalSection(mutex);
4538 #endif /* def FEATURE_PTHREAD */
4540 #endif /* def MUTEX_LOCKS_AVAILABLE */
4542 /*********************************************************************
4544 * Function : initialize_mutexes
4546 * Description : Prepares mutexes if mutex support is available.
4550 * Returns : Void, exits in case of errors.
4552 *********************************************************************/
4553 static void initialize_mutexes(void)
4555 #ifdef MUTEX_LOCKS_AVAILABLE
4557 * Prepare global mutex semaphores
4560 #ifdef FEATURE_HTTPS_INSPECTION
4561 privoxy_mutex_init(&certificate_mutex);
4562 privoxy_mutex_init(&ssl_init_mutex);
4565 privoxy_mutex_init(&log_mutex);
4566 privoxy_mutex_init(&log_init_mutex);
4567 privoxy_mutex_init(&connection_reuse_mutex);
4568 #ifdef FEATURE_EXTERNAL_FILTERS
4569 privoxy_mutex_init(&external_filter_mutex);
4571 #ifdef FEATURE_CLIENT_TAGS
4572 privoxy_mutex_init(&client_tags_mutex);
4574 #ifdef FEATURE_EXTENDED_STATISTICS
4575 privoxy_mutex_init(&filter_statistics_mutex);
4576 privoxy_mutex_init(&block_statistics_mutex);
4580 * XXX: The assumptions below are a bit naive
4581 * and can cause locks that aren't necessary.
4583 * For example older FreeBSD versions (< 6.x?)
4584 * have no gethostbyname_r, but gethostbyname is
4587 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
4588 privoxy_mutex_init(&resolver_mutex);
4589 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
4591 * XXX: should we use a single mutex for
4592 * localtime() and gmtime() as well?
4594 #ifndef HAVE_GMTIME_R
4595 privoxy_mutex_init(&gmtime_mutex);
4596 #endif /* ndef HAVE_GMTIME_R */
4598 #ifndef HAVE_LOCALTIME_R
4599 privoxy_mutex_init(&localtime_mutex);
4600 #endif /* ndef HAVE_GMTIME_R */
4602 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
4603 privoxy_mutex_init(&rand_mutex);
4604 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
4606 #endif /* def MUTEX_LOCKS_AVAILABLE */
4609 /*********************************************************************
4613 * Description : Load the config file and start the listen loop.
4614 * This function is a lot more *sane* with the `load_config'
4615 * and `listen_loop' functions; although it stills does
4616 * a *little* too much for my taste.
4619 * 1 : argc = Number of parameters (including $0).
4620 * 2 : argv = Array of (char *)'s to the parameters.
4622 * Returns : 1 if : can't open config file, unrecognized directive,
4623 * stats requested in multi-thread mode, can't open the
4624 * log file, can't open the jar file, listen port is invalid,
4625 * any load fails, and can't bind port.
4627 * Else main never returns, the process must be signaled
4628 * to terminate execution. Or, on Windows, use the
4629 * "File", "Exit" menu option.
4631 *********************************************************************/
4633 int real_main(int argc, char **argv)
4635 int main(int argc, char **argv)
4639 int do_config_test = 0;
4640 #ifndef HAVE_ARC4RANDOM
4641 unsigned int random_seed;
4644 struct passwd *pw = NULL;
4645 struct group *grp = NULL;
4647 char *pre_chroot_nslookup_to_load_resolver = NULL;
4650 char *fuzz_input_type = NULL;
4651 char *fuzz_input_file = NULL;
4658 #if !defined(_WIN32)
4665 /* Prepare mutexes if supported and necessary. */
4666 initialize_mutexes();
4668 /* Enable logging until further notice. */
4672 * Parse the command line arguments
4674 * XXX: simply printing usage information in case of
4675 * invalid arguments isn't particularly user friendly.
4677 while (++argc_pos < argc)
4680 /* Check to see if the service must be installed or uninstalled */
4681 if (strncmp(argv[argc_pos], "--install", 9) == 0)
4683 const char *pName = argv[argc_pos] + 9;
4686 exit((install_service(pName)) ? 0 : 1);
4688 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
4690 const char *pName = argv[argc_pos] + 11;
4693 exit((uninstall_service(pName)) ? 0 : 1);
4695 else if (strcmp(argv[argc_pos], "--service") == 0)
4697 bRunAsService = TRUE;
4698 w32_set_service_cwd();
4699 atexit(w32_service_exit_notify);
4702 #endif /* defined(_WIN32) */
4705 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4707 if (strcmp(argv[argc_pos], "--help") == 0)
4712 else if (strcmp(argv[argc_pos], "--version") == 0)
4714 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
4720 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
4722 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
4726 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
4728 if (++argc_pos == argc) usage(argv[0]);
4729 pidfile = strdup_or_die(argv[argc_pos]);
4732 else if (strcmp(argv[argc_pos], "--user") == 0)
4737 if (++argc_pos == argc) usage(argv[argc_pos]);
4739 user_arg = strdup_or_die(argv[argc_pos]);
4740 group_name = strchr(user_arg, '.');
4741 if (NULL != group_name)
4743 /* Nul-terminate the user name */
4746 /* Skip the former delimiter to actually reach the group name */
4749 grp = getgrnam(group_name);
4752 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
4755 pw = getpwnam(user_arg);
4758 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
4764 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
4766 if (++argc_pos == argc) usage(argv[0]);
4767 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
4770 else if (strcmp(argv[argc_pos], "--chroot") == 0)
4774 #endif /* defined(unix) */
4776 else if (strcmp(argv[argc_pos], "--config-test") == 0)
4781 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
4784 if (argc < argc_pos + 2) usage(argv[0]);
4785 fuzz_input_type = argv[argc_pos];
4787 fuzz_input_file = argv[argc_pos];
4789 else if (strcmp(argv[argc_pos], "--stfu") == 0)
4791 set_debug_level(LOG_LEVEL_STFU);
4794 else if (argc_pos + 1 != argc)
4797 * This is neither the last command line
4798 * option, nor was it recognized before,
4799 * therefore it must be invalid.
4805 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
4807 configfile = argv[argc_pos];
4810 } /* -END- while (more arguments) */
4812 show_version(Argv[0]);
4815 if (*configfile != '/')
4817 char cwd[BUFFER_SIZE];
4819 size_t abs_file_size;
4821 /* make config-filename absolute here */
4822 if (NULL == getcwd(cwd, sizeof(cwd)))
4824 perror("failed to get current working directory");
4828 basedir = strdup_or_die(cwd);
4830 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
4831 abs_file = malloc_or_die(abs_file_size);
4832 strlcpy(abs_file, basedir, abs_file_size);
4833 strlcat(abs_file, "/", abs_file_size);
4834 strlcat(abs_file, configfile, abs_file_size);
4835 configfile = abs_file;
4837 #endif /* defined unix */
4841 clients->next = NULL;
4843 /* XXX: factor out initialising after the next stable release. */
4848 #ifndef HAVE_ARC4RANDOM
4849 random_seed = (unsigned int)time(NULL);
4851 srandom(random_seed);
4854 #endif /* ifdef HAVE_RANDOM */
4855 #endif /* ifndef HAVE_ARC4RANDOM */
4858 * Unix signal handling
4860 * Catch the abort, interrupt and terminate signals for a graceful exit
4861 * Catch the hangup signal so the errlog can be reopened.
4863 * Ignore the broken pipe signal as connection failures
4864 * are handled when and where they occur without relying
4867 #if !defined(_WIN32) && !defined(__OS2__)
4870 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
4872 for (idx = 0; idx < SZ(catched_signals); idx++)
4874 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
4875 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
4877 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
4878 #endif /* ifdef sun */
4880 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
4884 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
4886 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
4890 #else /* ifdef _WIN32 */
4891 # ifdef _WIN_CONSOLE
4893 * We *are* in a windows console app.
4894 * Print a verbose messages about FAQ's and such
4896 printf("%s", win32_blurb);
4897 # endif /* def _WIN_CONSOLE */
4898 #endif /* def _WIN32 */
4901 if (fuzz_input_type != NULL)
4903 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
4905 log_error(LOG_LEVEL_FATAL,
4906 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
4907 "Various data structures are static which is unsafe when using threads.");
4912 exit(NULL == load_config());
4915 /* Initialize the CGI subsystem */
4916 cgi_init_error_messages();
4919 * If running on unix and without the --no-daemon
4920 * option, become a daemon. I.e. fork, detach
4921 * from tty and get process group leadership
4930 if (pid < 0) /* error */
4935 else if (pid != 0) /* parent */
4940 * must check for errors
4941 * child died due to missing files aso
4944 wpid = waitpid(pid, &status, WNOHANG);
4956 * stderr (fd 2) will be closed later on,
4957 * when the config file has been parsed.
4963 * Reserve fd 0 and 1 to prevent abort() and friends
4964 * from sending stuff to the clients or servers.
4966 fd = open("/dev/null", O_RDONLY);
4969 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4973 if (dup2(fd, 0) == -1)
4975 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
4979 fd = open("/dev/null", O_WRONLY);
4982 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4986 if (dup2(fd, 1) == -1)
4988 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
4993 #ifdef FEATURE_EXTERNAL_FILTERS
4994 for (fd = 0; fd < 3; fd++)
4996 mark_socket_for_close_on_execute(fd);
5002 } /* -END- if (daemon_mode) */
5005 * As soon as we have written the PID file, we can switch
5006 * to the user and group ID indicated by the --user option
5008 if (pidfile != NULL)
5010 write_pid_file(pidfile);
5014 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5016 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5020 if (setgroups(1, &grp->gr_gid))
5022 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5025 else if (initgroups(pw->pw_name, pw->pw_gid))
5027 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5033 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5035 /* Read the time zone file from /etc before doing chroot. */
5037 if (NULL != pre_chroot_nslookup_to_load_resolver
5038 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5040 /* Initialize resolver library. */
5041 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5043 if (chroot(pw->pw_dir) < 0)
5045 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5049 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5052 if (setuid(pw->pw_uid))
5054 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5058 char putenv_dummy[64];
5060 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5061 if (putenv(putenv_dummy) != 0)
5063 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5066 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5067 if (putenv(putenv_dummy) != 0)
5069 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5075 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5078 #endif /* defined unix */
5081 /* This will be FALSE unless the command line specified --service
5085 /* Yup, so now we must attempt to establish a connection
5086 * with the service dispatcher. This will only work if this
5087 * process was launched by the service control manager to
5088 * actually run as a service. If this isn't the case, i've
5089 * known it take around 30 seconds or so for the call to return.
5092 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5093 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5095 /* Service has run, and at this point is now being stopped, so just return */
5100 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5102 /* An error occurred. Usually it's because --service was wrongly specified
5103 * and we were unable to connect to the Service Control Dispatcher because
5104 * it wasn't expecting us and is therefore not listening.
5106 * For now, just continue below to call the listen_loop function.
5109 #endif /* def _WIN32 */
5119 /*********************************************************************
5121 * Function : bind_port_helper
5123 * Description : Bind the listen port. Handles logging, and aborts
5127 * 1 : haddr = Host address to bind to. Use NULL to bind to
5129 * 2 : hport = Specifies port to bind to.
5130 * 3 : backlog = Listen backlog.
5132 * Returns : Port that was opened.
5134 *********************************************************************/
5135 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5140 result = bind_port(haddr, hport, backlog, &bfd);
5144 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5148 log_error(LOG_LEVEL_FATAL,
5149 "can't bind to %s:%d: There may be another Privoxy "
5150 "or some other proxy running on port %d",
5151 bind_address, hport, hport);
5154 log_error(LOG_LEVEL_FATAL,
5155 "can't bind to %s:%d: The hostname is not resolvable",
5156 bind_address, hport);
5159 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5160 bind_address, hport);
5163 /* shouldn't get here */
5164 return JB_INVALID_SOCKET;
5169 if (bfd >= FD_SETSIZE)
5171 log_error(LOG_LEVEL_FATAL,
5172 "Bind socket number too high to use select(): %d >= %d",
5180 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5185 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5193 /*********************************************************************
5195 * Function : bind_ports_helper
5197 * Description : Bind the listen ports. Handles logging, and aborts
5201 * 1 : config = Privoxy configuration. Specifies ports
5203 * 2 : sockets = Preallocated array of opened sockets
5204 * corresponding to specification in config.
5205 * All non-opened sockets will be set to
5206 * JB_INVALID_SOCKET.
5208 * Returns : Nothing. Inspect sockets argument.
5210 *********************************************************************/
5211 static void bind_ports_helper(struct configuration_spec * config,
5212 jb_socket sockets[])
5216 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5218 if (config->hport[i])
5220 sockets[i] = bind_port_helper(config->haddr[i],
5221 config->hport[i], config->listen_backlog);
5222 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5223 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5225 struct accept_filter_arg af_options;
5226 bzero(&af_options, sizeof(af_options));
5227 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5228 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5229 sizeof(af_options)))
5231 log_error(LOG_LEVEL_ERROR,
5232 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5239 sockets[i] = JB_INVALID_SOCKET;
5242 config->need_bind = 0;
5246 /*********************************************************************
5248 * Function : close_ports_helper
5250 * Description : Close listenings ports.
5253 * 1 : sockets = Array of opened and non-opened sockets to
5254 * close. All sockets will be set to
5255 * JB_INVALID_SOCKET.
5257 * Returns : Nothing.
5259 *********************************************************************/
5260 static void close_ports_helper(jb_socket sockets[])
5264 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5266 if (JB_INVALID_SOCKET != sockets[i])
5268 close_socket(sockets[i]);
5270 sockets[i] = JB_INVALID_SOCKET;
5276 /* Without this simple workaround we get this compiler warning from _beginthread
5277 * warning C4028: formal parameter 1 different from declaration
5279 void w32_service_listen_loop(void *p)
5283 #endif /* def _WIN32 */
5286 /*********************************************************************
5288 * Function : listen_loop
5290 * Description : bind the listen port and enter a "FOREVER" listening loop.
5296 *********************************************************************/
5297 static void listen_loop(void)
5299 struct client_states *csp_list = NULL;
5300 struct client_state *csp = NULL;
5301 jb_socket bfds[MAX_LISTENING_SOCKETS];
5302 struct configuration_spec *config;
5303 unsigned int active_threads = 0;
5304 #if defined(FEATURE_PTHREAD)
5305 pthread_attr_t attrs;
5307 pthread_attr_init(&attrs);
5308 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5311 config = load_config();
5313 #ifdef FEATURE_CONNECTION_SHARING
5315 * XXX: Should be relocated once it no
5316 * longer needs to emit log messages.
5318 initialize_reusable_connections();
5319 #endif /* def FEATURE_CONNECTION_SHARING */
5321 bind_ports_helper(config, bfds);
5323 #ifdef FEATURE_GRACEFUL_TERMINATION
5324 while (!g_terminate)
5329 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
5330 while (waitpid(-1, NULL, WNOHANG) > 0)
5332 /* zombie children */
5334 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5337 * Free data that was used by died threads
5339 active_threads = sweep();
5343 * Re-open the errlog after HUP signal
5345 if (received_hup_signal)
5347 if (NULL != config->logfile)
5349 init_error_log(Argv[0], config->logfile);
5351 received_hup_signal = 0;
5355 csp_list = zalloc_or_die(sizeof(*csp_list));
5356 csp = &csp_list->csp;
5358 log_error(LOG_LEVEL_CONNECT,
5359 "Waiting for the next client connection. Currently active threads: %d",
5363 * This config may be outdated, but for accept_connection()
5364 * it's fresh enough.
5366 csp->config = config;
5368 if (!accept_connection(csp, bfds))
5370 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5375 csp->flags |= CSP_FLAG_ACTIVE;
5376 csp->server_connection.sfd = JB_INVALID_SOCKET;
5378 csp->config = config = load_config();
5380 if (config->need_bind)
5383 * Since we were listening to the "old port", we will not see
5384 * a "listen" param change until the next request. So, at
5385 * least 1 more request must be made for us to find the new
5386 * setting. I am simply closing the old socket and binding the
5389 * Which-ever is correct, we will serve 1 more page via the
5390 * old settings. This should probably be a "show-status"
5391 * request. This should not be a so common of an operation
5392 * that this will hurt people's feelings.
5395 close_ports_helper(bfds);
5397 bind_ports_helper(config, bfds);
5400 #ifdef FEATURE_TOGGLE
5401 if (global_toggle_state)
5402 #endif /* def FEATURE_TOGGLE */
5404 csp->flags |= CSP_FLAG_TOGGLED_ON;
5407 if (run_loader(csp))
5409 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5410 /* Never get here - LOG_LEVEL_FATAL causes program exit */
5414 if (block_acl(NULL,csp))
5416 log_error(LOG_LEVEL_CONNECT,
5417 "Connection from %s on %s (socket %d) dropped due to ACL",
5418 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5419 close_socket(csp->cfd);
5420 freez(csp->ip_addr_str);
5421 freez(csp->listen_addr_str);
5425 #endif /* def FEATURE_ACL */
5427 if ((0 != config->max_client_connections)
5428 && (active_threads >= config->max_client_connections))
5430 log_error(LOG_LEVEL_CONNECT,
5431 "Rejecting connection from %s. Maximum number of connections reached.",
5433 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5434 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5435 close_socket(csp->cfd);
5436 freez(csp->ip_addr_str);
5437 freez(csp->listen_addr_str);
5442 /* add it to the list of clients */
5443 csp_list->next = clients->next;
5444 clients->next = csp_list;
5446 if (config->multi_threaded)
5450 /* this is a switch () statement in the C preprocessor - ugh */
5451 #undef SELECTED_ONE_OPTION
5453 /* Use Pthreads in preference to native code */
5454 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
5455 #define SELECTED_ONE_OPTION
5457 pthread_t the_thread;
5459 errno = pthread_create(&the_thread, &attrs,
5460 (void * (*)(void *))serve, csp);
5461 child_id = errno ? -1 : 0;
5465 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
5466 #define SELECTED_ONE_OPTION
5467 child_id = _beginthread(
5468 (void (*)(void *))serve,
5473 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
5474 #define SELECTED_ONE_OPTION
5475 child_id = _beginthread(
5476 (void(* _Optlink)(void*))serve,
5482 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
5483 #define SELECTED_ONE_OPTION
5485 thread_id tid = spawn_thread
5486 (server_thread, "server", B_NORMAL_PRIORITY, csp);
5488 if ((tid >= 0) && (resume_thread(tid) == B_OK))
5490 child_id = (int) tid;
5499 #if !defined(SELECTED_ONE_OPTION)
5502 /* This block is only needed when using fork().
5503 * When using threads, the server thread was
5504 * created and run by the call to _beginthread().
5506 if (child_id == 0) /* child */
5509 #ifdef FEATURE_TOGGLE
5510 int inherited_toggle_state = global_toggle_state;
5511 #endif /* def FEATURE_TOGGLE */
5516 * If we've been toggled or we've blocked the request, tell Mom
5519 #ifdef FEATURE_TOGGLE
5520 if (inherited_toggle_state != global_toggle_state)
5522 rc |= RC_FLAG_TOGGLED;
5524 #endif /* def FEATURE_TOGGLE */
5526 #ifdef FEATURE_STATISTICS
5527 if (csp->flags & CSP_FLAG_REJECTED)
5529 rc |= RC_FLAG_BLOCKED;
5531 #endif /* ndef FEATURE_STATISTICS */
5535 else if (child_id > 0) /* parent */
5537 /* in a fork()'d environment, the parent's
5538 * copy of the client socket and the CSP
5542 #if !defined(_WIN32) && !defined(__CYGWIN__)
5544 wait(&child_status);
5547 * Evaluate child's return code: If the child has
5548 * - been toggled, toggle ourselves
5549 * - blocked its request, bump up the stats counter
5552 #ifdef FEATURE_TOGGLE
5553 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
5555 global_toggle_state = !global_toggle_state;
5557 #endif /* def FEATURE_TOGGLE */
5559 #ifdef FEATURE_STATISTICS
5561 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
5565 #endif /* def FEATURE_STATISTICS */
5567 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
5568 close_socket(csp->cfd);
5569 csp->flags &= ~CSP_FLAG_ACTIVE;
5573 #undef SELECTED_ONE_OPTION
5574 /* end of cpp switch () */
5579 * Spawning the child failed, assume it's because
5580 * there are too many children running already.
5581 * XXX: If you assume ...
5583 log_error(LOG_LEVEL_ERROR,
5584 "Unable to take any additional connections: %E. Active threads: %d",
5586 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5587 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5588 close_socket(csp->cfd);
5589 csp->flags &= ~CSP_FLAG_ACTIVE;
5598 #if defined(FEATURE_PTHREAD)
5599 pthread_attr_destroy(&attrs);
5602 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
5604 #ifdef FEATURE_HTTPS_INSPECTION
5605 /* Clean up. Aim: free all memory (no leaks) */
5609 #ifdef FEATURE_GRACEFUL_TERMINATION
5611 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
5613 unload_current_config_file();
5614 unload_current_actions_file();
5615 unload_current_re_filterfile();
5616 #ifdef FEATURE_TRUST
5617 unload_current_trust_file();
5620 if (config->multi_threaded)
5627 } while ((clients->next != NULL) && (--i > 0));
5631 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
5641 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
5642 /* Cleanup - remove taskbar icon etc. */
5647 #endif /* FEATURE_GRACEFUL_TERMINATION */