#! /usr/bin/perl
# anders@aftenposten.no
# 2008-04-05
# Check if a web servers Server HTTP string is as expected

use Net::Telnet ();
use Getopt::Std;

getopts('H:p:v:S:f:');
$httpok = "HTTP/1.(0|1) 200 OK";
$secs = 30;

if (!$opt_p) { $opt_p = 80; }
if (!$opt_v) { $opt_v = "localhost"; }
if (!$opt_f) { $opt_f = "/"; }
if ($opt_h) {
	$mode = "HEAD";
} else {
	$mode = "GET";
}

if ((!$opt_H) || (!$opt_S)) {
	print "Error: hostname or server string missing. Usage:\n\n";
	print "check_http_sstring -H <hostname> -S <server string> [ -p <port> ]\n";
	print "[ -v <virtual host (hostname)> ] [ -f <file to get> ]\n\n";
	print "Defaults: virtual host = localhost, port = 80, file to get = /.\n";
	print "This plugin checks for HTTP OK return code and checks if the Server: string is\n";
	print "as expected.\n";
	exit(1);
}

sub nil { }

my $nc = new Net::Telnet (Telnetmode => 0, Timeout => $secs, Errmode =>
\&nil);
$nc->open(Host => $opt_H, Port => $opt_p);
$nc->print("$mode $opt_f HTTP/1.0");
$nc->print("Host: $opt_v");
$nc->print("Connection: close");
$nc->print("");
@lines = $nc->getlines(Timeout => $secs);
$nc->close;

$rcode = (grep(/^HTTP\//, @lines))[0];
$sstring = (grep(/^Server: /, @lines))[0];
chomp($rcode);
chomp($sstring);

if ($rcode =~ /$httpok/ && $sstring =~ /$opt_S/) {
	print "OK $rcode, $sstring\n";
	exit(0);
} elsif ($rcode !~ /$httpok/) {
	print "FAIL bad return code $rcode, expected ~ $httpok.\n";
	exit(2);
} else {
	print "FAIL bad server string $sstring, expected $opt_S.\n";
	exit(2);
}

#print "rcode=$rcode sstring=$sstring\n";
