Add test scenario client-body-filter
[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-2023 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    if (get_bytes_missing_from_chunked_data(csp->iob->cur, size, 0) == 0)
1657    {
1658       if (CHUNK_STATUS_BODY_COMPLETE != status)
1659       {
1660          log_error(LOG_LEVEL_ERROR,
1661             "There's disagreement about whether or not the chunked body is complete.");
1662       }
1663    }
1664
1665    return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1666
1667 }
1668
1669
1670 /*********************************************************************
1671  *
1672  * Function    : fuzz_client_request
1673  *
1674  * Description : Try to get a client request from the fuzzed input.
1675  *
1676  * Parameters  :
1677  *          1  :  csp = Current client state (buffers, headers, etc...)
1678  *          2  :  fuzz_input_file = File to read the input from.
1679  *
1680  * Returns     :  Result of fuzzing.
1681  *
1682  *********************************************************************/
1683 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1684 {
1685    jb_err err;
1686
1687    csp->cfd = 0;
1688    csp->ip_addr_str = "fuzzer";
1689
1690    if (strcmp(fuzz_input_file, "-") != 0)
1691    {
1692       log_error(LOG_LEVEL_FATAL,
1693          "Fuzzed client requests can currently only be read from stdin (-).");
1694    }
1695    err = receive_client_request(csp);
1696    if (err != JB_ERR_OK)
1697    {
1698       return 1;
1699    }
1700    err = parse_client_request(csp);
1701    if (err != JB_ERR_OK)
1702    {
1703       return 1;
1704    }
1705
1706    return 0;
1707
1708 }
1709 #endif  /* def FUZZ */
1710
1711
1712 #ifdef FEATURE_FORCE_LOAD
1713 /*********************************************************************
1714  *
1715  * Function    :  force_required
1716  *
1717  * Description : Checks a request line to see if it contains
1718  *               the FORCE_PREFIX. If it does, it is removed
1719  *               unless enforcing requests has beend disabled.
1720  *
1721  * Parameters  :
1722  *          1  :  request_line = HTTP request line
1723  *
1724  * Returns     :  TRUE if force is required, FALSE otherwise.
1725  *
1726  *********************************************************************/
1727 static int force_required(const struct client_state *csp, char *request_line)
1728 {
1729    char *p;
1730
1731    p = strstr(request_line, "http://");
1732    if (p != NULL)
1733    {
1734       /* Skip protocol */
1735       p += strlen("http://");
1736    }
1737    else
1738    {
1739       /* Intercepted request usually don't specify the protocol. */
1740       p = request_line;
1741    }
1742
1743    /* Go to the beginning of the path */
1744    p = strstr(p, "/");
1745    if (p == NULL)
1746    {
1747       /*
1748        * If the path is missing the request line is invalid and we
1749        * are done here. The client-visible rejection happens later on.
1750        */
1751       return 0;
1752    }
1753
1754    if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1755    {
1756       if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1757       {
1758          /* XXX: Should clean more carefully */
1759          strclean(request_line, FORCE_PREFIX);
1760          log_error(LOG_LEVEL_FORCE,
1761             "Enforcing request: \"%s\".", request_line);
1762
1763          return 1;
1764       }
1765       log_error(LOG_LEVEL_FORCE,
1766          "Ignored force prefix in request: \"%s\".", request_line);
1767    }
1768
1769    return 0;
1770
1771 }
1772 #endif /* def FEATURE_FORCE_LOAD */
1773
1774
1775 /*********************************************************************
1776  *
1777  * Function    :  receive_client_request
1778  *
1779  * Description : Read the client's request (more precisely the
1780  *               client headers) and answer it if necessary.
1781  *
1782  * Parameters  :
1783  *          1  :  csp = Current client state (buffers, headers, etc...)
1784  *
1785  * Returns     :  JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1786  *
1787  *********************************************************************/
1788 static jb_err receive_client_request(struct client_state *csp)
1789 {
1790    char buf[BUFFER_SIZE];
1791    char *p;
1792    char *req = NULL;
1793    struct http_request *http;
1794    int len;
1795    jb_err err;
1796
1797    /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1798    struct list header_list;
1799    struct list *headers = &header_list;
1800
1801    /* We don't care if the arriving data is a valid HTTP request or not. */
1802    csp->requests_received_total++;
1803
1804    http = csp->http;
1805
1806    memset(buf, 0, sizeof(buf));
1807
1808    req = get_request_line(csp);
1809    if (req == NULL)
1810    {
1811       mark_server_socket_tainted(csp);
1812       return JB_ERR_PARSE;
1813    }
1814    assert(*req != '\0');
1815
1816    if (client_protocol_is_unsupported(csp, req))
1817    {
1818       return JB_ERR_PARSE;
1819    }
1820
1821 #ifdef FEATURE_FORCE_LOAD
1822    if (force_required(csp, req))
1823    {
1824       csp->flags |= CSP_FLAG_FORCED;
1825    }
1826 #endif /* def FEATURE_FORCE_LOAD */
1827
1828    err = parse_http_request(req, http);
1829    freez(req);
1830    if (JB_ERR_OK != err)
1831    {
1832       write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1833          get_write_delay(csp));
1834       /* XXX: Use correct size */
1835       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1836       log_error(LOG_LEVEL_ERROR,
1837          "Couldn't parse request line received from %s: %s",
1838          csp->ip_addr_str, jb_err_to_string(err));
1839
1840       free_http_request(http);
1841       return JB_ERR_PARSE;
1842    }
1843    if (http->ssl && strcmpic(http->gpc, "CONNECT"))
1844    {
1845       write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1846          get_write_delay(csp));
1847       /* XXX: Use correct size */
1848       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0",
1849          csp->ip_addr_str);
1850       log_error(LOG_LEVEL_ERROR, "Client %s tried to send a https "
1851          "URL without sending a CONNECT request first",
1852          csp->ip_addr_str);
1853       free_http_request(http);
1854       return JB_ERR_PARSE;
1855    }
1856
1857    /* grab the rest of the client's headers */
1858    init_list(headers);
1859    for (;;)
1860    {
1861       p = get_header(csp->client_iob);
1862
1863       if (p == NULL)
1864       {
1865          /* There are no additional headers to read. */
1866          break;
1867       }
1868
1869       if (*p == '\0')
1870       {
1871          /*
1872           * We didn't receive a complete header
1873           * line yet, get the rest of it.
1874           */
1875          if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1876          {
1877             log_error(LOG_LEVEL_ERROR,
1878                "Client headers did not arrive in time. Timeout: %d",
1879                csp->config->socket_timeout);
1880             destroy_list(headers);
1881             return JB_ERR_PARSE;
1882          }
1883
1884          len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1885          if (len <= 0)
1886          {
1887             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1888             destroy_list(headers);
1889             return JB_ERR_PARSE;
1890          }
1891
1892          if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1893          {
1894             /*
1895              * If there is no memory left for buffering the
1896              * request, there is nothing we can do but hang up
1897              */
1898             destroy_list(headers);
1899             return JB_ERR_MEMORY;
1900          }
1901       }
1902       else
1903       {
1904          if (!strncmpic(p, "Transfer-Encoding:", 18))
1905          {
1906             /*
1907              * XXX: should be called through sed()
1908              *      but currently can't.
1909              */
1910             client_transfer_encoding(csp, &p);
1911          }
1912          /*
1913           * We were able to read a complete
1914           * header and can finally enlist it.
1915           */
1916          enlist(headers, p);
1917          freez(p);
1918       }
1919    }
1920
1921    if (http->host == NULL)
1922    {
1923       /*
1924        * If we still don't know the request destination,
1925        * the request is invalid or the client uses
1926        * Privoxy without its knowledge.
1927        */
1928       if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1929       {
1930          /*
1931           * Our attempts to get the request destination
1932           * elsewhere failed or Privoxy is configured
1933           * to only accept proxy requests.
1934           *
1935           * An error response has already been sent
1936           * and we're done here.
1937           */
1938          return JB_ERR_PARSE;
1939       }
1940    }
1941
1942 #ifdef FEATURE_CLIENT_TAGS
1943    /* XXX: If the headers were enlisted sooner, passing csp would do. */
1944    set_client_address(csp, headers);
1945    get_tag_list_for_client(csp->client_tags, csp->client_address);
1946 #endif
1947
1948    /*
1949     * Determine the actions for this URL
1950     */
1951 #ifdef FEATURE_TOGGLE
1952    if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1953    {
1954       /* Most compatible set of actions (i.e. none) */
1955       init_current_action(csp->action);
1956    }
1957    else
1958 #endif /* ndef FEATURE_TOGGLE */
1959    {
1960       get_url_actions(csp, http);
1961    }
1962
1963    enlist(csp->headers, http->cmd);
1964
1965    /* Append the previously read headers */
1966    err = list_append_list_unique(csp->headers, headers);
1967    destroy_list(headers);
1968
1969    return err;
1970
1971 }
1972
1973
1974 /*********************************************************************
1975  *
1976  * Function    : parse_client_request
1977  *
1978  * Description : Parses the client's request and decides what to do
1979  *               with it.
1980  *
1981  *               Note that since we're not using select() we could get
1982  *               blocked here if a client connected, then didn't say
1983  *               anything!
1984  *
1985  * Parameters  :
1986  *          1  :  csp = Current client state (buffers, headers, etc...)
1987  *
1988  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1989  *
1990  *********************************************************************/
1991 static jb_err parse_client_request(struct client_state *csp)
1992 {
1993    struct http_request *http = csp->http;
1994    jb_err err;
1995
1996 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1997    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1998     && (!strcmpic(csp->http->version, "HTTP/1.1"))
1999     && (csp->http->ssl == 0))
2000    {
2001       /* Assume persistence until further notice */
2002       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2003    }
2004 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2005
2006    if (csp->http->ssl == 0)
2007    {
2008       /*
2009        * This whole block belongs to chat() but currently
2010        * has to be executed before sed().
2011        */
2012       if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
2013       {
2014          if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
2015          {
2016             return JB_ERR_PARSE;
2017          }
2018       }
2019       else
2020       {
2021          csp->expected_client_content_length = get_expected_content_length(csp->headers);
2022       }
2023       verify_request_length(csp);
2024    }
2025 #ifndef FEATURE_HTTPS_INSPECTION
2026    else
2027    {
2028       csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
2029    }
2030 #endif
2031
2032    err = sed(csp, FILTER_CLIENT_HEADERS);
2033    if (JB_ERR_OK != err)
2034    {
2035       log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2036          csp->ip_addr_str);
2037       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2038          csp->ip_addr_str, csp->http->cmd);
2039       write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
2040       return JB_ERR_PARSE;
2041    }
2042    csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
2043
2044    /* Check request line for rewrites. */
2045    if ((NULL == csp->headers->first->str)
2046       || (strcmp(http->cmd, csp->headers->first->str) &&
2047          (JB_ERR_OK != change_request_destination(csp))))
2048    {
2049       /*
2050        * A header filter broke the request line - bail out.
2051        */
2052       write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
2053          strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2054       /* XXX: Use correct size */
2055       log_error(LOG_LEVEL_CLF,
2056          "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2057       log_error(LOG_LEVEL_ERROR,
2058          "Invalid request line after applying header filters.");
2059       free_http_request(http);
2060
2061       return JB_ERR_PARSE;
2062    }
2063
2064    if (client_has_unsupported_expectations(csp))
2065    {
2066       return JB_ERR_PARSE;
2067    }
2068
2069    return JB_ERR_OK;
2070
2071 }
2072
2073
2074 /*********************************************************************
2075  *
2076  * Function    : read_http_request_body
2077  *
2078  * Description : Reads remaining request body from the client.
2079  *
2080  * Parameters  :
2081  *          1  :  csp = Current client state (buffers, headers, etc...)
2082  *
2083  * Returns     :  0 on success, anything else is an error.
2084  *
2085  *********************************************************************/
2086 static int read_http_request_body(struct client_state *csp)
2087 {
2088    size_t to_read = csp->expected_client_content_length;
2089    int len;
2090
2091    assert(to_read != 0);
2092
2093    /* check if all data has been already read */
2094    if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2095    {
2096       return 0;
2097    }
2098
2099    for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2100         to_read > 0 && data_is_available(csp->cfd, csp->config->socket_timeout);
2101         to_read -= (unsigned)len)
2102    {
2103       char buf[BUFFER_SIZE];
2104       size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2105
2106       log_error(LOG_LEVEL_CONNECT,
2107          "Waiting for up to %lu bytes of request body from the client.",
2108          max_bytes_to_read);
2109       len = read_socket(csp->cfd, buf, (int)max_bytes_to_read);
2110       if (len <= -1)
2111       {
2112          log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s: %E", csp->ip_addr_str);
2113          return 1;
2114       }
2115       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2116       {
2117          return 1;
2118       }
2119       assert(to_read >= len);
2120    }
2121
2122    if (to_read != 0)
2123    {
2124       log_error(LOG_LEVEL_CONNECT,
2125          "Not enough request body has been read: expected %lu more bytes.",
2126          to_read);
2127       return 1;
2128    }
2129    log_error(LOG_LEVEL_CONNECT,
2130       "The last %d bytes of the request body have been read.", len);
2131    return 0;
2132 }
2133
2134
2135 /*********************************************************************
2136  *
2137  * Function    : update_client_headers
2138  *
2139  * Description : Updates the HTTP headers from the client request.
2140  *
2141  * Parameters  :
2142  *          1  :  csp = Current client state (buffers, headers, etc...)
2143  *          2  :  new_content_length = new content length value to set
2144  *
2145  * Returns     :  0 on success, anything else is an error.
2146  *
2147  *********************************************************************/
2148 static int update_client_headers(struct client_state *csp, size_t new_content_length)
2149 {
2150    static const char content_length[] = "Content-Length:";
2151    int updated = 0;
2152    struct list_entry *p;
2153
2154 #ifndef FEATURE_HTTPS_INSPECTION
2155    for (p = csp->headers->first;
2156 #else
2157    for (p = csp->http->client_ssl ? csp->https_headers->first : csp->headers->first;
2158 #endif
2159         !updated  && (p != NULL); p = p->next)
2160    {
2161       /* Header crunch()ed in previous run? -> ignore */
2162       if (p->str == NULL)
2163       {
2164          continue;
2165       }
2166
2167       /* Does the current parser handle this header? */
2168       if (0 == strncmpic(p->str, content_length, sizeof(content_length) - 1))
2169       {
2170          updated = (JB_ERR_OK == header_adjust_content_length((char **)&(p->str), new_content_length));
2171          if (!updated)
2172          {
2173             return 1;
2174          }
2175       }
2176    }
2177
2178    return !updated;
2179 }
2180
2181
2182 /*********************************************************************
2183  *
2184  * Function    : can_buffer_request_body
2185  *
2186  * Description : Checks if the current request body can be stored in
2187  *               the client_iob without hitting buffer limit.
2188  *
2189  * Parameters  :
2190  *          1  : csp = Current client state (buffers, headers, etc...)
2191  *
2192  * Returns     : TRUE if the current request size do not exceed buffer limit
2193  *               FALSE otherwise.
2194  *
2195  *********************************************************************/
2196 static int can_buffer_request_body(const struct client_state *csp)
2197 {
2198    if (!can_add_to_iob(csp->client_iob, csp->config->buffer_limit,
2199                        csp->expected_client_content_length))
2200    {
2201       log_error(LOG_LEVEL_INFO,
2202          "Not filtering request body from %s: buffer limit %lu will be exceeded "
2203          "(content length %llu)", csp->ip_addr_str, csp->config->buffer_limit,
2204          csp->expected_client_content_length);
2205       return FALSE;
2206    }
2207    return TRUE;
2208 }
2209
2210
2211 /*********************************************************************
2212  *
2213  * Function    : send_http_request
2214  *
2215  * Description : Sends the HTTP headers from the client request
2216  *               and all the body data that has already been received.
2217  *
2218  * Parameters  :
2219  *          1  :  csp = Current client state (buffers, headers, etc...)
2220  *
2221  * Returns     :  0 on success, 1 on error, 2 if the request got crunched.
2222  *
2223  *********************************************************************/
2224 static int send_http_request(struct client_state *csp)
2225 {
2226    char *hdr;
2227    int write_failure;
2228
2229    hdr = list_to_text(csp->headers);
2230    if (hdr == NULL)
2231    {
2232       /* FIXME Should handle error properly */
2233       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2234    }
2235    list_remove_all(csp->headers);
2236
2237    /*
2238     * Write the client's (modified) header to the server
2239     * (along with anything else that may be in the buffer)
2240     */
2241    write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2242    freez(hdr);
2243
2244    if (write_failure)
2245    {
2246       log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2247          csp->http->hostport);
2248       return 1;
2249    }
2250
2251    /* XXX: Filtered data is not sent if there's a pipelined request? */
2252    if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2253       && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2254    {
2255       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2256          csp->http->hostport);
2257       return 1;
2258    }
2259    return 0;
2260 }
2261
2262
2263 #ifdef FEATURE_HTTPS_INSPECTION
2264 /*********************************************************************
2265  *
2266  * Function    : read_https_request_body
2267  *
2268  * Description : Reads remaining request body from the client.
2269  *
2270  * Parameters  :
2271  *          1  :  csp = Current client state (buffers, headers, etc...)
2272  *
2273  * Returns     :  0 on success, anything else is an error.
2274  *
2275  *********************************************************************/
2276 static int read_https_request_body(struct client_state *csp)
2277 {
2278    size_t to_read = csp->expected_client_content_length;
2279    int len;
2280
2281    assert(to_read != 0);
2282
2283    /* check if all data has been already read */
2284    if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2285    {
2286       return 0;
2287    }
2288
2289    for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2290         to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2291           data_is_available(csp->cfd, csp->config->socket_timeout));
2292         to_read -= (unsigned)len)
2293    {
2294       unsigned char buf[BUFFER_SIZE];
2295       size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2296
2297       log_error(LOG_LEVEL_CONNECT,
2298          "Buffering encrypted client body. Prepared to read up to %lu bytes.",
2299          max_bytes_to_read);
2300       len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2301          (unsigned)max_bytes_to_read);
2302       if (len <= 0)
2303       {
2304          log_error(LOG_LEVEL_CONNECT,
2305             "Did not receive the whole encrypted request body from %s.",
2306             csp->ip_addr_str);
2307          return 1;
2308       }
2309       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2310       {
2311          return 1;
2312       }
2313       assert(to_read >= len);
2314    }
2315
2316    if (to_read != 0)
2317    {
2318       log_error(LOG_LEVEL_CONNECT,
2319          "Not enough encrypted request body has been read: expected %lu more bytes.",
2320          to_read);
2321       return 1;
2322    }
2323
2324    log_error(LOG_LEVEL_CONNECT,
2325       "The last %llu bytes of the encrypted request body have been read.",
2326       csp->expected_client_content_length);
2327    return 0;
2328 }
2329
2330
2331 /*********************************************************************
2332  *
2333  * Function    : receive_and_send_encrypted_post_data
2334  *
2335  * Description : Reads remaining request body from the client and sends
2336  *               it to the server.
2337  *
2338  * Parameters  :
2339  *          1  :  csp = Current client state (buffers, headers, etc...)
2340  *
2341  * Returns     :  0 on success, anything else is an error.
2342  *
2343  *********************************************************************/
2344 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2345 {
2346    int content_length_known = csp->expected_client_content_length != 0;
2347
2348    while (is_ssl_pending(&(csp->ssl_client_attr))
2349       || (content_length_known && csp->expected_client_content_length != 0))
2350    {
2351       unsigned char buf[BUFFER_SIZE];
2352       int len;
2353       int max_bytes_to_read = sizeof(buf);
2354
2355       if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2356       {
2357          max_bytes_to_read = (int)csp->expected_client_content_length;
2358       }
2359       log_error(LOG_LEVEL_CONNECT,
2360          "Prepared to read up to %d bytes of encrypted request body from the client.",
2361          max_bytes_to_read);
2362       len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2363          (unsigned)max_bytes_to_read);
2364       if (len == -1)
2365       {
2366          return 1;
2367       }
2368       if (len == 0)
2369       {
2370          /* XXX: Does this actually happen? */
2371          break;
2372       }
2373       log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body.",
2374          len);
2375       len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2376       if (len == -1)
2377       {
2378          return 1;
2379       }
2380       if (csp->expected_client_content_length != 0)
2381       {
2382          if (csp->expected_client_content_length >= len)
2383          {
2384             csp->expected_client_content_length -= (unsigned)len;
2385          }
2386          if (csp->expected_client_content_length == 0)
2387          {
2388             log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes.", len);
2389             break;
2390          }
2391       }
2392    }
2393
2394    log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body.");
2395
2396    return 0;
2397
2398 }
2399
2400
2401 /*********************************************************************
2402  *
2403  * Function    : send_https_request
2404  *
2405  * Description : Sends the HTTP headers from the client request
2406  *               and all the body data that has already been received.
2407  *
2408  * Parameters  :
2409  *          1  :  csp = Current client state (buffers, headers, etc...)
2410  *
2411  * Returns     :  0 on success, anything else is an error.
2412  *
2413  *********************************************************************/
2414 static int send_https_request(struct client_state *csp)
2415 {
2416    char *hdr;
2417    int ret;
2418    long flushed = 0;
2419
2420    hdr = list_to_text(csp->https_headers);
2421    if (hdr == NULL)
2422    {
2423       /* FIXME Should handle error properly */
2424       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header.");
2425    }
2426    list_remove_all(csp->https_headers);
2427
2428    /*
2429     * Write the client's (modified) header to the server
2430     * (along with anything else that may be in the buffer)
2431     */
2432    ret = ssl_send_data(&(csp->ssl_server_attr),
2433       (const unsigned char *)hdr, strlen(hdr));
2434    freez(hdr);
2435
2436    if (ret < 0)
2437    {
2438       log_error(LOG_LEVEL_CONNECT,
2439          "Failed sending encrypted request headers to: %s: %E",
2440          csp->http->hostport);
2441       mark_server_socket_tainted(csp);
2442       return 1;
2443    }
2444
2445    /* XXX: Client body isn't sent if there's pipelined data? */
2446    if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2447       && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2448             csp->client_iob)) < 0))
2449    {
2450       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2451          csp->http->hostport);
2452       return 1;
2453    }
2454    if (flushed != 0 || csp->expected_client_content_length != 0)
2455    {
2456       if (csp->expected_client_content_length != 0)
2457       {
2458          if (csp->expected_client_content_length < flushed)
2459          {
2460             log_error(LOG_LEVEL_ERROR,
2461                "Flushed %ld bytes of request body while only expecting %llu.",
2462                flushed, csp->expected_client_content_length);
2463             csp->expected_client_content_length = 0;
2464          }
2465          else
2466          {
2467             log_error(LOG_LEVEL_CONNECT,
2468                "Flushed %ld bytes of request body while expecting %llu.",
2469                flushed, csp->expected_client_content_length);
2470             csp->expected_client_content_length -= (unsigned)flushed;
2471             if (receive_and_send_encrypted_post_data(csp))
2472             {
2473                return 1;
2474             }
2475          }
2476       }
2477       else
2478       {
2479          log_error(LOG_LEVEL_CONNECT,
2480             "Flushed %ld bytes of request body.", flushed);
2481       }
2482    }
2483
2484    log_error(LOG_LEVEL_CONNECT, "Encrypted request sent.");
2485
2486    return 0;
2487
2488 }
2489
2490
2491 /*********************************************************************
2492  *
2493  * Function    :  receive_encrypted_request_headers
2494  *
2495  * Description :  Receives the encrypted request headers when
2496  *                https-inspecting.
2497  *
2498  * Parameters  :
2499  *          1  :  csp = Current client state (buffers, headers, etc...)
2500  *
2501  * Returns     :  JB_ERR_OK on success,
2502  *                JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2503  *
2504  *********************************************************************/
2505 static jb_err receive_encrypted_request_headers(struct client_state *csp)
2506 {
2507    char buf[BUFFER_SIZE];
2508    int len;
2509    char *p;
2510
2511    do
2512    {
2513       log_error(LOG_LEVEL_HEADER, "Waiting for encrypted client headers.");
2514       if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2515           !data_is_available(csp->cfd, csp->config->socket_timeout))
2516       {
2517          log_error(LOG_LEVEL_CONNECT,
2518             "Socket %d timed out while waiting for client headers.", csp->cfd);
2519          return JB_ERR_PARSE;
2520       }
2521       len = ssl_recv_data(&(csp->ssl_client_attr),
2522          (unsigned char *)buf, sizeof(buf));
2523       if (len == 0)
2524       {
2525          log_error(LOG_LEVEL_CONNECT,
2526             "Socket %d closed while waiting for client headers.", csp->cfd);
2527          return JB_ERR_PARSE;
2528       }
2529       if (len == -1)
2530       {
2531          return JB_ERR_PARSE;
2532       }
2533       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2534       {
2535          return JB_ERR_MEMORY;
2536       }
2537       p = strstr(csp->client_iob->cur, "\r\n\r\n");
2538    } while (p == NULL);
2539
2540    log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely.");
2541
2542    return JB_ERR_OK;
2543 }
2544
2545
2546 /*********************************************************************
2547  *
2548  * Function    :  change_encrypted_request_destination
2549  *
2550  * Description :  Parse a (rewritten) request line from an encrypted
2551  *                request and regenerate the http request data.
2552  *
2553  * Parameters  :
2554  *          1  :  csp = Current client state (buffers, headers, etc...)
2555  *
2556  * Returns     :  Forwards the parse_http_request() return code.
2557  *                Terminates in case of memory problems.
2558  *
2559  *********************************************************************/
2560 static jb_err change_encrypted_request_destination(struct client_state *csp)
2561 {
2562    jb_err err;
2563    char *original_host = csp->http->host;
2564    int original_port = csp->http->port;
2565
2566    log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
2567       csp->https_headers->first->str);
2568    csp->http->host = NULL;
2569    free_http_request(csp->http);
2570    err = parse_http_request(csp->https_headers->first->str, csp->http);
2571    if (JB_ERR_OK != err)
2572    {
2573       log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2574          jb_err_to_string(err));
2575       freez(original_host);
2576       return err;
2577    }
2578
2579    if (csp->http->host == NULL)
2580    {
2581       char port_string[10];
2582       /*
2583        * The rewritten request line did not specify a host
2584        * which means we can use the original host specified
2585        * by the client.
2586        */
2587       csp->http->host = original_host;
2588       csp->http->port = original_port;
2589       log_error(LOG_LEVEL_REDIRECTS, "Keeping the original host: %s",
2590          csp->http->host);
2591       /*
2592        * If the rewritten request line didn't contain a host
2593        * it also didn't contain a port so we can reuse the host
2594        * port.
2595        */
2596       freez(csp->http->hostport);
2597       csp->http->hostport = strdup_or_die(csp->http->host);
2598       snprintf(port_string, sizeof(port_string), ":%d", original_port);
2599       err = string_append(&csp->http->hostport, port_string);
2600       if (err != JB_ERR_OK)
2601       {
2602          log_error(LOG_LEVEL_ERROR, "Failed to rebuild hostport: %s.",
2603             jb_err_to_string(err));
2604          return err;
2605       }
2606
2607       /*
2608        * While the request line didn't mention it,
2609        * we're https-inspecting and want to speak TLS
2610        * with the server.
2611        */
2612       csp->http->server_ssl = 1;
2613       csp->http->ssl = 1;
2614    }
2615    else
2616    {
2617       /* The rewrite filter added a host so we can ditch the original */
2618       freez(original_host);
2619       csp->http->server_ssl = csp->http->ssl;
2620    }
2621
2622    csp->http->client_ssl = 1;
2623
2624    freez(csp->https_headers->first->str);
2625    build_request_line(csp, NULL, &csp->https_headers->first->str);
2626
2627    if (!server_use_ssl(csp))
2628    {
2629       log_error(LOG_LEVEL_REDIRECTS,
2630          "Rewritten request line results in downgrade to http");
2631       /*
2632        * Replace the unencryptd headers received with the
2633        * CONNECT request with the ones we received securely.
2634        */
2635       destroy_list(csp->headers);
2636       csp->headers->first = csp->https_headers->first;
2637       csp->headers->last  = csp->https_headers->last;
2638       csp->https_headers->first = NULL;
2639       csp->https_headers->last = NULL;
2640    }
2641
2642    return JB_ERR_OK;
2643
2644 }
2645
2646
2647 /*********************************************************************
2648  *
2649  * Function    :  process_encrypted_request_headers
2650  *
2651  * Description :  Receives and parses the encrypted headers send
2652  *                by the client when https-inspecting.
2653  *
2654  * Parameters  :
2655  *          1  :  csp = Current client state (buffers, headers, etc...)
2656  *
2657  * Returns     :  JB_ERR_OK on success,
2658  *                JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2659  *
2660  *********************************************************************/
2661 static jb_err process_encrypted_request_headers(struct client_state *csp)
2662 {
2663    char *p;
2664    char *request_line;
2665    jb_err err;
2666    /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2667    struct list header_list;
2668    struct list *headers = &header_list;
2669
2670    assert(csp->ssl_with_client_is_opened);
2671
2672 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2673    if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2674    {
2675       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2676    }
2677 #endif
2678    err = receive_encrypted_request_headers(csp);
2679    if (err != JB_ERR_OK)
2680    {
2681       if (csp->client_iob->cur == NULL ||
2682           csp->client_iob->cur == csp->client_iob->eod)
2683       {
2684          /*
2685           * We did not receive any data, most likely because the
2686           * client is done. Don't log this as a parse failure.
2687           */
2688          return JB_ERR_PARSE;
2689       }
2690       /* XXX: Also used for JB_ERR_MEMORY */
2691       log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2692          jb_err_to_string(err));
2693       ssl_send_data_delayed(&(csp->ssl_client_attr),
2694          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2695       return err;
2696    }
2697
2698    /* We don't need get_request_line() because the whole HTTP head is buffered. */
2699    request_line = get_header(csp->client_iob);
2700    if (request_line == NULL)
2701    {
2702       log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2703       ssl_send_data_delayed(&(csp->ssl_client_attr),
2704          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2705       return JB_ERR_PARSE;
2706    }
2707    assert(*request_line != '\0');
2708
2709    if (client_protocol_is_unsupported(csp, request_line))
2710    {
2711       /*
2712        * If the protocol is unsupported we're done here.
2713        * client_protocol_is_unsupported() took care of sending
2714        * the error response and logging the error message.
2715        */
2716       return JB_ERR_PARSE;
2717    }
2718
2719 #ifdef FEATURE_FORCE_LOAD
2720    if (force_required(csp, request_line))
2721    {
2722       csp->flags |= CSP_FLAG_FORCED;
2723    }
2724 #endif /* def FEATURE_FORCE_LOAD */
2725
2726    free_http_request(csp->http);
2727
2728    err = parse_http_request(request_line, csp->http);
2729    /* XXX: Restore ssl setting. This is ugly */
2730    csp->http->client_ssl = 1;
2731    csp->http->server_ssl = 1;
2732
2733    freez(request_line);
2734    if (JB_ERR_OK != err)
2735    {
2736       ssl_send_data_delayed(&(csp->ssl_client_attr),
2737          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2738       /* XXX: Use correct size */
2739       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2740       log_error(LOG_LEVEL_ERROR,
2741          "Couldn't parse request line received from %s: %s",
2742          csp->ip_addr_str, jb_err_to_string(err));
2743
2744       free_http_request(csp->http);
2745       return JB_ERR_PARSE;
2746    }
2747
2748    /* Parse the rest of the client's headers. */
2749    init_list(headers);
2750    for (;;)
2751    {
2752       p = get_header(csp->client_iob);
2753
2754       if (p == NULL)
2755       {
2756          /* There are no additional headers to read. */
2757          break;
2758       }
2759       enlist(headers, p);
2760       freez(p);
2761    }
2762
2763    if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2764    {
2765       /*
2766        * Our attempts to get the request destination
2767        * elsewhere failed.
2768        */
2769       log_error(LOG_LEVEL_ERROR,
2770          "Failed to get the encrypted request destination");
2771       ssl_send_data_delayed(&(csp->ssl_client_attr),
2772          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2773       destroy_list(headers);
2774
2775       return JB_ERR_PARSE;
2776    }
2777
2778    /* Split the domain we just got for pattern matching */
2779    init_domain_components(csp->http);
2780
2781 #ifdef FEATURE_CLIENT_TAGS
2782    /* XXX: If the headers were enlisted sooner, passing csp would do. */
2783    if (csp->client_address == NULL)
2784    {
2785       set_client_address(csp, headers);
2786       get_tag_list_for_client(csp->client_tags, csp->client_address);
2787    }
2788 #endif
2789
2790 #ifdef FEATURE_TOGGLE
2791    if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2792 #endif
2793    {
2794       /*
2795        * Determine the actions for this request after
2796        * clearing the ones from the previous one.
2797        */
2798       free_current_action(csp->action);
2799       get_url_actions(csp, csp->http);
2800    }
2801
2802    enlist(csp->https_headers, csp->http->cmd);
2803
2804    /* Append the previously read headers */
2805    err = list_append_list_unique(csp->https_headers, headers);
2806    destroy_list(headers);
2807    if (JB_ERR_OK != err)
2808    {
2809       /* XXX: Send error message */
2810       return err;
2811    }
2812
2813    /* XXX: Work around crash */
2814    csp->error_message = NULL;
2815
2816    /* XXX: Why do this here? */
2817    csp->http->ssl = 1;
2818
2819    err = sed_https(csp);
2820    if (JB_ERR_OK != err)
2821    {
2822       ssl_send_data_delayed(&(csp->ssl_client_attr),
2823          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2824       log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2825          csp->ip_addr_str);
2826       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2827          csp->ip_addr_str, csp->http->cmd);
2828       return JB_ERR_PARSE;
2829    }
2830
2831    if ((NULL == csp->https_headers->first->str)
2832       || (strcmp(csp->http->cmd, csp->https_headers->first->str) &&
2833          (JB_ERR_OK != change_encrypted_request_destination(csp))))
2834    {
2835       ssl_send_data_delayed(&(csp->ssl_client_attr),
2836          (const unsigned char *)MESSED_UP_REQUEST_RESPONSE,
2837          strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2838       log_error(LOG_LEVEL_ERROR,
2839          "Invalid request line after applying header filters.");
2840       /* XXX: Use correct size */
2841       log_error(LOG_LEVEL_CLF,
2842          "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2843
2844       return JB_ERR_PARSE;
2845    }
2846
2847    log_error(LOG_LEVEL_HEADER, "Encrypted request headers processed");
2848    log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2849       csp->http->path);
2850
2851    return err;
2852
2853 }
2854
2855 /*********************************************************************
2856  *
2857  * Function    :  cgi_page_requested
2858  *
2859  * Description :  Checks if a request is for an internal CGI page.
2860  *
2861  * Parameters  :
2862  *          1  :  host = The host requested by the client.
2863  *
2864  * Returns     :  1 if a CGI page has been requested, 0 otherwise
2865  *
2866  *********************************************************************/
2867 static int cgi_page_requested(const char *host)
2868 {
2869    if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2870     || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2871     || (0 == strcmpic(host, CGI_SITE_2_HOST))
2872     || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2873    {
2874       return 1;
2875    }
2876
2877    return 0;
2878
2879 }
2880
2881
2882 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2883 /*********************************************************************
2884  *
2885  * Function    :  continue_https_chat
2886  *
2887  * Description :  Behaves similar to chat() but only deals with
2888  *                https-inspected requests that arrive on an already
2889  *                established connection. The first request is always
2890  *                served by chat() which is a lot more complex as it
2891  *                has to deal with forwarding settings and connection
2892  *                failures etc.
2893  *
2894  *                If a connection to the server has already been
2895  *                opened it is reused unless the request is blocked
2896  *                or the forwarder changed.
2897  *
2898  *                If a connection to the server has not yet been
2899  *                opened (because the previous request was crunched),
2900  *                or the forwarder changed, the connection is dropped
2901  *                so that the client retries on a fresh one.
2902  *
2903  * Parameters  :
2904  *          1  :  csp = Current client state (buffers, headers, etc...)
2905  *
2906  * Returns     :  Nothing.
2907  *
2908  *********************************************************************/
2909 static void continue_https_chat(struct client_state *csp)
2910 {
2911    const struct forward_spec *fwd;
2912
2913    if (JB_ERR_OK != process_encrypted_request_headers(csp))
2914    {
2915       csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2916       return;
2917    }
2918
2919 #if defined(FEATURE_STATISTICS) && defined(MUTEX_LOCKS_AVAILABLE)
2920    privoxy_mutex_lock(&block_statistics_mutex);
2921    number_of_requests_received++;
2922    privoxy_mutex_unlock(&block_statistics_mutex);
2923 #endif
2924
2925    csp->requests_received_total++;
2926
2927    /*
2928     * We have an encrypted request. Check if one of the crunchers wants it.
2929     */
2930    if (crunch_response_triggered(csp, crunchers_all))
2931    {
2932       /*
2933        * Yes. The client got the crunch response and we're done here.
2934        */
2935       return;
2936    }
2937    if (csp->ssl_with_server_is_opened == 0)
2938    {
2939       log_error(LOG_LEVEL_CONNECT,
2940          "Dropping the client connection on socket %d. "
2941          "The server connection has not been established yet.",
2942          csp->cfd);
2943       csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2944       return;
2945    }
2946    assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2947
2948    if (csp->expected_client_content_length != 0 &&
2949       (client_body_filters_enabled(csp->action) ||
2950        client_body_taggers_enabled(csp->action)) &&
2951       can_buffer_request_body(csp))
2952    {
2953       int content_modified;
2954
2955       if (read_https_request_body(csp))
2956       {
2957          /* XXX: handle */
2958          return;
2959       }
2960       if (client_body_taggers_enabled(csp->action))
2961       {
2962          execute_client_body_taggers(csp, csp->expected_client_content_length);
2963          if (crunch_response_triggered(csp, crunchers_all))
2964          {
2965             /*
2966              * Yes. The client got the crunch response and we're done here.
2967              */
2968             return;
2969          }
2970       }
2971       if (client_body_filters_enabled(csp->action))
2972       {
2973          size_t modified_content_length = csp->expected_client_content_length;
2974          content_modified = execute_client_body_filters(csp,
2975             &modified_content_length);
2976          if ((content_modified == 1) &&
2977             (modified_content_length != csp->expected_client_content_length) &&
2978             update_client_headers(csp, modified_content_length))
2979          {
2980             /* XXX: Send error response */
2981             log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2982             return;
2983          }
2984       }
2985       csp->expected_client_content_length = 0;
2986    }
2987
2988    fwd = forward_url(csp, csp->http);
2989    if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2990    {
2991       log_error(LOG_LEVEL_CONNECT,
2992          "Dropping the client connection on socket %d with "
2993          "server socket %d connected to %s. The forwarder has changed.",
2994          csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2995       csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2996       return;
2997    }
2998
2999    log_applied_actions(csp->action);
3000
3001    log_error(LOG_LEVEL_CONNECT,
3002       "Reusing server socket %d connected to %s. Requests already sent: %u.",
3003       csp->server_connection.sfd, csp->server_connection.host,
3004       csp->server_connection.requests_sent_total);
3005
3006    if (send_https_request(csp))
3007    {
3008       /*
3009        * Most likely the server connection timed out. We can't easily
3010        * create a new one so simply drop the client connection without a
3011        * error response to let the client retry.
3012        */
3013       log_error(LOG_LEVEL_CONNECT,
3014          "Dropping client connection on socket %d. "
3015          "Forwarding the encrypted client request failed.",
3016          csp->cfd);
3017       return;
3018    }
3019    csp->server_connection.request_sent = time(NULL);
3020    csp->server_connection.requests_sent_total++;
3021    handle_established_connection(csp);
3022    freez(csp->receive_buffer);
3023 }
3024 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3025 #endif
3026
3027
3028 /*********************************************************************
3029  *
3030  * Function    :  send_server_headers
3031  *
3032  * Description :  Sends the server headers to the client.
3033  *
3034  * Parameters  :
3035  *          1  :  csp = Current client state (buffers, headers, etc...)
3036  *
3037  * Returns     :  0 on succes, -1 on error.
3038  *
3039  *********************************************************************/
3040 static int send_server_headers(struct client_state *csp)
3041 {
3042    char *server_headers;
3043    int ret;
3044
3045    server_headers = list_to_text(csp->headers);
3046    if (server_headers == NULL)
3047    {
3048       /*
3049        * Memory is too tight to even generate the header.
3050        * Send our static "Out-of-memory" page.
3051        */
3052       log_error(LOG_LEVEL_ERROR,
3053          "Out of memory while trying to send server headers.");
3054       send_crunch_response(csp, cgi_error_memory());
3055       mark_server_socket_tainted(csp);
3056 #ifdef FEATURE_HTTPS_INSPECTION
3057       close_client_and_server_ssl_connections(csp);
3058 #endif
3059       return -1;
3060    }
3061 #ifdef FEATURE_HTTPS_INSPECTION
3062    if (client_use_ssl(csp))
3063    {
3064       ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3065          (const unsigned char *)server_headers, strlen(server_headers),
3066          get_write_delay(csp));
3067    }
3068    else
3069 #endif
3070    {
3071       ret = write_socket_delayed(csp->cfd, server_headers, strlen(server_headers),
3072          get_write_delay(csp));
3073    }
3074    freez(server_headers);
3075    if (ret < 0)
3076    {
3077       log_error(LOG_LEVEL_ERROR, "Failed to send server headers to the client.");
3078       mark_server_socket_tainted(csp);
3079 #ifdef FEATURE_HTTPS_INSPECTION
3080       close_client_and_server_ssl_connections(csp);
3081 #endif
3082       return -1;
3083    }
3084
3085    return 0;
3086
3087 }
3088
3089 /*********************************************************************
3090  *
3091  * Function    :  handle_established_connection
3092  *
3093  * Description :  Shuffle data between client and server once the
3094  *                connection has been established and the request
3095  *                has been sent.
3096  *
3097  * Parameters  :
3098  *          1  :  csp = Current client state (buffers, headers, etc...)
3099  *
3100  * Returns     :  Nothing.
3101  *
3102  *********************************************************************/
3103 static void handle_established_connection(struct client_state *csp)
3104 {
3105    char *p;
3106    int n;
3107 #ifdef HAVE_POLL
3108    struct pollfd poll_fds[2];
3109 #else
3110    fd_set rfds;
3111    jb_socket maxfd;
3112    struct timeval timeout;
3113 #endif
3114    int server_body;
3115    int ms_iis5_hack = 0;
3116    unsigned long long byte_count = 0;
3117    struct http_request *http;
3118    long len = 0; /* for buffer sizes (and negative error codes) */
3119    int buffer_and_filter_content = 0;
3120    unsigned int write_delay;
3121    size_t chunk_offset = 0;
3122 #ifdef FEATURE_HTTPS_INSPECTION
3123    int ret = 0;
3124    int use_ssl_tunnel = 0;
3125    csp->dont_verify_certificate = 0;
3126
3127    if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3128    {
3129       /* Pass encrypted content without filtering. */
3130       use_ssl_tunnel = 1;
3131    }
3132 #endif
3133
3134    /* Skeleton for HTTP response, if we should intercept the request */
3135    struct http_response *rsp;
3136 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3137    int watch_client_socket;
3138 #endif
3139
3140    csp->receive_buffer_size = csp->config->receive_buffer_size;
3141    csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
3142    if (csp->receive_buffer == NULL)
3143    {
3144       log_error(LOG_LEVEL_ERROR,
3145          "Out of memory. Failed to allocate the receive buffer.");
3146       rsp = cgi_error_memory();
3147       send_crunch_response(csp, rsp);
3148       return;
3149    }
3150
3151    http = csp->http;
3152
3153 #ifndef HAVE_POLL
3154    maxfd = (csp->cfd > csp->server_connection.sfd) ?
3155       csp->cfd : csp->server_connection.sfd;
3156 #endif
3157
3158    /* pass data between the client and server
3159     * until one or the other shuts down the connection.
3160     */
3161
3162    server_body = 0;
3163
3164 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3165    watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
3166 #endif
3167    write_delay = get_write_delay(csp);
3168
3169    for (;;)
3170    {
3171 #ifdef FEATURE_HTTPS_INSPECTION
3172       if (server_use_ssl(csp) && is_ssl_pending(&(csp->ssl_server_attr)))
3173       {
3174          /*
3175           * It's possible that the TLS library already consumed all the
3176           * data the server intends to send. If that happens poll() and
3177           * select() will no longer see the data as available so we have
3178           * to skip the calls.
3179           */
3180          goto server_wants_to_talk;
3181       }
3182       if (watch_client_socket && client_use_ssl(csp) &&
3183          is_ssl_pending(&(csp->ssl_client_attr)))
3184       {
3185          /*
3186           * The TLS libray may also consume all of the remaining data
3187           * from the client when we're shuffling the data from an
3188           * unbuffered request body to the server.
3189           */
3190          goto client_wants_to_talk;
3191       }
3192 #endif
3193 #ifndef HAVE_POLL
3194       FD_ZERO(&rfds);
3195 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3196       if (!watch_client_socket)
3197       {
3198          maxfd = csp->server_connection.sfd;
3199       }
3200       else
3201 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3202       {
3203          FD_SET(csp->cfd, &rfds);
3204       }
3205
3206       FD_SET(csp->server_connection.sfd, &rfds);
3207 #endif /* ndef HAVE_POLL */
3208
3209 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3210       if (server_body && server_response_is_complete(csp, byte_count))
3211       {
3212          if (csp->expected_content_length == byte_count)
3213          {
3214             log_error(LOG_LEVEL_CONNECT,
3215                "Done reading from server. Content length: %llu as expected. "
3216                "Bytes most recently read: %ld.",
3217                byte_count, len);
3218          }
3219          else
3220          {
3221             log_error(LOG_LEVEL_CONNECT,
3222                "Done reading from server. Expected content length: %llu. "
3223                "Actual content length: %llu. Bytes most recently read: %ld.",
3224                csp->expected_content_length, byte_count, len);
3225          }
3226          len = 0;
3227          /*
3228           * XXX: Should not jump around, handle_established_connection()
3229           * is complicated enough already.
3230           */
3231          goto reading_done;
3232       }
3233 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
3234
3235 #ifdef HAVE_POLL
3236       poll_fds[0].fd = csp->cfd;
3237 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3238       if (!watch_client_socket)
3239       {
3240          /*
3241           * Ignore incoming data, but still watch out
3242           * for disconnects etc. These flags are always
3243           * implied anyway but explicitly setting them
3244           * doesn't hurt.
3245           */
3246          poll_fds[0].events = POLLERR|POLLHUP;
3247       }
3248       else
3249 #endif
3250       {
3251          poll_fds[0].events = POLLIN;
3252       }
3253       poll_fds[1].fd = csp->server_connection.sfd;
3254       poll_fds[1].events = POLLIN;
3255       n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3256 #else
3257       timeout.tv_sec = csp->config->socket_timeout;
3258       timeout.tv_usec = 0;
3259       n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3260 #endif /* def HAVE_POLL */
3261
3262       /* Server or client not responding in timeout */
3263       if (n == 0)
3264       {
3265          log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3266             csp->config->socket_timeout, http->url);
3267          if ((byte_count == 0) && (http->ssl == 0))
3268          {
3269             send_crunch_response(csp, error_response(csp, "connection-timeout"));
3270          }
3271          mark_server_socket_tainted(csp);
3272 #ifdef FEATURE_HTTPS_INSPECTION
3273          close_client_and_server_ssl_connections(csp);
3274 #endif
3275          return;
3276       }
3277       else if (n < 0)
3278       {
3279 #ifdef HAVE_POLL
3280          log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3281 #else
3282          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3283 #endif
3284          mark_server_socket_tainted(csp);
3285 #ifdef FEATURE_HTTPS_INSPECTION
3286          close_client_and_server_ssl_connections(csp);
3287 #endif
3288          return;
3289       }
3290
3291       /*
3292        * This is the body of the browser's request,
3293        * just read and write it.
3294        *
3295        * Receives data from browser and sends it to server
3296        *
3297        * XXX: Make sure the client doesn't use pipelining
3298        * behind Privoxy's back.
3299        */
3300 #ifdef HAVE_POLL
3301       if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3302       {
3303          log_error(LOG_LEVEL_CONNECT,
3304             "The client socket %d has become unusable while "
3305             "the server socket %d is still open.",
3306             csp->cfd, csp->server_connection.sfd);
3307          mark_server_socket_tainted(csp);
3308          break;
3309       }
3310
3311       if (poll_fds[0].revents != 0)
3312 #else
3313       if (FD_ISSET(csp->cfd, &rfds))
3314 #endif /* def HAVE_POLL*/
3315       {
3316          int max_bytes_to_read;
3317
3318 #ifdef FEATURE_HTTPS_INSPECTION
3319          client_wants_to_talk:
3320 #endif
3321
3322          max_bytes_to_read = (int)csp->receive_buffer_size;
3323
3324 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3325          if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3326          {
3327             if (data_is_available(csp->cfd, 0))
3328             {
3329                /*
3330                 * If the next request is already waiting, we have
3331                 * to stop select()ing the client socket. Otherwise
3332                 * we would always return right away and get nothing
3333                 * else done.
3334                 */
3335                watch_client_socket = 0;
3336                log_error(LOG_LEVEL_CONNECT,
3337                   "Stop watching client socket %d. "
3338                   "There's already another request waiting.",
3339                   csp->cfd);
3340                continue;
3341             }
3342             /*
3343              * If the client socket is set, but there's no data
3344              * available on the socket, the client went fishing
3345              * and continuing talking to the server makes no sense.
3346              */
3347             log_error(LOG_LEVEL_CONNECT,
3348                "The client closed socket %d while "
3349                "the server socket %d is still open.",
3350                csp->cfd, csp->server_connection.sfd);
3351             mark_server_socket_tainted(csp);
3352             break;
3353          }
3354          if (csp->expected_client_content_length != 0)
3355          {
3356             if (csp->expected_client_content_length < csp->receive_buffer_size)
3357             {
3358                max_bytes_to_read = (int)csp->expected_client_content_length;
3359             }
3360             log_error(LOG_LEVEL_CONNECT,
3361                "Waiting for up to %d bytes from the client.",
3362                max_bytes_to_read);
3363          }
3364          assert(max_bytes_to_read <= csp->receive_buffer_size);
3365 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3366
3367 #ifdef FEATURE_HTTPS_INSPECTION
3368          if (client_use_ssl(csp))
3369          {
3370             if (csp->http->status == 101)
3371             {
3372                len = ssl_recv_data(&(csp->ssl_client_attr),
3373                   (unsigned char *)csp->receive_buffer,
3374                   (size_t)max_bytes_to_read);
3375                if (len == -1)
3376                {
3377                   log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3378                      "on client socket %d for an upgraded connection",
3379                      csp->cfd);
3380                   break;
3381                }
3382                if (len == 0)
3383                {
3384                   log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3385                      "on client socket %d for an upgraded connection",
3386                      csp->cfd);
3387                   break;
3388                }
3389                byte_count += (unsigned long long)len;
3390                len = ssl_send_data(&(csp->ssl_server_attr),
3391                   (unsigned char *)csp->receive_buffer, (size_t)len);
3392                if (len == -1)
3393                {
3394                   log_error(LOG_LEVEL_ERROR, "Failed to send data "
3395                      "on server socket %d for an upgraded connection",
3396                      csp->server_connection.sfd);
3397                   break;
3398                }
3399                continue;
3400             }
3401             log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3402             break;
3403          }
3404          else
3405 #endif /* def FEATURE_HTTPS_INSPECTION */
3406          {
3407             len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3408
3409             if (len <= 0)
3410             {
3411                /* XXX: not sure if this is necessary. */
3412                mark_server_socket_tainted(csp);
3413                break; /* "game over, man" */
3414             }
3415
3416 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3417             if (csp->expected_client_content_length != 0)
3418             {
3419                assert(len <= max_bytes_to_read);
3420                csp->expected_client_content_length -= (unsigned)len;
3421                log_error(LOG_LEVEL_CONNECT,
3422                   "Expected client content length set to %llu "
3423                   "after reading %ld bytes.",
3424                   csp->expected_client_content_length, len);
3425                if (csp->expected_client_content_length == 0)
3426                {
3427                   log_error(LOG_LEVEL_CONNECT,
3428                      "Done reading from the client.");
3429                   csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3430                }
3431             }
3432 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3433
3434             if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3435             {
3436                log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3437                mark_server_socket_tainted(csp);
3438                return;
3439             }
3440          }
3441          continue;
3442       }
3443
3444       /*
3445        * The server wants to talk. It could be the header or the body.
3446        */
3447 #ifdef HAVE_POLL
3448       if (poll_fds[1].revents != 0)
3449 #else
3450       if (FD_ISSET(csp->server_connection.sfd, &rfds))
3451 #endif /* HAVE_POLL */
3452       {
3453 #ifdef FEATURE_HTTPS_INSPECTION
3454          server_wants_to_talk:
3455 #endif
3456 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3457          /*
3458           * If we are buffering content, we don't want to eat up to
3459           * buffer-limit bytes if the client no longer cares about them.
3460           * If we aren't buffering, however, a dead client socket will be
3461           * noticed pretty much right away anyway, so we can reduce the
3462           * overhead by skipping the check.
3463           */
3464          if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3465          {
3466 #ifdef _WIN32
3467             log_error(LOG_LEVEL_CONNECT,
3468                "The server still wants to talk, but the client may already have hung up on us.");
3469 #else
3470             log_error(LOG_LEVEL_CONNECT,
3471                "The server still wants to talk, but the client hung up on us.");
3472             mark_server_socket_tainted(csp);
3473 #ifdef FEATURE_HTTPS_INSPECTION
3474             close_client_and_server_ssl_connections(csp);
3475 #endif
3476             return;
3477 #endif /* def _WIN32 */
3478          }
3479 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3480
3481 #ifdef FEATURE_HTTPS_INSPECTION
3482          /*
3483           * Reading data from standard or secured connection (HTTP/HTTPS)
3484           */
3485          if (server_use_ssl(csp))
3486          {
3487             len = ssl_recv_data(&(csp->ssl_server_attr),
3488                (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3489          }
3490          else
3491 #endif
3492          {
3493             len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3494                (int)csp->receive_buffer_size);
3495          }
3496
3497          if (len < 0)
3498          {
3499             log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3500
3501             if ((http->ssl && (csp->fwd == NULL))
3502 #ifdef FEATURE_HTTPS_INSPECTION
3503                && use_ssl_tunnel
3504 #endif
3505                 )
3506             {
3507                /*
3508                 * Just hang up. We already confirmed the client's CONNECT
3509                 * request with status code 200 and unencrypted content is
3510                 * no longer welcome.
3511                 */
3512                log_error(LOG_LEVEL_ERROR,
3513                   "CONNECT already confirmed. Unable to tell the client about the problem.");
3514                return;
3515             }
3516             else if (byte_count)
3517             {
3518                /*
3519                 * Just hang up. We already transmitted the original headers
3520                 * and parts of the original content and therefore missed the
3521                 * chance to send an error message (without risking data corruption).
3522                 *
3523                 * XXX: we could retry with a fancy range request here.
3524                 */
3525                log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3526                   "Unable to tell the client about the problem.");
3527                mark_server_socket_tainted(csp);
3528 #ifdef FEATURE_HTTPS_INSPECTION
3529                close_client_and_server_ssl_connections(csp);
3530 #endif
3531                return;
3532             }
3533             /*
3534              * XXX: Consider handling the cases above the same.
3535              */
3536             mark_server_socket_tainted(csp);
3537             len = 0;
3538          }
3539
3540 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3541          reading_done:
3542 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
3543
3544          /*
3545           * This is guaranteed by allocating with zalloc_or_die()
3546           * and never (intentionally) writing to the last byte.
3547           *
3548           * csp->receive_buffer_size is the size of the part of the
3549           * buffer we intentionally write to, but we actually
3550           * allocated csp->receive_buffer_size+1 bytes so the assertion
3551           * stays within the allocated range.
3552           */
3553          assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3554
3555          /*
3556           * Add a trailing zero to let be able to use string operations.
3557           * XXX: do we still need this with filter_popups gone?
3558           */
3559          assert(len <= csp->receive_buffer_size);
3560          csp->receive_buffer[len] = '\0';
3561
3562          /*
3563           * Normally, this would indicate that we've read
3564           * as much as the server has sent us and we can
3565           * close the client connection.  However, Microsoft
3566           * in its wisdom has released IIS/5 with a bug that
3567           * prevents it from sending the trailing \r\n in
3568           * a 302 redirect header (and possibly other headers).
3569           * To work around this if we've haven't parsed
3570           * a full header we'll append a trailing \r\n
3571           * and see if this now generates a valid one.
3572           *
3573           * This hack shouldn't have any impacts.  If we've
3574           * already transmitted the header or if this is a
3575           * SSL connection, then we won't bother with this
3576           * hack.  So we only work on partially received
3577           * headers.  If we append a \r\n and this still
3578           * doesn't generate a valid header, then we won't
3579           * transmit anything to the client.
3580           */
3581          if (len == 0)
3582          {
3583
3584             if (server_body || (http->ssl
3585 #ifdef FEATURE_HTTPS_INSPECTION
3586                   && use_ssl_tunnel
3587 #endif
3588                ))
3589             {
3590                /*
3591                 * If we have been buffering up the document,
3592                 * now is the time to apply content modification
3593                 * and send the result to the client.
3594                 */
3595                if (buffer_and_filter_content)
3596                {
3597                   p = execute_content_filters(csp);
3598                   /*
3599                    * If content filtering fails, use the original
3600                    * buffer and length.
3601                    * (see p != NULL ? p : csp->iob->cur below)
3602                    */
3603                   if (NULL == p)
3604                   {
3605                      csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3606                   }
3607 #ifdef FEATURE_COMPRESSION
3608                   else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3609                      && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3610                   {
3611                      char *compressed_content = compress_buffer(p,
3612                         (size_t *)&csp->content_length, csp->config->compression_level);
3613                      if (compressed_content != NULL)
3614                      {
3615                         freez(p);
3616                         p = compressed_content;
3617                         csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3618                      }
3619                   }
3620 #endif
3621
3622                   if (JB_ERR_OK != update_server_headers(csp))
3623                   {
3624                      log_error(LOG_LEVEL_FATAL,
3625                         "Failed to update server headers. after filtering.");
3626                   }
3627
3628                   if (send_server_headers(csp))
3629                   {
3630                      return;
3631                   }
3632
3633 #ifdef FEATURE_HTTPS_INSPECTION
3634                   /*
3635                    * Sending data with standard or secured connection (HTTP/HTTPS)
3636                    */
3637                   if (client_use_ssl(csp))
3638                   {
3639                      if (ssl_send_data_delayed(&(csp->ssl_client_attr),
3640                               (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3641                               csp->content_length, get_write_delay(csp)) < 0)
3642                      {
3643                         log_error(LOG_LEVEL_ERROR,
3644                            "Failed to send the modified content to the client over TLS");
3645                         freez(p);
3646                         mark_server_socket_tainted(csp);
3647                         close_client_and_server_ssl_connections(csp);
3648                         return;
3649                      }
3650                   }
3651                   else
3652 #endif /* def FEATURE_HTTPS_INSPECTION */
3653                   {
3654                      if (write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3655                          (size_t)csp->content_length, write_delay))
3656                      {
3657                         log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3658                         freez(p);
3659                         mark_server_socket_tainted(csp);
3660                         return;
3661                      }
3662                   }
3663
3664                   freez(p);
3665                }
3666
3667                break; /* "game over, man" */
3668             }
3669
3670             /*
3671              * This is not the body, so let's pretend the server just sent
3672              * us a blank line.
3673              */
3674             snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3675             len = (int)strlen(csp->receive_buffer);
3676
3677             /*
3678              * Now, let the normal header parsing algorithm below do its
3679              * job.  If it fails, we'll exit instead of continuing.
3680              */
3681
3682             ms_iis5_hack = 1;
3683          }
3684
3685          /*
3686           * If we're in the body of the server document, just write it to
3687           * the client, unless we need to buffer the body for later
3688           * content-filtering.
3689           */
3690          if (server_body || (http->ssl
3691 #ifdef FEATURE_HTTPS_INSPECTION
3692                && use_ssl_tunnel
3693 #endif
3694             ))
3695          {
3696             if (buffer_and_filter_content)
3697             {
3698                /*
3699                 * If there is no memory left for buffering the content, or the buffer limit
3700                 * has been reached, switch to non-filtering mode, i.e. make & write the
3701                 * header, flush the iob and buf, and get out of the way.
3702                 */
3703                if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3704                {
3705                   long flushed;
3706
3707                   log_error(LOG_LEVEL_INFO,
3708                      "Flushing header and buffers. Stepping back from filtering.");
3709
3710                   if (send_server_headers(csp))
3711                   {
3712                      return;
3713                   }
3714
3715 #ifdef FEATURE_HTTPS_INSPECTION
3716                   /*
3717                    * Sending data with standard or secured connection (HTTP/HTTPS)
3718                    */
3719                   if (client_use_ssl(csp))
3720                   {
3721                      if (((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3722                                 csp->iob)) < 0)
3723                         || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3724                               (const unsigned char *)csp->receive_buffer, (size_t)len,
3725                               get_write_delay(csp)) < 0))
3726                      {
3727                         log_error(LOG_LEVEL_CONNECT,
3728                            "Flush header and buffers to client failed");
3729                         mark_server_socket_tainted(csp);
3730                         close_client_and_server_ssl_connections(csp);
3731                         return;
3732                      }
3733                   }
3734                   else
3735 #endif /* def FEATURE_HTTPS_INSPECTION */
3736                   {
3737                      if (((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3738                       || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3739                             write_delay))
3740                      {
3741                         log_error(LOG_LEVEL_CONNECT,
3742                            "Flush header and buffers to client failed: %E");
3743                         mark_server_socket_tainted(csp);
3744                         return;
3745                      }
3746                   }
3747
3748                   /*
3749                    * Reset the byte_count to the amount of bytes we just
3750                    * flushed. len will be added a few lines below.
3751                    */
3752                   byte_count = (unsigned long long)flushed;
3753                   if ((csp->flags & CSP_FLAG_CHUNKED) && (chunk_offset != 0))
3754                   {
3755                      log_error(LOG_LEVEL_CONNECT,
3756                         "Reducing chunk offset %lu by %ld to %lu.", chunk_offset, flushed,
3757                         (chunk_offset - (unsigned)flushed));
3758                      assert(chunk_offset >= flushed); /* XXX: Reachable with malicious input? */
3759                      chunk_offset -= (unsigned)flushed;
3760
3761                      /* Make room in the iob. */
3762                      csp->iob->cur = csp->iob->eod = csp->iob->buf;
3763
3764                      if (add_to_iob(csp->iob, csp->config->buffer_limit,
3765                            csp->receive_buffer, len))
3766                      {
3767                         /* This is not supposed to happen but ... */
3768                         csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3769                         log_error(LOG_LEVEL_ERROR, "Failed to buffer %ld bytes of "
3770                            "chunk-encoded data after resetting the buffer.", len);
3771                         return;
3772                      }
3773                   }
3774                   buffer_and_filter_content = 0;
3775                   server_body = 1;
3776                }
3777             }
3778             else
3779             {
3780 #ifdef FEATURE_HTTPS_INSPECTION
3781                /*
3782                 * Sending data with standard or secured connection (HTTP/HTTPS)
3783                 */
3784                if (client_use_ssl(csp))
3785                {
3786                   ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3787                      (const unsigned char *)csp->receive_buffer, (size_t)len,
3788                      get_write_delay(csp));
3789                   if (ret < 0)
3790                   {
3791                      log_error(LOG_LEVEL_ERROR,
3792                         "Sending data to client failed");
3793                      mark_server_socket_tainted(csp);
3794                      close_client_and_server_ssl_connections(csp);
3795                      return;
3796                   }
3797                }
3798                else
3799 #endif /* def FEATURE_HTTPS_INSPECTION */
3800                {
3801                   if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3802                         (size_t)len, write_delay))
3803                   {
3804                      log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3805                      mark_server_socket_tainted(csp);
3806                      return;
3807                   }
3808                }
3809                if (csp->flags & CSP_FLAG_CHUNKED)
3810                {
3811                   /*
3812                    * While we don't need the data to filter it, put it in the
3813                    * buffer so we can keep track of the offset to the start of
3814                    * the next chunk and detect when the response is finished.
3815                    */
3816                   size_t encoded_bytes = (size_t)(csp->iob->eod - csp->iob->cur);
3817
3818                   if (csp->config->buffer_limit / 4 < encoded_bytes)
3819                   {
3820                      /*
3821                       * Reset the buffer to reduce the memory footprint.
3822                       */
3823                      log_error(LOG_LEVEL_CONNECT,
3824                         "Reducing the chunk offset from %lu to %lu after "
3825                         "discarding %lu bytes to make room in the buffer.",
3826                         chunk_offset, (chunk_offset - encoded_bytes),
3827                         encoded_bytes);
3828                      chunk_offset -= encoded_bytes;
3829                      csp->iob->cur = csp->iob->eod = csp->iob->buf;
3830                   }
3831                   if (add_to_iob(csp->iob, csp->config->buffer_limit,
3832                      csp->receive_buffer, len))
3833                   {
3834                      /* This is not supposed to happen but ... */
3835                      csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3836                      log_error(LOG_LEVEL_ERROR,
3837                         "Failed to buffer %ld bytes of chunk-encoded data.",
3838                         len);
3839                      return;
3840                   }
3841                }
3842             }
3843             byte_count += (unsigned long long)len;
3844
3845             if (csp->flags & CSP_FLAG_CHUNKED)
3846             {
3847                int rc;
3848                size_t encoded_bytes = (size_t)(csp->iob->eod - csp->iob->cur);
3849
3850                rc = get_bytes_missing_from_chunked_data(csp->iob->cur, encoded_bytes,
3851                   chunk_offset);
3852                if (rc >= 0)
3853                {
3854                   if (rc != 0)
3855                   {
3856                      chunk_offset = (size_t)rc;
3857                   }
3858
3859                   if (chunked_data_is_complete(csp->iob->cur, encoded_bytes, chunk_offset))
3860                   {
3861                      log_error(LOG_LEVEL_CONNECT,
3862                         "We buffered the last chunk of the response.");
3863                      csp->expected_content_length = byte_count;
3864                      csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3865                   }
3866                }
3867             }
3868
3869             continue;
3870          }
3871          else
3872          {
3873             /*
3874              * We're still looking for the end of the server's header.
3875              * Buffer up the data we just read.  If that fails, there's
3876              * little we can do but send our static out-of-memory page.
3877              */
3878             if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3879             {
3880                log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3881                rsp = cgi_error_memory();
3882                send_crunch_response(csp, rsp);
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             /* Convert iob into something sed() can digest */
3891             if (JB_ERR_PARSE == get_server_headers(csp))
3892             {
3893                if (ms_iis5_hack)
3894                {
3895                   /*
3896                    * Well, we tried our MS IIS/5 hack and it didn't work.
3897                    * The header is incomplete and there isn't anything
3898                    * we can do about it.
3899                    */
3900                   log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3901                      "Applying the MS IIS5 hack didn't help.");
3902                   log_error(LOG_LEVEL_CLF,
3903                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3904 #ifdef FEATURE_HTTPS_INSPECTION
3905                   /*
3906                    * Sending data with standard or secured connection (HTTP/HTTPS)
3907                    */
3908                   if (client_use_ssl(csp))
3909                   {
3910                      ssl_send_data_delayed(&(csp->ssl_client_attr),
3911                         (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3912                         strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3913                   }
3914                   else
3915 #endif /* def FEATURE_HTTPS_INSPECTION */
3916                   {
3917                      write_socket_delayed(csp->cfd,
3918                         INVALID_SERVER_HEADERS_RESPONSE,
3919                         strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3920                   }
3921                   mark_server_socket_tainted(csp);
3922 #ifdef FEATURE_HTTPS_INSPECTION
3923                   close_client_and_server_ssl_connections(csp);
3924 #endif
3925                   return;
3926                }
3927                else
3928                {
3929                   /*
3930                    * Since we have to wait for more from the server before
3931                    * we can parse the headers we just continue here.
3932                    */
3933                   log_error(LOG_LEVEL_CONNECT,
3934                      "Continuing buffering server headers from socket %d. "
3935                      "Bytes most recently read: %ld.", csp->cfd, len);
3936                   continue;
3937                }
3938             }
3939             else
3940             {
3941                /*
3942                 * Account for the content bytes we
3943                 * might have gotten with the headers.
3944                 */
3945                assert(csp->iob->eod >= csp->iob->cur);
3946                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3947             }
3948
3949             /* Did we actually get anything? */
3950             if (NULL == csp->headers->first)
3951             {
3952                if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3953                {
3954                   log_error(LOG_LEVEL_ERROR,
3955                      "No server or forwarder response received on socket %d. "
3956                      "Closing client socket %d without sending data.",
3957                      csp->server_connection.sfd, csp->cfd);
3958                   log_error(LOG_LEVEL_CLF,
3959                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3960                }
3961                else
3962                {
3963                   log_error(LOG_LEVEL_ERROR,
3964                      "No server or forwarder response received on socket %d.",
3965                      csp->server_connection.sfd);
3966                   send_crunch_response(csp, error_response(csp, "no-server-data"));
3967                }
3968                free_http_request(http);
3969                mark_server_socket_tainted(csp);
3970 #ifdef FEATURE_HTTPS_INSPECTION
3971                close_client_and_server_ssl_connections(csp);
3972 #endif
3973                return;
3974             }
3975
3976             if (!csp->headers->first->str)
3977             {
3978                log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3979             }
3980             assert(csp->headers->first->str);
3981
3982             if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3983                 strncmpic(csp->headers->first->str, "ICY", 3))
3984             {
3985                /*
3986                 * It doesn't look like a HTTP (or Shoutcast) response:
3987                 * tell the client and log the problem.
3988                 */
3989                if (strlen(csp->headers->first->str) > 30)
3990                {
3991                   csp->headers->first->str[30] = '\0';
3992                }
3993                log_error(LOG_LEVEL_ERROR,
3994                   "Invalid server or forwarder response. Starts with: %s",
3995                   csp->headers->first->str);
3996                log_error(LOG_LEVEL_CLF,
3997                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3998 #ifdef FEATURE_HTTPS_INSPECTION
3999                /*
4000                 * Sending data with standard or secured connection (HTTP/HTTPS)
4001                 */
4002                if (client_use_ssl(csp))
4003                {
4004                   ssl_send_data_delayed(&(csp->ssl_client_attr),
4005                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4006                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
4007                      get_write_delay(csp));
4008                }
4009                else
4010 #endif /* def FEATURE_HTTPS_INSPECTION */
4011                {
4012                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4013                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4014                }
4015                free_http_request(http);
4016                mark_server_socket_tainted(csp);
4017 #ifdef FEATURE_HTTPS_INSPECTION
4018                close_client_and_server_ssl_connections(csp);
4019 #endif
4020                return;
4021             }
4022
4023             /*
4024              * Disable redirect checkers, so that they will be only run
4025              * again if the user also enables them through tags.
4026              *
4027              * From a performance point of view it doesn't matter,
4028              * but it prevents duplicated log messages.
4029              */
4030 #ifdef FEATURE_FAST_REDIRECTS
4031             csp->action->flags &= ~ACTION_FAST_REDIRECTS;
4032 #endif
4033             csp->action->flags &= ~ACTION_REDIRECT;
4034
4035             /*
4036              * We have now received the entire server header,
4037              * filter it and send the result to the client
4038              */
4039             if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
4040             {
4041                log_error(LOG_LEVEL_CLF,
4042                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
4043 #ifdef FEATURE_HTTPS_INSPECTION
4044                /*
4045                 * Sending data with standard or secured connection (HTTP/HTTPS)
4046                 */
4047                if (client_use_ssl(csp))
4048                {
4049                   ssl_send_data_delayed(&(csp->ssl_client_attr),
4050                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4051                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
4052                      get_write_delay(csp));
4053                }
4054                else
4055 #endif
4056                {
4057                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4058                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4059                }
4060                free_http_request(http);
4061                mark_server_socket_tainted(csp);
4062 #ifdef FEATURE_HTTPS_INSPECTION
4063                close_client_and_server_ssl_connections(csp);
4064 #endif
4065                return;
4066             }
4067
4068             if ((csp->flags & CSP_FLAG_CHUNKED)
4069                && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET))
4070             {
4071                int rc;
4072                size_t encoded_size = (size_t)(csp->iob->eod - csp->iob->cur);
4073
4074                rc = get_bytes_missing_from_chunked_data(csp->iob->cur, encoded_size,
4075                   chunk_offset);
4076                if (rc >= 0)
4077                {
4078                   if (rc != 0)
4079                   {
4080                      chunk_offset = (size_t)rc;
4081                   }
4082                   if (chunked_data_is_complete(csp->iob->cur, encoded_size, chunk_offset))
4083                   {
4084                      log_error(LOG_LEVEL_CONNECT,
4085                         "Looks like we got the last chunk together with "
4086                         "the server headers. We better stop reading.");
4087                      byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
4088                      csp->expected_content_length = byte_count;
4089                      csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
4090                   }
4091                }
4092             }
4093             csp->server_connection.response_received = time(NULL);
4094
4095             if (crunch_response_triggered(csp, crunchers_light))
4096             {
4097                /*
4098                 * One of the tags created by a server-header
4099                 * tagger triggered a crunch. We already
4100                 * delivered the crunch response to the client
4101                 * and are done here after cleaning up.
4102                 */
4103                mark_server_socket_tainted(csp);
4104 #ifdef FEATURE_HTTPS_INSPECTION
4105                close_client_and_server_ssl_connections(csp);
4106 #endif
4107                return;
4108             }
4109
4110             /* Buffer and pcrs filter this if appropriate. */
4111             buffer_and_filter_content = content_requires_filtering(csp);
4112
4113             if (!buffer_and_filter_content)
4114             {
4115                /*
4116                 * Write the server's (modified) header to
4117                 * the client (along with anything else that
4118                 * may be in the buffer). Use standard or secured
4119                 * connection.
4120                 */
4121                if (send_server_headers(csp))
4122                {
4123                   return;
4124                }
4125 #ifdef FEATURE_HTTPS_INSPECTION
4126                if (client_use_ssl(csp))
4127                {
4128                   if ((len = ssl_flush_socket(&(csp->ssl_client_attr),
4129                            csp->iob)) < 0)
4130                   {
4131                      log_error(LOG_LEVEL_CONNECT,
4132                         "Sending buffered bytes to the client failed");
4133
4134                      /*
4135                       * The write failed, so don't bother mentioning it
4136                       * to the client... it probably can't hear us anyway.
4137                       */
4138                      mark_server_socket_tainted(csp);
4139 #ifdef FEATURE_HTTPS_INSPECTION
4140                      close_client_and_server_ssl_connections(csp);
4141 #endif
4142                      return;
4143                   }
4144                }
4145                else
4146 #endif /* def FEATURE_HTTPS_INSPECTION */
4147                {
4148                   if ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
4149                   {
4150                      log_error(LOG_LEVEL_ERROR,
4151                         "Sending buffered bytes to the client failed.");
4152                      /*
4153                       * The write failed, so don't bother mentioning it
4154                       * to the client... it probably can't hear us anyway.
4155                       */
4156                      mark_server_socket_tainted(csp);
4157                      return;
4158                   }
4159                }
4160                if (csp->flags & CSP_FLAG_CHUNKED &&
4161                  !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET))
4162                {
4163                   /*
4164                    * In case of valid data we shouldn't flush more
4165                    * data than chunk_offset but the data may be invalid.
4166                    */
4167                   if (chunk_offset >= len)
4168                   {
4169                      log_error(LOG_LEVEL_CONNECT, "Reducing the chunk offset "
4170                         "from %lu to %lu after flushing %ld bytes.",
4171                         chunk_offset, (chunk_offset - (unsigned)len), len);
4172                      chunk_offset = chunk_offset - (unsigned)len;
4173                   }
4174                   else
4175                   {
4176                      log_error(LOG_LEVEL_CONNECT,
4177                         "Keeping chunk offset at %lu despite flushing %ld bytes",
4178                         chunk_offset, len);
4179                      /*
4180                       * If we can't parse the chunk-encoded data we should
4181                       * not reuse the server connection.
4182                       */
4183                      mark_server_socket_tainted(csp);
4184                   }
4185                }
4186                                 }
4187
4188             /* we're finished with the server's header */
4189
4190             server_body = 1;
4191
4192             /*
4193              * If this was a MS IIS/5 hack then it means the server
4194              * has already closed the connection. Nothing more to read.
4195              * Time to bail.
4196              */
4197             if (ms_iis5_hack)
4198             {
4199                log_error(LOG_LEVEL_ERROR,
4200                   "Closed server connection detected. "
4201                   "Applying the MS IIS5 hack didn't help.");
4202                log_error(LOG_LEVEL_CLF,
4203                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
4204 #ifdef FEATURE_HTTPS_INSPECTION
4205                /*
4206                 * Sending data with standard or secured connection (HTTP/HTTPS)
4207                 */
4208                if (client_use_ssl(csp))
4209                {
4210                   ssl_send_data_delayed(&(csp->ssl_client_attr),
4211                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4212                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
4213                      get_write_delay(csp));
4214                }
4215                else
4216 #endif /* def FEATURE_HTTPS_INSPECTION */
4217                {
4218                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4219                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4220                }
4221                mark_server_socket_tainted(csp);
4222 #ifdef FEATURE_HTTPS_INSPECTION
4223                close_client_and_server_ssl_connections(csp);
4224 #endif
4225                return;
4226             }
4227          }
4228          continue;
4229       }
4230       mark_server_socket_tainted(csp);
4231 #ifdef FEATURE_HTTPS_INSPECTION
4232       close_client_and_server_ssl_connections(csp);
4233 #endif
4234       return; /* huh? we should never get here */
4235    }
4236
4237    if (csp->content_length == 0)
4238    {
4239       /*
4240        * If Privoxy didn't recalculate the Content-Length,
4241        * byte_count is still correct.
4242        */
4243       csp->content_length = byte_count;
4244    }
4245
4246 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4247    if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
4248       && (csp->expected_content_length != byte_count))
4249    {
4250       log_error(LOG_LEVEL_CONNECT,
4251          "Received %llu bytes while expecting %llu.",
4252          byte_count, csp->expected_content_length);
4253       mark_server_socket_tainted(csp);
4254    }
4255 #endif
4256
4257 #ifdef FEATURE_HTTPS_INSPECTION
4258    if (client_use_ssl(csp))
4259    {
4260       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
4261          csp->ip_addr_str, http->gpc, http->hostport, http->path,
4262          http->version, csp->content_length);
4263    }
4264    else
4265 #endif
4266    {
4267       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
4268          csp->ip_addr_str, http->ocmd, csp->content_length);
4269    }
4270    csp->server_connection.timestamp = time(NULL);
4271 }
4272
4273
4274 /*********************************************************************
4275  *
4276  * Function    :  chat
4277  *
4278  * Description :  Once a connection from the client has been accepted,
4279  *                this function is called (via serve()) to handle the
4280  *                main business of the communication.  This function
4281  *                returns after dealing with a single request. It can
4282  *                be called multiple times with the same client socket
4283  *                if the client is keeping the connection alive.
4284  *
4285  *                The decision whether or not a client connection will
4286  *                be kept alive is up to the caller which also must
4287  *                close the client socket when done.
4288  *
4289  *                FIXME: chat is nearly thousand lines long.
4290  *                Ridiculous.
4291  *
4292  * Parameters  :
4293  *          1  :  csp = Current client state (buffers, headers, etc...)
4294  *
4295  * Returns     :  Nothing.
4296  *
4297  *********************************************************************/
4298 static void chat(struct client_state *csp)
4299 {
4300    const struct forward_spec *fwd;
4301    struct http_request *http;
4302    /* Skeleton for HTTP response, if we should intercept the request */
4303    struct http_response *rsp;
4304 #ifdef FEATURE_HTTPS_INSPECTION
4305    int use_ssl_tunnel = 0;
4306 #endif
4307
4308    http = csp->http;
4309
4310    if (receive_client_request(csp) != JB_ERR_OK)
4311    {
4312       return;
4313    }
4314
4315 #if defined(FEATURE_STATISTICS) && defined(MUTEX_LOCKS_AVAILABLE)
4316    privoxy_mutex_lock(&block_statistics_mutex);
4317    number_of_requests_received++;
4318    privoxy_mutex_unlock(&block_statistics_mutex);
4319 #endif
4320
4321    if (parse_client_request(csp) != JB_ERR_OK)
4322    {
4323       return;
4324    }
4325
4326 #ifdef FEATURE_HTTPS_INSPECTION
4327    /*
4328     * Setting flags to use old solution with SSL tunnel and to disable
4329     * certificate verification.
4330     */
4331    if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
4332       && !cgi_page_requested(csp->http->host))
4333    {
4334       use_ssl_tunnel = 1;
4335    }
4336
4337    if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
4338    {
4339       csp->dont_verify_certificate = 1;
4340    }
4341 #endif
4342
4343    /*
4344     * build the http request to send to the server
4345     * we have to do one of the following:
4346     *
4347     * create =    use the original HTTP request to create a new
4348     *             HTTP request that has either the path component
4349     *             without the http://domainspec (w/path) or the
4350     *             full orininal URL (w/url)
4351     *             Note that the path and/or the HTTP version may
4352     *             have been altered by now.
4353     *
4354     * SSL proxy = Open a socket to the host:port of the server
4355     *             and create TLS/SSL connection with server and
4356     *             with client. Then behave like mediator between
4357     *             client and server over TLS/SSL.
4358     *
4359     * SSL proxy = Pass the request unchanged if forwarding a CONNECT
4360     *    with     request to a parent proxy. Note that we'll be sending
4361     * forwarding  the CFAIL message ourselves if connecting to the parent
4362     *             fails, but we won't send a CSUCCEED message if it works,
4363     *             since that would result in a double message (ours and the
4364     *             parent's). After sending the request to the parent, we
4365     *             must parse answer and send it to client. If connection
4366     *             with server is established, we do TLS/SSL proxy. Otherwise
4367     *             we send parent response to client and close connections.
4368     *
4369     * here's the matrix:
4370     *                        SSL
4371     *                    0        1
4372     *                +--------+--------+
4373     *                |        |        |
4374     *             0  | create |   SSL  |
4375     *                | w/path |  proxy |
4376     *  Forwarding    +--------+--------+
4377     *                |        |   SSL  |
4378     *             1  | create |  proxy |
4379     *                | w/url  |+forward|
4380     *                +--------+--------+
4381     *
4382     */
4383
4384 #ifdef FEATURE_HTTPS_INSPECTION
4385    /*
4386     * Presetting SSL client and server flags
4387     */
4388    if (http->ssl && !use_ssl_tunnel)
4389    {
4390       http->client_ssl = 1;
4391       http->server_ssl = 1;
4392    }
4393    else
4394    {
4395       http->client_ssl = 0;
4396       http->server_ssl = 0;
4397    }
4398 #endif
4399
4400 #ifdef FEATURE_HTTPS_INSPECTION
4401    /*
4402     * Log the request unless we're https inspecting
4403     * in which case we don't have the path yet and
4404     * will log the request later.
4405     */
4406    if (!client_use_ssl(csp))
4407 #endif
4408    {
4409       log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
4410    }
4411
4412    if (http->ssl && connect_port_is_forbidden(csp))
4413    {
4414       const char *acceptable_connect_ports =
4415          csp->action->string[ACTION_STRING_LIMIT_CONNECT];
4416       assert(NULL != acceptable_connect_ports);
4417       log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
4418          "limit-connect{%s} doesn't allow CONNECT requests to %s",
4419          csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
4420       csp->action->flags |= ACTION_BLOCK;
4421       http->ssl = 0;
4422 #ifdef FEATURE_HTTPS_INSPECTION
4423       http->client_ssl = 0;
4424       http->server_ssl = 0;
4425 #endif
4426    }
4427
4428    /*
4429     * We have a request. Check if one of the crunchers wants it
4430     * unless the client wants to use TLS/SSL in which case we
4431     * haven't setup the TLS context yet and will send the crunch
4432     * response later.
4433     */
4434    if (
4435 #ifdef FEATURE_HTTPS_INSPECTION
4436        !client_use_ssl(csp) &&
4437 #endif
4438        crunch_response_triggered(csp, crunchers_all))
4439    {
4440       /*
4441        * Yes. The client got the crunch response and we're done here.
4442        */
4443       return;
4444    }
4445
4446 #ifdef FEATURE_HTTPS_INSPECTION
4447    if (client_use_ssl(csp) && !use_ssl_tunnel)
4448    {
4449       int ret;
4450       /*
4451        * Creating a SSL proxy.
4452        *
4453        * By sending the CSUCCEED message we're lying to the client as
4454        * the connection hasn't actually been established yet. We don't
4455        * establish the connection until we have seen and parsed the
4456        * encrypted client headers.
4457        */
4458       if (write_socket_delayed(csp->cfd, CSUCCEED,
4459             strlen(CSUCCEED), get_write_delay(csp)) != 0)
4460       {
4461          log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
4462          return;
4463       }
4464
4465       ret = create_client_ssl_connection(csp);
4466       if (ret != 0)
4467       {
4468          log_error(LOG_LEVEL_ERROR,
4469             "Failed to open a secure connection with the client");
4470          return;
4471       }
4472       if (JB_ERR_OK != process_encrypted_request_headers(csp))
4473       {
4474          close_client_ssl_connection(csp);
4475          return;
4476       }
4477       /*
4478        * We have an encrypted request. Check if one of the crunchers now
4479        * wants it (for example because the previously invisible path was
4480        * required to match).
4481        */
4482       if (crunch_response_triggered(csp, crunchers_all))
4483       {
4484          /*
4485           * Yes. The client got the crunch response and we're done here.
4486           */
4487          return;
4488       }
4489    }
4490 #endif
4491
4492    /* If we need to apply client body filters, buffer the whole request now. */
4493    if (csp->expected_client_content_length != 0 &&
4494       (client_body_filters_enabled(csp->action) ||
4495          client_body_taggers_enabled(csp->action)) &&
4496       can_buffer_request_body(csp))
4497    {
4498       int content_modified;
4499       size_t modified_content_length;
4500
4501 #ifdef FEATURE_HTTPS_INSPECTION
4502       if (client_use_ssl(csp) && read_https_request_body(csp))
4503       {
4504          log_error(LOG_LEVEL_ERROR, "Failed to buffer the encrypted "
4505             "request body to apply filters or taggers.");
4506          log_error(LOG_LEVEL_CLF,
4507             "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, csp->http->cmd);
4508
4509          ssl_send_data_delayed(&(csp->ssl_client_attr),
4510             (const unsigned char *)CLIENT_BODY_BUFFER_ERROR_RESPONSE,
4511             strlen(CLIENT_BODY_BUFFER_ERROR_RESPONSE),
4512             get_write_delay(csp));
4513
4514          return;
4515       }
4516       else
4517 #endif
4518       if (read_http_request_body(csp))
4519       {
4520          log_error(LOG_LEVEL_ERROR,
4521             "Failed to buffer the request body to apply filters or taggers,");
4522          log_error(LOG_LEVEL_CLF,
4523             "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, csp->http->cmd);
4524
4525          write_socket_delayed(csp->cfd, CLIENT_BODY_BUFFER_ERROR_RESPONSE,
4526             strlen(CLIENT_BODY_BUFFER_ERROR_RESPONSE), get_write_delay(csp));
4527
4528          return;
4529       }
4530       if (client_body_taggers_enabled(csp->action))
4531       {
4532          execute_client_body_taggers(csp, csp->expected_client_content_length);
4533          if (crunch_response_triggered(csp, crunchers_all))
4534          {
4535             /*
4536              * Yes. The client got the crunch response and we're done here.
4537              */
4538             return;
4539          }
4540       }
4541       if (client_body_filters_enabled(csp->action))
4542       {
4543          modified_content_length = csp->expected_client_content_length;
4544          content_modified = execute_client_body_filters(csp,
4545             &modified_content_length);
4546          if ((content_modified == 1) &&
4547             (modified_content_length != csp->expected_client_content_length) &&
4548             update_client_headers(csp, modified_content_length))
4549          {
4550             /* XXX: Send error response */
4551             log_error(LOG_LEVEL_HEADER, "Error updating client headers");
4552             return;
4553          }
4554       }
4555       csp->expected_client_content_length = 0;
4556    }
4557
4558    log_applied_actions(csp->action);
4559
4560    /* decide how to route the HTTP request */
4561    fwd = forward_url(csp, http);
4562
4563    freez(csp->headers->first->str);
4564    build_request_line(csp, fwd, &csp->headers->first->str);
4565
4566    if (fwd->forward_host)
4567    {
4568       log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
4569          fwd->forward_host, fwd->forward_port, http->hostport);
4570    }
4571    else
4572    {
4573       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
4574    }
4575
4576    /* here we connect to the server, gateway, or the forwarder */
4577
4578 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4579    if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
4580       && socket_is_still_alive(csp->server_connection.sfd)
4581       && connection_destination_matches(&csp->server_connection, http, fwd))
4582    {
4583       log_error(LOG_LEVEL_CONNECT,
4584          "Reusing server socket %d connected to %s. Total requests: %u.",
4585          csp->server_connection.sfd, csp->server_connection.host,
4586          csp->server_connection.requests_sent_total);
4587    }
4588    else
4589    {
4590       if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4591       {
4592 #ifdef FEATURE_CONNECTION_SHARING
4593          if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
4594 #ifdef FEATURE_HTTPS_INSPECTION
4595             && !server_use_ssl(csp)
4596 #endif
4597             )
4598          {
4599             remember_connection(&csp->server_connection);
4600          }
4601          else
4602 #endif /* def FEATURE_CONNECTION_SHARING */
4603          {
4604             log_error(LOG_LEVEL_CONNECT,
4605                "Closing server socket %d connected to %s. Total requests: %u.",
4606                csp->server_connection.sfd, csp->server_connection.host,
4607                csp->server_connection.requests_sent_total);
4608             close_socket(csp->server_connection.sfd);
4609          }
4610          mark_connection_closed(&csp->server_connection);
4611       }
4612 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4613
4614       /*
4615        * Connecting to destination server
4616        */
4617       csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
4618
4619       if (csp->server_connection.sfd == JB_INVALID_SOCKET)
4620       {
4621          if (fwd->type != SOCKS_NONE)
4622          {
4623             /* Socks error. */
4624             rsp = error_response(csp, "forwarding-failed");
4625          }
4626          else if (errno == EINVAL)
4627          {
4628             rsp = error_response(csp, "no-such-domain");
4629          }
4630          else
4631          {
4632             rsp = error_response(csp, "connect-failed");
4633          }
4634
4635          /* Write the answer to the client */
4636          if (rsp != NULL)
4637          {
4638             send_crunch_response(csp, rsp);
4639          }
4640
4641          /*
4642           * Temporary workaround to prevent already-read client
4643           * bodies from being parsed as new requests. For now we
4644           * err on the safe side and throw all the following
4645           * requests under the bus, even if no client body has been
4646           * buffered. A compliant client will repeat the dropped
4647           * requests on an untainted connection.
4648           *
4649           * The proper fix is to discard the no longer needed
4650           * client body in the buffer (if there is one) and to
4651           * continue parsing the bytes that follow.
4652           */
4653 #ifdef FEATURE_HTTPS_INSPECTION
4654          close_client_ssl_connection(csp);
4655 #endif
4656          drain_and_close_socket(csp->cfd);
4657          csp->cfd = JB_INVALID_SOCKET;
4658
4659          return;
4660       }
4661
4662 #ifdef FEATURE_HTTPS_INSPECTION
4663       /*
4664        * Creating TLS/SSL connections with destination server or parent
4665        * proxy. If forwarding is enabled, we must send client request to
4666        * parent proxy and receive, parse and resend parent proxy answer.
4667        */
4668       if (http->ssl && !use_ssl_tunnel)
4669       {
4670          if (fwd->forward_host != NULL)
4671          {
4672             char server_response[BUFFER_SIZE];
4673             int ret = 0;
4674             int len = 0;
4675             char *hdr = list_to_text(csp->headers);
4676             memset(server_response, 0, sizeof(server_response));
4677
4678             if (hdr == NULL)
4679             {
4680                log_error(LOG_LEVEL_FATAL,
4681                   "Out of memory parsing client header");
4682             }
4683             list_remove_all(csp->headers);
4684
4685             /*
4686              * Sending client's CONNECT request to the parent proxy
4687              */
4688             ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4689
4690             freez(hdr);
4691
4692             if (ret != 0)
4693             {
4694                log_error(LOG_LEVEL_CONNECT,
4695                   "Sending request headers to: %s failed", http->hostport);
4696                mark_server_socket_tainted(csp);
4697                close_client_ssl_connection(csp);
4698                return;
4699             }
4700
4701             /* Waiting for parent proxy server response */
4702             len = read_socket(csp->server_connection.sfd, server_response,
4703                sizeof(server_response)-1);
4704
4705             if (len <= 0)
4706             {
4707                log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4708                   "server on socket %d.", csp->server_connection.sfd);
4709
4710                rsp = error_response(csp, "no-server-data");
4711                if (rsp)
4712                {
4713                   send_crunch_response(csp, rsp);
4714                }
4715                mark_server_socket_tainted(csp);
4716                close_client_ssl_connection(csp);
4717                return;
4718             }
4719
4720             /*
4721              * Test if the connection to the destination server was
4722              * established successfully by the parent proxy.
4723              */
4724             if (!tunnel_established_successfully(server_response, (unsigned int)len))
4725             {
4726                log_error(LOG_LEVEL_ERROR,
4727                   "The forwarder %s failed to establish a connection with %s",
4728                   fwd->forward_host, http->host);
4729                rsp = error_response(csp, "connect-failed");
4730                if (rsp)
4731                {
4732                   send_crunch_response(csp, rsp);
4733                }
4734                mark_server_socket_tainted(csp);
4735                close_client_ssl_connection(csp);
4736                return;
4737             }
4738          } /* -END- if (fwd->forward_host != NULL) */
4739
4740          /*
4741           * We can now create the TLS/SSL connection with the destination server.
4742           */
4743          int ret = create_server_ssl_connection(csp);
4744          if (ret != 0)
4745          {
4746             if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4747                 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4748             {
4749                /*
4750                 * If the server certificate is invalid, we must inform
4751                 * the client and then close connection to the client.
4752                 */
4753                ssl_send_certificate_error(csp);
4754                close_client_and_server_ssl_connections(csp);
4755                return;
4756             }
4757             if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4758              || csp->server_cert_verification_result == SSL_CERT_VALID)
4759             {
4760                /*
4761                 * The TLS/SSL connection wasn't created but an invalid
4762                 * certificate wasn't detected. Report it as connection
4763                 * failure.
4764                 */
4765                rsp = error_response(csp, "connect-failed");
4766                if (rsp)
4767                {
4768                   send_crunch_response(csp, rsp);
4769                }
4770                close_client_and_server_ssl_connections(csp);
4771                return;
4772             }
4773          }
4774       }/* -END- if (http->ssl) */
4775 #endif /* def FEATURE_HTTPS_INSPECTION */
4776
4777 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4778       save_connection_destination(csp->server_connection.sfd,
4779          http, fwd, &csp->server_connection);
4780       csp->server_connection.keep_alive_timeout =
4781          (unsigned)csp->config->keep_alive_timeout;
4782    }
4783 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4784
4785    csp->server_connection.requests_sent_total++;
4786
4787    if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4788    {
4789       /* Client headers have been sent optimistically */
4790       assert(csp->headers->last == NULL);
4791    }
4792    else if (http->ssl == 0 || (fwd->forward_host
4793 #ifdef FEATURE_HTTPS_INSPECTION
4794          && use_ssl_tunnel
4795 #endif
4796            ))
4797    {
4798       int status = send_http_request(csp);
4799       if (status == 2)
4800       {
4801          /* The request got crunched, a response has been delivered. */
4802          return;
4803       }
4804       if (status != 0)
4805       {
4806          rsp = error_response(csp, "connect-failed");
4807          if (rsp)
4808          {
4809             send_crunch_response(csp, rsp);
4810          }
4811          return;
4812       }
4813    }
4814    else
4815    {
4816       /*
4817        * Using old solution with SSL tunnel or new solution with SSL proxy
4818        */
4819       list_remove_all(csp->headers);
4820 #ifdef FEATURE_HTTPS_INSPECTION
4821       if (use_ssl_tunnel)
4822 #endif
4823       {
4824          /*
4825          * We're running an SSL tunnel and we're not forwarding,
4826          * so just ditch the client headers, send the "connect succeeded"
4827          * message to the client, flush the rest, and get out of the way.
4828          */
4829          if (write_socket_delayed(csp->cfd, CSUCCEED,
4830                strlen(CSUCCEED), get_write_delay(csp)))
4831          {
4832             return;
4833          }
4834       }
4835 #ifdef FEATURE_HTTPS_INSPECTION
4836       else
4837       {
4838          /*
4839           * If server certificate has been verified and is invalid,
4840           * we must inform the client and then close the connection
4841           * with client and server.
4842           */
4843          if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4844              csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4845          {
4846             ssl_send_certificate_error(csp);
4847             close_client_and_server_ssl_connections(csp);
4848             return;
4849          }
4850          if (send_https_request(csp))
4851          {
4852             rsp = error_response(csp, "connect-failed");
4853             if (rsp)
4854             {
4855                send_crunch_response(csp, rsp);
4856             }
4857             close_client_and_server_ssl_connections(csp);
4858             return;
4859          }
4860       }
4861 #endif /* def FEATURE_HTTPS_INSPECTION */
4862       clear_iob(csp->client_iob);
4863    }/* -END- else ... if (http->ssl == 1) */
4864
4865    log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4866
4867    /* XXX: should the time start earlier for optimistically sent data? */
4868    csp->server_connection.request_sent = time(NULL);
4869
4870    handle_established_connection(csp);
4871    freez(csp->receive_buffer);
4872 }
4873
4874
4875 #ifdef FUZZ
4876 /*********************************************************************
4877  *
4878  * Function    :  fuzz_server_response
4879  *
4880  * Description :  Treat the input as a whole server response.
4881  *
4882  * Parameters  :
4883  *          1  :  csp = Current client state (buffers, headers, etc...)
4884  *          2  :  fuzz_input_file = File to read the input from.
4885  *
4886  * Returns     :  0
4887  *
4888  *********************************************************************/
4889 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4890 {
4891    static struct forward_spec fwd; /* Zero'd due to being static */
4892    csp->cfd = 0;
4893
4894    if (strcmp(fuzz_input_file, "-") == 0)
4895    {
4896       /* XXX: Doesn't work yet. */
4897       csp->server_connection.sfd = 0;
4898    }
4899    else
4900    {
4901       csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4902       if (csp->server_connection.sfd == -1)
4903       {
4904          log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4905             fuzz_input_file);
4906       }
4907    }
4908    csp->fwd = &fwd;
4909    csp->content_type |= CT_GIF;
4910    csp->action->flags |= ACTION_DEANIMATE;
4911    csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4912
4913    csp->http->path = strdup_or_die("/");
4914    csp->http->host = strdup_or_die("fuzz.example.org");
4915    csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4916    /* Prevent client socket monitoring */
4917    csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4918    csp->flags |= CSP_FLAG_CHUNKED;
4919
4920    csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4921    csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4922
4923    csp->content_type |= CT_DECLARED|CT_GIF;
4924
4925    csp->config->socket_timeout = 0;
4926
4927    cgi_init_error_messages();
4928
4929    handle_established_connection(csp);
4930    freez(csp->receive_buffer);
4931
4932    return 0;
4933 }
4934 #endif
4935
4936
4937 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4938 /*********************************************************************
4939  *
4940  * Function    :  prepare_csp_for_next_request
4941  *
4942  * Description :  Put the csp in a mostly vergin state.
4943  *
4944  * Parameters  :
4945  *          1  :  csp = Current client state (buffers, headers, etc...)
4946  *
4947  * Returns     :  N/A
4948  *
4949  *********************************************************************/
4950 static void prepare_csp_for_next_request(struct client_state *csp)
4951 {
4952    csp->content_type = 0;
4953    csp->content_length = 0;
4954    csp->expected_content_length = 0;
4955    csp->expected_client_content_length = 0;
4956    list_remove_all(csp->headers);
4957    clear_iob(csp->iob);
4958    freez(csp->error_message);
4959    free_http_request(csp->http);
4960    destroy_list(csp->headers);
4961 #ifdef FEATURE_HTTPS_INSPECTION
4962    destroy_list(csp->https_headers);
4963 #endif
4964    destroy_list(csp->tags);
4965 #ifdef FEATURE_CLIENT_TAGS
4966    destroy_list(csp->client_tags);
4967    freez(csp->client_address);
4968 #endif
4969    free_current_action(csp->action);
4970    if (NULL != csp->fwd)
4971    {
4972       unload_forward_spec(csp->fwd);
4973       csp->fwd = NULL;
4974    }
4975    /* XXX: Store per-connection flags someplace else. */
4976    csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4977 #ifdef FEATURE_TOGGLE
4978    if (global_toggle_state)
4979 #endif /* def FEATURE_TOGGLE */
4980    {
4981       csp->flags |= CSP_FLAG_TOGGLED_ON;
4982    }
4983
4984    if (csp->client_iob->eod > csp->client_iob->cur)
4985    {
4986       long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4987       size_t data_length  = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4988
4989       assert(bytes_to_shift > 0);
4990       assert(data_length > 0);
4991
4992       log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4993          data_length, bytes_to_shift);
4994       memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4995       csp->client_iob->cur = csp->client_iob->buf;
4996       assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4997       csp->client_iob->eod = csp->client_iob->buf + data_length;
4998       memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4999
5000       csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
5001    }
5002    else
5003    {
5004       /*
5005        * We mainly care about resetting client_iob->cur so we don't
5006        * waste buffer space at the beginning and don't mess up the
5007        * request restoration done by cgi_show_request().
5008        *
5009        * Freeing the buffer itself isn't technically necessary,
5010        * but makes debugging more convenient.
5011        */
5012       clear_iob(csp->client_iob);
5013    }
5014 }
5015 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
5016
5017
5018 /*********************************************************************
5019  *
5020  * Function    :  serve
5021  *
5022  * Description :  This is little more than chat.  We only "serve" to
5023  *                to close (or remember) any socket that chat may have
5024  *                opened.
5025  *
5026  * Parameters  :
5027  *          1  :  csp = Current client state (buffers, headers, etc...)
5028  *
5029  * Returns     :  N/A
5030  *
5031  *********************************************************************/
5032 static void serve(struct client_state *csp)
5033 {
5034    int config_file_change_detected = 0; /* Only used for debugging */
5035 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
5036 #ifdef FEATURE_CONNECTION_SHARING
5037    static int monitor_thread_running = 0;
5038 #endif /* def FEATURE_CONNECTION_SHARING */
5039    int continue_chatting = 0;
5040
5041    log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
5042       csp->ip_addr_str, csp->cfd);
5043
5044    do
5045    {
5046       unsigned int latency;
5047
5048 #ifdef FEATURE_HTTPS_INSPECTION
5049       if (continue_chatting && client_use_ssl(csp))
5050       {
5051          continue_https_chat(csp);
5052       }
5053       else
5054 #endif
5055       {
5056          chat(csp);
5057       }
5058
5059       /*
5060        * If the request has been crunched,
5061        * the calculated latency is zero.
5062        */
5063       latency = (unsigned)(csp->server_connection.response_received -
5064          csp->server_connection.request_sent) / 2;
5065
5066       if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
5067          && (csp->flags & CSP_FLAG_CRUNCHED)
5068          && (csp->expected_client_content_length != 0))
5069       {
5070          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
5071          log_error(LOG_LEVEL_CONNECT,
5072             "Tainting client socket %d due to unread data.", csp->cfd);
5073       }
5074
5075       continue_chatting = (csp->config->feature_flags
5076          & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
5077          && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
5078          && (csp->cfd != JB_INVALID_SOCKET)
5079          && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
5080          && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
5081             || (csp->flags & CSP_FLAG_CHUNKED));
5082
5083       if (!(csp->flags & CSP_FLAG_CRUNCHED)
5084          && (csp->server_connection.sfd != JB_INVALID_SOCKET))
5085       {
5086          if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
5087          {
5088             csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
5089          }
5090          if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
5091             || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
5092             || !socket_is_still_alive(csp->server_connection.sfd)
5093             || !(latency < csp->server_connection.keep_alive_timeout))
5094          {
5095             log_error(LOG_LEVEL_CONNECT,
5096                "Closing server socket %d connected to %s. "
5097                "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
5098                csp->server_connection.sfd, (csp->server_connection.host != NULL) ?
5099                csp->server_connection.host : csp->http->host,
5100                0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
5101                0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
5102                socket_is_still_alive(csp->server_connection.sfd),
5103                csp->server_connection.keep_alive_timeout);
5104 #ifdef FEATURE_CONNECTION_SHARING
5105             if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
5106             {
5107                forget_connection(csp->server_connection.sfd);
5108             }
5109 #endif /* def FEATURE_CONNECTION_SHARING */
5110 #ifdef FEATURE_HTTPS_INSPECTION
5111             close_server_ssl_connection(csp);
5112 #endif
5113             close_socket(csp->server_connection.sfd);
5114             mark_connection_closed(&csp->server_connection);
5115 #ifdef FEATURE_HTTPS_INSPECTION
5116             if (continue_chatting && client_use_ssl(csp))
5117             {
5118                /*
5119                 * Close the client socket as well as Privoxy currently
5120                 * can't establish a new server connection when the client
5121                 * socket is reused and would drop the connection in
5122                 * continue_https_chat() anyway.
5123                 */
5124                continue_chatting = 0;
5125                csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
5126                log_error(LOG_LEVEL_CONNECT,
5127                   "Client socket %d is no longer usable. "
5128                   "The server socket has been closed.", csp->cfd);
5129             }
5130 #endif
5131          }
5132       }
5133
5134       if (continue_chatting && any_loaded_file_changed(csp))
5135       {
5136          continue_chatting = 0;
5137          config_file_change_detected = 1;
5138       }
5139 #ifdef FEATURE_HTTPS_INSPECTION
5140       if (continue_chatting && client_use_ssl(csp) &&
5141          csp->ssl_with_client_is_opened == 0)
5142       {
5143          continue_chatting = 0;
5144          log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
5145             "The TLS session has been terminated.", csp->cfd);
5146       }
5147 #endif
5148
5149       if (continue_chatting)
5150       {
5151          if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
5152             && socket_is_still_alive(csp->cfd))
5153          {
5154             log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
5155                "pipelined on socket %d and the socket is still alive.",
5156                csp->requests_received_total+1, csp->cfd);
5157             prepare_csp_for_next_request(csp);
5158             continue;
5159          }
5160
5161          if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
5162          {
5163             if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5164             {
5165                log_error(LOG_LEVEL_CONNECT,
5166                   "Waiting for the next client request on socket %d. "
5167                   "Keeping the server socket %d to %s open.",
5168                   csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
5169             }
5170             else
5171             {
5172                log_error(LOG_LEVEL_CONNECT,
5173                   "Waiting for the next client request on socket %d. "
5174                   "No server socket to keep open.", csp->cfd);
5175             }
5176          }
5177
5178          if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
5179             && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
5180             && socket_is_still_alive(csp->cfd))
5181          {
5182             log_error(LOG_LEVEL_CONNECT,
5183                "Data arrived in time on client socket %d. Requests so far: %u",
5184                csp->cfd, csp->requests_received_total);
5185             prepare_csp_for_next_request(csp);
5186          }
5187          else
5188          {
5189 #ifdef FEATURE_CONNECTION_SHARING
5190             if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
5191                && (csp->server_connection.sfd != JB_INVALID_SOCKET)
5192                && (socket_is_still_alive(csp->server_connection.sfd))
5193 #ifdef FEATURE_HTTPS_INSPECTION
5194                && !server_use_ssl(csp)
5195 #endif
5196                 )
5197             {
5198                time_t time_open = time(NULL) - csp->server_connection.timestamp;
5199
5200                if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
5201                {
5202                   break;
5203                }
5204
5205                remember_connection(&csp->server_connection);
5206                csp->server_connection.sfd = JB_INVALID_SOCKET;
5207                drain_and_close_socket(csp->cfd);
5208                csp->cfd = JB_INVALID_SOCKET;
5209                privoxy_mutex_lock(&connection_reuse_mutex);
5210                if (!monitor_thread_running)
5211                {
5212                   monitor_thread_running = 1;
5213                   privoxy_mutex_unlock(&connection_reuse_mutex);
5214                   wait_for_alive_connections();
5215                   privoxy_mutex_lock(&connection_reuse_mutex);
5216                   monitor_thread_running = 0;
5217                }
5218                privoxy_mutex_unlock(&connection_reuse_mutex);
5219             }
5220 #endif /* def FEATURE_CONNECTION_SHARING */
5221             break;
5222          }
5223       }
5224       else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5225       {
5226          log_error(LOG_LEVEL_CONNECT,
5227             "Closing server socket %d connected to %s. Keep-alive: %u. "
5228             "Tainted: %u. Socket alive: %u. Timeout: %u. "
5229             "Configuration file change detected: %u",
5230             csp->server_connection.sfd, csp->server_connection.host,
5231             0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
5232             0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
5233             socket_is_still_alive(csp->server_connection.sfd),
5234             csp->server_connection.keep_alive_timeout,
5235             config_file_change_detected);
5236       }
5237    } while (continue_chatting);
5238
5239 #else
5240    chat(csp);
5241 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
5242
5243    if (csp->cfd != JB_INVALID_SOCKET)
5244    {
5245       log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
5246          "Keep-alive: %u. Socket alive: %u. Data available: %u. "
5247          "Configuration file change detected: %u. Requests received: %u.",
5248          csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
5249          socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
5250          config_file_change_detected, csp->requests_received_total);
5251 #ifdef FEATURE_HTTPS_INSPECTION
5252       close_client_ssl_connection(csp);
5253 #endif
5254       drain_and_close_socket(csp->cfd);
5255    }
5256
5257    if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5258    {
5259 #ifdef FEATURE_CONNECTION_SHARING
5260       if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
5261       {
5262          forget_connection(csp->server_connection.sfd);
5263       }
5264 #endif /* def FEATURE_CONNECTION_SHARING */
5265
5266 #ifdef FEATURE_HTTPS_INSPECTION
5267       close_server_ssl_connection(csp);
5268 #endif /* def FEATURE_HTTPS_INSPECTION */
5269
5270       close_socket(csp->server_connection.sfd);
5271    }
5272
5273 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
5274    mark_connection_closed(&csp->server_connection);
5275 #endif
5276
5277    free_csp_resources(csp);
5278
5279    csp->flags &= ~CSP_FLAG_ACTIVE;
5280
5281 }
5282
5283
5284 #ifdef __BEOS__
5285 /*********************************************************************
5286  *
5287  * Function    :  server_thread
5288  *
5289  * Description :  We only exist to call `serve' in a threaded environment.
5290  *
5291  * Parameters  :
5292  *          1  :  data = Current client state (buffers, headers, etc...)
5293  *
5294  * Returns     :  Always 0.
5295  *
5296  *********************************************************************/
5297 static int32 server_thread(void *data)
5298 {
5299    serve((struct client_state *) data);
5300    return 0;
5301
5302 }
5303 #endif
5304
5305
5306 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5307 /*********************************************************************
5308  *
5309  * Function    :  usage
5310  *
5311  * Description :  Print usage info & exit.
5312  *
5313  * Parameters  :  Pointer to argv[0] for identifying ourselves
5314  *
5315  * Returns     :  No. ,-)
5316  *
5317  *********************************************************************/
5318 static void usage(const char *name)
5319 {
5320    printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
5321           "Usage: %s [--config-test] "
5322 #if defined(unix)
5323           "[--chroot] "
5324 #endif /* defined(unix) */
5325           "[--help] "
5326 #if defined(unix)
5327           "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
5328 #endif /* defined(unix) */
5329          "[--version] [configfile]\n",
5330           name);
5331
5332 #ifdef FUZZ
5333    show_fuzz_usage(name);
5334 #endif
5335
5336    printf("Aborting\n");
5337
5338    exit(2);
5339
5340 }
5341 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
5342
5343
5344 #ifdef MUTEX_LOCKS_AVAILABLE
5345 /*********************************************************************
5346  *
5347  * Function    :  privoxy_mutex_lock
5348  *
5349  * Description :  Locks a mutex.
5350  *
5351  * Parameters  :
5352  *          1  :  mutex = The mutex to lock.
5353  *
5354  * Returns     :  Void. May exit in case of errors.
5355  *
5356  *********************************************************************/
5357 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
5358 {
5359 #ifdef FEATURE_PTHREAD
5360    int err = pthread_mutex_lock(mutex);
5361    if (err)
5362    {
5363       if (mutex != &log_mutex)
5364       {
5365          log_error(LOG_LEVEL_FATAL,
5366             "Mutex locking failed: %s.\n", strerror(err));
5367       }
5368       exit(1);
5369    }
5370 #else
5371    EnterCriticalSection(mutex);
5372 #endif /* def FEATURE_PTHREAD */
5373 }
5374
5375
5376 /*********************************************************************
5377  *
5378  * Function    :  privoxy_mutex_unlock
5379  *
5380  * Description :  Unlocks a mutex.
5381  *
5382  * Parameters  :
5383  *          1  :  mutex = The mutex to unlock.
5384  *
5385  * Returns     :  Void. May exit in case of errors.
5386  *
5387  *********************************************************************/
5388 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
5389 {
5390 #ifdef FEATURE_PTHREAD
5391    int err = pthread_mutex_unlock(mutex);
5392    if (err)
5393    {
5394       if (mutex != &log_mutex)
5395       {
5396          log_error(LOG_LEVEL_FATAL,
5397             "Mutex unlocking failed: %s.\n", strerror(err));
5398       }
5399       exit(1);
5400    }
5401 #else
5402    LeaveCriticalSection(mutex);
5403 #endif /* def FEATURE_PTHREAD */
5404 }
5405
5406
5407 /*********************************************************************
5408  *
5409  * Function    :  privoxy_mutex_init
5410  *
5411  * Description :  Prepares a mutex.
5412  *
5413  * Parameters  :
5414  *          1  :  mutex = The mutex to initialize.
5415  *
5416  * Returns     :  Void. May exit in case of errors.
5417  *
5418  *********************************************************************/
5419 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
5420 {
5421 #ifdef FEATURE_PTHREAD
5422    int err = pthread_mutex_init(mutex, 0);
5423    if (err)
5424    {
5425       printf("Fatal error. Mutex initialization failed: %s.\n",
5426          strerror(err));
5427       exit(1);
5428    }
5429 #else
5430    InitializeCriticalSection(mutex);
5431 #endif /* def FEATURE_PTHREAD */
5432 }
5433 #endif /* def MUTEX_LOCKS_AVAILABLE */
5434
5435 /*********************************************************************
5436  *
5437  * Function    :  initialize_mutexes
5438  *
5439  * Description :  Prepares mutexes if mutex support is available.
5440  *
5441  * Parameters  :  None
5442  *
5443  * Returns     :  Void, exits in case of errors.
5444  *
5445  *********************************************************************/
5446 static void initialize_mutexes(void)
5447 {
5448 #ifdef MUTEX_LOCKS_AVAILABLE
5449    /*
5450     * Prepare global mutex semaphores
5451     */
5452
5453 #ifdef FEATURE_HTTPS_INSPECTION
5454    privoxy_mutex_init(&certificate_mutex);
5455    privoxy_mutex_init(&ssl_init_mutex);
5456 #endif
5457
5458    privoxy_mutex_init(&log_mutex);
5459    privoxy_mutex_init(&log_init_mutex);
5460    privoxy_mutex_init(&connection_reuse_mutex);
5461 #ifdef FEATURE_EXTERNAL_FILTERS
5462    privoxy_mutex_init(&external_filter_mutex);
5463 #endif
5464 #ifdef FEATURE_CLIENT_TAGS
5465    privoxy_mutex_init(&client_tags_mutex);
5466 #endif
5467 #ifdef FEATURE_STATISTICS
5468    privoxy_mutex_init(&block_statistics_mutex);
5469 #endif
5470 #ifdef FEATURE_EXTENDED_STATISTICS
5471    privoxy_mutex_init(&filter_statistics_mutex);
5472    privoxy_mutex_init(&block_reason_statistics_mutex);
5473 #endif
5474
5475    /*
5476     * XXX: The assumptions below are a bit naive
5477     * and can cause locks that aren't necessary.
5478     *
5479     * For example older FreeBSD versions (< 6.x?)
5480     * have no gethostbyname_r, but gethostbyname is
5481     * thread safe.
5482     */
5483 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
5484    privoxy_mutex_init(&resolver_mutex);
5485 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
5486    /*
5487     * XXX: should we use a single mutex for
5488     * localtime() and gmtime() as well?
5489     */
5490 #ifndef HAVE_GMTIME_R
5491    privoxy_mutex_init(&gmtime_mutex);
5492 #endif /* ndef HAVE_GMTIME_R */
5493
5494 #ifndef HAVE_LOCALTIME_R
5495    privoxy_mutex_init(&localtime_mutex);
5496 #endif /* ndef HAVE_GMTIME_R */
5497
5498 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
5499    privoxy_mutex_init(&rand_mutex);
5500 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
5501
5502 #endif /* def MUTEX_LOCKS_AVAILABLE */
5503 }
5504
5505 /*********************************************************************
5506  *
5507  * Function    :  main
5508  *
5509  * Description :  Load the config file and start the listen loop.
5510  *                This function is a lot more *sane* with the `load_config'
5511  *                and `listen_loop' functions; although it stills does
5512  *                a *little* too much for my taste.
5513  *
5514  * Parameters  :
5515  *          1  :  argc = Number of parameters (including $0).
5516  *          2  :  argv = Array of (char *)'s to the parameters.
5517  *
5518  * Returns     :  1 if : can't open config file, unrecognized directive,
5519  *                stats requested in multi-thread mode, can't open the
5520  *                log file, can't open the jar file, listen port is invalid,
5521  *                any load fails, and can't bind port.
5522  *
5523  *                Else main never returns, the process must be signaled
5524  *                to terminate execution.  Or, on Windows, use the
5525  *                "File", "Exit" menu option.
5526  *
5527  *********************************************************************/
5528 #ifdef __MINGW32__
5529 int real_main(int argc, char **argv)
5530 #else
5531 int main(int argc, char **argv)
5532 #endif
5533 {
5534    int argc_pos = 0;
5535    int do_config_test = 0;
5536 #ifndef HAVE_ARC4RANDOM
5537    unsigned int random_seed;
5538 #endif
5539 #ifdef unix
5540    struct passwd *pw = NULL;
5541    struct group *grp = NULL;
5542    int do_chroot = 0;
5543    char *pre_chroot_nslookup_to_load_resolver = NULL;
5544 #endif
5545 #ifdef FUZZ
5546    char *fuzz_input_type = NULL;
5547    char *fuzz_input_file = NULL;
5548 #endif
5549
5550    Argc = argc;
5551    Argv = argv;
5552
5553    configfile =
5554 #if !defined(_WIN32)
5555    "config"
5556 #else
5557    "config.txt"
5558 #endif
5559       ;
5560
5561    /* Prepare mutexes if supported and necessary. */
5562    initialize_mutexes();
5563
5564    /* Enable logging until further notice. */
5565    init_log_module();
5566
5567    /*
5568     * Parse the command line arguments
5569     *
5570     * XXX: simply printing usage information in case of
5571     * invalid arguments isn't particularly user friendly.
5572     */
5573    while (++argc_pos < argc)
5574    {
5575 #ifdef _WIN32
5576       /* Check to see if the service must be installed or uninstalled */
5577       if (strncmp(argv[argc_pos], "--install", 9) == 0)
5578       {
5579          const char *pName = argv[argc_pos] + 9;
5580          if (*pName == ':')
5581             pName++;
5582          exit((install_service(pName)) ? 0 : 1);
5583       }
5584       else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
5585       {
5586          const char *pName = argv[argc_pos] + 11;
5587          if (*pName == ':')
5588             pName++;
5589          exit((uninstall_service(pName)) ? 0 : 1);
5590       }
5591       else if (strcmp(argv[argc_pos], "--service") == 0)
5592       {
5593          bRunAsService = TRUE;
5594          w32_set_service_cwd();
5595          atexit(w32_service_exit_notify);
5596       }
5597       else
5598 #endif /* defined(_WIN32) */
5599
5600
5601 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5602
5603       if (strcmp(argv[argc_pos], "--help") == 0)
5604       {
5605          usage(argv[0]);
5606       }
5607
5608       else if (strcmp(argv[argc_pos], "--version") == 0)
5609       {
5610          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
5611          exit(0);
5612       }
5613
5614 #if defined(unix)
5615
5616       else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
5617       {
5618          set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
5619          daemon_mode = 0;
5620       }
5621
5622       else if (strcmp(argv[argc_pos], "--pidfile") == 0)
5623       {
5624          if (++argc_pos == argc) usage(argv[0]);
5625          pidfile = strdup_or_die(argv[argc_pos]);
5626       }
5627
5628       else if (strcmp(argv[argc_pos], "--user") == 0)
5629       {
5630          char *user_arg;
5631          char *group_name;
5632
5633          if (++argc_pos == argc) usage(argv[argc_pos]);
5634
5635          user_arg = strdup_or_die(argv[argc_pos]);
5636          group_name = strchr(user_arg, '.');
5637          if (NULL != group_name)
5638          {
5639             /* Nul-terminate the user name */
5640             *group_name = '\0';
5641
5642             /* Skip the former delimiter to actually reach the group name */
5643             group_name++;
5644
5645             grp = getgrnam(group_name);
5646             if (NULL == grp)
5647             {
5648                log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
5649             }
5650          }
5651          pw = getpwnam(user_arg);
5652          if (NULL == pw)
5653          {
5654             log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
5655          }
5656
5657          freez(user_arg);
5658       }
5659
5660       else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
5661       {
5662          if (++argc_pos == argc) usage(argv[0]);
5663          pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
5664       }
5665
5666       else if (strcmp(argv[argc_pos], "--chroot") == 0)
5667       {
5668          do_chroot = 1;
5669       }
5670 #endif /* defined(unix) */
5671
5672       else if (strcmp(argv[argc_pos], "--config-test") == 0)
5673       {
5674          do_config_test = 1;
5675       }
5676 #ifdef FUZZ
5677       else if (strcmp(argv[argc_pos], "--fuzz") == 0)
5678       {
5679          argc_pos++;
5680          if (argc < argc_pos + 2) usage(argv[0]);
5681          fuzz_input_type = argv[argc_pos];
5682          argc_pos++;
5683          fuzz_input_file = argv[argc_pos];
5684       }
5685       else if (strcmp(argv[argc_pos], "--stfu") == 0)
5686       {
5687          set_debug_level(LOG_LEVEL_STFU);
5688       }
5689 #endif
5690       else if (argc_pos + 1 != argc)
5691       {
5692          /*
5693           * This is neither the last command line
5694           * option, nor was it recognized before,
5695           * therefore it must be invalid.
5696           */
5697          usage(argv[0]);
5698       }
5699       else
5700
5701 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
5702       {
5703          configfile = argv[argc_pos];
5704       }
5705
5706    } /* -END- while (more arguments) */
5707
5708    show_version(Argv[0]);
5709
5710 #if defined(unix)
5711    if (*configfile != '/')
5712    {
5713       char cwd[BUFFER_SIZE];
5714       char *abs_file;
5715       size_t abs_file_size;
5716
5717       /* make config-filename absolute here */
5718       if (NULL == getcwd(cwd, sizeof(cwd)))
5719       {
5720          perror("failed to get current working directory");
5721          exit(1);
5722       }
5723
5724       basedir = strdup_or_die(cwd);
5725       /* XXX: why + 5? */
5726       abs_file_size = strlen(cwd) + strlen(configfile) + 5;
5727       abs_file = malloc_or_die(abs_file_size);
5728       strlcpy(abs_file, basedir, abs_file_size);
5729       strlcat(abs_file, "/", abs_file_size);
5730       strlcat(abs_file, configfile, abs_file_size);
5731       configfile = abs_file;
5732    }
5733 #endif /* defined unix */
5734
5735
5736    files->next = NULL;
5737    clients->next = NULL;
5738
5739    /* XXX: factor out initialising after the next stable release. */
5740 #ifdef _WIN32
5741    InitWin32();
5742 #endif
5743
5744 #ifndef HAVE_ARC4RANDOM
5745    random_seed = (unsigned int)time(NULL);
5746 #ifdef HAVE_RANDOM
5747    srandom(random_seed);
5748 #else
5749    srand(random_seed);
5750 #endif /* ifdef HAVE_RANDOM */
5751 #endif /* ifndef HAVE_ARC4RANDOM */
5752
5753    /*
5754     * Unix signal handling
5755     *
5756     * Catch the abort, interrupt and terminate signals for a graceful exit
5757     * Catch the hangup signal so the errlog can be reopened.
5758     *
5759     * Ignore the broken pipe signal as connection failures
5760     * are handled when and where they occur without relying
5761     * on a signal.
5762     */
5763 #if !defined(_WIN32)
5764 {
5765    int idx;
5766    const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5767
5768    for (idx = 0; idx < SZ(catched_signals); idx++)
5769    {
5770 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5771       if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5772 #else
5773       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5774 #endif /* ifdef sun */
5775       {
5776          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5777       }
5778    }
5779
5780    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5781    {
5782       log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5783    }
5784
5785 }
5786 #else /* ifdef _WIN32 */
5787 # ifdef _WIN_CONSOLE
5788    /*
5789     * We *are* in a windows console app.
5790     * Print a verbose messages about FAQ's and such
5791     */
5792    printf("%s", win32_blurb);
5793 # endif /* def _WIN_CONSOLE */
5794 #endif /* def _WIN32 */
5795
5796 #ifdef FUZZ
5797    if (fuzz_input_type != NULL)
5798    {
5799       exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5800    }
5801    log_error(LOG_LEVEL_FATAL,
5802       "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5803       "Various data structures are static which is unsafe when using threads.");
5804 #endif
5805
5806    if (do_config_test)
5807    {
5808       exit(NULL == load_config());
5809    }
5810
5811    /* Initialize the CGI subsystem */
5812    cgi_init_error_messages();
5813
5814    /*
5815     * If running on unix and without the --no-daemon
5816     * option, become a daemon. I.e. fork, detach
5817     * from tty and get process group leadership
5818     */
5819 #if defined(unix)
5820 {
5821    if (daemon_mode)
5822    {
5823       int fd;
5824       pid_t pid = fork();
5825
5826       if (pid < 0) /* error */
5827       {
5828          perror("fork");
5829          exit(3);
5830       }
5831       else if (pid != 0) /* parent */
5832       {
5833          int status;
5834          pid_t wpid;
5835          /*
5836           * must check for errors
5837           * child died due to missing files aso
5838           */
5839          sleep(1);
5840          wpid = waitpid(pid, &status, WNOHANG);
5841          if (wpid != 0)
5842          {
5843             exit(1);
5844          }
5845          exit(0);
5846       }
5847       /* child */
5848
5849       setsid();
5850
5851       /*
5852        * stderr (fd 2) will be closed later on,
5853        * when the config file has been parsed.
5854        */
5855       close(0);
5856       close(1);
5857
5858       /*
5859        * Reserve fd 0 and 1 to prevent abort() and friends
5860        * from sending stuff to the clients or servers.
5861        */
5862       fd = open("/dev/null", O_RDONLY);
5863       if (fd == -1)
5864       {
5865          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5866       }
5867       else if (fd != 0)
5868       {
5869          if (dup2(fd, 0) == -1)
5870          {
5871             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5872          }
5873          close(fd);
5874       }
5875       fd = open("/dev/null", O_WRONLY);
5876       if (fd == -1)
5877       {
5878          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5879       }
5880       else if (fd != 1)
5881       {
5882          if (dup2(fd, 1) == -1)
5883          {
5884             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5885          }
5886          close(fd);
5887       }
5888
5889 #ifdef FEATURE_EXTERNAL_FILTERS
5890       for (fd = 0; fd < 3; fd++)
5891       {
5892          mark_socket_for_close_on_execute(fd);
5893       }
5894 #endif
5895
5896       if (chdir("/") != 0)
5897       {
5898          log_error(LOG_LEVEL_FATAL, "Failed to cd into '/': %E");
5899       }
5900
5901    } /* -END- if (daemon_mode) */
5902
5903    /*
5904     * As soon as we have written the PID file, we can switch
5905     * to the user and group ID indicated by the --user option
5906     */
5907    if (pidfile != NULL)
5908    {
5909       write_pid_file(pidfile);
5910    }
5911    if (NULL != pw)
5912    {
5913       if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5914       {
5915          log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5916       }
5917       if (NULL != grp)
5918       {
5919          if (setgroups(1, &grp->gr_gid))
5920          {
5921             log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5922          }
5923       }
5924       else if (initgroups(pw->pw_name, pw->pw_gid))
5925       {
5926          log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5927       }
5928       if (do_chroot)
5929       {
5930          if (!pw->pw_dir)
5931          {
5932             log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5933          }
5934          /* Read the time zone file from /etc before doing chroot. */
5935          tzset();
5936          if (NULL != pre_chroot_nslookup_to_load_resolver
5937              && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5938          {
5939             /* Initialize resolver library. */
5940             (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5941          }
5942          if (chroot(pw->pw_dir) < 0)
5943          {
5944             log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5945          }
5946          if (chdir ("/"))
5947          {
5948             log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5949          }
5950       }
5951       if (setuid(pw->pw_uid))
5952       {
5953          log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5954       }
5955       if (do_chroot)
5956       {
5957          char putenv_dummy[64];
5958
5959          strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5960          if (putenv(putenv_dummy) != 0)
5961          {
5962             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5963          }
5964
5965          snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5966          if (putenv(putenv_dummy) != 0)
5967          {
5968             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5969          }
5970       }
5971    }
5972    else if (do_chroot)
5973    {
5974       log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5975    }
5976 }
5977 #endif /* defined unix */
5978
5979 #ifdef _WIN32
5980    /* This will be FALSE unless the command line specified --service
5981     */
5982    if (bRunAsService)
5983    {
5984       /* Yup, so now we must attempt to establish a connection
5985        * with the service dispatcher. This will only work if this
5986        * process was launched by the service control manager to
5987        * actually run as a service. If this isn't the case, i've
5988        * known it take around 30 seconds or so for the call to return.
5989        */
5990
5991       /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5992       if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5993       {
5994          /* Service has run, and at this point is now being stopped, so just return */
5995          return 0;
5996       }
5997
5998 #ifdef _WIN_CONSOLE
5999       printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
6000 #endif
6001       /* An error occurred. Usually it's because --service was wrongly specified
6002        * and we were unable to connect to the Service Control Dispatcher because
6003        * it wasn't expecting us and is therefore not listening.
6004        *
6005        * For now, just continue below to call the listen_loop function.
6006        */
6007    }
6008 #endif /* def _WIN32 */
6009
6010    listen_loop();
6011
6012    /* NOTREACHED */
6013    return(-1);
6014
6015 }
6016
6017
6018 /*********************************************************************
6019  *
6020  * Function    :  bind_port_helper
6021  *
6022  * Description :  Bind the listen port.  Handles logging, and aborts
6023  *                on failure.
6024  *
6025  * Parameters  :
6026  *          1  :  haddr = Host address to bind to. Use NULL to bind to
6027  *                        INADDR_ANY.
6028  *          2  :  hport = Specifies port to bind to.
6029  *          3  :  backlog = Listen backlog.
6030  *
6031  * Returns     :  Port that was opened.
6032  *
6033  *********************************************************************/
6034 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
6035 {
6036    int result;
6037    jb_socket bfd;
6038
6039    result = bind_port(haddr, hport, backlog, &bfd);
6040
6041    if (result < 0)
6042    {
6043       const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
6044       switch(result)
6045       {
6046          case -3:
6047             log_error(LOG_LEVEL_FATAL,
6048                "can't bind to %s:%d: There may be another Privoxy "
6049                "or some other proxy running on port %d",
6050                bind_address, hport, hport);
6051             exit(-1);
6052
6053          case -2:
6054             log_error(LOG_LEVEL_FATAL,
6055                "can't bind to %s:%d: The hostname is not resolvable",
6056                bind_address, hport);
6057             exit(-1);
6058
6059          default:
6060             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
6061                bind_address, hport);
6062             exit(-1);
6063       }
6064
6065       /* shouldn't get here */
6066       return JB_INVALID_SOCKET;
6067    }
6068
6069 #ifndef HAVE_POLL
6070 #ifndef _WIN32
6071    if (bfd >= FD_SETSIZE)
6072    {
6073       log_error(LOG_LEVEL_FATAL,
6074          "Bind socket number too high to use select(): %d >= %d",
6075          bfd, FD_SETSIZE);
6076    }
6077 #endif
6078 #endif
6079
6080    if (haddr == NULL)
6081    {
6082       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
6083          hport);
6084    }
6085    else
6086    {
6087       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
6088          hport, haddr);
6089    }
6090
6091    return bfd;
6092 }
6093
6094
6095 /*********************************************************************
6096  *
6097  * Function    :  bind_ports_helper
6098  *
6099  * Description :  Bind the listen ports.  Handles logging, and aborts
6100  *                on failure.
6101  *
6102  * Parameters  :
6103  *          1  :  config = Privoxy configuration.  Specifies ports
6104  *                         to bind to.
6105  *          2  :  sockets = Preallocated array of opened sockets
6106  *                          corresponding to specification in config.
6107  *                          All non-opened sockets will be set to
6108  *                          JB_INVALID_SOCKET.
6109  *
6110  * Returns     :  Nothing. Inspect sockets argument.
6111  *
6112  *********************************************************************/
6113 static void bind_ports_helper(struct configuration_spec * config,
6114                               jb_socket sockets[])
6115 {
6116    int i;
6117
6118    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
6119    {
6120       if (config->hport[i])
6121       {
6122          sockets[i] = bind_port_helper(config->haddr[i],
6123             config->hport[i], config->listen_backlog);
6124 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
6125          if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
6126          {
6127             struct accept_filter_arg af_options;
6128             bzero(&af_options, sizeof(af_options));
6129             strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
6130             if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
6131                   sizeof(af_options)))
6132             {
6133                log_error(LOG_LEVEL_ERROR,
6134                   "Enabling accept filter for socket %d failed: %E", sockets[i]);
6135             }
6136          }
6137 #endif
6138       }
6139       else
6140       {
6141          sockets[i] = JB_INVALID_SOCKET;
6142       }
6143    }
6144    config->need_bind = 0;
6145 }
6146
6147
6148 /*********************************************************************
6149  *
6150  * Function    :  close_ports_helper
6151  *
6152  * Description :  Close listenings ports.
6153  *
6154  * Parameters  :
6155  *          1  :  sockets = Array of opened and non-opened sockets to
6156  *                          close. All sockets will be set to
6157  *                          JB_INVALID_SOCKET.
6158  *
6159  * Returns     :  Nothing.
6160  *
6161  *********************************************************************/
6162 static void close_ports_helper(jb_socket sockets[])
6163 {
6164    int i;
6165
6166    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
6167    {
6168       if (JB_INVALID_SOCKET != sockets[i])
6169       {
6170          close_socket(sockets[i]);
6171       }
6172       sockets[i] = JB_INVALID_SOCKET;
6173    }
6174 }
6175
6176
6177 #ifdef _WIN32
6178 /* Without this simple workaround we get this compiler warning from _beginthread
6179  *     warning C4028: formal parameter 1 different from declaration
6180  */
6181 void w32_service_listen_loop(void *p)
6182 {
6183    listen_loop();
6184 }
6185 #endif /* def _WIN32 */
6186
6187
6188 /*********************************************************************
6189  *
6190  * Function    :  listen_loop
6191  *
6192  * Description :  bind the listen port and enter a "FOREVER" listening loop.
6193  *
6194  * Parameters  :  N/A
6195  *
6196  * Returns     :  Never.
6197  *
6198  *********************************************************************/
6199 static void listen_loop(void)
6200 {
6201    struct client_states *csp_list = NULL;
6202    struct client_state *csp = NULL;
6203    jb_socket bfds[MAX_LISTENING_SOCKETS];
6204    struct configuration_spec *config;
6205    unsigned int active_threads = 0;
6206 #if defined(FEATURE_PTHREAD)
6207    pthread_attr_t attrs;
6208
6209    pthread_attr_init(&attrs);
6210    pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
6211 #endif
6212
6213    config = load_config();
6214
6215 #ifdef FEATURE_CONNECTION_SHARING
6216    /*
6217     * XXX: Should be relocated once it no
6218     * longer needs to emit log messages.
6219     */
6220    initialize_reusable_connections();
6221 #endif /* def FEATURE_CONNECTION_SHARING */
6222
6223    bind_ports_helper(config, bfds);
6224
6225 #ifdef FEATURE_GRACEFUL_TERMINATION
6226    while (!g_terminate)
6227 #else
6228    for (;;)
6229 #endif
6230    {
6231 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
6232       while (waitpid(-1, NULL, WNOHANG) > 0)
6233       {
6234          /* zombie children */
6235       }
6236 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
6237
6238       /*
6239        * Free data that was used by died threads
6240        */
6241       active_threads = sweep();
6242
6243 #if defined(unix)
6244       /*
6245        * Re-open the errlog after HUP signal
6246        */
6247       if (received_hup_signal)
6248       {
6249          if (NULL != config->logfile)
6250          {
6251             init_error_log(Argv[0], config->logfile);
6252          }
6253          received_hup_signal = 0;
6254       }
6255 #endif
6256
6257       csp_list = zalloc_or_die(sizeof(*csp_list));
6258       csp = &csp_list->csp;
6259
6260       log_error(LOG_LEVEL_CONNECT,
6261          "Waiting for the next client connection. Currently active threads: %u",
6262          active_threads);
6263
6264       /*
6265        * This config may be outdated, but for accept_connection()
6266        * it's fresh enough.
6267        */
6268       csp->config = config;
6269
6270       if (!accept_connection(csp, bfds))
6271       {
6272          log_error(LOG_LEVEL_CONNECT,
6273             "Failed to accept() incoming connection: %E");
6274          freez(csp_list);
6275          continue;
6276       }
6277
6278       csp->flags |= CSP_FLAG_ACTIVE;
6279       csp->server_connection.sfd = JB_INVALID_SOCKET;
6280
6281       csp->config = config = load_config();
6282
6283       if (config->need_bind)
6284       {
6285          /*
6286           * Since we were listening to the "old port", we will not see
6287           * a "listen" param change until the next request.  So, at
6288           * least 1 more request must be made for us to find the new
6289           * setting.  I am simply closing the old socket and binding the
6290           * new one.
6291           *
6292           * Which-ever is correct, we will serve 1 more page via the
6293           * old settings.  This should probably be a "show-status"
6294           * request.  This should not be a so common of an operation
6295           * that this will hurt people's feelings.
6296           */
6297
6298          close_ports_helper(bfds);
6299
6300          bind_ports_helper(config, bfds);
6301       }
6302
6303 #ifdef FEATURE_TOGGLE
6304       if (global_toggle_state)
6305 #endif /* def FEATURE_TOGGLE */
6306       {
6307          csp->flags |= CSP_FLAG_TOGGLED_ON;
6308       }
6309
6310       if (run_loader(csp))
6311       {
6312          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
6313          /* Never get here - LOG_LEVEL_FATAL causes program exit */
6314       }
6315
6316 #ifdef FEATURE_ACL
6317       if (block_acl(NULL,csp))
6318       {
6319          log_error(LOG_LEVEL_CONNECT,
6320             "Connection from %s on %s (socket %d) dropped due to ACL",
6321             csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
6322          close_socket(csp->cfd);
6323          freez(csp->ip_addr_str);
6324          freez(csp->listen_addr_str);
6325          freez(csp_list);
6326          continue;
6327       }
6328 #endif /* def FEATURE_ACL */
6329
6330       if ((0 != config->max_client_connections)
6331          && (active_threads >= config->max_client_connections))
6332       {
6333          log_error(LOG_LEVEL_ERROR,
6334             "Rejecting connection from %s. Maximum number of connections reached.",
6335             csp->ip_addr_str);
6336          write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6337             strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6338          close_socket(csp->cfd);
6339          freez(csp->ip_addr_str);
6340          freez(csp->listen_addr_str);
6341          freez(csp_list);
6342          continue;
6343       }
6344
6345       /* add it to the list of clients */
6346       csp_list->next = clients->next;
6347       clients->next = csp_list;
6348
6349       if (config->multi_threaded)
6350       {
6351          int child_id;
6352
6353 /* this is a switch () statement in the C preprocessor - ugh */
6354 #undef SELECTED_ONE_OPTION
6355
6356 /* Use Pthreads in preference to native code */
6357 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
6358 #define SELECTED_ONE_OPTION
6359          {
6360             pthread_t the_thread;
6361             int ret;
6362
6363             ret = pthread_create(&the_thread, &attrs,
6364                (void * (*)(void *))serve, csp);
6365             child_id = ret ? -1 : 0;
6366          }
6367 #endif
6368
6369 #if defined(_WIN32) && !defined(SELECTED_ONE_OPTION)
6370 #define SELECTED_ONE_OPTION
6371          child_id = _beginthread(
6372             (void (*)(void *))serve,
6373             64 * 1024,
6374             csp);
6375 #endif
6376
6377 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
6378 #define SELECTED_ONE_OPTION
6379          {
6380             thread_id tid = spawn_thread
6381                (server_thread, "server", B_NORMAL_PRIORITY, csp);
6382
6383             if ((tid >= 0) && (resume_thread(tid) == B_OK))
6384             {
6385                child_id = (int) tid;
6386             }
6387             else
6388             {
6389                child_id = -1;
6390             }
6391          }
6392 #endif
6393
6394 #if !defined(SELECTED_ONE_OPTION)
6395          child_id = fork();
6396
6397          /* This block is only needed when using fork().
6398           * When using threads, the server thread was
6399           * created and run by the call to _beginthread().
6400           */
6401          if (child_id == 0)   /* child */
6402          {
6403             int rc = 0;
6404 #ifdef FEATURE_TOGGLE
6405             int inherited_toggle_state = global_toggle_state;
6406 #endif /* def FEATURE_TOGGLE */
6407
6408             serve(csp);
6409
6410             /*
6411              * If we've been toggled or we've blocked the request, tell Mom
6412              */
6413
6414 #ifdef FEATURE_TOGGLE
6415             if (inherited_toggle_state != global_toggle_state)
6416             {
6417                rc |= RC_FLAG_TOGGLED;
6418             }
6419 #endif /* def FEATURE_TOGGLE */
6420
6421 #ifdef FEATURE_STATISTICS
6422             if (csp->flags & CSP_FLAG_REJECTED)
6423             {
6424                rc |= RC_FLAG_BLOCKED;
6425             }
6426 #endif /* ndef FEATURE_STATISTICS */
6427
6428             _exit(rc);
6429          }
6430          else if (child_id > 0) /* parent */
6431          {
6432             /* in a fork()'d environment, the parent's
6433              * copy of the client socket and the CSP
6434              * are not used.
6435              */
6436             int child_status;
6437 #if !defined(_WIN32) && !defined(__CYGWIN__)
6438
6439             wait(&child_status);
6440
6441             /*
6442              * Evaluate child's return code: If the child has
6443              *  - been toggled, toggle ourselves
6444              *  - blocked its request, bump up the stats counter
6445              */
6446
6447 #ifdef FEATURE_TOGGLE
6448             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
6449             {
6450                global_toggle_state = !global_toggle_state;
6451             }
6452 #endif /* def FEATURE_TOGGLE */
6453
6454 #ifdef FEATURE_STATISTICS
6455             urls_read++;
6456             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
6457             {
6458                urls_rejected++;
6459             }
6460 #endif /* def FEATURE_STATISTICS */
6461
6462 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
6463             close_socket(csp->cfd);
6464             csp->flags &= ~CSP_FLAG_ACTIVE;
6465          }
6466 #endif
6467
6468 #undef SELECTED_ONE_OPTION
6469 /* end of cpp switch () */
6470
6471          if (child_id < 0)
6472          {
6473             /*
6474              * Spawning the child failed, assume it's because
6475              * there are too many children running already.
6476              * XXX: If you assume ...
6477              */
6478             log_error(LOG_LEVEL_ERROR,
6479                "Unable to take any additional connections: %E. Active threads: %u",
6480                active_threads);
6481             write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6482                strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6483             close_socket(csp->cfd);
6484             csp->flags &= ~CSP_FLAG_ACTIVE;
6485          }
6486       }
6487       else
6488       {
6489          serve(csp);
6490       }
6491    }
6492
6493 #if defined(FEATURE_PTHREAD)
6494    pthread_attr_destroy(&attrs);
6495 #endif
6496
6497    /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
6498
6499 #ifdef FEATURE_GRACEFUL_TERMINATION
6500
6501    log_error(LOG_LEVEL_INFO, "Graceful termination requested.");
6502
6503    close_ports_helper(bfds);
6504
6505    unload_current_config_file();
6506    unload_current_actions_file();
6507    unload_current_re_filterfile();
6508 #ifdef FEATURE_TRUST
6509    unload_current_trust_file();
6510 #endif
6511
6512    if (config->multi_threaded)
6513    {
6514       int i = 60;
6515       do
6516       {
6517          sleep(1);
6518          sweep();
6519       } while ((clients->next != NULL) && (--i > 0));
6520
6521       if (i <= 0)
6522       {
6523          log_error(LOG_LEVEL_ERROR, "Graceful termination failed "
6524             "- still some live clients after 1 minute wait.");
6525       }
6526    }
6527    sweep();
6528    sweep();
6529
6530 #if defined(unix)
6531    freez(basedir);
6532 #endif
6533
6534 #ifdef FEATURE_HTTPS_INSPECTION
6535    /*
6536     * Only release TLS backed resources if there
6537     * are no active connections left.
6538     */
6539    if (clients->next == NULL)
6540    {
6541       ssl_release();
6542    }
6543 #endif
6544
6545    log_error(LOG_LEVEL_INFO, "Exiting gracefully.");
6546
6547 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
6548    /* Cleanup - remove taskbar icon etc. */
6549    TermLogWindow();
6550 #endif
6551
6552    exit(0);
6553 #endif /* FEATURE_GRACEFUL_TERMINATION */
6554
6555 }
6556
6557
6558 /*
6559   Local Variables:
6560   tab-width: 3
6561   end:
6562 */