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