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