edda17d54c59ecab096098b5ef9f0f06d195d640
[privoxy.git] / jcc.c
1 const char jcc_rcs[] = "$Id: jcc.c,v 1.438 2016/01/16 12:30:43 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/jcc.c,v $
5  *
6  * Purpose     :  Main file.  Contains main() method, main loop, and
7  *                the main connection-handling function.
8  *
9  * Copyright   :  Written by and Copyright (C) 2001-2014 the
10  *                Privoxy team. http://www.privoxy.org/
11  *
12  *                Based on the Internet Junkbuster originally written
13  *                by and Copyright (C) 1997 Anonymous Coders and
14  *                Junkbusters Corporation.  http://www.junkbusters.com
15  *
16  *                This program is free software; you can redistribute it
17  *                and/or modify it under the terms of the GNU General
18  *                Public License as published by the Free Software
19  *                Foundation; either version 2 of the License, or (at
20  *                your option) any later version.
21  *
22  *                This program is distributed in the hope that it will
23  *                be useful, but WITHOUT ANY WARRANTY; without even the
24  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
25  *                PARTICULAR PURPOSE.  See the GNU General Public
26  *                License for more details.
27  *
28  *                The GNU General Public License should be included with
29  *                this file.  If not, you can view it at
30  *                http://www.gnu.org/copyleft/gpl.html
31  *                or write to the Free Software Foundation, Inc., 59
32  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
33  *
34  *********************************************************************/
35
36
37 #include "config.h"
38
39 #include <stdio.h>
40 #include <sys/types.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <signal.h>
44 #include <fcntl.h>
45 #include <errno.h>
46 #include <assert.h>
47
48 #ifdef _WIN32
49 # ifndef FEATURE_PTHREAD
50 #  ifndef STRICT
51 #   define STRICT
52 #  endif
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 # if !defined (__OS2__)
66 # include <unistd.h>
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
72
73 #ifdef sun
74 #include <sys/termios.h>
75 #endif /* sun */
76
77 #ifdef unix
78 #include <pwd.h>
79 #include <grp.h>
80 #endif
81
82 # include <signal.h>
83
84 # ifdef __BEOS__
85 #  include <socket.h>  /* BeOS has select() for sockets only. */
86 #  include <OS.h>      /* declarations for threads and stuff. */
87 # endif
88
89 # if defined(__EMX__) || defined(__OS2__)
90 #  include <sys/select.h>  /* OS/2/EMX needs a little help with select */
91 # endif
92 # ifdef __OS2__
93 #define INCL_DOS
94 # include <os2.h>
95 #define bzero(B,N) memset(B,0x00,n)
96 # endif
97
98 # ifndef FD_ZERO
99 #  include <select.h>
100 # endif
101
102 #endif
103
104 #include "project.h"
105 #include "list.h"
106 #include "jcc.h"
107 #include "filters.h"
108 #include "loaders.h"
109 #include "parsers.h"
110 #include "miscutil.h"
111 #include "errlog.h"
112 #include "jbsockets.h"
113 #include "gateway.h"
114 #include "actions.h"
115 #include "cgi.h"
116 #include "loadcfg.h"
117 #include "urlmatch.h"
118
119 const char jcc_h_rcs[] = JCC_H_VERSION;
120 const char project_h_rcs[] = PROJECT_H_VERSION;
121
122 int daemon_mode = 1;
123 struct client_states clients[1];
124 struct file_list     files[1];
125
126 #ifdef FEATURE_STATISTICS
127 int urls_read     = 0;     /* total nr of urls read inc rejected */
128 int urls_rejected = 0;     /* total nr of urls rejected */
129 #endif /* def FEATURE_STATISTICS */
130
131 #ifdef FEATURE_GRACEFUL_TERMINATION
132 int g_terminate = 0;
133 #endif
134
135 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
136 static void sig_handler(int the_signal);
137 #endif
138 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
139 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
140 static jb_err get_server_headers(struct client_state *csp);
141 static const char *crunch_reason(const struct http_response *rsp);
142 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
143 static char *get_request_line(struct client_state *csp);
144 static jb_err receive_client_request(struct client_state *csp);
145 static jb_err parse_client_request(struct client_state *csp);
146 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
147 static jb_err change_request_destination(struct client_state *csp);
148 static void chat(struct client_state *csp);
149 static void serve(struct client_state *csp);
150 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
151 static void usage(const char *myname);
152 #endif
153 static void initialize_mutexes(void);
154 static jb_socket bind_port_helper(const char *haddr, int hport);
155 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
156 static void close_ports_helper(jb_socket sockets[]);
157 static void listen_loop(void);
158
159 #ifdef AMIGA
160 void serve(struct client_state *csp);
161 #else /* ifndef AMIGA */
162 static void serve(struct client_state *csp);
163 #endif /* def AMIGA */
164
165 #ifdef __BEOS__
166 static int32 server_thread(void *data);
167 #endif /* def __BEOS__ */
168
169 #ifdef _WIN32
170 #define sleep(N)  Sleep(((N) * 1000))
171 #endif
172
173 #ifdef __OS2__
174 #define sleep(N)  DosSleep(((N) * 100))
175 #endif
176
177 #ifdef MUTEX_LOCKS_AVAILABLE
178 /*
179  * XXX: Does the locking stuff really belong in this file?
180  */
181 privoxy_mutex_t log_mutex;
182 privoxy_mutex_t log_init_mutex;
183 privoxy_mutex_t connection_reuse_mutex;
184
185 #ifdef FEATURE_EXTERNAL_FILTERS
186 privoxy_mutex_t external_filter_mutex;
187 #endif
188
189 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
190 privoxy_mutex_t resolver_mutex;
191 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
192
193 #ifndef HAVE_GMTIME_R
194 privoxy_mutex_t gmtime_mutex;
195 #endif /* ndef HAVE_GMTIME_R */
196
197 #ifndef HAVE_LOCALTIME_R
198 privoxy_mutex_t localtime_mutex;
199 #endif /* ndef HAVE_GMTIME_R */
200
201 #ifndef HAVE_RANDOM
202 privoxy_mutex_t rand_mutex;
203 #endif /* ndef HAVE_RANDOM */
204
205 #endif /* def MUTEX_LOCKS_AVAILABLE */
206
207 #if defined(unix)
208 const char *basedir = NULL;
209 const char *pidfile = NULL;
210 static int received_hup_signal = 0;
211 #endif /* defined unix */
212
213 /* HTTP snipplets. */
214 static const char CSUCCEED[] =
215    "HTTP/1.1 200 Connection established\r\n\r\n";
216
217 static const char CHEADER[] =
218    "HTTP/1.1 400 Invalid header received from client\r\n"
219    "Content-Type: text/plain\r\n"
220    "Connection: close\r\n\r\n"
221    "Invalid header received from client.\r\n";
222
223 static const char FTP_RESPONSE[] =
224    "HTTP/1.1 400 Invalid request received from client\r\n"
225    "Content-Type: text/plain\r\n"
226    "Connection: close\r\n\r\n"
227    "Invalid request. Privoxy doesn't support FTP.\r\n";
228
229 static const char GOPHER_RESPONSE[] =
230    "HTTP/1.1 400 Invalid request received from client\r\n"
231    "Content-Type: text/plain\r\n"
232    "Connection: close\r\n\r\n"
233    "Invalid request. Privoxy doesn't support gopher.\r\n";
234
235 /* XXX: should be a template */
236 static const char MISSING_DESTINATION_RESPONSE[] =
237    "HTTP/1.1 400 Bad request received from client\r\n"
238    "Content-Type: text/plain\r\n"
239    "Connection: close\r\n\r\n"
240    "Bad request. Privoxy was unable to extract the destination.\r\n";
241
242 /* XXX: should be a template */
243 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
244    "HTTP/1.1 502 Server or forwarder response invalid\r\n"
245    "Content-Type: text/plain\r\n"
246    "Connection: close\r\n\r\n"
247    "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
248
249 /* XXX: should be a template */
250 static const char MESSED_UP_REQUEST_RESPONSE[] =
251    "HTTP/1.1 400 Malformed request after rewriting\r\n"
252    "Content-Type: text/plain\r\n"
253    "Connection: close\r\n\r\n"
254    "Bad request. Messed up with header filters.\r\n";
255
256 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
257    "HTTP/1.1 503 Too many open connections\r\n"
258    "Content-Type: text/plain\r\n"
259    "Connection: close\r\n\r\n"
260    "Maximum number of open connections reached.\r\n";
261
262 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
263    "HTTP/1.1 504 Connection timeout\r\n"
264    "Content-Type: text/plain\r\n"
265    "Connection: close\r\n\r\n"
266    "The connection timed out because the client request didn't arrive in time.\r\n";
267
268 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
269    "HTTP/1.1 400 Failed reading client body\r\n"
270    "Content-Type: text/plain\r\n"
271    "Connection: close\r\n\r\n"
272    "Failed parsing or buffering the chunk-encoded client body.\r\n";
273
274 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
275    "HTTP/1.1 417 Expecting too much\r\n"
276    "Content-Type: text/plain\r\n"
277    "Connection: close\r\n\r\n"
278    "Privoxy detected an unsupported Expect header value.\r\n";
279
280 /* A function to crunch a response */
281 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
282
283 /* Crunch function flags */
284 #define CF_NO_FLAGS        0
285 /* Cruncher applies to forced requests as well */
286 #define CF_IGNORE_FORCE    1
287 /* Crunched requests are counted for the block statistics */
288 #define CF_COUNT_AS_REJECT 2
289
290 /* A crunch function and its flags */
291 struct cruncher
292 {
293    const crunch_func_ptr cruncher;
294    const int flags;
295 };
296
297 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
298
299 /* Complete list of cruncher functions */
300 static const struct cruncher crunchers_all[] = {
301    { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
302    { block_url,       CF_COUNT_AS_REJECT },
303 #ifdef FEATURE_TRUST
304    { trust_url,       CF_COUNT_AS_REJECT },
305 #endif /* def FEATURE_TRUST */
306    { redirect_url,    CF_NO_FLAGS  },
307    { dispatch_cgi,    CF_IGNORE_FORCE},
308    { NULL,            0 }
309 };
310
311 /* Light version, used after tags are applied */
312 static const struct cruncher crunchers_light[] = {
313    { block_url,       CF_COUNT_AS_REJECT },
314    { redirect_url,    CF_NO_FLAGS },
315    { NULL,            0 }
316 };
317
318
319 /*
320  * XXX: Don't we really mean
321  *
322  * #if defined(unix)
323  *
324  * here?
325  */
326 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
327 /*********************************************************************
328  *
329  * Function    :  sig_handler
330  *
331  * Description :  Signal handler for different signals.
332  *                Exit gracefully on TERM and INT
333  *                or set a flag that will cause the errlog
334  *                to be reopened by the main thread on HUP.
335  *
336  * Parameters  :
337  *          1  :  the_signal = the signal cause this function to call
338  *
339  * Returns     :  -
340  *
341  *********************************************************************/
342 static void sig_handler(int the_signal)
343 {
344    switch(the_signal)
345    {
346       case SIGTERM:
347       case SIGINT:
348          log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
349 #if defined(unix)
350          if (pidfile)
351          {
352             unlink(pidfile);
353          }
354 #endif /* unix */
355          exit(the_signal);
356          break;
357
358       case SIGHUP:
359 #if defined(unix)
360          received_hup_signal = 1;
361 #endif
362          break;
363
364       default:
365          /*
366           * We shouldn't be here, unless we catch signals
367           * in main() that we can't handle here!
368           */
369          log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
370    }
371    return;
372
373 }
374 #endif
375
376
377 /*********************************************************************
378  *
379  * Function    :  client_protocol_is_unsupported
380  *
381  * Description :  Checks if the client used a known unsupported
382  *                protocol and deals with it by sending an error
383  *                response.
384  *
385  * Parameters  :
386  *          1  :  csp = Current client state (buffers, headers, etc...)
387  *          2  :  req = the first request line send by the client
388  *
389  * Returns     :  TRUE if an error response has been generated, or
390  *                FALSE if the request doesn't look invalid.
391  *
392  *********************************************************************/
393 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
394 {
395    /*
396     * If it's a FTP or gopher request, we don't support it.
397     *
398     * These checks are better than nothing, but they might
399     * not work in all configurations and some clients might
400     * have problems digesting the answer.
401     *
402     * They should, however, never cause more problems than
403     * Privoxy's old behaviour (returning the misleading HTML
404     * error message:
405     *
406     * "Could not resolve http://(ftp|gopher)://example.org").
407     */
408    if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
409    {
410       const char *response = NULL;
411       const char *protocol = NULL;
412
413       if (!strncmpic(req, "GET ftp://", 10))
414       {
415          response = FTP_RESPONSE;
416          protocol = "FTP";
417       }
418       else
419       {
420          response = GOPHER_RESPONSE;
421          protocol = "GOPHER";
422       }
423       log_error(LOG_LEVEL_ERROR,
424          "%s tried to use Privoxy as %s proxy: %s",
425          csp->ip_addr_str, protocol, req);
426       log_error(LOG_LEVEL_CLF,
427          "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
428       freez(req);
429       write_socket(csp->cfd, response, strlen(response));
430
431       return TRUE;
432    }
433
434    return FALSE;
435 }
436
437
438 /*********************************************************************
439  *
440  * Function    :  client_has_unsupported_expectations
441  *
442  * Description :  Checks if the client used an unsupported expectation
443  *                in which case an error message is delivered.
444  *
445  * Parameters  :
446  *          1  :  csp = Current client state (buffers, headers, etc...)
447  *
448  * Returns     :  TRUE if an error response has been generated, or
449  *                FALSE if the request doesn't look invalid.
450  *
451  *********************************************************************/
452 static int client_has_unsupported_expectations(const struct client_state *csp)
453 {
454    if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
455    {
456       log_error(LOG_LEVEL_ERROR,
457          "Rejecting request from client %s with unsupported Expect header value",
458          csp->ip_addr_str);
459       log_error(LOG_LEVEL_CLF,
460          "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
461       write_socket(csp->cfd, UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
462          strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE));
463
464       return TRUE;
465    }
466
467    return FALSE;
468
469 }
470
471
472 /*********************************************************************
473  *
474  * Function    :  get_request_destination_elsewhere
475  *
476  * Description :  If the client's request was redirected into
477  *                Privoxy without the client's knowledge,
478  *                the request line lacks the destination host.
479  *
480  *                This function tries to get it elsewhere,
481  *                provided accept-intercepted-requests is enabled.
482  *
483  *                "Elsewhere" currently only means "Host: header",
484  *                but in the future we may ask the redirecting
485  *                packet filter to look the destination up.
486  *
487  *                If the destination stays unknown, an error
488  *                response is send to the client and headers
489  *                are freed so that chat() can return directly.
490  *
491  * Parameters  :
492  *          1  :  csp = Current client state (buffers, headers, etc...)
493  *          2  :  headers = a header list
494  *
495  * Returns     :  JB_ERR_OK if the destination is now known, or
496  *                JB_ERR_PARSE if it isn't.
497  *
498  *********************************************************************/
499 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
500 {
501    char *req;
502
503    if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
504    {
505       log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
506          " Privoxy isn't configured to accept intercepted requests.",
507          csp->ip_addr_str, csp->http->cmd);
508       /* XXX: Use correct size */
509       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
510          csp->ip_addr_str, csp->http->cmd);
511
512       write_socket(csp->cfd, CHEADER, strlen(CHEADER));
513       destroy_list(headers);
514
515       return JB_ERR_PARSE;
516    }
517    else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
518    {
519 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
520       /* Split the domain we just got for pattern matching */
521       init_domain_components(csp->http);
522 #endif
523
524       return JB_ERR_OK;
525    }
526    else
527    {
528       /* We can't work without destination. Go spread the news.*/
529
530       req = list_to_text(headers);
531       chomp(req);
532       /* XXX: Use correct size */
533       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
534          csp->ip_addr_str, csp->http->cmd);
535       log_error(LOG_LEVEL_ERROR,
536          "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
537          csp->ip_addr_str, csp->http->cmd, req);
538       freez(req);
539
540       write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
541       destroy_list(headers);
542
543       return JB_ERR_PARSE;
544    }
545    /*
546     * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
547     * to get the destination IP address, use it as host directly
548     * or do a reverse DNS lookup first.
549     */
550 }
551
552
553 /*********************************************************************
554  *
555  * Function    :  get_server_headers
556  *
557  * Description :  Parses server headers in iob and fills them
558  *                into csp->headers so that they can later be
559  *                handled by sed().
560  *
561  * Parameters  :
562  *          1  :  csp = Current client state (buffers, headers, etc...)
563  *
564  * Returns     :  JB_ERR_OK if everything went fine, or
565  *                JB_ERR_PARSE if the headers were incomplete.
566  *
567  *********************************************************************/
568 static jb_err get_server_headers(struct client_state *csp)
569 {
570    int continue_hack_in_da_house = 0;
571    char * header;
572
573    while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
574    {
575       if (header == NULL)
576       {
577          /*
578           * continue hack in da house. Ignore the ending of
579           * this head and continue enlisting header lines.
580           * The reason is described below.
581           */
582          enlist(csp->headers, "");
583          continue_hack_in_da_house = 0;
584          continue;
585       }
586       else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
587       {
588          /*
589           * It's a bodyless continue response, don't
590           * stop header parsing after reaching its end.
591           *
592           * As a result Privoxy will concatenate the
593           * next response's head and parse and deliver
594           * the headers as if they belonged to one request.
595           *
596           * The client will separate them because of the
597           * empty line between them.
598           *
599           * XXX: What we're doing here is clearly against
600           * the intended purpose of the continue header,
601           * and under some conditions (HTTP/1.0 client request)
602           * it's a standard violation.
603           *
604           * Anyway, "sort of against the spec" is preferable
605           * to "always getting confused by Continue responses"
606           * (Privoxy's behaviour before this hack was added)
607           */
608          log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
609          continue_hack_in_da_house = 1;
610       }
611       else if (*header == '\0')
612       {
613          /*
614           * If the header is empty, but the Continue hack
615           * isn't active, we can assume that we reached the
616           * end of the buffer before we hit the end of the
617           * head.
618           *
619           * Inform the caller an let it decide how to handle it.
620           */
621          return JB_ERR_PARSE;
622       }
623
624       if (JB_ERR_MEMORY == enlist(csp->headers, header))
625       {
626          /*
627           * XXX: Should we quit the request and return a
628           * out of memory error page instead?
629           */
630          log_error(LOG_LEVEL_ERROR,
631             "Out of memory while enlisting server headers. %s lost.",
632             header);
633       }
634       freez(header);
635    }
636
637    return JB_ERR_OK;
638 }
639
640
641 /*********************************************************************
642  *
643  * Function    :  crunch_reason
644  *
645  * Description :  Translates the crunch reason code into a string.
646  *
647  * Parameters  :
648  *          1  :  rsp = a http_response
649  *
650  * Returns     :  A string with the crunch reason or an error description.
651  *
652  *********************************************************************/
653 static const char *crunch_reason(const struct http_response *rsp)
654 {
655    char * reason = NULL;
656
657    assert(rsp != NULL);
658    if (rsp == NULL)
659    {
660       return "Internal error while searching for crunch reason";
661    }
662
663    switch (rsp->crunch_reason)
664    {
665       case UNSUPPORTED:
666          reason = "Unsupported HTTP feature";
667          break;
668       case BLOCKED:
669          reason = "Blocked";
670          break;
671       case UNTRUSTED:
672          reason = "Untrusted";
673          break;
674       case REDIRECTED:
675          reason = "Redirected";
676          break;
677       case CGI_CALL:
678          reason = "CGI Call";
679          break;
680       case NO_SUCH_DOMAIN:
681          reason = "DNS failure";
682          break;
683       case FORWARDING_FAILED:
684          reason = "Forwarding failed";
685          break;
686       case CONNECT_FAILED:
687          reason = "Connection failure";
688          break;
689       case OUT_OF_MEMORY:
690          reason = "Out of memory (may mask other reasons)";
691          break;
692       case CONNECTION_TIMEOUT:
693          reason = "Connection timeout";
694          break;
695       case NO_SERVER_DATA:
696          reason = "No server data received";
697          break;
698       default:
699          reason = "No reason recorded";
700          break;
701    }
702
703    return reason;
704 }
705
706
707 /*********************************************************************
708  *
709  * Function    :  log_applied_actions
710  *
711  * Description :  Logs the applied actions if LOG_LEVEL_ACTIONS is
712  *                enabled.
713  *
714  * Parameters  :
715  *          1  :  actions = Current action spec to log
716  *
717  * Returns     :  Nothing.
718  *
719  *********************************************************************/
720 static void log_applied_actions(const struct current_action_spec *actions)
721 {
722    /*
723     * The conversion to text requires lots of memory allocations so
724     * we only do the conversion if the user is actually interested.
725     */
726    if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
727    {
728       char *actions_as_text = actions_to_line_of_text(actions);
729       log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
730       freez(actions_as_text);
731    }
732 }
733
734
735 /*********************************************************************
736  *
737  * Function    :  send_crunch_response
738  *
739  * Description :  Delivers already prepared response for
740  *                intercepted requests, logs the interception
741  *                and frees the response.
742  *
743  * Parameters  :
744  *          1  :  csp = Current client state (buffers, headers, etc...)
745  *          1  :  rsp = Fully prepared response. Will be freed on exit.
746  *
747  * Returns     :  Nothing.
748  *
749  *********************************************************************/
750 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
751 {
752       const struct http_request *http = csp->http;
753       char status_code[4];
754
755       assert(rsp != NULL);
756       assert(rsp->head != NULL);
757
758       if (rsp == NULL)
759       {
760          log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
761       }
762
763       /*
764        * Extract the status code from the actual head
765        * that will be send to the client. It is the only
766        * way to get it right for all requests, including
767        * the fixed ones for out-of-memory problems.
768        *
769        * A head starts like this: 'HTTP/1.1 200...'
770        *                           0123456789|11
771        *                                     10
772        */
773       status_code[0] = rsp->head[9];
774       status_code[1] = rsp->head[10];
775       status_code[2] = rsp->head[11];
776       status_code[3] = '\0';
777
778       /* Log that the request was crunched and why. */
779       log_applied_actions(csp->action);
780       log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
781       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
782          csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
783
784       /* Write the answer to the client */
785       if (write_socket(csp->cfd, rsp->head, rsp->head_length)
786        || write_socket(csp->cfd, rsp->body, rsp->content_length))
787       {
788          /* There is nothing we can do about it. */
789          log_error(LOG_LEVEL_ERROR,
790             "Couldn't deliver the error message through client socket %d: %E",
791             csp->cfd);
792       }
793
794       /* Clean up and return */
795       if (cgi_error_memory() != rsp)
796       {
797          free_http_response(rsp);
798       }
799       return;
800 }
801
802
803 /*********************************************************************
804  *
805  * Function    :  crunch_response_triggered
806  *
807  * Description :  Checks if the request has to be crunched,
808  *                and delivers the crunch response if necessary.
809  *
810  * Parameters  :
811  *          1  :  csp = Current client state (buffers, headers, etc...)
812  *          2  :  crunchers = list of cruncher functions to run
813  *
814  * Returns     :  TRUE if the request was answered with a crunch response
815  *                FALSE otherwise.
816  *
817  *********************************************************************/
818 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
819 {
820    struct http_response *rsp = NULL;
821    const struct cruncher *c;
822
823    /*
824     * If CGI request crunching is disabled,
825     * check the CGI dispatcher out of order to
826     * prevent unintentional blocks or redirects.
827     */
828    if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
829        && (NULL != (rsp = dispatch_cgi(csp))))
830    {
831       /* Deliver, log and free the interception response. */
832       send_crunch_response(csp, rsp);
833       csp->flags |= CSP_FLAG_CRUNCHED;
834       return TRUE;
835    }
836
837    for (c = crunchers; c->cruncher != NULL; c++)
838    {
839       /*
840        * Check the cruncher if either Privoxy is toggled
841        * on and the request isn't forced, or if the cruncher
842        * applies to forced requests as well.
843        */
844       if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
845           !(csp->flags & CSP_FLAG_FORCED)) ||
846           (c->flags & CF_IGNORE_FORCE))
847       {
848          rsp = c->cruncher(csp);
849          if (NULL != rsp)
850          {
851             /* Deliver, log and free the interception response. */
852             send_crunch_response(csp, rsp);
853             csp->flags |= CSP_FLAG_CRUNCHED;
854 #ifdef FEATURE_STATISTICS
855             if (c->flags & CF_COUNT_AS_REJECT)
856             {
857                csp->flags |= CSP_FLAG_REJECTED;
858             }
859 #endif /* def FEATURE_STATISTICS */
860
861             return TRUE;
862          }
863       }
864    }
865
866    return FALSE;
867 }
868
869
870 /*********************************************************************
871  *
872  * Function    :  build_request_line
873  *
874  * Description :  Builds the HTTP request line.
875  *
876  *                If a HTTP forwarder is used it expects the whole URL,
877  *                web servers only get the path.
878  *
879  * Parameters  :
880  *          1  :  csp = Current client state (buffers, headers, etc...)
881  *          2  :  fwd = The forwarding spec used for the request
882  *                XXX: Should use http->fwd instead.
883  *          3  :  request_line = The old request line which will be replaced.
884  *
885  * Returns     :  Nothing. Terminates in case of memory problems.
886  *
887  *********************************************************************/
888 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
889 {
890    struct http_request *http = csp->http;
891
892    assert(http->ssl == 0);
893
894    /*
895     * Downgrade http version from 1.1 to 1.0
896     * if +downgrade action applies.
897     */
898    if ((csp->action->flags & ACTION_DOWNGRADE)
899      && (!strcmpic(http->ver, "HTTP/1.1")))
900    {
901       freez(http->ver);
902       http->ver = strdup_or_die("HTTP/1.0");
903    }
904
905    /*
906     * Rebuild the request line.
907     */
908    freez(*request_line);
909    *request_line = strdup(http->gpc);
910    string_append(request_line, " ");
911
912    if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
913    {
914       string_append(request_line, http->url);
915    }
916    else
917    {
918       string_append(request_line, http->path);
919    }
920    string_append(request_line, " ");
921    string_append(request_line, http->ver);
922
923    if (*request_line == NULL)
924    {
925       log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
926    }
927    log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
928 }
929
930
931 /*********************************************************************
932  *
933  * Function    :  change_request_destination
934  *
935  * Description :  Parse a (rewritten) request line and regenerate
936  *                the http request data.
937  *
938  * Parameters  :
939  *          1  :  csp = Current client state (buffers, headers, etc...)
940  *
941  * Returns     :  Forwards the parse_http_request() return code.
942  *                Terminates in case of memory problems.
943  *
944  *********************************************************************/
945 static jb_err change_request_destination(struct client_state *csp)
946 {
947    struct http_request *http = csp->http;
948    jb_err err;
949
950    log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
951       csp->headers->first->str);
952    free_http_request(http);
953    err = parse_http_request(csp->headers->first->str, http);
954    if (JB_ERR_OK != err)
955    {
956       log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
957          jb_err_to_string(err));
958    }
959
960    return err;
961 }
962
963
964 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
965 /*********************************************************************
966  *
967  * Function    :  server_response_is_complete
968  *
969  * Description :  Determines whether we should stop reading
970  *                from the server socket.
971  *
972  * Parameters  :
973  *          1  :  csp = Current client state (buffers, headers, etc...)
974  *          2  :  content_length = Length of content received so far.
975  *
976  * Returns     :  TRUE if the response is complete,
977  *                FALSE otherwise.
978  *
979  *********************************************************************/
980 static int server_response_is_complete(struct client_state *csp,
981    unsigned long long content_length)
982 {
983    int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
984
985    if (!strcmpic(csp->http->gpc, "HEAD"))
986    {
987       /*
988        * "HEAD" implies no body, we are thus expecting
989        * no content. XXX: incomplete "list" of methods?
990        */
991       csp->expected_content_length = 0;
992       content_length_known = TRUE;
993       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
994    }
995
996    if (csp->http->status == 204 || csp->http->status == 304)
997    {
998       /*
999        * Expect no body. XXX: incomplete "list" of status codes?
1000        */
1001       csp->expected_content_length = 0;
1002       content_length_known = TRUE;
1003       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1004    }
1005
1006    return (content_length_known && ((0 == csp->expected_content_length)
1007             || (csp->expected_content_length <= content_length)));
1008 }
1009
1010
1011 #ifdef FEATURE_CONNECTION_SHARING
1012 /*********************************************************************
1013  *
1014  * Function    :  wait_for_alive_connections
1015  *
1016  * Description :  Waits for alive connections to timeout.
1017  *
1018  * Parameters  :  N/A
1019  *
1020  * Returns     :  N/A
1021  *
1022  *********************************************************************/
1023 static void wait_for_alive_connections(void)
1024 {
1025    int connections_alive = close_unusable_connections();
1026
1027    while (0 < connections_alive)
1028    {
1029       log_error(LOG_LEVEL_CONNECT,
1030          "Waiting for %d connections to timeout.",
1031          connections_alive);
1032       sleep(60);
1033       connections_alive = close_unusable_connections();
1034    }
1035
1036    log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1037
1038 }
1039 #endif /* def FEATURE_CONNECTION_SHARING */
1040
1041
1042 /*********************************************************************
1043  *
1044  * Function    :  save_connection_destination
1045  *
1046  * Description :  Remembers a connection for reuse later on.
1047  *
1048  * Parameters  :
1049  *          1  :  sfd  = Open socket to remember.
1050  *          2  :  http = The destination for the connection.
1051  *          3  :  fwd  = The forwarder settings used.
1052  *          3  :  server_connection  = storage.
1053  *
1054  * Returns     : void
1055  *
1056  *********************************************************************/
1057 void save_connection_destination(jb_socket sfd,
1058                                  const struct http_request *http,
1059                                  const struct forward_spec *fwd,
1060                                  struct reusable_connection *server_connection)
1061 {
1062    assert(sfd != JB_INVALID_SOCKET);
1063    assert(NULL != http->host);
1064
1065    server_connection->sfd = sfd;
1066    server_connection->host = strdup_or_die(http->host);
1067    server_connection->port = http->port;
1068
1069    assert(NULL != fwd);
1070    assert(server_connection->gateway_host == NULL);
1071    assert(server_connection->gateway_port == 0);
1072    assert(server_connection->forwarder_type == 0);
1073    assert(server_connection->forward_host == NULL);
1074    assert(server_connection->forward_port == 0);
1075
1076    server_connection->forwarder_type = fwd->type;
1077    if (NULL != fwd->gateway_host)
1078    {
1079       server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1080    }
1081    else
1082    {
1083       server_connection->gateway_host = NULL;
1084    }
1085    server_connection->gateway_port = fwd->gateway_port;
1086
1087    if (NULL != fwd->forward_host)
1088    {
1089       server_connection->forward_host = strdup_or_die(fwd->forward_host);
1090    }
1091    else
1092    {
1093       server_connection->forward_host = NULL;
1094    }
1095    server_connection->forward_port = fwd->forward_port;
1096 }
1097
1098
1099 /*********************************************************************
1100  *
1101  * Function    : verify_request_length
1102  *
1103  * Description : Checks if we already got the whole client requests
1104  *               and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1105  *               we do.
1106  *
1107  *               Data that doesn't belong to the current request is
1108  *               either thrown away to let the client retry on a clean
1109  *               socket, or stashed to be dealt with after the current
1110  *               request is served.
1111  *
1112  * Parameters  :
1113  *          1  :  csp = Current client state (buffers, headers, etc...)
1114  *
1115  * Returns     :  void
1116  *
1117  *********************************************************************/
1118 static void verify_request_length(struct client_state *csp)
1119 {
1120    unsigned long long buffered_request_bytes =
1121       (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1122
1123    if ((csp->expected_client_content_length != 0)
1124       && (buffered_request_bytes != 0))
1125    {
1126       if (csp->expected_client_content_length >= buffered_request_bytes)
1127       {
1128          csp->expected_client_content_length -= buffered_request_bytes;
1129          log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1130             "to account for the %llu ones we already got.",
1131             csp->expected_client_content_length, buffered_request_bytes);
1132       }
1133       else
1134       {
1135          assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1136          csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1137          log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1138             "Marking the server socket tainted after throwing %llu bytes away.",
1139             buffered_request_bytes - csp->expected_client_content_length);
1140          csp->expected_client_content_length = 0;
1141          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1142       }
1143
1144       if (csp->expected_client_content_length == 0)
1145       {
1146          csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1147       }
1148    }
1149
1150    if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1151       && ((csp->client_iob->cur < csp->client_iob->eod)
1152          || (csp->expected_client_content_length != 0)))
1153    {
1154       if (strcmpic(csp->http->gpc, "GET")
1155          && strcmpic(csp->http->gpc, "HEAD")
1156          && strcmpic(csp->http->gpc, "TRACE")
1157          && strcmpic(csp->http->gpc, "OPTIONS")
1158          && strcmpic(csp->http->gpc, "DELETE"))
1159       {
1160          /* XXX: this is an incomplete hack */
1161          csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1162          log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1163       }
1164       else
1165       {
1166          csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1167
1168          if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1169          {
1170             csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1171             log_error(LOG_LEVEL_CONNECT,
1172                "Possible pipeline attempt detected. The connection will not "
1173                "be kept alive and we will only serve the first request.");
1174             /* Nuke the pipelined requests from orbit, just to be sure. */
1175             clear_iob(csp->client_iob);
1176          }
1177          else
1178          {
1179             /*
1180              * Keep the pipelined data around for now, we'll deal with
1181              * it once we're done serving the current request.
1182              */
1183             csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1184             assert(csp->client_iob->eod >= csp->client_iob->cur);
1185             log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1186                "%d bytes of pipelined data received.",
1187                (int)(csp->client_iob->eod - csp->client_iob->cur));
1188          }
1189       }
1190    }
1191    else
1192    {
1193       csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1194       log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1195    }
1196 }
1197 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1198
1199
1200 /*********************************************************************
1201  *
1202  * Function    :  mark_server_socket_tainted
1203  *
1204  * Description :  Makes sure we don't reuse a server socket
1205  *                (if we didn't read everything the server sent
1206  *                us reusing the socket would lead to garbage).
1207  *
1208  * Parameters  :
1209  *          1  :  csp = Current client state (buffers, headers, etc...)
1210  *
1211  * Returns     :  void.
1212  *
1213  *********************************************************************/
1214 static void mark_server_socket_tainted(struct client_state *csp)
1215 {
1216    /*
1217     * For consistency we always mark the server socket
1218     * tainted, however, to reduce the log noise we only
1219     * emit a log message if the server socket could have
1220     * actually been reused.
1221     */
1222    if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1223       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1224    {
1225       log_error(LOG_LEVEL_CONNECT,
1226          "Marking the server socket %d tainted.",
1227          csp->server_connection.sfd);
1228    }
1229    csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1230 }
1231
1232 /*********************************************************************
1233  *
1234  * Function    :  get_request_line
1235  *
1236  * Description : Read the client request line.
1237  *
1238  * Parameters  :
1239  *          1  :  csp = Current client state (buffers, headers, etc...)
1240  *
1241  * Returns     :  Pointer to request line or NULL in case of errors.
1242  *
1243  *********************************************************************/
1244 static char *get_request_line(struct client_state *csp)
1245 {
1246    char buf[BUFFER_SIZE];
1247    char *request_line = NULL;
1248    int len;
1249
1250    memset(buf, 0, sizeof(buf));
1251
1252    if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1253    {
1254       /*
1255        * If there are multiple pipelined requests waiting,
1256        * the flag will be set again once the next request
1257        * has been parsed.
1258        */
1259       csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1260
1261       request_line = get_header(csp->client_iob);
1262       if ((NULL != request_line) && ('\0' != *request_line))
1263       {
1264          return request_line;
1265       }
1266       else
1267       {
1268          log_error(LOG_LEVEL_CONNECT, "No complete request line "
1269             "received yet. Continuing reading from %d.", csp->cfd);
1270       }
1271    }
1272
1273    do
1274    {
1275       if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1276       {
1277          if (socket_is_still_alive(csp->cfd))
1278          {
1279             log_error(LOG_LEVEL_CONNECT,
1280                "No request line on socket %d received in time. Timeout: %d.",
1281                csp->cfd, csp->config->socket_timeout);
1282             write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1283                strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1284          }
1285          else
1286          {
1287             log_error(LOG_LEVEL_CONNECT,
1288                "The client side of the connection on socket %d got "
1289                "closed without sending a complete request line.", csp->cfd);
1290          }
1291          return NULL;
1292       }
1293
1294       len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1295
1296       if (len <= 0) return NULL;
1297
1298       /*
1299        * If there is no memory left for buffering the
1300        * request, there is nothing we can do but hang up
1301        */
1302       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1303       {
1304          return NULL;
1305       }
1306
1307       request_line = get_header(csp->client_iob);
1308
1309    } while ((NULL != request_line) && ('\0' == *request_line));
1310
1311    return request_line;
1312
1313 }
1314
1315 enum chunk_status
1316 {
1317    CHUNK_STATUS_MISSING_DATA,
1318    CHUNK_STATUS_BODY_COMPLETE,
1319    CHUNK_STATUS_PARSE_ERROR
1320 };
1321
1322
1323 /*********************************************************************
1324  *
1325  * Function    :  chunked_body_is_complete
1326  *
1327  * Description :  Figures out whether or not a chunked body is complete.
1328  *
1329  *                Currently it always starts at the beginning of the
1330  *                buffer which is somewhat wasteful and prevents Privoxy
1331  *                from starting to forward the correctly parsed chunks
1332  *                as soon as theoretically possible.
1333  *
1334  *                Should be modified to work with a common buffer,
1335  *                and allow the caller to skip already parsed chunks.
1336  *
1337  *                This would allow the function to be used for unbuffered
1338  *                response bodies as well.
1339  *
1340  * Parameters  :
1341  *          1  :  iob = Buffer with the body to check.
1342  *          2  :  length = Length of complete body
1343  *
1344  * Returns     :  Enum with the result of the check.
1345  *
1346  *********************************************************************/
1347 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1348 {
1349    unsigned int chunksize;
1350    char *p = iob->cur;
1351
1352    do
1353    {
1354       /*
1355        * We need at least a single digit, followed by "\r\n",
1356        * followed by an unknown amount of data, followed by "\r\n".
1357        */
1358       if (p + 5 > iob->eod)
1359       {
1360          return CHUNK_STATUS_MISSING_DATA;
1361       }
1362       if (sscanf(p, "%x", &chunksize) != 1)
1363       {
1364          return CHUNK_STATUS_PARSE_ERROR;
1365       }
1366
1367       /*
1368        * We want at least a single digit, followed by "\r\n",
1369        * followed by the specified amount of data, followed by "\r\n".
1370        */
1371       if (p + chunksize + 5 > iob->eod)
1372       {
1373          return CHUNK_STATUS_MISSING_DATA;
1374       }
1375
1376       /* Skip chunk-size. */
1377       p = strstr(p, "\r\n");
1378       if (NULL == p)
1379       {
1380          return CHUNK_STATUS_PARSE_ERROR;
1381       }
1382       /* Move beyond the chunkdata. */
1383       p += 2 + chunksize;
1384
1385       /* There should be another "\r\n" to skip */
1386       if (memcmp(p, "\r\n", 2))
1387       {
1388          return CHUNK_STATUS_PARSE_ERROR;
1389       }
1390       p += 2;
1391    } while (chunksize > 0U);
1392
1393    *length = (size_t)(p - iob->cur);
1394    assert(*length <= (size_t)(iob->eod - iob->cur));
1395    assert(p <= iob->eod);
1396
1397    return CHUNK_STATUS_BODY_COMPLETE;
1398
1399 }
1400
1401
1402 /*********************************************************************
1403  *
1404  * Function    : receive_chunked_client_request_body
1405  *
1406  * Description : Read the chunk-encoded client request body.
1407  *               Failures are dealt with.
1408  *
1409  * Parameters  :
1410  *          1  :  csp = Current client state (buffers, headers, etc...)
1411  *
1412  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1413  *
1414  *********************************************************************/
1415 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1416 {
1417    size_t body_length;
1418    enum chunk_status status;
1419
1420    while (CHUNK_STATUS_MISSING_DATA ==
1421       (status = chunked_body_is_complete(csp->client_iob,&body_length)))
1422    {
1423       char buf[BUFFER_SIZE];
1424       int len;
1425
1426       if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1427       {
1428          log_error(LOG_LEVEL_ERROR,
1429             "Timeout while waiting for the client body.");
1430          break;
1431       }
1432       len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1433       if (len <= 0)
1434       {
1435          log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1436          break;
1437       }
1438       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1439       {
1440          break;
1441       }
1442    }
1443    if (status != CHUNK_STATUS_BODY_COMPLETE)
1444    {
1445       write_socket(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1446          strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE));
1447       log_error(LOG_LEVEL_CLF,
1448          "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1449       return JB_ERR_PARSE;
1450    }
1451    log_error(LOG_LEVEL_CONNECT,
1452       "Chunked client body completely read. Length: %d", body_length);
1453    csp->expected_client_content_length = body_length;
1454
1455    return JB_ERR_OK;
1456
1457 }
1458
1459
1460 #ifdef FEATURE_FORCE_LOAD
1461 /*********************************************************************
1462  *
1463  * Function    :  force_required
1464  *
1465  * Description : Checks a request line to see if it contains
1466  *               the FORCE_PREFIX. If it does, it is removed
1467  *               unless enforcing requests has beend disabled.
1468  *
1469  * Parameters  :
1470  *          1  :  request_line = HTTP request line
1471  *
1472  * Returns     :  TRUE if force is required, FALSE otherwise.
1473  *
1474  *********************************************************************/
1475 static int force_required(const struct client_state *csp, char *request_line)
1476 {
1477    char *p;
1478
1479    p = strstr(request_line, "http://");
1480    if (p != NULL)
1481    {
1482       /* Skip protocol */
1483       p += strlen("http://");
1484    }
1485    else
1486    {
1487       /* Intercepted request usually don't specify the protocol. */
1488       p = request_line;
1489    }
1490
1491    /* Go to the beginning of the path */
1492    p = strstr(p, "/");
1493    if (p == NULL)
1494    {
1495       /*
1496        * If the path is missing the request line is invalid and we
1497        * are done here. The client-visible rejection happens later on.
1498        */
1499       return 0;
1500    }
1501
1502    if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1503    {
1504       if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1505       {
1506          /* XXX: Should clean more carefully */
1507          strclean(request_line, FORCE_PREFIX);
1508          log_error(LOG_LEVEL_FORCE,
1509             "Enforcing request: \"%s\".", request_line);
1510
1511          return 1;
1512       }
1513       log_error(LOG_LEVEL_FORCE,
1514          "Ignored force prefix in request: \"%s\".", request_line);
1515    }
1516
1517    return 0;
1518
1519 }
1520 #endif /* def FEATURE_FORCE_LOAD */
1521
1522
1523 /*********************************************************************
1524  *
1525  * Function    :  receive_client_request
1526  *
1527  * Description : Read the client's request (more precisely the
1528  *               client headers) and answer it if necessary.
1529  *
1530  * Parameters  :
1531  *          1  :  csp = Current client state (buffers, headers, etc...)
1532  *
1533  * Returns     :  JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1534  *
1535  *********************************************************************/
1536 static jb_err receive_client_request(struct client_state *csp)
1537 {
1538    char buf[BUFFER_SIZE];
1539    char *p;
1540    char *req = NULL;
1541    struct http_request *http;
1542    int len;
1543    jb_err err;
1544
1545    /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1546    struct list header_list;
1547    struct list *headers = &header_list;
1548
1549    /* We don't care if the arriving data is a valid HTTP request or not. */
1550    csp->requests_received_total++;
1551
1552    http = csp->http;
1553
1554    memset(buf, 0, sizeof(buf));
1555
1556    req = get_request_line(csp);
1557    if (req == NULL)
1558    {
1559       mark_server_socket_tainted(csp);
1560       return JB_ERR_PARSE;
1561    }
1562    assert(*req != '\0');
1563
1564    if (client_protocol_is_unsupported(csp, req))
1565    {
1566       return JB_ERR_PARSE;
1567    }
1568
1569 #ifdef FEATURE_FORCE_LOAD
1570    if (force_required(csp, req))
1571    {
1572       csp->flags |= CSP_FLAG_FORCED;
1573    }
1574 #endif /* def FEATURE_FORCE_LOAD */
1575
1576    err = parse_http_request(req, http);
1577    freez(req);
1578    if (JB_ERR_OK != err)
1579    {
1580       write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1581       /* XXX: Use correct size */
1582       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1583       log_error(LOG_LEVEL_ERROR,
1584          "Couldn't parse request line received from %s: %s",
1585          csp->ip_addr_str, jb_err_to_string(err));
1586
1587       free_http_request(http);
1588       return JB_ERR_PARSE;
1589    }
1590
1591    /* grab the rest of the client's headers */
1592    init_list(headers);
1593    for (;;)
1594    {
1595       p = get_header(csp->client_iob);
1596
1597       if (p == NULL)
1598       {
1599          /* There are no additional headers to read. */
1600          break;
1601       }
1602
1603       if (*p == '\0')
1604       {
1605          /*
1606           * We didn't receive a complete header
1607           * line yet, get the rest of it.
1608           */
1609          if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1610          {
1611             log_error(LOG_LEVEL_ERROR,
1612                "Stopped grabbing the client headers.");
1613             destroy_list(headers);
1614             return JB_ERR_PARSE;
1615          }
1616
1617          len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1618          if (len <= 0)
1619          {
1620             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1621             destroy_list(headers);
1622             return JB_ERR_PARSE;
1623          }
1624
1625          if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1626          {
1627             /*
1628              * If there is no memory left for buffering the
1629              * request, there is nothing we can do but hang up
1630              */
1631             destroy_list(headers);
1632             return JB_ERR_MEMORY;
1633          }
1634       }
1635       else
1636       {
1637          if (!strncmpic(p, "Transfer-Encoding:", 18))
1638          {
1639             /*
1640              * XXX: should be called through sed()
1641              *      but currently can't.
1642              */
1643             client_transfer_encoding(csp, &p);
1644          }
1645          /*
1646           * We were able to read a complete
1647           * header and can finally enlist it.
1648           */
1649          enlist(headers, p);
1650          freez(p);
1651       }
1652    }
1653
1654    if (http->host == NULL)
1655    {
1656       /*
1657        * If we still don't know the request destination,
1658        * the request is invalid or the client uses
1659        * Privoxy without its knowledge.
1660        */
1661       if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1662       {
1663          /*
1664           * Our attempts to get the request destination
1665           * elsewhere failed or Privoxy is configured
1666           * to only accept proxy requests.
1667           *
1668           * An error response has already been send
1669           * and we're done here.
1670           */
1671          return JB_ERR_PARSE;
1672       }
1673    }
1674
1675    /*
1676     * Determine the actions for this URL
1677     */
1678 #ifdef FEATURE_TOGGLE
1679    if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1680    {
1681       /* Most compatible set of actions (i.e. none) */
1682       init_current_action(csp->action);
1683    }
1684    else
1685 #endif /* ndef FEATURE_TOGGLE */
1686    {
1687       get_url_actions(csp, http);
1688    }
1689
1690    enlist(csp->headers, http->cmd);
1691
1692    /* Append the previously read headers */
1693    err = list_append_list_unique(csp->headers, headers);
1694    destroy_list(headers);
1695
1696    return err;
1697
1698 }
1699
1700
1701 /*********************************************************************
1702  *
1703  * Function    : parse_client_request
1704  *
1705  * Description : Parses the client's request and decides what to do
1706  *               with it.
1707  *
1708  *               Note that since we're not using select() we could get
1709  *               blocked here if a client connected, then didn't say
1710  *               anything!
1711  *
1712  * Parameters  :
1713  *          1  :  csp = Current client state (buffers, headers, etc...)
1714  *
1715  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1716  *
1717  *********************************************************************/
1718 static jb_err parse_client_request(struct client_state *csp)
1719 {
1720    struct http_request *http = csp->http;
1721    jb_err err;
1722
1723 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1724    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1725     && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1726     && (csp->http->ssl == 0))
1727    {
1728       /* Assume persistence until further notice */
1729       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1730    }
1731
1732    if (csp->http->ssl == 0)
1733    {
1734       /*
1735        * This whole block belongs to chat() but currently
1736        * has to be executed before sed().
1737        */
1738       if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1739       {
1740          if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1741          {
1742             return JB_ERR_PARSE;
1743          }
1744       }
1745       else
1746       {
1747          csp->expected_client_content_length = get_expected_content_length(csp->headers);
1748       }
1749       verify_request_length(csp);
1750    }
1751 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1752
1753    err = sed(csp, FILTER_CLIENT_HEADERS);
1754    if (JB_ERR_OK != err)
1755    {
1756       log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1757          csp->ip_addr_str);
1758       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1759          csp->ip_addr_str, csp->http->cmd);
1760       write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1761       return JB_ERR_PARSE;
1762    }
1763    csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1764
1765    /* Check request line for rewrites. */
1766    if ((NULL == csp->headers->first->str)
1767       || (strcmp(http->cmd, csp->headers->first->str) &&
1768          (JB_ERR_OK != change_request_destination(csp))))
1769    {
1770       /*
1771        * A header filter broke the request line - bail out.
1772        */
1773       write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1774       /* XXX: Use correct size */
1775       log_error(LOG_LEVEL_CLF,
1776          "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1777       log_error(LOG_LEVEL_ERROR,
1778          "Invalid request line after applying header filters.");
1779       free_http_request(http);
1780
1781       return JB_ERR_PARSE;
1782    }
1783
1784    if (client_has_unsupported_expectations(csp))
1785    {
1786       return JB_ERR_PARSE;
1787    }
1788
1789    return JB_ERR_OK;
1790
1791 }
1792
1793
1794 /*********************************************************************
1795  *
1796  * Function    :  chat
1797  *
1798  * Description :  Once a connection from the client has been accepted,
1799  *                this function is called (via serve()) to handle the
1800  *                main business of the communication.  This function
1801  *                returns after dealing with a single request. It can
1802  *                be called multiple times with the same client socket
1803  *                if the client is keeping the connection alive.
1804  *
1805  *                The decision whether or not a client connection will
1806  *                be kept alive is up to the caller which also must
1807  *                close the client socket when done.
1808  *
1809  *                FIXME: chat is nearly thousand lines long.
1810  *                Ridiculous.
1811  *
1812  * Parameters  :
1813  *          1  :  csp = Current client state (buffers, headers, etc...)
1814  *
1815  * Returns     :  Nothing.
1816  *
1817  *********************************************************************/
1818 static void chat(struct client_state *csp)
1819 {
1820    char buf[BUFFER_SIZE];
1821    char *hdr;
1822    char *p;
1823    fd_set rfds;
1824    int n;
1825    jb_socket maxfd;
1826    int server_body;
1827    int ms_iis5_hack = 0;
1828    unsigned long long byte_count = 0;
1829    const struct forward_spec *fwd;
1830    struct http_request *http;
1831    long len = 0; /* for buffer sizes (and negative error codes) */
1832    int buffer_and_filter_content = 0;
1833
1834    /* Skeleton for HTTP response, if we should intercept the request */
1835    struct http_response *rsp;
1836    struct timeval timeout;
1837 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1838    int watch_client_socket;
1839 #endif
1840
1841    memset(buf, 0, sizeof(buf));
1842
1843    http = csp->http;
1844
1845    if (receive_client_request(csp) != JB_ERR_OK)
1846    {
1847       return;
1848    }
1849    if (parse_client_request(csp) != JB_ERR_OK)
1850    {
1851       return;
1852    }
1853
1854    /* decide how to route the HTTP request */
1855    fwd = forward_url(csp, http);
1856    if (NULL == fwd)
1857    {
1858       log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!?  This can't happen!");
1859       /* Never get here - LOG_LEVEL_FATAL causes program exit */
1860       return;
1861    }
1862
1863    /*
1864     * build the http request to send to the server
1865     * we have to do one of the following:
1866     *
1867     * create = use the original HTTP request to create a new
1868     *          HTTP request that has either the path component
1869     *          without the http://domainspec (w/path) or the
1870     *          full orininal URL (w/url)
1871     *          Note that the path and/or the HTTP version may
1872     *          have been altered by now.
1873     *
1874     * connect = Open a socket to the host:port of the server
1875     *           and short-circuit server and client socket.
1876     *
1877     * pass =  Pass the request unchanged if forwarding a CONNECT
1878     *         request to a parent proxy. Note that we'll be sending
1879     *         the CFAIL message ourselves if connecting to the parent
1880     *         fails, but we won't send a CSUCCEED message if it works,
1881     *         since that would result in a double message (ours and the
1882     *         parent's). After sending the request to the parent, we simply
1883     *         tunnel.
1884     *
1885     * here's the matrix:
1886     *                        SSL
1887     *                    0        1
1888     *                +--------+--------+
1889     *                |        |        |
1890     *             0  | create | connect|
1891     *                | w/path |        |
1892     *  Forwarding    +--------+--------+
1893     *                |        |        |
1894     *             1  | create | pass   |
1895     *                | w/url  |        |
1896     *                +--------+--------+
1897     *
1898     */
1899
1900    if (http->ssl && connect_port_is_forbidden(csp))
1901    {
1902       const char *acceptable_connect_ports =
1903          csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1904       assert(NULL != acceptable_connect_ports);
1905       log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1906          "limit-connect{%s} doesn't allow CONNECT requests to %s",
1907          csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
1908       csp->action->flags |= ACTION_BLOCK;
1909       http->ssl = 0;
1910    }
1911
1912    if (http->ssl == 0)
1913    {
1914       freez(csp->headers->first->str);
1915       build_request_line(csp, fwd, &csp->headers->first->str);
1916    }
1917
1918    /*
1919     * We have a request. Check if one of the crunchers wants it.
1920     */
1921    if (crunch_response_triggered(csp, crunchers_all))
1922    {
1923       /*
1924        * Yes. The client got the crunch response and we're done here.
1925        */
1926       return;
1927    }
1928
1929    log_applied_actions(csp->action);
1930    log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1931
1932    if (fwd->forward_host)
1933    {
1934       log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1935          fwd->forward_host, fwd->forward_port, http->hostport);
1936    }
1937    else
1938    {
1939       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1940    }
1941
1942    /* here we connect to the server, gateway, or the forwarder */
1943
1944 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1945    if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
1946       && socket_is_still_alive(csp->server_connection.sfd)
1947       && connection_destination_matches(&csp->server_connection, http, fwd))
1948    {
1949       log_error(LOG_LEVEL_CONNECT,
1950          "Reusing server socket %d connected to %s. Total requests: %u.",
1951          csp->server_connection.sfd, csp->server_connection.host,
1952          csp->server_connection.requests_sent_total);
1953    }
1954    else
1955    {
1956       if (csp->server_connection.sfd != JB_INVALID_SOCKET)
1957       {
1958 #ifdef FEATURE_CONNECTION_SHARING
1959          if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1960          {
1961             remember_connection(&csp->server_connection);
1962          }
1963          else
1964 #endif /* def FEATURE_CONNECTION_SHARING */
1965          {
1966             log_error(LOG_LEVEL_CONNECT,
1967                "Closing server socket %d connected to %s. Total requests: %u.",
1968                csp->server_connection.sfd, csp->server_connection.host,
1969                csp->server_connection.requests_sent_total);
1970             close_socket(csp->server_connection.sfd);
1971          }
1972          mark_connection_closed(&csp->server_connection);
1973       }
1974 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1975
1976       csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
1977
1978       if (csp->server_connection.sfd == JB_INVALID_SOCKET)
1979       {
1980          if ((fwd->type != SOCKS_NONE) && (fwd->type != FORWARD_WEBSERVER))
1981          {
1982             /* Socks error. */
1983             rsp = error_response(csp, "forwarding-failed");
1984          }
1985          else if (errno == EINVAL)
1986          {
1987             rsp = error_response(csp, "no-such-domain");
1988          }
1989          else
1990          {
1991             rsp = error_response(csp, "connect-failed");
1992          }
1993
1994          /* Write the answer to the client */
1995          if (rsp != NULL)
1996          {
1997             send_crunch_response(csp, rsp);
1998          }
1999
2000          /*
2001           * Temporary workaround to prevent already-read client
2002           * bodies from being parsed as new requests. For now we
2003           * err on the safe side and throw all the following
2004           * requests under the bus, even if no client body has been
2005           * buffered. A compliant client will repeat the dropped
2006           * requests on an untainted connection.
2007           *
2008           * The proper fix is to discard the no longer needed
2009           * client body in the buffer (if there is one) and to
2010           * continue parsing the bytes that follow.
2011           */
2012          drain_and_close_socket(csp->cfd);
2013          csp->cfd = JB_INVALID_SOCKET;
2014
2015          return;
2016       }
2017 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2018       save_connection_destination(csp->server_connection.sfd,
2019          http, fwd, &csp->server_connection);
2020       csp->server_connection.keep_alive_timeout =
2021          (unsigned)csp->config->keep_alive_timeout;
2022    }
2023 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2024
2025    csp->server_connection.requests_sent_total++;
2026
2027    if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
2028    {
2029       /* Client headers have been sent optimistically */
2030       assert(csp->headers->last == NULL);
2031    }
2032    else if (fwd->forward_host || (http->ssl == 0))
2033    {
2034       int write_failure;
2035       hdr = list_to_text(csp->headers);
2036       if (hdr == NULL)
2037       {
2038          /* FIXME Should handle error properly */
2039          log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2040       }
2041       list_remove_all(csp->headers);
2042
2043       /*
2044        * Write the client's (modified) header to the server
2045        * (along with anything else that may be in the buffer)
2046        */
2047       write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2048       freez(hdr);
2049
2050       if (write_failure)
2051       {
2052          log_error(LOG_LEVEL_CONNECT,
2053             "Failed sending request headers to: %s: %E", http->hostport);
2054       }
2055       else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2056          && (flush_socket(csp->server_connection.sfd, csp->client_iob) < 0))
2057       {
2058          write_failure = 1;
2059          log_error(LOG_LEVEL_CONNECT,
2060             "Failed sending request body to: %s: %E", http->hostport);
2061       }
2062
2063       if (write_failure)
2064       {
2065          rsp = error_response(csp, "connect-failed");
2066          if (rsp)
2067          {
2068             send_crunch_response(csp, rsp);
2069          }
2070          return;
2071       }
2072    }
2073    else
2074    {
2075       /*
2076        * We're running an SSL tunnel and we're not forwarding,
2077        * so just ditch the client headers, send the "connect succeeded"
2078        * message to the client, flush the rest, and get out of the way.
2079        */
2080       list_remove_all(csp->headers);
2081       if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
2082       {
2083          return;
2084       }
2085       clear_iob(csp->client_iob);
2086    }
2087
2088    log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
2089
2090    /* XXX: should the time start earlier for optimistically sent data? */
2091    csp->server_connection.request_sent = time(NULL);
2092
2093    maxfd = (csp->cfd > csp->server_connection.sfd) ?
2094       csp->cfd : csp->server_connection.sfd;
2095
2096    /* pass data between the client and server
2097     * until one or the other shuts down the connection.
2098     */
2099
2100    server_body = 0;
2101
2102 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2103    watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2104 #endif
2105
2106    for (;;)
2107    {
2108 #ifdef __OS2__
2109       /*
2110        * FD_ZERO here seems to point to an errant macro which crashes.
2111        * So do this by hand for now...
2112        */
2113       memset(&rfds,0x00,sizeof(fd_set));
2114 #else
2115       FD_ZERO(&rfds);
2116 #endif
2117 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2118       if (!watch_client_socket)
2119       {
2120          maxfd = csp->server_connection.sfd;
2121       }
2122       else
2123 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2124       {
2125          FD_SET(csp->cfd, &rfds);
2126       }
2127
2128       FD_SET(csp->server_connection.sfd, &rfds);
2129
2130 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2131       if ((csp->flags & CSP_FLAG_CHUNKED)
2132          && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2133          && ((csp->iob->eod - csp->iob->cur) >= 5)
2134          && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2135       {
2136          /*
2137           * XXX: This check should be obsolete now,
2138           *      but let's wait a while to be sure.
2139           */
2140          log_error(LOG_LEVEL_CONNECT,
2141             "Looks like we got the last chunk together with "
2142             "the server headers but didn't detect it earlier. "
2143             "We better stop reading.");
2144          byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2145          csp->expected_content_length = byte_count;
2146          csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2147       }
2148       if (server_body && server_response_is_complete(csp, byte_count))
2149       {
2150          if (csp->expected_content_length == byte_count)
2151          {
2152             log_error(LOG_LEVEL_CONNECT,
2153                "Done reading from server. Content length: %llu as expected. "
2154                "Bytes most recently read: %d.",
2155                byte_count, len);
2156          }
2157          else
2158          {
2159             log_error(LOG_LEVEL_CONNECT,
2160                "Done reading from server. Expected content length: %llu. "
2161                "Actual content length: %llu. Bytes most recently read: %d.",
2162                csp->expected_content_length, byte_count, len);
2163          }
2164          len = 0;
2165          /*
2166           * XXX: should not jump around,
2167           * chat() is complicated enough already.
2168           */
2169          goto reading_done;
2170       }
2171 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
2172
2173       timeout.tv_sec = csp->config->socket_timeout;
2174       timeout.tv_usec = 0;
2175       n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2176
2177       if (n == 0)
2178       {
2179          log_error(LOG_LEVEL_ERROR,
2180             "Didn't receive data in time: %s", http->url);
2181          if ((byte_count == 0) && (http->ssl == 0))
2182          {
2183             send_crunch_response(csp, error_response(csp, "connection-timeout"));
2184          }
2185          mark_server_socket_tainted(csp);
2186          return;
2187       }
2188       else if (n < 0)
2189       {
2190          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2191          mark_server_socket_tainted(csp);
2192          return;
2193       }
2194
2195       /*
2196        * This is the body of the browser's request,
2197        * just read and write it.
2198        *
2199        * XXX: Make sure the client doesn't use pipelining
2200        * behind Privoxy's back.
2201        */
2202       if (FD_ISSET(csp->cfd, &rfds))
2203       {
2204          int max_bytes_to_read = sizeof(buf) - 1;
2205
2206 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2207          if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2208          {
2209             if (data_is_available(csp->cfd, 0))
2210             {
2211                /*
2212                 * If the next request is already waiting, we have
2213                 * to stop select()ing the client socket. Otherwise
2214                 * we would always return right away and get nothing
2215                 * else done.
2216                 */
2217                watch_client_socket = 0;
2218                log_error(LOG_LEVEL_CONNECT,
2219                   "Stopping to watch the client socket %d. "
2220                   "There's already another request waiting.",
2221                   csp->cfd);
2222                continue;
2223             }
2224             /*
2225              * If the client socket is set, but there's no data
2226              * available on the socket, the client went fishing
2227              * and continuing talking to the server makes no sense.
2228              */
2229             log_error(LOG_LEVEL_CONNECT,
2230                "The client closed socket %d while "
2231                "the server socket %d is still open.",
2232                csp->cfd, csp->server_connection.sfd);
2233             mark_server_socket_tainted(csp);
2234             break;
2235          }
2236          if (csp->expected_client_content_length != 0)
2237          {
2238             if (csp->expected_client_content_length < (sizeof(buf) - 1))
2239             {
2240                max_bytes_to_read = (int)csp->expected_client_content_length;
2241             }
2242             log_error(LOG_LEVEL_CONNECT,
2243                "Waiting for up to %d bytes from the client.",
2244                max_bytes_to_read);
2245          }
2246          assert(max_bytes_to_read < sizeof(buf));
2247 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2248
2249          len = read_socket(csp->cfd, buf, max_bytes_to_read);
2250
2251          if (len <= 0)
2252          {
2253             /* XXX: not sure if this is necessary. */
2254             mark_server_socket_tainted(csp);
2255             break; /* "game over, man" */
2256          }
2257
2258 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2259          if (csp->expected_client_content_length != 0)
2260          {
2261             assert(len <= max_bytes_to_read);
2262             csp->expected_client_content_length -= (unsigned)len;
2263             log_error(LOG_LEVEL_CONNECT,
2264                "Expected client content length set to %llu "
2265                "after reading %d bytes.",
2266                csp->expected_client_content_length, len);
2267             if (csp->expected_client_content_length == 0)
2268             {
2269                log_error(LOG_LEVEL_CONNECT,
2270                   "Done reading from the client.");
2271                csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2272             }
2273          }
2274 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2275
2276          if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
2277          {
2278             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2279             mark_server_socket_tainted(csp);
2280             return;
2281          }
2282          continue;
2283       }
2284
2285       /*
2286        * The server wants to talk. It could be the header or the body.
2287        * If `hdr' is null, then it's the header otherwise it's the body.
2288        * FIXME: Does `hdr' really mean `host'? No.
2289        */
2290       if (FD_ISSET(csp->server_connection.sfd, &rfds))
2291       {
2292 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2293          /*
2294           * If we are buffering content, we don't want to eat up to
2295           * buffer-limit bytes if the client no longer cares about them.
2296           * If we aren't buffering, however, a dead client socket will be
2297           * noticed pretty much right away anyway, so we can reduce the
2298           * overhead by skipping the check.
2299           */
2300          if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2301          {
2302 #ifdef _WIN32
2303             log_error(LOG_LEVEL_CONNECT,
2304                "The server still wants to talk, but the client may already have hung up on us.");
2305 #else
2306             log_error(LOG_LEVEL_CONNECT,
2307                "The server still wants to talk, but the client hung up on us.");
2308             mark_server_socket_tainted(csp);
2309             return;
2310 #endif /* def _WIN32 */
2311          }
2312 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2313
2314          len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
2315
2316          if (len < 0)
2317          {
2318             log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2319
2320             if (http->ssl && (fwd->forward_host == NULL))
2321             {
2322                /*
2323                 * Just hang up. We already confirmed the client's CONNECT
2324                 * request with status code 200 and unencrypted content is
2325                 * no longer welcome.
2326                 */
2327                log_error(LOG_LEVEL_ERROR,
2328                   "CONNECT already confirmed. Unable to tell the client about the problem.");
2329                return;
2330             }
2331             else if (byte_count)
2332             {
2333                /*
2334                 * Just hang up. We already transmitted the original headers
2335                 * and parts of the original content and therefore missed the
2336                 * chance to send an error message (without risking data corruption).
2337                 *
2338                 * XXX: we could retry with a fancy range request here.
2339                 */
2340                log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2341                   "Unable to tell the client about the problem.");
2342                mark_server_socket_tainted(csp);
2343                return;
2344             }
2345             /*
2346              * XXX: Consider handling the cases above the same.
2347              */
2348             mark_server_socket_tainted(csp);
2349             len = 0;
2350          }
2351
2352 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2353          if (csp->flags & CSP_FLAG_CHUNKED)
2354          {
2355             if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2356             {
2357                /* XXX: this is a temporary hack */
2358                log_error(LOG_LEVEL_CONNECT,
2359                   "Looks like we reached the end of the last chunk. "
2360                   "We better stop reading.");
2361                csp->expected_content_length = byte_count + (unsigned long long)len;
2362                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2363             }
2364          }
2365          reading_done:
2366 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
2367
2368          /*
2369           * Add a trailing zero to let be able to use string operations.
2370           * XXX: do we still need this with filter_popups gone?
2371           */
2372          buf[len] = '\0';
2373
2374          /*
2375           * Normally, this would indicate that we've read
2376           * as much as the server has sent us and we can
2377           * close the client connection.  However, Microsoft
2378           * in its wisdom has released IIS/5 with a bug that
2379           * prevents it from sending the trailing \r\n in
2380           * a 302 redirect header (and possibly other headers).
2381           * To work around this if we've haven't parsed
2382           * a full header we'll append a trailing \r\n
2383           * and see if this now generates a valid one.
2384           *
2385           * This hack shouldn't have any impacts.  If we've
2386           * already transmitted the header or if this is a
2387           * SSL connection, then we won't bother with this
2388           * hack.  So we only work on partially received
2389           * headers.  If we append a \r\n and this still
2390           * doesn't generate a valid header, then we won't
2391           * transmit anything to the client.
2392           */
2393          if (len == 0)
2394          {
2395
2396             if (server_body || http->ssl)
2397             {
2398                /*
2399                 * If we have been buffering up the document,
2400                 * now is the time to apply content modification
2401                 * and send the result to the client.
2402                 */
2403                if (buffer_and_filter_content)
2404                {
2405                   p = execute_content_filters(csp);
2406                   /*
2407                    * If content filtering fails, use the original
2408                    * buffer and length.
2409                    * (see p != NULL ? p : csp->iob->cur below)
2410                    */
2411                   if (NULL == p)
2412                   {
2413                      csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2414                   }
2415 #ifdef FEATURE_COMPRESSION
2416                   else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2417                      && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2418                   {
2419                      char *compressed_content = compress_buffer(p,
2420                         (size_t *)&csp->content_length, csp->config->compression_level);
2421                      if (compressed_content != NULL)
2422                      {
2423                         freez(p);
2424                         p = compressed_content;
2425                         csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2426                      }
2427                   }
2428 #endif
2429
2430                   if (JB_ERR_OK != update_server_headers(csp))
2431                   {
2432                      log_error(LOG_LEVEL_FATAL,
2433                         "Failed to update server headers. after filtering.");
2434                   }
2435
2436                   hdr = list_to_text(csp->headers);
2437                   if (hdr == NULL)
2438                   {
2439                      /* FIXME Should handle error properly */
2440                      log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2441                   }
2442
2443                   if (write_socket(csp->cfd, hdr, strlen(hdr))
2444                    || write_socket(csp->cfd,
2445                          ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2446                   {
2447                      log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2448                      freez(hdr);
2449                      freez(p);
2450                      mark_server_socket_tainted(csp);
2451                      return;
2452                   }
2453
2454                   freez(hdr);
2455                   freez(p);
2456                }
2457
2458                break; /* "game over, man" */
2459             }
2460
2461             /*
2462              * This is NOT the body, so
2463              * Let's pretend the server just sent us a blank line.
2464              */
2465             snprintf(buf, sizeof(buf), "\r\n");
2466             len = (int)strlen(buf);
2467
2468             /*
2469              * Now, let the normal header parsing algorithm below do its
2470              * job.  If it fails, we'll exit instead of continuing.
2471              */
2472
2473             ms_iis5_hack = 1;
2474          }
2475
2476          /*
2477           * If this is an SSL connection or we're in the body
2478           * of the server document, just write it to the client,
2479           * unless we need to buffer the body for later content-filtering
2480           */
2481          if (server_body || http->ssl)
2482          {
2483             if (buffer_and_filter_content)
2484             {
2485                /*
2486                 * If there is no memory left for buffering the content, or the buffer limit
2487                 * has been reached, switch to non-filtering mode, i.e. make & write the
2488                 * header, flush the iob and buf, and get out of the way.
2489                 */
2490                if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2491                {
2492                   size_t hdrlen;
2493                   long flushed;
2494
2495                   log_error(LOG_LEVEL_INFO,
2496                      "Flushing header and buffers. Stepping back from filtering.");
2497
2498                   hdr = list_to_text(csp->headers);
2499                   if (hdr == NULL)
2500                   {
2501                      /*
2502                       * Memory is too tight to even generate the header.
2503                       * Send our static "Out-of-memory" page.
2504                       */
2505                      log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2506                      rsp = cgi_error_memory();
2507                      send_crunch_response(csp, rsp);
2508                      mark_server_socket_tainted(csp);
2509                      return;
2510                   }
2511                   hdrlen = strlen(hdr);
2512
2513                   if (write_socket(csp->cfd, hdr, hdrlen)
2514                    || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2515                    || (write_socket(csp->cfd, buf, (size_t)len)))
2516                   {
2517                      log_error(LOG_LEVEL_CONNECT,
2518                         "Flush header and buffers to client failed: %E");
2519                      freez(hdr);
2520                      mark_server_socket_tainted(csp);
2521                      return;
2522                   }
2523
2524                   /*
2525                    * Reset the byte_count to the amount of bytes
2526                    * we just flushed. len will be added a few lines below,
2527                    * hdrlen doesn't matter for LOG_LEVEL_CLF.
2528                    */
2529                   byte_count = (unsigned long long)flushed;
2530                   freez(hdr);
2531                   buffer_and_filter_content = 0;
2532                   server_body = 1;
2533                }
2534             }
2535             else
2536             {
2537                if (write_socket(csp->cfd, buf, (size_t)len))
2538                {
2539                   log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2540                   mark_server_socket_tainted(csp);
2541                   return;
2542                }
2543             }
2544             byte_count += (unsigned long long)len;
2545             continue;
2546          }
2547          else
2548          {
2549             /*
2550              * We're still looking for the end of the server's header.
2551              * Buffer up the data we just read.  If that fails, there's
2552              * little we can do but send our static out-of-memory page.
2553              */
2554             if (add_to_iob(csp->iob, csp->config->buffer_limit, buf, len))
2555             {
2556                log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2557                rsp = cgi_error_memory();
2558                send_crunch_response(csp, rsp);
2559                mark_server_socket_tainted(csp);
2560                return;
2561             }
2562
2563             /* Convert iob into something sed() can digest */
2564             if (JB_ERR_PARSE == get_server_headers(csp))
2565             {
2566                if (ms_iis5_hack)
2567                {
2568                   /*
2569                    * Well, we tried our MS IIS/5 hack and it didn't work.
2570                    * The header is incomplete and there isn't anything
2571                    * we can do about it.
2572                    */
2573                   log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2574                      "Applying the MS IIS5 hack didn't help.");
2575                   log_error(LOG_LEVEL_CLF,
2576                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2577                   write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2578                      strlen(INVALID_SERVER_HEADERS_RESPONSE));
2579                   mark_server_socket_tainted(csp);
2580                   return;
2581                }
2582                else
2583                {
2584                   /*
2585                    * Since we have to wait for more from the server before
2586                    * we can parse the headers we just continue here.
2587                    */
2588                   log_error(LOG_LEVEL_CONNECT,
2589                      "Continuing buffering server headers from socket %d. "
2590                      "Bytes most recently read: %d.", csp->cfd, len);
2591                   continue;
2592                }
2593             }
2594             else
2595             {
2596                /*
2597                 * Account for the content bytes we
2598                 * might have gotten with the headers.
2599                 */
2600                assert(csp->iob->eod >= csp->iob->cur);
2601                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2602             }
2603
2604             /* Did we actually get anything? */
2605             if (NULL == csp->headers->first)
2606             {
2607                if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2608                {
2609                   log_error(LOG_LEVEL_ERROR,
2610                      "No server or forwarder response received on socket %d. "
2611                      "Closing client socket %d without sending data.",
2612                      csp->server_connection.sfd, csp->cfd);
2613                   log_error(LOG_LEVEL_CLF,
2614                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2615                }
2616                else
2617                {
2618                   log_error(LOG_LEVEL_ERROR,
2619                      "No server or forwarder response received on socket %d.",
2620                      csp->server_connection.sfd);
2621                   send_crunch_response(csp, error_response(csp, "no-server-data"));
2622                }
2623                free_http_request(http);
2624                mark_server_socket_tainted(csp);
2625                return;
2626             }
2627
2628             assert(csp->headers->first->str);
2629             assert(!http->ssl);
2630             if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2631                 strncmpic(csp->headers->first->str, "ICY", 3))
2632             {
2633                /*
2634                 * It doesn't look like a HTTP (or Shoutcast) response:
2635                 * tell the client and log the problem.
2636                 */
2637                if (strlen(csp->headers->first->str) > 30)
2638                {
2639                   csp->headers->first->str[30] = '\0';
2640                }
2641                log_error(LOG_LEVEL_ERROR,
2642                   "Invalid server or forwarder response. Starts with: %s",
2643                   csp->headers->first->str);
2644                log_error(LOG_LEVEL_CLF,
2645                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2646                write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2647                   strlen(INVALID_SERVER_HEADERS_RESPONSE));
2648                free_http_request(http);
2649                mark_server_socket_tainted(csp);
2650                return;
2651             }
2652
2653             /*
2654              * We have now received the entire server header,
2655              * filter it and send the result to the client
2656              */
2657             if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2658             {
2659                log_error(LOG_LEVEL_CLF,
2660                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2661                write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2662                   strlen(INVALID_SERVER_HEADERS_RESPONSE));
2663                free_http_request(http);
2664                mark_server_socket_tainted(csp);
2665                return;
2666             }
2667             hdr = list_to_text(csp->headers);
2668             if (hdr == NULL)
2669             {
2670                /* FIXME Should handle error properly */
2671                log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2672             }
2673
2674             if ((csp->flags & CSP_FLAG_CHUNKED)
2675                && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2676                && ((csp->iob->eod - csp->iob->cur) >= 5)
2677                && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2678             {
2679                log_error(LOG_LEVEL_CONNECT,
2680                   "Looks like we got the last chunk together with "
2681                   "the server headers. We better stop reading.");
2682                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2683                csp->expected_content_length = byte_count;
2684                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2685             }
2686
2687             csp->server_connection.response_received = time(NULL);
2688
2689             if (crunch_response_triggered(csp, crunchers_light))
2690             {
2691                /*
2692                 * One of the tags created by a server-header
2693                 * tagger triggered a crunch. We already
2694                 * delivered the crunch response to the client
2695                 * and are done here after cleaning up.
2696                 */
2697                 freez(hdr);
2698                 mark_server_socket_tainted(csp);
2699                 return;
2700             }
2701             /* Buffer and pcrs filter this if appropriate. */
2702
2703             if (!http->ssl) /* We talk plaintext */
2704             {
2705                buffer_and_filter_content = content_requires_filtering(csp);
2706             }
2707             /*
2708              * Only write if we're not buffering for content modification
2709              */
2710             if (!buffer_and_filter_content)
2711             {
2712                /*
2713                 * Write the server's (modified) header to
2714                 * the client (along with anything else that
2715                 * may be in the buffer)
2716                 */
2717
2718                if (write_socket(csp->cfd, hdr, strlen(hdr))
2719                 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2720                {
2721                   log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2722
2723                   /*
2724                    * The write failed, so don't bother mentioning it
2725                    * to the client... it probably can't hear us anyway.
2726                    */
2727                   freez(hdr);
2728                   mark_server_socket_tainted(csp);
2729                   return;
2730                }
2731             }
2732
2733             /* we're finished with the server's header */
2734
2735             freez(hdr);
2736             server_body = 1;
2737
2738             /*
2739              * If this was a MS IIS/5 hack then it means the server
2740              * has already closed the connection. Nothing more to read.
2741              * Time to bail.
2742              */
2743             if (ms_iis5_hack)
2744             {
2745                log_error(LOG_LEVEL_ERROR,
2746                   "Closed server connection detected. "
2747                   "Applying the MS IIS5 hack didn't help.");
2748                log_error(LOG_LEVEL_CLF,
2749                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2750                write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2751                   strlen(INVALID_SERVER_HEADERS_RESPONSE));
2752                mark_server_socket_tainted(csp);
2753                return;
2754             }
2755          }
2756          continue;
2757       }
2758       mark_server_socket_tainted(csp);
2759       return; /* huh? we should never get here */
2760    }
2761
2762    if (csp->content_length == 0)
2763    {
2764       /*
2765        * If Privoxy didn't recalculate the Content-Length,
2766        * byte_count is still correct.
2767        */
2768       csp->content_length = byte_count;
2769    }
2770
2771 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2772    if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2773       && (csp->expected_content_length != byte_count))
2774    {
2775       log_error(LOG_LEVEL_CONNECT,
2776          "Received %llu bytes while expecting %llu.",
2777          byte_count, csp->expected_content_length);
2778       mark_server_socket_tainted(csp);
2779    }
2780 #endif
2781
2782    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2783       csp->ip_addr_str, http->ocmd, csp->content_length);
2784
2785    csp->server_connection.timestamp = time(NULL);
2786 }
2787
2788
2789 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2790 /*********************************************************************
2791  *
2792  * Function    :  prepare_csp_for_next_request
2793  *
2794  * Description :  Put the csp in a mostly vergin state.
2795  *
2796  * Parameters  :
2797  *          1  :  csp = Current client state (buffers, headers, etc...)
2798  *
2799  * Returns     :  N/A
2800  *
2801  *********************************************************************/
2802 static void prepare_csp_for_next_request(struct client_state *csp)
2803 {
2804    unsigned int toggled_on_flag_set = (0 != (csp->flags & CSP_FLAG_TOGGLED_ON));
2805
2806    csp->content_type = 0;
2807    csp->content_length = 0;
2808    csp->expected_content_length = 0;
2809    csp->expected_client_content_length = 0;
2810    list_remove_all(csp->headers);
2811    clear_iob(csp->iob);
2812    freez(csp->error_message);
2813    free_http_request(csp->http);
2814    destroy_list(csp->headers);
2815    destroy_list(csp->tags);
2816    free_current_action(csp->action);
2817    if (NULL != csp->fwd)
2818    {
2819       unload_forward_spec(csp->fwd);
2820       csp->fwd = NULL;
2821    }
2822    /* XXX: Store per-connection flags someplace else. */
2823    csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
2824    if (toggled_on_flag_set)
2825    {
2826       csp->flags |= CSP_FLAG_TOGGLED_ON;
2827    }
2828
2829    if (csp->client_iob->eod > csp->client_iob->cur)
2830    {
2831       long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
2832       size_t data_length  = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2833
2834       assert(bytes_to_shift > 0);
2835       assert(data_length > 0);
2836
2837       log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
2838          data_length, bytes_to_shift);
2839       memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
2840       csp->client_iob->cur = csp->client_iob->buf;
2841       assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
2842       csp->client_iob->eod = csp->client_iob->buf + data_length;
2843       memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
2844
2845       csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
2846    }
2847    else
2848    {
2849       /*
2850        * We mainly care about resetting client_iob->cur so we don't
2851        * waste buffer space at the beginning and don't mess up the
2852        * request restoration done by cgi_show_request().
2853        *
2854        * Freeing the buffer itself isn't technically necessary,
2855        * but makes debugging more convenient.
2856        */
2857       clear_iob(csp->client_iob);
2858    }
2859 }
2860 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2861
2862
2863 /*********************************************************************
2864  *
2865  * Function    :  serve
2866  *
2867  * Description :  This is little more than chat.  We only "serve" to
2868  *                to close (or remember) any socket that chat may have
2869  *                opened.
2870  *
2871  * Parameters  :
2872  *          1  :  csp = Current client state (buffers, headers, etc...)
2873  *
2874  * Returns     :  N/A
2875  *
2876  *********************************************************************/
2877 #ifdef AMIGA
2878 void serve(struct client_state *csp)
2879 #else /* ifndef AMIGA */
2880 static void serve(struct client_state *csp)
2881 #endif /* def AMIGA */
2882 {
2883    int config_file_change_detected = 0; /* Only used for debugging */
2884 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2885 #ifdef FEATURE_CONNECTION_SHARING
2886    static int monitor_thread_running = 0;
2887 #endif /* def FEATURE_CONNECTION_SHARING */
2888    int continue_chatting = 0;
2889
2890    log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
2891       csp->ip_addr_str, csp->cfd);
2892
2893    do
2894    {
2895       unsigned int latency;
2896
2897       chat(csp);
2898
2899       /*
2900        * If the request has been crunched,
2901        * the calculated latency is zero.
2902        */
2903       latency = (unsigned)(csp->server_connection.response_received -
2904          csp->server_connection.request_sent) / 2;
2905
2906       if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2907          && (csp->flags & CSP_FLAG_CRUNCHED)
2908          && (csp->expected_client_content_length != 0))
2909       {
2910          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
2911          log_error(LOG_LEVEL_CONNECT,
2912             "Tainting client socket %d due to unread data.", csp->cfd);
2913       }
2914
2915       continue_chatting = (csp->config->feature_flags
2916          & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2917          && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2918          && (csp->cfd != JB_INVALID_SOCKET)
2919          && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2920          && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
2921             || (csp->flags & CSP_FLAG_CHUNKED));
2922
2923       if (!(csp->flags & CSP_FLAG_CRUNCHED)
2924          && (csp->server_connection.sfd != JB_INVALID_SOCKET))
2925       {
2926          if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
2927          {
2928             csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
2929          }
2930          if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2931             || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2932             || !socket_is_still_alive(csp->server_connection.sfd)
2933             || !(latency < csp->server_connection.keep_alive_timeout))
2934          {
2935             log_error(LOG_LEVEL_CONNECT,
2936                "Closing server socket %d connected to %s. "
2937                "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
2938                csp->server_connection.sfd, csp->server_connection.host,
2939                0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2940                0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2941                socket_is_still_alive(csp->server_connection.sfd),
2942                csp->server_connection.keep_alive_timeout);
2943 #ifdef FEATURE_CONNECTION_SHARING
2944             if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2945             {
2946                forget_connection(csp->server_connection.sfd);
2947             }
2948 #endif /* def FEATURE_CONNECTION_SHARING */
2949             close_socket(csp->server_connection.sfd);
2950             mark_connection_closed(&csp->server_connection);
2951          }
2952       }
2953
2954       if (continue_chatting && any_loaded_file_changed(csp))
2955       {
2956          continue_chatting = 0;
2957          config_file_change_detected = 1;
2958       }
2959
2960       if (continue_chatting)
2961       {
2962          if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
2963             && socket_is_still_alive(csp->cfd))
2964          {
2965             log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
2966                "pipelined on socket %d and the socket is still alive.",
2967                csp->requests_received_total+1, csp->cfd);
2968             prepare_csp_for_next_request(csp);
2969             continue;
2970          }
2971
2972          if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
2973          {
2974             if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2975             {
2976                log_error(LOG_LEVEL_CONNECT,
2977                   "Waiting for the next client request on socket %d. "
2978                   "Keeping the server socket %d to %s open.",
2979                   csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2980             }
2981             else
2982             {
2983                log_error(LOG_LEVEL_CONNECT,
2984                   "Waiting for the next client request on socket %d. "
2985                   "No server socket to keep open.", csp->cfd);
2986             }
2987          }
2988
2989          if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2990             && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
2991             && socket_is_still_alive(csp->cfd))
2992          {
2993             log_error(LOG_LEVEL_CONNECT,
2994                "Client request %u arrived in time on socket %d.",
2995                csp->requests_received_total+1, csp->cfd);
2996             prepare_csp_for_next_request(csp);
2997          }
2998          else
2999          {
3000 #ifdef FEATURE_CONNECTION_SHARING
3001             if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3002                && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3003                && (socket_is_still_alive(csp->server_connection.sfd)))
3004             {
3005                time_t time_open = time(NULL) - csp->server_connection.timestamp;
3006
3007                if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3008                {
3009                   break;
3010                }
3011
3012                remember_connection(&csp->server_connection);
3013                csp->server_connection.sfd = JB_INVALID_SOCKET;
3014                drain_and_close_socket(csp->cfd);
3015                csp->cfd = JB_INVALID_SOCKET;
3016                privoxy_mutex_lock(&connection_reuse_mutex);
3017                if (!monitor_thread_running)
3018                {
3019                   monitor_thread_running = 1;
3020                   privoxy_mutex_unlock(&connection_reuse_mutex);
3021                   wait_for_alive_connections();
3022                   privoxy_mutex_lock(&connection_reuse_mutex);
3023                   monitor_thread_running = 0;
3024                }
3025                privoxy_mutex_unlock(&connection_reuse_mutex);
3026             }
3027 #endif /* def FEATURE_CONNECTION_SHARING */
3028             break;
3029          }
3030       }
3031       else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3032       {
3033          log_error(LOG_LEVEL_CONNECT,
3034             "Closing server socket %d connected to %s. Keep-alive: %u. "
3035             "Tainted: %u. Socket alive: %u. Timeout: %u. "
3036             "Configuration file change detected: %u",
3037             csp->server_connection.sfd, csp->server_connection.host,
3038             0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3039             0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3040             socket_is_still_alive(csp->server_connection.sfd),
3041             csp->server_connection.keep_alive_timeout,
3042             config_file_change_detected);
3043       }
3044    } while (continue_chatting);
3045
3046 #else
3047    chat(csp);
3048 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3049
3050    if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3051    {
3052 #ifdef FEATURE_CONNECTION_SHARING
3053       if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3054       {
3055          forget_connection(csp->server_connection.sfd);
3056       }
3057 #endif /* def FEATURE_CONNECTION_SHARING */
3058       close_socket(csp->server_connection.sfd);
3059    }
3060
3061 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3062    mark_connection_closed(&csp->server_connection);
3063 #endif
3064
3065    if (csp->cfd != JB_INVALID_SOCKET)
3066    {
3067       log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3068          "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3069          "Configuration file change detected: %u. Requests received: %u.",
3070          csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3071          socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3072          config_file_change_detected, csp->requests_received_total);
3073       drain_and_close_socket(csp->cfd);
3074    }
3075
3076    csp->flags &= ~CSP_FLAG_ACTIVE;
3077
3078 }
3079
3080
3081 #ifdef __BEOS__
3082 /*********************************************************************
3083  *
3084  * Function    :  server_thread
3085  *
3086  * Description :  We only exist to call `serve' in a threaded environment.
3087  *
3088  * Parameters  :
3089  *          1  :  data = Current client state (buffers, headers, etc...)
3090  *
3091  * Returns     :  Always 0.
3092  *
3093  *********************************************************************/
3094 static int32 server_thread(void *data)
3095 {
3096    serve((struct client_state *) data);
3097    return 0;
3098
3099 }
3100 #endif
3101
3102
3103 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3104 /*********************************************************************
3105  *
3106  * Function    :  usage
3107  *
3108  * Description :  Print usage info & exit.
3109  *
3110  * Parameters  :  Pointer to argv[0] for identifying ourselves
3111  *
3112  * Returns     :  No. ,-)
3113  *
3114  *********************************************************************/
3115 static void usage(const char *myname)
3116 {
3117    printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3118           "Usage: %s [--config-test] "
3119 #if defined(unix)
3120           "[--chroot] "
3121 #endif /* defined(unix) */
3122           "[--help] "
3123 #if defined(unix)
3124           "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3125 #endif /* defined(unix) */
3126           "[--version] [configfile]\n"
3127           "Aborting\n", myname);
3128
3129    exit(2);
3130
3131 }
3132 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3133
3134
3135 #ifdef MUTEX_LOCKS_AVAILABLE
3136 /*********************************************************************
3137  *
3138  * Function    :  privoxy_mutex_lock
3139  *
3140  * Description :  Locks a mutex.
3141  *
3142  * Parameters  :
3143  *          1  :  mutex = The mutex to lock.
3144  *
3145  * Returns     :  Void. May exit in case of errors.
3146  *
3147  *********************************************************************/
3148 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3149 {
3150 #ifdef FEATURE_PTHREAD
3151    int err = pthread_mutex_lock(mutex);
3152    if (err)
3153    {
3154       if (mutex != &log_mutex)
3155       {
3156          log_error(LOG_LEVEL_FATAL,
3157             "Mutex locking failed: %s.\n", strerror(err));
3158       }
3159       exit(1);
3160    }
3161 #else
3162    EnterCriticalSection(mutex);
3163 #endif /* def FEATURE_PTHREAD */
3164 }
3165
3166
3167 /*********************************************************************
3168  *
3169  * Function    :  privoxy_mutex_unlock
3170  *
3171  * Description :  Unlocks a mutex.
3172  *
3173  * Parameters  :
3174  *          1  :  mutex = The mutex to unlock.
3175  *
3176  * Returns     :  Void. May exit in case of errors.
3177  *
3178  *********************************************************************/
3179 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3180 {
3181 #ifdef FEATURE_PTHREAD
3182    int err = pthread_mutex_unlock(mutex);
3183    if (err)
3184    {
3185       if (mutex != &log_mutex)
3186       {
3187          log_error(LOG_LEVEL_FATAL,
3188             "Mutex unlocking failed: %s.\n", strerror(err));
3189       }
3190       exit(1);
3191    }
3192 #else
3193    LeaveCriticalSection(mutex);
3194 #endif /* def FEATURE_PTHREAD */
3195 }
3196
3197
3198 /*********************************************************************
3199  *
3200  * Function    :  privoxy_mutex_init
3201  *
3202  * Description :  Prepares a mutex.
3203  *
3204  * Parameters  :
3205  *          1  :  mutex = The mutex to initialize.
3206  *
3207  * Returns     :  Void. May exit in case of errors.
3208  *
3209  *********************************************************************/
3210 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3211 {
3212 #ifdef FEATURE_PTHREAD
3213    int err = pthread_mutex_init(mutex, 0);
3214    if (err)
3215    {
3216       printf("Fatal error. Mutex initialization failed: %s.\n",
3217          strerror(err));
3218       exit(1);
3219    }
3220 #else
3221    InitializeCriticalSection(mutex);
3222 #endif /* def FEATURE_PTHREAD */
3223 }
3224 #endif /* def MUTEX_LOCKS_AVAILABLE */
3225
3226 /*********************************************************************
3227  *
3228  * Function    :  initialize_mutexes
3229  *
3230  * Description :  Prepares mutexes if mutex support is available.
3231  *
3232  * Parameters  :  None
3233  *
3234  * Returns     :  Void, exits in case of errors.
3235  *
3236  *********************************************************************/
3237 static void initialize_mutexes(void)
3238 {
3239 #ifdef MUTEX_LOCKS_AVAILABLE
3240    /*
3241     * Prepare global mutex semaphores
3242     */
3243    privoxy_mutex_init(&log_mutex);
3244    privoxy_mutex_init(&log_init_mutex);
3245    privoxy_mutex_init(&connection_reuse_mutex);
3246 #ifdef FEATURE_EXTERNAL_FILTERS
3247    privoxy_mutex_init(&external_filter_mutex);
3248 #endif
3249
3250    /*
3251     * XXX: The assumptions below are a bit naive
3252     * and can cause locks that aren't necessary.
3253     *
3254     * For example older FreeBSD versions (< 6.x?)
3255     * have no gethostbyname_r, but gethostbyname is
3256     * thread safe.
3257     */
3258 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3259    privoxy_mutex_init(&resolver_mutex);
3260 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3261    /*
3262     * XXX: should we use a single mutex for
3263     * localtime() and gmtime() as well?
3264     */
3265 #ifndef HAVE_GMTIME_R
3266    privoxy_mutex_init(&gmtime_mutex);
3267 #endif /* ndef HAVE_GMTIME_R */
3268
3269 #ifndef HAVE_LOCALTIME_R
3270    privoxy_mutex_init(&localtime_mutex);
3271 #endif /* ndef HAVE_GMTIME_R */
3272
3273 #ifndef HAVE_RANDOM
3274    privoxy_mutex_init(&rand_mutex);
3275 #endif /* ndef HAVE_RANDOM */
3276
3277 #endif /* def MUTEX_LOCKS_AVAILABLE */
3278 }
3279
3280
3281 /*********************************************************************
3282  *
3283  * Function    :  main
3284  *
3285  * Description :  Load the config file and start the listen loop.
3286  *                This function is a lot more *sane* with the `load_config'
3287  *                and `listen_loop' functions; although it stills does
3288  *                a *little* too much for my taste.
3289  *
3290  * Parameters  :
3291  *          1  :  argc = Number of parameters (including $0).
3292  *          2  :  argv = Array of (char *)'s to the parameters.
3293  *
3294  * Returns     :  1 if : can't open config file, unrecognized directive,
3295  *                stats requested in multi-thread mode, can't open the
3296  *                log file, can't open the jar file, listen port is invalid,
3297  *                any load fails, and can't bind port.
3298  *
3299  *                Else main never returns, the process must be signaled
3300  *                to terminate execution.  Or, on Windows, use the
3301  *                "File", "Exit" menu option.
3302  *
3303  *********************************************************************/
3304 #ifdef __MINGW32__
3305 int real_main(int argc, char **argv)
3306 #else
3307 int main(int argc, char **argv)
3308 #endif
3309 {
3310    int argc_pos = 0;
3311    int do_config_test = 0;
3312    unsigned int random_seed;
3313 #ifdef unix
3314    struct passwd *pw = NULL;
3315    struct group *grp = NULL;
3316    int do_chroot = 0;
3317    char *pre_chroot_nslookup_to_load_resolver = NULL;
3318 #endif
3319
3320    Argc = argc;
3321    Argv = argv;
3322
3323    configfile =
3324 #if !defined(_WIN32)
3325    "config"
3326 #else
3327    "config.txt"
3328 #endif
3329       ;
3330
3331    /* Prepare mutexes if supported and necessary. */
3332    initialize_mutexes();
3333
3334    /* Enable logging until further notice. */
3335    init_log_module();
3336
3337    /*
3338     * Parse the command line arguments
3339     *
3340     * XXX: simply printing usage information in case of
3341     * invalid arguments isn't particularly user friendly.
3342     */
3343    while (++argc_pos < argc)
3344    {
3345 #ifdef _WIN32
3346       /* Check to see if the service must be installed or uninstalled */
3347       if (strncmp(argv[argc_pos], "--install", 9) == 0)
3348       {
3349          const char *pName = argv[argc_pos] + 9;
3350          if (*pName == ':')
3351             pName++;
3352          exit((install_service(pName)) ? 0 : 1);
3353       }
3354       else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3355       {
3356          const char *pName = argv[argc_pos] + 11;
3357          if (*pName == ':')
3358             pName++;
3359          exit((uninstall_service(pName)) ? 0 : 1);
3360       }
3361       else if (strcmp(argv[argc_pos], "--service") == 0)
3362       {
3363          bRunAsService = TRUE;
3364          w32_set_service_cwd();
3365          atexit(w32_service_exit_notify);
3366       }
3367       else
3368 #endif /* defined(_WIN32) */
3369
3370
3371 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3372
3373       if (strcmp(argv[argc_pos], "--help") == 0)
3374       {
3375          usage(argv[0]);
3376       }
3377
3378       else if (strcmp(argv[argc_pos], "--version") == 0)
3379       {
3380          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3381          exit(0);
3382       }
3383
3384 #if defined(unix)
3385
3386       else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3387       {
3388          set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3389          daemon_mode = 0;
3390       }
3391
3392       else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3393       {
3394          if (++argc_pos == argc) usage(argv[0]);
3395          pidfile = strdup_or_die(argv[argc_pos]);
3396       }
3397
3398       else if (strcmp(argv[argc_pos], "--user") == 0)
3399       {
3400          char *user_arg;
3401          char *group_name;
3402
3403          if (++argc_pos == argc) usage(argv[argc_pos]);
3404
3405          user_arg = strdup_or_die(argv[argc_pos]);
3406          group_name = strchr(user_arg, '.');
3407          if (NULL != group_name)
3408          {
3409             /* Nul-terminate the user name */
3410             *group_name = '\0';
3411
3412             /* Skip the former delimiter to actually reach the group name */
3413             group_name++;
3414
3415             grp = getgrnam(group_name);
3416             if (NULL == grp)
3417             {
3418                log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3419             }
3420          }
3421          pw = getpwnam(user_arg);
3422          if (NULL == pw)
3423          {
3424             log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3425          }
3426
3427          freez(user_arg);
3428       }
3429
3430       else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3431       {
3432          if (++argc_pos == argc) usage(argv[0]);
3433          pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3434       }
3435
3436       else if (strcmp(argv[argc_pos], "--chroot") == 0)
3437       {
3438          do_chroot = 1;
3439       }
3440 #endif /* defined(unix) */
3441
3442       else if (strcmp(argv[argc_pos], "--config-test") == 0)
3443       {
3444          do_config_test = 1;
3445       }
3446
3447       else if (argc_pos + 1 != argc)
3448       {
3449          /*
3450           * This is neither the last command line
3451           * option, nor was it recognized before,
3452           * therefore it must be invalid.
3453           */
3454          usage(argv[0]);
3455       }
3456       else
3457
3458 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3459       {
3460          configfile = argv[argc_pos];
3461       }
3462
3463    } /* -END- while (more arguments) */
3464
3465    show_version(Argv[0]);
3466
3467 #if defined(unix)
3468    if (*configfile != '/')
3469    {
3470       char cwd[BUFFER_SIZE];
3471       char *abs_file;
3472       size_t abs_file_size;
3473
3474       /* make config-filename absolute here */
3475       if (NULL == getcwd(cwd, sizeof(cwd)))
3476       {
3477          perror("failed to get current working directory");
3478          exit(1);
3479       }
3480
3481       basedir = strdup_or_die(cwd);
3482       /* XXX: why + 5? */
3483       abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3484       abs_file = malloc_or_die(abs_file_size);
3485       strlcpy(abs_file, basedir, abs_file_size);
3486       strlcat(abs_file, "/", abs_file_size);
3487       strlcat(abs_file, configfile, abs_file_size);
3488       configfile = abs_file;
3489    }
3490 #endif /* defined unix */
3491
3492
3493    files->next = NULL;
3494    clients->next = NULL;
3495
3496    /* XXX: factor out initialising after the next stable release. */
3497 #ifdef AMIGA
3498    InitAmiga();
3499 #elif defined(_WIN32)
3500    InitWin32();
3501 #endif
3502
3503    random_seed = (unsigned int)time(NULL);
3504 #ifdef HAVE_RANDOM
3505    srandom(random_seed);
3506 #else
3507    srand(random_seed);
3508 #endif /* ifdef HAVE_RANDOM */
3509
3510    /*
3511     * Unix signal handling
3512     *
3513     * Catch the abort, interrupt and terminate signals for a graceful exit
3514     * Catch the hangup signal so the errlog can be reopened.
3515     * Ignore the broken pipe signals (FIXME: Why?)
3516     */
3517 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3518 {
3519    int idx;
3520    const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3521
3522    for (idx = 0; idx < SZ(catched_signals); idx++)
3523    {
3524 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3525       if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3526 #else
3527       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3528 #endif /* ifdef sun */
3529       {
3530          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3531       }
3532    }
3533
3534    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3535    {
3536       log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3537    }
3538
3539 }
3540 #else /* ifdef _WIN32 */
3541 # ifdef _WIN_CONSOLE
3542    /*
3543     * We *are* in a windows console app.
3544     * Print a verbose messages about FAQ's and such
3545     */
3546    printf("%s", win32_blurb);
3547 # endif /* def _WIN_CONSOLE */
3548 #endif /* def _WIN32 */
3549
3550    if (do_config_test)
3551    {
3552       exit(NULL == load_config());
3553    }
3554
3555    /* Initialize the CGI subsystem */
3556    cgi_init_error_messages();
3557
3558    /*
3559     * If running on unix and without the --no-daemon
3560     * option, become a daemon. I.e. fork, detach
3561     * from tty and get process group leadership
3562     */
3563 #if defined(unix)
3564 {
3565    if (daemon_mode)
3566    {
3567       int fd;
3568       pid_t pid = fork();
3569
3570       if (pid < 0) /* error */
3571       {
3572          perror("fork");
3573          exit(3);
3574       }
3575       else if (pid != 0) /* parent */
3576       {
3577          int status;
3578          pid_t wpid;
3579          /*
3580           * must check for errors
3581           * child died due to missing files aso
3582           */
3583          sleep(1);
3584          wpid = waitpid(pid, &status, WNOHANG);
3585          if (wpid != 0)
3586          {
3587             exit(1);
3588          }
3589          exit(0);
3590       }
3591       /* child */
3592
3593       setsid();
3594
3595       /*
3596        * stderr (fd 2) will be closed later on,
3597        * when the config file has been parsed.
3598        */
3599       close(0);
3600       close(1);
3601
3602       /*
3603        * Reserve fd 0 and 1 to prevent abort() and friends
3604        * from sending stuff to the clients or servers.
3605        */
3606       fd = open("/dev/null", O_RDONLY);
3607       if (fd == -1)
3608       {
3609          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3610       }
3611       else if (fd != 0)
3612       {
3613          if (dup2(fd, 0) == -1)
3614          {
3615             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3616          }
3617          close(fd);
3618       }
3619       fd = open("/dev/null", O_WRONLY);
3620       if (fd == -1)
3621       {
3622          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3623       }
3624       else if (fd != 1)
3625       {
3626          if (dup2(fd, 1) == -1)
3627          {
3628             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3629          }
3630          close(fd);
3631       }
3632
3633 #ifdef FEATURE_EXTERNAL_FILTERS
3634       for (fd = 0; fd < 3; fd++)
3635       {
3636          mark_socket_for_close_on_execute(fd);
3637       }
3638 #endif
3639
3640       chdir("/");
3641
3642    } /* -END- if (daemon_mode) */
3643
3644    /*
3645     * As soon as we have written the PID file, we can switch
3646     * to the user and group ID indicated by the --user option
3647     */
3648    write_pid_file();
3649
3650    if (NULL != pw)
3651    {
3652       if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3653       {
3654          log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3655       }
3656       if (NULL != grp)
3657       {
3658          if (setgroups(1, &grp->gr_gid))
3659          {
3660             log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3661          }
3662       }
3663       else if (initgroups(pw->pw_name, pw->pw_gid))
3664       {
3665          log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3666       }
3667       if (do_chroot)
3668       {
3669          if (!pw->pw_dir)
3670          {
3671             log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3672          }
3673          /* Read the time zone file from /etc before doing chroot. */
3674          tzset();
3675          if (NULL != pre_chroot_nslookup_to_load_resolver
3676              && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3677          {
3678             /* Initialize resolver library. */
3679             (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3680          }
3681          if (chroot(pw->pw_dir) < 0)
3682          {
3683             log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3684          }
3685          if (chdir ("/"))
3686          {
3687             log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3688          }
3689       }
3690       if (setuid(pw->pw_uid))
3691       {
3692          log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3693       }
3694       if (do_chroot)
3695       {
3696          char putenv_dummy[64];
3697
3698          strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3699          if (putenv(putenv_dummy) != 0)
3700          {
3701             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3702          }
3703
3704          snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3705          if (putenv(putenv_dummy) != 0)
3706          {
3707             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3708          }
3709       }
3710    }
3711    else if (do_chroot)
3712    {
3713       log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3714    }
3715 }
3716 #endif /* defined unix */
3717
3718 #ifdef _WIN32
3719    /* This will be FALSE unless the command line specified --service
3720     */
3721    if (bRunAsService)
3722    {
3723       /* Yup, so now we must attempt to establish a connection
3724        * with the service dispatcher. This will only work if this
3725        * process was launched by the service control manager to
3726        * actually run as a service. If this isn't the case, i've
3727        * known it take around 30 seconds or so for the call to return.
3728        */
3729
3730       /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3731       if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3732       {
3733          /* Service has run, and at this point is now being stopped, so just return */
3734          return 0;
3735       }
3736
3737 #ifdef _WIN_CONSOLE
3738       printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3739 #endif
3740       /* An error occurred. Usually it's because --service was wrongly specified
3741        * and we were unable to connect to the Service Control Dispatcher because
3742        * it wasn't expecting us and is therefore not listening.
3743        *
3744        * For now, just continue below to call the listen_loop function.
3745        */
3746    }
3747 #endif /* def _WIN32 */
3748
3749    listen_loop();
3750
3751    /* NOTREACHED */
3752    return(-1);
3753
3754 }
3755
3756
3757 /*********************************************************************
3758  *
3759  * Function    :  bind_port_helper
3760  *
3761  * Description :  Bind the listen port.  Handles logging, and aborts
3762  *                on failure.
3763  *
3764  * Parameters  :
3765  *          1  :  haddr = Host address to bind to. Use NULL to bind to
3766  *                        INADDR_ANY.
3767  *          2  :  hport = Specifies port to bind to.
3768  *
3769  * Returns     :  Port that was opened.
3770  *
3771  *********************************************************************/
3772 static jb_socket bind_port_helper(const char *haddr, int hport)
3773 {
3774    int result;
3775    jb_socket bfd;
3776
3777    result = bind_port(haddr, hport, &bfd);
3778
3779    if (result < 0)
3780    {
3781       const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
3782       switch(result)
3783       {
3784          case -3:
3785             log_error(LOG_LEVEL_FATAL,
3786                "can't bind to %s:%d: There may be another Privoxy "
3787                "or some other proxy running on port %d",
3788                bind_address, hport, hport);
3789
3790          case -2:
3791             log_error(LOG_LEVEL_FATAL,
3792                "can't bind to %s:%d: The hostname is not resolvable",
3793                bind_address, hport);
3794
3795          default:
3796             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3797                bind_address, hport);
3798       }
3799
3800       /* shouldn't get here */
3801       return JB_INVALID_SOCKET;
3802    }
3803
3804 #ifndef _WIN32
3805    if (bfd >= FD_SETSIZE)
3806    {
3807       log_error(LOG_LEVEL_FATAL,
3808          "Bind socket number too high to use select(): %d >= %d",
3809          bfd, FD_SETSIZE);
3810    }
3811 #endif
3812
3813    if (haddr == NULL)
3814    {
3815       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3816          hport);
3817    }
3818    else
3819    {
3820       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3821          hport, haddr);
3822    }
3823
3824    return bfd;
3825 }
3826
3827
3828 /*********************************************************************
3829  *
3830  * Function    :  bind_ports_helper
3831  *
3832  * Description :  Bind the listen ports.  Handles logging, and aborts
3833  *                on failure.
3834  *
3835  * Parameters  :
3836  *          1  :  config = Privoxy configuration.  Specifies ports
3837  *                         to bind to.
3838  *          2  :  sockets = Preallocated array of opened sockets
3839  *                          corresponding to specification in config.
3840  *                          All non-opened sockets will be set to
3841  *                          JB_INVALID_SOCKET.
3842  *
3843  * Returns     :  Nothing. Inspect sockets argument.
3844  *
3845  *********************************************************************/
3846 static void bind_ports_helper(struct configuration_spec * config,
3847                               jb_socket sockets[])
3848 {
3849    int i;
3850
3851    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3852    {
3853       if (config->hport[i])
3854       {
3855          sockets[i] = bind_port_helper(config->haddr[i], config->hport[i]);
3856       }
3857       else
3858       {
3859          sockets[i] = JB_INVALID_SOCKET;
3860       }
3861    }
3862    config->need_bind = 0;
3863 }
3864
3865
3866 /*********************************************************************
3867  *
3868  * Function    :  close_ports_helper
3869  *
3870  * Description :  Close listenings ports.
3871  *
3872  * Parameters  :
3873  *          1  :  sockets = Array of opened and non-opened sockets to
3874  *                          close. All sockets will be set to
3875  *                          JB_INVALID_SOCKET.
3876  *
3877  * Returns     :  Nothing.
3878  *
3879  *********************************************************************/
3880 static void close_ports_helper(jb_socket sockets[])
3881 {
3882    int i;
3883
3884    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3885    {
3886       if (JB_INVALID_SOCKET != sockets[i])
3887       {
3888          close_socket(sockets[i]);
3889       }
3890       sockets[i] = JB_INVALID_SOCKET;
3891    }
3892 }
3893
3894
3895 #ifdef _WIN32
3896 /* Without this simple workaround we get this compiler warning from _beginthread
3897  *     warning C4028: formal parameter 1 different from declaration
3898  */
3899 void w32_service_listen_loop(void *p)
3900 {
3901    listen_loop();
3902 }
3903 #endif /* def _WIN32 */
3904
3905
3906 /*********************************************************************
3907  *
3908  * Function    :  listen_loop
3909  *
3910  * Description :  bind the listen port and enter a "FOREVER" listening loop.
3911  *
3912  * Parameters  :  N/A
3913  *
3914  * Returns     :  Never.
3915  *
3916  *********************************************************************/
3917 static void listen_loop(void)
3918 {
3919    struct client_states *csp_list = NULL;
3920    struct client_state *csp = NULL;
3921    jb_socket bfds[MAX_LISTENING_SOCKETS];
3922    struct configuration_spec *config;
3923    unsigned int active_threads = 0;
3924
3925    config = load_config();
3926
3927 #ifdef FEATURE_CONNECTION_SHARING
3928    /*
3929     * XXX: Should be relocated once it no
3930     * longer needs to emit log messages.
3931     */
3932    initialize_reusable_connections();
3933 #endif /* def FEATURE_CONNECTION_SHARING */
3934
3935    bind_ports_helper(config, bfds);
3936
3937 #ifdef FEATURE_GRACEFUL_TERMINATION
3938    while (!g_terminate)
3939 #else
3940    for (;;)
3941 #endif
3942    {
3943 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3944       while (waitpid(-1, NULL, WNOHANG) > 0)
3945       {
3946          /* zombie children */
3947       }
3948 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3949
3950       /*
3951        * Free data that was used by died threads
3952        */
3953       active_threads = sweep();
3954
3955 #if defined(unix)
3956       /*
3957        * Re-open the errlog after HUP signal
3958        */
3959       if (received_hup_signal)
3960       {
3961          if (NULL != config->logfile)
3962          {
3963             init_error_log(Argv[0], config->logfile);
3964          }
3965          received_hup_signal = 0;
3966       }
3967 #endif
3968
3969       csp_list = (struct client_states *)zalloc(sizeof(*csp_list));
3970       if (NULL == csp_list)
3971       {
3972          log_error(LOG_LEVEL_FATAL,
3973             "malloc(%d) for csp_list failed: %E", sizeof(*csp_list));
3974          continue;
3975       }
3976       csp = &csp_list->csp;
3977
3978       log_error(LOG_LEVEL_CONNECT,
3979          "Waiting for the next client connection. Currently active threads: %d",
3980          active_threads);
3981
3982       if (!accept_connection(csp, bfds))
3983       {
3984          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3985
3986 #ifdef AMIGA
3987          if (!childs)
3988          {
3989             exit(1);
3990          }
3991 #endif
3992          freez(csp_list);
3993          continue;
3994       }
3995
3996       csp->flags |= CSP_FLAG_ACTIVE;
3997       csp->server_connection.sfd = JB_INVALID_SOCKET;
3998
3999       csp->config = config = load_config();
4000
4001       if (config->need_bind)
4002       {
4003          /*
4004           * Since we were listening to the "old port", we will not see
4005           * a "listen" param change until the next request.  So, at
4006           * least 1 more request must be made for us to find the new
4007           * setting.  I am simply closing the old socket and binding the
4008           * new one.
4009           *
4010           * Which-ever is correct, we will serve 1 more page via the
4011           * old settings.  This should probably be a "show-proxy-args"
4012           * request.  This should not be a so common of an operation
4013           * that this will hurt people's feelings.
4014           */
4015
4016          close_ports_helper(bfds);
4017
4018          bind_ports_helper(config, bfds);
4019       }
4020
4021 #ifdef FEATURE_TOGGLE
4022       if (global_toggle_state)
4023 #endif /* def FEATURE_TOGGLE */
4024       {
4025          csp->flags |= CSP_FLAG_TOGGLED_ON;
4026       }
4027
4028       if (run_loader(csp))
4029       {
4030          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
4031          /* Never get here - LOG_LEVEL_FATAL causes program exit */
4032       }
4033
4034 #ifdef FEATURE_ACL
4035       if (block_acl(NULL,csp))
4036       {
4037          log_error(LOG_LEVEL_CONNECT,
4038             "Connection from %s on socket %d dropped due to ACL", csp->ip_addr_str, csp->cfd);
4039          close_socket(csp->cfd);
4040          freez(csp->ip_addr_str);
4041          freez(csp_list);
4042          continue;
4043       }
4044 #endif /* def FEATURE_ACL */
4045
4046       if ((0 != config->max_client_connections)
4047          && (active_threads >= config->max_client_connections))
4048       {
4049          log_error(LOG_LEVEL_CONNECT,
4050             "Rejecting connection from %s. Maximum number of connections reached.",
4051             csp->ip_addr_str);
4052          write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4053             strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4054          close_socket(csp->cfd);
4055          freez(csp->ip_addr_str);
4056          freez(csp_list);
4057          continue;
4058       }
4059
4060       /* add it to the list of clients */
4061       csp_list->next = clients->next;
4062       clients->next = csp_list;
4063
4064       if (config->multi_threaded)
4065       {
4066          int child_id;
4067
4068 /* this is a switch () statement in the C preprocessor - ugh */
4069 #undef SELECTED_ONE_OPTION
4070
4071 /* Use Pthreads in preference to native code */
4072 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
4073 #define SELECTED_ONE_OPTION
4074          {
4075             pthread_t the_thread;
4076             pthread_attr_t attrs;
4077
4078             pthread_attr_init(&attrs);
4079             pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4080             errno = pthread_create(&the_thread, &attrs,
4081                (void * (*)(void *))serve, csp);
4082             child_id = errno ? -1 : 0;
4083             pthread_attr_destroy(&attrs);
4084          }
4085 #endif
4086
4087 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
4088 #define SELECTED_ONE_OPTION
4089          child_id = _beginthread(
4090             (void (*)(void *))serve,
4091             64 * 1024,
4092             csp);
4093 #endif
4094
4095 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
4096 #define SELECTED_ONE_OPTION
4097          child_id = _beginthread(
4098             (void(* _Optlink)(void*))serve,
4099             NULL,
4100             64 * 1024,
4101             csp);
4102 #endif
4103
4104 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
4105 #define SELECTED_ONE_OPTION
4106          {
4107             thread_id tid = spawn_thread
4108                (server_thread, "server", B_NORMAL_PRIORITY, csp);
4109
4110             if ((tid >= 0) && (resume_thread(tid) == B_OK))
4111             {
4112                child_id = (int) tid;
4113             }
4114             else
4115             {
4116                child_id = -1;
4117             }
4118          }
4119 #endif
4120
4121 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
4122 #define SELECTED_ONE_OPTION
4123          csp->cfd = ReleaseSocket(csp->cfd, -1);
4124
4125 #ifdef __amigaos4__
4126          child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4127                                            NP_Output, Output(),
4128                                            NP_CloseOutput, FALSE,
4129                                            NP_Name, (ULONG)"privoxy child",
4130                                            NP_Child, TRUE,
4131                                            TAG_DONE);
4132 #else
4133          child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4134                                            NP_Output, Output(),
4135                                            NP_CloseOutput, FALSE,
4136                                            NP_Name, (ULONG)"privoxy child",
4137                                            NP_StackSize, 200*1024,
4138                                            TAG_DONE);
4139 #endif
4140          if (0 != child_id)
4141          {
4142             childs++;
4143             ((struct Task *)child_id)->tc_UserData = csp;
4144             Signal((struct Task *)child_id, SIGF_SINGLE);
4145             Wait(SIGF_SINGLE);
4146          }
4147 #endif
4148
4149 #if !defined(SELECTED_ONE_OPTION)
4150          child_id = fork();
4151
4152          /* This block is only needed when using fork().
4153           * When using threads, the server thread was
4154           * created and run by the call to _beginthread().
4155           */
4156          if (child_id == 0)   /* child */
4157          {
4158             int rc = 0;
4159 #ifdef FEATURE_TOGGLE
4160             int inherited_toggle_state = global_toggle_state;
4161 #endif /* def FEATURE_TOGGLE */
4162
4163             serve(csp);
4164
4165             /*
4166              * If we've been toggled or we've blocked the request, tell Mom
4167              */
4168
4169 #ifdef FEATURE_TOGGLE
4170             if (inherited_toggle_state != global_toggle_state)
4171             {
4172                rc |= RC_FLAG_TOGGLED;
4173             }
4174 #endif /* def FEATURE_TOGGLE */
4175
4176 #ifdef FEATURE_STATISTICS
4177             if (csp->flags & CSP_FLAG_REJECTED)
4178             {
4179                rc |= RC_FLAG_BLOCKED;
4180             }
4181 #endif /* ndef FEATURE_STATISTICS */
4182
4183             _exit(rc);
4184          }
4185          else if (child_id > 0) /* parent */
4186          {
4187             /* in a fork()'d environment, the parent's
4188              * copy of the client socket and the CSP
4189              * are not used.
4190              */
4191             int child_status;
4192 #if !defined(_WIN32) && !defined(__CYGWIN__)
4193
4194             wait(&child_status);
4195
4196             /*
4197              * Evaluate child's return code: If the child has
4198              *  - been toggled, toggle ourselves
4199              *  - blocked its request, bump up the stats counter
4200              */
4201
4202 #ifdef FEATURE_TOGGLE
4203             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4204             {
4205                global_toggle_state = !global_toggle_state;
4206             }
4207 #endif /* def FEATURE_TOGGLE */
4208
4209 #ifdef FEATURE_STATISTICS
4210             urls_read++;
4211             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4212             {
4213                urls_rejected++;
4214             }
4215 #endif /* def FEATURE_STATISTICS */
4216
4217 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4218             close_socket(csp->cfd);
4219             csp->flags &= ~CSP_FLAG_ACTIVE;
4220          }
4221 #endif
4222
4223 #undef SELECTED_ONE_OPTION
4224 /* end of cpp switch () */
4225
4226          if (child_id < 0)
4227          {
4228             /*
4229              * Spawning the child failed, assume it's because
4230              * there are too many children running already.
4231              * XXX: If you assume ...
4232              */
4233             log_error(LOG_LEVEL_ERROR,
4234                "Unable to take any additional connections: %E. Active threads: %d",
4235                active_threads);
4236             write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4237                strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4238             close_socket(csp->cfd);
4239             csp->flags &= ~CSP_FLAG_ACTIVE;
4240          }
4241       }
4242       else
4243       {
4244          serve(csp);
4245       }
4246    }
4247
4248    /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4249
4250    /* Clean up.  Aim: free all memory (no leaks) */
4251 #ifdef FEATURE_GRACEFUL_TERMINATION
4252
4253    log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4254
4255    unload_current_config_file();
4256    unload_current_actions_file();
4257    unload_current_re_filterfile();
4258 #ifdef FEATURE_TRUST
4259    unload_current_trust_file();
4260 #endif
4261
4262    if (config->multi_threaded)
4263    {
4264       int i = 60;
4265       do
4266       {
4267          sleep(1);
4268          sweep();
4269       } while ((clients->next != NULL) && (--i > 0));
4270
4271       if (i <= 0)
4272       {
4273          log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4274       }
4275    }
4276    sweep();
4277    sweep();
4278
4279 #if defined(unix)
4280    freez(basedir);
4281 #endif
4282
4283 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4284    /* Cleanup - remove taskbar icon etc. */
4285    TermLogWindow();
4286 #endif
4287
4288    exit(0);
4289 #endif /* FEATURE_GRACEFUL_TERMINATION */
4290
4291 }
4292
4293
4294 /*
4295   Local Variables:
4296   tab-width: 3
4297   end:
4298 */