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