#!/usr/bin/perl

# andyw 20070202 - under the gpl, etc
# usage - checkthing somesites
# andyw 20070502 - added time to live calculations
# andyw 20070820 - copes with connecting and getting esmtp certs

use POSIX qw/mktime/;
 
my $certtemp = '/tmp/certout';
my ($validfrom, $validto,$extrargs);

for my $host (@ARGV) {
	print "$host: ";
	if ($host =~/smtp/) {
		$host.=':25';
		$extrargs = '-starttls smtp';
	} else { $host .= ':443'; $extraargs = ''; }
	#if (! open(A,"/bin/echo 'GET / HTTP/1.0' | /usr/bin/socksify /usr/bin/openssl s_client -connect $host:443 2>/dev/null|")) {
	#if (! open(A,"/bin/echo 'GET / HTTP/1.0' | /usr/bin/socksify /usr/bin/openssl s_client $extrargs -connect $host 2>/dev/null|")) {
	if (! open(A,"/bin/echo 'GET / HTTP/1.0' | /usr/bin/openssl s_client $extrargs -connect $host 2>/dev/null|")) {
		# something went wrong
		print "Failed to get cert for: $!\n";
		next;
	}

	$c=0;

	open(OUT,">$certtemp");

	while (<A>) {
		#print "A: $_\n";
		$c=1 if /BEGIN CERTIFICATE/;
		print OUT $_ if $c == 1;
		$c++ if /END CERTIFICATE/;
		
	}

	if ($c == 0) {
		print "failed to get a cert!\n";
		next;
	}

	close(OUT);
	close(A);

	open(X,"/usr/bin/openssl x509 -dates -in $certtemp 2>/dev/null| ");
	while (<X>) {
		if (/notBefore=(.*)/) {$validfrom = $1; }
		if (/notAfter=(.*)/) { $validto = $1; }
	}

	print "from $validfrom to $validto (";
	my $diff = parsedate($validto) - time;
	my $days = int($diff / 60/60/24);
	print $diff > 0 ? ($days < 30 ?  'only ' : '') . $days . ' days' : 'EXPIRED';
	print ")\n";

	close(X);
	unlink $certttemp;
	
}


sub parsedate {
	my $dstr = shift;
	my %months = qw/Jan 0 Feb 1 Mar 2 Apr 3 May 4 Jun 5 Jul 6 Aug 7 Sep 8 Oct 9 Nov 10 Dec 11/;
	my @tb;
	
	# Jun 27 07:40:51 2005 GMT to

	@tb = localtime;

	$dstr =~ m/(\w{3}) ([\d ]{2}) (\d{2})\:(\d{2})\:(\d{2}) (\d{4}) \w+/;
	@tb[0, 1, 2, 3, 4, 5, 6, 7] = ($5, $4, $3, $2, $months{$1}, $6 - 1900, undef, undef);

	return mktime(@tb);
}
