get_block_reason_statistics_table(): Add new lines between table rows
[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 #ifdef FEATURE_EXTENDED_STATISTICS
208 privoxy_mutex_t filter_statistics_mutex;
209 privoxy_mutex_t block_statistics_mutex;
210 #endif
211
212 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
213 privoxy_mutex_t resolver_mutex;
214 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
215
216 #ifndef HAVE_GMTIME_R
217 privoxy_mutex_t gmtime_mutex;
218 #endif /* ndef HAVE_GMTIME_R */
219
220 #ifndef HAVE_LOCALTIME_R
221 privoxy_mutex_t localtime_mutex;
222 #endif /* ndef HAVE_GMTIME_R */
223
224 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
225 privoxy_mutex_t rand_mutex;
226 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
227
228 #endif /* def MUTEX_LOCKS_AVAILABLE */
229
230 #if defined(unix)
231 const char *basedir = NULL;
232 const char *pidfile = NULL;
233 static int received_hup_signal = 0;
234 #endif /* defined unix */
235
236 /* HTTP snipplets. */
237 static const char CSUCCEED[] =
238    "HTTP/1.1 200 Connection established\r\n\r\n";
239
240 static const char CHEADER[] =
241    "HTTP/1.1 400 Invalid header received from client\r\n"
242    "Content-Type: text/plain\r\n"
243    "Connection: close\r\n\r\n"
244    "Invalid header received from client.\r\n";
245
246 static const char FTP_RESPONSE[] =
247    "HTTP/1.1 400 Invalid request received from client\r\n"
248    "Content-Type: text/plain\r\n"
249    "Connection: close\r\n\r\n"
250    "Invalid request. Privoxy doesn't support FTP.\r\n";
251
252 static const char GOPHER_RESPONSE[] =
253    "HTTP/1.1 400 Invalid request received from client\r\n"
254    "Content-Type: text/plain\r\n"
255    "Connection: close\r\n\r\n"
256    "Invalid request. Privoxy doesn't support gopher.\r\n";
257
258 /* XXX: should be a template */
259 static const char MISSING_DESTINATION_RESPONSE[] =
260    "HTTP/1.1 400 Bad request received from client\r\n"
261    "Content-Type: text/plain\r\n"
262    "Connection: close\r\n\r\n"
263    "Bad request. Privoxy was unable to extract the destination.\r\n";
264
265 /* XXX: should be a template */
266 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
267    "HTTP/1.1 502 Server or forwarder response invalid\r\n"
268    "Content-Type: text/plain\r\n"
269    "Connection: close\r\n\r\n"
270    "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
271
272 /* XXX: should be a template */
273 static const char MESSED_UP_REQUEST_RESPONSE[] =
274    "HTTP/1.1 400 Malformed request after rewriting\r\n"
275    "Content-Type: text/plain\r\n"
276    "Connection: close\r\n\r\n"
277    "Bad request. Messed up with header filters.\r\n";
278
279 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
280    "HTTP/1.1 503 Too many open connections\r\n"
281    "Content-Type: text/plain\r\n"
282    "Connection: close\r\n\r\n"
283    "Maximum number of open connections reached.\r\n";
284
285 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
286    "HTTP/1.1 504 Connection timeout\r\n"
287    "Content-Type: text/plain\r\n"
288    "Connection: close\r\n\r\n"
289    "The connection timed out because the client request didn't arrive in time.\r\n";
290
291 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
292    "HTTP/1.1 400 Failed reading client body\r\n"
293    "Content-Type: text/plain\r\n"
294    "Connection: close\r\n\r\n"
295    "Failed parsing or buffering the chunk-encoded client body.\r\n";
296
297 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
298    "HTTP/1.1 417 Expecting too much\r\n"
299    "Content-Type: text/plain\r\n"
300    "Connection: close\r\n\r\n"
301    "Privoxy detected an unsupported Expect header value.\r\n";
302
303 /* A function to crunch a response */
304 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
305
306 /* Crunch function flags */
307 #define CF_NO_FLAGS        0
308 /* Cruncher applies to forced requests as well */
309 #define CF_IGNORE_FORCE    1
310 /* Crunched requests are counted for the block statistics */
311 #define CF_COUNT_AS_REJECT 2
312
313 /* A crunch function and its flags */
314 struct cruncher
315 {
316    const crunch_func_ptr cruncher;
317    const int flags;
318 };
319
320 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
321
322 /* Complete list of cruncher functions */
323 static const struct cruncher crunchers_all[] = {
324    { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
325    { block_url,       CF_COUNT_AS_REJECT },
326 #ifdef FEATURE_TRUST
327    { trust_url,       CF_COUNT_AS_REJECT },
328 #endif /* def FEATURE_TRUST */
329    { redirect_url,    CF_NO_FLAGS  },
330    { dispatch_cgi,    CF_IGNORE_FORCE},
331    { NULL,            0 }
332 };
333
334 /* Light version, used after tags are applied */
335 static const struct cruncher crunchers_light[] = {
336    { block_url,       CF_COUNT_AS_REJECT },
337    { redirect_url,    CF_NO_FLAGS },
338    { NULL,            0 }
339 };
340
341
342 /*
343  * XXX: Don't we really mean
344  *
345  * #if defined(unix)
346  *
347  * here?
348  */
349 #if !defined(_WIN32) && !defined(__OS2__)
350 /*********************************************************************
351  *
352  * Function    :  sig_handler
353  *
354  * Description :  Signal handler for different signals.
355  *                Exit gracefully on TERM and INT
356  *                or set a flag that will cause the errlog
357  *                to be reopened by the main thread on HUP.
358  *
359  * Parameters  :
360  *          1  :  the_signal = the signal cause this function to call
361  *
362  * Returns     :  -
363  *
364  *********************************************************************/
365 static void sig_handler(int the_signal)
366 {
367    switch(the_signal)
368    {
369       case SIGTERM:
370       case SIGINT:
371          log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
372 #if defined(unix)
373          if (pidfile)
374          {
375             unlink(pidfile);
376          }
377 #endif /* unix */
378          exit(the_signal);
379          break;
380
381       case SIGHUP:
382 #if defined(unix)
383          received_hup_signal = 1;
384 #endif
385          break;
386
387       default:
388          /*
389           * We shouldn't be here, unless we catch signals
390           * in main() that we can't handle here!
391           */
392          log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
393    }
394    return;
395
396 }
397 #endif
398
399
400 /*********************************************************************
401  *
402  * Function    :  get_write_delay
403  *
404  * Description :  Parse the delay-response parameter.
405  *
406  * Parameters  :
407  *          1  :  csp = Current client state (buffers, headers, etc...)
408  *
409  * Returns     :  Number of milliseconds to delay writes.
410  *
411  *********************************************************************/
412 static unsigned int get_write_delay(const struct client_state *csp)
413 {
414    unsigned int delay;
415    char *endptr;
416    char *newval;
417
418    if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
419    {
420       return 0;
421    }
422    newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
423
424    delay = (unsigned)strtol(newval, &endptr, 0);
425    if (*endptr != '\0')
426    {
427       log_error(LOG_LEVEL_FATAL,
428          "Invalid delay-response{} parameter: '%s'", newval);
429    }
430
431    return delay;
432
433 }
434
435
436 /*********************************************************************
437  *
438  * Function    :  client_protocol_is_unsupported
439  *
440  * Description :  Checks if the client used a known unsupported
441  *                protocol and deals with it by sending an error
442  *                response.
443  *
444  * Parameters  :
445  *          1  :  csp = Current client state (buffers, headers, etc...)
446  *          2  :  req = the first request line send by the client
447  *
448  * Returns     :  TRUE if an error response has been generated, or
449  *                FALSE if the request doesn't look invalid.
450  *
451  *********************************************************************/
452 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
453 {
454    /*
455     * If it's a FTP or gopher request, we don't support it.
456     *
457     * These checks are better than nothing, but they might
458     * not work in all configurations and some clients might
459     * have problems digesting the answer.
460     *
461     * They should, however, never cause more problems than
462     * Privoxy's old behaviour (returning the misleading HTML
463     * error message:
464     *
465     * "Could not resolve http://(ftp|gopher)://example.org").
466     */
467    if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
468    {
469       const char *response = NULL;
470       const char *protocol = NULL;
471
472       if (!strncmpic(req, "GET ftp://", 10))
473       {
474          response = FTP_RESPONSE;
475          protocol = "FTP";
476       }
477       else
478       {
479          response = GOPHER_RESPONSE;
480          protocol = "GOPHER";
481       }
482       log_error(LOG_LEVEL_ERROR,
483          "%s tried to use Privoxy as %s proxy: %s",
484          csp->ip_addr_str, protocol, req);
485       log_error(LOG_LEVEL_CLF,
486          "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
487       freez(req);
488
489 #ifdef FEATURE_HTTPS_INSPECTION
490       if (client_use_ssl(csp))
491       {
492          ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
493             (const unsigned char *)response, strlen(response),
494             get_write_delay(csp));
495       }
496       else
497 #endif
498       {
499          write_socket_delayed(csp->cfd, response, strlen(response),
500             get_write_delay(csp));
501       }
502
503       return TRUE;
504    }
505
506    return FALSE;
507 }
508
509
510 /*********************************************************************
511  *
512  * Function    :  client_has_unsupported_expectations
513  *
514  * Description :  Checks if the client used an unsupported expectation
515  *                in which case an error message is delivered.
516  *
517  * Parameters  :
518  *          1  :  csp = Current client state (buffers, headers, etc...)
519  *
520  * Returns     :  TRUE if an error response has been generated, or
521  *                FALSE if the request doesn't look invalid.
522  *
523  *********************************************************************/
524 static int client_has_unsupported_expectations(const struct client_state *csp)
525 {
526    if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
527    {
528       log_error(LOG_LEVEL_ERROR,
529          "Rejecting request from client %s with unsupported Expect header value",
530          csp->ip_addr_str);
531       log_error(LOG_LEVEL_CLF,
532          "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
533       write_socket_delayed(csp->cfd,
534          UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
535          strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
536          get_write_delay(csp));
537
538       return TRUE;
539    }
540
541    return FALSE;
542
543 }
544
545
546 /*********************************************************************
547  *
548  * Function    :  get_request_destination_elsewhere
549  *
550  * Description :  If the client's request was redirected into
551  *                Privoxy without the client's knowledge,
552  *                the request line lacks the destination host.
553  *
554  *                This function tries to get it elsewhere,
555  *                provided accept-intercepted-requests is enabled.
556  *
557  *                "Elsewhere" currently only means "Host: header",
558  *                but in the future we may ask the redirecting
559  *                packet filter to look the destination up.
560  *
561  *                If the destination stays unknown, an error
562  *                response is send to the client and headers
563  *                are freed so that chat() can return directly.
564  *
565  * Parameters  :
566  *          1  :  csp = Current client state (buffers, headers, etc...)
567  *          2  :  headers = a header list
568  *
569  * Returns     :  JB_ERR_OK if the destination is now known, or
570  *                JB_ERR_PARSE if it isn't.
571  *
572  *********************************************************************/
573 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
574 {
575    char *req;
576
577    if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
578    {
579       log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
580          " Privoxy isn't configured to accept intercepted requests.",
581          csp->ip_addr_str, csp->http->cmd);
582       /* XXX: Use correct size */
583       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
584          csp->ip_addr_str, csp->http->cmd);
585
586       write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
587          get_write_delay(csp));
588       destroy_list(headers);
589
590       return JB_ERR_PARSE;
591    }
592    else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
593    {
594       /* Split the domain we just got for pattern matching */
595       init_domain_components(csp->http);
596
597       return JB_ERR_OK;
598    }
599    else
600    {
601       /* We can't work without destination. Go spread the news.*/
602
603       req = list_to_text(headers);
604       chomp(req);
605       /* XXX: Use correct size */
606       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
607          csp->ip_addr_str, csp->http->cmd);
608       log_error(LOG_LEVEL_ERROR,
609          "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
610          csp->ip_addr_str, csp->http->cmd, req);
611       freez(req);
612
613       write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
614          strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
615       destroy_list(headers);
616
617       return JB_ERR_PARSE;
618    }
619    /*
620     * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
621     * to get the destination IP address, use it as host directly
622     * or do a reverse DNS lookup first.
623     */
624 }
625
626
627 /*********************************************************************
628  *
629  * Function    :  get_server_headers
630  *
631  * Description :  Parses server headers in iob and fills them
632  *                into csp->headers so that they can later be
633  *                handled by sed().
634  *
635  * Parameters  :
636  *          1  :  csp = Current client state (buffers, headers, etc...)
637  *
638  * Returns     :  JB_ERR_OK if everything went fine, or
639  *                JB_ERR_PARSE if the headers were incomplete.
640  *
641  *********************************************************************/
642 static jb_err get_server_headers(struct client_state *csp)
643 {
644    int continue_hack_in_da_house = 0;
645    char * header;
646
647    while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
648    {
649       if (header == NULL)
650       {
651          /*
652           * continue hack in da house. Ignore the ending of
653           * this head and continue enlisting header lines.
654           * The reason is described below.
655           */
656          enlist(csp->headers, "");
657          continue_hack_in_da_house = 0;
658          continue;
659       }
660       else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
661       {
662          /*
663           * It's a bodyless continue response, don't
664           * stop header parsing after reaching its end.
665           *
666           * As a result Privoxy will concatenate the
667           * next response's head and parse and deliver
668           * the headers as if they belonged to one request.
669           *
670           * The client will separate them because of the
671           * empty line between them.
672           *
673           * XXX: What we're doing here is clearly against
674           * the intended purpose of the continue header,
675           * and under some conditions (HTTP/1.0 client request)
676           * it's a standard violation.
677           *
678           * Anyway, "sort of against the spec" is preferable
679           * to "always getting confused by Continue responses"
680           * (Privoxy's behaviour before this hack was added)
681           */
682          log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
683          continue_hack_in_da_house = 1;
684       }
685       else if (*header == '\0')
686       {
687          /*
688           * If the header is empty, but the Continue hack
689           * isn't active, we can assume that we reached the
690           * end of the buffer before we hit the end of the
691           * head.
692           *
693           * Inform the caller an let it decide how to handle it.
694           */
695          return JB_ERR_PARSE;
696       }
697
698       if (JB_ERR_MEMORY == enlist(csp->headers, header))
699       {
700          /*
701           * XXX: Should we quit the request and return a
702           * out of memory error page instead?
703           */
704          log_error(LOG_LEVEL_ERROR,
705             "Out of memory while enlisting server headers. %s lost.",
706             header);
707       }
708       freez(header);
709    }
710
711    return JB_ERR_OK;
712 }
713
714
715 /*********************************************************************
716  *
717  * Function    :  crunch_reason
718  *
719  * Description :  Translates the crunch reason code into a string.
720  *
721  * Parameters  :
722  *          1  :  rsp = a http_response
723  *
724  * Returns     :  A string with the crunch reason or an error description.
725  *
726  *********************************************************************/
727 static const char *crunch_reason(const struct http_response *rsp)
728 {
729    char * reason = NULL;
730
731    assert(rsp != NULL);
732    if (rsp == NULL)
733    {
734       return "Internal error while searching for crunch reason";
735    }
736
737    switch (rsp->crunch_reason)
738    {
739       case UNSUPPORTED:
740          reason = "Unsupported HTTP feature";
741          break;
742       case BLOCKED:
743          reason = "Blocked";
744          break;
745       case UNTRUSTED:
746          reason = "Untrusted";
747          break;
748       case REDIRECTED:
749          reason = "Redirected";
750          break;
751       case CGI_CALL:
752          reason = "CGI Call";
753          break;
754       case NO_SUCH_DOMAIN:
755          reason = "DNS failure";
756          break;
757       case FORWARDING_FAILED:
758          reason = "Forwarding failed";
759          break;
760       case CONNECT_FAILED:
761          reason = "Connection failure";
762          break;
763       case OUT_OF_MEMORY:
764          reason = "Out of memory (may mask other reasons)";
765          break;
766       case CONNECTION_TIMEOUT:
767          reason = "Connection timeout";
768          break;
769       case NO_SERVER_DATA:
770          reason = "No server data received";
771          break;
772       default:
773          reason = "No reason recorded";
774          break;
775    }
776
777    return reason;
778 }
779
780
781 /*********************************************************************
782  *
783  * Function    :  log_applied_actions
784  *
785  * Description :  Logs the applied actions if LOG_LEVEL_ACTIONS is
786  *                enabled.
787  *
788  * Parameters  :
789  *          1  :  actions = Current action spec to log
790  *
791  * Returns     :  Nothing.
792  *
793  *********************************************************************/
794 static void log_applied_actions(const struct current_action_spec *actions)
795 {
796    /*
797     * The conversion to text requires lots of memory allocations so
798     * we only do the conversion if the user is actually interested.
799     */
800    if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
801    {
802       char *actions_as_text = actions_to_line_of_text(actions);
803       log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
804       freez(actions_as_text);
805    }
806 }
807
808
809 /*********************************************************************
810  *
811  * Function    :  send_crunch_response
812  *
813  * Description :  Delivers already prepared response for
814  *                intercepted requests, logs the interception
815  *                and frees the response.
816  *
817  * Parameters  :
818  *          1  :  csp = Current client state (buffers, headers, etc...)
819  *          2  :  rsp = Fully prepared response. Will be freed on exit.
820  *
821  * Returns     :  Nothing.
822  *
823  *********************************************************************/
824 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
825 {
826       const struct http_request *http = csp->http;
827       char status_code[4];
828
829       assert(rsp != NULL);
830       assert(rsp->head != NULL);
831
832       if (rsp == NULL)
833       {
834          log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
835       }
836
837       /*
838        * Extract the status code from the actual head
839        * that will be send to the client. It is the only
840        * way to get it right for all requests, including
841        * the fixed ones for out-of-memory problems.
842        *
843        * A head starts like this: 'HTTP/1.1 200...'
844        *                           0123456789|11
845        *                                     10
846        */
847       status_code[0] = rsp->head[9];
848       status_code[1] = rsp->head[10];
849       status_code[2] = rsp->head[11];
850       status_code[3] = '\0';
851
852       /* Log that the request was crunched and why. */
853       log_applied_actions(csp->action);
854 #ifdef FEATURE_HTTPS_INSPECTION
855       if (client_use_ssl(csp))
856       {
857          log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
858             http->hostport, http->path);
859          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %llu",
860             csp->ip_addr_str, http->gpc, http->hostport, http->path,
861             http->version, status_code, rsp->content_length);
862       }
863       else
864 #endif
865       {
866          log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
867          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
868             csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
869       }
870       /* Write the answer to the client */
871 #ifdef FEATURE_HTTPS_INSPECTION
872       if (client_use_ssl(csp))
873       {
874          if ((ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
875                 (const unsigned char *)rsp->head, rsp->head_length,
876                 get_write_delay(csp)) < 0)
877           || (ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
878                 (const unsigned char *)rsp->body, rsp->content_length,
879                 get_write_delay(csp)) < 0))
880          {
881             /* There is nothing we can do about it. */
882             log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
883                "for %s through client socket %d using TLS/SSL",
884                http->url, csp->cfd);
885          }
886       }
887       else
888 #endif
889       {
890          if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
891                 get_write_delay(csp))
892           || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
893                 get_write_delay(csp)))
894          {
895             /* There is nothing we can do about it. */
896             log_error(LOG_LEVEL_CONNECT,
897                "Couldn't deliver the error message for %s through client socket %d: %E",
898                http->url, csp->cfd);
899          }
900       }
901
902       /* Clean up and return */
903       if (cgi_error_memory() != rsp)
904       {
905          free_http_response(rsp);
906       }
907       return;
908 }
909
910
911 /*********************************************************************
912  *
913  * Function    :  crunch_response_triggered
914  *
915  * Description :  Checks if the request has to be crunched,
916  *                and delivers the crunch response if necessary.
917  *
918  * Parameters  :
919  *          1  :  csp = Current client state (buffers, headers, etc...)
920  *          2  :  crunchers = list of cruncher functions to run
921  *
922  * Returns     :  TRUE if the request was answered with a crunch response
923  *                FALSE otherwise.
924  *
925  *********************************************************************/
926 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
927 {
928    struct http_response *rsp = NULL;
929    const struct cruncher *c;
930
931    /*
932     * If CGI request crunching is disabled,
933     * check the CGI dispatcher out of order to
934     * prevent unintentional blocks or redirects.
935     */
936    if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
937        && (NULL != (rsp = dispatch_cgi(csp))))
938    {
939       /* Deliver, log and free the interception response. */
940       send_crunch_response(csp, rsp);
941       csp->flags |= CSP_FLAG_CRUNCHED;
942       return TRUE;
943    }
944
945    for (c = crunchers; c->cruncher != NULL; c++)
946    {
947       /*
948        * Check the cruncher if either Privoxy is toggled
949        * on and the request isn't forced, or if the cruncher
950        * applies to forced requests as well.
951        */
952       if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
953           !(csp->flags & CSP_FLAG_FORCED)) ||
954           (c->flags & CF_IGNORE_FORCE))
955       {
956          rsp = c->cruncher(csp);
957          if (NULL != rsp)
958          {
959             /* Deliver, log and free the interception response. */
960             send_crunch_response(csp, rsp);
961             csp->flags |= CSP_FLAG_CRUNCHED;
962 #ifdef FEATURE_STATISTICS
963             if (c->flags & CF_COUNT_AS_REJECT)
964             {
965                csp->flags |= CSP_FLAG_REJECTED;
966             }
967 #endif /* def FEATURE_STATISTICS */
968
969             return TRUE;
970          }
971       }
972    }
973
974    return FALSE;
975 }
976
977
978 /*********************************************************************
979  *
980  * Function    :  build_request_line
981  *
982  * Description :  Builds the HTTP request line.
983  *
984  *                If a HTTP forwarder is used it expects the whole URL,
985  *                web servers only get the path.
986  *
987  * Parameters  :
988  *          1  :  csp = Current client state (buffers, headers, etc...)
989  *          2  :  fwd = The forwarding spec used for the request
990  *                XXX: Should use http->fwd instead.
991  *          3  :  request_line = The old request line which will be replaced.
992  *
993  * Returns     :  Nothing. Terminates in case of memory problems.
994  *
995  *********************************************************************/
996 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
997 {
998    struct http_request *http = csp->http;
999
1000    /*
1001     * Downgrade http version from 1.1 to 1.0
1002     * if +downgrade action applies.
1003     */
1004    if ((csp->action->flags & ACTION_DOWNGRADE)
1005      && (!strcmpic(http->version, "HTTP/1.1")))
1006    {
1007       freez(http->version);
1008       http->version = strdup_or_die("HTTP/1.0");
1009    }
1010
1011    /*
1012     * Rebuild the request line.
1013     */
1014    freez(*request_line);
1015    *request_line = strdup(http->gpc);
1016    string_append(request_line, " ");
1017
1018    if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1019    {
1020       string_append(request_line, http->url);
1021    }
1022    else
1023    {
1024       string_append(request_line, http->path);
1025    }
1026    string_append(request_line, " ");
1027    string_append(request_line, http->version);
1028
1029    if (*request_line == NULL)
1030    {
1031       log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1032    }
1033    log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1034 }
1035
1036
1037 /*********************************************************************
1038  *
1039  * Function    :  change_request_destination
1040  *
1041  * Description :  Parse a (rewritten) request line and regenerate
1042  *                the http request data.
1043  *
1044  * Parameters  :
1045  *          1  :  csp = Current client state (buffers, headers, etc...)
1046  *
1047  * Returns     :  Forwards the parse_http_request() return code.
1048  *                Terminates in case of memory problems.
1049  *
1050  *********************************************************************/
1051 static jb_err change_request_destination(struct client_state *csp)
1052 {
1053    struct http_request *http = csp->http;
1054    jb_err err;
1055
1056    log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1057       csp->headers->first->str);
1058    free_http_request(http);
1059    err = parse_http_request(csp->headers->first->str, http);
1060    if (JB_ERR_OK != err)
1061    {
1062       log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1063          jb_err_to_string(err));
1064    }
1065
1066    return err;
1067 }
1068
1069
1070 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1071 /*********************************************************************
1072  *
1073  * Function    :  server_response_is_complete
1074  *
1075  * Description :  Determines whether we should stop reading
1076  *                from the server socket.
1077  *
1078  * Parameters  :
1079  *          1  :  csp = Current client state (buffers, headers, etc...)
1080  *          2  :  content_length = Length of content received so far.
1081  *
1082  * Returns     :  TRUE if the response is complete,
1083  *                FALSE otherwise.
1084  *
1085  *********************************************************************/
1086 static int server_response_is_complete(struct client_state *csp,
1087    unsigned long long content_length)
1088 {
1089    int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1090
1091    if (!strcmpic(csp->http->gpc, "HEAD"))
1092    {
1093       /*
1094        * "HEAD" implies no body, we are thus expecting
1095        * no content. XXX: incomplete "list" of methods?
1096        */
1097       csp->expected_content_length = 0;
1098       content_length_known = TRUE;
1099       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1100    }
1101
1102    if (csp->http->status == 204 || csp->http->status == 304)
1103    {
1104       /*
1105        * Expect no body. XXX: incomplete "list" of status codes?
1106        */
1107       csp->expected_content_length = 0;
1108       content_length_known = TRUE;
1109       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1110    }
1111
1112    return (content_length_known && ((0 == csp->expected_content_length)
1113             || (csp->expected_content_length <= content_length)));
1114 }
1115
1116
1117 #ifdef FEATURE_CONNECTION_SHARING
1118 /*********************************************************************
1119  *
1120  * Function    :  wait_for_alive_connections
1121  *
1122  * Description :  Waits for alive connections to timeout.
1123  *
1124  * Parameters  :  N/A
1125  *
1126  * Returns     :  N/A
1127  *
1128  *********************************************************************/
1129 static void wait_for_alive_connections(void)
1130 {
1131    int connections_alive = close_unusable_connections();
1132
1133    while (0 < connections_alive)
1134    {
1135       log_error(LOG_LEVEL_CONNECT,
1136          "Waiting for %d connections to timeout.",
1137          connections_alive);
1138       sleep(60);
1139       connections_alive = close_unusable_connections();
1140    }
1141
1142    log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1143
1144 }
1145 #endif /* def FEATURE_CONNECTION_SHARING */
1146
1147
1148 /*********************************************************************
1149  *
1150  * Function    :  save_connection_destination
1151  *
1152  * Description :  Remembers a connection for reuse later on.
1153  *
1154  * Parameters  :
1155  *          1  :  sfd  = Open socket to remember.
1156  *          2  :  http = The destination for the connection.
1157  *          3  :  fwd  = The forwarder settings used.
1158  *          4  :  server_connection  = storage.
1159  *
1160  * Returns     : void
1161  *
1162  *********************************************************************/
1163 void save_connection_destination(jb_socket sfd,
1164                                  const struct http_request *http,
1165                                  const struct forward_spec *fwd,
1166                                  struct reusable_connection *server_connection)
1167 {
1168    assert(sfd != JB_INVALID_SOCKET);
1169    assert(NULL != http->host);
1170
1171    server_connection->sfd = sfd;
1172    server_connection->host = strdup_or_die(http->host);
1173    server_connection->port = http->port;
1174
1175    assert(NULL != fwd);
1176    assert(server_connection->gateway_host == NULL);
1177    assert(server_connection->gateway_port == 0);
1178    assert(server_connection->forwarder_type == 0);
1179    assert(server_connection->forward_host == NULL);
1180    assert(server_connection->forward_port == 0);
1181
1182    server_connection->forwarder_type = fwd->type;
1183    if (NULL != fwd->gateway_host)
1184    {
1185       server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1186    }
1187    else
1188    {
1189       server_connection->gateway_host = NULL;
1190    }
1191    server_connection->gateway_port = fwd->gateway_port;
1192
1193    if (NULL != fwd->forward_host)
1194    {
1195       server_connection->forward_host = strdup_or_die(fwd->forward_host);
1196    }
1197    else
1198    {
1199       server_connection->forward_host = NULL;
1200    }
1201    server_connection->forward_port = fwd->forward_port;
1202 }
1203
1204
1205 /*********************************************************************
1206  *
1207  * Function    : verify_request_length
1208  *
1209  * Description : Checks if we already got the whole client requests
1210  *               and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1211  *               we do.
1212  *
1213  *               Data that doesn't belong to the current request is
1214  *               either thrown away to let the client retry on a clean
1215  *               socket, or stashed to be dealt with after the current
1216  *               request is served.
1217  *
1218  * Parameters  :
1219  *          1  :  csp = Current client state (buffers, headers, etc...)
1220  *
1221  * Returns     :  void
1222  *
1223  *********************************************************************/
1224 static void verify_request_length(struct client_state *csp)
1225 {
1226    unsigned long long buffered_request_bytes =
1227       (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1228
1229    if ((csp->expected_client_content_length != 0)
1230       && (buffered_request_bytes != 0))
1231    {
1232       if (csp->expected_client_content_length >= buffered_request_bytes)
1233       {
1234          csp->expected_client_content_length -= buffered_request_bytes;
1235          log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1236             "to account for the %llu ones we already got.",
1237             csp->expected_client_content_length, buffered_request_bytes);
1238       }
1239       else
1240       {
1241          assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1242          csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1243          log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1244             "Marking the server socket tainted after throwing %llu bytes away.",
1245             buffered_request_bytes - csp->expected_client_content_length);
1246          csp->expected_client_content_length = 0;
1247          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1248       }
1249
1250       if (csp->expected_client_content_length == 0)
1251       {
1252          csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1253       }
1254    }
1255
1256    if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1257       && ((csp->client_iob->cur < csp->client_iob->eod)
1258          || (csp->expected_client_content_length != 0)))
1259    {
1260       if (strcmpic(csp->http->gpc, "GET")
1261          && strcmpic(csp->http->gpc, "HEAD")
1262          && strcmpic(csp->http->gpc, "TRACE")
1263          && strcmpic(csp->http->gpc, "OPTIONS")
1264          && strcmpic(csp->http->gpc, "DELETE"))
1265       {
1266          /* XXX: this is an incomplete hack */
1267          csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1268          log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1269       }
1270       else
1271       {
1272          csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1273
1274          if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1275          {
1276             csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1277             log_error(LOG_LEVEL_CONNECT,
1278                "Possible pipeline attempt detected. The connection will not "
1279                "be kept alive and we will only serve the first request.");
1280             /* Nuke the pipelined requests from orbit, just to be sure. */
1281             clear_iob(csp->client_iob);
1282          }
1283          else
1284          {
1285             /*
1286              * Keep the pipelined data around for now, we'll deal with
1287              * it once we're done serving the current request.
1288              */
1289             csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1290             assert(csp->client_iob->eod >= csp->client_iob->cur);
1291             log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1292                "%d bytes of pipelined data received.",
1293                (int)(csp->client_iob->eod - csp->client_iob->cur));
1294          }
1295       }
1296    }
1297    else
1298    {
1299       csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1300       log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1301    }
1302 }
1303 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1304
1305
1306 /*********************************************************************
1307  *
1308  * Function    :  mark_server_socket_tainted
1309  *
1310  * Description :  Makes sure we don't reuse a server socket
1311  *                (if we didn't read everything the server sent
1312  *                us reusing the socket would lead to garbage).
1313  *
1314  * Parameters  :
1315  *          1  :  csp = Current client state (buffers, headers, etc...)
1316  *
1317  * Returns     :  void.
1318  *
1319  *********************************************************************/
1320 static void mark_server_socket_tainted(struct client_state *csp)
1321 {
1322    /*
1323     * For consistency we always mark the server socket
1324     * tainted, however, to reduce the log noise we only
1325     * emit a log message if the server socket could have
1326     * actually been reused.
1327     */
1328    if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1329       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1330    {
1331       log_error(LOG_LEVEL_CONNECT,
1332          "Marking the server socket %d tainted.",
1333          csp->server_connection.sfd);
1334    }
1335    csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1336 }
1337
1338 /*********************************************************************
1339  *
1340  * Function    :  get_request_line
1341  *
1342  * Description : Read the client request line.
1343  *
1344  * Parameters  :
1345  *          1  :  csp = Current client state (buffers, headers, etc...)
1346  *
1347  * Returns     :  Pointer to request line or NULL in case of errors.
1348  *
1349  *********************************************************************/
1350 static char *get_request_line(struct client_state *csp)
1351 {
1352    char buf[BUFFER_SIZE];
1353    char *request_line = NULL;
1354    int len;
1355
1356    memset(buf, 0, sizeof(buf));
1357
1358    if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1359    {
1360       /*
1361        * If there are multiple pipelined requests waiting,
1362        * the flag will be set again once the next request
1363        * has been parsed.
1364        */
1365       csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1366
1367       request_line = get_header(csp->client_iob);
1368       if ((NULL != request_line) && ('\0' != *request_line))
1369       {
1370          return request_line;
1371       }
1372       else
1373       {
1374          log_error(LOG_LEVEL_CONNECT, "No complete request line "
1375             "received yet. Continuing reading from %d.", csp->cfd);
1376       }
1377    }
1378
1379    do
1380    {
1381       if (
1382 #ifdef FUZZ
1383           0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1384 #endif
1385           !data_is_available(csp->cfd, csp->config->socket_timeout)
1386           )
1387       {
1388          if (socket_is_still_alive(csp->cfd))
1389          {
1390             log_error(LOG_LEVEL_CONNECT,
1391                "No request line on socket %d received in time. Timeout: %d.",
1392                csp->cfd, csp->config->socket_timeout);
1393             write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1394                strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1395                get_write_delay(csp));
1396          }
1397          else
1398          {
1399             log_error(LOG_LEVEL_CONNECT,
1400                "The client side of the connection on socket %d got "
1401                "closed without sending a complete request line.", csp->cfd);
1402          }
1403          return NULL;
1404       }
1405
1406       len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1407
1408       if (len <= 0) return NULL;
1409
1410       /*
1411        * If there is no memory left for buffering the
1412        * request, there is nothing we can do but hang up
1413        */
1414       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1415       {
1416          return NULL;
1417       }
1418
1419       request_line = get_header(csp->client_iob);
1420
1421    } while ((NULL != request_line) && ('\0' == *request_line));
1422
1423    return request_line;
1424
1425 }
1426
1427 enum chunk_status
1428 {
1429    CHUNK_STATUS_MISSING_DATA,
1430    CHUNK_STATUS_BODY_COMPLETE,
1431    CHUNK_STATUS_PARSE_ERROR
1432 };
1433
1434
1435 /*********************************************************************
1436  *
1437  * Function    :  chunked_body_is_complete
1438  *
1439  * Description :  Figures out whether or not a chunked body is complete.
1440  *
1441  *                Currently it always starts at the beginning of the
1442  *                buffer which is somewhat wasteful and prevents Privoxy
1443  *                from starting to forward the correctly parsed chunks
1444  *                as soon as theoretically possible.
1445  *
1446  *                Should be modified to work with a common buffer,
1447  *                and allow the caller to skip already parsed chunks.
1448  *
1449  *                This would allow the function to be used for unbuffered
1450  *                response bodies as well.
1451  *
1452  * Parameters  :
1453  *          1  :  iob = Buffer with the body to check.
1454  *          2  :  length = Length of complete body
1455  *
1456  * Returns     :  Enum with the result of the check.
1457  *
1458  *********************************************************************/
1459 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1460 {
1461    unsigned int chunksize;
1462    char *p = iob->cur;
1463
1464    do
1465    {
1466       /*
1467        * We need at least a single digit, followed by "\r\n",
1468        * followed by an unknown amount of data, followed by "\r\n".
1469        */
1470       if (p + 5 > iob->eod)
1471       {
1472          return CHUNK_STATUS_MISSING_DATA;
1473       }
1474       if (sscanf(p, "%x", &chunksize) != 1)
1475       {
1476          return CHUNK_STATUS_PARSE_ERROR;
1477       }
1478
1479       /*
1480        * We want at least a single digit, followed by "\r\n",
1481        * followed by the specified amount of data, followed by "\r\n".
1482        */
1483       if (p + chunksize + 5 > iob->eod)
1484       {
1485          return CHUNK_STATUS_MISSING_DATA;
1486       }
1487
1488       /* Skip chunk-size. */
1489       p = strstr(p, "\r\n");
1490       if (NULL == p)
1491       {
1492          return CHUNK_STATUS_PARSE_ERROR;
1493       }
1494       /* Move beyond the chunkdata. */
1495       p += 2 + chunksize;
1496
1497       /* There should be another "\r\n" to skip */
1498       if (memcmp(p, "\r\n", 2))
1499       {
1500          return CHUNK_STATUS_PARSE_ERROR;
1501       }
1502       p += 2;
1503    } while (chunksize > 0U);
1504
1505    *length = (size_t)(p - iob->cur);
1506    assert(*length <= (size_t)(iob->eod - iob->cur));
1507    assert(p <= iob->eod);
1508
1509    return CHUNK_STATUS_BODY_COMPLETE;
1510
1511 }
1512
1513
1514 /*********************************************************************
1515  *
1516  * Function    : receive_chunked_client_request_body
1517  *
1518  * Description : Read the chunk-encoded client request body.
1519  *               Failures are dealt with.
1520  *
1521  * Parameters  :
1522  *          1  :  csp = Current client state (buffers, headers, etc...)
1523  *
1524  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1525  *
1526  *********************************************************************/
1527 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1528 {
1529    size_t body_length;
1530    enum chunk_status status;
1531
1532    while (CHUNK_STATUS_MISSING_DATA ==
1533       (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1534    {
1535       char buf[BUFFER_SIZE];
1536       int len;
1537
1538       if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1539       {
1540          log_error(LOG_LEVEL_ERROR,
1541             "Timeout while waiting for the client body.");
1542          break;
1543       }
1544       len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1545       if (len <= 0)
1546       {
1547          log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1548          break;
1549       }
1550       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1551       {
1552          break;
1553       }
1554    }
1555    if (status != CHUNK_STATUS_BODY_COMPLETE)
1556    {
1557       write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1558          strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1559       log_error(LOG_LEVEL_CLF,
1560          "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1561       return JB_ERR_PARSE;
1562    }
1563    log_error(LOG_LEVEL_CONNECT,
1564       "Chunked client body completely read. Length: %d", body_length);
1565    csp->expected_client_content_length = body_length;
1566
1567    return JB_ERR_OK;
1568
1569 }
1570
1571
1572 #ifdef FUZZ
1573 /*********************************************************************
1574  *
1575  * Function    :  fuzz_chunked_transfer_encoding
1576  *
1577  * Description :  Treat the fuzzed input as chunked transfer encoding
1578  *                to check and dechunk.
1579  *
1580  * Parameters  :
1581  *          1  :  csp      = Used to store the data.
1582  *          2  :  fuzz_input_file = File to read the input from.
1583  *
1584  * Returns     : Result of dechunking
1585  *
1586  *********************************************************************/
1587 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1588 {
1589    size_t length;
1590    size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1591    enum chunk_status status;
1592
1593    status = chunked_body_is_complete(csp->iob, &length);
1594    if (CHUNK_STATUS_BODY_COMPLETE != status)
1595    {
1596       log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1597    }
1598
1599    return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1600
1601 }
1602
1603
1604 /*********************************************************************
1605  *
1606  * Function    : fuzz_client_request
1607  *
1608  * Description : Try to get a client request from the fuzzed input.
1609  *
1610  * Parameters  :
1611  *          1  :  csp = Current client state (buffers, headers, etc...)
1612  *          2  :  fuzz_input_file = File to read the input from.
1613  *
1614  * Returns     :  Result of fuzzing.
1615  *
1616  *********************************************************************/
1617 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1618 {
1619    jb_err err;
1620
1621    csp->cfd = 0;
1622    csp->ip_addr_str = "fuzzer";
1623
1624    if (strcmp(fuzz_input_file, "-") != 0)
1625    {
1626       log_error(LOG_LEVEL_FATAL,
1627          "Fuzzed client requests can currently only be read from stdin (-).");
1628    }
1629    err = receive_client_request(csp);
1630    if (err != JB_ERR_OK)
1631    {
1632       return 1;
1633    }
1634    err = parse_client_request(csp);
1635    if (err != JB_ERR_OK)
1636    {
1637       return 1;
1638    }
1639
1640    return 0;
1641
1642 }
1643 #endif  /* def FUZZ */
1644
1645
1646 #ifdef FEATURE_FORCE_LOAD
1647 /*********************************************************************
1648  *
1649  * Function    :  force_required
1650  *
1651  * Description : Checks a request line to see if it contains
1652  *               the FORCE_PREFIX. If it does, it is removed
1653  *               unless enforcing requests has beend disabled.
1654  *
1655  * Parameters  :
1656  *          1  :  request_line = HTTP request line
1657  *
1658  * Returns     :  TRUE if force is required, FALSE otherwise.
1659  *
1660  *********************************************************************/
1661 static int force_required(const struct client_state *csp, char *request_line)
1662 {
1663    char *p;
1664
1665    p = strstr(request_line, "http://");
1666    if (p != NULL)
1667    {
1668       /* Skip protocol */
1669       p += strlen("http://");
1670    }
1671    else
1672    {
1673       /* Intercepted request usually don't specify the protocol. */
1674       p = request_line;
1675    }
1676
1677    /* Go to the beginning of the path */
1678    p = strstr(p, "/");
1679    if (p == NULL)
1680    {
1681       /*
1682        * If the path is missing the request line is invalid and we
1683        * are done here. The client-visible rejection happens later on.
1684        */
1685       return 0;
1686    }
1687
1688    if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1689    {
1690       if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1691       {
1692          /* XXX: Should clean more carefully */
1693          strclean(request_line, FORCE_PREFIX);
1694          log_error(LOG_LEVEL_FORCE,
1695             "Enforcing request: \"%s\".", request_line);
1696
1697          return 1;
1698       }
1699       log_error(LOG_LEVEL_FORCE,
1700          "Ignored force prefix in request: \"%s\".", request_line);
1701    }
1702
1703    return 0;
1704
1705 }
1706 #endif /* def FEATURE_FORCE_LOAD */
1707
1708
1709 /*********************************************************************
1710  *
1711  * Function    :  receive_client_request
1712  *
1713  * Description : Read the client's request (more precisely the
1714  *               client headers) and answer it if necessary.
1715  *
1716  * Parameters  :
1717  *          1  :  csp = Current client state (buffers, headers, etc...)
1718  *
1719  * Returns     :  JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1720  *
1721  *********************************************************************/
1722 static jb_err receive_client_request(struct client_state *csp)
1723 {
1724    char buf[BUFFER_SIZE];
1725    char *p;
1726    char *req = NULL;
1727    struct http_request *http;
1728    int len;
1729    jb_err err;
1730
1731    /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1732    struct list header_list;
1733    struct list *headers = &header_list;
1734
1735    /* We don't care if the arriving data is a valid HTTP request or not. */
1736    csp->requests_received_total++;
1737
1738    http = csp->http;
1739
1740    memset(buf, 0, sizeof(buf));
1741
1742    req = get_request_line(csp);
1743    if (req == NULL)
1744    {
1745       mark_server_socket_tainted(csp);
1746       return JB_ERR_PARSE;
1747    }
1748    assert(*req != '\0');
1749
1750    if (client_protocol_is_unsupported(csp, req))
1751    {
1752       return JB_ERR_PARSE;
1753    }
1754
1755 #ifdef FEATURE_FORCE_LOAD
1756    if (force_required(csp, req))
1757    {
1758       csp->flags |= CSP_FLAG_FORCED;
1759    }
1760 #endif /* def FEATURE_FORCE_LOAD */
1761
1762    err = parse_http_request(req, http);
1763    freez(req);
1764    if (JB_ERR_OK != err)
1765    {
1766       write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1767          get_write_delay(csp));
1768       /* XXX: Use correct size */
1769       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1770       log_error(LOG_LEVEL_ERROR,
1771          "Couldn't parse request line received from %s: %s",
1772          csp->ip_addr_str, jb_err_to_string(err));
1773
1774       free_http_request(http);
1775       return JB_ERR_PARSE;
1776    }
1777
1778    /* grab the rest of the client's headers */
1779    init_list(headers);
1780    for (;;)
1781    {
1782       p = get_header(csp->client_iob);
1783
1784       if (p == NULL)
1785       {
1786          /* There are no additional headers to read. */
1787          break;
1788       }
1789
1790       if (*p == '\0')
1791       {
1792          /*
1793           * We didn't receive a complete header
1794           * line yet, get the rest of it.
1795           */
1796          if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1797          {
1798             log_error(LOG_LEVEL_ERROR,
1799                "Stopped grabbing the client headers.");
1800             destroy_list(headers);
1801             return JB_ERR_PARSE;
1802          }
1803
1804          len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1805          if (len <= 0)
1806          {
1807             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1808             destroy_list(headers);
1809             return JB_ERR_PARSE;
1810          }
1811
1812          if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1813          {
1814             /*
1815              * If there is no memory left for buffering the
1816              * request, there is nothing we can do but hang up
1817              */
1818             destroy_list(headers);
1819             return JB_ERR_MEMORY;
1820          }
1821       }
1822       else
1823       {
1824          if (!strncmpic(p, "Transfer-Encoding:", 18))
1825          {
1826             /*
1827              * XXX: should be called through sed()
1828              *      but currently can't.
1829              */
1830             client_transfer_encoding(csp, &p);
1831          }
1832          /*
1833           * We were able to read a complete
1834           * header and can finally enlist it.
1835           */
1836          enlist(headers, p);
1837          freez(p);
1838       }
1839    }
1840
1841    if (http->host == NULL)
1842    {
1843       /*
1844        * If we still don't know the request destination,
1845        * the request is invalid or the client uses
1846        * Privoxy without its knowledge.
1847        */
1848       if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1849       {
1850          /*
1851           * Our attempts to get the request destination
1852           * elsewhere failed or Privoxy is configured
1853           * to only accept proxy requests.
1854           *
1855           * An error response has already been send
1856           * and we're done here.
1857           */
1858          return JB_ERR_PARSE;
1859       }
1860    }
1861
1862 #ifdef FEATURE_CLIENT_TAGS
1863    /* XXX: If the headers were enlisted sooner, passing csp would do. */
1864    set_client_address(csp, headers);
1865    get_tag_list_for_client(csp->client_tags, csp->client_address);
1866 #endif
1867
1868    /*
1869     * Determine the actions for this URL
1870     */
1871 #ifdef FEATURE_TOGGLE
1872    if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1873    {
1874       /* Most compatible set of actions (i.e. none) */
1875       init_current_action(csp->action);
1876    }
1877    else
1878 #endif /* ndef FEATURE_TOGGLE */
1879    {
1880       get_url_actions(csp, http);
1881    }
1882
1883    enlist(csp->headers, http->cmd);
1884
1885    /* Append the previously read headers */
1886    err = list_append_list_unique(csp->headers, headers);
1887    destroy_list(headers);
1888
1889    return err;
1890
1891 }
1892
1893
1894 /*********************************************************************
1895  *
1896  * Function    : parse_client_request
1897  *
1898  * Description : Parses the client's request and decides what to do
1899  *               with it.
1900  *
1901  *               Note that since we're not using select() we could get
1902  *               blocked here if a client connected, then didn't say
1903  *               anything!
1904  *
1905  * Parameters  :
1906  *          1  :  csp = Current client state (buffers, headers, etc...)
1907  *
1908  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1909  *
1910  *********************************************************************/
1911 static jb_err parse_client_request(struct client_state *csp)
1912 {
1913    struct http_request *http = csp->http;
1914    jb_err err;
1915
1916 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1917    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1918     && (!strcmpic(csp->http->version, "HTTP/1.1"))
1919     && (csp->http->ssl == 0))
1920    {
1921       /* Assume persistence until further notice */
1922       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1923    }
1924
1925    if (csp->http->ssl == 0)
1926    {
1927       /*
1928        * This whole block belongs to chat() but currently
1929        * has to be executed before sed().
1930        */
1931       if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1932       {
1933          if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1934          {
1935             return JB_ERR_PARSE;
1936          }
1937       }
1938       else
1939       {
1940          csp->expected_client_content_length = get_expected_content_length(csp->headers);
1941       }
1942       verify_request_length(csp);
1943    }
1944    else
1945    {
1946       csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1947    }
1948 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1949
1950    err = sed(csp, FILTER_CLIENT_HEADERS);
1951    if (JB_ERR_OK != err)
1952    {
1953       log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1954          csp->ip_addr_str);
1955       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1956          csp->ip_addr_str, csp->http->cmd);
1957       write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1958       return JB_ERR_PARSE;
1959    }
1960    csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1961
1962    /* Check request line for rewrites. */
1963    if ((NULL == csp->headers->first->str)
1964       || (strcmp(http->cmd, csp->headers->first->str) &&
1965          (JB_ERR_OK != change_request_destination(csp))))
1966    {
1967       /*
1968        * A header filter broke the request line - bail out.
1969        */
1970       write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1971          strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1972       /* XXX: Use correct size */
1973       log_error(LOG_LEVEL_CLF,
1974          "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1975       log_error(LOG_LEVEL_ERROR,
1976          "Invalid request line after applying header filters.");
1977       free_http_request(http);
1978
1979       return JB_ERR_PARSE;
1980    }
1981
1982    if (client_has_unsupported_expectations(csp))
1983    {
1984       return JB_ERR_PARSE;
1985    }
1986
1987    return JB_ERR_OK;
1988
1989 }
1990
1991
1992 /*********************************************************************
1993  *
1994  * Function    : send_http_request
1995  *
1996  * Description : Sends the HTTP headers from the client request
1997  *               and all the body data that has already been received.
1998  *
1999  * Parameters  :
2000  *          1  :  csp = Current client state (buffers, headers, etc...)
2001  *
2002  * Returns     :  0 on success, anything else is an error.
2003  *
2004  *********************************************************************/
2005 static int send_http_request(struct client_state *csp)
2006 {
2007    char *hdr;
2008    int write_failure;
2009
2010    hdr = list_to_text(csp->headers);
2011    if (hdr == NULL)
2012    {
2013       /* FIXME Should handle error properly */
2014       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2015    }
2016    list_remove_all(csp->headers);
2017
2018    /*
2019     * Write the client's (modified) header to the server
2020     * (along with anything else that may be in the buffer)
2021     */
2022    write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2023    freez(hdr);
2024
2025    if (write_failure)
2026    {
2027       log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2028          csp->http->hostport);
2029    }
2030    else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2031       && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2032    {
2033       write_failure = 1;
2034       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2035          csp->http->hostport);
2036    }
2037
2038    return write_failure;
2039
2040 }
2041
2042
2043 #ifdef FEATURE_HTTPS_INSPECTION
2044 /*********************************************************************
2045  *
2046  * Function    : receive_and_send_encrypted_post_data
2047  *
2048  * Description : Reads remaining POST data from the client and sends
2049  *               it to the server.
2050  *
2051  * Parameters  :
2052  *          1  :  csp = Current client state (buffers, headers, etc...)
2053  *
2054  * Returns     :  0 on success, anything else is an error.
2055  *
2056  *********************************************************************/
2057 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2058 {
2059    int content_length_known = csp->expected_client_content_length != 0;
2060
2061    while (is_ssl_pending(&(csp->mbedtls_client_attr.ssl))
2062       || (content_length_known && csp->expected_client_content_length != 0))
2063    {
2064       unsigned char buf[BUFFER_SIZE];
2065       int len;
2066       int max_bytes_to_read = sizeof(buf);
2067
2068       if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2069       {
2070          max_bytes_to_read = (int)csp->expected_client_content_length;
2071       }
2072       log_error(LOG_LEVEL_CONNECT,
2073          "Waiting for up to %d bytes of POST data from the client.",
2074          max_bytes_to_read);
2075       len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl), buf,
2076          (unsigned)max_bytes_to_read);
2077       if (len == -1)
2078       {
2079          return 1;
2080       }
2081       if (len == 0)
2082       {
2083          /* XXX: Does this actually happen? */
2084          break;
2085       }
2086       log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted POST data",
2087          len);
2088       len = ssl_send_data(&(csp->mbedtls_server_attr.ssl), buf, (size_t)len);
2089       if (len == -1)
2090       {
2091          return 1;
2092       }
2093       if (csp->expected_client_content_length != 0)
2094       {
2095          if (csp->expected_client_content_length >= len)
2096          {
2097             csp->expected_client_content_length -= (unsigned)len;
2098          }
2099          if (csp->expected_client_content_length == 0)
2100          {
2101             log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2102             break;
2103          }
2104       }
2105    }
2106
2107    log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted POST data");
2108
2109    return 0;
2110
2111 }
2112
2113
2114 /*********************************************************************
2115  *
2116  * Function    : send_https_request
2117  *
2118  * Description : Sends the HTTP headers from the client request
2119  *               and all the body data that has already been received.
2120  *
2121  * Parameters  :
2122  *          1  :  csp = Current client state (buffers, headers, etc...)
2123  *
2124  * Returns     :  0 on success, anything else is an error.
2125  *
2126  *********************************************************************/
2127 static int send_https_request(struct client_state *csp)
2128 {
2129    char *hdr;
2130    int ret;
2131    long flushed = 0;
2132
2133    hdr = list_to_text(csp->https_headers);
2134    if (hdr == NULL)
2135    {
2136       /* FIXME Should handle error properly */
2137       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2138    }
2139    list_remove_all(csp->https_headers);
2140
2141    /*
2142     * Write the client's (modified) header to the server
2143     * (along with anything else that may be in the buffer)
2144     */
2145    ret = ssl_send_data(&(csp->mbedtls_server_attr.ssl),
2146       (const unsigned char *)hdr, strlen(hdr));
2147    freez(hdr);
2148
2149    if (ret < 0)
2150    {
2151       log_error(LOG_LEVEL_CONNECT,
2152          "Failed sending encrypted request headers to: %s: %E",
2153          csp->http->hostport);
2154       mark_server_socket_tainted(csp);
2155       return 1;
2156    }
2157
2158    if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2159       && ((flushed = ssl_flush_socket(&(csp->mbedtls_server_attr.ssl),
2160             csp->client_iob)) < 0))
2161    {
2162       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2163          csp->http->hostport);
2164       return 1;
2165    }
2166    if (flushed != 0)
2167    {
2168       if (csp->expected_client_content_length != 0)
2169       {
2170          if (csp->expected_client_content_length < flushed)
2171          {
2172             log_error(LOG_LEVEL_ERROR,
2173                "Flushed %d bytes of request body while only expecting %llu",
2174                flushed, csp->expected_client_content_length);
2175             csp->expected_client_content_length = 0;
2176          }
2177          else
2178          {
2179             log_error(LOG_LEVEL_CONNECT,
2180                "Flushed %d bytes of request body while expecting %llu",
2181                flushed, csp->expected_client_content_length);
2182             csp->expected_client_content_length -= (unsigned)flushed;
2183             if (receive_and_send_encrypted_post_data(csp))
2184             {
2185                return 1;
2186             }
2187          }
2188       }
2189       else
2190       {
2191          log_error(LOG_LEVEL_CONNECT,
2192             "Flushed %d bytes of request body", flushed);
2193       }
2194    }
2195
2196    log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2197
2198    return 0;
2199
2200 }
2201
2202
2203 /*********************************************************************
2204  *
2205  * Function    :  receive_encrypted_request
2206  *
2207  * Description :  Receives an encrypted request.
2208  *
2209  * Parameters  :
2210  *          1  :  csp = Current client state (buffers, headers, etc...)
2211  *
2212  * Returns     :  JB_ERR_OK on success,
2213  *                JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2214  *
2215  *********************************************************************/
2216 static jb_err receive_encrypted_request(struct client_state *csp)
2217 {
2218    char buf[BUFFER_SIZE];
2219    int len;
2220    char *p;
2221
2222    do
2223    {
2224       log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2225       if (!is_ssl_pending(&(csp->mbedtls_client_attr.ssl)) &&
2226           !data_is_available(csp->cfd, csp->config->socket_timeout))
2227       {
2228          log_error(LOG_LEVEL_CONNECT,
2229             "Socket %d timed out while waiting for client headers", csp->cfd);
2230          return JB_ERR_PARSE;
2231       }
2232       len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl),
2233          (unsigned char *)buf, sizeof(buf));
2234       if (len == -1)
2235       {
2236          return JB_ERR_PARSE;
2237       }
2238       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2239       {
2240          return JB_ERR_MEMORY;
2241       }
2242       p = strstr(csp->client_iob->cur, "\r\n\r\n");
2243    } while (p == NULL);
2244
2245    log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2246
2247    return JB_ERR_OK;
2248 }
2249
2250
2251 /*********************************************************************
2252  *
2253  * Function    :  process_encrypted_request
2254  *
2255  * Description :  Receives and parses an encrypted request.
2256  *
2257  * Parameters  :
2258  *          1  :  csp = Current client state (buffers, headers, etc...)
2259  *
2260  * Returns     :  JB_ERR_OK on success,
2261  *                JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2262  *
2263  *********************************************************************/
2264 static jb_err process_encrypted_request(struct client_state *csp)
2265 {
2266    char *p;
2267    char *request_line;
2268    jb_err err;
2269    /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2270    struct list header_list;
2271    struct list *headers = &header_list;
2272
2273    err = receive_encrypted_request(csp);
2274    if (err != JB_ERR_OK)
2275    {
2276       /* XXX: Also used for JB_ERR_MEMORY */
2277       log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2278          jb_err_to_string(err));
2279       ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
2280          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2281       return err;
2282    }
2283
2284    /* We don't need get_request_line() because the whole HTTP head is buffered. */
2285    request_line = get_header(csp->client_iob);
2286    if (request_line == NULL)
2287    {
2288       log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2289       ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
2290          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2291       return JB_ERR_PARSE;
2292    }
2293    assert(*request_line != '\0');
2294
2295    if (client_protocol_is_unsupported(csp, request_line))
2296    {
2297       /*
2298        * If the protocol is unsupported we're done here.
2299        * client_protocol_is_unsupported() took care of sending
2300        * the error response and logging the error message.
2301        */
2302       return JB_ERR_PARSE;
2303    }
2304
2305 #ifdef FEATURE_FORCE_LOAD
2306    if (force_required(csp, request_line))
2307    {
2308       csp->flags |= CSP_FLAG_FORCED;
2309    }
2310 #endif /* def FEATURE_FORCE_LOAD */
2311
2312    free_http_request(csp->http);
2313
2314    err = parse_http_request(request_line, csp->http);
2315    /* XXX: Restore ssl setting. This is ugly */
2316    csp->http->client_ssl = 1;
2317    csp->http->server_ssl = 1;
2318
2319    freez(request_line);
2320    if (JB_ERR_OK != err)
2321    {
2322       ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
2323          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2324       /* XXX: Use correct size */
2325       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2326       log_error(LOG_LEVEL_ERROR,
2327          "Couldn't parse request line received from %s: %s",
2328          csp->ip_addr_str, jb_err_to_string(err));
2329
2330       free_http_request(csp->http);
2331       return JB_ERR_PARSE;
2332    }
2333
2334    /* Parse the rest of the client's headers. */
2335    init_list(headers);
2336    for (;;)
2337    {
2338       p = get_header(csp->client_iob);
2339
2340       if (p == NULL)
2341       {
2342          /* There are no additional headers to read. */
2343          break;
2344       }
2345       enlist(headers, p);
2346       freez(p);
2347    }
2348
2349    if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2350    {
2351       /*
2352        * Our attempts to get the request destination
2353        * elsewhere failed.
2354        */
2355       log_error(LOG_LEVEL_ERROR,
2356          "Failed to get the encrypted request destination");
2357       ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
2358          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2359       return JB_ERR_PARSE;
2360    }
2361
2362    /* Split the domain we just got for pattern matching */
2363    init_domain_components(csp->http);
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 #ifdef FEATURE_EXTENDED_STATISTICS
4575    privoxy_mutex_init(&filter_statistics_mutex);
4576    privoxy_mutex_init(&block_statistics_mutex);
4577 #endif
4578
4579    /*
4580     * XXX: The assumptions below are a bit naive
4581     * and can cause locks that aren't necessary.
4582     *
4583     * For example older FreeBSD versions (< 6.x?)
4584     * have no gethostbyname_r, but gethostbyname is
4585     * thread safe.
4586     */
4587 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
4588    privoxy_mutex_init(&resolver_mutex);
4589 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
4590    /*
4591     * XXX: should we use a single mutex for
4592     * localtime() and gmtime() as well?
4593     */
4594 #ifndef HAVE_GMTIME_R
4595    privoxy_mutex_init(&gmtime_mutex);
4596 #endif /* ndef HAVE_GMTIME_R */
4597
4598 #ifndef HAVE_LOCALTIME_R
4599    privoxy_mutex_init(&localtime_mutex);
4600 #endif /* ndef HAVE_GMTIME_R */
4601
4602 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
4603    privoxy_mutex_init(&rand_mutex);
4604 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
4605
4606 #endif /* def MUTEX_LOCKS_AVAILABLE */
4607 }
4608
4609 /*********************************************************************
4610  *
4611  * Function    :  main
4612  *
4613  * Description :  Load the config file and start the listen loop.
4614  *                This function is a lot more *sane* with the `load_config'
4615  *                and `listen_loop' functions; although it stills does
4616  *                a *little* too much for my taste.
4617  *
4618  * Parameters  :
4619  *          1  :  argc = Number of parameters (including $0).
4620  *          2  :  argv = Array of (char *)'s to the parameters.
4621  *
4622  * Returns     :  1 if : can't open config file, unrecognized directive,
4623  *                stats requested in multi-thread mode, can't open the
4624  *                log file, can't open the jar file, listen port is invalid,
4625  *                any load fails, and can't bind port.
4626  *
4627  *                Else main never returns, the process must be signaled
4628  *                to terminate execution.  Or, on Windows, use the
4629  *                "File", "Exit" menu option.
4630  *
4631  *********************************************************************/
4632 #ifdef __MINGW32__
4633 int real_main(int argc, char **argv)
4634 #else
4635 int main(int argc, char **argv)
4636 #endif
4637 {
4638    int argc_pos = 0;
4639    int do_config_test = 0;
4640 #ifndef HAVE_ARC4RANDOM
4641    unsigned int random_seed;
4642 #endif
4643 #ifdef unix
4644    struct passwd *pw = NULL;
4645    struct group *grp = NULL;
4646    int do_chroot = 0;
4647    char *pre_chroot_nslookup_to_load_resolver = NULL;
4648 #endif
4649 #ifdef FUZZ
4650    char *fuzz_input_type = NULL;
4651    char *fuzz_input_file = NULL;
4652 #endif
4653
4654    Argc = argc;
4655    Argv = argv;
4656
4657    configfile =
4658 #if !defined(_WIN32)
4659    "config"
4660 #else
4661    "config.txt"
4662 #endif
4663       ;
4664
4665    /* Prepare mutexes if supported and necessary. */
4666    initialize_mutexes();
4667
4668    /* Enable logging until further notice. */
4669    init_log_module();
4670
4671    /*
4672     * Parse the command line arguments
4673     *
4674     * XXX: simply printing usage information in case of
4675     * invalid arguments isn't particularly user friendly.
4676     */
4677    while (++argc_pos < argc)
4678    {
4679 #ifdef _WIN32
4680       /* Check to see if the service must be installed or uninstalled */
4681       if (strncmp(argv[argc_pos], "--install", 9) == 0)
4682       {
4683          const char *pName = argv[argc_pos] + 9;
4684          if (*pName == ':')
4685             pName++;
4686          exit((install_service(pName)) ? 0 : 1);
4687       }
4688       else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
4689       {
4690          const char *pName = argv[argc_pos] + 11;
4691          if (*pName == ':')
4692             pName++;
4693          exit((uninstall_service(pName)) ? 0 : 1);
4694       }
4695       else if (strcmp(argv[argc_pos], "--service") == 0)
4696       {
4697          bRunAsService = TRUE;
4698          w32_set_service_cwd();
4699          atexit(w32_service_exit_notify);
4700       }
4701       else
4702 #endif /* defined(_WIN32) */
4703
4704
4705 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4706
4707       if (strcmp(argv[argc_pos], "--help") == 0)
4708       {
4709          usage(argv[0]);
4710       }
4711
4712       else if (strcmp(argv[argc_pos], "--version") == 0)
4713       {
4714          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
4715          exit(0);
4716       }
4717
4718 #if defined(unix)
4719
4720       else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
4721       {
4722          set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
4723          daemon_mode = 0;
4724       }
4725
4726       else if (strcmp(argv[argc_pos], "--pidfile") == 0)
4727       {
4728          if (++argc_pos == argc) usage(argv[0]);
4729          pidfile = strdup_or_die(argv[argc_pos]);
4730       }
4731
4732       else if (strcmp(argv[argc_pos], "--user") == 0)
4733       {
4734          char *user_arg;
4735          char *group_name;
4736
4737          if (++argc_pos == argc) usage(argv[argc_pos]);
4738
4739          user_arg = strdup_or_die(argv[argc_pos]);
4740          group_name = strchr(user_arg, '.');
4741          if (NULL != group_name)
4742          {
4743             /* Nul-terminate the user name */
4744             *group_name = '\0';
4745
4746             /* Skip the former delimiter to actually reach the group name */
4747             group_name++;
4748
4749             grp = getgrnam(group_name);
4750             if (NULL == grp)
4751             {
4752                log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
4753             }
4754          }
4755          pw = getpwnam(user_arg);
4756          if (NULL == pw)
4757          {
4758             log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
4759          }
4760
4761          freez(user_arg);
4762       }
4763
4764       else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
4765       {
4766          if (++argc_pos == argc) usage(argv[0]);
4767          pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
4768       }
4769
4770       else if (strcmp(argv[argc_pos], "--chroot") == 0)
4771       {
4772          do_chroot = 1;
4773       }
4774 #endif /* defined(unix) */
4775
4776       else if (strcmp(argv[argc_pos], "--config-test") == 0)
4777       {
4778          do_config_test = 1;
4779       }
4780 #ifdef FUZZ
4781       else if (strcmp(argv[argc_pos], "--fuzz") == 0)
4782       {
4783          argc_pos++;
4784          if (argc < argc_pos + 2) usage(argv[0]);
4785          fuzz_input_type = argv[argc_pos];
4786          argc_pos++;
4787          fuzz_input_file = argv[argc_pos];
4788       }
4789       else if (strcmp(argv[argc_pos], "--stfu") == 0)
4790       {
4791          set_debug_level(LOG_LEVEL_STFU);
4792       }
4793 #endif
4794       else if (argc_pos + 1 != argc)
4795       {
4796          /*
4797           * This is neither the last command line
4798           * option, nor was it recognized before,
4799           * therefore it must be invalid.
4800           */
4801          usage(argv[0]);
4802       }
4803       else
4804
4805 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
4806       {
4807          configfile = argv[argc_pos];
4808       }
4809
4810    } /* -END- while (more arguments) */
4811
4812    show_version(Argv[0]);
4813
4814 #if defined(unix)
4815    if (*configfile != '/')
4816    {
4817       char cwd[BUFFER_SIZE];
4818       char *abs_file;
4819       size_t abs_file_size;
4820
4821       /* make config-filename absolute here */
4822       if (NULL == getcwd(cwd, sizeof(cwd)))
4823       {
4824          perror("failed to get current working directory");
4825          exit(1);
4826       }
4827
4828       basedir = strdup_or_die(cwd);
4829       /* XXX: why + 5? */
4830       abs_file_size = strlen(cwd) + strlen(configfile) + 5;
4831       abs_file = malloc_or_die(abs_file_size);
4832       strlcpy(abs_file, basedir, abs_file_size);
4833       strlcat(abs_file, "/", abs_file_size);
4834       strlcat(abs_file, configfile, abs_file_size);
4835       configfile = abs_file;
4836    }
4837 #endif /* defined unix */
4838
4839
4840    files->next = NULL;
4841    clients->next = NULL;
4842
4843    /* XXX: factor out initialising after the next stable release. */
4844 #ifdef _WIN32
4845    InitWin32();
4846 #endif
4847
4848 #ifndef HAVE_ARC4RANDOM
4849    random_seed = (unsigned int)time(NULL);
4850 #ifdef HAVE_RANDOM
4851    srandom(random_seed);
4852 #else
4853    srand(random_seed);
4854 #endif /* ifdef HAVE_RANDOM */
4855 #endif /* ifndef HAVE_ARC4RANDOM */
4856
4857    /*
4858     * Unix signal handling
4859     *
4860     * Catch the abort, interrupt and terminate signals for a graceful exit
4861     * Catch the hangup signal so the errlog can be reopened.
4862     *
4863     * Ignore the broken pipe signal as connection failures
4864     * are handled when and where they occur without relying
4865     * on a signal.
4866     */
4867 #if !defined(_WIN32) && !defined(__OS2__)
4868 {
4869    int idx;
4870    const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
4871
4872    for (idx = 0; idx < SZ(catched_signals); idx++)
4873    {
4874 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
4875       if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
4876 #else
4877       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
4878 #endif /* ifdef sun */
4879       {
4880          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
4881       }
4882    }
4883
4884    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
4885    {
4886       log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
4887    }
4888
4889 }
4890 #else /* ifdef _WIN32 */
4891 # ifdef _WIN_CONSOLE
4892    /*
4893     * We *are* in a windows console app.
4894     * Print a verbose messages about FAQ's and such
4895     */
4896    printf("%s", win32_blurb);
4897 # endif /* def _WIN_CONSOLE */
4898 #endif /* def _WIN32 */
4899
4900 #ifdef FUZZ
4901    if (fuzz_input_type != NULL)
4902    {
4903       exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
4904    }
4905    log_error(LOG_LEVEL_FATAL,
4906       "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
4907       "Various data structures are static which is unsafe when using threads.");
4908 #endif
4909
4910    if (do_config_test)
4911    {
4912       exit(NULL == load_config());
4913    }
4914
4915    /* Initialize the CGI subsystem */
4916    cgi_init_error_messages();
4917
4918    /*
4919     * If running on unix and without the --no-daemon
4920     * option, become a daemon. I.e. fork, detach
4921     * from tty and get process group leadership
4922     */
4923 #if defined(unix)
4924 {
4925    if (daemon_mode)
4926    {
4927       int fd;
4928       pid_t pid = fork();
4929
4930       if (pid < 0) /* error */
4931       {
4932          perror("fork");
4933          exit(3);
4934       }
4935       else if (pid != 0) /* parent */
4936       {
4937          int status;
4938          pid_t wpid;
4939          /*
4940           * must check for errors
4941           * child died due to missing files aso
4942           */
4943          sleep(1);
4944          wpid = waitpid(pid, &status, WNOHANG);
4945          if (wpid != 0)
4946          {
4947             exit(1);
4948          }
4949          exit(0);
4950       }
4951       /* child */
4952
4953       setsid();
4954
4955       /*
4956        * stderr (fd 2) will be closed later on,
4957        * when the config file has been parsed.
4958        */
4959       close(0);
4960       close(1);
4961
4962       /*
4963        * Reserve fd 0 and 1 to prevent abort() and friends
4964        * from sending stuff to the clients or servers.
4965        */
4966       fd = open("/dev/null", O_RDONLY);
4967       if (fd == -1)
4968       {
4969          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4970       }
4971       else if (fd != 0)
4972       {
4973          if (dup2(fd, 0) == -1)
4974          {
4975             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
4976          }
4977          close(fd);
4978       }
4979       fd = open("/dev/null", O_WRONLY);
4980       if (fd == -1)
4981       {
4982          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4983       }
4984       else if (fd != 1)
4985       {
4986          if (dup2(fd, 1) == -1)
4987          {
4988             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
4989          }
4990          close(fd);
4991       }
4992
4993 #ifdef FEATURE_EXTERNAL_FILTERS
4994       for (fd = 0; fd < 3; fd++)
4995       {
4996          mark_socket_for_close_on_execute(fd);
4997       }
4998 #endif
4999
5000       chdir("/");
5001
5002    } /* -END- if (daemon_mode) */
5003
5004    /*
5005     * As soon as we have written the PID file, we can switch
5006     * to the user and group ID indicated by the --user option
5007     */
5008    if (pidfile != NULL)
5009    {
5010       write_pid_file(pidfile);
5011    }
5012    if (NULL != pw)
5013    {
5014       if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5015       {
5016          log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5017       }
5018       if (NULL != grp)
5019       {
5020          if (setgroups(1, &grp->gr_gid))
5021          {
5022             log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5023          }
5024       }
5025       else if (initgroups(pw->pw_name, pw->pw_gid))
5026       {
5027          log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5028       }
5029       if (do_chroot)
5030       {
5031          if (!pw->pw_dir)
5032          {
5033             log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5034          }
5035          /* Read the time zone file from /etc before doing chroot. */
5036          tzset();
5037          if (NULL != pre_chroot_nslookup_to_load_resolver
5038              && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5039          {
5040             /* Initialize resolver library. */
5041             (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5042          }
5043          if (chroot(pw->pw_dir) < 0)
5044          {
5045             log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5046          }
5047          if (chdir ("/"))
5048          {
5049             log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5050          }
5051       }
5052       if (setuid(pw->pw_uid))
5053       {
5054          log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5055       }
5056       if (do_chroot)
5057       {
5058          char putenv_dummy[64];
5059
5060          strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5061          if (putenv(putenv_dummy) != 0)
5062          {
5063             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5064          }
5065
5066          snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5067          if (putenv(putenv_dummy) != 0)
5068          {
5069             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5070          }
5071       }
5072    }
5073    else if (do_chroot)
5074    {
5075       log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5076    }
5077 }
5078 #endif /* defined unix */
5079
5080 #ifdef _WIN32
5081    /* This will be FALSE unless the command line specified --service
5082     */
5083    if (bRunAsService)
5084    {
5085       /* Yup, so now we must attempt to establish a connection
5086        * with the service dispatcher. This will only work if this
5087        * process was launched by the service control manager to
5088        * actually run as a service. If this isn't the case, i've
5089        * known it take around 30 seconds or so for the call to return.
5090        */
5091
5092       /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5093       if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5094       {
5095          /* Service has run, and at this point is now being stopped, so just return */
5096          return 0;
5097       }
5098
5099 #ifdef _WIN_CONSOLE
5100       printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5101 #endif
5102       /* An error occurred. Usually it's because --service was wrongly specified
5103        * and we were unable to connect to the Service Control Dispatcher because
5104        * it wasn't expecting us and is therefore not listening.
5105        *
5106        * For now, just continue below to call the listen_loop function.
5107        */
5108    }
5109 #endif /* def _WIN32 */
5110
5111    listen_loop();
5112
5113    /* NOTREACHED */
5114    return(-1);
5115
5116 }
5117
5118
5119 /*********************************************************************
5120  *
5121  * Function    :  bind_port_helper
5122  *
5123  * Description :  Bind the listen port.  Handles logging, and aborts
5124  *                on failure.
5125  *
5126  * Parameters  :
5127  *          1  :  haddr = Host address to bind to. Use NULL to bind to
5128  *                        INADDR_ANY.
5129  *          2  :  hport = Specifies port to bind to.
5130  *          3  :  backlog = Listen backlog.
5131  *
5132  * Returns     :  Port that was opened.
5133  *
5134  *********************************************************************/
5135 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5136 {
5137    int result;
5138    jb_socket bfd;
5139
5140    result = bind_port(haddr, hport, backlog, &bfd);
5141
5142    if (result < 0)
5143    {
5144       const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5145       switch(result)
5146       {
5147          case -3:
5148             log_error(LOG_LEVEL_FATAL,
5149                "can't bind to %s:%d: There may be another Privoxy "
5150                "or some other proxy running on port %d",
5151                bind_address, hport, hport);
5152
5153          case -2:
5154             log_error(LOG_LEVEL_FATAL,
5155                "can't bind to %s:%d: The hostname is not resolvable",
5156                bind_address, hport);
5157
5158          default:
5159             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5160                bind_address, hport);
5161       }
5162
5163       /* shouldn't get here */
5164       return JB_INVALID_SOCKET;
5165    }
5166
5167 #ifndef HAVE_POLL
5168 #ifndef _WIN32
5169    if (bfd >= FD_SETSIZE)
5170    {
5171       log_error(LOG_LEVEL_FATAL,
5172          "Bind socket number too high to use select(): %d >= %d",
5173          bfd, FD_SETSIZE);
5174    }
5175 #endif
5176 #endif
5177
5178    if (haddr == NULL)
5179    {
5180       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5181          hport);
5182    }
5183    else
5184    {
5185       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5186          hport, haddr);
5187    }
5188
5189    return bfd;
5190 }
5191
5192
5193 /*********************************************************************
5194  *
5195  * Function    :  bind_ports_helper
5196  *
5197  * Description :  Bind the listen ports.  Handles logging, and aborts
5198  *                on failure.
5199  *
5200  * Parameters  :
5201  *          1  :  config = Privoxy configuration.  Specifies ports
5202  *                         to bind to.
5203  *          2  :  sockets = Preallocated array of opened sockets
5204  *                          corresponding to specification in config.
5205  *                          All non-opened sockets will be set to
5206  *                          JB_INVALID_SOCKET.
5207  *
5208  * Returns     :  Nothing. Inspect sockets argument.
5209  *
5210  *********************************************************************/
5211 static void bind_ports_helper(struct configuration_spec * config,
5212                               jb_socket sockets[])
5213 {
5214    int i;
5215
5216    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5217    {
5218       if (config->hport[i])
5219       {
5220          sockets[i] = bind_port_helper(config->haddr[i],
5221             config->hport[i], config->listen_backlog);
5222 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5223          if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5224          {
5225             struct accept_filter_arg af_options;
5226             bzero(&af_options, sizeof(af_options));
5227             strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5228             if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5229                   sizeof(af_options)))
5230             {
5231                log_error(LOG_LEVEL_ERROR,
5232                   "Enabling accept filter for socket %d failed: %E", sockets[i]);
5233             }
5234          }
5235 #endif
5236       }
5237       else
5238       {
5239          sockets[i] = JB_INVALID_SOCKET;
5240       }
5241    }
5242    config->need_bind = 0;
5243 }
5244
5245
5246 /*********************************************************************
5247  *
5248  * Function    :  close_ports_helper
5249  *
5250  * Description :  Close listenings ports.
5251  *
5252  * Parameters  :
5253  *          1  :  sockets = Array of opened and non-opened sockets to
5254  *                          close. All sockets will be set to
5255  *                          JB_INVALID_SOCKET.
5256  *
5257  * Returns     :  Nothing.
5258  *
5259  *********************************************************************/
5260 static void close_ports_helper(jb_socket sockets[])
5261 {
5262    int i;
5263
5264    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5265    {
5266       if (JB_INVALID_SOCKET != sockets[i])
5267       {
5268          close_socket(sockets[i]);
5269       }
5270       sockets[i] = JB_INVALID_SOCKET;
5271    }
5272 }
5273
5274
5275 #ifdef _WIN32
5276 /* Without this simple workaround we get this compiler warning from _beginthread
5277  *     warning C4028: formal parameter 1 different from declaration
5278  */
5279 void w32_service_listen_loop(void *p)
5280 {
5281    listen_loop();
5282 }
5283 #endif /* def _WIN32 */
5284
5285
5286 /*********************************************************************
5287  *
5288  * Function    :  listen_loop
5289  *
5290  * Description :  bind the listen port and enter a "FOREVER" listening loop.
5291  *
5292  * Parameters  :  N/A
5293  *
5294  * Returns     :  Never.
5295  *
5296  *********************************************************************/
5297 static void listen_loop(void)
5298 {
5299    struct client_states *csp_list = NULL;
5300    struct client_state *csp = NULL;
5301    jb_socket bfds[MAX_LISTENING_SOCKETS];
5302    struct configuration_spec *config;
5303    unsigned int active_threads = 0;
5304 #if defined(FEATURE_PTHREAD)
5305    pthread_attr_t attrs;
5306
5307    pthread_attr_init(&attrs);
5308    pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5309 #endif
5310
5311    config = load_config();
5312
5313 #ifdef FEATURE_CONNECTION_SHARING
5314    /*
5315     * XXX: Should be relocated once it no
5316     * longer needs to emit log messages.
5317     */
5318    initialize_reusable_connections();
5319 #endif /* def FEATURE_CONNECTION_SHARING */
5320
5321    bind_ports_helper(config, bfds);
5322
5323 #ifdef FEATURE_GRACEFUL_TERMINATION
5324    while (!g_terminate)
5325 #else
5326    for (;;)
5327 #endif
5328    {
5329 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
5330       while (waitpid(-1, NULL, WNOHANG) > 0)
5331       {
5332          /* zombie children */
5333       }
5334 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5335
5336       /*
5337        * Free data that was used by died threads
5338        */
5339       active_threads = sweep();
5340
5341 #if defined(unix)
5342       /*
5343        * Re-open the errlog after HUP signal
5344        */
5345       if (received_hup_signal)
5346       {
5347          if (NULL != config->logfile)
5348          {
5349             init_error_log(Argv[0], config->logfile);
5350          }
5351          received_hup_signal = 0;
5352       }
5353 #endif
5354
5355       csp_list = zalloc_or_die(sizeof(*csp_list));
5356       csp = &csp_list->csp;
5357
5358       log_error(LOG_LEVEL_CONNECT,
5359          "Waiting for the next client connection. Currently active threads: %d",
5360          active_threads);
5361
5362       /*
5363        * This config may be outdated, but for accept_connection()
5364        * it's fresh enough.
5365        */
5366       csp->config = config;
5367
5368       if (!accept_connection(csp, bfds))
5369       {
5370          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5371          freez(csp_list);
5372          continue;
5373       }
5374
5375       csp->flags |= CSP_FLAG_ACTIVE;
5376       csp->server_connection.sfd = JB_INVALID_SOCKET;
5377
5378       csp->config = config = load_config();
5379
5380       if (config->need_bind)
5381       {
5382          /*
5383           * Since we were listening to the "old port", we will not see
5384           * a "listen" param change until the next request.  So, at
5385           * least 1 more request must be made for us to find the new
5386           * setting.  I am simply closing the old socket and binding the
5387           * new one.
5388           *
5389           * Which-ever is correct, we will serve 1 more page via the
5390           * old settings.  This should probably be a "show-status"
5391           * request.  This should not be a so common of an operation
5392           * that this will hurt people's feelings.
5393           */
5394
5395          close_ports_helper(bfds);
5396
5397          bind_ports_helper(config, bfds);
5398       }
5399
5400 #ifdef FEATURE_TOGGLE
5401       if (global_toggle_state)
5402 #endif /* def FEATURE_TOGGLE */
5403       {
5404          csp->flags |= CSP_FLAG_TOGGLED_ON;
5405       }
5406
5407       if (run_loader(csp))
5408       {
5409          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5410          /* Never get here - LOG_LEVEL_FATAL causes program exit */
5411       }
5412
5413 #ifdef FEATURE_ACL
5414       if (block_acl(NULL,csp))
5415       {
5416          log_error(LOG_LEVEL_CONNECT,
5417             "Connection from %s on %s (socket %d) dropped due to ACL",
5418             csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5419          close_socket(csp->cfd);
5420          freez(csp->ip_addr_str);
5421          freez(csp->listen_addr_str);
5422          freez(csp_list);
5423          continue;
5424       }
5425 #endif /* def FEATURE_ACL */
5426
5427       if ((0 != config->max_client_connections)
5428          && (active_threads >= config->max_client_connections))
5429       {
5430          log_error(LOG_LEVEL_CONNECT,
5431             "Rejecting connection from %s. Maximum number of connections reached.",
5432             csp->ip_addr_str);
5433          write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5434             strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5435          close_socket(csp->cfd);
5436          freez(csp->ip_addr_str);
5437          freez(csp->listen_addr_str);
5438          freez(csp_list);
5439          continue;
5440       }
5441
5442       /* add it to the list of clients */
5443       csp_list->next = clients->next;
5444       clients->next = csp_list;
5445
5446       if (config->multi_threaded)
5447       {
5448          int child_id;
5449
5450 /* this is a switch () statement in the C preprocessor - ugh */
5451 #undef SELECTED_ONE_OPTION
5452
5453 /* Use Pthreads in preference to native code */
5454 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
5455 #define SELECTED_ONE_OPTION
5456          {
5457             pthread_t the_thread;
5458
5459             errno = pthread_create(&the_thread, &attrs,
5460                (void * (*)(void *))serve, csp);
5461             child_id = errno ? -1 : 0;
5462          }
5463 #endif
5464
5465 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
5466 #define SELECTED_ONE_OPTION
5467          child_id = _beginthread(
5468             (void (*)(void *))serve,
5469             64 * 1024,
5470             csp);
5471 #endif
5472
5473 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
5474 #define SELECTED_ONE_OPTION
5475          child_id = _beginthread(
5476             (void(* _Optlink)(void*))serve,
5477             NULL,
5478             64 * 1024,
5479             csp);
5480 #endif
5481
5482 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
5483 #define SELECTED_ONE_OPTION
5484          {
5485             thread_id tid = spawn_thread
5486                (server_thread, "server", B_NORMAL_PRIORITY, csp);
5487
5488             if ((tid >= 0) && (resume_thread(tid) == B_OK))
5489             {
5490                child_id = (int) tid;
5491             }
5492             else
5493             {
5494                child_id = -1;
5495             }
5496          }
5497 #endif
5498
5499 #if !defined(SELECTED_ONE_OPTION)
5500          child_id = fork();
5501
5502          /* This block is only needed when using fork().
5503           * When using threads, the server thread was
5504           * created and run by the call to _beginthread().
5505           */
5506          if (child_id == 0)   /* child */
5507          {
5508             int rc = 0;
5509 #ifdef FEATURE_TOGGLE
5510             int inherited_toggle_state = global_toggle_state;
5511 #endif /* def FEATURE_TOGGLE */
5512
5513             serve(csp);
5514
5515             /*
5516              * If we've been toggled or we've blocked the request, tell Mom
5517              */
5518
5519 #ifdef FEATURE_TOGGLE
5520             if (inherited_toggle_state != global_toggle_state)
5521             {
5522                rc |= RC_FLAG_TOGGLED;
5523             }
5524 #endif /* def FEATURE_TOGGLE */
5525
5526 #ifdef FEATURE_STATISTICS
5527             if (csp->flags & CSP_FLAG_REJECTED)
5528             {
5529                rc |= RC_FLAG_BLOCKED;
5530             }
5531 #endif /* ndef FEATURE_STATISTICS */
5532
5533             _exit(rc);
5534          }
5535          else if (child_id > 0) /* parent */
5536          {
5537             /* in a fork()'d environment, the parent's
5538              * copy of the client socket and the CSP
5539              * are not used.
5540              */
5541             int child_status;
5542 #if !defined(_WIN32) && !defined(__CYGWIN__)
5543
5544             wait(&child_status);
5545
5546             /*
5547              * Evaluate child's return code: If the child has
5548              *  - been toggled, toggle ourselves
5549              *  - blocked its request, bump up the stats counter
5550              */
5551
5552 #ifdef FEATURE_TOGGLE
5553             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
5554             {
5555                global_toggle_state = !global_toggle_state;
5556             }
5557 #endif /* def FEATURE_TOGGLE */
5558
5559 #ifdef FEATURE_STATISTICS
5560             urls_read++;
5561             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
5562             {
5563                urls_rejected++;
5564             }
5565 #endif /* def FEATURE_STATISTICS */
5566
5567 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
5568             close_socket(csp->cfd);
5569             csp->flags &= ~CSP_FLAG_ACTIVE;
5570          }
5571 #endif
5572
5573 #undef SELECTED_ONE_OPTION
5574 /* end of cpp switch () */
5575
5576          if (child_id < 0)
5577          {
5578             /*
5579              * Spawning the child failed, assume it's because
5580              * there are too many children running already.
5581              * XXX: If you assume ...
5582              */
5583             log_error(LOG_LEVEL_ERROR,
5584                "Unable to take any additional connections: %E. Active threads: %d",
5585                active_threads);
5586             write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5587                strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5588             close_socket(csp->cfd);
5589             csp->flags &= ~CSP_FLAG_ACTIVE;
5590          }
5591       }
5592       else
5593       {
5594          serve(csp);
5595       }
5596    }
5597
5598 #if defined(FEATURE_PTHREAD)
5599    pthread_attr_destroy(&attrs);
5600 #endif
5601
5602    /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
5603
5604 #ifdef FEATURE_HTTPS_INSPECTION
5605    /* Clean up.  Aim: free all memory (no leaks) */
5606    if (rng_seeded == 1)
5607    {
5608       mbedtls_ctr_drbg_free(&ctr_drbg);
5609       mbedtls_entropy_free(&entropy);
5610    }
5611 #endif
5612
5613 #ifdef FEATURE_GRACEFUL_TERMINATION
5614
5615    log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
5616
5617    unload_current_config_file();
5618    unload_current_actions_file();
5619    unload_current_re_filterfile();
5620 #ifdef FEATURE_TRUST
5621    unload_current_trust_file();
5622 #endif
5623
5624    if (config->multi_threaded)
5625    {
5626       int i = 60;
5627       do
5628       {
5629          sleep(1);
5630          sweep();
5631       } while ((clients->next != NULL) && (--i > 0));
5632
5633       if (i <= 0)
5634       {
5635          log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
5636       }
5637    }
5638    sweep();
5639    sweep();
5640
5641 #if defined(unix)
5642    freez(basedir);
5643 #endif
5644
5645 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
5646    /* Cleanup - remove taskbar icon etc. */
5647    TermLogWindow();
5648 #endif
5649
5650    exit(0);
5651 #endif /* FEATURE_GRACEFUL_TERMINATION */
5652
5653 }
5654
5655
5656 /*
5657   Local Variables:
5658   tab-width: 3
5659   end:
5660 */