use strict;
use warnings;
use Net::SIP;
use IO::Socket::IP;
use IO::Socket::SSL;
use Getopt::Long qw(:config posix_default bundling);

my ($repeat,$cert_and_key,$cafile);
GetOptions(
    'd|debug'  => sub { 
	$IO::Socket::SSL::DEBUG = 5;
    },
    'h|help'   => sub { usage() },
    'cert:s'   => \$cert_and_key,
    'cafile:s' => \$cafile,
    'repeat:i' => \$repeat,
) or usage();

my ($dst) = @ARGV;
$dst or usage("no target ip:port given");
$cert_and_key or usage("no cert given");
$repeat ||= 2;

my $ctx = IO::Socket::SSL::SSL_Context->new(
    SSL_cert_file => $cert_and_key,
    SSL_key_file  => $cert_and_key,
    $cafile ? (SSL_ca_file => $cafile): (SSL_verify_mode => 0),
    SSL_version => 'TLSv1_2',
    SSL_session_cache_size => 10,
) or die "creating SSL context failed: $SSL_ERROR";

for (1..$repeat) {
    my $cl = IO::Socket::IP->new($dst) or die "connection to $dst failed: $!";
    IO::Socket::SSL->start_SSL($cl,
	SSL_verifycn_scheme => 'none',
	SSL_reuse_ctx => $ctx,
    ) or die "connection #$_ failed: $SSL_ERROR";
    printf STDERR "connection %d success, resume=%s\n", $_,
	Net::SSLeay::session_reused($cl->_get_ssl_object) ? "yes":"no";
    close($cl);
}


sub usage {
    print STDERR "@_\n\n" if @_;
    print STDERR <<USAGE;
Usage: $0 [options] ip:port
Multple attempts to connect to same ip:port while reusing TLS sessions
Options
    -d|--debug      SIP and TLS debugging
    -h|--help       this usage
    --cert F.pem    load client cert, chain and key from F.pem
    --cafile C.pem  load CA certificates from C.pem
    --repeat N      do N (default 2) calls with same SSL context to use
                    session resumption if possible
USAGE
    exit(1);
};

