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