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