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