#!perl
use Cassandane::Tiny;

my $host_line;

sub valid_options($self, $s, $desc) {
    my $res = http1_read_response($s);
    $self->assert_num_equals(200, $res->{status}, "status 200 for $desc");
    $self->assert(defined $res->{headers}{allow}, "Allow header for $desc");
}

sub unknown_method($self, $s, $desc) {
    my $res = http1_read_response($s);
    $self->assert_num_equals(501, $res->{status}, "status 501 for $desc");
    $self->assert(!defined $res->{headers}{allow}, "no Allow header for $desc");
}

sub bad_request($self, $s, $desc) {
    my $res = http1_read_response($s);
    $self->assert_num_equals(400, $res->{status}, "status 400 for $desc");
    $self->assert(!defined $res->{headers}{allow}, "no Allow header for $desc");
}

# Wait for EOF rather than probing with another request: a write to a socket
# that's closed at the server end gets an RST, and if that lands before our
# read, the read fails with ECONNRESET instead of returning EOF.
sub server_closed_connection($self, $s, $desc) {
    $self->assert(scalar IO::Select->new($s)->can_read(10),
                  "socket readable for $desc");

    my $n = $s->my_read(my $buf, 4096);
    $self->assert_not_null($n, "read failed for $desc: $!");
    $self->assert_num_equals(0, $n, "server closed the connection for $desc");
}

sub test_unknown_method
    ($self)
{
    my $service = $self->{instance}->get_service('http');
    $host_line = "Host: " . $service->host . ":" . $service->port . "\r\n";

    my $s = http1_connect($self);
    print $s "OPTIONS * HTTP/1.1\r\n"
           . $host_line
           . "\r\n";
    valid_options($self, $s, "plain OPTIONS");

    print $s "POST * HTTP/1.1\r\n"
           . $host_line
           . "X-HTTP-Method-Override: OPTIONS\r\n"
           . "\r\n";
    valid_options($self, $s, "Method Override OPTIONS");

    print $s "POST * HTTP/1.1\r\n"
           . $host_line
           . "X-HTTP-Method-Override: BREW\r\n"
           . "\r\n";
    unknown_method($self, $s, "Method Override BREW");
    server_closed_connection($self, $s, "Method Override BREW");

    $s = http1_connect($self);
    print $s "BREW * HTTP/1.1\r\n"
           . $host_line
           . "\r\n";
    unknown_method($self, $s, "plain BREW");
    server_closed_connection($self, $s, "plain BREW");

    $s = http1_connect($self);
    print $s "POST * HTTP/1.1\r\n"
           . $host_line
           . "X-HTTP-Method-Override: OPTIONS\r\n"
           . "X-HTTP-Method-Override: OPTIONS\r\n"
           . "\r\n";
    bad_request($self, $s, "repeated Method Override");
    server_closed_connection($self, $s, "repeated Method Override");

    $s = http1_connect($self);
    print $s "OPTIONS * HTTP/1.1\r\n"
           . $host_line
           . $host_line
           . "\r\n";
    bad_request($self, $s, "repeated Host header");

    $s = http1_connect($self);
    print $s "OPTIONS * HTTP/1.1\r\n"
           . "\r\n";
    bad_request($self, $s, "missing Host header");
}
