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