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