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