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