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