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