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