+sub send_response {
+ my ($self, $req, $url_rec, $con) = @_;
+
+ # create response
+ my ($code, $msg, $headers);
+ my $send_content = ($req->method eq "GET");
+ if (exists $url_rec->{'auth_method'}) {
+ ($send_content, $code, $msg, $headers) =
+ $self->handle_auth($req, $url_rec);
+ } elsif (!$self->verify_request_headers ($req, $url_rec)) {
+ ($send_content, $code, $msg, $headers) =
+ ('', 400, 'Mismatch on expected headers', {});
+ } else {
+ ($code, $msg) = @{$url_rec}{'code', 'msg'};
+ $headers = $url_rec->{headers};
+ }
+ my $resp = HTTP::Response->new ($code, $msg);
+ print STDERR "HTTP::Response: \n", $resp->as_string if $log;
+
+ while (my ($name, $value) = each %{$headers}) {
+ # print STDERR "setting header: $name = $value\n";
+ $resp->header($name => $value);
+ }
+ print STDERR "HTTP::Response with headers: \n", $resp->as_string if $log;
+
+ if ($send_content) {
+ my $content = $url_rec->{content};
+ if (exists($url_rec->{headers}{"Content-Length"})) {
+ # Content-Length and length($content) don't match
+ # manually prepare the HTTP response
+ $con->send_basic_header($url_rec->{code}, $resp->message, $resp->protocol);
+ print $con $resp->headers_as_string($CRLF);
+ print $con $CRLF;
+ print $con $content;
+ next;
+ }
+ if ($req->header("Range") && !$url_rec->{'force_code'}) {
+ $req->header("Range") =~ m/bytes=(\d*)-(\d*)/;
+ my $content_len = length($content);
+ my $start = $1 ? $1 : 0;
+ my $end = $2 ? $2 : ($content_len - 1);
+ my $len = $2 ? ($2 - $start) : ($content_len - $start);
+ if ($len > 0) {
+ $resp->header("Accept-Ranges" => "bytes");
+ $resp->header("Content-Length" => $len);
+ $resp->header("Content-Range"
+ => "bytes $start-$end/$content_len");
+ $resp->header("Keep-Alive" => "timeout=15, max=100");
+ $resp->header("Connection" => "Keep-Alive");
+ $con->send_basic_header(206,
+ "Partial Content", $resp->protocol);
+ print $con $resp->headers_as_string($CRLF);
+ print $con $CRLF;
+ print $con substr($content, $start, $len);
+ } else {
+ $con->send_basic_header(416, "Range Not Satisfiable",
+ $resp->protocol);
+ $resp->header("Keep-Alive" => "timeout=15, max=100");
+ $resp->header("Connection" => "Keep-Alive");
+ print $con $CRLF;
+ }
+ next;
+ }
+ # fill in content
+ $content = $self->_substitute_port($content) if defined $content;
+ $resp->content($content);
+ print STDERR "HTTP::Response with content: \n", $resp->as_string if $log;
+ }