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