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