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