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