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