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