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