use strict;
use warnings FATAL => 'all';

use Apache::Test;
use Apache::TestRequest;
use Apache::TestUtil;
use MIME::Base64;
use Data::Dumper;
use HTTP::Response;
use Socket;

plan tests => 1, need_min_apache_version('2.4.42');

my $sock = Apache::TestRequest::vhost_socket("core");
if (!$sock) {
    print "# failed to connect\n";
    ok(0);
    next;
}

my $req = sprintf "GET /CVE-2020-1927/%%0D%%0Ahttp://127.0.0.1/ HTTP/1.1\r\nHost: merge-disabled\r\nConnection: close\r\n\r\n";
print "# SENDING to " . peer($sock) . "\n# $req\n";
$sock->print("$req");
$sock->flush();
sleep(0.1);
$req = escape($req);
print "# SENDING to " . peer($sock) . "\n# $req\n";

my $response_data = "";
my $buf;
while ($sock->read($buf, 10000) > 0) {
    $response_data .= $buf;
}
my $response = HTTP::Response->parse($response_data);
if (! defined $response) {
    die "HTTP::Response->parse failed";
}
ok t_cmp($response->code, 404,  "regex didn't match and redirect");

sub escape
{
    my $in = shift;
    $in =~ s{\\}{\\\\}g;
    $in =~ s{\r}{\\r}g;
    $in =~ s{\n}{\\n}g;
    $in =~ s{\t}{\\t}g;
    $in =~ s{([\x00-\x1f])}{sprintf("\\x%02x", ord($1))}ge;
    return $in;
}

sub peer
{
   my $sock = shift;
   my $hersockaddr    = getpeername($sock);
   return "<disconnected>" if !$hersockaddr;
   my ($port, $iaddr) = sockaddr_in($hersockaddr);
   my $herhostname    = gethostbyaddr($iaddr, AF_INET);
   my $herstraddr     = inet_ntoa($iaddr);
   return "$herstraddr:$port";
}
