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