#!/usr/local/bin/perl
#
# Use try to connect to a http server.
# For use with "mon".
#
# Arguments are "-p port host [host...]"
#
# Jon Meek
# American Cyanamid Company
# Princeton, NJ
#
# $Id: https.plugin,v 1.1.1.1.2.1 2002/07/22 15:21:48 paul-cs Exp $
#
#    Copyright (C) 1998, Jim Trocki
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Modified by Paul van Tilburg. Speedup needed for Checkservice...
# (removed multiple host support and changed default values)
#
# Modified for https by Justin Penney <justin@solve.net>

use Getopt::Std;
use English;
require "opensocket.pl";

getopts ("p:t:u:h:");
$Port = $opt_p || 443;
$TIMEOUT = $opt_t || 5;
$Host = $opt_h || "localhost";
$URL = $opt_u || "/";

exit &httpsGET($Host, $Port);

sub httpsGET {
  use Socket;

  my ($Server, $Port) = @_;
  my ($ServerOK, $TheContent) = (1);

  eval {
    local $SIG{ALRM} = sub { die "Timeout Alarm" };
    alarm $TIMEOUT;
	
    $result = &OpenSocket($Server, $Port); # Open a connection to the server
    if (!$result) { # Failure to open the socket
      return 1;
    }

    print S "GET $URL HTTP/1.1\r\n";
    print S "Host: $Server\r\n";
    print S "User-Agent: Checkservice/http.plugin\r\n\r\n";

    while ($in = <S>) {
      $TheContent .= $in;  # Store data for later processing
    }

    # HTTP/1.1 200 OK
    if ($TheContent =~ /^HTTP\/([\d\.]+)\s+200\b/) { $ServerOK = 0; } 
    else { print STDERR "Could not find HTTP/1.? OK\n"; $ServerOK = 1; }

    close(S);
    alarm 0; # Cancel the alarm
  };

  if ($EVAL_ERROR and ($EVAL_ERROR =~ /Timeout Alarm/)) {
    return 2;
  }
    
  return $ServerOK;
}


syntax highlighted by Code2HTML, v. 0.9.1