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