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