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