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