#!perl
use Cassandane::Tiny;

sub test_http1_upgrade_header
    # :NoCheckSyslog -- a successful h2c upgrade logs "...NO_ERROR" on
    # teardown, which the syslog checker misflags on the "ERROR" substring.
    :NoCheckSyslog :needs_dependency_nghttp2
    ($self)
{
    my $service = $self->{instance}->get_service('http');

    # No upgrade attempted: 404, websocket advertised.
    my $s = http1_connect($self);

    http1_send($s,
        "GET / HTTP/1.1\r\n",
        "Host: " . $service->host . ":" . $service->port . "\r\n",
        "\r\n");

    my $res = http1_read_response($s);
    xlog $self, "response (no upgrade attempted): $res->{status}";
    $self->assert_num_equals(404, $res->{status});
    $self->assert_matches(qr/\bwebsocket\b/i, $res->{headers}{upgrade} // '');
    close($s);

    # h2c attempted but declined (no HTTP2-Settings): 404, no
    # Upgrade header at all.
    $s = http1_connect($self);

    http1_send($s,
        "GET / HTTP/1.1\r\n",
        "Host: " . $service->host . ":" . $service->port . "\r\n",
        "Connection: Upgrade\r\n",
        "Upgrade: h2c\r\n",
        "\r\n");

    $res = http1_read_response($s);
    xlog $self, "response (h2c declined): $res->{status}";
    $self->assert_num_equals(404, $res->{status});
    $self->assert(!exists $res->{headers}{upgrade});
    close($s);

    # h2c attempted and succeeds: 101 advertising h2c, not websocket.
    $s = http1_connect($self);

    http1_send($s,
        "GET / HTTP/1.1\r\n",
        "Host: " . $service->host . ":" . $service->port . "\r\n",
        "Connection: Upgrade, HTTP2-Settings\r\n",
        "Upgrade: h2c\r\n",
        "HTTP2-Settings: AAMAAABkAAQAAQAAAAIAAAAA\r\n",
        "\r\n");

    $res = http1_read_response($s);
    xlog $self, "response (h2c upgrade attempted): $res->{status}";
    $self->assert_num_equals(101, $res->{status});
    $self->assert_matches(qr/\bh2c\b/i, $res->{headers}{upgrade} // '');
    $self->assert($res->{headers}{upgrade} !~ /\bwebsocket\b/i,
                  "websocket must not be advertised while another "
                . "upgrade (h2c) is being attempted");

    # Drain the SETTINGS frame header sent right after the 101.
    my $frame_header = http1_read_bytes($s, 9);
    my $frame_type = unpack('C', substr($frame_header, 3, 1));
    $self->assert_num_equals(0x4, $frame_type);

    close($s);
}
