package EPrints::KlarasConnect::PanelClient;

# The only outbound HTTP the plugin makes: JSON POSTs to the control panel.
#
# - https only (http only in a development install), certificate checked
# - the panel URL comes from code, never from a request (no SSRF)
# - short timeouts and a response size cap, so a slow or hostile network
#   can never tie up an Apache child or the indexer
# - LWP 6 or later when it can speak https, otherwise the curl binary
#   (secrets passed in a 0600 temp file, never on the command line).
#   LWP 5 (CentOS 6, Debian squeeze: the Perl 5.10 systems) also loads
#   LWP::Protocol::https, but ignores ssl_opts and does not check the
#   certificate, so it is never used.

use strict;
use warnings;

use File::Temp ();
use EPrints::KlarasConnect;
use EPrints::KlarasConnect::Util qw( json_encode json_decode );

use constant CONNECT_TIMEOUT => 5;
use constant TOTAL_TIMEOUT   => 15;
use constant MAX_RESPONSE    => 256 * 1024;

# Which transport this host can use: 'lwp', 'curl' or undef. Both check
# the panel's certificate.
sub transport
{
	return 'lwp' if lwp_verifies();
	return 'curl' if defined _curl_path();
	return undef;
}

# LWP that checks certificates: libwww-perl 6+ with its https protocol.
sub lwp_verifies
{
	return eval {
		require LWP::UserAgent;
		require LWP::Protocol::https;
		_major( LWP::UserAgent->VERSION ) >= 6 && _major( LWP::Protocol::https->VERSION ) >= 6;
	} ? 1 : 0;
}

# LWP::Protocol::https loads but is too old to check certificates.
sub lwp_too_old
{
	return 0 if lwp_verifies();
	return eval { require LWP::UserAgent; require LWP::Protocol::https; 1 } ? 1 : 0;
}

sub _major
{
	my( $v ) = @_;
	return defined $v && $v =~ /\A([0-9]+)/ ? $1 + 0 : 0;
}

sub _curl_path
{
	foreach my $p ( qw( /usr/bin/curl /usr/local/bin/curl /bin/curl ) )
	{
		return $p if -x $p;
	}
	return undef;
}

# post( $repo, '/api/v1/instances/heartbeat', $payload, api_key => ... )
# Returns { ok => 0|1, status => n, data => {...}|undef, error => {code,message}|undef }.
sub post
{
	my( $repo, $path, $payload, %opts ) = @_;

	my $base = EPrints::KlarasConnect::panel_url( $repo );
	if( $base !~ m{\Ahttps://} && !EPrints::KlarasConnect::is_development( $repo ) )
	{
		return _fail( 0, 'insecure_panel', 'Alamat panel harus https.' );
	}
	die "klaras_connect: bad panel path\n" if $path !~ m{\A/api/v1/[a-z0-9/_-]+\z};

	my $url = $base . $path;
	my $body = json_encode( $payload );
	my @headers = (
		'Content-Type' => 'application/json',
		'Accept'       => 'application/json',
		'User-Agent'   => EPrints::KlarasConnect::USER_AGENT,
		# Uncompressed, so the size cap is the size of what is read.
		'Accept-Encoding' => 'identity',
	);
	push @headers, ( 'Authorization' => 'Bearer ' . $opts{api_key} ) if defined $opts{api_key};

	my $t = transport();
	my( $status, $content, $neterr );
	if( !defined $t )
	{
		return _fail( 0, 'no_https_client',
			'Server ini belum bisa membuat koneksi HTTPS keluar. Pasang paket LWP::Protocol::https (liblwp-protocol-https-perl) atau curl.' );
	}
	elsif( $t eq 'lwp' )
	{
		( $status, $content, $neterr ) = _lwp( $url, $body, \@headers );
	}
	else
	{
		( $status, $content, $neterr ) = _curl( $url, $body, \@headers );
	}

	if( !$status )
	{
		return _fail( 0, 'network_error', 'Tidak bisa menghubungi panel Klaras: ' . ( $neterr || 'koneksi gagal' ) . '.' );
	}

	my $json = json_decode( $content );
	if( ref $json ne 'HASH' )
	{
		return _fail( $status, 'bad_response', "Panel Klaras membalas dengan format yang tidak dikenali (HTTP $status)." );
	}

	if( $status >= 200 && $status < 300 )
	{
		return { ok => 1, status => $status, data => ref $json->{data} eq 'HASH' ? $json->{data} : {}, error => undef };
	}

	my $err = ref $json->{error} eq 'HASH' ? $json->{error} : {};
	return _fail( $status,
		defined $err->{code} && !ref $err->{code} ? $err->{code} : 'http_' . $status,
		defined $err->{message} && !ref $err->{message} ? $err->{message} : "Panel Klaras menolak permintaan (HTTP $status)." );
}

sub _lwp
{
	my( $url, $body, $headers ) = @_;

	my $ua = LWP::UserAgent->new(
		timeout      => TOTAL_TIMEOUT,
		max_size     => MAX_RESPONSE,
		max_redirect => 0,
		protocols_allowed => [ 'https', 'http' ],
		# SSL_verify_mode 1 = SSL_VERIFY_PEER, explicitly: never rely on
		# the default. The CA store is Mozilla::CA or the system's.
		ssl_opts     => { verify_hostname => 1, SSL_verify_mode => 1 },
		agent        => EPrints::KlarasConnect::USER_AGENT,
	);
	$ua->env_proxy;

	my $res = eval { $ua->post( $url, @$headers, Content => $body ) };
	return ( 0, undef, 'permintaan gagal' ) if !$res;

	# LWP reports its own failures (DNS, TLS, timeout) as 500 with this header.
	if( ( $res->header( 'Client-Warning' ) || '' ) eq 'Internal response' )
	{
		my $msg = $res->message || 'koneksi gagal';
		$msg =~ s/[\r\n]+/ /g;
		return ( 0, undef, substr( $msg, 0, 200 ) );
	}
	return ( 0, undef, 'balasan panel terlalu besar' ) if $res->header( 'Client-Aborted' );

	# Raw bytes as received (identity encoding asked for above): never
	# inflated past the cap.
	my $content = $res->content;
	return ( 0, undef, 'balasan panel terlalu besar' ) if defined $content && length( $content ) > MAX_RESPONSE;
	return ( $res->code, $content, undef );
}

sub _curl
{
	my( $url, $body, $headers ) = @_;

	my $curl = _curl_path() or return ( 0, undef, 'curl tidak ditemukan' );

	my $hfile = File::Temp->new( UNLINK => 1 );
	my $bfile = File::Temp->new( UNLINK => 1 );
	chmod 0600, $hfile->filename, $bfile->filename;

	# A curl config file (-K) rather than "-H @file", which needs curl 7.55;
	# CentOS 7 ships 7.29.
	my @h = @$headers;
	while( my( $k, $v ) = splice( @h, 0, 2 ) )
	{
		my $line = "$k: $v";
		$line =~ s/[\r\n]//g;
		$line =~ s/(["\\])/\\$1/g;
		print {$hfile} qq{header = "$line"\n};
	}
	close $hfile;
	binmode $bfile;
	print {$bfile} $body;
	close $bfile;

	my @cmd = (
		# -q must come first: ignore ~/.curlrc, where a line such as
		# "insecure" would turn certificate checks off.
		$curl, '-q', '--silent', '--show-error',
		'--proto', '=https,http', '--max-redirs', '0',
		'--connect-timeout', CONNECT_TIMEOUT, '--max-time', TOTAL_TIMEOUT,
		'--max-filesize', MAX_RESPONSE,
		'-K', $hfile->filename,
		'--data-binary', '@' . $bfile->filename,
		'--write-out', "\n%{http_code}",
		'--', $url,
	);

	my $pid = open( my $out, '-|' );
	return ( 0, undef, 'tidak bisa menjalankan curl' ) if !defined $pid;
	if( !$pid )
	{
		open( STDERR, '>', '/dev/null' );
		{ no warnings 'exec'; exec { $cmd[0] } @cmd; }
		# Not exit: under mod_perl that ends the request, not this forked
		# copy of the Apache child.
		require POSIX;
		POSIX::_exit( 127 );
	}
	binmode $out;
	# --max-filesize does not stop a chunked response: cap what is read.
	my $all = '';
	my $cap = MAX_RESPONSE + 8;
	while( length( $all ) <= $cap )
	{
		my $n = sysread( $out, $all, 65536, length $all );
		last if !$n;
	}
	if( length( $all ) > $cap )
	{
		kill( 'TERM', $pid );
		close $out;
		return ( 0, undef, 'balasan panel terlalu besar' );
	}
	close $out;
	return ( 0, undef, 'curl gagal (' . ( $? >> 8 ) . ')' ) if $? != 0;

	my( $content, $code ) = $all =~ /\A(.*)\n([0-9]{3})\z/s or return ( 0, undef, 'balasan curl tidak dikenali' );
	return ( $code + 0, $content, undef );
}

sub _fail
{
	my( $status, $code, $message ) = @_;
	return { ok => 0, status => $status, data => undef, error => { code => $code, message => $message } };
}

1;
