#!/usr/local/bin/perl
#
# Use try to connect to a POP-3 server, and
# wait for the right output.
#
# For use with "mon".
#
# Arguments are "-p port -t timeout -h host"
#
# Adapted from "http.monitor" by
# Jim Trocki, trockij@transmeta.com
#
# http.monitor written by
#
# Jon Meek
# American Cyanamid Company
# Princeton, NJ
#
# $Id: pop3.plugin,v 1.2.2.1 2002/07/22 15:21:49 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)

use Getopt::Std;
use English;
use CS::Functions;

getopts ("p:t:h:");
$Port = $opt_p || 110;
$TIMEOUT = $opt_t || 5;
$Host = $opt_h || "localhost";

exit &pop3GET($Host, $Port);

sub pop3GET {
  my ($Server, $Port) = @_;
  my $ServerOK = 1;

  eval {
    local $SIG{ALRM} = sub { die "Timeout Alarm" };
    alarm $TIMEOUT;

    $sock = opensocket($Server, $Port); # Open a connection to the server
    if (!$sock) { # Failure to open the socket
      return 1;
    }

    $in = <$sock>;
    if ($in !~ /^\+OK/) {
      alarm 0;
      return 1;
    }

    print $sock "quit\r\n";

    $in = <$sock>;
    if ($in !~ /^\+OK/) {
      alarm 0;
      return 1;
    }

    $ServerOK = 0;

    close($sock);
    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