Bump copyright
[privoxy.git] / jcc.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/jcc.c,v $
4  *
5  * Purpose     :  Main file.  Contains main() method, main loop, and
6  *                the main connection-handling function.
7  *
8  * Copyright   :  Written by and Copyright (C) 2001-2021 the
9  *                Privoxy team. https://www.privoxy.org/
10  *
11  *                Based on the Internet Junkbuster originally written
12  *                by and Copyright (C) 1997 Anonymous Coders and
13  *                Junkbusters Corporation.  http://www.junkbusters.com
14  *
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.
20  *
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.
26  *
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.
32  *
33  *********************************************************************/
34
35
36 #include "config.h"
37
38 #include <stdio.h>
39 #include <sys/types.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <signal.h>
43 #include <fcntl.h>
44 #include <errno.h>
45 #include <assert.h>
46
47 #ifdef _WIN32
48 # ifndef FEATURE_PTHREAD
49 #  ifndef STRICT
50 #   define STRICT
51 #  endif
52 #  include <winsock2.h>
53 #  include <windows.h>
54 #  include <process.h>
55 # endif /* ndef FEATURE_PTHREAD */
56
57 # include "win32.h"
58 # ifndef _WIN_CONSOLE
59 #  include "w32log.h"
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
62
63 #else /* ifndef _WIN32 */
64
65 # include <unistd.h>
66 # include <sys/wait.h>
67 # include <sys/time.h>
68 # include <sys/stat.h>
69 # include <sys/ioctl.h>
70
71 #ifdef sun
72 #include <sys/termios.h>
73 #endif /* sun */
74
75 #ifdef unix
76 #include <pwd.h>
77 #include <grp.h>
78 #endif
79
80 # include <signal.h>
81
82 # ifdef __BEOS__
83 #  include <socket.h>  /* BeOS has select() for sockets only. */
84 #  include <OS.h>      /* declarations for threads and stuff. */
85 # endif
86
87 #ifdef HAVE_POLL
88 #ifdef __GLIBC__
89 #include <sys/poll.h>
90 #else
91 #include <poll.h>
92 #endif /* def __GLIBC__ */
93 #else
94 # ifndef FD_ZERO
95 #  include <select.h>
96 # endif
97 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
98 #endif /* HAVE_POLL */
99
100 #endif
101
102 #include "project.h"
103 #include "list.h"
104 #include "jcc.h"
105 #ifdef FEATURE_HTTPS_INSPECTION
106 #include "ssl.h"
107 #endif
108 #include "filters.h"
109 #include "loaders.h"
110 #include "parsers.h"
111 #include "miscutil.h"
112 #include "errlog.h"
113 #include "jbsockets.h"
114 #include "gateway.h"
115 #include "actions.h"
116 #include "cgi.h"
117 #include "loadcfg.h"
118 #include "urlmatch.h"
119 #ifdef FEATURE_CLIENT_TAGS
120 #include "client-tags.h"
121 #endif
122
123 int daemon_mode = 1;
124 struct client_states clients[1];
125 struct file_list     files[1];
126
127 #ifdef FEATURE_STATISTICS
128 int urls_read     = 0;     /* total nr of urls read inc rejected */
129 int urls_rejected = 0;     /* total nr of urls rejected */
130 #endif /* def FEATURE_STATISTICS */
131
132 #ifdef FEATURE_GRACEFUL_TERMINATION
133 int g_terminate = 0;
134 #endif
135
136 #if !defined(_WIN32)
137 static void sig_handler(int the_signal);
138 #endif
139 static int client_protocol_is_unsupported(struct client_state *csp, char *req);
140 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
141 static jb_err get_server_headers(struct client_state *csp);
142 static const char *crunch_reason(const struct http_response *rsp);
143 static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
144 static char *get_request_line(struct client_state *csp);
145 static jb_err receive_client_request(struct client_state *csp);
146 static jb_err parse_client_request(struct client_state *csp);
147 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
148 static jb_err change_request_destination(struct client_state *csp);
149 static void handle_established_connection(struct client_state *csp);
150 static void chat(struct client_state *csp);
151 static void serve(struct client_state *csp);
152 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
153 static void usage(const char *myname);
154 #endif
155 static void initialize_mutexes(void);
156 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
157 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
158 static void close_ports_helper(jb_socket sockets[]);
159 static void listen_loop(void);
160 static void serve(struct client_state *csp);
161
162 #ifdef __BEOS__
163 static int32 server_thread(void *data);
164 #endif /* def __BEOS__ */
165
166 #ifdef _WIN32
167 #define sleep(N)  Sleep(((N) * 1000))
168 #endif
169
170 #ifdef FUZZ
171 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
172 void show_fuzz_usage(const char *name);
173 #endif
174
175 #ifdef MUTEX_LOCKS_AVAILABLE
176 /*
177  * XXX: Does the locking stuff really belong in this file?
178  */
179 privoxy_mutex_t log_mutex;
180 privoxy_mutex_t log_init_mutex;
181 privoxy_mutex_t connection_reuse_mutex;
182
183 #ifdef FEATURE_HTTPS_INSPECTION
184 privoxy_mutex_t certificate_mutex;
185 privoxy_mutex_t ssl_init_mutex;
186 #endif
187
188 #ifdef FEATURE_EXTERNAL_FILTERS
189 privoxy_mutex_t external_filter_mutex;
190 #endif
191 #ifdef FEATURE_CLIENT_TAGS
192 privoxy_mutex_t client_tags_mutex;
193 #endif
194 #ifdef FEATURE_EXTENDED_STATISTICS
195 privoxy_mutex_t filter_statistics_mutex;
196 privoxy_mutex_t block_statistics_mutex;
197 #endif
198
199 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
200 privoxy_mutex_t resolver_mutex;
201 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
202
203 #ifndef HAVE_GMTIME_R
204 privoxy_mutex_t gmtime_mutex;
205 #endif /* ndef HAVE_GMTIME_R */
206
207 #ifndef HAVE_LOCALTIME_R
208 privoxy_mutex_t localtime_mutex;
209 #endif /* ndef HAVE_GMTIME_R */
210
211 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
212 privoxy_mutex_t rand_mutex;
213 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
214
215 #endif /* def MUTEX_LOCKS_AVAILABLE */
216
217 #if defined(unix)
218 const char *basedir = NULL;
219 const char *pidfile = NULL;
220 static int received_hup_signal = 0;
221 #endif /* defined unix */
222
223 /* HTTP snipplets. */
224 static const char CSUCCEED[] =
225    "HTTP/1.1 200 Connection established\r\n\r\n";
226
227 static const char CHEADER[] =
228    "HTTP/1.1 400 Invalid header received from client\r\n"
229    "Content-Type: text/plain\r\n"
230    "Connection: close\r\n\r\n"
231    "Invalid header received from client.\r\n";
232
233 static const char FTP_RESPONSE[] =
234    "HTTP/1.1 400 Invalid request received from client\r\n"
235    "Content-Type: text/plain\r\n"
236    "Connection: close\r\n\r\n"
237    "Invalid request. Privoxy doesn't support FTP.\r\n";
238
239 static const char GOPHER_RESPONSE[] =
240    "HTTP/1.1 400 Invalid request received from client\r\n"
241    "Content-Type: text/plain\r\n"
242    "Connection: close\r\n\r\n"
243    "Invalid request. Privoxy doesn't support gopher.\r\n";
244
245 /* XXX: should be a template */
246 static const char MISSING_DESTINATION_RESPONSE[] =
247    "HTTP/1.1 400 Bad request received from client\r\n"
248    "Content-Type: text/plain\r\n"
249    "Connection: close\r\n\r\n"
250    "Bad request. Privoxy was unable to extract the destination.\r\n";
251
252 /* XXX: should be a template */
253 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
254    "HTTP/1.1 502 Server or forwarder response invalid\r\n"
255    "Content-Type: text/plain\r\n"
256    "Connection: close\r\n\r\n"
257    "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
258
259 /* XXX: should be a template */
260 static const char MESSED_UP_REQUEST_RESPONSE[] =
261    "HTTP/1.1 400 Malformed request after rewriting\r\n"
262    "Content-Type: text/plain\r\n"
263    "Connection: close\r\n\r\n"
264    "Bad request. Messed up with header filters.\r\n";
265
266 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
267    "HTTP/1.1 503 Too many open connections\r\n"
268    "Content-Type: text/plain\r\n"
269    "Connection: close\r\n\r\n"
270    "Maximum number of open connections reached.\r\n";
271
272 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
273    "HTTP/1.1 504 Connection timeout\r\n"
274    "Content-Type: text/plain\r\n"
275    "Connection: close\r\n\r\n"
276    "The connection timed out because the client request didn't arrive in time.\r\n";
277
278 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
279    "HTTP/1.1 400 Failed reading client body\r\n"
280    "Content-Type: text/plain\r\n"
281    "Connection: close\r\n\r\n"
282    "Failed parsing or buffering the chunk-encoded client body.\r\n";
283
284 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
285    "HTTP/1.1 417 Expecting too much\r\n"
286    "Content-Type: text/plain\r\n"
287    "Connection: close\r\n\r\n"
288    "Privoxy detected an unsupported Expect header value.\r\n";
289
290 /* A function to crunch a response */
291 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
292
293 /* Crunch function flags */
294 #define CF_NO_FLAGS        0
295 /* Cruncher applies to forced requests as well */
296 #define CF_IGNORE_FORCE    1
297 /* Crunched requests are counted for the block statistics */
298 #define CF_COUNT_AS_REJECT 2
299
300 /* A crunch function and its flags */
301 struct cruncher
302 {
303    const crunch_func_ptr cruncher;
304    const int flags;
305 };
306
307 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
308
309 /* Complete list of cruncher functions */
310 static const struct cruncher crunchers_all[] = {
311    { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
312    { block_url,       CF_COUNT_AS_REJECT },
313 #ifdef FEATURE_TRUST
314    { trust_url,       CF_COUNT_AS_REJECT },
315 #endif /* def FEATURE_TRUST */
316    { redirect_url,    CF_NO_FLAGS  },
317    { dispatch_cgi,    CF_IGNORE_FORCE},
318    { NULL,            0 }
319 };
320
321 /* Light version, used after tags are applied */
322 static const struct cruncher crunchers_light[] = {
323    { block_url,       CF_COUNT_AS_REJECT },
324    { redirect_url,    CF_NO_FLAGS },
325    { NULL,            0 }
326 };
327
328
329 /*
330  * XXX: Don't we really mean
331  *
332  * #if defined(unix)
333  *
334  * here?
335  */
336 #if !defined(_WIN32)
337 /*********************************************************************
338  *
339  * Function    :  sig_handler
340  *
341  * Description :  Signal handler for different signals.
342  *                Exit gracefully on TERM and INT
343  *                or set a flag that will cause the errlog
344  *                to be reopened by the main thread on HUP.
345  *
346  * Parameters  :
347  *          1  :  the_signal = the signal cause this function to call
348  *
349  * Returns     :  -
350  *
351  *********************************************************************/
352 static void sig_handler(int the_signal)
353 {
354    switch(the_signal)
355    {
356       case SIGTERM:
357       case SIGINT:
358          log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
359 #if defined(unix)
360          if (pidfile)
361          {
362             unlink(pidfile);
363          }
364 #endif /* unix */
365          exit(the_signal);
366          break;
367
368       case SIGHUP:
369 #if defined(unix)
370          received_hup_signal = 1;
371 #endif
372          break;
373
374       default:
375          /*
376           * We shouldn't be here, unless we catch signals
377           * in main() that we can't handle here!
378           */
379          log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
380    }
381    return;
382
383 }
384 #endif
385
386
387 /*********************************************************************
388  *
389  * Function    :  get_write_delay
390  *
391  * Description :  Parse the delay-response parameter.
392  *
393  * Parameters  :
394  *          1  :  csp = Current client state (buffers, headers, etc...)
395  *
396  * Returns     :  Number of milliseconds to delay writes.
397  *
398  *********************************************************************/
399 static unsigned int get_write_delay(const struct client_state *csp)
400 {
401    unsigned int delay;
402    char *endptr;
403    char *newval;
404
405    if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
406    {
407       return 0;
408    }
409    newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
410
411    delay = (unsigned)strtol(newval, &endptr, 0);
412    if (*endptr != '\0')
413    {
414       log_error(LOG_LEVEL_FATAL,
415          "Invalid delay-response{} parameter: '%s'", newval);
416    }
417
418    return delay;
419
420 }
421
422
423 /*********************************************************************
424  *
425  * Function    :  client_protocol_is_unsupported
426  *
427  * Description :  Checks if the client used a known unsupported
428  *                protocol and deals with it by sending an error
429  *                response.
430  *
431  * Parameters  :
432  *          1  :  csp = Current client state (buffers, headers, etc...)
433  *          2  :  req = the first request line send by the client
434  *
435  * Returns     :  TRUE if an error response has been generated, or
436  *                FALSE if the request doesn't look invalid.
437  *
438  *********************************************************************/
439 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
440 {
441    /*
442     * If it's a FTP or gopher request, we don't support it.
443     *
444     * These checks are better than nothing, but they might
445     * not work in all configurations and some clients might
446     * have problems digesting the answer.
447     *
448     * They should, however, never cause more problems than
449     * Privoxy's old behaviour (returning the misleading HTML
450     * error message:
451     *
452     * "Could not resolve http://(ftp|gopher)://example.org").
453     */
454    if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
455    {
456       const char *response = NULL;
457       const char *protocol = NULL;
458
459       if (!strncmpic(req, "GET ftp://", 10))
460       {
461          response = FTP_RESPONSE;
462          protocol = "FTP";
463       }
464       else
465       {
466          response = GOPHER_RESPONSE;
467          protocol = "GOPHER";
468       }
469       log_error(LOG_LEVEL_ERROR,
470          "%s tried to use Privoxy as %s proxy: %s",
471          csp->ip_addr_str, protocol, req);
472       log_error(LOG_LEVEL_CLF,
473          "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
474       freez(req);
475
476 #ifdef FEATURE_HTTPS_INSPECTION
477       if (client_use_ssl(csp))
478       {
479          ssl_send_data_delayed(&(csp->ssl_client_attr),
480             (const unsigned char *)response, strlen(response),
481             get_write_delay(csp));
482       }
483       else
484 #endif
485       {
486          write_socket_delayed(csp->cfd, response, strlen(response),
487             get_write_delay(csp));
488       }
489
490       return TRUE;
491    }
492
493    return FALSE;
494 }
495
496
497 /*********************************************************************
498  *
499  * Function    :  client_has_unsupported_expectations
500  *
501  * Description :  Checks if the client used an unsupported expectation
502  *                in which case an error message is delivered.
503  *
504  * Parameters  :
505  *          1  :  csp = Current client state (buffers, headers, etc...)
506  *
507  * Returns     :  TRUE if an error response has been generated, or
508  *                FALSE if the request doesn't look invalid.
509  *
510  *********************************************************************/
511 static int client_has_unsupported_expectations(const struct client_state *csp)
512 {
513    if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
514    {
515       log_error(LOG_LEVEL_ERROR,
516          "Rejecting request from client %s with unsupported Expect header value",
517          csp->ip_addr_str);
518       log_error(LOG_LEVEL_CLF,
519          "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
520       write_socket_delayed(csp->cfd,
521          UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
522          strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
523          get_write_delay(csp));
524
525       return TRUE;
526    }
527
528    return FALSE;
529
530 }
531
532
533 /*********************************************************************
534  *
535  * Function    :  get_request_destination_elsewhere
536  *
537  * Description :  If the client's request was redirected into
538  *                Privoxy without the client's knowledge,
539  *                the request line lacks the destination host.
540  *
541  *                This function tries to get it elsewhere,
542  *                provided accept-intercepted-requests is enabled.
543  *
544  *                "Elsewhere" currently only means "Host: header",
545  *                but in the future we may ask the redirecting
546  *                packet filter to look the destination up.
547  *
548  *                If the destination stays unknown, an error
549  *                response is send to the client and headers
550  *                are freed so that chat() can return directly.
551  *
552  * Parameters  :
553  *          1  :  csp = Current client state (buffers, headers, etc...)
554  *          2  :  headers = a header list
555  *
556  * Returns     :  JB_ERR_OK if the destination is now known, or
557  *                JB_ERR_PARSE if it isn't.
558  *
559  *********************************************************************/
560 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
561 {
562    if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
563    {
564       log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
565          " Privoxy isn't configured to accept intercepted requests.",
566          csp->ip_addr_str, csp->http->cmd);
567       /* XXX: Use correct size */
568       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
569          csp->ip_addr_str, csp->http->cmd);
570
571       write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
572          get_write_delay(csp));
573       destroy_list(headers);
574
575       return JB_ERR_PARSE;
576    }
577    else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
578    {
579       /* Split the domain we just got for pattern matching */
580       init_domain_components(csp->http);
581
582       return JB_ERR_OK;
583    }
584    else
585    {
586       /* We can't work without destination. Go spread the news.*/
587
588       /* XXX: Use correct size */
589       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
590          csp->ip_addr_str, csp->http->cmd);
591       log_error(LOG_LEVEL_ERROR,
592          "Privoxy was unable to get the destination for %s's request: %s",
593          csp->ip_addr_str, csp->http->cmd);
594
595       write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
596          strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
597       destroy_list(headers);
598
599       return JB_ERR_PARSE;
600    }
601    /*
602     * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
603     * to get the destination IP address, use it as host directly
604     * or do a reverse DNS lookup first.
605     */
606 }
607
608
609 /*********************************************************************
610  *
611  * Function    :  get_server_headers
612  *
613  * Description :  Parses server headers in iob and fills them
614  *                into csp->headers so that they can later be
615  *                handled by sed().
616  *
617  * Parameters  :
618  *          1  :  csp = Current client state (buffers, headers, etc...)
619  *
620  * Returns     :  JB_ERR_OK if everything went fine, or
621  *                JB_ERR_PARSE if the headers were incomplete.
622  *
623  *********************************************************************/
624 static jb_err get_server_headers(struct client_state *csp)
625 {
626    int continue_hack_in_da_house = 0;
627    char * header;
628
629    while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
630    {
631       if (header == NULL)
632       {
633          /*
634           * continue hack in da house. Ignore the ending of
635           * this head and continue enlisting header lines.
636           * The reason is described below.
637           */
638          enlist(csp->headers, "");
639          continue_hack_in_da_house = 0;
640          continue;
641       }
642       else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
643       {
644          /*
645           * It's a bodyless continue response, don't
646           * stop header parsing after reaching its end.
647           *
648           * As a result Privoxy will concatenate the
649           * next response's head and parse and deliver
650           * the headers as if they belonged to one request.
651           *
652           * The client will separate them because of the
653           * empty line between them.
654           *
655           * XXX: What we're doing here is clearly against
656           * the intended purpose of the continue header,
657           * and under some conditions (HTTP/1.0 client request)
658           * it's a standard violation.
659           *
660           * Anyway, "sort of against the spec" is preferable
661           * to "always getting confused by Continue responses"
662           * (Privoxy's behaviour before this hack was added)
663           */
664          log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
665          continue_hack_in_da_house = 1;
666       }
667       else if (*header == '\0')
668       {
669          /*
670           * If the header is empty, but the Continue hack
671           * isn't active, we can assume that we reached the
672           * end of the buffer before we hit the end of the
673           * head.
674           *
675           * Inform the caller an let it decide how to handle it.
676           */
677          return JB_ERR_PARSE;
678       }
679
680       if (JB_ERR_MEMORY == enlist(csp->headers, header))
681       {
682          /*
683           * XXX: Should we quit the request and return a
684           * out of memory error page instead?
685           */
686          log_error(LOG_LEVEL_ERROR,
687             "Out of memory while enlisting server headers. %s lost.",
688             header);
689       }
690       freez(header);
691    }
692
693    return JB_ERR_OK;
694 }
695
696
697 /*********************************************************************
698  *
699  * Function    :  crunch_reason
700  *
701  * Description :  Translates the crunch reason code into a string.
702  *
703  * Parameters  :
704  *          1  :  rsp = a http_response
705  *
706  * Returns     :  A string with the crunch reason or an error description.
707  *
708  *********************************************************************/
709 static const char *crunch_reason(const struct http_response *rsp)
710 {
711    char * reason = NULL;
712
713    assert(rsp != NULL);
714    if (rsp == NULL)
715    {
716       return "Internal error while searching for crunch reason";
717    }
718
719    switch (rsp->crunch_reason)
720    {
721       case UNSUPPORTED:
722          reason = "Unsupported HTTP feature";
723          break;
724       case BLOCKED:
725          reason = "Blocked";
726          break;
727       case UNTRUSTED:
728          reason = "Untrusted";
729          break;
730       case REDIRECTED:
731          reason = "Redirected";
732          break;
733       case CGI_CALL:
734          reason = "CGI Call";
735          break;
736       case NO_SUCH_DOMAIN:
737          reason = "DNS failure";
738          break;
739       case FORWARDING_FAILED:
740          reason = "Forwarding failed";
741          break;
742       case CONNECT_FAILED:
743          reason = "Connection failure";
744          break;
745       case OUT_OF_MEMORY:
746          reason = "Out of memory (may mask other reasons)";
747          break;
748       case CONNECTION_TIMEOUT:
749          reason = "Connection timeout";
750          break;
751       case NO_SERVER_DATA:
752          reason = "No server data received";
753          break;
754       default:
755          reason = "No reason recorded";
756          break;
757    }
758
759    return reason;
760 }
761
762
763 /*********************************************************************
764  *
765  * Function    :  log_applied_actions
766  *
767  * Description :  Logs the applied actions if LOG_LEVEL_ACTIONS is
768  *                enabled.
769  *
770  * Parameters  :
771  *          1  :  actions = Current action spec to log
772  *
773  * Returns     :  Nothing.
774  *
775  *********************************************************************/
776 static void log_applied_actions(const struct current_action_spec *actions)
777 {
778    /*
779     * The conversion to text requires lots of memory allocations so
780     * we only do the conversion if the user is actually interested.
781     */
782    if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
783    {
784       char *actions_as_text = actions_to_line_of_text(actions);
785       log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
786       freez(actions_as_text);
787    }
788 }
789
790
791 /*********************************************************************
792  *
793  * Function    :  send_crunch_response
794  *
795  * Description :  Delivers already prepared response for
796  *                intercepted requests, logs the interception
797  *                and frees the response.
798  *
799  * Parameters  :
800  *          1  :  csp = Current client state (buffers, headers, etc...)
801  *          2  :  rsp = Fully prepared response. Will be freed on exit.
802  *
803  * Returns     :  Nothing.
804  *
805  *********************************************************************/
806 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
807 {
808       const struct http_request *http = csp->http;
809       char status_code[4];
810
811       assert(rsp != NULL);
812       assert(rsp->head != NULL);
813
814       if (rsp == NULL)
815       {
816          log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
817       }
818
819       /*
820        * Extract the status code from the actual head
821        * that will be send to the client. It is the only
822        * way to get it right for all requests, including
823        * the fixed ones for out-of-memory problems.
824        *
825        * A head starts like this: 'HTTP/1.1 200...'
826        *                           0123456789|11
827        *                                     10
828        */
829       status_code[0] = rsp->head[9];
830       status_code[1] = rsp->head[10];
831       status_code[2] = rsp->head[11];
832       status_code[3] = '\0';
833
834       /* Log that the request was crunched and why. */
835       log_applied_actions(csp->action);
836 #ifdef FEATURE_HTTPS_INSPECTION
837       if (client_use_ssl(csp))
838       {
839          log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
840             http->hostport, http->path);
841          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %lu",
842             csp->ip_addr_str, http->gpc, http->hostport, http->path,
843             http->version, status_code, rsp->content_length);
844       }
845       else
846 #endif
847       {
848          log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
849          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %lu",
850             csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
851       }
852       /* Write the answer to the client */
853 #ifdef FEATURE_HTTPS_INSPECTION
854       if (client_use_ssl(csp))
855       {
856          if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
857                 (const unsigned char *)rsp->head, rsp->head_length,
858                 get_write_delay(csp)) < 0)
859           || (ssl_send_data_delayed(&(csp->ssl_client_attr),
860                 (const unsigned char *)rsp->body, rsp->content_length,
861                 get_write_delay(csp)) < 0))
862          {
863             /* There is nothing we can do about it. */
864             log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
865                "for https://%s%s through client socket %d using TLS/SSL",
866                http->hostport, http->url, csp->cfd);
867          }
868       }
869       else
870 #endif
871       {
872          if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
873                 get_write_delay(csp))
874           || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
875                 get_write_delay(csp)))
876          {
877             /* There is nothing we can do about it. */
878             log_error(LOG_LEVEL_CONNECT,
879                "Couldn't deliver the error message for %s through client socket %d: %E",
880                http->url, csp->cfd);
881          }
882       }
883
884       /* Clean up and return */
885       if (cgi_error_memory() != rsp)
886       {
887          free_http_response(rsp);
888       }
889       return;
890 }
891
892
893 /*********************************************************************
894  *
895  * Function    :  crunch_response_triggered
896  *
897  * Description :  Checks if the request has to be crunched,
898  *                and delivers the crunch response if necessary.
899  *
900  * Parameters  :
901  *          1  :  csp = Current client state (buffers, headers, etc...)
902  *          2  :  crunchers = list of cruncher functions to run
903  *
904  * Returns     :  TRUE if the request was answered with a crunch response
905  *                FALSE otherwise.
906  *
907  *********************************************************************/
908 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
909 {
910    struct http_response *rsp = NULL;
911    const struct cruncher *c;
912
913    /*
914     * If CGI request crunching is disabled,
915     * check the CGI dispatcher out of order to
916     * prevent unintentional blocks or redirects.
917     */
918    if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
919        && (NULL != (rsp = dispatch_cgi(csp))))
920    {
921       /* Deliver, log and free the interception response. */
922       send_crunch_response(csp, rsp);
923       csp->flags |= CSP_FLAG_CRUNCHED;
924       return TRUE;
925    }
926
927    for (c = crunchers; c->cruncher != NULL; c++)
928    {
929       /*
930        * Check the cruncher if either Privoxy is toggled
931        * on and the request isn't forced, or if the cruncher
932        * applies to forced requests as well.
933        */
934       if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
935           !(csp->flags & CSP_FLAG_FORCED)) ||
936           (c->flags & CF_IGNORE_FORCE))
937       {
938          rsp = c->cruncher(csp);
939          if (NULL != rsp)
940          {
941             /* Deliver, log and free the interception response. */
942             send_crunch_response(csp, rsp);
943             csp->flags |= CSP_FLAG_CRUNCHED;
944 #ifdef FEATURE_STATISTICS
945             if (c->flags & CF_COUNT_AS_REJECT)
946             {
947                csp->flags |= CSP_FLAG_REJECTED;
948             }
949 #endif /* def FEATURE_STATISTICS */
950
951             return TRUE;
952          }
953       }
954    }
955
956    return FALSE;
957 }
958
959
960 /*********************************************************************
961  *
962  * Function    :  build_request_line
963  *
964  * Description :  Builds the HTTP request line.
965  *
966  *                If a HTTP forwarder is used it expects the whole URL,
967  *                web servers only get the path.
968  *
969  * Parameters  :
970  *          1  :  csp = Current client state (buffers, headers, etc...)
971  *          2  :  fwd = The forwarding spec used for the request.
972  *                      Can be NULL.
973  *          3  :  request_line = The old request line which will be replaced.
974  *
975  * Returns     :  Nothing. Terminates in case of memory problems.
976  *
977  *********************************************************************/
978 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
979 {
980    struct http_request *http = csp->http;
981
982    /*
983     * Downgrade http version from 1.1 to 1.0
984     * if +downgrade action applies.
985     */
986    if ((csp->action->flags & ACTION_DOWNGRADE)
987      && (!strcmpic(http->version, "HTTP/1.1")))
988    {
989       freez(http->version);
990       http->version = strdup_or_die("HTTP/1.0");
991    }
992
993    /*
994     * Rebuild the request line.
995     */
996    freez(*request_line);
997    *request_line = strdup(http->gpc);
998    string_append(request_line, " ");
999
1000    if (fwd != NULL && fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1001    {
1002       string_append(request_line, http->url);
1003    }
1004    else
1005    {
1006       string_append(request_line, http->path);
1007    }
1008    string_append(request_line, " ");
1009    string_append(request_line, http->version);
1010
1011    if (*request_line == NULL)
1012    {
1013       log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1014    }
1015    log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1016 }
1017
1018
1019 /*********************************************************************
1020  *
1021  * Function    :  change_request_destination
1022  *
1023  * Description :  Parse a (rewritten) request line and regenerate
1024  *                the http request data.
1025  *
1026  * Parameters  :
1027  *          1  :  csp = Current client state (buffers, headers, etc...)
1028  *
1029  * Returns     :  Forwards the parse_http_request() return code.
1030  *                Terminates in case of memory problems.
1031  *
1032  *********************************************************************/
1033 static jb_err change_request_destination(struct client_state *csp)
1034 {
1035    struct http_request *http = csp->http;
1036    jb_err err;
1037
1038    log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1039       csp->headers->first->str);
1040    free_http_request(http);
1041    err = parse_http_request(csp->headers->first->str, http);
1042    if (JB_ERR_OK != err)
1043    {
1044       log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1045          jb_err_to_string(err));
1046    }
1047
1048    return err;
1049 }
1050
1051
1052 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1053 /*********************************************************************
1054  *
1055  * Function    :  server_response_is_complete
1056  *
1057  * Description :  Determines whether we should stop reading
1058  *                from the server socket.
1059  *
1060  * Parameters  :
1061  *          1  :  csp = Current client state (buffers, headers, etc...)
1062  *          2  :  content_length = Length of content received so far.
1063  *
1064  * Returns     :  TRUE if the response is complete,
1065  *                FALSE otherwise.
1066  *
1067  *********************************************************************/
1068 static int server_response_is_complete(struct client_state *csp,
1069    unsigned long long content_length)
1070 {
1071    int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1072
1073    if (!strcmpic(csp->http->gpc, "HEAD"))
1074    {
1075       /*
1076        * "HEAD" implies no body, we are thus expecting
1077        * no content. XXX: incomplete "list" of methods?
1078        */
1079       csp->expected_content_length = 0;
1080       content_length_known = TRUE;
1081       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1082    }
1083
1084    if (csp->http->status == 204 || csp->http->status == 304)
1085    {
1086       /*
1087        * Expect no body. XXX: incomplete "list" of status codes?
1088        */
1089       csp->expected_content_length = 0;
1090       content_length_known = TRUE;
1091       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1092    }
1093
1094    return (content_length_known && ((0 == csp->expected_content_length)
1095             || (csp->expected_content_length <= content_length)));
1096 }
1097
1098
1099 #ifdef FEATURE_CONNECTION_SHARING
1100 /*********************************************************************
1101  *
1102  * Function    :  wait_for_alive_connections
1103  *
1104  * Description :  Waits for alive connections to timeout.
1105  *
1106  * Parameters  :  N/A
1107  *
1108  * Returns     :  N/A
1109  *
1110  *********************************************************************/
1111 static void wait_for_alive_connections(void)
1112 {
1113    int connections_alive = close_unusable_connections();
1114
1115    while (0 < connections_alive)
1116    {
1117       log_error(LOG_LEVEL_CONNECT,
1118          "Waiting for %d connections to timeout.",
1119          connections_alive);
1120       sleep(60);
1121       connections_alive = close_unusable_connections();
1122    }
1123
1124    log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1125
1126 }
1127 #endif /* def FEATURE_CONNECTION_SHARING */
1128
1129
1130 /*********************************************************************
1131  *
1132  * Function    :  save_connection_destination
1133  *
1134  * Description :  Remembers a connection for reuse later on.
1135  *
1136  * Parameters  :
1137  *          1  :  sfd  = Open socket to remember.
1138  *          2  :  http = The destination for the connection.
1139  *          3  :  fwd  = The forwarder settings used.
1140  *          4  :  server_connection  = storage.
1141  *
1142  * Returns     : void
1143  *
1144  *********************************************************************/
1145 void save_connection_destination(jb_socket sfd,
1146                                  const struct http_request *http,
1147                                  const struct forward_spec *fwd,
1148                                  struct reusable_connection *server_connection)
1149 {
1150    assert(sfd != JB_INVALID_SOCKET);
1151    assert(NULL != http->host);
1152
1153    server_connection->sfd = sfd;
1154    server_connection->host = strdup_or_die(http->host);
1155    server_connection->port = http->port;
1156
1157    assert(NULL != fwd);
1158    assert(server_connection->gateway_host == NULL);
1159    assert(server_connection->gateway_port == 0);
1160    assert(server_connection->forwarder_type == 0);
1161    assert(server_connection->forward_host == NULL);
1162    assert(server_connection->forward_port == 0);
1163
1164    server_connection->forwarder_type = fwd->type;
1165    if (NULL != fwd->gateway_host)
1166    {
1167       server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1168    }
1169    else
1170    {
1171       server_connection->gateway_host = NULL;
1172    }
1173    server_connection->gateway_port = fwd->gateway_port;
1174    if (NULL != fwd->auth_username)
1175    {
1176       server_connection->auth_username = strdup_or_die(fwd->auth_username);
1177    }
1178    else
1179    {
1180       server_connection->auth_username = NULL;
1181    }
1182    if (NULL != fwd->auth_password)
1183    {
1184       server_connection->auth_password = strdup_or_die(fwd->auth_password);
1185    }
1186    else
1187    {
1188       server_connection->auth_password = NULL;
1189    }
1190
1191    if (NULL != fwd->forward_host)
1192    {
1193       server_connection->forward_host = strdup_or_die(fwd->forward_host);
1194    }
1195    else
1196    {
1197       server_connection->forward_host = NULL;
1198    }
1199    server_connection->forward_port = fwd->forward_port;
1200 }
1201 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1202
1203
1204 /*********************************************************************
1205  *
1206  * Function    : verify_request_length
1207  *
1208  * Description : Checks if we already got the whole client requests
1209  *               and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1210  *               we do.
1211  *
1212  *               Data that doesn't belong to the current request is
1213  *               either thrown away to let the client retry on a clean
1214  *               socket, or stashed to be dealt with after the current
1215  *               request is served.
1216  *
1217  * Parameters  :
1218  *          1  :  csp = Current client state (buffers, headers, etc...)
1219  *
1220  * Returns     :  void
1221  *
1222  *********************************************************************/
1223 static void verify_request_length(struct client_state *csp)
1224 {
1225    unsigned long long buffered_request_bytes =
1226       (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1227
1228    if ((csp->expected_client_content_length != 0)
1229       && (buffered_request_bytes != 0))
1230    {
1231       if (csp->expected_client_content_length >= buffered_request_bytes)
1232       {
1233          csp->expected_client_content_length -= buffered_request_bytes;
1234          log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1235             "to account for the %llu ones we already got.",
1236             csp->expected_client_content_length, buffered_request_bytes);
1237       }
1238       else
1239       {
1240          assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1241          csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1242          log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1243             "Marking the server socket tainted after throwing %llu bytes away.",
1244             buffered_request_bytes - csp->expected_client_content_length);
1245          csp->expected_client_content_length = 0;
1246          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1247       }
1248
1249       if (csp->expected_client_content_length == 0)
1250       {
1251          csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1252       }
1253    }
1254
1255    if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1256       && ((csp->client_iob->cur < csp->client_iob->eod)
1257          || (csp->expected_client_content_length != 0)))
1258    {
1259       if (strcmpic(csp->http->gpc, "GET")
1260          && strcmpic(csp->http->gpc, "HEAD")
1261          && strcmpic(csp->http->gpc, "TRACE")
1262          && strcmpic(csp->http->gpc, "OPTIONS")
1263          && strcmpic(csp->http->gpc, "DELETE"))
1264       {
1265          /* XXX: this is an incomplete hack */
1266          csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1267          log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1268       }
1269       else
1270       {
1271          csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1272
1273          if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1274          {
1275             csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1276             log_error(LOG_LEVEL_CONNECT,
1277                "Possible pipeline attempt detected. The connection will not "
1278                "be kept alive and we will only serve the first request.");
1279             /* Nuke the pipelined requests from orbit, just to be sure. */
1280             clear_iob(csp->client_iob);
1281          }
1282          else
1283          {
1284             /*
1285              * Keep the pipelined data around for now, we'll deal with
1286              * it once we're done serving the current request.
1287              */
1288             csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1289             assert(csp->client_iob->eod >= csp->client_iob->cur);
1290             log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1291                "%d bytes of pipelined data received.",
1292                (int)(csp->client_iob->eod - csp->client_iob->cur));
1293          }
1294       }
1295    }
1296    else
1297    {
1298       csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1299       log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1300    }
1301 }
1302
1303
1304 /*********************************************************************
1305  *
1306  * Function    :  mark_server_socket_tainted
1307  *
1308  * Description :  Makes sure we don't reuse a server socket
1309  *                (if we didn't read everything the server sent
1310  *                us reusing the socket would lead to garbage).
1311  *
1312  * Parameters  :
1313  *          1  :  csp = Current client state (buffers, headers, etc...)
1314  *
1315  * Returns     :  void.
1316  *
1317  *********************************************************************/
1318 static void mark_server_socket_tainted(struct client_state *csp)
1319 {
1320    /*
1321     * For consistency we always mark the server socket
1322     * tainted, however, to reduce the log noise we only
1323     * emit a log message if the server socket could have
1324     * actually been reused.
1325     */
1326    if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1327       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1328    {
1329       log_error(LOG_LEVEL_CONNECT,
1330          "Marking the server socket %d tainted.",
1331          csp->server_connection.sfd);
1332    }
1333    csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1334 }
1335
1336 /*********************************************************************
1337  *
1338  * Function    :  get_request_line
1339  *
1340  * Description : Read the client request line.
1341  *
1342  * Parameters  :
1343  *          1  :  csp = Current client state (buffers, headers, etc...)
1344  *
1345  * Returns     :  Pointer to request line or NULL in case of errors.
1346  *
1347  *********************************************************************/
1348 static char *get_request_line(struct client_state *csp)
1349 {
1350    char buf[BUFFER_SIZE];
1351    char *request_line = NULL;
1352    int len;
1353
1354    memset(buf, 0, sizeof(buf));
1355
1356    if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1357    {
1358       /*
1359        * If there are multiple pipelined requests waiting,
1360        * the flag will be set again once the next request
1361        * has been parsed.
1362        */
1363       csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1364
1365       request_line = get_header(csp->client_iob);
1366       if ((NULL != request_line) && ('\0' != *request_line))
1367       {
1368          return request_line;
1369       }
1370       else
1371       {
1372          log_error(LOG_LEVEL_CONNECT, "No complete request line "
1373             "received yet. Continuing reading from %d.", csp->cfd);
1374       }
1375    }
1376
1377    do
1378    {
1379       if (
1380 #ifdef FUZZ
1381           0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1382 #endif
1383           !data_is_available(csp->cfd, csp->config->socket_timeout)
1384           )
1385       {
1386          if (socket_is_still_alive(csp->cfd))
1387          {
1388             log_error(LOG_LEVEL_CONNECT,
1389                "No request line on socket %d received in time. Timeout: %d.",
1390                csp->cfd, csp->config->socket_timeout);
1391             write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1392                strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1393                get_write_delay(csp));
1394          }
1395          else
1396          {
1397             log_error(LOG_LEVEL_CONNECT,
1398                "The client side of the connection on socket %d got "
1399                "closed without sending a complete request line.", csp->cfd);
1400          }
1401          return NULL;
1402       }
1403
1404       len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1405
1406       if (len <= 0) return NULL;
1407
1408       /*
1409        * If there is no memory left for buffering the
1410        * request, there is nothing we can do but hang up
1411        */
1412       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1413       {
1414          return NULL;
1415       }
1416
1417       request_line = get_header(csp->client_iob);
1418
1419    } while ((NULL != request_line) && ('\0' == *request_line));
1420
1421    return request_line;
1422
1423 }
1424
1425 enum chunk_status
1426 {
1427    CHUNK_STATUS_MISSING_DATA,
1428    CHUNK_STATUS_BODY_COMPLETE,
1429    CHUNK_STATUS_PARSE_ERROR
1430 };
1431
1432
1433 /*********************************************************************
1434  *
1435  * Function    :  chunked_body_is_complete
1436  *
1437  * Description :  Figures out whether or not a chunked body is complete.
1438  *
1439  *                Currently it always starts at the beginning of the
1440  *                buffer which is somewhat wasteful and prevents Privoxy
1441  *                from starting to forward the correctly parsed chunks
1442  *                as soon as theoretically possible.
1443  *
1444  *                Should be modified to work with a common buffer,
1445  *                and allow the caller to skip already parsed chunks.
1446  *
1447  *                This would allow the function to be used for unbuffered
1448  *                response bodies as well.
1449  *
1450  * Parameters  :
1451  *          1  :  iob = Buffer with the body to check.
1452  *          2  :  length = Length of complete body
1453  *
1454  * Returns     :  Enum with the result of the check.
1455  *
1456  *********************************************************************/
1457 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1458 {
1459    unsigned int chunksize;
1460    char *p = iob->cur;
1461
1462    do
1463    {
1464       /*
1465        * We need at least a single digit, followed by "\r\n",
1466        * followed by an unknown amount of data, followed by "\r\n".
1467        */
1468       if (p + 5 > iob->eod)
1469       {
1470          return CHUNK_STATUS_MISSING_DATA;
1471       }
1472       if (sscanf(p, "%x", &chunksize) != 1)
1473       {
1474          return CHUNK_STATUS_PARSE_ERROR;
1475       }
1476
1477       /*
1478        * We want at least a single digit, followed by "\r\n",
1479        * followed by the specified amount of data, followed by "\r\n".
1480        */
1481       if (p + chunksize + 5 > iob->eod)
1482       {
1483          return CHUNK_STATUS_MISSING_DATA;
1484       }
1485
1486       /* Skip chunk-size. */
1487       p = strstr(p, "\r\n");
1488       if (NULL == p)
1489       {
1490          return CHUNK_STATUS_PARSE_ERROR;
1491       }
1492       /* Move beyond the chunkdata. */
1493       p += 2 + chunksize;
1494
1495       /* There should be another "\r\n" to skip */
1496       if (memcmp(p, "\r\n", 2))
1497       {
1498          return CHUNK_STATUS_PARSE_ERROR;
1499       }
1500       p += 2;
1501    } while (chunksize > 0U);
1502
1503    *length = (size_t)(p - iob->cur);
1504    assert(*length <= (size_t)(iob->eod - iob->cur));
1505    assert(p <= iob->eod);
1506
1507    return CHUNK_STATUS_BODY_COMPLETE;
1508
1509 }
1510
1511
1512 /*********************************************************************
1513  *
1514  * Function    : receive_chunked_client_request_body
1515  *
1516  * Description : Read the chunk-encoded client request body.
1517  *               Failures are dealt with.
1518  *
1519  * Parameters  :
1520  *          1  :  csp = Current client state (buffers, headers, etc...)
1521  *
1522  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1523  *
1524  *********************************************************************/
1525 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1526 {
1527    size_t body_length;
1528    enum chunk_status status;
1529
1530    while (CHUNK_STATUS_MISSING_DATA ==
1531       (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1532    {
1533       char buf[BUFFER_SIZE];
1534       int len;
1535
1536       if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1537       {
1538          log_error(LOG_LEVEL_ERROR,
1539             "Timeout while waiting for the client body.");
1540          break;
1541       }
1542       len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1543       if (len <= 0)
1544       {
1545          log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1546          break;
1547       }
1548       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1549       {
1550          break;
1551       }
1552    }
1553    if (status != CHUNK_STATUS_BODY_COMPLETE)
1554    {
1555       write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1556          strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1557       log_error(LOG_LEVEL_CLF,
1558          "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1559       return JB_ERR_PARSE;
1560    }
1561    log_error(LOG_LEVEL_CONNECT,
1562       "Chunked client body completely read. Length: %lu", body_length);
1563    csp->expected_client_content_length = body_length;
1564
1565    return JB_ERR_OK;
1566
1567 }
1568
1569
1570 #ifdef FUZZ
1571 /*********************************************************************
1572  *
1573  * Function    :  fuzz_chunked_transfer_encoding
1574  *
1575  * Description :  Treat the fuzzed input as chunked transfer encoding
1576  *                to check and dechunk.
1577  *
1578  * Parameters  :
1579  *          1  :  csp      = Used to store the data.
1580  *          2  :  fuzz_input_file = File to read the input from.
1581  *
1582  * Returns     : Result of dechunking
1583  *
1584  *********************************************************************/
1585 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1586 {
1587    size_t length;
1588    size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1589    enum chunk_status status;
1590
1591    status = chunked_body_is_complete(csp->iob, &length);
1592    if (CHUNK_STATUS_BODY_COMPLETE != status)
1593    {
1594       log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1595    }
1596
1597    return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1598
1599 }
1600
1601
1602 /*********************************************************************
1603  *
1604  * Function    : fuzz_client_request
1605  *
1606  * Description : Try to get a client request from the fuzzed input.
1607  *
1608  * Parameters  :
1609  *          1  :  csp = Current client state (buffers, headers, etc...)
1610  *          2  :  fuzz_input_file = File to read the input from.
1611  *
1612  * Returns     :  Result of fuzzing.
1613  *
1614  *********************************************************************/
1615 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1616 {
1617    jb_err err;
1618
1619    csp->cfd = 0;
1620    csp->ip_addr_str = "fuzzer";
1621
1622    if (strcmp(fuzz_input_file, "-") != 0)
1623    {
1624       log_error(LOG_LEVEL_FATAL,
1625          "Fuzzed client requests can currently only be read from stdin (-).");
1626    }
1627    err = receive_client_request(csp);
1628    if (err != JB_ERR_OK)
1629    {
1630       return 1;
1631    }
1632    err = parse_client_request(csp);
1633    if (err != JB_ERR_OK)
1634    {
1635       return 1;
1636    }
1637
1638    return 0;
1639
1640 }
1641 #endif  /* def FUZZ */
1642
1643
1644 #ifdef FEATURE_FORCE_LOAD
1645 /*********************************************************************
1646  *
1647  * Function    :  force_required
1648  *
1649  * Description : Checks a request line to see if it contains
1650  *               the FORCE_PREFIX. If it does, it is removed
1651  *               unless enforcing requests has beend disabled.
1652  *
1653  * Parameters  :
1654  *          1  :  request_line = HTTP request line
1655  *
1656  * Returns     :  TRUE if force is required, FALSE otherwise.
1657  *
1658  *********************************************************************/
1659 static int force_required(const struct client_state *csp, char *request_line)
1660 {
1661    char *p;
1662
1663    p = strstr(request_line, "http://");
1664    if (p != NULL)
1665    {
1666       /* Skip protocol */
1667       p += strlen("http://");
1668    }
1669    else
1670    {
1671       /* Intercepted request usually don't specify the protocol. */
1672       p = request_line;
1673    }
1674
1675    /* Go to the beginning of the path */
1676    p = strstr(p, "/");
1677    if (p == NULL)
1678    {
1679       /*
1680        * If the path is missing the request line is invalid and we
1681        * are done here. The client-visible rejection happens later on.
1682        */
1683       return 0;
1684    }
1685
1686    if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1687    {
1688       if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1689       {
1690          /* XXX: Should clean more carefully */
1691          strclean(request_line, FORCE_PREFIX);
1692          log_error(LOG_LEVEL_FORCE,
1693             "Enforcing request: \"%s\".", request_line);
1694
1695          return 1;
1696       }
1697       log_error(LOG_LEVEL_FORCE,
1698          "Ignored force prefix in request: \"%s\".", request_line);
1699    }
1700
1701    return 0;
1702
1703 }
1704 #endif /* def FEATURE_FORCE_LOAD */
1705
1706
1707 /*********************************************************************
1708  *
1709  * Function    :  receive_client_request
1710  *
1711  * Description : Read the client's request (more precisely the
1712  *               client headers) and answer it if necessary.
1713  *
1714  * Parameters  :
1715  *          1  :  csp = Current client state (buffers, headers, etc...)
1716  *
1717  * Returns     :  JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1718  *
1719  *********************************************************************/
1720 static jb_err receive_client_request(struct client_state *csp)
1721 {
1722    char buf[BUFFER_SIZE];
1723    char *p;
1724    char *req = NULL;
1725    struct http_request *http;
1726    int len;
1727    jb_err err;
1728
1729    /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1730    struct list header_list;
1731    struct list *headers = &header_list;
1732
1733    /* We don't care if the arriving data is a valid HTTP request or not. */
1734    csp->requests_received_total++;
1735
1736    http = csp->http;
1737
1738    memset(buf, 0, sizeof(buf));
1739
1740    req = get_request_line(csp);
1741    if (req == NULL)
1742    {
1743       mark_server_socket_tainted(csp);
1744       return JB_ERR_PARSE;
1745    }
1746    assert(*req != '\0');
1747
1748    if (client_protocol_is_unsupported(csp, req))
1749    {
1750       return JB_ERR_PARSE;
1751    }
1752
1753 #ifdef FEATURE_FORCE_LOAD
1754    if (force_required(csp, req))
1755    {
1756       csp->flags |= CSP_FLAG_FORCED;
1757    }
1758 #endif /* def FEATURE_FORCE_LOAD */
1759
1760    err = parse_http_request(req, http);
1761    freez(req);
1762    if (JB_ERR_OK != err)
1763    {
1764       write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1765          get_write_delay(csp));
1766       /* XXX: Use correct size */
1767       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1768       log_error(LOG_LEVEL_ERROR,
1769          "Couldn't parse request line received from %s: %s",
1770          csp->ip_addr_str, jb_err_to_string(err));
1771
1772       free_http_request(http);
1773       return JB_ERR_PARSE;
1774    }
1775
1776    /* grab the rest of the client's headers */
1777    init_list(headers);
1778    for (;;)
1779    {
1780       p = get_header(csp->client_iob);
1781
1782       if (p == NULL)
1783       {
1784          /* There are no additional headers to read. */
1785          break;
1786       }
1787
1788       if (*p == '\0')
1789       {
1790          /*
1791           * We didn't receive a complete header
1792           * line yet, get the rest of it.
1793           */
1794          if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1795          {
1796             log_error(LOG_LEVEL_ERROR,
1797                "Stopped grabbing the client headers.");
1798             destroy_list(headers);
1799             return JB_ERR_PARSE;
1800          }
1801
1802          len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1803          if (len <= 0)
1804          {
1805             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1806             destroy_list(headers);
1807             return JB_ERR_PARSE;
1808          }
1809
1810          if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1811          {
1812             /*
1813              * If there is no memory left for buffering the
1814              * request, there is nothing we can do but hang up
1815              */
1816             destroy_list(headers);
1817             return JB_ERR_MEMORY;
1818          }
1819       }
1820       else
1821       {
1822          if (!strncmpic(p, "Transfer-Encoding:", 18))
1823          {
1824             /*
1825              * XXX: should be called through sed()
1826              *      but currently can't.
1827              */
1828             client_transfer_encoding(csp, &p);
1829          }
1830          /*
1831           * We were able to read a complete
1832           * header and can finally enlist it.
1833           */
1834          enlist(headers, p);
1835          freez(p);
1836       }
1837    }
1838
1839    if (http->host == NULL)
1840    {
1841       /*
1842        * If we still don't know the request destination,
1843        * the request is invalid or the client uses
1844        * Privoxy without its knowledge.
1845        */
1846       if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1847       {
1848          /*
1849           * Our attempts to get the request destination
1850           * elsewhere failed or Privoxy is configured
1851           * to only accept proxy requests.
1852           *
1853           * An error response has already been send
1854           * and we're done here.
1855           */
1856          return JB_ERR_PARSE;
1857       }
1858    }
1859
1860 #ifdef FEATURE_CLIENT_TAGS
1861    /* XXX: If the headers were enlisted sooner, passing csp would do. */
1862    set_client_address(csp, headers);
1863    get_tag_list_for_client(csp->client_tags, csp->client_address);
1864 #endif
1865
1866    /*
1867     * Determine the actions for this URL
1868     */
1869 #ifdef FEATURE_TOGGLE
1870    if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1871    {
1872       /* Most compatible set of actions (i.e. none) */
1873       init_current_action(csp->action);
1874    }
1875    else
1876 #endif /* ndef FEATURE_TOGGLE */
1877    {
1878       get_url_actions(csp, http);
1879    }
1880
1881    enlist(csp->headers, http->cmd);
1882
1883    /* Append the previously read headers */
1884    err = list_append_list_unique(csp->headers, headers);
1885    destroy_list(headers);
1886
1887    return err;
1888
1889 }
1890
1891
1892 /*********************************************************************
1893  *
1894  * Function    : parse_client_request
1895  *
1896  * Description : Parses the client's request and decides what to do
1897  *               with it.
1898  *
1899  *               Note that since we're not using select() we could get
1900  *               blocked here if a client connected, then didn't say
1901  *               anything!
1902  *
1903  * Parameters  :
1904  *          1  :  csp = Current client state (buffers, headers, etc...)
1905  *
1906  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1907  *
1908  *********************************************************************/
1909 static jb_err parse_client_request(struct client_state *csp)
1910 {
1911    struct http_request *http = csp->http;
1912    jb_err err;
1913
1914 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1915    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1916     && (!strcmpic(csp->http->version, "HTTP/1.1"))
1917     && (csp->http->ssl == 0))
1918    {
1919       /* Assume persistence until further notice */
1920       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1921    }
1922 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1923
1924    if (csp->http->ssl == 0)
1925    {
1926       /*
1927        * This whole block belongs to chat() but currently
1928        * has to be executed before sed().
1929        */
1930       if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1931       {
1932          if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1933          {
1934             return JB_ERR_PARSE;
1935          }
1936       }
1937       else
1938       {
1939          csp->expected_client_content_length = get_expected_content_length(csp->headers);
1940       }
1941       verify_request_length(csp);
1942    }
1943 #ifndef FEATURE_HTTPS_INSPECTION
1944    else
1945    {
1946       csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1947    }
1948 #endif
1949
1950    err = sed(csp, FILTER_CLIENT_HEADERS);
1951    if (JB_ERR_OK != err)
1952    {
1953       log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1954          csp->ip_addr_str);
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;
1959    }
1960    csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1961
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))))
1966    {
1967       /*
1968        * A header filter broke the request line - bail out.
1969        */
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);
1978
1979       return JB_ERR_PARSE;
1980    }
1981
1982    if (client_has_unsupported_expectations(csp))
1983    {
1984       return JB_ERR_PARSE;
1985    }
1986
1987    return JB_ERR_OK;
1988
1989 }
1990
1991
1992 /*********************************************************************
1993  *
1994  * Function    : read_http_request_body
1995  *
1996  * Description : Reads remaining request body from the client.
1997  *
1998  * Parameters  :
1999  *          1  :  csp = Current client state (buffers, headers, etc...)
2000  *
2001  * Returns     :  0 on success, anything else is an error.
2002  *
2003  *********************************************************************/
2004 static int read_http_request_body(struct client_state *csp)
2005 {
2006    size_t to_read = csp->expected_client_content_length;
2007    int len;
2008
2009    assert(to_read != 0);
2010
2011    /* check if all data has been already read */
2012    if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2013    {
2014       return 0;
2015    }
2016
2017    for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2018         to_read > 0 && data_is_available(csp->cfd, csp->config->socket_timeout);
2019         to_read -= (unsigned)len)
2020    {
2021       char buf[BUFFER_SIZE];
2022       size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2023
2024       log_error(LOG_LEVEL_CONNECT,
2025          "Waiting for up to %d bytes of request body from the client.",
2026          max_bytes_to_read);
2027       len = read_socket(csp->cfd, buf, (int)max_bytes_to_read);
2028       if (len <= -1)
2029       {
2030          log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s: %E", csp->ip_addr_str);
2031          return 1;
2032       }
2033       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2034       {
2035          return 1;
2036       }
2037       assert(to_read >= len);
2038    }
2039
2040    if (to_read != 0)
2041    {
2042       log_error(LOG_LEVEL_CONNECT, "Not enough request body has been read: expected %d more bytes",
2043          csp->expected_client_content_length);
2044       return 1;
2045    }
2046    log_error(LOG_LEVEL_CONNECT, "The last %d bytes of the request body have been read",
2047       csp->expected_client_content_length);
2048    return 0;
2049 }
2050
2051
2052 /*********************************************************************
2053  *
2054  * Function    : update_client_headers
2055  *
2056  * Description : Updates the HTTP headers from the client request.
2057  *
2058  * Parameters  :
2059  *          1  :  csp = Current client state (buffers, headers, etc...)
2060  *          2  :  new_content_length = new content length value to set
2061  *
2062  * Returns     :  0 on success, anything else is an error.
2063  *
2064  *********************************************************************/
2065 static int update_client_headers(struct client_state *csp, size_t new_content_length)
2066 {
2067    static const char content_length[] = "Content-Length:";
2068    int updated = 0;
2069    struct list_entry *p;
2070
2071 #ifndef FEATURE_HTTPS_INSPECTION
2072    for (p = csp->headers->first;
2073 #else
2074    for (p = csp->http->client_ssl ? csp->https_headers->first : csp->headers->first;
2075 #endif
2076         !updated  && (p != NULL); p = p->next)
2077    {
2078       /* Header crunch()ed in previous run? -> ignore */
2079       if (p->str == NULL)
2080       {
2081          continue;
2082       }
2083
2084       /* Does the current parser handle this header? */
2085       if (0 == strncmpic(p->str, content_length, sizeof(content_length) - 1))
2086       {
2087          updated = (JB_ERR_OK == header_adjust_content_length((char **)&(p->str), new_content_length));
2088          if (!updated)
2089          {
2090             return 1;
2091          }
2092       }
2093    }
2094
2095    return !updated;
2096 }
2097
2098
2099 /*********************************************************************
2100  *
2101  * Function    : can_filter_request_body
2102  *
2103  * Description : Checks if the current request body can be stored in
2104  *               the client_iob without hitting buffer limit.
2105  *
2106  * Parameters  :
2107  *          1  : csp = Current client state (buffers, headers, etc...)
2108  *
2109  * Returns     : TRUE if the current request size do not exceed buffer limit
2110  *               FALSE otherwise.
2111  *
2112  *********************************************************************/
2113 static int can_filter_request_body(const struct client_state *csp)
2114 {
2115    if (!can_add_to_iob(csp->client_iob, csp->config->buffer_limit,
2116                        csp->expected_client_content_length))
2117    {
2118       log_error(LOG_LEVEL_INFO,
2119          "Not filtering request body from %s: buffer limit %d will be exceeded "
2120          "(content length %d)", csp->ip_addr_str, csp->config->buffer_limit,
2121          csp->expected_client_content_length);
2122       return FALSE;
2123    }
2124    return TRUE;
2125 }
2126
2127
2128 /*********************************************************************
2129  *
2130  * Function    : send_http_request
2131  *
2132  * Description : Sends the HTTP headers from the client request
2133  *               and all the body data that has already been received.
2134  *
2135  * Parameters  :
2136  *          1  :  csp = Current client state (buffers, headers, etc...)
2137  *
2138  * Returns     :  0 on success, anything else is an error.
2139  *
2140  *********************************************************************/
2141 static int send_http_request(struct client_state *csp)
2142 {
2143    char *hdr;
2144    int write_failure;
2145    const char *to_send;
2146    size_t to_send_len;
2147    int filter_client_body = csp->expected_client_content_length != 0 &&
2148       client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2149
2150    if (filter_client_body)
2151    {
2152       if (read_http_request_body(csp))
2153       {
2154          return 1;
2155       }
2156       to_send_len = csp->expected_client_content_length;
2157       to_send = execute_client_body_filters(csp, &to_send_len);
2158       if (to_send == NULL)
2159       {
2160          /* just flush client_iob */
2161          filter_client_body = FALSE;
2162       }
2163       else if (to_send_len != csp->expected_client_content_length &&
2164          update_client_headers(csp, to_send_len))
2165       {
2166          log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2167          return 1;
2168       }
2169       csp->expected_client_content_length = 0;
2170    }
2171
2172    hdr = list_to_text(csp->headers);
2173    if (hdr == NULL)
2174    {
2175       /* FIXME Should handle error properly */
2176       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2177    }
2178    list_remove_all(csp->headers);
2179
2180    /*
2181     * Write the client's (modified) header to the server
2182     * (along with anything else that may be in the buffer)
2183     */
2184    write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2185    freez(hdr);
2186
2187    if (write_failure)
2188    {
2189       log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2190          csp->http->hostport);
2191       return 1;
2192    }
2193
2194    if (filter_client_body)
2195    {
2196       write_failure = 0 != write_socket(csp->server_connection.sfd, to_send, to_send_len);
2197       freez(to_send);
2198       if (write_failure)
2199       {
2200          log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s: %E",
2201             csp->http->hostport);
2202          return 1;
2203       }
2204    }
2205
2206    if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2207       && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2208    {
2209       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2210          csp->http->hostport);
2211       return 1;
2212    }
2213    return 0;
2214 }
2215
2216
2217 #ifdef FEATURE_HTTPS_INSPECTION
2218 /*********************************************************************
2219  *
2220  * Function    : read_https_request_body
2221  *
2222  * Description : Reads remaining request body from the client.
2223  *
2224  * Parameters  :
2225  *          1  :  csp = Current client state (buffers, headers, etc...)
2226  *
2227  * Returns     :  0 on success, anything else is an error.
2228  *
2229  *********************************************************************/
2230 static int read_https_request_body(struct client_state *csp)
2231 {
2232    size_t to_read = csp->expected_client_content_length;
2233    int len;
2234
2235    assert(to_read != 0);
2236
2237    /* check if all data has been already read */
2238    if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2239    {
2240       return 0;
2241    }
2242
2243    for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2244         to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2245           data_is_available(csp->cfd, csp->config->socket_timeout));
2246         to_read -= (unsigned)len)
2247    {
2248       unsigned char buf[BUFFER_SIZE];
2249       size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2250
2251       log_error(LOG_LEVEL_CONNECT,
2252          "Waiting for up to %d bytes of request body from the client.",
2253          max_bytes_to_read);
2254       len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2255          (unsigned)max_bytes_to_read);
2256       if (len <= 0)
2257       {
2258          log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s", csp->ip_addr_str);
2259          return 1;
2260       }
2261       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2262       {
2263          return 1;
2264       }
2265       assert(to_read >= len);
2266    }
2267
2268    if (to_read != 0)
2269    {
2270       log_error(LOG_LEVEL_CONNECT, "Not enough request body has been read: expected %d more bytes", to_read);
2271       return 1;
2272    }
2273
2274    log_error(LOG_LEVEL_CONNECT, "The last %d bytes of the request body have been read",
2275       csp->expected_client_content_length);
2276    return 0;
2277 }
2278
2279
2280 /*********************************************************************
2281  *
2282  * Function    : receive_and_send_encrypted_post_data
2283  *
2284  * Description : Reads remaining request body from the client and sends
2285  *               it to the server.
2286  *
2287  * Parameters  :
2288  *          1  :  csp = Current client state (buffers, headers, etc...)
2289  *
2290  * Returns     :  0 on success, anything else is an error.
2291  *
2292  *********************************************************************/
2293 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2294 {
2295    int content_length_known = csp->expected_client_content_length != 0;
2296
2297    while (is_ssl_pending(&(csp->ssl_client_attr))
2298       || (content_length_known && csp->expected_client_content_length != 0))
2299    {
2300       unsigned char buf[BUFFER_SIZE];
2301       int len;
2302       int max_bytes_to_read = sizeof(buf);
2303
2304       if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2305       {
2306          max_bytes_to_read = (int)csp->expected_client_content_length;
2307       }
2308       log_error(LOG_LEVEL_CONNECT,
2309          "Waiting for up to %d bytes of request body from the client.",
2310          max_bytes_to_read);
2311       len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2312          (unsigned)max_bytes_to_read);
2313       if (len == -1)
2314       {
2315          return 1;
2316       }
2317       if (len == 0)
2318       {
2319          /* XXX: Does this actually happen? */
2320          break;
2321       }
2322       log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body",
2323          len);
2324       len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2325       if (len == -1)
2326       {
2327          return 1;
2328       }
2329       if (csp->expected_client_content_length != 0)
2330       {
2331          if (csp->expected_client_content_length >= len)
2332          {
2333             csp->expected_client_content_length -= (unsigned)len;
2334          }
2335          if (csp->expected_client_content_length == 0)
2336          {
2337             log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2338             break;
2339          }
2340       }
2341    }
2342
2343    log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body");
2344
2345    return 0;
2346
2347 }
2348
2349
2350 /*********************************************************************
2351  *
2352  * Function    : send_https_request
2353  *
2354  * Description : Sends the HTTP headers from the client request
2355  *               and all the body data that has already been received.
2356  *
2357  * Parameters  :
2358  *          1  :  csp = Current client state (buffers, headers, etc...)
2359  *
2360  * Returns     :  0 on success, anything else is an error.
2361  *
2362  *********************************************************************/
2363 static int send_https_request(struct client_state *csp)
2364 {
2365    char *hdr;
2366    int ret;
2367    long flushed = 0;
2368    const char *to_send;
2369    size_t to_send_len;
2370    int filter_client_body = csp->expected_client_content_length != 0 &&
2371       client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2372
2373    if (filter_client_body)
2374    {
2375       if (read_https_request_body(csp))
2376       {
2377          return 1;
2378       }
2379       to_send_len = csp->expected_client_content_length;
2380       to_send = execute_client_body_filters(csp, &to_send_len);
2381       if (to_send == NULL)
2382       {
2383          /* just flush client_iob */
2384          filter_client_body = FALSE;
2385       }
2386       else if (to_send_len != csp->expected_client_content_length &&
2387          update_client_headers(csp, to_send_len))
2388       {
2389          log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2390          return 1;
2391       }
2392       csp->expected_client_content_length = 0;
2393    }
2394
2395    hdr = list_to_text(csp->https_headers);
2396    if (hdr == NULL)
2397    {
2398       /* FIXME Should handle error properly */
2399       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2400    }
2401    list_remove_all(csp->https_headers);
2402
2403    /*
2404     * Write the client's (modified) header to the server
2405     * (along with anything else that may be in the buffer)
2406     */
2407    ret = ssl_send_data(&(csp->ssl_server_attr),
2408       (const unsigned char *)hdr, strlen(hdr));
2409    freez(hdr);
2410
2411    if (ret < 0)
2412    {
2413       log_error(LOG_LEVEL_CONNECT,
2414          "Failed sending encrypted request headers to: %s: %E",
2415          csp->http->hostport);
2416       mark_server_socket_tainted(csp);
2417       return 1;
2418    }
2419
2420    if (filter_client_body)
2421    {
2422       ret = ssl_send_data(&(csp->ssl_server_attr), (const unsigned char *)to_send, to_send_len);
2423       freez(to_send);
2424       if (ret < 0)
2425       {
2426          log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s",
2427             csp->http->hostport);
2428          return 1;
2429       }
2430    }
2431
2432    if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2433       && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2434             csp->client_iob)) < 0))
2435    {
2436       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2437          csp->http->hostport);
2438       return 1;
2439    }
2440    if (flushed != 0 || csp->expected_client_content_length != 0)
2441    {
2442       if (csp->expected_client_content_length != 0)
2443       {
2444          if (csp->expected_client_content_length < flushed)
2445          {
2446             log_error(LOG_LEVEL_ERROR,
2447                "Flushed %ld bytes of request body while only expecting %llu",
2448                flushed, csp->expected_client_content_length);
2449             csp->expected_client_content_length = 0;
2450          }
2451          else
2452          {
2453             log_error(LOG_LEVEL_CONNECT,
2454                "Flushed %ld bytes of request body while expecting %llu",
2455                flushed, csp->expected_client_content_length);
2456             csp->expected_client_content_length -= (unsigned)flushed;
2457             if (receive_and_send_encrypted_post_data(csp))
2458             {
2459                return 1;
2460             }
2461          }
2462       }
2463       else
2464       {
2465          log_error(LOG_LEVEL_CONNECT,
2466             "Flushed %ld bytes of request body", flushed);
2467       }
2468    }
2469
2470    log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2471
2472    return 0;
2473
2474 }
2475
2476
2477 /*********************************************************************
2478  *
2479  * Function    :  receive_encrypted_request
2480  *
2481  * Description :  Receives an encrypted request.
2482  *
2483  * Parameters  :
2484  *          1  :  csp = Current client state (buffers, headers, etc...)
2485  *
2486  * Returns     :  JB_ERR_OK on success,
2487  *                JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2488  *
2489  *********************************************************************/
2490 static jb_err receive_encrypted_request(struct client_state *csp)
2491 {
2492    char buf[BUFFER_SIZE];
2493    int len;
2494    char *p;
2495
2496    do
2497    {
2498       log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2499       if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2500           !data_is_available(csp->cfd, csp->config->socket_timeout))
2501       {
2502          log_error(LOG_LEVEL_CONNECT,
2503             "Socket %d timed out while waiting for client headers", csp->cfd);
2504          return JB_ERR_PARSE;
2505       }
2506       len = ssl_recv_data(&(csp->ssl_client_attr),
2507          (unsigned char *)buf, sizeof(buf));
2508       if (len == 0)
2509       {
2510          log_error(LOG_LEVEL_CONNECT,
2511             "Socket %d closed while waiting for client headers", csp->cfd);
2512          return JB_ERR_PARSE;
2513       }
2514       if (len == -1)
2515       {
2516          return JB_ERR_PARSE;
2517       }
2518       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2519       {
2520          return JB_ERR_MEMORY;
2521       }
2522       p = strstr(csp->client_iob->cur, "\r\n\r\n");
2523    } while (p == NULL);
2524
2525    log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2526
2527    return JB_ERR_OK;
2528 }
2529
2530
2531 /*********************************************************************
2532  *
2533  * Function    :  change_encrypted_request_destination
2534  *
2535  * Description :  Parse a (rewritten) request line from an encrypted
2536  *                request and regenerate the http request data.
2537  *
2538  * Parameters  :
2539  *          1  :  csp = Current client state (buffers, headers, etc...)
2540  *
2541  * Returns     :  Forwards the parse_http_request() return code.
2542  *                Terminates in case of memory problems.
2543  *
2544  *********************************************************************/
2545 static jb_err change_encrypted_request_destination(struct client_state *csp)
2546 {
2547    jb_err err;
2548    char *original_host = csp->http->host;
2549
2550    log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
2551       csp->https_headers->first->str);
2552    csp->http->host = NULL;
2553    free_http_request(csp->http);
2554    err = parse_http_request(csp->https_headers->first->str, csp->http);
2555    if (JB_ERR_OK != err)
2556    {
2557       log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2558          jb_err_to_string(err));
2559       return err;
2560    }
2561
2562    if (csp->http->host == NULL)
2563    {
2564       /*
2565        * The rewritten request line did not specify a host
2566        * which means we can use the original host specified
2567        * by the client.
2568        */
2569       csp->http->host = original_host;
2570       log_error(LOG_LEVEL_REDIRECTS, "Keeping the original host: %s",
2571          csp->http->host);
2572       /*
2573        * If the rewritten request line didn't contain a host
2574        * it also didn't contain a port so we can reuse the host
2575        * and set the port to 443.
2576        */
2577       freez(csp->http->hostport);
2578       csp->http->hostport = strdup_or_die(csp->http->host);
2579       csp->http->port = 443;
2580       /*
2581        * While the request line didn't mention it,
2582        * we're https-inspecting and want to speak TLS
2583        * with the server.
2584        */
2585       csp->http->server_ssl = 1;
2586       csp->http->ssl = 1;
2587    }
2588    else
2589    {
2590       /* The rewrite filter added a host so we can ditch the original */
2591       freez(original_host);
2592       csp->http->server_ssl = csp->http->ssl;
2593    }
2594
2595    csp->http->client_ssl = 1;
2596
2597    freez(csp->https_headers->first->str);
2598    build_request_line(csp, NULL, &csp->https_headers->first->str);
2599
2600    if (!server_use_ssl(csp))
2601    {
2602       log_error(LOG_LEVEL_REDIRECTS,
2603          "Rewritten request line results in downgrade to http");
2604       /*
2605        * Replace the unencryptd headers received with the
2606        * CONNECT request with the ones we received securely.
2607        */
2608       destroy_list(csp->headers);
2609       csp->headers->first = csp->https_headers->first;
2610       csp->headers->last  = csp->https_headers->last;
2611       csp->https_headers->first = NULL;
2612       csp->https_headers->last = NULL;
2613    }
2614
2615    return JB_ERR_OK;
2616
2617 }
2618
2619
2620 /*********************************************************************
2621  *
2622  * Function    :  process_encrypted_request
2623  *
2624  * Description :  Receives and parses an encrypted request.
2625  *
2626  * Parameters  :
2627  *          1  :  csp = Current client state (buffers, headers, etc...)
2628  *
2629  * Returns     :  JB_ERR_OK on success,
2630  *                JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2631  *
2632  *********************************************************************/
2633 static jb_err process_encrypted_request(struct client_state *csp)
2634 {
2635    char *p;
2636    char *request_line;
2637    jb_err err;
2638    /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2639    struct list header_list;
2640    struct list *headers = &header_list;
2641
2642    assert(csp->ssl_with_client_is_opened);
2643
2644 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2645    if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2646    {
2647       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2648    }
2649 #endif
2650    err = receive_encrypted_request(csp);
2651    if (err != JB_ERR_OK)
2652    {
2653       if (csp->client_iob->cur == NULL ||
2654           csp->client_iob->cur == csp->client_iob->eod)
2655       {
2656          /*
2657           * We did not receive any data, most likely because the
2658           * client is done. Don't log this as a parse failure.
2659           */
2660          return JB_ERR_PARSE;
2661       }
2662       /* XXX: Also used for JB_ERR_MEMORY */
2663       log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2664          jb_err_to_string(err));
2665       ssl_send_data_delayed(&(csp->ssl_client_attr),
2666          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2667       return err;
2668    }
2669
2670    /* We don't need get_request_line() because the whole HTTP head is buffered. */
2671    request_line = get_header(csp->client_iob);
2672    if (request_line == NULL)
2673    {
2674       log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2675       ssl_send_data_delayed(&(csp->ssl_client_attr),
2676          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2677       return JB_ERR_PARSE;
2678    }
2679    assert(*request_line != '\0');
2680
2681    if (client_protocol_is_unsupported(csp, request_line))
2682    {
2683       /*
2684        * If the protocol is unsupported we're done here.
2685        * client_protocol_is_unsupported() took care of sending
2686        * the error response and logging the error message.
2687        */
2688       return JB_ERR_PARSE;
2689    }
2690
2691 #ifdef FEATURE_FORCE_LOAD
2692    if (force_required(csp, request_line))
2693    {
2694       csp->flags |= CSP_FLAG_FORCED;
2695    }
2696 #endif /* def FEATURE_FORCE_LOAD */
2697
2698    free_http_request(csp->http);
2699
2700    err = parse_http_request(request_line, csp->http);
2701    /* XXX: Restore ssl setting. This is ugly */
2702    csp->http->client_ssl = 1;
2703    csp->http->server_ssl = 1;
2704
2705    freez(request_line);
2706    if (JB_ERR_OK != err)
2707    {
2708       ssl_send_data_delayed(&(csp->ssl_client_attr),
2709          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2710       /* XXX: Use correct size */
2711       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2712       log_error(LOG_LEVEL_ERROR,
2713          "Couldn't parse request line received from %s: %s",
2714          csp->ip_addr_str, jb_err_to_string(err));
2715
2716       free_http_request(csp->http);
2717       return JB_ERR_PARSE;
2718    }
2719
2720    /* Parse the rest of the client's headers. */
2721    init_list(headers);
2722    for (;;)
2723    {
2724       p = get_header(csp->client_iob);
2725
2726       if (p == NULL)
2727       {
2728          /* There are no additional headers to read. */
2729          break;
2730       }
2731       enlist(headers, p);
2732       freez(p);
2733    }
2734
2735    if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2736    {
2737       /*
2738        * Our attempts to get the request destination
2739        * elsewhere failed.
2740        */
2741       log_error(LOG_LEVEL_ERROR,
2742          "Failed to get the encrypted request destination");
2743       ssl_send_data_delayed(&(csp->ssl_client_attr),
2744          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2745       return JB_ERR_PARSE;
2746    }
2747
2748    /* Split the domain we just got for pattern matching */
2749    init_domain_components(csp->http);
2750
2751 #ifdef FEATURE_CLIENT_TAGS
2752    /* XXX: If the headers were enlisted sooner, passing csp would do. */
2753    if (csp->client_address == NULL)
2754    {
2755       set_client_address(csp, headers);
2756       get_tag_list_for_client(csp->client_tags, csp->client_address);
2757    }
2758 #endif
2759
2760 #ifdef FEATURE_TOGGLE
2761    if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2762 #endif
2763    {
2764       /*
2765        * Determine the actions for this request after
2766        * clearing the ones from the previous one.
2767        */
2768       free_current_action(csp->action);
2769       get_url_actions(csp, csp->http);
2770    }
2771
2772    enlist(csp->https_headers, csp->http->cmd);
2773
2774    /* Append the previously read headers */
2775    err = list_append_list_unique(csp->https_headers, headers);
2776    destroy_list(headers);
2777    if (JB_ERR_OK != err)
2778    {
2779       /* XXX: Send error message */
2780       return err;
2781    }
2782
2783    /* XXX: Work around crash */
2784    csp->error_message = NULL;
2785
2786    /* XXX: Why do this here? */
2787    csp->http->ssl = 1;
2788
2789    err = sed_https(csp);
2790    if (JB_ERR_OK != err)
2791    {
2792       ssl_send_data_delayed(&(csp->ssl_client_attr),
2793          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2794       log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2795          csp->ip_addr_str);
2796       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2797          csp->ip_addr_str, csp->http->cmd);
2798       return JB_ERR_PARSE;
2799    }
2800
2801    if ((NULL == csp->https_headers->first->str)
2802       || (strcmp(csp->http->cmd, csp->https_headers->first->str) &&
2803          (JB_ERR_OK != change_encrypted_request_destination(csp))))
2804    {
2805       log_error(LOG_LEVEL_ERROR,
2806          "Failed to get the request destination in the rewritten headers");
2807       ssl_send_data_delayed(&(csp->ssl_client_attr),
2808          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2809       return JB_ERR_PARSE;
2810    }
2811
2812    log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2813    log_applied_actions(csp->action);
2814    log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2815       csp->http->path);
2816
2817    return err;
2818
2819 }
2820
2821 /*********************************************************************
2822  *
2823  * Function    :  cgi_page_requested
2824  *
2825  * Description :  Checks if a request is for an internal CGI page.
2826  *
2827  * Parameters  :
2828  *          1  :  host = The host requested by the client.
2829  *
2830  * Returns     :  1 if a CGI page has been requested, 0 otherwise
2831  *
2832  *********************************************************************/
2833 static int cgi_page_requested(const char *host)
2834 {
2835    if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2836     || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2837     || (0 == strcmpic(host, CGI_SITE_2_HOST))
2838     || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2839    {
2840       return 1;
2841    }
2842
2843    return 0;
2844
2845 }
2846
2847
2848 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2849 /*********************************************************************
2850  *
2851  * Function    :  continue_https_chat
2852  *
2853  * Description :  Behaves similar to chat() but only deals with
2854  *                https-inspected requests that arrive on an already
2855  *                established connection. The first request is always
2856  *                served by chat() which is a lot more complex as it
2857  *                has to deal with forwarding settings and connection
2858  *                failures etc.
2859  *
2860  *                If a connection to the server has already been
2861  *                opened it is reused unless the request is blocked
2862  *                or the forwarder changed.
2863  *
2864  *                If a connection to the server has not yet been
2865  *                opened (because the previous request was crunched),
2866  *                or the forwarder changed, the connection is dropped
2867  *                so that the client retries on a fresh one.
2868  *
2869  * Parameters  :
2870  *          1  :  csp = Current client state (buffers, headers, etc...)
2871  *
2872  * Returns     :  Nothing.
2873  *
2874  *********************************************************************/
2875 static void continue_https_chat(struct client_state *csp)
2876 {
2877    const struct forward_spec *fwd;
2878
2879    if (JB_ERR_OK != process_encrypted_request(csp))
2880    {
2881       return;
2882    }
2883
2884    csp->requests_received_total++;
2885
2886    /*
2887     * We have an encrypted request. Check if one of the crunchers wants it.
2888     */
2889    if (crunch_response_triggered(csp, crunchers_all))
2890    {
2891       /*
2892        * Yes. The client got the crunch response and we're done here.
2893        */
2894       return;
2895    }
2896    if (csp->ssl_with_server_is_opened == 0)
2897    {
2898       log_error(LOG_LEVEL_CONNECT,
2899          "Dropping the client connection on socket %d. "
2900          "The server connection has not been established yet.",
2901          csp->cfd);
2902       csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2903       return;
2904    }
2905    assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2906
2907    fwd = forward_url(csp, csp->http);
2908    if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2909    {
2910       log_error(LOG_LEVEL_CONNECT,
2911          "Dropping the client connection on socket %d with "
2912          "server socket %d connected to %s. The forwarder has changed.",
2913          csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2914       csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2915       return;
2916    }
2917
2918    log_error(LOG_LEVEL_CONNECT,
2919       "Reusing server socket %d connected to %s. Requests already sent: %u.",
2920       csp->server_connection.sfd, csp->server_connection.host,
2921       csp->server_connection.requests_sent_total);
2922
2923    if (send_https_request(csp))
2924    {
2925       /*
2926        * Most likely the server connection timed out. We can't easily
2927        * create a new one so simply drop the client connection without a
2928        * error response to let the client retry.
2929        */
2930       log_error(LOG_LEVEL_CONNECT,
2931          "Dropping client connection on socket %d. "
2932          "Forwarding the encrypted client request failed.",
2933          csp->cfd);
2934       return;
2935    }
2936    csp->server_connection.requests_sent_total++;
2937    handle_established_connection(csp);
2938    freez(csp->receive_buffer);
2939 }
2940 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2941 #endif
2942
2943
2944 /*********************************************************************
2945  *
2946  * Function    :  handle_established_connection
2947  *
2948  * Description :  Shuffle data between client and server once the
2949  *                connection has been established.
2950  *
2951  * Parameters  :
2952  *          1  :  csp = Current client state (buffers, headers, etc...)
2953  *
2954  * Returns     :  Nothing.
2955  *
2956  *********************************************************************/
2957 static void handle_established_connection(struct client_state *csp)
2958 {
2959    char *hdr;
2960    char *p;
2961    int n;
2962 #ifdef HAVE_POLL
2963    struct pollfd poll_fds[2];
2964 #else
2965    fd_set rfds;
2966    jb_socket maxfd;
2967    struct timeval timeout;
2968 #endif
2969    int server_body;
2970    int ms_iis5_hack = 0;
2971    unsigned long long byte_count = 0;
2972    struct http_request *http;
2973    long len = 0; /* for buffer sizes (and negative error codes) */
2974    int buffer_and_filter_content = 0;
2975    unsigned int write_delay;
2976 #ifdef FEATURE_HTTPS_INSPECTION
2977    int ret = 0;
2978    int use_ssl_tunnel = 0;
2979    csp->dont_verify_certificate = 0;
2980
2981    if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2982    {
2983       /* Pass encrypted content without filtering. */
2984       use_ssl_tunnel = 1;
2985    }
2986 #endif
2987
2988    /* Skeleton for HTTP response, if we should intercept the request */
2989    struct http_response *rsp;
2990 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2991    int watch_client_socket;
2992 #endif
2993
2994    csp->receive_buffer_size = csp->config->receive_buffer_size;
2995    csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2996    if (csp->receive_buffer == NULL)
2997    {
2998       log_error(LOG_LEVEL_ERROR,
2999          "Out of memory. Failed to allocate the receive buffer.");
3000       rsp = cgi_error_memory();
3001       send_crunch_response(csp, rsp);
3002       return;
3003    }
3004
3005    http = csp->http;
3006
3007 #ifndef HAVE_POLL
3008    maxfd = (csp->cfd > csp->server_connection.sfd) ?
3009       csp->cfd : csp->server_connection.sfd;
3010 #endif
3011
3012    /* pass data between the client and server
3013     * until one or the other shuts down the connection.
3014     */
3015
3016    server_body = 0;
3017
3018 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3019    watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
3020 #endif
3021    write_delay = get_write_delay(csp);
3022
3023    for (;;)
3024    {
3025 #ifndef HAVE_POLL
3026       FD_ZERO(&rfds);
3027 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3028       if (!watch_client_socket)
3029       {
3030          maxfd = csp->server_connection.sfd;
3031       }
3032       else
3033 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3034       {
3035          FD_SET(csp->cfd, &rfds);
3036       }
3037
3038       FD_SET(csp->server_connection.sfd, &rfds);
3039 #endif /* ndef HAVE_POLL */
3040
3041 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3042       if ((csp->flags & CSP_FLAG_CHUNKED)
3043          && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3044          && ((csp->iob->eod - csp->iob->cur) >= 5)
3045          && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3046       {
3047          /*
3048           * XXX: This check should be obsolete now,
3049           *      but let's wait a while to be sure.
3050           */
3051          log_error(LOG_LEVEL_CONNECT,
3052             "Looks like we got the last chunk together with "
3053             "the server headers but didn't detect it earlier. "
3054             "We better stop reading.");
3055          byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3056          csp->expected_content_length = byte_count;
3057          csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3058       }
3059       if (server_body && server_response_is_complete(csp, byte_count))
3060       {
3061          if (csp->expected_content_length == byte_count)
3062          {
3063             log_error(LOG_LEVEL_CONNECT,
3064                "Done reading from server. Content length: %llu as expected. "
3065                "Bytes most recently read: %ld.",
3066                byte_count, len);
3067          }
3068          else
3069          {
3070             log_error(LOG_LEVEL_CONNECT,
3071                "Done reading from server. Expected content length: %llu. "
3072                "Actual content length: %llu. Bytes most recently read: %ld.",
3073                csp->expected_content_length, byte_count, len);
3074          }
3075          len = 0;
3076          /*
3077           * XXX: Should not jump around, handle_established_connection()
3078           * is complicated enough already.
3079           */
3080          goto reading_done;
3081       }
3082 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
3083
3084 #ifdef HAVE_POLL
3085       poll_fds[0].fd = csp->cfd;
3086 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3087       if (!watch_client_socket)
3088       {
3089          /*
3090           * Ignore incoming data, but still watch out
3091           * for disconnects etc. These flags are always
3092           * implied anyway but explicitly setting them
3093           * doesn't hurt.
3094           */
3095          poll_fds[0].events = POLLERR|POLLHUP;
3096       }
3097       else
3098 #endif
3099       {
3100          poll_fds[0].events = POLLIN;
3101       }
3102       poll_fds[1].fd = csp->server_connection.sfd;
3103       poll_fds[1].events = POLLIN;
3104       n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3105 #else
3106       timeout.tv_sec = csp->config->socket_timeout;
3107       timeout.tv_usec = 0;
3108       n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3109 #endif /* def HAVE_POLL */
3110
3111       /*server or client not responding in timeout */
3112       if (n == 0)
3113       {
3114          log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3115             csp->config->socket_timeout, http->url);
3116          if ((byte_count == 0) && (http->ssl == 0))
3117          {
3118             send_crunch_response(csp, error_response(csp, "connection-timeout"));
3119          }
3120          mark_server_socket_tainted(csp);
3121 #ifdef FEATURE_HTTPS_INSPECTION
3122          close_client_and_server_ssl_connections(csp);
3123 #endif
3124          return;
3125       }
3126       else if (n < 0)
3127       {
3128 #ifdef HAVE_POLL
3129          log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3130 #else
3131          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3132 #endif
3133          mark_server_socket_tainted(csp);
3134 #ifdef FEATURE_HTTPS_INSPECTION
3135          close_client_and_server_ssl_connections(csp);
3136 #endif
3137          return;
3138       }
3139
3140       /*
3141        * This is the body of the browser's request,
3142        * just read and write it.
3143        *
3144        * Receives data from browser and sends it to server
3145        *
3146        * XXX: Make sure the client doesn't use pipelining
3147        * behind Privoxy's back.
3148        */
3149 #ifdef HAVE_POLL
3150       if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3151       {
3152          log_error(LOG_LEVEL_CONNECT,
3153             "The client socket %d has become unusable while "
3154             "the server socket %d is still open.",
3155             csp->cfd, csp->server_connection.sfd);
3156          mark_server_socket_tainted(csp);
3157          break;
3158       }
3159
3160       if (poll_fds[0].revents != 0)
3161 #else
3162       if (FD_ISSET(csp->cfd, &rfds))
3163 #endif /* def HAVE_POLL*/
3164       {
3165          int max_bytes_to_read = (int)csp->receive_buffer_size;
3166
3167 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3168          if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3169          {
3170             if (data_is_available(csp->cfd, 0))
3171             {
3172                /*
3173                 * If the next request is already waiting, we have
3174                 * to stop select()ing the client socket. Otherwise
3175                 * we would always return right away and get nothing
3176                 * else done.
3177                 */
3178                watch_client_socket = 0;
3179                log_error(LOG_LEVEL_CONNECT,
3180                   "Stop watching client socket %d. "
3181                   "There's already another request waiting.",
3182                   csp->cfd);
3183                continue;
3184             }
3185             /*
3186              * If the client socket is set, but there's no data
3187              * available on the socket, the client went fishing
3188              * and continuing talking to the server makes no sense.
3189              */
3190             log_error(LOG_LEVEL_CONNECT,
3191                "The client closed socket %d while "
3192                "the server socket %d is still open.",
3193                csp->cfd, csp->server_connection.sfd);
3194             mark_server_socket_tainted(csp);
3195             break;
3196          }
3197          if (csp->expected_client_content_length != 0)
3198          {
3199             if (csp->expected_client_content_length < csp->receive_buffer_size)
3200             {
3201                max_bytes_to_read = (int)csp->expected_client_content_length;
3202             }
3203             log_error(LOG_LEVEL_CONNECT,
3204                "Waiting for up to %d bytes from the client.",
3205                max_bytes_to_read);
3206          }
3207          assert(max_bytes_to_read <= csp->receive_buffer_size);
3208 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3209
3210 #ifdef FEATURE_HTTPS_INSPECTION
3211          if (client_use_ssl(csp))
3212          {
3213             if (csp->http->status == 101)
3214             {
3215                len = ssl_recv_data(&(csp->ssl_client_attr),
3216                   (unsigned char *)csp->receive_buffer,
3217                   (size_t)max_bytes_to_read);
3218                if (len == -1)
3219                {
3220                   log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3221                      "on client socket %d for an upgraded connection",
3222                      csp->cfd);
3223                   break;
3224                }
3225                if (len == 0)
3226                {
3227                   log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3228                      "on client socket %d for an upgraded connection",
3229                      csp->cfd);
3230                   break;
3231                }
3232                byte_count += (unsigned long long)len;
3233                len = ssl_send_data(&(csp->ssl_server_attr),
3234                   (unsigned char *)csp->receive_buffer, (size_t)len);
3235                if (len == -1)
3236                {
3237                   log_error(LOG_LEVEL_ERROR, "Failed to send data "
3238                      "on server socket %d for an upgraded connection",
3239                      csp->server_connection.sfd);
3240                   break;
3241                }
3242                continue;
3243             }
3244             log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3245             break;
3246          }
3247          else
3248 #endif /* def FEATURE_HTTPS_INSPECTION */
3249          {
3250             len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3251
3252             if (len <= 0)
3253             {
3254                /* XXX: not sure if this is necessary. */
3255                mark_server_socket_tainted(csp);
3256                break; /* "game over, man" */
3257             }
3258
3259 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3260             if (csp->expected_client_content_length != 0)
3261             {
3262                assert(len <= max_bytes_to_read);
3263                csp->expected_client_content_length -= (unsigned)len;
3264                log_error(LOG_LEVEL_CONNECT,
3265                   "Expected client content length set to %llu "
3266                   "after reading %ld bytes.",
3267                   csp->expected_client_content_length, len);
3268                if (csp->expected_client_content_length == 0)
3269                {
3270                   log_error(LOG_LEVEL_CONNECT,
3271                      "Done reading from the client.");
3272                   csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3273                }
3274             }
3275 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3276
3277             if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3278             {
3279                log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3280                mark_server_socket_tainted(csp);
3281                return;
3282             }
3283          }
3284          continue;
3285       }
3286
3287       /*
3288        * The server wants to talk. It could be the header or the body.
3289        * If `hdr' is null, then it's the header otherwise it's the body.
3290        * FIXME: Does `hdr' really mean `host'? No.
3291        */
3292 #ifdef HAVE_POLL
3293       if (poll_fds[1].revents != 0)
3294 #else
3295       if (FD_ISSET(csp->server_connection.sfd, &rfds))
3296 #endif /* HAVE_POLL */
3297       {
3298 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3299          /*
3300           * If we are buffering content, we don't want to eat up to
3301           * buffer-limit bytes if the client no longer cares about them.
3302           * If we aren't buffering, however, a dead client socket will be
3303           * noticed pretty much right away anyway, so we can reduce the
3304           * overhead by skipping the check.
3305           */
3306          if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3307          {
3308 #ifdef _WIN32
3309             log_error(LOG_LEVEL_CONNECT,
3310                "The server still wants to talk, but the client may already have hung up on us.");
3311 #else
3312             log_error(LOG_LEVEL_CONNECT,
3313                "The server still wants to talk, but the client hung up on us.");
3314             mark_server_socket_tainted(csp);
3315 #ifdef FEATURE_HTTPS_INSPECTION
3316             close_client_and_server_ssl_connections(csp);
3317 #endif
3318             return;
3319 #endif /* def _WIN32 */
3320          }
3321 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3322
3323 #ifdef FEATURE_HTTPS_INSPECTION
3324          /*
3325           * Reading data from standard or secured connection (HTTP/HTTPS)
3326           */
3327          if (server_use_ssl(csp))
3328          {
3329             len = ssl_recv_data(&(csp->ssl_server_attr),
3330                (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3331          }
3332          else
3333 #endif
3334          {
3335             len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3336                (int)csp->receive_buffer_size);
3337          }
3338
3339          if (len < 0)
3340          {
3341             log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3342
3343             if ((http->ssl && (csp->fwd == NULL))
3344 #ifdef FEATURE_HTTPS_INSPECTION
3345                && use_ssl_tunnel
3346 #endif
3347                 )
3348             {
3349                /*
3350                 * Just hang up. We already confirmed the client's CONNECT
3351                 * request with status code 200 and unencrypted content is
3352                 * no longer welcome.
3353                 */
3354                log_error(LOG_LEVEL_ERROR,
3355                   "CONNECT already confirmed. Unable to tell the client about the problem.");
3356                return;
3357             }
3358             else if (byte_count)
3359             {
3360                /*
3361                 * Just hang up. We already transmitted the original headers
3362                 * and parts of the original content and therefore missed the
3363                 * chance to send an error message (without risking data corruption).
3364                 *
3365                 * XXX: we could retry with a fancy range request here.
3366                 */
3367                log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3368                   "Unable to tell the client about the problem.");
3369                mark_server_socket_tainted(csp);
3370 #ifdef FEATURE_HTTPS_INSPECTION
3371                close_client_and_server_ssl_connections(csp);
3372 #endif
3373                return;
3374             }
3375             /*
3376              * XXX: Consider handling the cases above the same.
3377              */
3378             mark_server_socket_tainted(csp);
3379             len = 0;
3380          }
3381
3382 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3383          if (csp->flags & CSP_FLAG_CHUNKED)
3384          {
3385             if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
3386             {
3387                /* XXX: this is a temporary hack */
3388                log_error(LOG_LEVEL_CONNECT,
3389                   "Looks like we reached the end of the last chunk. "
3390                   "We better stop reading.");
3391                csp->expected_content_length = byte_count + (unsigned long long)len;
3392                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3393             }
3394          }
3395          reading_done:
3396 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
3397
3398          /*
3399           * This is guaranteed by allocating with zalloc_or_die()
3400           * and never (intentionally) writing to the last byte.
3401           *
3402           * csp->receive_buffer_size is the size of the part of the
3403           * buffer we intentionally write to, but we actually
3404           * allocated csp->receive_buffer_size+1 bytes so the assertion
3405           * stays within the allocated range.
3406           */
3407          assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3408
3409          /*
3410           * Add a trailing zero to let be able to use string operations.
3411           * XXX: do we still need this with filter_popups gone?
3412           */
3413          assert(len <= csp->receive_buffer_size);
3414          csp->receive_buffer[len] = '\0';
3415
3416          /*
3417           * Normally, this would indicate that we've read
3418           * as much as the server has sent us and we can
3419           * close the client connection.  However, Microsoft
3420           * in its wisdom has released IIS/5 with a bug that
3421           * prevents it from sending the trailing \r\n in
3422           * a 302 redirect header (and possibly other headers).
3423           * To work around this if we've haven't parsed
3424           * a full header we'll append a trailing \r\n
3425           * and see if this now generates a valid one.
3426           *
3427           * This hack shouldn't have any impacts.  If we've
3428           * already transmitted the header or if this is a
3429           * SSL connection, then we won't bother with this
3430           * hack.  So we only work on partially received
3431           * headers.  If we append a \r\n and this still
3432           * doesn't generate a valid header, then we won't
3433           * transmit anything to the client.
3434           */
3435          if (len == 0)
3436          {
3437
3438             if (server_body || (http->ssl
3439 #ifdef FEATURE_HTTPS_INSPECTION
3440                   && use_ssl_tunnel
3441 #endif
3442                ))
3443             {
3444                /*
3445                 * If we have been buffering up the document,
3446                 * now is the time to apply content modification
3447                 * and send the result to the client.
3448                 */
3449                if (buffer_and_filter_content)
3450                {
3451                   p = execute_content_filters(csp);
3452                   /*
3453                    * If content filtering fails, use the original
3454                    * buffer and length.
3455                    * (see p != NULL ? p : csp->iob->cur below)
3456                    */
3457                   if (NULL == p)
3458                   {
3459                      csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3460                   }
3461 #ifdef FEATURE_COMPRESSION
3462                   else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3463                      && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3464                   {
3465                      char *compressed_content = compress_buffer(p,
3466                         (size_t *)&csp->content_length, csp->config->compression_level);
3467                      if (compressed_content != NULL)
3468                      {
3469                         freez(p);
3470                         p = compressed_content;
3471                         csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3472                      }
3473                   }
3474 #endif
3475
3476                   if (JB_ERR_OK != update_server_headers(csp))
3477                   {
3478                      log_error(LOG_LEVEL_FATAL,
3479                         "Failed to update server headers. after filtering.");
3480                   }
3481
3482                   hdr = list_to_text(csp->headers);
3483                   if (hdr == NULL)
3484                   {
3485                      /* FIXME Should handle error properly */
3486                      log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3487                   }
3488
3489 #ifdef FEATURE_HTTPS_INSPECTION
3490                   /*
3491                    * Sending data with standard or secured connection (HTTP/HTTPS)
3492                    */
3493                   if (client_use_ssl(csp))
3494                   {
3495                      if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3496                               (const unsigned char *)hdr, strlen(hdr),
3497                               get_write_delay(csp)) < 0)
3498                         || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3499                               (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3500                               csp->content_length, get_write_delay(csp)) < 0))
3501                      {
3502                         log_error(LOG_LEVEL_ERROR, "write modified content to "
3503                            "client over TLS/SSL failed");
3504                         freez(hdr);
3505                         freez(p);
3506                         mark_server_socket_tainted(csp);
3507                         close_client_and_server_ssl_connections(csp);
3508                         return;
3509                      }
3510                   }
3511                   else
3512 #endif /* def FEATURE_HTTPS_INSPECTION */
3513                   {
3514                      if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3515                       || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3516                          (size_t)csp->content_length, write_delay))
3517                      {
3518                         log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3519                         freez(hdr);
3520                         freez(p);
3521                         mark_server_socket_tainted(csp);
3522                         return;
3523                      }
3524                   }
3525
3526                   freez(hdr);
3527                   freez(p);
3528                }
3529
3530                break; /* "game over, man" */
3531             }
3532
3533             /*
3534              * This is NOT the body, so
3535              * Let's pretend the server just sent us a blank line.
3536              */
3537             snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3538             len = (int)strlen(csp->receive_buffer);
3539
3540             /*
3541              * Now, let the normal header parsing algorithm below do its
3542              * job.  If it fails, we'll exit instead of continuing.
3543              */
3544
3545             ms_iis5_hack = 1;
3546          }
3547
3548          /*
3549           * If we're in the body of the server document, just write it to
3550           * the client, unless we need to buffer the body for later
3551           * content-filtering.
3552           */
3553          if (server_body || (http->ssl
3554 #ifdef FEATURE_HTTPS_INSPECTION
3555                && use_ssl_tunnel
3556 #endif
3557             ))
3558          {
3559             if (buffer_and_filter_content)
3560             {
3561                /*
3562                 * If there is no memory left for buffering the content, or the buffer limit
3563                 * has been reached, switch to non-filtering mode, i.e. make & write the
3564                 * header, flush the iob and buf, and get out of the way.
3565                 */
3566                if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3567                {
3568                   size_t hdrlen;
3569                   long flushed;
3570
3571                   log_error(LOG_LEVEL_INFO,
3572                      "Flushing header and buffers. Stepping back from filtering.");
3573
3574                   hdr = list_to_text(csp->headers);
3575                   if (hdr == NULL)
3576                   {
3577                      /*
3578                       * Memory is too tight to even generate the header.
3579                       * Send our static "Out-of-memory" page.
3580                       */
3581                      log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3582                      rsp = cgi_error_memory();
3583                      send_crunch_response(csp, rsp);
3584                      mark_server_socket_tainted(csp);
3585 #ifdef FEATURE_HTTPS_INSPECTION
3586                      close_client_and_server_ssl_connections(csp);
3587 #endif
3588                      return;
3589                   }
3590                   hdrlen = strlen(hdr);
3591
3592 #ifdef FEATURE_HTTPS_INSPECTION
3593                   /*
3594                    * Sending data with standard or secured connection (HTTP/HTTPS)
3595                    */
3596                   if (client_use_ssl(csp))
3597                   {
3598                      if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3599                              (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3600                         || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3601                                 csp->iob)) < 0)
3602                         || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3603                               (const unsigned char *)csp->receive_buffer, (size_t)len,
3604                               get_write_delay(csp)) < 0))
3605                      {
3606                         log_error(LOG_LEVEL_CONNECT,
3607                            "Flush header and buffers to client failed");
3608                         freez(hdr);
3609                         mark_server_socket_tainted(csp);
3610                         close_client_and_server_ssl_connections(csp);
3611                         return;
3612                      }
3613                   }
3614                   else
3615 #endif /* def FEATURE_HTTPS_INSPECTION */
3616                   {
3617                      if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3618                       || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3619                       || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3620                             write_delay))
3621                      {
3622                         log_error(LOG_LEVEL_CONNECT,
3623                            "Flush header and buffers to client failed: %E");
3624                         freez(hdr);
3625                         mark_server_socket_tainted(csp);
3626                         return;
3627                      }
3628                   }
3629
3630                   /*
3631                    * Reset the byte_count to the amount of bytes
3632                    * we just flushed. len will be added a few lines below,
3633                    * hdrlen doesn't matter for LOG_LEVEL_CLF.
3634                    */
3635                   byte_count = (unsigned long long)flushed;
3636                   freez(hdr);
3637                   buffer_and_filter_content = 0;
3638                   server_body = 1;
3639                }
3640             }
3641             else
3642             {
3643 #ifdef FEATURE_HTTPS_INSPECTION
3644                /*
3645                 * Sending data with standard or secured connection (HTTP/HTTPS)
3646                 */
3647                if (client_use_ssl(csp))
3648                {
3649                   ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3650                      (const unsigned char *)csp->receive_buffer, (size_t)len,
3651                      get_write_delay(csp));
3652                   if (ret < 0)
3653                   {
3654                      log_error(LOG_LEVEL_ERROR,
3655                         "Sending data to client failed");
3656                      mark_server_socket_tainted(csp);
3657                      close_client_and_server_ssl_connections(csp);
3658                      return;
3659                   }
3660                }
3661                else
3662 #endif /* def FEATURE_HTTPS_INSPECTION */
3663                {
3664                   if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3665                         (size_t)len, write_delay))
3666                   {
3667                      log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3668                      mark_server_socket_tainted(csp);
3669                      return;
3670                   }
3671                }
3672             }
3673             byte_count += (unsigned long long)len;
3674             continue;
3675          }
3676          else
3677          {
3678             /*
3679              * We're still looking for the end of the server's header.
3680              * Buffer up the data we just read.  If that fails, there's
3681              * little we can do but send our static out-of-memory page.
3682              */
3683             if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3684             {
3685                log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3686                rsp = cgi_error_memory();
3687                send_crunch_response(csp, rsp);
3688                mark_server_socket_tainted(csp);
3689 #ifdef FEATURE_HTTPS_INSPECTION
3690                close_client_and_server_ssl_connections(csp);
3691 #endif
3692                return;
3693             }
3694
3695             /* Convert iob into something sed() can digest */
3696             if (JB_ERR_PARSE == get_server_headers(csp))
3697             {
3698                if (ms_iis5_hack)
3699                {
3700                   /*
3701                    * Well, we tried our MS IIS/5 hack and it didn't work.
3702                    * The header is incomplete and there isn't anything
3703                    * we can do about it.
3704                    */
3705                   log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3706                      "Applying the MS IIS5 hack didn't help.");
3707                   log_error(LOG_LEVEL_CLF,
3708                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3709 #ifdef FEATURE_HTTPS_INSPECTION
3710                   /*
3711                    * Sending data with standard or secured connection (HTTP/HTTPS)
3712                    */
3713                   if (client_use_ssl(csp))
3714                   {
3715                      ssl_send_data_delayed(&(csp->ssl_client_attr),
3716                         (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3717                         strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3718                   }
3719                   else
3720 #endif /* def FEATURE_HTTPS_INSPECTION */
3721                   {
3722                      write_socket_delayed(csp->cfd,
3723                         INVALID_SERVER_HEADERS_RESPONSE,
3724                         strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3725                   }
3726                   mark_server_socket_tainted(csp);
3727 #ifdef FEATURE_HTTPS_INSPECTION
3728                   close_client_and_server_ssl_connections(csp);
3729 #endif
3730                   return;
3731                }
3732                else
3733                {
3734                   /*
3735                    * Since we have to wait for more from the server before
3736                    * we can parse the headers we just continue here.
3737                    */
3738                   log_error(LOG_LEVEL_CONNECT,
3739                      "Continuing buffering server headers from socket %d. "
3740                      "Bytes most recently read: %ld.", csp->cfd, len);
3741                   continue;
3742                }
3743             }
3744             else
3745             {
3746                /*
3747                 * Account for the content bytes we
3748                 * might have gotten with the headers.
3749                 */
3750                assert(csp->iob->eod >= csp->iob->cur);
3751                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3752             }
3753
3754             /* Did we actually get anything? */
3755             if (NULL == csp->headers->first)
3756             {
3757                if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3758                {
3759                   log_error(LOG_LEVEL_ERROR,
3760                      "No server or forwarder response received on socket %d. "
3761                      "Closing client socket %d without sending data.",
3762                      csp->server_connection.sfd, csp->cfd);
3763                   log_error(LOG_LEVEL_CLF,
3764                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3765                }
3766                else
3767                {
3768                   log_error(LOG_LEVEL_ERROR,
3769                      "No server or forwarder response received on socket %d.",
3770                      csp->server_connection.sfd);
3771                   send_crunch_response(csp, error_response(csp, "no-server-data"));
3772                }
3773                free_http_request(http);
3774                mark_server_socket_tainted(csp);
3775 #ifdef FEATURE_HTTPS_INSPECTION
3776                close_client_and_server_ssl_connections(csp);
3777 #endif
3778                return;
3779             }
3780
3781             if (!csp->headers->first->str)
3782             {
3783                log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3784             }
3785             assert(csp->headers->first->str);
3786
3787             if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3788                 strncmpic(csp->headers->first->str, "ICY", 3))
3789             {
3790                /*
3791                 * It doesn't look like a HTTP (or Shoutcast) response:
3792                 * tell the client and log the problem.
3793                 */
3794                if (strlen(csp->headers->first->str) > 30)
3795                {
3796                   csp->headers->first->str[30] = '\0';
3797                }
3798                log_error(LOG_LEVEL_ERROR,
3799                   "Invalid server or forwarder response. Starts with: %s",
3800                   csp->headers->first->str);
3801                log_error(LOG_LEVEL_CLF,
3802                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3803 #ifdef FEATURE_HTTPS_INSPECTION
3804                /*
3805                 * Sending data with standard or secured connection (HTTP/HTTPS)
3806                 */
3807                if (client_use_ssl(csp))
3808                {
3809                   ssl_send_data_delayed(&(csp->ssl_client_attr),
3810                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3811                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
3812                      get_write_delay(csp));
3813                }
3814                else
3815 #endif /* def FEATURE_HTTPS_INSPECTION */
3816                {
3817                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3818                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3819                }
3820                free_http_request(http);
3821                mark_server_socket_tainted(csp);
3822 #ifdef FEATURE_HTTPS_INSPECTION
3823                close_client_and_server_ssl_connections(csp);
3824 #endif
3825                return;
3826             }
3827
3828             /*
3829              * We have now received the entire server header,
3830              * filter it and send the result to the client
3831              */
3832             if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3833             {
3834                log_error(LOG_LEVEL_CLF,
3835                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3836 #ifdef FEATURE_HTTPS_INSPECTION
3837                /*
3838                 * Sending data with standard or secured connection (HTTP/HTTPS)
3839                 */
3840                if (client_use_ssl(csp))
3841                {
3842                   ssl_send_data_delayed(&(csp->ssl_client_attr),
3843                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3844                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
3845                      get_write_delay(csp));
3846                }
3847                else
3848 #endif
3849                {
3850                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3851                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3852                }
3853                free_http_request(http);
3854                mark_server_socket_tainted(csp);
3855 #ifdef FEATURE_HTTPS_INSPECTION
3856                close_client_and_server_ssl_connections(csp);
3857 #endif
3858                return;
3859             }
3860             hdr = list_to_text(csp->headers);
3861             if (hdr == NULL)
3862             {
3863                /* FIXME Should handle error properly */
3864                log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3865             }
3866
3867             if ((csp->flags & CSP_FLAG_CHUNKED)
3868                && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3869                && ((csp->iob->eod - csp->iob->cur) >= 5)
3870                && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3871             {
3872                log_error(LOG_LEVEL_CONNECT,
3873                   "Looks like we got the last chunk together with "
3874                   "the server headers. We better stop reading.");
3875                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3876                csp->expected_content_length = byte_count;
3877                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3878             }
3879
3880             csp->server_connection.response_received = time(NULL);
3881
3882             if (crunch_response_triggered(csp, crunchers_light))
3883             {
3884                /*
3885                 * One of the tags created by a server-header
3886                 * tagger triggered a crunch. We already
3887                 * delivered the crunch response to the client
3888                 * and are done here after cleaning up.
3889                 */
3890                freez(hdr);
3891                mark_server_socket_tainted(csp);
3892 #ifdef FEATURE_HTTPS_INSPECTION
3893                close_client_and_server_ssl_connections(csp);
3894 #endif
3895                return;
3896             }
3897
3898             /* Buffer and pcrs filter this if appropriate. */
3899             buffer_and_filter_content = content_requires_filtering(csp);
3900
3901             if (!buffer_and_filter_content)
3902             {
3903                /*
3904                 * Write the server's (modified) header to
3905                 * the client (along with anything else that
3906                 * may be in the buffer). Use standard or secured
3907                 * connection.
3908                 */
3909 #ifdef FEATURE_HTTPS_INSPECTION
3910                if (client_use_ssl(csp))
3911                {
3912                   if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3913                           (const unsigned char *)hdr, strlen(hdr),
3914                           get_write_delay(csp)) < 0)
3915                      || (len = ssl_flush_socket(&(csp->ssl_client_attr),
3916                             csp->iob) < 0))
3917                   {
3918                      log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3919
3920                      /*
3921                       * The write failed, so don't bother mentioning it
3922                       * to the client... it probably can't hear us anyway.
3923                       */
3924                      freez(hdr);
3925                      mark_server_socket_tainted(csp);
3926 #ifdef FEATURE_HTTPS_INSPECTION
3927                      close_client_and_server_ssl_connections(csp);
3928 #endif
3929                      return;
3930                   }
3931                }
3932                else
3933 #endif /* def FEATURE_HTTPS_INSPECTION */
3934                {
3935                   if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3936                      || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3937                   {
3938                      log_error(LOG_LEVEL_ERROR,
3939                         "write header to client failed");
3940                      /*
3941                       * The write failed, so don't bother mentioning it
3942                       * to the client... it probably can't hear us anyway.
3943                       */
3944                      freez(hdr);
3945                      mark_server_socket_tainted(csp);
3946                      return;
3947                   }
3948                }
3949                                 }
3950
3951             /* we're finished with the server's header */
3952
3953             freez(hdr);
3954             server_body = 1;
3955
3956             /*
3957              * If this was a MS IIS/5 hack then it means the server
3958              * has already closed the connection. Nothing more to read.
3959              * Time to bail.
3960              */
3961             if (ms_iis5_hack)
3962             {
3963                log_error(LOG_LEVEL_ERROR,
3964                   "Closed server connection detected. "
3965                   "Applying the MS IIS5 hack didn't help.");
3966                log_error(LOG_LEVEL_CLF,
3967                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3968 #ifdef FEATURE_HTTPS_INSPECTION
3969                /*
3970                 * Sending data with standard or secured connection (HTTP/HTTPS)
3971                 */
3972                if (client_use_ssl(csp))
3973                {
3974                   ssl_send_data_delayed(&(csp->ssl_client_attr),
3975                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3976                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
3977                      get_write_delay(csp));
3978                }
3979                else
3980 #endif /* def FEATURE_HTTPS_INSPECTION */
3981                {
3982                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3983                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3984                }
3985                mark_server_socket_tainted(csp);
3986 #ifdef FEATURE_HTTPS_INSPECTION
3987                close_client_and_server_ssl_connections(csp);
3988 #endif
3989                return;
3990             }
3991          }
3992          continue;
3993       }
3994       mark_server_socket_tainted(csp);
3995 #ifdef FEATURE_HTTPS_INSPECTION
3996       close_client_and_server_ssl_connections(csp);
3997 #endif
3998       return; /* huh? we should never get here */
3999    }
4000
4001    if (csp->content_length == 0)
4002    {
4003       /*
4004        * If Privoxy didn't recalculate the Content-Length,
4005        * byte_count is still correct.
4006        */
4007       csp->content_length = byte_count;
4008    }
4009
4010 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4011    if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
4012       && (csp->expected_content_length != byte_count))
4013    {
4014       log_error(LOG_LEVEL_CONNECT,
4015          "Received %llu bytes while expecting %llu.",
4016          byte_count, csp->expected_content_length);
4017       mark_server_socket_tainted(csp);
4018    }
4019 #endif
4020
4021 #ifdef FEATURE_HTTPS_INSPECTION
4022    if (client_use_ssl(csp))
4023    {
4024       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
4025          csp->ip_addr_str, http->gpc, http->hostport, http->path,
4026          http->version, csp->content_length);
4027    }
4028    else
4029 #endif
4030    {
4031       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
4032          csp->ip_addr_str, http->ocmd, csp->content_length);
4033    }
4034    csp->server_connection.timestamp = time(NULL);
4035 }
4036
4037
4038 /*********************************************************************
4039  *
4040  * Function    :  chat
4041  *
4042  * Description :  Once a connection from the client has been accepted,
4043  *                this function is called (via serve()) to handle the
4044  *                main business of the communication.  This function
4045  *                returns after dealing with a single request. It can
4046  *                be called multiple times with the same client socket
4047  *                if the client is keeping the connection alive.
4048  *
4049  *                The decision whether or not a client connection will
4050  *                be kept alive is up to the caller which also must
4051  *                close the client socket when done.
4052  *
4053  *                FIXME: chat is nearly thousand lines long.
4054  *                Ridiculous.
4055  *
4056  * Parameters  :
4057  *          1  :  csp = Current client state (buffers, headers, etc...)
4058  *
4059  * Returns     :  Nothing.
4060  *
4061  *********************************************************************/
4062 static void chat(struct client_state *csp)
4063 {
4064    const struct forward_spec *fwd;
4065    struct http_request *http;
4066    /* Skeleton for HTTP response, if we should intercept the request */
4067    struct http_response *rsp;
4068 #ifdef FEATURE_HTTPS_INSPECTION
4069    int use_ssl_tunnel = 0;
4070 #endif
4071
4072    http = csp->http;
4073
4074    if (receive_client_request(csp) != JB_ERR_OK)
4075    {
4076       return;
4077    }
4078    if (parse_client_request(csp) != JB_ERR_OK)
4079    {
4080       return;
4081    }
4082
4083    /* decide how to route the HTTP request */
4084    fwd = forward_url(csp, http);
4085
4086 #ifdef FEATURE_HTTPS_INSPECTION
4087    /*
4088     * Setting flags to use old solution with SSL tunnel and to disable
4089     * certificate verification.
4090     */
4091    if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
4092       && !cgi_page_requested(csp->http->host))
4093    {
4094       use_ssl_tunnel = 1;
4095    }
4096
4097    if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
4098    {
4099       csp->dont_verify_certificate = 1;
4100    }
4101 #endif
4102
4103    /*
4104     * build the http request to send to the server
4105     * we have to do one of the following:
4106     *
4107     * create =    use the original HTTP request to create a new
4108     *             HTTP request that has either the path component
4109     *             without the http://domainspec (w/path) or the
4110     *             full orininal URL (w/url)
4111     *             Note that the path and/or the HTTP version may
4112     *             have been altered by now.
4113     *
4114     * SSL proxy = Open a socket to the host:port of the server
4115     *             and create TLS/SSL connection with server and
4116     *             with client. Then behave like mediator between
4117     *             client and server over TLS/SSL.
4118     *
4119     * SSL proxy = Pass the request unchanged if forwarding a CONNECT
4120     *    with     request to a parent proxy. Note that we'll be sending
4121     * forwarding  the CFAIL message ourselves if connecting to the parent
4122     *             fails, but we won't send a CSUCCEED message if it works,
4123     *             since that would result in a double message (ours and the
4124     *             parent's). After sending the request to the parent, we
4125     *             must parse answer and send it to client. If connection
4126     *             with server is established, we do TLS/SSL proxy. Otherwise
4127     *             we send parent response to client and close connections.
4128     *
4129     * here's the matrix:
4130     *                        SSL
4131     *                    0        1
4132     *                +--------+--------+
4133     *                |        |        |
4134     *             0  | create |   SSL  |
4135     *                | w/path |  proxy |
4136     *  Forwarding    +--------+--------+
4137     *                |        |   SSL  |
4138     *             1  | create |  proxy |
4139     *                | w/url  |+forward|
4140     *                +--------+--------+
4141     *
4142     */
4143
4144 #ifdef FEATURE_HTTPS_INSPECTION
4145    /*
4146     * Presetting SSL client and server flags
4147     */
4148    if (http->ssl && !use_ssl_tunnel)
4149    {
4150       http->client_ssl = 1;
4151       http->server_ssl = 1;
4152    }
4153    else
4154    {
4155       http->client_ssl = 0;
4156       http->server_ssl = 0;
4157    }
4158 #endif
4159
4160 #ifdef FEATURE_HTTPS_INSPECTION
4161    /*
4162     * Log the request unless we're https inspecting
4163     * in which case we don't have the path yet and
4164     * will log the request later.
4165     */
4166    if (!client_use_ssl(csp))
4167 #endif
4168    {
4169       log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
4170    }
4171
4172    if (http->ssl && connect_port_is_forbidden(csp))
4173    {
4174       const char *acceptable_connect_ports =
4175          csp->action->string[ACTION_STRING_LIMIT_CONNECT];
4176       assert(NULL != acceptable_connect_ports);
4177       log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
4178          "limit-connect{%s} doesn't allow CONNECT requests to %s",
4179          csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
4180       csp->action->flags |= ACTION_BLOCK;
4181       http->ssl = 0;
4182 #ifdef FEATURE_HTTPS_INSPECTION
4183       http->client_ssl = 0;
4184       http->server_ssl = 0;
4185 #endif
4186    }
4187
4188
4189    freez(csp->headers->first->str);
4190    build_request_line(csp, fwd, &csp->headers->first->str);
4191
4192    /*
4193     * We have a request. Check if one of the crunchers wants it
4194     * unless the client wants to use TLS/SSL in which case we
4195     * haven't setup the TLS context yet and will send the crunch
4196     * response later.
4197     */
4198    if (
4199 #ifdef FEATURE_HTTPS_INSPECTION
4200        !client_use_ssl(csp) &&
4201 #endif
4202        crunch_response_triggered(csp, crunchers_all))
4203    {
4204       /*
4205        * Yes. The client got the crunch response and we're done here.
4206        */
4207       return;
4208    }
4209
4210    log_applied_actions(csp->action);
4211    if (fwd->forward_host)
4212    {
4213       log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
4214          fwd->forward_host, fwd->forward_port, http->hostport);
4215    }
4216    else
4217    {
4218       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
4219    }
4220
4221    /* here we connect to the server, gateway, or the forwarder */
4222
4223 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4224    if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
4225       && socket_is_still_alive(csp->server_connection.sfd)
4226       && connection_destination_matches(&csp->server_connection, http, fwd))
4227    {
4228       log_error(LOG_LEVEL_CONNECT,
4229          "Reusing server socket %d connected to %s. Total requests: %u.",
4230          csp->server_connection.sfd, csp->server_connection.host,
4231          csp->server_connection.requests_sent_total);
4232    }
4233    else
4234    {
4235       if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4236       {
4237 #ifdef FEATURE_CONNECTION_SHARING
4238          if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
4239 #ifdef FEATURE_HTTPS_INSPECTION
4240             && !server_use_ssl(csp)
4241 #endif
4242             )
4243          {
4244             remember_connection(&csp->server_connection);
4245          }
4246          else
4247 #endif /* def FEATURE_CONNECTION_SHARING */
4248          {
4249             log_error(LOG_LEVEL_CONNECT,
4250                "Closing server socket %d connected to %s. Total requests: %u.",
4251                csp->server_connection.sfd, csp->server_connection.host,
4252                csp->server_connection.requests_sent_total);
4253             close_socket(csp->server_connection.sfd);
4254          }
4255          mark_connection_closed(&csp->server_connection);
4256       }
4257 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4258 #ifdef FEATURE_HTTPS_INSPECTION
4259       if (http->ssl && !use_ssl_tunnel)
4260       {
4261          int ret;
4262          /*
4263           * Creating a SSL proxy.
4264           *
4265           * By sending the CSUCCEED message we're lying to the client as
4266           * the connection hasn't actually been established yet. We don't
4267           * establish the connection until we have seen and parsed the
4268           * encrypted client headers.
4269           */
4270          if (write_socket_delayed(csp->cfd, CSUCCEED,
4271                strlen(CSUCCEED), get_write_delay(csp)) != 0)
4272          {
4273             log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
4274             return;
4275          }
4276
4277          ret = create_client_ssl_connection(csp);
4278          if (ret != 0)
4279          {
4280             log_error(LOG_LEVEL_ERROR,
4281                "Failed to open a secure connection with the client");
4282             return;
4283          }
4284          if (JB_ERR_OK != process_encrypted_request(csp))
4285          {
4286             close_client_ssl_connection(csp);
4287             return;
4288          }
4289          /*
4290           * We have an encrypted request. Check if one of the crunchers now
4291           * wants it (for example because the previously invisible path was
4292           * required to match).
4293           */
4294          if (crunch_response_triggered(csp, crunchers_all))
4295          {
4296             /*
4297              * Yes. The client got the crunch response and we're done here.
4298              */
4299             return;
4300          }
4301       }
4302 #endif
4303       /*
4304        * Connecting to destination server
4305        */
4306       csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
4307
4308       if (csp->server_connection.sfd == JB_INVALID_SOCKET)
4309       {
4310          if (fwd->type != SOCKS_NONE)
4311          {
4312             /* Socks error. */
4313             rsp = error_response(csp, "forwarding-failed");
4314          }
4315          else if (errno == EINVAL)
4316          {
4317             rsp = error_response(csp, "no-such-domain");
4318          }
4319          else
4320          {
4321             rsp = error_response(csp, "connect-failed");
4322          }
4323
4324          /* Write the answer to the client */
4325          if (rsp != NULL)
4326          {
4327             send_crunch_response(csp, rsp);
4328          }
4329
4330          /*
4331           * Temporary workaround to prevent already-read client
4332           * bodies from being parsed as new requests. For now we
4333           * err on the safe side and throw all the following
4334           * requests under the bus, even if no client body has been
4335           * buffered. A compliant client will repeat the dropped
4336           * requests on an untainted connection.
4337           *
4338           * The proper fix is to discard the no longer needed
4339           * client body in the buffer (if there is one) and to
4340           * continue parsing the bytes that follow.
4341           */
4342 #ifdef FEATURE_HTTPS_INSPECTION
4343          close_client_ssl_connection(csp);
4344 #endif
4345          drain_and_close_socket(csp->cfd);
4346          csp->cfd = JB_INVALID_SOCKET;
4347
4348          return;
4349       }
4350
4351 #ifdef FEATURE_HTTPS_INSPECTION
4352       /*
4353        * Creating TLS/SSL connections with destination server or parent
4354        * proxy. If forwarding is enabled, we must send client request to
4355        * parent proxy and receive, parse and resend parent proxy answer.
4356        */
4357       if (http->ssl && !use_ssl_tunnel)
4358       {
4359          if (fwd->forward_host != NULL)
4360          {
4361             char server_response[BUFFER_SIZE];
4362             int ret = 0;
4363             int len = 0;
4364             char *hdr = list_to_text(csp->headers);
4365             memset(server_response, 0, sizeof(server_response));
4366
4367             if (hdr == NULL)
4368             {
4369                log_error(LOG_LEVEL_FATAL,
4370                   "Out of memory parsing client header");
4371             }
4372             list_remove_all(csp->headers);
4373
4374             /*
4375              * Sending client's CONNECT request to the parent proxy
4376              */
4377             ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4378
4379             freez(hdr);
4380
4381             if (ret != 0)
4382             {
4383                log_error(LOG_LEVEL_CONNECT,
4384                   "Sending request headers to: %s failed", http->hostport);
4385                mark_server_socket_tainted(csp);
4386                close_client_ssl_connection(csp);
4387                return;
4388             }
4389
4390             /* Waiting for parent proxy server response */
4391             len = read_socket(csp->server_connection.sfd, server_response,
4392                sizeof(server_response)-1);
4393
4394             if (len <= 0)
4395             {
4396                log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4397                   "server on socket %d.", csp->server_connection.sfd);
4398
4399                rsp = error_response(csp, "no-server-data");
4400                if (rsp)
4401                {
4402                   send_crunch_response(csp, rsp);
4403                }
4404                mark_server_socket_tainted(csp);
4405                close_client_ssl_connection(csp);
4406                return;
4407             }
4408
4409             /*
4410              * Test if the connection to the destination server was
4411              * established successfully by the parent proxy.
4412              */
4413             if (!tunnel_established_successfully(server_response, (unsigned int)len))
4414             {
4415                log_error(LOG_LEVEL_ERROR,
4416                   "The forwarder %s failed to establish a connection with %s",
4417                   fwd->forward_host, http->host);
4418                rsp = error_response(csp, "connect-failed");
4419                if (rsp)
4420                {
4421                   send_crunch_response(csp, rsp);
4422                }
4423                mark_server_socket_tainted(csp);
4424                close_client_ssl_connection(csp);
4425                return;
4426             }
4427          } /* -END- if (fwd->forward_host != NULL) */
4428
4429          /*
4430           * We can now create the TLS/SSL connection with the destination server.
4431           */
4432          int ret = create_server_ssl_connection(csp);
4433          if (ret != 0)
4434          {
4435             if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4436                 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4437             {
4438                /*
4439                 * If the server certificate is invalid, we must inform
4440                 * the client and then close connection to the client.
4441                 */
4442                ssl_send_certificate_error(csp);
4443                close_client_and_server_ssl_connections(csp);
4444                return;
4445             }
4446             if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4447              || csp->server_cert_verification_result == SSL_CERT_VALID)
4448             {
4449                /*
4450                 * The TLS/SSL connection wasn't created but an invalid
4451                 * certificate wasn't detected. Report it as connection
4452                 * failure.
4453                 */
4454                rsp = error_response(csp, "connect-failed");
4455                if (rsp)
4456                {
4457                   send_crunch_response(csp, rsp);
4458                }
4459                close_client_and_server_ssl_connections(csp);
4460                return;
4461             }
4462          }
4463       }/* -END- if (http->ssl) */
4464 #endif /* def FEATURE_HTTPS_INSPECTION */
4465
4466 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4467       save_connection_destination(csp->server_connection.sfd,
4468          http, fwd, &csp->server_connection);
4469       csp->server_connection.keep_alive_timeout =
4470          (unsigned)csp->config->keep_alive_timeout;
4471    }
4472 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4473
4474    csp->server_connection.requests_sent_total++;
4475
4476    if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4477    {
4478       /* Client headers have been sent optimistically */
4479       assert(csp->headers->last == NULL);
4480    }
4481    else if (http->ssl == 0 || (fwd->forward_host
4482 #ifdef FEATURE_HTTPS_INSPECTION
4483          && use_ssl_tunnel
4484 #endif
4485            ))
4486    {
4487       if (send_http_request(csp))
4488       {
4489          rsp = error_response(csp, "connect-failed");
4490          if (rsp)
4491          {
4492             send_crunch_response(csp, rsp);
4493          }
4494          return;
4495       }
4496    }
4497    else
4498    {
4499       /*
4500        * Using old solution with SSL tunnel or new solution with SSL proxy
4501        */
4502       list_remove_all(csp->headers);
4503 #ifdef FEATURE_HTTPS_INSPECTION
4504       if (use_ssl_tunnel)
4505 #endif
4506       {
4507          /*
4508          * We're running an SSL tunnel and we're not forwarding,
4509          * so just ditch the client headers, send the "connect succeeded"
4510          * message to the client, flush the rest, and get out of the way.
4511          */
4512          if (write_socket_delayed(csp->cfd, CSUCCEED,
4513                strlen(CSUCCEED), get_write_delay(csp)))
4514          {
4515             return;
4516          }
4517       }
4518 #ifdef FEATURE_HTTPS_INSPECTION
4519       else
4520       {
4521          /*
4522           * If server certificate has been verified and is invalid,
4523           * we must inform the client and then close the connection
4524           * with client and server.
4525           */
4526          if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4527              csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4528          {
4529             ssl_send_certificate_error(csp);
4530             close_client_and_server_ssl_connections(csp);
4531             return;
4532          }
4533          if (send_https_request(csp))
4534          {
4535             rsp = error_response(csp, "connect-failed");
4536             if (rsp)
4537             {
4538                send_crunch_response(csp, rsp);
4539             }
4540             close_client_and_server_ssl_connections(csp);
4541             return;
4542          }
4543       }
4544 #endif /* def FEATURE_HTTPS_INSPECTION */
4545       clear_iob(csp->client_iob);
4546    }/* -END- else ... if (http->ssl == 1) */
4547
4548    log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4549
4550    /* XXX: should the time start earlier for optimistically sent data? */
4551    csp->server_connection.request_sent = time(NULL);
4552
4553    handle_established_connection(csp);
4554    freez(csp->receive_buffer);
4555 }
4556
4557
4558 #ifdef FUZZ
4559 /*********************************************************************
4560  *
4561  * Function    :  fuzz_server_response
4562  *
4563  * Description :  Treat the input as a whole server response.
4564  *
4565  * Parameters  :
4566  *          1  :  csp = Current client state (buffers, headers, etc...)
4567  *          2  :  fuzz_input_file = File to read the input from.
4568  *
4569  * Returns     :  0
4570  *
4571  *********************************************************************/
4572 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4573 {
4574    static struct forward_spec fwd; /* Zero'd due to being static */
4575    csp->cfd = 0;
4576
4577    if (strcmp(fuzz_input_file, "-") == 0)
4578    {
4579       /* XXX: Doesn't work yet. */
4580       csp->server_connection.sfd = 0;
4581    }
4582    else
4583    {
4584       csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4585       if (csp->server_connection.sfd == -1)
4586       {
4587          log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4588             fuzz_input_file);
4589       }
4590    }
4591    csp->fwd = &fwd;
4592    csp->content_type |= CT_GIF;
4593    csp->action->flags |= ACTION_DEANIMATE;
4594    csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4595
4596    csp->http->path = strdup_or_die("/");
4597    csp->http->host = strdup_or_die("fuzz.example.org");
4598    csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4599    /* Prevent client socket monitoring */
4600    csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4601    csp->flags |= CSP_FLAG_CHUNKED;
4602
4603    csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4604    csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4605
4606    csp->content_type |= CT_DECLARED|CT_GIF;
4607
4608    csp->config->socket_timeout = 0;
4609
4610    cgi_init_error_messages();
4611
4612    handle_established_connection(csp);
4613    freez(csp->receive_buffer);
4614
4615    return 0;
4616 }
4617 #endif
4618
4619
4620 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4621 /*********************************************************************
4622  *
4623  * Function    :  prepare_csp_for_next_request
4624  *
4625  * Description :  Put the csp in a mostly vergin state.
4626  *
4627  * Parameters  :
4628  *          1  :  csp = Current client state (buffers, headers, etc...)
4629  *
4630  * Returns     :  N/A
4631  *
4632  *********************************************************************/
4633 static void prepare_csp_for_next_request(struct client_state *csp)
4634 {
4635    csp->content_type = 0;
4636    csp->content_length = 0;
4637    csp->expected_content_length = 0;
4638    csp->expected_client_content_length = 0;
4639    list_remove_all(csp->headers);
4640    clear_iob(csp->iob);
4641    freez(csp->error_message);
4642    free_http_request(csp->http);
4643    destroy_list(csp->headers);
4644 #ifdef FEATURE_HTTPS_INSPECTION
4645    destroy_list(csp->https_headers);
4646 #endif
4647    destroy_list(csp->tags);
4648 #ifdef FEATURE_CLIENT_TAGS
4649    destroy_list(csp->client_tags);
4650    freez(csp->client_address);
4651 #endif
4652    free_current_action(csp->action);
4653    if (NULL != csp->fwd)
4654    {
4655       unload_forward_spec(csp->fwd);
4656       csp->fwd = NULL;
4657    }
4658    /* XXX: Store per-connection flags someplace else. */
4659    csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4660 #ifdef FEATURE_TOGGLE
4661    if (global_toggle_state)
4662 #endif /* def FEATURE_TOGGLE */
4663    {
4664       csp->flags |= CSP_FLAG_TOGGLED_ON;
4665    }
4666
4667    if (csp->client_iob->eod > csp->client_iob->cur)
4668    {
4669       long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4670       size_t data_length  = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4671
4672       assert(bytes_to_shift > 0);
4673       assert(data_length > 0);
4674
4675       log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4676          data_length, bytes_to_shift);
4677       memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4678       csp->client_iob->cur = csp->client_iob->buf;
4679       assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4680       csp->client_iob->eod = csp->client_iob->buf + data_length;
4681       memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4682
4683       csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4684    }
4685    else
4686    {
4687       /*
4688        * We mainly care about resetting client_iob->cur so we don't
4689        * waste buffer space at the beginning and don't mess up the
4690        * request restoration done by cgi_show_request().
4691        *
4692        * Freeing the buffer itself isn't technically necessary,
4693        * but makes debugging more convenient.
4694        */
4695       clear_iob(csp->client_iob);
4696    }
4697 }
4698 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4699
4700
4701 /*********************************************************************
4702  *
4703  * Function    :  serve
4704  *
4705  * Description :  This is little more than chat.  We only "serve" to
4706  *                to close (or remember) any socket that chat may have
4707  *                opened.
4708  *
4709  * Parameters  :
4710  *          1  :  csp = Current client state (buffers, headers, etc...)
4711  *
4712  * Returns     :  N/A
4713  *
4714  *********************************************************************/
4715 static void serve(struct client_state *csp)
4716 {
4717    int config_file_change_detected = 0; /* Only used for debugging */
4718 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4719 #ifdef FEATURE_CONNECTION_SHARING
4720    static int monitor_thread_running = 0;
4721 #endif /* def FEATURE_CONNECTION_SHARING */
4722    int continue_chatting = 0;
4723
4724    log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4725       csp->ip_addr_str, csp->cfd);
4726
4727    do
4728    {
4729       unsigned int latency;
4730
4731 #ifdef FEATURE_HTTPS_INSPECTION
4732       if (continue_chatting && client_use_ssl(csp))
4733       {
4734          continue_https_chat(csp);
4735       }
4736       else
4737 #endif
4738       {
4739          chat(csp);
4740       }
4741
4742       /*
4743        * If the request has been crunched,
4744        * the calculated latency is zero.
4745        */
4746       latency = (unsigned)(csp->server_connection.response_received -
4747          csp->server_connection.request_sent) / 2;
4748
4749       if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4750          && (csp->flags & CSP_FLAG_CRUNCHED)
4751          && (csp->expected_client_content_length != 0))
4752       {
4753          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4754          log_error(LOG_LEVEL_CONNECT,
4755             "Tainting client socket %d due to unread data.", csp->cfd);
4756       }
4757
4758       continue_chatting = (csp->config->feature_flags
4759          & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4760          && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4761          && (csp->cfd != JB_INVALID_SOCKET)
4762          && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4763          && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4764             || (csp->flags & CSP_FLAG_CHUNKED));
4765
4766       if (!(csp->flags & CSP_FLAG_CRUNCHED)
4767          && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4768       {
4769          if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4770          {
4771             csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4772          }
4773          if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4774             || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4775             || !socket_is_still_alive(csp->server_connection.sfd)
4776             || !(latency < csp->server_connection.keep_alive_timeout))
4777          {
4778             log_error(LOG_LEVEL_CONNECT,
4779                "Closing server socket %d connected to %s. "
4780                "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4781                csp->server_connection.sfd, csp->server_connection.host,
4782                0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4783                0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4784                socket_is_still_alive(csp->server_connection.sfd),
4785                csp->server_connection.keep_alive_timeout);
4786 #ifdef FEATURE_CONNECTION_SHARING
4787             if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4788             {
4789                forget_connection(csp->server_connection.sfd);
4790             }
4791 #endif /* def FEATURE_CONNECTION_SHARING */
4792 #ifdef FEATURE_HTTPS_INSPECTION
4793             close_server_ssl_connection(csp);
4794 #endif
4795             close_socket(csp->server_connection.sfd);
4796             mark_connection_closed(&csp->server_connection);
4797          }
4798       }
4799
4800       if (continue_chatting && any_loaded_file_changed(csp))
4801       {
4802          continue_chatting = 0;
4803          config_file_change_detected = 1;
4804       }
4805 #ifdef FEATURE_HTTPS_INSPECTION
4806       if (continue_chatting && client_use_ssl(csp) &&
4807          csp->ssl_with_client_is_opened == 0)
4808       {
4809          continue_chatting = 0;
4810          log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4811             "The TLS session has been terminated.", csp->cfd);
4812       }
4813 #endif
4814
4815       if (continue_chatting)
4816       {
4817          if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4818             && socket_is_still_alive(csp->cfd))
4819          {
4820             log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4821                "pipelined on socket %d and the socket is still alive.",
4822                csp->requests_received_total+1, csp->cfd);
4823             prepare_csp_for_next_request(csp);
4824             continue;
4825          }
4826
4827          if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4828          {
4829             if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4830             {
4831                log_error(LOG_LEVEL_CONNECT,
4832                   "Waiting for the next client request on socket %d. "
4833                   "Keeping the server socket %d to %s open.",
4834                   csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4835             }
4836             else
4837             {
4838                log_error(LOG_LEVEL_CONNECT,
4839                   "Waiting for the next client request on socket %d. "
4840                   "No server socket to keep open.", csp->cfd);
4841             }
4842          }
4843
4844          if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4845             && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4846             && socket_is_still_alive(csp->cfd))
4847          {
4848             log_error(LOG_LEVEL_CONNECT,
4849                "Data arrived in time on client socket %d. Requests so far: %u",
4850                csp->cfd, csp->requests_received_total);
4851             prepare_csp_for_next_request(csp);
4852          }
4853          else
4854          {
4855 #ifdef FEATURE_CONNECTION_SHARING
4856             if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4857                && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4858                && (socket_is_still_alive(csp->server_connection.sfd))
4859 #ifdef FEATURE_HTTPS_INSPECTION
4860                && !server_use_ssl(csp)
4861 #endif
4862                 )
4863             {
4864                time_t time_open = time(NULL) - csp->server_connection.timestamp;
4865
4866                if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4867                {
4868                   break;
4869                }
4870
4871                remember_connection(&csp->server_connection);
4872                csp->server_connection.sfd = JB_INVALID_SOCKET;
4873                drain_and_close_socket(csp->cfd);
4874                csp->cfd = JB_INVALID_SOCKET;
4875                privoxy_mutex_lock(&connection_reuse_mutex);
4876                if (!monitor_thread_running)
4877                {
4878                   monitor_thread_running = 1;
4879                   privoxy_mutex_unlock(&connection_reuse_mutex);
4880                   wait_for_alive_connections();
4881                   privoxy_mutex_lock(&connection_reuse_mutex);
4882                   monitor_thread_running = 0;
4883                }
4884                privoxy_mutex_unlock(&connection_reuse_mutex);
4885             }
4886 #endif /* def FEATURE_CONNECTION_SHARING */
4887             break;
4888          }
4889       }
4890       else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4891       {
4892          log_error(LOG_LEVEL_CONNECT,
4893             "Closing server socket %d connected to %s. Keep-alive: %u. "
4894             "Tainted: %u. Socket alive: %u. Timeout: %u. "
4895             "Configuration file change detected: %u",
4896             csp->server_connection.sfd, csp->server_connection.host,
4897             0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4898             0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4899             socket_is_still_alive(csp->server_connection.sfd),
4900             csp->server_connection.keep_alive_timeout,
4901             config_file_change_detected);
4902       }
4903    } while (continue_chatting);
4904
4905 #else
4906    chat(csp);
4907 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4908
4909    if (csp->cfd != JB_INVALID_SOCKET)
4910    {
4911       log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4912          "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4913          "Configuration file change detected: %u. Requests received: %u.",
4914          csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4915          socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4916          config_file_change_detected, csp->requests_received_total);
4917 #ifdef FEATURE_HTTPS_INSPECTION
4918       close_client_ssl_connection(csp);
4919 #endif
4920       drain_and_close_socket(csp->cfd);
4921    }
4922
4923    if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4924    {
4925 #ifdef FEATURE_CONNECTION_SHARING
4926       if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4927       {
4928          forget_connection(csp->server_connection.sfd);
4929       }
4930 #endif /* def FEATURE_CONNECTION_SHARING */
4931
4932 #ifdef FEATURE_HTTPS_INSPECTION
4933       close_server_ssl_connection(csp);
4934 #endif /* def FEATURE_HTTPS_INSPECTION */
4935
4936       close_socket(csp->server_connection.sfd);
4937    }
4938
4939 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4940    mark_connection_closed(&csp->server_connection);
4941 #endif
4942
4943    free_csp_resources(csp);
4944
4945    csp->flags &= ~CSP_FLAG_ACTIVE;
4946
4947 }
4948
4949
4950 #ifdef __BEOS__
4951 /*********************************************************************
4952  *
4953  * Function    :  server_thread
4954  *
4955  * Description :  We only exist to call `serve' in a threaded environment.
4956  *
4957  * Parameters  :
4958  *          1  :  data = Current client state (buffers, headers, etc...)
4959  *
4960  * Returns     :  Always 0.
4961  *
4962  *********************************************************************/
4963 static int32 server_thread(void *data)
4964 {
4965    serve((struct client_state *) data);
4966    return 0;
4967
4968 }
4969 #endif
4970
4971
4972 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4973 /*********************************************************************
4974  *
4975  * Function    :  usage
4976  *
4977  * Description :  Print usage info & exit.
4978  *
4979  * Parameters  :  Pointer to argv[0] for identifying ourselves
4980  *
4981  * Returns     :  No. ,-)
4982  *
4983  *********************************************************************/
4984 static void usage(const char *name)
4985 {
4986    printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
4987           "Usage: %s [--config-test] "
4988 #if defined(unix)
4989           "[--chroot] "
4990 #endif /* defined(unix) */
4991           "[--help] "
4992 #if defined(unix)
4993           "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
4994 #endif /* defined(unix) */
4995          "[--version] [configfile]\n",
4996           name);
4997
4998 #ifdef FUZZ
4999    show_fuzz_usage(name);
5000 #endif
5001
5002    printf("Aborting\n");
5003
5004    exit(2);
5005
5006 }
5007 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
5008
5009
5010 #ifdef MUTEX_LOCKS_AVAILABLE
5011 /*********************************************************************
5012  *
5013  * Function    :  privoxy_mutex_lock
5014  *
5015  * Description :  Locks a mutex.
5016  *
5017  * Parameters  :
5018  *          1  :  mutex = The mutex to lock.
5019  *
5020  * Returns     :  Void. May exit in case of errors.
5021  *
5022  *********************************************************************/
5023 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
5024 {
5025 #ifdef FEATURE_PTHREAD
5026    int err = pthread_mutex_lock(mutex);
5027    if (err)
5028    {
5029       if (mutex != &log_mutex)
5030       {
5031          log_error(LOG_LEVEL_FATAL,
5032             "Mutex locking failed: %s.\n", strerror(err));
5033       }
5034       exit(1);
5035    }
5036 #else
5037    EnterCriticalSection(mutex);
5038 #endif /* def FEATURE_PTHREAD */
5039 }
5040
5041
5042 /*********************************************************************
5043  *
5044  * Function    :  privoxy_mutex_unlock
5045  *
5046  * Description :  Unlocks a mutex.
5047  *
5048  * Parameters  :
5049  *          1  :  mutex = The mutex to unlock.
5050  *
5051  * Returns     :  Void. May exit in case of errors.
5052  *
5053  *********************************************************************/
5054 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
5055 {
5056 #ifdef FEATURE_PTHREAD
5057    int err = pthread_mutex_unlock(mutex);
5058    if (err)
5059    {
5060       if (mutex != &log_mutex)
5061       {
5062          log_error(LOG_LEVEL_FATAL,
5063             "Mutex unlocking failed: %s.\n", strerror(err));
5064       }
5065       exit(1);
5066    }
5067 #else
5068    LeaveCriticalSection(mutex);
5069 #endif /* def FEATURE_PTHREAD */
5070 }
5071
5072
5073 /*********************************************************************
5074  *
5075  * Function    :  privoxy_mutex_init
5076  *
5077  * Description :  Prepares a mutex.
5078  *
5079  * Parameters  :
5080  *          1  :  mutex = The mutex to initialize.
5081  *
5082  * Returns     :  Void. May exit in case of errors.
5083  *
5084  *********************************************************************/
5085 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
5086 {
5087 #ifdef FEATURE_PTHREAD
5088    int err = pthread_mutex_init(mutex, 0);
5089    if (err)
5090    {
5091       printf("Fatal error. Mutex initialization failed: %s.\n",
5092          strerror(err));
5093       exit(1);
5094    }
5095 #else
5096    InitializeCriticalSection(mutex);
5097 #endif /* def FEATURE_PTHREAD */
5098 }
5099 #endif /* def MUTEX_LOCKS_AVAILABLE */
5100
5101 /*********************************************************************
5102  *
5103  * Function    :  initialize_mutexes
5104  *
5105  * Description :  Prepares mutexes if mutex support is available.
5106  *
5107  * Parameters  :  None
5108  *
5109  * Returns     :  Void, exits in case of errors.
5110  *
5111  *********************************************************************/
5112 static void initialize_mutexes(void)
5113 {
5114 #ifdef MUTEX_LOCKS_AVAILABLE
5115    /*
5116     * Prepare global mutex semaphores
5117     */
5118
5119 #ifdef FEATURE_HTTPS_INSPECTION
5120    privoxy_mutex_init(&certificate_mutex);
5121    privoxy_mutex_init(&ssl_init_mutex);
5122 #endif
5123
5124    privoxy_mutex_init(&log_mutex);
5125    privoxy_mutex_init(&log_init_mutex);
5126    privoxy_mutex_init(&connection_reuse_mutex);
5127 #ifdef FEATURE_EXTERNAL_FILTERS
5128    privoxy_mutex_init(&external_filter_mutex);
5129 #endif
5130 #ifdef FEATURE_CLIENT_TAGS
5131    privoxy_mutex_init(&client_tags_mutex);
5132 #endif
5133 #ifdef FEATURE_EXTENDED_STATISTICS
5134    privoxy_mutex_init(&filter_statistics_mutex);
5135    privoxy_mutex_init(&block_statistics_mutex);
5136 #endif
5137
5138    /*
5139     * XXX: The assumptions below are a bit naive
5140     * and can cause locks that aren't necessary.
5141     *
5142     * For example older FreeBSD versions (< 6.x?)
5143     * have no gethostbyname_r, but gethostbyname is
5144     * thread safe.
5145     */
5146 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
5147    privoxy_mutex_init(&resolver_mutex);
5148 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
5149    /*
5150     * XXX: should we use a single mutex for
5151     * localtime() and gmtime() as well?
5152     */
5153 #ifndef HAVE_GMTIME_R
5154    privoxy_mutex_init(&gmtime_mutex);
5155 #endif /* ndef HAVE_GMTIME_R */
5156
5157 #ifndef HAVE_LOCALTIME_R
5158    privoxy_mutex_init(&localtime_mutex);
5159 #endif /* ndef HAVE_GMTIME_R */
5160
5161 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
5162    privoxy_mutex_init(&rand_mutex);
5163 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
5164
5165 #endif /* def MUTEX_LOCKS_AVAILABLE */
5166 }
5167
5168 /*********************************************************************
5169  *
5170  * Function    :  main
5171  *
5172  * Description :  Load the config file and start the listen loop.
5173  *                This function is a lot more *sane* with the `load_config'
5174  *                and `listen_loop' functions; although it stills does
5175  *                a *little* too much for my taste.
5176  *
5177  * Parameters  :
5178  *          1  :  argc = Number of parameters (including $0).
5179  *          2  :  argv = Array of (char *)'s to the parameters.
5180  *
5181  * Returns     :  1 if : can't open config file, unrecognized directive,
5182  *                stats requested in multi-thread mode, can't open the
5183  *                log file, can't open the jar file, listen port is invalid,
5184  *                any load fails, and can't bind port.
5185  *
5186  *                Else main never returns, the process must be signaled
5187  *                to terminate execution.  Or, on Windows, use the
5188  *                "File", "Exit" menu option.
5189  *
5190  *********************************************************************/
5191 #ifdef __MINGW32__
5192 int real_main(int argc, char **argv)
5193 #else
5194 int main(int argc, char **argv)
5195 #endif
5196 {
5197    int argc_pos = 0;
5198    int do_config_test = 0;
5199 #ifndef HAVE_ARC4RANDOM
5200    unsigned int random_seed;
5201 #endif
5202 #ifdef unix
5203    struct passwd *pw = NULL;
5204    struct group *grp = NULL;
5205    int do_chroot = 0;
5206    char *pre_chroot_nslookup_to_load_resolver = NULL;
5207 #endif
5208 #ifdef FUZZ
5209    char *fuzz_input_type = NULL;
5210    char *fuzz_input_file = NULL;
5211 #endif
5212
5213    Argc = argc;
5214    Argv = argv;
5215
5216    configfile =
5217 #if !defined(_WIN32)
5218    "config"
5219 #else
5220    "config.txt"
5221 #endif
5222       ;
5223
5224    /* Prepare mutexes if supported and necessary. */
5225    initialize_mutexes();
5226
5227    /* Enable logging until further notice. */
5228    init_log_module();
5229
5230    /*
5231     * Parse the command line arguments
5232     *
5233     * XXX: simply printing usage information in case of
5234     * invalid arguments isn't particularly user friendly.
5235     */
5236    while (++argc_pos < argc)
5237    {
5238 #ifdef _WIN32
5239       /* Check to see if the service must be installed or uninstalled */
5240       if (strncmp(argv[argc_pos], "--install", 9) == 0)
5241       {
5242          const char *pName = argv[argc_pos] + 9;
5243          if (*pName == ':')
5244             pName++;
5245          exit((install_service(pName)) ? 0 : 1);
5246       }
5247       else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
5248       {
5249          const char *pName = argv[argc_pos] + 11;
5250          if (*pName == ':')
5251             pName++;
5252          exit((uninstall_service(pName)) ? 0 : 1);
5253       }
5254       else if (strcmp(argv[argc_pos], "--service") == 0)
5255       {
5256          bRunAsService = TRUE;
5257          w32_set_service_cwd();
5258          atexit(w32_service_exit_notify);
5259       }
5260       else
5261 #endif /* defined(_WIN32) */
5262
5263
5264 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5265
5266       if (strcmp(argv[argc_pos], "--help") == 0)
5267       {
5268          usage(argv[0]);
5269       }
5270
5271       else if (strcmp(argv[argc_pos], "--version") == 0)
5272       {
5273          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
5274          exit(0);
5275       }
5276
5277 #if defined(unix)
5278
5279       else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
5280       {
5281          set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
5282          daemon_mode = 0;
5283       }
5284
5285       else if (strcmp(argv[argc_pos], "--pidfile") == 0)
5286       {
5287          if (++argc_pos == argc) usage(argv[0]);
5288          pidfile = strdup_or_die(argv[argc_pos]);
5289       }
5290
5291       else if (strcmp(argv[argc_pos], "--user") == 0)
5292       {
5293          char *user_arg;
5294          char *group_name;
5295
5296          if (++argc_pos == argc) usage(argv[argc_pos]);
5297
5298          user_arg = strdup_or_die(argv[argc_pos]);
5299          group_name = strchr(user_arg, '.');
5300          if (NULL != group_name)
5301          {
5302             /* Nul-terminate the user name */
5303             *group_name = '\0';
5304
5305             /* Skip the former delimiter to actually reach the group name */
5306             group_name++;
5307
5308             grp = getgrnam(group_name);
5309             if (NULL == grp)
5310             {
5311                log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
5312             }
5313          }
5314          pw = getpwnam(user_arg);
5315          if (NULL == pw)
5316          {
5317             log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
5318          }
5319
5320          freez(user_arg);
5321       }
5322
5323       else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
5324       {
5325          if (++argc_pos == argc) usage(argv[0]);
5326          pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
5327       }
5328
5329       else if (strcmp(argv[argc_pos], "--chroot") == 0)
5330       {
5331          do_chroot = 1;
5332       }
5333 #endif /* defined(unix) */
5334
5335       else if (strcmp(argv[argc_pos], "--config-test") == 0)
5336       {
5337          do_config_test = 1;
5338       }
5339 #ifdef FUZZ
5340       else if (strcmp(argv[argc_pos], "--fuzz") == 0)
5341       {
5342          argc_pos++;
5343          if (argc < argc_pos + 2) usage(argv[0]);
5344          fuzz_input_type = argv[argc_pos];
5345          argc_pos++;
5346          fuzz_input_file = argv[argc_pos];
5347       }
5348       else if (strcmp(argv[argc_pos], "--stfu") == 0)
5349       {
5350          set_debug_level(LOG_LEVEL_STFU);
5351       }
5352 #endif
5353       else if (argc_pos + 1 != argc)
5354       {
5355          /*
5356           * This is neither the last command line
5357           * option, nor was it recognized before,
5358           * therefore it must be invalid.
5359           */
5360          usage(argv[0]);
5361       }
5362       else
5363
5364 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
5365       {
5366          configfile = argv[argc_pos];
5367       }
5368
5369    } /* -END- while (more arguments) */
5370
5371    show_version(Argv[0]);
5372
5373 #if defined(unix)
5374    if (*configfile != '/')
5375    {
5376       char cwd[BUFFER_SIZE];
5377       char *abs_file;
5378       size_t abs_file_size;
5379
5380       /* make config-filename absolute here */
5381       if (NULL == getcwd(cwd, sizeof(cwd)))
5382       {
5383          perror("failed to get current working directory");
5384          exit(1);
5385       }
5386
5387       basedir = strdup_or_die(cwd);
5388       /* XXX: why + 5? */
5389       abs_file_size = strlen(cwd) + strlen(configfile) + 5;
5390       abs_file = malloc_or_die(abs_file_size);
5391       strlcpy(abs_file, basedir, abs_file_size);
5392       strlcat(abs_file, "/", abs_file_size);
5393       strlcat(abs_file, configfile, abs_file_size);
5394       configfile = abs_file;
5395    }
5396 #endif /* defined unix */
5397
5398
5399    files->next = NULL;
5400    clients->next = NULL;
5401
5402    /* XXX: factor out initialising after the next stable release. */
5403 #ifdef _WIN32
5404    InitWin32();
5405 #endif
5406
5407 #ifndef HAVE_ARC4RANDOM
5408    random_seed = (unsigned int)time(NULL);
5409 #ifdef HAVE_RANDOM
5410    srandom(random_seed);
5411 #else
5412    srand(random_seed);
5413 #endif /* ifdef HAVE_RANDOM */
5414 #endif /* ifndef HAVE_ARC4RANDOM */
5415
5416    /*
5417     * Unix signal handling
5418     *
5419     * Catch the abort, interrupt and terminate signals for a graceful exit
5420     * Catch the hangup signal so the errlog can be reopened.
5421     *
5422     * Ignore the broken pipe signal as connection failures
5423     * are handled when and where they occur without relying
5424     * on a signal.
5425     */
5426 #if !defined(_WIN32)
5427 {
5428    int idx;
5429    const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5430
5431    for (idx = 0; idx < SZ(catched_signals); idx++)
5432    {
5433 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5434       if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5435 #else
5436       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5437 #endif /* ifdef sun */
5438       {
5439          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5440       }
5441    }
5442
5443    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5444    {
5445       log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5446    }
5447
5448 }
5449 #else /* ifdef _WIN32 */
5450 # ifdef _WIN_CONSOLE
5451    /*
5452     * We *are* in a windows console app.
5453     * Print a verbose messages about FAQ's and such
5454     */
5455    printf("%s", win32_blurb);
5456 # endif /* def _WIN_CONSOLE */
5457 #endif /* def _WIN32 */
5458
5459 #ifdef FUZZ
5460    if (fuzz_input_type != NULL)
5461    {
5462       exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5463    }
5464    log_error(LOG_LEVEL_FATAL,
5465       "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5466       "Various data structures are static which is unsafe when using threads.");
5467 #endif
5468
5469    if (do_config_test)
5470    {
5471       exit(NULL == load_config());
5472    }
5473
5474    /* Initialize the CGI subsystem */
5475    cgi_init_error_messages();
5476
5477    /*
5478     * If running on unix and without the --no-daemon
5479     * option, become a daemon. I.e. fork, detach
5480     * from tty and get process group leadership
5481     */
5482 #if defined(unix)
5483 {
5484    if (daemon_mode)
5485    {
5486       int fd;
5487       pid_t pid = fork();
5488
5489       if (pid < 0) /* error */
5490       {
5491          perror("fork");
5492          exit(3);
5493       }
5494       else if (pid != 0) /* parent */
5495       {
5496          int status;
5497          pid_t wpid;
5498          /*
5499           * must check for errors
5500           * child died due to missing files aso
5501           */
5502          sleep(1);
5503          wpid = waitpid(pid, &status, WNOHANG);
5504          if (wpid != 0)
5505          {
5506             exit(1);
5507          }
5508          exit(0);
5509       }
5510       /* child */
5511
5512       setsid();
5513
5514       /*
5515        * stderr (fd 2) will be closed later on,
5516        * when the config file has been parsed.
5517        */
5518       close(0);
5519       close(1);
5520
5521       /*
5522        * Reserve fd 0 and 1 to prevent abort() and friends
5523        * from sending stuff to the clients or servers.
5524        */
5525       fd = open("/dev/null", O_RDONLY);
5526       if (fd == -1)
5527       {
5528          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5529       }
5530       else if (fd != 0)
5531       {
5532          if (dup2(fd, 0) == -1)
5533          {
5534             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5535          }
5536          close(fd);
5537       }
5538       fd = open("/dev/null", O_WRONLY);
5539       if (fd == -1)
5540       {
5541          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5542       }
5543       else if (fd != 1)
5544       {
5545          if (dup2(fd, 1) == -1)
5546          {
5547             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5548          }
5549          close(fd);
5550       }
5551
5552 #ifdef FEATURE_EXTERNAL_FILTERS
5553       for (fd = 0; fd < 3; fd++)
5554       {
5555          mark_socket_for_close_on_execute(fd);
5556       }
5557 #endif
5558
5559       if (chdir("/") != 0)
5560       {
5561          log_error(LOG_LEVEL_FATAL, "Failed to cd into '/': %E");
5562       }
5563
5564    } /* -END- if (daemon_mode) */
5565
5566    /*
5567     * As soon as we have written the PID file, we can switch
5568     * to the user and group ID indicated by the --user option
5569     */
5570    if (pidfile != NULL)
5571    {
5572       write_pid_file(pidfile);
5573    }
5574    if (NULL != pw)
5575    {
5576       if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5577       {
5578          log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5579       }
5580       if (NULL != grp)
5581       {
5582          if (setgroups(1, &grp->gr_gid))
5583          {
5584             log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5585          }
5586       }
5587       else if (initgroups(pw->pw_name, pw->pw_gid))
5588       {
5589          log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5590       }
5591       if (do_chroot)
5592       {
5593          if (!pw->pw_dir)
5594          {
5595             log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5596          }
5597          /* Read the time zone file from /etc before doing chroot. */
5598          tzset();
5599          if (NULL != pre_chroot_nslookup_to_load_resolver
5600              && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5601          {
5602             /* Initialize resolver library. */
5603             (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5604          }
5605          if (chroot(pw->pw_dir) < 0)
5606          {
5607             log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5608          }
5609          if (chdir ("/"))
5610          {
5611             log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5612          }
5613       }
5614       if (setuid(pw->pw_uid))
5615       {
5616          log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5617       }
5618       if (do_chroot)
5619       {
5620          char putenv_dummy[64];
5621
5622          strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5623          if (putenv(putenv_dummy) != 0)
5624          {
5625             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5626          }
5627
5628          snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5629          if (putenv(putenv_dummy) != 0)
5630          {
5631             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5632          }
5633       }
5634    }
5635    else if (do_chroot)
5636    {
5637       log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5638    }
5639 }
5640 #endif /* defined unix */
5641
5642 #ifdef _WIN32
5643    /* This will be FALSE unless the command line specified --service
5644     */
5645    if (bRunAsService)
5646    {
5647       /* Yup, so now we must attempt to establish a connection
5648        * with the service dispatcher. This will only work if this
5649        * process was launched by the service control manager to
5650        * actually run as a service. If this isn't the case, i've
5651        * known it take around 30 seconds or so for the call to return.
5652        */
5653
5654       /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5655       if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5656       {
5657          /* Service has run, and at this point is now being stopped, so just return */
5658          return 0;
5659       }
5660
5661 #ifdef _WIN_CONSOLE
5662       printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5663 #endif
5664       /* An error occurred. Usually it's because --service was wrongly specified
5665        * and we were unable to connect to the Service Control Dispatcher because
5666        * it wasn't expecting us and is therefore not listening.
5667        *
5668        * For now, just continue below to call the listen_loop function.
5669        */
5670    }
5671 #endif /* def _WIN32 */
5672
5673    listen_loop();
5674
5675    /* NOTREACHED */
5676    return(-1);
5677
5678 }
5679
5680
5681 /*********************************************************************
5682  *
5683  * Function    :  bind_port_helper
5684  *
5685  * Description :  Bind the listen port.  Handles logging, and aborts
5686  *                on failure.
5687  *
5688  * Parameters  :
5689  *          1  :  haddr = Host address to bind to. Use NULL to bind to
5690  *                        INADDR_ANY.
5691  *          2  :  hport = Specifies port to bind to.
5692  *          3  :  backlog = Listen backlog.
5693  *
5694  * Returns     :  Port that was opened.
5695  *
5696  *********************************************************************/
5697 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5698 {
5699    int result;
5700    jb_socket bfd;
5701
5702    result = bind_port(haddr, hport, backlog, &bfd);
5703
5704    if (result < 0)
5705    {
5706       const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5707       switch(result)
5708       {
5709          case -3:
5710             log_error(LOG_LEVEL_FATAL,
5711                "can't bind to %s:%d: There may be another Privoxy "
5712                "or some other proxy running on port %d",
5713                bind_address, hport, hport);
5714
5715          case -2:
5716             log_error(LOG_LEVEL_FATAL,
5717                "can't bind to %s:%d: The hostname is not resolvable",
5718                bind_address, hport);
5719
5720          default:
5721             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5722                bind_address, hport);
5723       }
5724
5725       /* shouldn't get here */
5726       return JB_INVALID_SOCKET;
5727    }
5728
5729 #ifndef HAVE_POLL
5730 #ifndef _WIN32
5731    if (bfd >= FD_SETSIZE)
5732    {
5733       log_error(LOG_LEVEL_FATAL,
5734          "Bind socket number too high to use select(): %d >= %d",
5735          bfd, FD_SETSIZE);
5736    }
5737 #endif
5738 #endif
5739
5740    if (haddr == NULL)
5741    {
5742       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5743          hport);
5744    }
5745    else
5746    {
5747       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5748          hport, haddr);
5749    }
5750
5751    return bfd;
5752 }
5753
5754
5755 /*********************************************************************
5756  *
5757  * Function    :  bind_ports_helper
5758  *
5759  * Description :  Bind the listen ports.  Handles logging, and aborts
5760  *                on failure.
5761  *
5762  * Parameters  :
5763  *          1  :  config = Privoxy configuration.  Specifies ports
5764  *                         to bind to.
5765  *          2  :  sockets = Preallocated array of opened sockets
5766  *                          corresponding to specification in config.
5767  *                          All non-opened sockets will be set to
5768  *                          JB_INVALID_SOCKET.
5769  *
5770  * Returns     :  Nothing. Inspect sockets argument.
5771  *
5772  *********************************************************************/
5773 static void bind_ports_helper(struct configuration_spec * config,
5774                               jb_socket sockets[])
5775 {
5776    int i;
5777
5778    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5779    {
5780       if (config->hport[i])
5781       {
5782          sockets[i] = bind_port_helper(config->haddr[i],
5783             config->hport[i], config->listen_backlog);
5784 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5785          if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5786          {
5787             struct accept_filter_arg af_options;
5788             bzero(&af_options, sizeof(af_options));
5789             strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5790             if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5791                   sizeof(af_options)))
5792             {
5793                log_error(LOG_LEVEL_ERROR,
5794                   "Enabling accept filter for socket %d failed: %E", sockets[i]);
5795             }
5796          }
5797 #endif
5798       }
5799       else
5800       {
5801          sockets[i] = JB_INVALID_SOCKET;
5802       }
5803    }
5804    config->need_bind = 0;
5805 }
5806
5807
5808 /*********************************************************************
5809  *
5810  * Function    :  close_ports_helper
5811  *
5812  * Description :  Close listenings ports.
5813  *
5814  * Parameters  :
5815  *          1  :  sockets = Array of opened and non-opened sockets to
5816  *                          close. All sockets will be set to
5817  *                          JB_INVALID_SOCKET.
5818  *
5819  * Returns     :  Nothing.
5820  *
5821  *********************************************************************/
5822 static void close_ports_helper(jb_socket sockets[])
5823 {
5824    int i;
5825
5826    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5827    {
5828       if (JB_INVALID_SOCKET != sockets[i])
5829       {
5830          close_socket(sockets[i]);
5831       }
5832       sockets[i] = JB_INVALID_SOCKET;
5833    }
5834 }
5835
5836
5837 #ifdef _WIN32
5838 /* Without this simple workaround we get this compiler warning from _beginthread
5839  *     warning C4028: formal parameter 1 different from declaration
5840  */
5841 void w32_service_listen_loop(void *p)
5842 {
5843    listen_loop();
5844 }
5845 #endif /* def _WIN32 */
5846
5847
5848 /*********************************************************************
5849  *
5850  * Function    :  listen_loop
5851  *
5852  * Description :  bind the listen port and enter a "FOREVER" listening loop.
5853  *
5854  * Parameters  :  N/A
5855  *
5856  * Returns     :  Never.
5857  *
5858  *********************************************************************/
5859 static void listen_loop(void)
5860 {
5861    struct client_states *csp_list = NULL;
5862    struct client_state *csp = NULL;
5863    jb_socket bfds[MAX_LISTENING_SOCKETS];
5864    struct configuration_spec *config;
5865    unsigned int active_threads = 0;
5866 #if defined(FEATURE_PTHREAD)
5867    pthread_attr_t attrs;
5868
5869    pthread_attr_init(&attrs);
5870    pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5871 #endif
5872
5873    config = load_config();
5874
5875 #ifdef FEATURE_CONNECTION_SHARING
5876    /*
5877     * XXX: Should be relocated once it no
5878     * longer needs to emit log messages.
5879     */
5880    initialize_reusable_connections();
5881 #endif /* def FEATURE_CONNECTION_SHARING */
5882
5883    bind_ports_helper(config, bfds);
5884
5885 #ifdef FEATURE_GRACEFUL_TERMINATION
5886    while (!g_terminate)
5887 #else
5888    for (;;)
5889 #endif
5890    {
5891 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
5892       while (waitpid(-1, NULL, WNOHANG) > 0)
5893       {
5894          /* zombie children */
5895       }
5896 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5897
5898       /*
5899        * Free data that was used by died threads
5900        */
5901       active_threads = sweep();
5902
5903 #if defined(unix)
5904       /*
5905        * Re-open the errlog after HUP signal
5906        */
5907       if (received_hup_signal)
5908       {
5909          if (NULL != config->logfile)
5910          {
5911             init_error_log(Argv[0], config->logfile);
5912          }
5913          received_hup_signal = 0;
5914       }
5915 #endif
5916
5917       csp_list = zalloc_or_die(sizeof(*csp_list));
5918       csp = &csp_list->csp;
5919
5920       log_error(LOG_LEVEL_CONNECT,
5921          "Waiting for the next client connection. Currently active threads: %u",
5922          active_threads);
5923
5924       /*
5925        * This config may be outdated, but for accept_connection()
5926        * it's fresh enough.
5927        */
5928       csp->config = config;
5929
5930       if (!accept_connection(csp, bfds))
5931       {
5932          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5933          freez(csp_list);
5934          continue;
5935       }
5936
5937       csp->flags |= CSP_FLAG_ACTIVE;
5938       csp->server_connection.sfd = JB_INVALID_SOCKET;
5939
5940       csp->config = config = load_config();
5941
5942       if (config->need_bind)
5943       {
5944          /*
5945           * Since we were listening to the "old port", we will not see
5946           * a "listen" param change until the next request.  So, at
5947           * least 1 more request must be made for us to find the new
5948           * setting.  I am simply closing the old socket and binding the
5949           * new one.
5950           *
5951           * Which-ever is correct, we will serve 1 more page via the
5952           * old settings.  This should probably be a "show-status"
5953           * request.  This should not be a so common of an operation
5954           * that this will hurt people's feelings.
5955           */
5956
5957          close_ports_helper(bfds);
5958
5959          bind_ports_helper(config, bfds);
5960       }
5961
5962 #ifdef FEATURE_TOGGLE
5963       if (global_toggle_state)
5964 #endif /* def FEATURE_TOGGLE */
5965       {
5966          csp->flags |= CSP_FLAG_TOGGLED_ON;
5967       }
5968
5969       if (run_loader(csp))
5970       {
5971          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5972          /* Never get here - LOG_LEVEL_FATAL causes program exit */
5973       }
5974
5975 #ifdef FEATURE_ACL
5976       if (block_acl(NULL,csp))
5977       {
5978          log_error(LOG_LEVEL_CONNECT,
5979             "Connection from %s on %s (socket %d) dropped due to ACL",
5980             csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5981          close_socket(csp->cfd);
5982          freez(csp->ip_addr_str);
5983          freez(csp->listen_addr_str);
5984          freez(csp_list);
5985          continue;
5986       }
5987 #endif /* def FEATURE_ACL */
5988
5989       if ((0 != config->max_client_connections)
5990          && (active_threads >= config->max_client_connections))
5991       {
5992          log_error(LOG_LEVEL_CONNECT,
5993             "Rejecting connection from %s. Maximum number of connections reached.",
5994             csp->ip_addr_str);
5995          write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5996             strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5997          close_socket(csp->cfd);
5998          freez(csp->ip_addr_str);
5999          freez(csp->listen_addr_str);
6000          freez(csp_list);
6001          continue;
6002       }
6003
6004       /* add it to the list of clients */
6005       csp_list->next = clients->next;
6006       clients->next = csp_list;
6007
6008       if (config->multi_threaded)
6009       {
6010          int child_id;
6011
6012 /* this is a switch () statement in the C preprocessor - ugh */
6013 #undef SELECTED_ONE_OPTION
6014
6015 /* Use Pthreads in preference to native code */
6016 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
6017 #define SELECTED_ONE_OPTION
6018          {
6019             pthread_t the_thread;
6020             int ret;
6021
6022             ret = pthread_create(&the_thread, &attrs,
6023                (void * (*)(void *))serve, csp);
6024             child_id = ret ? -1 : 0;
6025          }
6026 #endif
6027
6028 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
6029 #define SELECTED_ONE_OPTION
6030          child_id = _beginthread(
6031             (void (*)(void *))serve,
6032             64 * 1024,
6033             csp);
6034 #endif
6035
6036 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
6037 #define SELECTED_ONE_OPTION
6038          {
6039             thread_id tid = spawn_thread
6040                (server_thread, "server", B_NORMAL_PRIORITY, csp);
6041
6042             if ((tid >= 0) && (resume_thread(tid) == B_OK))
6043             {
6044                child_id = (int) tid;
6045             }
6046             else
6047             {
6048                child_id = -1;
6049             }
6050          }
6051 #endif
6052
6053 #if !defined(SELECTED_ONE_OPTION)
6054          child_id = fork();
6055
6056          /* This block is only needed when using fork().
6057           * When using threads, the server thread was
6058           * created and run by the call to _beginthread().
6059           */
6060          if (child_id == 0)   /* child */
6061          {
6062             int rc = 0;
6063 #ifdef FEATURE_TOGGLE
6064             int inherited_toggle_state = global_toggle_state;
6065 #endif /* def FEATURE_TOGGLE */
6066
6067             serve(csp);
6068
6069             /*
6070              * If we've been toggled or we've blocked the request, tell Mom
6071              */
6072
6073 #ifdef FEATURE_TOGGLE
6074             if (inherited_toggle_state != global_toggle_state)
6075             {
6076                rc |= RC_FLAG_TOGGLED;
6077             }
6078 #endif /* def FEATURE_TOGGLE */
6079
6080 #ifdef FEATURE_STATISTICS
6081             if (csp->flags & CSP_FLAG_REJECTED)
6082             {
6083                rc |= RC_FLAG_BLOCKED;
6084             }
6085 #endif /* ndef FEATURE_STATISTICS */
6086
6087             _exit(rc);
6088          }
6089          else if (child_id > 0) /* parent */
6090          {
6091             /* in a fork()'d environment, the parent's
6092              * copy of the client socket and the CSP
6093              * are not used.
6094              */
6095             int child_status;
6096 #if !defined(_WIN32) && !defined(__CYGWIN__)
6097
6098             wait(&child_status);
6099
6100             /*
6101              * Evaluate child's return code: If the child has
6102              *  - been toggled, toggle ourselves
6103              *  - blocked its request, bump up the stats counter
6104              */
6105
6106 #ifdef FEATURE_TOGGLE
6107             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
6108             {
6109                global_toggle_state = !global_toggle_state;
6110             }
6111 #endif /* def FEATURE_TOGGLE */
6112
6113 #ifdef FEATURE_STATISTICS
6114             urls_read++;
6115             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
6116             {
6117                urls_rejected++;
6118             }
6119 #endif /* def FEATURE_STATISTICS */
6120
6121 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
6122             close_socket(csp->cfd);
6123             csp->flags &= ~CSP_FLAG_ACTIVE;
6124          }
6125 #endif
6126
6127 #undef SELECTED_ONE_OPTION
6128 /* end of cpp switch () */
6129
6130          if (child_id < 0)
6131          {
6132             /*
6133              * Spawning the child failed, assume it's because
6134              * there are too many children running already.
6135              * XXX: If you assume ...
6136              */
6137             log_error(LOG_LEVEL_ERROR,
6138                "Unable to take any additional connections: %E. Active threads: %u",
6139                active_threads);
6140             write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6141                strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6142             close_socket(csp->cfd);
6143             csp->flags &= ~CSP_FLAG_ACTIVE;
6144          }
6145       }
6146       else
6147       {
6148          serve(csp);
6149       }
6150    }
6151
6152 #if defined(FEATURE_PTHREAD)
6153    pthread_attr_destroy(&attrs);
6154 #endif
6155
6156    /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
6157
6158 #ifdef FEATURE_HTTPS_INSPECTION
6159    /* Clean up.  Aim: free all memory (no leaks) */
6160    ssl_release();
6161 #endif
6162
6163 #ifdef FEATURE_GRACEFUL_TERMINATION
6164
6165    log_error(LOG_LEVEL_INFO, "Graceful termination requested");
6166
6167    unload_current_config_file();
6168    unload_current_actions_file();
6169    unload_current_re_filterfile();
6170 #ifdef FEATURE_TRUST
6171    unload_current_trust_file();
6172 #endif
6173
6174    if (config->multi_threaded)
6175    {
6176       int i = 60;
6177       do
6178       {
6179          sleep(1);
6180          sweep();
6181       } while ((clients->next != NULL) && (--i > 0));
6182
6183       if (i <= 0)
6184       {
6185          log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
6186       }
6187    }
6188    sweep();
6189    sweep();
6190
6191 #if defined(unix)
6192    freez(basedir);
6193 #endif
6194
6195 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
6196    /* Cleanup - remove taskbar icon etc. */
6197    TermLogWindow();
6198 #endif
6199
6200    exit(0);
6201 #endif /* FEATURE_GRACEFUL_TERMINATION */
6202
6203 }
6204
6205
6206 /*
6207   Local Variables:
6208   tab-width: 3
6209   end:
6210 */