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