Merge branch 'master' of ssh://git.privoxy.org:23/git/privoxy
[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             close_client_ssl_connection(csp);
3878             return;
3879          }
3880          /*
3881           * We have an encrypted request. Check if one of the crunchers now
3882           * wants it (for example because the previously invisible path was
3883           * required to match).
3884           */
3885          if (crunch_response_triggered(csp, crunchers_all))
3886          {
3887             /*
3888              * Yes. The client got the crunch response and we're done here.
3889              */
3890             return;
3891          }
3892       }
3893 #endif
3894       /*
3895        * Connecting to destination server
3896        */
3897       csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
3898
3899       if (csp->server_connection.sfd == JB_INVALID_SOCKET)
3900       {
3901          if (fwd->type != SOCKS_NONE)
3902          {
3903             /* Socks error. */
3904             rsp = error_response(csp, "forwarding-failed");
3905          }
3906          else if (errno == EINVAL)
3907          {
3908             rsp = error_response(csp, "no-such-domain");
3909          }
3910          else
3911          {
3912             rsp = error_response(csp, "connect-failed");
3913          }
3914
3915          /* Write the answer to the client */
3916          if (rsp != NULL)
3917          {
3918             send_crunch_response(csp, rsp);
3919          }
3920
3921          /*
3922           * Temporary workaround to prevent already-read client
3923           * bodies from being parsed as new requests. For now we
3924           * err on the safe side and throw all the following
3925           * requests under the bus, even if no client body has been
3926           * buffered. A compliant client will repeat the dropped
3927           * requests on an untainted connection.
3928           *
3929           * The proper fix is to discard the no longer needed
3930           * client body in the buffer (if there is one) and to
3931           * continue parsing the bytes that follow.
3932           */
3933 #ifdef FEATURE_HTTPS_INSPECTION
3934          close_client_ssl_connection(csp);
3935 #endif
3936          drain_and_close_socket(csp->cfd);
3937          csp->cfd = JB_INVALID_SOCKET;
3938
3939          return;
3940       }
3941
3942 #ifdef FEATURE_HTTPS_INSPECTION
3943       /*
3944        * Creating TLS/SSL connections with destination server or parent
3945        * proxy. If forwarding is enabled, we must send client request to
3946        * parent proxy and receive, parse and resend parent proxy answer.
3947        */
3948       if (http->ssl && !use_ssl_tunnel)
3949       {
3950          if (fwd->forward_host != NULL)
3951          {
3952             char server_response[BUFFER_SIZE];
3953             int ret = 0;
3954             int len = 0;
3955             char *hdr = list_to_text(csp->headers);
3956             memset(server_response, 0, sizeof(server_response));
3957
3958             if (hdr == NULL)
3959             {
3960                log_error(LOG_LEVEL_FATAL,
3961                   "Out of memory parsing client header");
3962             }
3963             list_remove_all(csp->headers);
3964
3965             /*
3966              * Sending client's CONNECT request to the parent proxy
3967              */
3968             ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
3969
3970             freez(hdr);
3971
3972             if (ret != 0)
3973             {
3974                log_error(LOG_LEVEL_CONNECT,
3975                   "Sending request headers to: %s failed", http->hostport);
3976                mark_server_socket_tainted(csp);
3977                close_client_ssl_connection(csp);
3978                return;
3979             }
3980
3981             /* Waiting for parent proxy server response */
3982             len = read_socket(csp->server_connection.sfd, server_response,
3983                sizeof(server_response)-1);
3984
3985             if (len <= 0)
3986             {
3987                log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
3988                   "server on socket %d.", csp->server_connection.sfd);
3989
3990                rsp = error_response(csp, "no-server-data");
3991                if (rsp)
3992                {
3993                   send_crunch_response(csp, rsp);
3994                }
3995                mark_server_socket_tainted(csp);
3996                close_client_ssl_connection(csp);
3997                return;
3998             }
3999
4000             /*
4001              * Test if the connection to the destination server was
4002              * established successfully by the parent proxy.
4003              */
4004             if (!tunnel_established_successfully(server_response, (unsigned int)len))
4005             {
4006                log_error(LOG_LEVEL_ERROR,
4007                   "The forwarder %s failed to establish a connection with %s",
4008                   fwd->forward_host, http->host);
4009                rsp = error_response(csp, "connect-failed");
4010                if (rsp)
4011                {
4012                   send_crunch_response(csp, rsp);
4013                }
4014                mark_server_socket_tainted(csp);
4015                close_client_ssl_connection(csp);
4016                return;
4017             }
4018          } /* -END- if (fwd->forward_host != NULL) */
4019
4020          /*
4021           * We can now create the TLS/SSL connection with the destination server.
4022           */
4023          int ret = create_server_ssl_connection(csp);
4024          if (ret != 0)
4025          {
4026             if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4027                 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4028             {
4029                /*
4030                 * If the server certificate is invalid, we must inform
4031                 * the client and then close connection to the client.
4032                 */
4033                ssl_send_certificate_error(csp);
4034                close_client_and_server_ssl_connections(csp);
4035                return;
4036             }
4037             if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4038              || csp->server_cert_verification_result == SSL_CERT_VALID)
4039             {
4040                /*
4041                 * The TLS/SSL connection wasn't created but an invalid
4042                 * certificate wasn't detected. Report it as connection
4043                 * failure.
4044                 */
4045                rsp = error_response(csp, "connect-failed");
4046                if (rsp)
4047                {
4048                   send_crunch_response(csp, rsp);
4049                }
4050                close_client_and_server_ssl_connections(csp);
4051                return;
4052             }
4053          }
4054       }/* -END- if (http->ssl) */
4055 #endif /* def FEATURE_HTTPS_INSPECTION */
4056
4057 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4058       save_connection_destination(csp->server_connection.sfd,
4059          http, fwd, &csp->server_connection);
4060       csp->server_connection.keep_alive_timeout =
4061          (unsigned)csp->config->keep_alive_timeout;
4062    }
4063 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4064
4065    csp->server_connection.requests_sent_total++;
4066
4067    if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4068    {
4069       /* Client headers have been sent optimistically */
4070       assert(csp->headers->last == NULL);
4071    }
4072    else if (http->ssl == 0 || (fwd->forward_host
4073 #ifdef FEATURE_HTTPS_INSPECTION
4074          && use_ssl_tunnel
4075 #endif
4076            ))
4077    {
4078       if (send_http_request(csp))
4079       {
4080          rsp = error_response(csp, "connect-failed");
4081          if (rsp)
4082          {
4083             send_crunch_response(csp, rsp);
4084          }
4085          return;
4086       }
4087    }
4088    else
4089    {
4090       /*
4091        * Using old solution with SSL tunnel or new solution with SSL proxy
4092        */
4093       list_remove_all(csp->headers);
4094 #ifdef FEATURE_HTTPS_INSPECTION
4095       if (use_ssl_tunnel)
4096 #endif
4097       {
4098          /*
4099          * We're running an SSL tunnel and we're not forwarding,
4100          * so just ditch the client headers, send the "connect succeeded"
4101          * message to the client, flush the rest, and get out of the way.
4102          */
4103          if (write_socket_delayed(csp->cfd, CSUCCEED,
4104                strlen(CSUCCEED), get_write_delay(csp)))
4105          {
4106             return;
4107          }
4108       }
4109 #ifdef FEATURE_HTTPS_INSPECTION
4110       else
4111       {
4112          /*
4113           * If server certificate is invalid, we must inform client and then
4114           * close connection with client.
4115           */
4116          if (csp->server_cert_verification_result != SSL_CERT_VALID)
4117          {
4118             ssl_send_certificate_error(csp);
4119             close_client_and_server_ssl_connections(csp);
4120             return;
4121          }
4122          if (send_https_request(csp))
4123          {
4124             rsp = error_response(csp, "connect-failed");
4125             if (rsp)
4126             {
4127                send_crunch_response(csp, rsp);
4128             }
4129             close_client_and_server_ssl_connections(csp);
4130             return;
4131          }
4132       }
4133 #endif /* def FEATURE_HTTPS_INSPECTION */
4134       clear_iob(csp->client_iob);
4135    }/* -END- else ... if (http->ssl == 1) */
4136
4137    log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4138
4139    /* XXX: should the time start earlier for optimistically sent data? */
4140    csp->server_connection.request_sent = time(NULL);
4141
4142    handle_established_connection(csp);
4143    freez(csp->receive_buffer);
4144 }
4145
4146
4147 #ifdef FUZZ
4148 /*********************************************************************
4149  *
4150  * Function    :  fuzz_server_response
4151  *
4152  * Description :  Treat the input as a whole server response.
4153  *
4154  * Parameters  :
4155  *          1  :  csp = Current client state (buffers, headers, etc...)
4156  *          2  :  fuzz_input_file = File to read the input from.
4157  *
4158  * Returns     :  0
4159  *
4160  *********************************************************************/
4161 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4162 {
4163    static struct forward_spec fwd; /* Zero'd due to being static */
4164    csp->cfd = 0;
4165
4166    if (strcmp(fuzz_input_file, "-") == 0)
4167    {
4168       /* XXX: Doesn't work yet. */
4169       csp->server_connection.sfd = 0;
4170    }
4171    else
4172    {
4173       csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4174       if (csp->server_connection.sfd == -1)
4175       {
4176          log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4177             fuzz_input_file);
4178       }
4179    }
4180    csp->fwd = &fwd;
4181    csp->content_type |= CT_GIF;
4182    csp->action->flags |= ACTION_DEANIMATE;
4183    csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4184
4185    csp->http->path = strdup_or_die("/");
4186    csp->http->host = strdup_or_die("fuzz.example.org");
4187    csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4188    /* Prevent client socket monitoring */
4189    csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4190    csp->flags |= CSP_FLAG_CHUNKED;
4191
4192    csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4193    csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4194
4195    csp->content_type |= CT_DECLARED|CT_GIF;
4196
4197    csp->config->socket_timeout = 0;
4198
4199    cgi_init_error_messages();
4200
4201    handle_established_connection(csp);
4202    freez(csp->receive_buffer);
4203
4204    return 0;
4205 }
4206 #endif
4207
4208
4209 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4210 /*********************************************************************
4211  *
4212  * Function    :  prepare_csp_for_next_request
4213  *
4214  * Description :  Put the csp in a mostly vergin state.
4215  *
4216  * Parameters  :
4217  *          1  :  csp = Current client state (buffers, headers, etc...)
4218  *
4219  * Returns     :  N/A
4220  *
4221  *********************************************************************/
4222 static void prepare_csp_for_next_request(struct client_state *csp)
4223 {
4224    csp->content_type = 0;
4225    csp->content_length = 0;
4226    csp->expected_content_length = 0;
4227    csp->expected_client_content_length = 0;
4228    list_remove_all(csp->headers);
4229    clear_iob(csp->iob);
4230    freez(csp->error_message);
4231    free_http_request(csp->http);
4232    destroy_list(csp->headers);
4233 #ifdef FEATURE_HTTPS_INSPECTION
4234    destroy_list(csp->https_headers);
4235 #endif
4236    destroy_list(csp->tags);
4237 #ifdef FEATURE_CLIENT_TAGS
4238    destroy_list(csp->client_tags);
4239    freez(csp->client_address);
4240 #endif
4241    free_current_action(csp->action);
4242    if (NULL != csp->fwd)
4243    {
4244       unload_forward_spec(csp->fwd);
4245       csp->fwd = NULL;
4246    }
4247    /* XXX: Store per-connection flags someplace else. */
4248    csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4249 #ifdef FEATURE_TOGGLE
4250    if (global_toggle_state)
4251 #endif /* def FEATURE_TOGGLE */
4252    {
4253       csp->flags |= CSP_FLAG_TOGGLED_ON;
4254    }
4255
4256    if (csp->client_iob->eod > csp->client_iob->cur)
4257    {
4258       long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4259       size_t data_length  = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4260
4261       assert(bytes_to_shift > 0);
4262       assert(data_length > 0);
4263
4264       log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
4265          data_length, bytes_to_shift);
4266       memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4267       csp->client_iob->cur = csp->client_iob->buf;
4268       assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4269       csp->client_iob->eod = csp->client_iob->buf + data_length;
4270       memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4271
4272       csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4273    }
4274    else
4275    {
4276       /*
4277        * We mainly care about resetting client_iob->cur so we don't
4278        * waste buffer space at the beginning and don't mess up the
4279        * request restoration done by cgi_show_request().
4280        *
4281        * Freeing the buffer itself isn't technically necessary,
4282        * but makes debugging more convenient.
4283        */
4284       clear_iob(csp->client_iob);
4285    }
4286 }
4287 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4288
4289
4290 /*********************************************************************
4291  *
4292  * Function    :  serve
4293  *
4294  * Description :  This is little more than chat.  We only "serve" to
4295  *                to close (or remember) any socket that chat may have
4296  *                opened.
4297  *
4298  * Parameters  :
4299  *          1  :  csp = Current client state (buffers, headers, etc...)
4300  *
4301  * Returns     :  N/A
4302  *
4303  *********************************************************************/
4304 static void serve(struct client_state *csp)
4305 {
4306    int config_file_change_detected = 0; /* Only used for debugging */
4307 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4308 #ifdef FEATURE_CONNECTION_SHARING
4309    static int monitor_thread_running = 0;
4310 #endif /* def FEATURE_CONNECTION_SHARING */
4311    int continue_chatting = 0;
4312
4313    log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4314       csp->ip_addr_str, csp->cfd);
4315
4316    do
4317    {
4318       unsigned int latency;
4319
4320 #ifdef FEATURE_HTTPS_INSPECTION
4321       if (continue_chatting && client_use_ssl(csp))
4322       {
4323          continue_https_chat(csp);
4324       }
4325       else
4326 #endif
4327       {
4328          chat(csp);
4329       }
4330
4331       /*
4332        * If the request has been crunched,
4333        * the calculated latency is zero.
4334        */
4335       latency = (unsigned)(csp->server_connection.response_received -
4336          csp->server_connection.request_sent) / 2;
4337
4338       if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4339          && (csp->flags & CSP_FLAG_CRUNCHED)
4340          && (csp->expected_client_content_length != 0))
4341       {
4342          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4343          log_error(LOG_LEVEL_CONNECT,
4344             "Tainting client socket %d due to unread data.", csp->cfd);
4345       }
4346
4347       continue_chatting = (csp->config->feature_flags
4348          & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4349          && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4350          && (csp->cfd != JB_INVALID_SOCKET)
4351          && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4352          && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4353             || (csp->flags & CSP_FLAG_CHUNKED));
4354
4355       if (!(csp->flags & CSP_FLAG_CRUNCHED)
4356          && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4357       {
4358          if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4359          {
4360             csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4361          }
4362          if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4363             || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4364             || !socket_is_still_alive(csp->server_connection.sfd)
4365             || !(latency < csp->server_connection.keep_alive_timeout))
4366          {
4367             log_error(LOG_LEVEL_CONNECT,
4368                "Closing server socket %d connected to %s. "
4369                "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4370                csp->server_connection.sfd, csp->server_connection.host,
4371                0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4372                0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4373                socket_is_still_alive(csp->server_connection.sfd),
4374                csp->server_connection.keep_alive_timeout);
4375 #ifdef FEATURE_CONNECTION_SHARING
4376             if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4377             {
4378                forget_connection(csp->server_connection.sfd);
4379             }
4380 #endif /* def FEATURE_CONNECTION_SHARING */
4381 #ifdef FEATURE_HTTPS_INSPECTION
4382             close_server_ssl_connection(csp);
4383 #endif
4384             close_socket(csp->server_connection.sfd);
4385             mark_connection_closed(&csp->server_connection);
4386          }
4387       }
4388
4389       if (continue_chatting && any_loaded_file_changed(csp))
4390       {
4391          continue_chatting = 0;
4392          config_file_change_detected = 1;
4393       }
4394 #ifdef FEATURE_HTTPS_INSPECTION
4395       if (continue_chatting && client_use_ssl(csp) &&
4396          csp->ssl_with_client_is_opened == 0)
4397       {
4398          continue_chatting = 0;
4399          log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4400             "The TLS session has been terminated.", csp->cfd);
4401       }
4402 #endif
4403
4404       if (continue_chatting)
4405       {
4406          if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4407             && socket_is_still_alive(csp->cfd))
4408          {
4409             log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4410                "pipelined on socket %d and the socket is still alive.",
4411                csp->requests_received_total+1, csp->cfd);
4412             prepare_csp_for_next_request(csp);
4413             continue;
4414          }
4415
4416          if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4417          {
4418             if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4419             {
4420                log_error(LOG_LEVEL_CONNECT,
4421                   "Waiting for the next client request on socket %d. "
4422                   "Keeping the server socket %d to %s open.",
4423                   csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4424             }
4425             else
4426             {
4427                log_error(LOG_LEVEL_CONNECT,
4428                   "Waiting for the next client request on socket %d. "
4429                   "No server socket to keep open.", csp->cfd);
4430             }
4431          }
4432
4433          if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4434             && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4435             && socket_is_still_alive(csp->cfd))
4436          {
4437             log_error(LOG_LEVEL_CONNECT,
4438                "Data arrived in time on client socket %d. Requests so far: %u",
4439                csp->cfd, csp->requests_received_total);
4440             prepare_csp_for_next_request(csp);
4441          }
4442          else
4443          {
4444 #ifdef FEATURE_CONNECTION_SHARING
4445             if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4446                && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4447                && (socket_is_still_alive(csp->server_connection.sfd))
4448 #ifdef FEATURE_HTTPS_INSPECTION
4449                && !server_use_ssl(csp)
4450 #endif
4451                 )
4452             {
4453                time_t time_open = time(NULL) - csp->server_connection.timestamp;
4454
4455                if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4456                {
4457                   break;
4458                }
4459
4460                remember_connection(&csp->server_connection);
4461                csp->server_connection.sfd = JB_INVALID_SOCKET;
4462                drain_and_close_socket(csp->cfd);
4463                csp->cfd = JB_INVALID_SOCKET;
4464                privoxy_mutex_lock(&connection_reuse_mutex);
4465                if (!monitor_thread_running)
4466                {
4467                   monitor_thread_running = 1;
4468                   privoxy_mutex_unlock(&connection_reuse_mutex);
4469                   wait_for_alive_connections();
4470                   privoxy_mutex_lock(&connection_reuse_mutex);
4471                   monitor_thread_running = 0;
4472                }
4473                privoxy_mutex_unlock(&connection_reuse_mutex);
4474             }
4475 #endif /* def FEATURE_CONNECTION_SHARING */
4476             break;
4477          }
4478       }
4479       else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4480       {
4481          log_error(LOG_LEVEL_CONNECT,
4482             "Closing server socket %d connected to %s. Keep-alive: %u. "
4483             "Tainted: %u. Socket alive: %u. Timeout: %u. "
4484             "Configuration file change detected: %u",
4485             csp->server_connection.sfd, csp->server_connection.host,
4486             0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4487             0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4488             socket_is_still_alive(csp->server_connection.sfd),
4489             csp->server_connection.keep_alive_timeout,
4490             config_file_change_detected);
4491       }
4492    } while (continue_chatting);
4493
4494 #else
4495    chat(csp);
4496 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4497
4498    if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4499    {
4500 #ifdef FEATURE_CONNECTION_SHARING
4501       if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4502       {
4503          forget_connection(csp->server_connection.sfd);
4504       }
4505 #endif /* def FEATURE_CONNECTION_SHARING */
4506
4507 #ifdef FEATURE_HTTPS_INSPECTION
4508       close_server_ssl_connection(csp);
4509 #endif /* def FEATURE_HTTPS_INSPECTION */
4510
4511       close_socket(csp->server_connection.sfd);
4512    }
4513
4514 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4515    mark_connection_closed(&csp->server_connection);
4516 #endif
4517
4518    if (csp->cfd != JB_INVALID_SOCKET)
4519    {
4520       log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4521          "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4522          "Configuration file change detected: %u. Requests received: %u.",
4523          csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4524          socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4525          config_file_change_detected, csp->requests_received_total);
4526 #ifdef FEATURE_HTTPS_INSPECTION
4527       close_client_ssl_connection(csp);
4528 #endif
4529       drain_and_close_socket(csp->cfd);
4530    }
4531
4532    free_csp_resources(csp);
4533
4534    csp->flags &= ~CSP_FLAG_ACTIVE;
4535
4536 }
4537
4538
4539 #ifdef __BEOS__
4540 /*********************************************************************
4541  *
4542  * Function    :  server_thread
4543  *
4544  * Description :  We only exist to call `serve' in a threaded environment.
4545  *
4546  * Parameters  :
4547  *          1  :  data = Current client state (buffers, headers, etc...)
4548  *
4549  * Returns     :  Always 0.
4550  *
4551  *********************************************************************/
4552 static int32 server_thread(void *data)
4553 {
4554    serve((struct client_state *) data);
4555    return 0;
4556
4557 }
4558 #endif
4559
4560
4561 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4562 /*********************************************************************
4563  *
4564  * Function    :  usage
4565  *
4566  * Description :  Print usage info & exit.
4567  *
4568  * Parameters  :  Pointer to argv[0] for identifying ourselves
4569  *
4570  * Returns     :  No. ,-)
4571  *
4572  *********************************************************************/
4573 static void usage(const char *name)
4574 {
4575    printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
4576           "Usage: %s [--config-test] "
4577 #if defined(unix)
4578           "[--chroot] "
4579 #endif /* defined(unix) */
4580           "[--help] "
4581 #if defined(unix)
4582           "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
4583 #endif /* defined(unix) */
4584          "[--version] [configfile]\n",
4585           name);
4586
4587 #ifdef FUZZ
4588    show_fuzz_usage(name);
4589 #endif
4590
4591    printf("Aborting\n");
4592
4593    exit(2);
4594
4595 }
4596 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
4597
4598
4599 #ifdef MUTEX_LOCKS_AVAILABLE
4600 /*********************************************************************
4601  *
4602  * Function    :  privoxy_mutex_lock
4603  *
4604  * Description :  Locks a mutex.
4605  *
4606  * Parameters  :
4607  *          1  :  mutex = The mutex to lock.
4608  *
4609  * Returns     :  Void. May exit in case of errors.
4610  *
4611  *********************************************************************/
4612 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
4613 {
4614 #ifdef FEATURE_PTHREAD
4615    int err = pthread_mutex_lock(mutex);
4616    if (err)
4617    {
4618       if (mutex != &log_mutex)
4619       {
4620          log_error(LOG_LEVEL_FATAL,
4621             "Mutex locking failed: %s.\n", strerror(err));
4622       }
4623       exit(1);
4624    }
4625 #else
4626    EnterCriticalSection(mutex);
4627 #endif /* def FEATURE_PTHREAD */
4628 }
4629
4630
4631 /*********************************************************************
4632  *
4633  * Function    :  privoxy_mutex_unlock
4634  *
4635  * Description :  Unlocks a mutex.
4636  *
4637  * Parameters  :
4638  *          1  :  mutex = The mutex to unlock.
4639  *
4640  * Returns     :  Void. May exit in case of errors.
4641  *
4642  *********************************************************************/
4643 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
4644 {
4645 #ifdef FEATURE_PTHREAD
4646    int err = pthread_mutex_unlock(mutex);
4647    if (err)
4648    {
4649       if (mutex != &log_mutex)
4650       {
4651          log_error(LOG_LEVEL_FATAL,
4652             "Mutex unlocking failed: %s.\n", strerror(err));
4653       }
4654       exit(1);
4655    }
4656 #else
4657    LeaveCriticalSection(mutex);
4658 #endif /* def FEATURE_PTHREAD */
4659 }
4660
4661
4662 /*********************************************************************
4663  *
4664  * Function    :  privoxy_mutex_init
4665  *
4666  * Description :  Prepares a mutex.
4667  *
4668  * Parameters  :
4669  *          1  :  mutex = The mutex to initialize.
4670  *
4671  * Returns     :  Void. May exit in case of errors.
4672  *
4673  *********************************************************************/
4674 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
4675 {
4676 #ifdef FEATURE_PTHREAD
4677    int err = pthread_mutex_init(mutex, 0);
4678    if (err)
4679    {
4680       printf("Fatal error. Mutex initialization failed: %s.\n",
4681          strerror(err));
4682       exit(1);
4683    }
4684 #else
4685    InitializeCriticalSection(mutex);
4686 #endif /* def FEATURE_PTHREAD */
4687 }
4688 #endif /* def MUTEX_LOCKS_AVAILABLE */
4689
4690 /*********************************************************************
4691  *
4692  * Function    :  initialize_mutexes
4693  *
4694  * Description :  Prepares mutexes if mutex support is available.
4695  *
4696  * Parameters  :  None
4697  *
4698  * Returns     :  Void, exits in case of errors.
4699  *
4700  *********************************************************************/
4701 static void initialize_mutexes(void)
4702 {
4703 #ifdef MUTEX_LOCKS_AVAILABLE
4704    /*
4705     * Prepare global mutex semaphores
4706     */
4707
4708 #ifdef FEATURE_HTTPS_INSPECTION
4709    privoxy_mutex_init(&certificate_mutex);
4710    privoxy_mutex_init(&ssl_init_mutex);
4711 #endif
4712
4713    privoxy_mutex_init(&log_mutex);
4714    privoxy_mutex_init(&log_init_mutex);
4715    privoxy_mutex_init(&connection_reuse_mutex);
4716 #ifdef FEATURE_EXTERNAL_FILTERS
4717    privoxy_mutex_init(&external_filter_mutex);
4718 #endif
4719 #ifdef FEATURE_CLIENT_TAGS
4720    privoxy_mutex_init(&client_tags_mutex);
4721 #endif
4722 #ifdef FEATURE_EXTENDED_STATISTICS
4723    privoxy_mutex_init(&filter_statistics_mutex);
4724    privoxy_mutex_init(&block_statistics_mutex);
4725 #endif
4726
4727    /*
4728     * XXX: The assumptions below are a bit naive
4729     * and can cause locks that aren't necessary.
4730     *
4731     * For example older FreeBSD versions (< 6.x?)
4732     * have no gethostbyname_r, but gethostbyname is
4733     * thread safe.
4734     */
4735 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
4736    privoxy_mutex_init(&resolver_mutex);
4737 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
4738    /*
4739     * XXX: should we use a single mutex for
4740     * localtime() and gmtime() as well?
4741     */
4742 #ifndef HAVE_GMTIME_R
4743    privoxy_mutex_init(&gmtime_mutex);
4744 #endif /* ndef HAVE_GMTIME_R */
4745
4746 #ifndef HAVE_LOCALTIME_R
4747    privoxy_mutex_init(&localtime_mutex);
4748 #endif /* ndef HAVE_GMTIME_R */
4749
4750 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
4751    privoxy_mutex_init(&rand_mutex);
4752 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
4753
4754 #endif /* def MUTEX_LOCKS_AVAILABLE */
4755 }
4756
4757 /*********************************************************************
4758  *
4759  * Function    :  main
4760  *
4761  * Description :  Load the config file and start the listen loop.
4762  *                This function is a lot more *sane* with the `load_config'
4763  *                and `listen_loop' functions; although it stills does
4764  *                a *little* too much for my taste.
4765  *
4766  * Parameters  :
4767  *          1  :  argc = Number of parameters (including $0).
4768  *          2  :  argv = Array of (char *)'s to the parameters.
4769  *
4770  * Returns     :  1 if : can't open config file, unrecognized directive,
4771  *                stats requested in multi-thread mode, can't open the
4772  *                log file, can't open the jar file, listen port is invalid,
4773  *                any load fails, and can't bind port.
4774  *
4775  *                Else main never returns, the process must be signaled
4776  *                to terminate execution.  Or, on Windows, use the
4777  *                "File", "Exit" menu option.
4778  *
4779  *********************************************************************/
4780 #ifdef __MINGW32__
4781 int real_main(int argc, char **argv)
4782 #else
4783 int main(int argc, char **argv)
4784 #endif
4785 {
4786    int argc_pos = 0;
4787    int do_config_test = 0;
4788 #ifndef HAVE_ARC4RANDOM
4789    unsigned int random_seed;
4790 #endif
4791 #ifdef unix
4792    struct passwd *pw = NULL;
4793    struct group *grp = NULL;
4794    int do_chroot = 0;
4795    char *pre_chroot_nslookup_to_load_resolver = NULL;
4796 #endif
4797 #ifdef FUZZ
4798    char *fuzz_input_type = NULL;
4799    char *fuzz_input_file = NULL;
4800 #endif
4801
4802    Argc = argc;
4803    Argv = argv;
4804
4805    configfile =
4806 #if !defined(_WIN32)
4807    "config"
4808 #else
4809    "config.txt"
4810 #endif
4811       ;
4812
4813    /* Prepare mutexes if supported and necessary. */
4814    initialize_mutexes();
4815
4816    /* Enable logging until further notice. */
4817    init_log_module();
4818
4819    /*
4820     * Parse the command line arguments
4821     *
4822     * XXX: simply printing usage information in case of
4823     * invalid arguments isn't particularly user friendly.
4824     */
4825    while (++argc_pos < argc)
4826    {
4827 #ifdef _WIN32
4828       /* Check to see if the service must be installed or uninstalled */
4829       if (strncmp(argv[argc_pos], "--install", 9) == 0)
4830       {
4831          const char *pName = argv[argc_pos] + 9;
4832          if (*pName == ':')
4833             pName++;
4834          exit((install_service(pName)) ? 0 : 1);
4835       }
4836       else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
4837       {
4838          const char *pName = argv[argc_pos] + 11;
4839          if (*pName == ':')
4840             pName++;
4841          exit((uninstall_service(pName)) ? 0 : 1);
4842       }
4843       else if (strcmp(argv[argc_pos], "--service") == 0)
4844       {
4845          bRunAsService = TRUE;
4846          w32_set_service_cwd();
4847          atexit(w32_service_exit_notify);
4848       }
4849       else
4850 #endif /* defined(_WIN32) */
4851
4852
4853 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4854
4855       if (strcmp(argv[argc_pos], "--help") == 0)
4856       {
4857          usage(argv[0]);
4858       }
4859
4860       else if (strcmp(argv[argc_pos], "--version") == 0)
4861       {
4862          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
4863          exit(0);
4864       }
4865
4866 #if defined(unix)
4867
4868       else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
4869       {
4870          set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
4871          daemon_mode = 0;
4872       }
4873
4874       else if (strcmp(argv[argc_pos], "--pidfile") == 0)
4875       {
4876          if (++argc_pos == argc) usage(argv[0]);
4877          pidfile = strdup_or_die(argv[argc_pos]);
4878       }
4879
4880       else if (strcmp(argv[argc_pos], "--user") == 0)
4881       {
4882          char *user_arg;
4883          char *group_name;
4884
4885          if (++argc_pos == argc) usage(argv[argc_pos]);
4886
4887          user_arg = strdup_or_die(argv[argc_pos]);
4888          group_name = strchr(user_arg, '.');
4889          if (NULL != group_name)
4890          {
4891             /* Nul-terminate the user name */
4892             *group_name = '\0';
4893
4894             /* Skip the former delimiter to actually reach the group name */
4895             group_name++;
4896
4897             grp = getgrnam(group_name);
4898             if (NULL == grp)
4899             {
4900                log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
4901             }
4902          }
4903          pw = getpwnam(user_arg);
4904          if (NULL == pw)
4905          {
4906             log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
4907          }
4908
4909          freez(user_arg);
4910       }
4911
4912       else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
4913       {
4914          if (++argc_pos == argc) usage(argv[0]);
4915          pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
4916       }
4917
4918       else if (strcmp(argv[argc_pos], "--chroot") == 0)
4919       {
4920          do_chroot = 1;
4921       }
4922 #endif /* defined(unix) */
4923
4924       else if (strcmp(argv[argc_pos], "--config-test") == 0)
4925       {
4926          do_config_test = 1;
4927       }
4928 #ifdef FUZZ
4929       else if (strcmp(argv[argc_pos], "--fuzz") == 0)
4930       {
4931          argc_pos++;
4932          if (argc < argc_pos + 2) usage(argv[0]);
4933          fuzz_input_type = argv[argc_pos];
4934          argc_pos++;
4935          fuzz_input_file = argv[argc_pos];
4936       }
4937       else if (strcmp(argv[argc_pos], "--stfu") == 0)
4938       {
4939          set_debug_level(LOG_LEVEL_STFU);
4940       }
4941 #endif
4942       else if (argc_pos + 1 != argc)
4943       {
4944          /*
4945           * This is neither the last command line
4946           * option, nor was it recognized before,
4947           * therefore it must be invalid.
4948           */
4949          usage(argv[0]);
4950       }
4951       else
4952
4953 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
4954       {
4955          configfile = argv[argc_pos];
4956       }
4957
4958    } /* -END- while (more arguments) */
4959
4960    show_version(Argv[0]);
4961
4962 #if defined(unix)
4963    if (*configfile != '/')
4964    {
4965       char cwd[BUFFER_SIZE];
4966       char *abs_file;
4967       size_t abs_file_size;
4968
4969       /* make config-filename absolute here */
4970       if (NULL == getcwd(cwd, sizeof(cwd)))
4971       {
4972          perror("failed to get current working directory");
4973          exit(1);
4974       }
4975
4976       basedir = strdup_or_die(cwd);
4977       /* XXX: why + 5? */
4978       abs_file_size = strlen(cwd) + strlen(configfile) + 5;
4979       abs_file = malloc_or_die(abs_file_size);
4980       strlcpy(abs_file, basedir, abs_file_size);
4981       strlcat(abs_file, "/", abs_file_size);
4982       strlcat(abs_file, configfile, abs_file_size);
4983       configfile = abs_file;
4984    }
4985 #endif /* defined unix */
4986
4987
4988    files->next = NULL;
4989    clients->next = NULL;
4990
4991    /* XXX: factor out initialising after the next stable release. */
4992 #ifdef _WIN32
4993    InitWin32();
4994 #endif
4995
4996 #ifndef HAVE_ARC4RANDOM
4997    random_seed = (unsigned int)time(NULL);
4998 #ifdef HAVE_RANDOM
4999    srandom(random_seed);
5000 #else
5001    srand(random_seed);
5002 #endif /* ifdef HAVE_RANDOM */
5003 #endif /* ifndef HAVE_ARC4RANDOM */
5004
5005    /*
5006     * Unix signal handling
5007     *
5008     * Catch the abort, interrupt and terminate signals for a graceful exit
5009     * Catch the hangup signal so the errlog can be reopened.
5010     *
5011     * Ignore the broken pipe signal as connection failures
5012     * are handled when and where they occur without relying
5013     * on a signal.
5014     */
5015 #if !defined(_WIN32) && !defined(__OS2__)
5016 {
5017    int idx;
5018    const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5019
5020    for (idx = 0; idx < SZ(catched_signals); idx++)
5021    {
5022 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5023       if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5024 #else
5025       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5026 #endif /* ifdef sun */
5027       {
5028          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5029       }
5030    }
5031
5032    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5033    {
5034       log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5035    }
5036
5037 }
5038 #else /* ifdef _WIN32 */
5039 # ifdef _WIN_CONSOLE
5040    /*
5041     * We *are* in a windows console app.
5042     * Print a verbose messages about FAQ's and such
5043     */
5044    printf("%s", win32_blurb);
5045 # endif /* def _WIN_CONSOLE */
5046 #endif /* def _WIN32 */
5047
5048 #ifdef FUZZ
5049    if (fuzz_input_type != NULL)
5050    {
5051       exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5052    }
5053    log_error(LOG_LEVEL_FATAL,
5054       "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5055       "Various data structures are static which is unsafe when using threads.");
5056 #endif
5057
5058    if (do_config_test)
5059    {
5060       exit(NULL == load_config());
5061    }
5062
5063    /* Initialize the CGI subsystem */
5064    cgi_init_error_messages();
5065
5066    /*
5067     * If running on unix and without the --no-daemon
5068     * option, become a daemon. I.e. fork, detach
5069     * from tty and get process group leadership
5070     */
5071 #if defined(unix)
5072 {
5073    if (daemon_mode)
5074    {
5075       int fd;
5076       pid_t pid = fork();
5077
5078       if (pid < 0) /* error */
5079       {
5080          perror("fork");
5081          exit(3);
5082       }
5083       else if (pid != 0) /* parent */
5084       {
5085          int status;
5086          pid_t wpid;
5087          /*
5088           * must check for errors
5089           * child died due to missing files aso
5090           */
5091          sleep(1);
5092          wpid = waitpid(pid, &status, WNOHANG);
5093          if (wpid != 0)
5094          {
5095             exit(1);
5096          }
5097          exit(0);
5098       }
5099       /* child */
5100
5101       setsid();
5102
5103       /*
5104        * stderr (fd 2) will be closed later on,
5105        * when the config file has been parsed.
5106        */
5107       close(0);
5108       close(1);
5109
5110       /*
5111        * Reserve fd 0 and 1 to prevent abort() and friends
5112        * from sending stuff to the clients or servers.
5113        */
5114       fd = open("/dev/null", O_RDONLY);
5115       if (fd == -1)
5116       {
5117          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5118       }
5119       else if (fd != 0)
5120       {
5121          if (dup2(fd, 0) == -1)
5122          {
5123             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5124          }
5125          close(fd);
5126       }
5127       fd = open("/dev/null", O_WRONLY);
5128       if (fd == -1)
5129       {
5130          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5131       }
5132       else if (fd != 1)
5133       {
5134          if (dup2(fd, 1) == -1)
5135          {
5136             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5137          }
5138          close(fd);
5139       }
5140
5141 #ifdef FEATURE_EXTERNAL_FILTERS
5142       for (fd = 0; fd < 3; fd++)
5143       {
5144          mark_socket_for_close_on_execute(fd);
5145       }
5146 #endif
5147
5148       chdir("/");
5149
5150    } /* -END- if (daemon_mode) */
5151
5152    /*
5153     * As soon as we have written the PID file, we can switch
5154     * to the user and group ID indicated by the --user option
5155     */
5156    if (pidfile != NULL)
5157    {
5158       write_pid_file(pidfile);
5159    }
5160    if (NULL != pw)
5161    {
5162       if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5163       {
5164          log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5165       }
5166       if (NULL != grp)
5167       {
5168          if (setgroups(1, &grp->gr_gid))
5169          {
5170             log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5171          }
5172       }
5173       else if (initgroups(pw->pw_name, pw->pw_gid))
5174       {
5175          log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5176       }
5177       if (do_chroot)
5178       {
5179          if (!pw->pw_dir)
5180          {
5181             log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5182          }
5183          /* Read the time zone file from /etc before doing chroot. */
5184          tzset();
5185          if (NULL != pre_chroot_nslookup_to_load_resolver
5186              && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5187          {
5188             /* Initialize resolver library. */
5189             (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5190          }
5191          if (chroot(pw->pw_dir) < 0)
5192          {
5193             log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5194          }
5195          if (chdir ("/"))
5196          {
5197             log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5198          }
5199       }
5200       if (setuid(pw->pw_uid))
5201       {
5202          log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5203       }
5204       if (do_chroot)
5205       {
5206          char putenv_dummy[64];
5207
5208          strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5209          if (putenv(putenv_dummy) != 0)
5210          {
5211             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5212          }
5213
5214          snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5215          if (putenv(putenv_dummy) != 0)
5216          {
5217             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5218          }
5219       }
5220    }
5221    else if (do_chroot)
5222    {
5223       log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5224    }
5225 }
5226 #endif /* defined unix */
5227
5228 #ifdef _WIN32
5229    /* This will be FALSE unless the command line specified --service
5230     */
5231    if (bRunAsService)
5232    {
5233       /* Yup, so now we must attempt to establish a connection
5234        * with the service dispatcher. This will only work if this
5235        * process was launched by the service control manager to
5236        * actually run as a service. If this isn't the case, i've
5237        * known it take around 30 seconds or so for the call to return.
5238        */
5239
5240       /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5241       if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5242       {
5243          /* Service has run, and at this point is now being stopped, so just return */
5244          return 0;
5245       }
5246
5247 #ifdef _WIN_CONSOLE
5248       printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5249 #endif
5250       /* An error occurred. Usually it's because --service was wrongly specified
5251        * and we were unable to connect to the Service Control Dispatcher because
5252        * it wasn't expecting us and is therefore not listening.
5253        *
5254        * For now, just continue below to call the listen_loop function.
5255        */
5256    }
5257 #endif /* def _WIN32 */
5258
5259    listen_loop();
5260
5261    /* NOTREACHED */
5262    return(-1);
5263
5264 }
5265
5266
5267 /*********************************************************************
5268  *
5269  * Function    :  bind_port_helper
5270  *
5271  * Description :  Bind the listen port.  Handles logging, and aborts
5272  *                on failure.
5273  *
5274  * Parameters  :
5275  *          1  :  haddr = Host address to bind to. Use NULL to bind to
5276  *                        INADDR_ANY.
5277  *          2  :  hport = Specifies port to bind to.
5278  *          3  :  backlog = Listen backlog.
5279  *
5280  * Returns     :  Port that was opened.
5281  *
5282  *********************************************************************/
5283 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5284 {
5285    int result;
5286    jb_socket bfd;
5287
5288    result = bind_port(haddr, hport, backlog, &bfd);
5289
5290    if (result < 0)
5291    {
5292       const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5293       switch(result)
5294       {
5295          case -3:
5296             log_error(LOG_LEVEL_FATAL,
5297                "can't bind to %s:%d: There may be another Privoxy "
5298                "or some other proxy running on port %d",
5299                bind_address, hport, hport);
5300
5301          case -2:
5302             log_error(LOG_LEVEL_FATAL,
5303                "can't bind to %s:%d: The hostname is not resolvable",
5304                bind_address, hport);
5305
5306          default:
5307             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5308                bind_address, hport);
5309       }
5310
5311       /* shouldn't get here */
5312       return JB_INVALID_SOCKET;
5313    }
5314
5315 #ifndef HAVE_POLL
5316 #ifndef _WIN32
5317    if (bfd >= FD_SETSIZE)
5318    {
5319       log_error(LOG_LEVEL_FATAL,
5320          "Bind socket number too high to use select(): %d >= %d",
5321          bfd, FD_SETSIZE);
5322    }
5323 #endif
5324 #endif
5325
5326    if (haddr == NULL)
5327    {
5328       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5329          hport);
5330    }
5331    else
5332    {
5333       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5334          hport, haddr);
5335    }
5336
5337    return bfd;
5338 }
5339
5340
5341 /*********************************************************************
5342  *
5343  * Function    :  bind_ports_helper
5344  *
5345  * Description :  Bind the listen ports.  Handles logging, and aborts
5346  *                on failure.
5347  *
5348  * Parameters  :
5349  *          1  :  config = Privoxy configuration.  Specifies ports
5350  *                         to bind to.
5351  *          2  :  sockets = Preallocated array of opened sockets
5352  *                          corresponding to specification in config.
5353  *                          All non-opened sockets will be set to
5354  *                          JB_INVALID_SOCKET.
5355  *
5356  * Returns     :  Nothing. Inspect sockets argument.
5357  *
5358  *********************************************************************/
5359 static void bind_ports_helper(struct configuration_spec * config,
5360                               jb_socket sockets[])
5361 {
5362    int i;
5363
5364    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5365    {
5366       if (config->hport[i])
5367       {
5368          sockets[i] = bind_port_helper(config->haddr[i],
5369             config->hport[i], config->listen_backlog);
5370 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5371          if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5372          {
5373             struct accept_filter_arg af_options;
5374             bzero(&af_options, sizeof(af_options));
5375             strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5376             if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5377                   sizeof(af_options)))
5378             {
5379                log_error(LOG_LEVEL_ERROR,
5380                   "Enabling accept filter for socket %d failed: %E", sockets[i]);
5381             }
5382          }
5383 #endif
5384       }
5385       else
5386       {
5387          sockets[i] = JB_INVALID_SOCKET;
5388       }
5389    }
5390    config->need_bind = 0;
5391 }
5392
5393
5394 /*********************************************************************
5395  *
5396  * Function    :  close_ports_helper
5397  *
5398  * Description :  Close listenings ports.
5399  *
5400  * Parameters  :
5401  *          1  :  sockets = Array of opened and non-opened sockets to
5402  *                          close. All sockets will be set to
5403  *                          JB_INVALID_SOCKET.
5404  *
5405  * Returns     :  Nothing.
5406  *
5407  *********************************************************************/
5408 static void close_ports_helper(jb_socket sockets[])
5409 {
5410    int i;
5411
5412    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5413    {
5414       if (JB_INVALID_SOCKET != sockets[i])
5415       {
5416          close_socket(sockets[i]);
5417       }
5418       sockets[i] = JB_INVALID_SOCKET;
5419    }
5420 }
5421
5422
5423 #ifdef _WIN32
5424 /* Without this simple workaround we get this compiler warning from _beginthread
5425  *     warning C4028: formal parameter 1 different from declaration
5426  */
5427 void w32_service_listen_loop(void *p)
5428 {
5429    listen_loop();
5430 }
5431 #endif /* def _WIN32 */
5432
5433
5434 /*********************************************************************
5435  *
5436  * Function    :  listen_loop
5437  *
5438  * Description :  bind the listen port and enter a "FOREVER" listening loop.
5439  *
5440  * Parameters  :  N/A
5441  *
5442  * Returns     :  Never.
5443  *
5444  *********************************************************************/
5445 static void listen_loop(void)
5446 {
5447    struct client_states *csp_list = NULL;
5448    struct client_state *csp = NULL;
5449    jb_socket bfds[MAX_LISTENING_SOCKETS];
5450    struct configuration_spec *config;
5451    unsigned int active_threads = 0;
5452 #if defined(FEATURE_PTHREAD)
5453    pthread_attr_t attrs;
5454
5455    pthread_attr_init(&attrs);
5456    pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5457 #endif
5458
5459    config = load_config();
5460
5461 #ifdef FEATURE_CONNECTION_SHARING
5462    /*
5463     * XXX: Should be relocated once it no
5464     * longer needs to emit log messages.
5465     */
5466    initialize_reusable_connections();
5467 #endif /* def FEATURE_CONNECTION_SHARING */
5468
5469    bind_ports_helper(config, bfds);
5470
5471 #ifdef FEATURE_GRACEFUL_TERMINATION
5472    while (!g_terminate)
5473 #else
5474    for (;;)
5475 #endif
5476    {
5477 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
5478       while (waitpid(-1, NULL, WNOHANG) > 0)
5479       {
5480          /* zombie children */
5481       }
5482 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5483
5484       /*
5485        * Free data that was used by died threads
5486        */
5487       active_threads = sweep();
5488
5489 #if defined(unix)
5490       /*
5491        * Re-open the errlog after HUP signal
5492        */
5493       if (received_hup_signal)
5494       {
5495          if (NULL != config->logfile)
5496          {
5497             init_error_log(Argv[0], config->logfile);
5498          }
5499          received_hup_signal = 0;
5500       }
5501 #endif
5502
5503       csp_list = zalloc_or_die(sizeof(*csp_list));
5504       csp = &csp_list->csp;
5505
5506       log_error(LOG_LEVEL_CONNECT,
5507          "Waiting for the next client connection. Currently active threads: %d",
5508          active_threads);
5509
5510       /*
5511        * This config may be outdated, but for accept_connection()
5512        * it's fresh enough.
5513        */
5514       csp->config = config;
5515
5516       if (!accept_connection(csp, bfds))
5517       {
5518          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5519          freez(csp_list);
5520          continue;
5521       }
5522
5523       csp->flags |= CSP_FLAG_ACTIVE;
5524       csp->server_connection.sfd = JB_INVALID_SOCKET;
5525
5526       csp->config = config = load_config();
5527
5528       if (config->need_bind)
5529       {
5530          /*
5531           * Since we were listening to the "old port", we will not see
5532           * a "listen" param change until the next request.  So, at
5533           * least 1 more request must be made for us to find the new
5534           * setting.  I am simply closing the old socket and binding the
5535           * new one.
5536           *
5537           * Which-ever is correct, we will serve 1 more page via the
5538           * old settings.  This should probably be a "show-status"
5539           * request.  This should not be a so common of an operation
5540           * that this will hurt people's feelings.
5541           */
5542
5543          close_ports_helper(bfds);
5544
5545          bind_ports_helper(config, bfds);
5546       }
5547
5548 #ifdef FEATURE_TOGGLE
5549       if (global_toggle_state)
5550 #endif /* def FEATURE_TOGGLE */
5551       {
5552          csp->flags |= CSP_FLAG_TOGGLED_ON;
5553       }
5554
5555       if (run_loader(csp))
5556       {
5557          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5558          /* Never get here - LOG_LEVEL_FATAL causes program exit */
5559       }
5560
5561 #ifdef FEATURE_ACL
5562       if (block_acl(NULL,csp))
5563       {
5564          log_error(LOG_LEVEL_CONNECT,
5565             "Connection from %s on %s (socket %d) dropped due to ACL",
5566             csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5567          close_socket(csp->cfd);
5568          freez(csp->ip_addr_str);
5569          freez(csp->listen_addr_str);
5570          freez(csp_list);
5571          continue;
5572       }
5573 #endif /* def FEATURE_ACL */
5574
5575       if ((0 != config->max_client_connections)
5576          && (active_threads >= config->max_client_connections))
5577       {
5578          log_error(LOG_LEVEL_CONNECT,
5579             "Rejecting connection from %s. Maximum number of connections reached.",
5580             csp->ip_addr_str);
5581          write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5582             strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5583          close_socket(csp->cfd);
5584          freez(csp->ip_addr_str);
5585          freez(csp->listen_addr_str);
5586          freez(csp_list);
5587          continue;
5588       }
5589
5590       /* add it to the list of clients */
5591       csp_list->next = clients->next;
5592       clients->next = csp_list;
5593
5594       if (config->multi_threaded)
5595       {
5596          int child_id;
5597
5598 /* this is a switch () statement in the C preprocessor - ugh */
5599 #undef SELECTED_ONE_OPTION
5600
5601 /* Use Pthreads in preference to native code */
5602 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
5603 #define SELECTED_ONE_OPTION
5604          {
5605             pthread_t the_thread;
5606             int ret;
5607
5608             ret = pthread_create(&the_thread, &attrs,
5609                (void * (*)(void *))serve, csp);
5610             child_id = ret ? -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 */