#!/usr/bin/env bash
set -u  # force better programming and ability to use check for not set

if [ "${1:-}" = "-x" ]; then set -xv; shift; fi

# this is cheap option processing. Must be in this order when checking.
if [ "${1:-}" = "-a" ]; then ALARM=1; shift; else ALARM=0; fi
if [ "${1:-}" = "-c" ]; then CROND=1; shift; else CROND=0; fi
if [ "${1:-}" = "-i" ]; then INTER=1; shift; else INTER=0; fi
if [ "${1:-}" = "-q" ]; then QUIET=1; shift; else QUIET=0; fi

set +u
. /usr/local/etc/setups.sh
FLAVOR=`ups flavor -3`
setup enstore
set -u

# Things checked:
# . Correct configuration files
# . Correct authorization files
# . Check ups and product support
# . Verify that both /fnal and /local exist
# . Check that ngop is installed and running
# . Check enstore scripts in /etc/rc.d/init.d
# . Check that rc.local contains boot_cleanup
# . Check that rc.local contains ipmi_startup
## . Check that eth1 is working (if present)
## . Check that mounted disks are less than 90% full
# . Check that ntp is working, fix if not
# . Check that root crontab includes netscan, reset of watchdog,
# .  (NOTE: /etc/cron.d is an alternate location for crontabs)
# . Check that enstore and root .forward files contain enstore-admin@fnal.gov
# . Check whether hyperthreading is enabled on dual Xeon platforms
# . Check number and sizes of pnfs databases on srv1 nodes
# . Check for running pnfs manager on srv1 nodes
# . Check largest of today's log files on srv2 nodes
# . Check grid user certs for expiration on srv3 nodes
# . Check the date and time on the connected Sun system
# . Check that lock status of library managers is consistent with config
# . Check for reasonable number of processes running on the node
# . Check for correct number of pnfs daemons running on servers
# . Generate informational alarm if we detect server has just rebooted
# . Verify hosts, k5login, and /etc/sysconfig/network files contain this host's fqdn
# . Verify that farmlets files contain this host's name
# . Check that web servers are running on right nodes and not elsewhere
# . Check cgi scripts on web server nodes
# . Verify ownership and permissions of enstore mover status directory
# . Verify ownership and permissions of enstore keytab directory and file
# . Check the /etc/krb5.keytab and /fnal/ups/kt/enstorekt files for legal values
# . Look for "lost" files in mounted local file systems
# . Look for local files hidden behind nfs mount points
# . Check that ipmisrv is running and has NO_DOG option
# . Check that watchdog timer action is to do nothing
# . Check for open LISTEN sockets
# . Check that the farmlets directory matches the base farmlet

# Known vunerabilities:
# . I know I don't check everything!
# . Only check for LISTEN, ignoring TCP and UDP for now.
#        TCP could be done, but UDP seems very hard (sh, mt... open lots of sockets!).
# . Require connection to live across a ps, so I can get the process name for later checks
# . Depend on installed version of os (grep, lsof...)
#        Should download a static version each time.
# . Swapped out versions of jobs with open connections - allowed, not checked.
#        Should look into the proc file system to get cmdline and check that.
#        Could also buy more memory to make sure nothing is ever swapped out.
# . Allow all tasks run from enstore/bin or enstore/src
#        Should check for individual applications
# . RPM - could be modified
#        Too many exceptions in rpm -Va to be useful...

# List of binaries/scripts used in checking.
# In principle, these should be loaded onto the machine each time to prevent hacker tampering
DF="/bin/df"
LS="/bin/ls"
PS="/bin/ps"
RM="/bin/rm"
AWK="/bin/awk"
SED="/bin/sed"
RPM="/bin/rpm"
ECHO="/bin/echo"
KILL="/bin/kill"
DATE="/bin/date"
GREP="/bin/grep"
SORT="/bin/sort"
CHMOD="/bin/chmod"
CHOWN="/bin/chown"
EGREP="/bin/egrep"
MKDIR="/bin/mkdir"
SLEEP="/bin/sleep"
BASENAME="/bin/basename"
HOSTNAME="/bin/hostname"
DU="/usr/bin/du"
TR="/usr/bin/tr"
WC="/usr/bin/wc"
M4="/usr/bin/m4"
CMP="/usr/bin/cmp"
if [ -x /usr/bin/cut ]; then
  CUT="/usr/bin/cut"
elif [ -x /bin/cut ]; then
  CUT="/bin/cut"
else
  $ECHO "Can not find cut"
  exit 1
fi
EXPR="/usr/bin/expr"
TAIL="/usr/bin/tail"
UNIQ="/usr/bin/uniq"
DIRNAME="/usr/bin/dirname"
CRONTAB="/usr/bin/crontab"
OPENSSL="/usr/bin/openssl"
if [ -x /usr/local/bin/lsof ]
then
    LSOF="/usr/local/bin/lsof"
else
    LSOF="/usr/sbin/lsof"
fi
SERVICE="/sbin/service"
NTPDATE="/usr/sbin/ntpdate"
IFUP="/etc/sysconfig/network-scripts/ifup"
IFDOWN="/etc/sysconfig/network-scripts/ifdown"

OCTAL="printf 0%o"

FARMLETS="$ENSTORE_DIR/sbin/farmlets"
KEYTAB_CHECK="$ENSTORE_DIR/sbin/keytab_check"

LOG=/tmp/netscan.log
ACTIVE=/root/CRON/netscanACTIVE

node=`$HOSTNAME -s`
fqdn=`$HOSTNAME -f`
gang=`$ENSTORE_DIR/sbin/gang`

umask 022

# convert uptime to units of our scheduling interval (15 minutes)
let uptime=`$CUT -d. -f1 /proc/uptime`/900

# did we just reboot?
if (( uptime > 0 ))
then
  REBOOT=0
else
  REBOOT=1
fi

# treat srv?n nodes like the ones they will replace
node=`$ECHO $node | $SED -e 's/\(ensrv[0-9]\)n/\1/'`
fqdn=`$ECHO $fqdn | $SED -e 's/\(ensrv[0-9]\)n/\1/'`

# are we an enstore server? (accept srv0-9 or pnfs[12])
if $ECHO $node | $EGREP '^(d0|stk|cdf)ensrv[0-9]$' >/dev/null
then
  SERVER=1
  nodetype=srv
elif $ECHO $node | $EGREP '^(cms|eag)pnfs[12]$' >/dev/null
then
  SERVER=1
  nodetype=srv
else
  SERVER=0
fi

# are we an enstore mover? (accept mvr1a-999a)
if $ECHO $node | $EGREP '^(d0|stk|cdf)enmvr[1-9][0-9]?[0-9]?a$' >/dev/null
then
  MOVER=1
  nodetype=mvr
else
  MOVER=0
fi

# are we a dcache node? (accept fndca2a-3a, stkendca2a-3a,6a-29a)
# admin nodes (head, door, monitor)
if $ECHO $node | $EGREP '^(fn|stken)dca[23]a$' >/dev/null
then
  DCACHE=1
  nodetype=dca
# pool nodes
elif $ECHO $node | $EGREP '^stkendca([6-9]|[12][0-9])a$' >/dev/null
then
  DCACHE=1
  nodetype=dca
else
  DCACHE=0
fi

# force alarms off if we are not a production node
[ -e /PRODUCTION ] || ALARM=0

# when invoked by cron, once a day, or after reboot,
# override quiet mode and log verbose information
(( ! (uptime % 97) && CROND )) && QUIET=0

# function to log messages, optionally print the ps state

logit() { $ECHO `$DATE` "$1" >>$LOG 2>&1
	  if [ "${2:-}"x = psx ]; then
	     $ECHO "${PSfirst:-}" >>$LOG 2>&1
	  fi
	  $ECHO "$1"
	}

# function to conditionally generate an enstore alarm

alarm() { if (( ALARM )); then
	     enstore alarm --raise --severity "${2:-A}" --root-error "$1"
	  fi
	}

# this script requires bash 2.05, usually /bin/bash (not /usr/local/bin/bash)
if [ $BASH = "/usr/local/bin/bash" -o $BASH_VERSION \< "2.05" ]; then
   msg="Insufficient version of bash: $BASH $BASH_VERSION"
   logit "$msg"
   alarm "$msg" W
fi

# function to parse file mode from terse output of stat(1)

getfilemode() { set `stat -t $1 2>/dev/null`
		if (( $# == 15 )); then
		   # 0x4000 => directory
		   # 0x8000 => regular file
		   # 0xa000 => symbolic link
		   # 0xc000 => socket
		   $OCTAL $((0x$4 & 0777))
		else
		   # probably an older stat, w/o -t option
		   $ECHO "$9" | $CUT -f2 -d\( | $CUT -f1 -d/
		fi
	      }

# function to check the owner of a file or directory

check_owner() { local theUsr=${2:-enstore}
		local theGrp=${3:-$theUsr}
		if [ ! -r $1 ]; then
		  msg1="BAD CONFIGURATION: $1 does not exist"
		  logit "$msg1"
		  alarm "$msg1"
		else
		  local theOwn=${theUsr}.${theGrp}
		  # /etc/{passwd,group} don't always contain "products"
		  local chkOwn=`$LS -ld $1 | $AWK '{printf "%s.%s", $3 == 1342 ? "products" : $3, $4 == 4525 ? "products" : $4}'`
		  if [ "$chkOwn" != "$theOwn" ]; then
		     [ -e /PRODUCTION ] && $CHOWN "${theUsr/products/1342}.${theGrp/products/4525}" $1
		     msg1="Changing $1 owner ($chkOwn to $theOwn)"
		     logit "$msg1"
		     if (( ALARM )) && [ -e /PRODUCTION ]; then
			enstore alarm --raise --severity "I" --root-error "$msg1"
		     fi
		  elif (( ! QUIET )); then
		     logit "$1 owner is $theOwn, ok"
		  fi
		fi
	      }

# function to check the mode of a file or device
#
# Note that the mode argument must be in octal, with a leading
# 0 (for example, 0755).
#
# Also check file owner against 3rd and 4th arguments, if present,
# or confirm that files under /, /etc or /root are owned by root,
# or confirm that files under /home/enstore are owned by enstore.

check_mode() { local theFile=$1
	       local theMode=$2
	       shift 2
	       if [ ! -r $theFile ]; then
		 msg1="BAD CONFIGURATION: $theFile does not exist"
		 logit "$msg1"
		 alarm "$msg1"
	       else
		 local fmode=`getfilemode $theFile`
		 if (( fmode != $theMode )); then
		    [ -e /PRODUCTION ] && $CHMOD $theMode $theFile
		    msg1="Changing $theFile mode ($fmode to $theMode)"
		    logit "$msg1"
		    if (( ALARM )) && [ -e /PRODUCTION ]; then
		       enstore alarm --raise --severity "I" --root-error "$msg1"
		    fi
		 elif (( ! QUIET )); then
		       logit "$theFile mode is $theMode, ok"
		 fi
		 if (( $# )); then
		    check_owner $theFile "$@"
		 elif $DIRNAME $theFile | $EGREP '^/($|etc|root)' >/dev/null; then
		    check_owner $theFile root
		 elif $DIRNAME $theFile | $EGREP '^/home/enstore' >/dev/null; then
		    check_owner $theFile
		 fi
	       fi
	     }

# function to check for a regular expression within a crontab
#
# If no file is specified, check only within the root crontab.

check_cron() { local oneFile=1
	       if (( $# == 1 )); then
		  local theFile=/var/spool/cron/root
		  local aRegExp=$1
	       elif (( $# == 2)); then
		  local theFile=$1
		  local aRegExp=$2
	       else
		  local theList=$1
		  while (( $# > 2 ))
		  do
		     shift
		     theList="$theList $1"
		  done
		  oneFile=0
		  local aRegExp=$2
	       fi
	       if (( ! oneFile )); then
		  local theFile
		  for theFile in $theList
		  do
		     if [ -r "$theFile" ] && $GREP -v '^#' "$theFile" | $EGREP "$aRegExp" >/dev/null; then
			(( ! QUIET )) && logit "$aRegExp in $theFile, ok"
			return
		     fi
		  done
		  msg1="BAD CONFIGURATION: $aRegExp not found in any crontab"
		  logit "$msg1"
	       elif [ ! -r "$theFile" ]; then
		  msg1="BAD CONFIGURATION: $theFile is missing"
		  logit "$msg1"
	       elif ! $GREP -v '^#' "$theFile" | $EGREP "$aRegExp" >/dev/null; then
		  msg1="BAD CONFIGURATION: $theFile is missing $aRegExp"
		  logit "$msg1"
	       elif (( ! QUIET )); then
		  msg1=
		  logit "$aRegExp in $theFile, ok"
	       fi
	       if [ -n "${msg1:-}" ] && (( ALARM )); then
		  enstore alarm --raise --severity "A" --root-error "$msg1"
	       fi
	     }

# function to compare files and complain if they are not the same
#
# The 1st argument is the source file. If the source file has an m4
# extension, or such a file exists, it will be passed thru the m4
# macro processor before comparison with the target file.
#
# The 2nd argument is the target file, or the directory containing
# the target file if the source and target file names are the same.
#
# Also check file mode against 3rd argument, if present,
# or confirm that files under /, /etc or /root are owned by root,
# or confirm that files under /home/enstore are owned by enstore.
#
# Note that the 3rd argument, if specified, must be in octal,
# with a leading 0 (for example, 0755).

right_file() { local src=$1
	       local dst=$2
	       shift 2
	       srcfile=`$BASENAME $src .m4`
	       [ -d $dst ] && dst=$dst/$srcfile
	       if [ $src = ${src%.m4} -a -r $src.m4 ]; then
		  if [ -f $src ]; then
		     msg1="Removing obsolete source $src"
		     logit "$msg1"
		     alarm "$msg1" I
		     $RM -f $src
		  fi
		  src=$src.m4
		  if [ ! -r $dst ]; then
		     msg1="BAD CONFIGURATION: $dst does not exist"
		     logit "$msg1"
		     alarm "$msg1"
		     return
		  fi
	       elif [ ! -r $src -o ! -r $dst ]; then
		  msg1="BAD CONFIGURATION: $src $dst do not both exist"
		  logit "$msg1"
		  alarm "$msg1"
		  return
	       fi
	       if [ $src = ${src%.m4}.m4 ]; then
		  tmp=/tmp/${srcfile}_$$
		  $M4 -DHOSTNAME=$node $src >$tmp 2>/dev/null
		  if ! $CMP $tmp $dst >/dev/null; then
		     msg1="BAD CONFIGURATION: $src $dst do not match"
		     logit "$msg1"
		     alarm "$msg1"
		     $RM -f $tmp
		     return
		  elif (( ! QUIET )); then
		     logit "$dst matches $src, ok"
		  fi
		  $RM -f $tmp
	       elif ! $CMP $src $dst >/dev/null; then
		  msg1="BAD CONFIGURATION: $src $dst do not match"
		  logit "$msg1"
		  alarm "$msg1"
		  return
	       elif (( ! QUIET )); then
		  logit "$dst matches $src, ok"
	       fi
	       if (( $# )); then
		  check_mode $dst "$@"
	       elif $DIRNAME $dst | $EGREP '^/($|etc|root)' >/dev/null; then
		  check_owner $dst root
	       elif $DIRNAME $dst | $EGREP '^/home/enstore' >/dev/null; then
		  check_owner $dst
	       fi
	     }

# function to check for a regular expression within a file

check_file() { local theFile=$1
	       local aRegExp=$2
	       shift 2
	       if [ ! -r "$theFile" ]; then
		  msg1="BAD CONFIGURATION: $theFile is missing"
		  logit "$msg1"
		  alarm "$msg1"
	       else
		  if ! $EGREP "$aRegExp" "$theFile" >/dev/null; then
		     msg1="BAD CONFIGURATION: $theFile is missing $aRegExp"
		     logit "$msg1"
		     alarm "$msg1"
		  elif (( ! QUIET )); then
		     logit "$aRegExp in $theFile, ok"
		  fi
	       fi
	     }

# function to check that a symlink exists and points to the specified file

check_link() { local link=`readlink -f $1`
	       if [ ! -L $1 ]; then
		  msg1="$1 is not a symlink"
		  logit "$msg1"
		  alarm "$msg1"
	       elif [ $link != $2 ]; then
		  msg1="$1 is not a symlink to $2"
		  logit "$msg1"
		  alarm "$msg1"
	       elif (( ! QUIET )); then
		  logit "$1 is a symlink to $2, ok"
	       fi
	     }

# function to check the system clock on an ACSLS host for accuracy

dateFmt="(10#%S+60*(10#%M+60*(10#%H+24*10#%j)))"

check_time() { let delta=`$DATE +"$dateFmt"`-`su -c "/usr/bin/rsh -l acsss $1 \"$DATE +'$dateFmt'\"" enstore`
	       if (( delta < 0 )); then
		  let delta=-delta
		  off=fast
	       else
		  off=slow
	       fi
	       if (( delta > 59 )); then
		  msg1="Clock on $1 is $off by $((delta/60)) minutes, $((delta%60)) seconds"
		  logit "$msg1"
		  alarm "$msg1" I
	       elif (( ! QUIET )); then
		  logit "Clock on $1 is $off by $delta seconds, ok"
	       fi
	     }

# function to check for allowed services and complain if not allowed
#
# This function uses the rules in $ALLOW, which must be defined with no embedded
# spaces (substitute # for a space). Each rule is terminated by a newline (\n).
# The loop is limited to rules for which the first 4 of the 5 requirements in
# each rule match a process with an open socket. There may be more than one such
# rule. If there is at least one, and they all fail, that is a "type 1" error;
# if there are none, that is a "type 2" error.

allow() { tt=${1:-UNKNOWN}
	  local psline=""
	  for i in `$ECHO -e -n $ALLOW | $AWK -F, -v TT=$tt -v CMD=$command -v REST="$rest" \
	    'NF == 5 && $1 ~ TT && $2 == CMD && REST ~ $3 && REST ~ $4 {printf "a=\"%s\";b=\"%s\";c=\"%s\";p=\"%s\"", $2, $3, $4, $5}'`
	  do
	    eval $i
	    if [ $p != x ]; then
	       if [ -z "$psline" ]; then
		  psline=`$ECHO "$PSfirst" | $AWK -v PID=$pid '$2 ~ PID {print}'`
	       fi
	       if $ECHO $psline | $EGREP '\[.*\]' >/dev/null; then
		  logit "Swapped out $node $tt $command $pid $rest -> $psline"
		  return 0
	       elif ! $ECHO $psline | $SED 's/  */#/g' | $EGREP "$p" >/dev/null; then
		  continue
	       fi
	    else
	      p=""
	    fi
	    if (( ! QUIET )); then
	       logit "Allowing $node $c $tt $a $b $p, ok"
	    fi
	    return 0
	  done
	  if [ -n "$psline" ]; then
	     type=1
	  else
	     psline=`$ECHO "$PSfirst" | $AWK -v PID=$pid '$2 ~ PID {print}'`
	     type=2
	  fi
	  msg1="UNAUTHORIZED NETWORK SERVICE, type ${type}! $node $tt $command $pid $rest"
	  logit "$msg1 $psline" "ps"
	  alarm "$msg1 $psline"
	  return $type
	 }

if [ -r "/etc/inetd.conf" ]; then
       INETD=inetd
elif [ -r "/etc/xinetd.conf" ]; then
       INETD=xinetd
else
       INETD=unknown
fi

if [ "$FLAVOR" = 'Linux+2.6' ]; then
	LOCALHOST=localhost.localdomain
else
	LOCALHOST=localhost
fi

# We allow these everywhere
ALLOW_BASE="
	LISTEN,$INETD,:(kshell|klogin|eklogin|telnet|netperf),TCP,x\n
	LISTEN,sendmail,$LOCALHOST:smtp,TCP,sendmail:#accepting#connections\n
	LISTEN,cfservd,*:cfengine,TCP,/usr/sbin/cfservd\n
	LISTEN,dccp,:,TCP,x\n
	LISTEN,netserver,:,TCP,x\n
	LISTEN,portmap,:sunrpc,TCP,x\n
	LISTEN,xinetd,$LOCALHOST:,TCP,x\n
	LISTEN,rsh,:,TCP,/usr/krb5/bin/rsh\n
	LISTEN,sshd,:ssh,TCP,/usr/sbin/sshd\n
	LISTEN,sshd,$LOCALHOST:,TCP,/usr/sbin/sshd\n
	LISTEN,sh,inet,TCP,MSG_TYPE|enstore\n
	LISTEN,mv,inet,TCP,MSG_TYPE|enstore\n
	LISTEN,grep,inet,TCP,MSG_TYPE|enstore\n
	LISTEN,sort,inet,TCP,MSG_TYPE|enstore\n
	LISTEN,ALARM_CLIENT,inet,TCP,x\n
"
#	TCP,xemacs,:x11,TCP,x\n
#	TCP,rsh,:kshell,TCP,x\n
#	TCP,rsh,:,TCP,/usr/krb5/bin/rsh\n
#	TCP,kshd,:kshell,TCP,x\n
#	TCP,kshd,:,TCP,kshd#kshd#-5c\n
#	TCP,klogind,:eklogin,TCP,x\n
#	TCP,telnetd,:telnet,TCP,telnetd#-Pa#valid\n
#	TCP,netserver,TCP,:netperf,x\n
#	TCP,python,:,TCP,$ENSTORE_DIR/(bin/encp|src/(encp|monitor_server).py)\n
#	UDP,python,:,UDP,$ENSTORE_DIR/(bin/encp|src/(encp|monitor_server|volume_assert).py|ngop/cronjobAgent.py)\n
#	UDP,python,:7499,UDP,$ENSTORE_DIR/src/monitor_server.py\n
#	UDP,portmap,:sunrpc,UDP,x\n
#	UDP,ntpd,:ntp,UDP,x\n
#	UDP,tee,:,UDP,tee#/dev/tty\n

# Extra for console servers
ALLOW_CONS="$ALLOW_BASE
	LISTEN,X,:x11,TCP,x\n
	LISTEN,conserver,:console,TCP,x\n
	LISTEN,conserver,:,TCP,conserver\n
"
#	TCP,console,:console,TCP,x\n

# Extra for enstore postgres db servers
ALLOW_PGDB="$ALLOW_BASE
	LISTEN,$INETD,:ftp,TCP,x\n
	LISTEN,postmaste,:(postgres|5432|8076|8800|8802|8888|9999),TCP,x\n
"

# Extra for srv3 - console + ftp + nfs server + pagedcache
ALLOW_SRV3="$ALLOW_CONS
	LISTEN,$INETD,:ftp,TCP,x\n
	LISTEN,rpc.mount,:,TCP,rpc.mountd\n
	LISTEN,rpc.nfsd,:(nfs|2049),TCP,x\n
	LISTEN,java,:,TCP,java#-cp\n
	LISTEN,python,(d0|stk|cdf)ensrv3.fnal.gov:,TCP,python\n
"
#	UDP,rpc.mount,:mount,UDP,x\n
#	UDP,rpc.nfsd,:(nfs|2049),UDP,x\n

# Extra for srv2 - web server
ALLOW_SRV2="$ALLOW_BASE
	LISTEN,$INETD,:ftp,TCP,x\n
	LISTEN,httpd,:http,TCP,/(fnal|local)/ups/prd/apache/\n
	LISTEN,mv,(d0|stk|cdf)ensrv2.fnal.gov:,TCP,mv\n
	LISTEN,sh,(d0|stk|cdf)ensrv2.fnal.gov:,TCP,sh\n
	LISTEN,grep,(d0|stk|cdf)ensrv2.fnal.gov:,TCP,grep\n
	LISTEN,sort,(d0|stk|cdf)ensrv2.fnal.gov:,TCP,sort\n
	LISTEN,python,(d0|stk|cdf)ensrv2.fnal.gov:,TCP,$ENSTORE_DIR/src/inquisitor.py\n
"

# Extra for srv1 - pnfs server, local postgres db server
ALLOW_SRV1="$ALLOW_BASE
	LISTEN,postmaste,$LOCALHOST:postgres,TCP,x\n
	LISTEN,java,:,TCP,/home/enstore/dcache/run|[java]\n
	LISTEN,python,(cms|eag)pnfs[12].fnal.gov:,TCP,migrate.py\n
	LISTEN,python,(d0|stk|cdf)ensrv1.fnal.gov:,TCP,migrate.py\n
"

# Extra for adic
ALLOW_ADIC="$ALLOW_BASE
	LISTEN,dasadmin,:663,TCP,x\n
	LISTEN,dasadmin,:,TCP,dasadmin\n
"

# Extra for d0ensrv4 - makes stk and adic calls
ALLOW_DSRV4="$ALLOW_ADIC
	LISTEN,$INETD,:ftp,TCP,x\n
	LISTEN,rsh,:,TCP,fntt#-l#acsss\n
	LISTEN,rsh,:,TCP,-l#acsss#fntt\n
	LISTEN,rsh,:,TCP,fntt-gcc#-l#acsss\n
	LISTEN,rsh,:,TCP,-l#acsss#fntt-gcc\n
"

# Extra for stkensrv4 - makes stk and adic calls
ALLOW_SSRV4="$ALLOW_ADIC
	LISTEN,$INETD,:ftp,TCP,x\n
	LISTEN,rsh,:,TCP,fntt#-l#acsss\n
	LISTEN,rsh,:,TCP,-l#acsss#fntt\n
	LISTEN,rsh,:,TCP,fntt-gcc#-l#acsss\n
	LISTEN,rsh,:,TCP,-l#acsss#fntt-gcc\n
"

# Extra for cdfensrv4 - makes stk calls
ALLOW_CSRV4="$ALLOW_BASE
	LISTEN,$INETD,:ftp,TCP,x\n
	LISTEN,rsh,:,TCP,fntt2#-l#acsss\n
	LISTEN,rsh,:,TCP,-l#acsss#fntt2\n
	LISTEN,rsh,:,TCP,fntt-gcc#-l#acsss\n
	LISTEN,rsh,:,TCP,-l#acsss#fntt-gcc\n
"

# Extra for d0ensrv3
ALLOW_DSRV3="$ALLOW_SRV3
	LISTEN,perl,d0ensrv3p.fnal.gov:,TCP,mirror#everything:adic2.fnal.gov\n
"

# Extra for d0ensrv2
ALLOW_DSRV2="$ALLOW_SRV2
	LISTEN,mirror,d0ensrv2p.fnal.gov:,TCP,mirror#logs:adic2.fnal.gov\n
"

# Extra for stkensrv2 - nfs server
ALLOW_SSRV2="$ALLOW_SRV2
	LISTEN,rpc.mount,:,TCP,rpc.mountd\n
	LISTEN,rpc.nfsd,:(nfs|2049),TCP,x\n
"
#	UDP,rpc.mount,:mount,UDP,x\n
#	UDP,rpc.nfsd,:(nfs|2049),UDP,x\n

# Extra for cmspnfs? - pnfs server
ALLOW_CMS1="$ALLOW_SRV1
	LISTEN,xinetd,:terad,TCP,x\n
	LISTEN,gmond,:8649,TCP,/usr/sbin/gmond\n
	LISTEN,iperf,:5001,TCP,/opt/iperf/bin/iperf\n
"

# Extra for eagpnfs? - pnfs server
ALLOW_EAG1="$ALLOW_SRV1
	LISTEN,iperf,:5001,TCP,/opt/iperf/bin/iperf\n
"

# Extra for movers
ALLOW_MVR="$ALLOW_BASE
	LISTEN,python,:,TCP,$ENSTORE_DIR/src/mover.py\n
"
#	TCP,python,:,TCP,$ENSTORE_DIR/src/mover.py\n
#	UDP,python,:,UDP,$ENSTORE_DIR/src/mover.py\n

# Extra for dcache
# Allowing swapped out javas is not good, but I don't know what else to do right now.
ALLOW_DCA="$ALLOW_BASE
	LISTEN,httpd,:http,TCP,/(fnal|local)/ups/prd/apache/\n
	LISTEN,java,:,TCP,/home/enstore/dcache/run/diskCache|[java]|dmg.cells.services.Domain\n
"

# make the choice
case $node in
       *srv0)      ALLOW=$ALLOW_PGDB;  logit "Comparing to srv0";;
       *srv1)      ALLOW=$ALLOW_SRV1;  logit "Comparing to srv1";;
    cmspnfs?)      ALLOW=$ALLOW_CMS1;  logit "Comparing to $node";;
    eagpnfs?)      ALLOW=$ALLOW_EAG1;  logit "Comparing to $node";;
    d0ensrv2)      ALLOW=$ALLOW_DSRV2; logit "Comparing to $node";;
   stkensrv2)      ALLOW=$ALLOW_SSRV2; logit "Comparing to $node";;
       *srv2)      ALLOW=$ALLOW_SRV2;  logit "Comparing to srv2";;
    d0ensrv3)      ALLOW=$ALLOW_DSRV3; logit "Comparing to $node";;
       *srv3)      ALLOW=$ALLOW_SRV3;  logit "Comparing to srv3";;
    d0ensrv4)      ALLOW=$ALLOW_DSRV4; logit "Comparing to $node";;
   stkensrv4)      ALLOW=$ALLOW_SSRV4; logit "Comparing to $node";;
   cdfensrv4)      ALLOW=$ALLOW_CSRV4; logit "Comparing to $node";;
   *srv[579])      ALLOW=$ALLOW_CONS;  logit "Comparing to cons";;
       *srv6)      ALLOW=$ALLOW_PGDB;  logit "Comparing to srv6";;
       *mvr*|rip*) ALLOW=$ALLOW_MVR;   logit "Comparing to mvr";;
       *dca*)      ALLOW=$ALLOW_DCA;   logit "Comparing to dca";;
	   *)      ALLOW=$ALLOW_BASE;  logit "Comparing to base";;
esac

# Extra for all servers - 3ware web server
if (( SERVER | DCACHE )); then
  ALLOW="$ALLOW
	LISTEN,3dm2,:webcache,TCP,/usr/sbin/3dm2\n
"
fi
echo "Allowing $ALLOW"

# try to start - but if one netscan is already running, then exit
if ! [ -d `$DIRNAME $ACTIVE` ]; then
   msg="no directory on $node for $ACTIVE... exiting"
   logit "$msg"
   alarm "$msg"
   exit 1
fi
if ! $MKDIR $ACTIVE 1>/dev/null 2>/dev/null; then
   # ok, this is terrible..., but I don't know what else to do.  Dang kerberos!
   # the most likely thing that has failed or hung is the task that accesses the net.  Kill it.
   # kill the farmlets task
   $PS axwww | $GREP "farmlets" | $GREP -v grep | while read pid line
   do
      $ECHO `$DATE` $KILL -9 $pid $line >>$LOG 2>&1
      $ECHO $KILL -9 $pid $line
      $KILL -9 $pid
   done
   $SLEEP 30
   # kill any remaining rsyncs that check the cron area
   $PS axwww | $EGREP "farmlets|rsync" | $GREP -v grep | $GREP cron | while read pid line
   do
      $ECHO `$DATE` $KILL -9 $pid $line >>$LOG 2>&1
      $ECHO $KILL -9 $pid $line
      $KILL -9 $pid
   done
   $SLEEP 30
   if ! $MKDIR $ACTIVE 1>/dev/null 2>/dev/null; then
      msg="netscan on $node already ACTIVE... exiting"
      logit "$msg"
      alarm "$msg"
      exit 1
   else
      logit "netscan starting"
   fi
else
   logit "netscan starting"
fi

# make this a dry run if we are not a production node
[ -e /PRODUCTION ] || logit "Dry Run - bad file attributes will not be corrected"

# generate an informational alarm if we detect a server has rebooted
if (( REBOOT && SERVER )); then
   msg="Server $node has rebooted"
   logit "$msg"
   alarm "$msg" I
fi

# check these files
right_file $ENSTORE_DIR/etc/root.k5login		/root/.k5login		0600
right_file $ENSTORE_DIR/etc/$gang.enstore.k5login	/home/enstore/.k5login	0600
right_file $ENSTORE_DIR/etc/$gang.hosts.allow		/etc/hosts.allow
right_file $ENSTORE_DIR/etc/hosts.deny			/etc/hosts.deny
right_file $ENSTORE_DIR/etc/hosts			/etc/hosts
right_file $ENSTORE_DIR/etc/sudoers			/etc/sudoers		0440
right_file $ENSTORE_DIR/etc/krb5.conf			/etc/krb5.conf		0644
right_file $ENSTORE_DIR/etc/xserverrc			/etc/X11/xinit		0755
right_file $ENSTORE_DIR/bin/enstore-boot		/etc/rc.d/init.d	0755
right_file $ENSTORE_DIR/bin/monitor_server-boot		/etc/rc.d/init.d	0755

# check these files only on db or configuration server nodes
(( SERVER )) && case $node in
  d0ensrv0|stkensrv0|cdfensrv0)
    right_file $ENSTORE_DIR/databases/scripts/accounting-db	/etc/rc.d/init.d	0755
    right_file $ENSTORE_DIR/databases/scripts/drivestat-db	/etc/rc.d/init.d	0755
    right_file $ENSTORE_DIR/databases/scripts/enstore-db	/etc/rc.d/init.d	0755
    ;;
# deprecated - functionality moved from srv6 to srv0
  d0ensrv6|stkensrv6|cdfensrv6)
    right_file $ENSTORE_DIR/sbin/enstore-drivestat		/etc/rc.d/init.d	0755
    right_file $ENSTORE_DIR/sbin/enstore-pgdb			/etc/rc.d/init.d	0755
    ;;
  d0ensrv2)
    check_mode $ENSTORE_DIR/etc/sam.conf		0664	enstore
    ;;
  stkensrv2)
    check_mode $ENSTORE_DIR/etc/stk.conf		0664	enstore
    ;;
  cdfensrv2)
    check_mode $ENSTORE_DIR/etc/cdf.conf		0664	enstore
    ;;
  d0ensrv1|stkensrv1|cdfensrv1|eagpnfs?|cmspnfs?)
    check_mode /etc/rc.d/init.d/pnfs			0755	root
    ;;
esac

for x in /etc/rc.d/rc.{sysinit,local} /var/log/sa
do
  check_mode	$x					0755	root
done

check_mode	/home/enstore				0755	enstore

if [ -e /PRODUCTION ]
then
  check_mode	/PRODUCTION				0644
  check_mode	/root/CRON				0755
  if [ -d /home/enstore/CRON ]
  then
    check_mode	/home/enstore/CRON			0755
  fi
fi

if [ -e /PRODUCTION ] && (( MOVER || SERVER ))
then

  # verify hosts, k5login, and network files contain this host's fqdn
  check_file	/etc/hosts				"${fqdn}"
  check_file	/etc/sysconfig/network			"${fqdn}"
  check_file	/root/.k5login				"host/${fqdn}@FNAL.GOV"
  check_file	/home/enstore/.k5login			"enstore/cd/${fqdn}@FNAL.GOV"
  # verify farmlets files exist and contain this host's name
  check_mode	/usr/local/etc/farmlets			0755	root
  for f in $node $gang$nodetype ${gang}-all ${gang}-alla enstore
  do
    check_file	/usr/local/etc/farmlets/$f		"$node"
  done
  # verify symlinks in farmlets directory
  for g in {d0,stk,cdf}en
  do
    check_link	/usr/local/etc/farmlets/$g		/usr/local/etc/farmlets/${g}-alla
  done
  for g in {d0,stk,cdf}enmvr
  do
    check_link	/usr/local/etc/farmlets/$g		/usr/local/etc/farmlets/${g}-a
  done

  # one of /fnal and /local should be a symlink to the other
  let inode1=`ls -iL /fnal  | awk '{print $1}'`
  let inode2=`ls -iL /local | awk '{print $1}'`
  if (( inode1 != inode2 )); then
     msg="problem with /fnal or /local"
     logit "$msg"
     alarm "$msg"
  elif (( ! QUIET )); then
     logit "/fnal and /local are the same directory, ok"
  fi

  # check ups and product support
  if [ ~products = \~products ]; then
     msg="products is not a user"
     logit "$msg"
     alarm "$msg"
  elif (( ! QUIET )); then
     logit "products is a user, ok"
  fi

  for d in . etc
  do
    check_mode	/fnal/ups/$d	0755	products
  done
  for d in db prd
  do
    check_mode	/fnal/ups/$d	0775	products
  done
  check_file	/fnal/ups/etc/upsdb_list		"/(fnal|local)/ups/db"
  check_mode	/fnal/ups/etc/upsdb_list					0664	products
  right_file	$ENSTORE_DIR/etc/products.k5login	/fnal/ups/.k5login	0600	products
  # the ups PRODUCTS variable should contain /fnal/ups/db or /local/ups/db, but not both
  let nupsdb=0
  for db in `$ECHO "${PRODUCTS:-}" | $TR ':' ' '`
  do
    if $ECHO $db | $EGREP '/(fnal|local)/ups/db' >/dev/null
    then
       let nupsdb+=1
    fi
  done
  if (( nupsdb != 1 )); then
     msg="problem with ups PRODUCTS variable: '${PRODUCTS:-}'"
     logit "$msg"
     alarm "$msg"
  elif (( ! QUIET )); then
     logit "ups PRODUCTS variable correctly defined, ok"
  fi
  for d in startup shutdown
  do
    f="/fnal/ups/db/.upsfiles/$d/${node}.products"
    check_file	$f	"ups[[:space:]]+(start|stop)[[:space:]]+ngop"
    check_mode	$f								0775	products
  done
  right_file	$ENSTORE_DIR/etc/ups		/etc/rc.d/init.d		0755

  # skip all this unless /var/ngop exists
  if [ -d /var/ngop ]; then

     # check ngop configuration directories
     for d in . include cron_agent plugins_agent
     do
       check_mode  /var/ngop/$d    0755    root
     done

     # check ngop configuration files

     NGOP_DIR=$ENSTORE_DIR/ngop
     for i in $NGOP_DIR/check*.py
     do
       right_file  $i				   /var/ngop/include		   0644    root
     done
     right_file    $NGOP_DIR/raise_enstore_alarm   /var/ngop/include		   0755    root
     right_file    $NGOP_DIR/local_cronjob.xml     /var/ngop/cron_agent 	   0644    root
     right_file    $NGOP_DIR/start_cron 	   /var/ngop/cron_agent/.start     0755    root
     if   (( SERVER )); then
       lh_xml=srv_linuxHealth	   # server
     elif (( DCACHE )); then
       lh_xml=dca_linuxHealth	   # dcache
     else
       lh_xml=linuxHealth	   # movers
     fi
     right_file    $NGOP_DIR/${lh_xml}.xml	   /var/ngop/plugins_agent	   0644    root
     unset NGOP_DIR

     # are both ngop agents running? (but don't check immediately after reboot)

     if (( ! REBOOT )); then
	set +u
	setup ngop
	set -u
	agents=`ngop check`
	if [ `$ECHO "$agents" | $WC -l` -ne 2 ] ||
	   [ `$ECHO "$agents" | $AWK '$1 != "dead" && $2 == "root"' | $WC -l` -ne 2 ] ||
	    ! $ECHO "$agents" | $GREP "ngop plugins_agent -c /var/ngop/plugins_agent/${lh_xml}\.xml" >/dev/null ||
	    ! $ECHO "$agents" | $GREP "/var/ngop/cron_agent/\.start -c /var/ngop/cron_agent/local_cronjob\.xml" >/dev/null
	then
	   msg=`$ECHO -e "problem with ngop agent(s):\n$agents"`
	   logit "$msg"
	   alarm "$msg"
	   ngop stop >>$LOG 2>&1
	   $SLEEP 3
	   ngop start >>$LOG 2>&1
	elif (( ! QUIET )); then
	   logit "two ngop agents running, ok"
	fi
     fi
  else
     msg="MISSING CONFIGURATION: no /var/ngop directory"
     logit "$msg"
     alarm "$msg"
  fi
fi

# it seems we almost always change the mode of /dev/console after reboot,
# so don't alarm then
if (( REBOOT )); then
 (
  ALARM=0
  check_mode	/dev/console	0622	root
 )
else
  check_mode	/dev/console	0622	root
fi

# there needs to be more logic for xinetd or inetd files
if [ "$INETD" = unknown ]; then
  # neither file existed, this is a problem
  msg="MISSING CONFIGURATION: no inetd.conf or xinetd.conf in /etc"
  logit "$msg"
  alarm "$msg"
else
  right_file	$ENSTORE_DIR/etc/${INETD}.conf		/etc/${INETD}.conf
  if [ "$INETD" = xinetd ]; then
# ftp is special - it is enabled on most servers, disabled elsewhere
#   if echo $node | egrep '^(d0|stk|cdf)ensrv[02346]$' >/dev/null; then
#     sed -e '/disable/s/yes/no/' $ENSTORE_DIR/etc/ftp > /tmp/ftp.xinetd
#   else
#     sed -e '/disable/s/no/yes/' $ENSTORE_DIR/etc/ftp > /tmp/ftp.xinetd
#   fi
#   right_file	/tmp/ftp.xinetd				/etc/xinetd.d/ftp
# check the other services
    for s in kshell klogin eklogin telnet ftp
    do
      right_file $ENSTORE_DIR/etc/$s			/etc/xinetd.d
    done
  fi
fi

right_file	$ENSTORE_DIR/etc/enstore.bashrc		/home/enstore/.bashrc
right_file	$ENSTORE_DIR/etc/enstore.bash_profile	/home/enstore/.bash_profile
right_file	$ENSTORE_DIR/etc/$gang.step-tickers	/etc/ntp/step-tickers
right_file	$ENSTORE_DIR/etc/ntp.conf		/etc/ntp.conf
if [ "$FLAVOR" = 'Linux+2.4' -o "$FLAVOR" = 'Linux+2.6' ]; then
  right_file	$ENSTORE_DIR/etc/services		/etc/services
  check_mode	/var/lib/ntp		0755	ntp
  check_mode	/var/lib/ntp/drift	0644	ntp
fi

# check that no rpm binaries have been tampered with
# disabled... we made changes, check is not robust.
#$RPM -Va | $GREP bin | $EGREP -v '/usr/bin/X11|/usr/local/bin|/bin/bash|/usr/bin/bashbug|/usr/bin/db_|/usr/bin/run-parts|\.h$|\.h$|/bin/login'

# check that eth1 is working, fix if not
#eth1_err="eth1: card reports no RX buffers"
#if $TAIL -n 10 /var/log/messages | $EGREP "$eth1_err" >/dev/null; then
#   logit "ERROR: $eth1_err"
#   alarm "ERROR: $eth1_err"
#   [ -e /PRODUCTION ] && $IFDOWN eth1 >>$LOG 2>&1
#   [ -e /PRODUCTION ] && $IFUP   eth1 >>$LOG 2>&1
#elif (( ! QUIET )); then
#   logit "No eth1 errors found in messages, ok"
#fi

# check that we have sufficient disk space available.
#dflines=`$DF -P`
#$ECHO "$dflines" | while read a b c d e rest
#do
#  if [ `$ECHO $e | $GREP -c %` -eq 1 ]; then
#    cap=`$ECHO $e | $SED -e 's/%//'`
#    mess="$a $b $c $d $e $rest"
#    if (( $cap >= 90 )); then
#      msg="DISK FULL: $mess"
#      logit "$msg"
#      alarm "$msg"
#    else
#      if (( ! QUIET )); then
#         logit "DISK $a at $cap%, ok"
#      fi
#    fi
#  fi
#done

# check that ntpd is working, fix if not, schedule at script to check time
if [ `$PS --no-headers -C ntpd | $WC -l` -ne 1 ]; then
   msg="problem with ntpd process"
   logit "$msg"
   alarm "$msg" W
   $SERVICE ntpd restart
elif (( ! QUIET )); then
   logit "ntpd process found, ok"
fi

OEMline=`$GREP '^OEM' /var/log/dmesg`
if [ -n "${OEMline:-}" ]; then
   for motherboard in SDS2 Lancewood Lindenhurst SE7320SP20 SE7505VB2 SE7525GP2 S7501HG0 N440BX Unknown
   do
     if $ECHO $OEMline | $GREP $motherboard >/dev/null; then break; fi
   done
fi
if [ "${motherboard:-Unknown}" = Unknown ]; then
   model=`$AWK -F: '$1 ~ "model" && $2 !~ /[a-zA-Z().]/ {print $2}' /proc/cpuinfo | $SORT -u`
   case `$EXPR $model` in
     15)	motherboard=Lindenhurst	;;
     11)	motherboard=SDS2	;;
      7|8)	motherboard=Lancewood	;;
      5)	motherboard=N440BX	;;
      4)	motherboard=SE7320SP20	;;	# or Lindenhurst
      2)	motherboard=SE7505VB2	;;	# or S7501HG0
      *)	motherboard=Unknown	;;
   esac
fi
if (( ! QUIET )); then
   logit "Motherboard is $motherboard"
fi

if [ -e /PRODUCTION ]; then
   if [ $motherboard = Unknown ]; then
      msg="Unknown or undetermined motherboard"
      logit "$msg"
      alarm "$msg" I
   fi
   set +u
   ipmiVersion=`ups list -cKversion ipmi | $SED -e s/\"//g -e s/\ //g`
   set -u
   if [ -z "${ipmiVersion:-}" ]; then
      msg="No current ups version of ipmi"
      logit "$msg"
      alarm "$msg" I
   elif (( ! QUIET )); then
      logit "Current ups version of ipmi is $ipmiVersion"
   fi
   case ${ipmiVersion} in
     devel)
	case ${motherboard} in
	  N440BX | Lancewood)
	    IPMISRV=1
	    ;;
	esac
	;;
     v1.5)
	case ${motherboard} in
	  SDS2 | S7501HG0)
	    IPMISRV=0
	    ;;
	  SE7320SP20 | SE7505VB2 | SE7525GP2 | Lindenhurst)
	    IPMISRV=0
	    NOIPMI=1		# for now, ipmi seg faults on some Xeon boards
	    ;;
	esac
	;;
   esac
   if [ -z "${IPMISRV:-}" ]; then
      msg="Current ups version of ipmi is incompatible with this motherboard"
      logit "$msg"
      alarm "$msg"
      NOIPMI=1
   elif (( ! QUIET )); then
      logit "Current ups version of ipmi is compatible with this motherboard"
   fi
fi

# check that special jobs are listed in root crontab or /etc/cron.d

if [ -r /var/spool/cron/root ]; then
   rootCron="/var/spool/cron/root"
elif (( ! QUIET )); then
   logit "No root crontab"
fi

if [ -e /PRODUCTION ]; then
   if [ ${IPMISRV:-0} -eq 1 ]; then
      check_cron     /etc/cron.d/ipmi	     ${rootCron:-}       "/home/enstore/ipmi/check_watchdog_reset.py"
   fi
   check_cron	     /etc/cron.d/ekill       ${rootCron:-}       \
		     "ekill -v -9 \"sdrread\|selread\|chip2\|Chip2\|netperf\|dog\|selbit\|selclear\|netstat\|Nodeinfo\|biterror\""
fi

# check whether hyperthreading is enabled on dual Xeon platforms
# we assume that multiple processors are identical, and we don't
# handle multi-core processors
case `$AWK -F: '$1 ~ "flags" {print $2}' /proc/cpuinfo | $GREP -c " ht"` in
  0) ;;
  1) msg="One processor disabled, hyperthreading OFF"
     logit "$msg"
     alarm "$msg"
     ;;
  2) if $AWK -F: '$1 ~ "siblings" {print ($2 > 1) ? "ON" : "OFF"}' /proc/cpuinfo | $GREP ON >/dev/null
     then
	msg="One processor disabled, hyperthreading ON"
	logit "$msg"
	alarm "$msg"
    else
	if (( ! QUIET )); then
	   logit "Both processors enabled, hyperthreading OFF, ok"
	fi
     fi
     ;;
  3) msg="Hyperthreading on one processor disabled"
     logit "$msg"
     alarm "$msg"
     ;;
  4) if (( ! QUIET )); then
	logit "Both processors enabled, hyperthreading ON, ok"
     fi
     ;;
esac

check_file	/etc/rc.d/rc.local	"boot_cleanup"
check_file	/etc/rc.d/rc.local	"ipmi_startup"
if [ "$FLAVOR" = 'Linux+2.4' -o "$FLAVOR" = 'Linux+2.6' ]; then
   check_cron	/etc/cron.d/sysstat	"/usr/lib/sa/sa1"		# system accounting
fi
# not so dumb, because we can run netscan manually, too
check_cron	/etc/cron.d/netscan	"netscan -a -c -q"

# is srv3:/diskc mountable as /backup and in the right gang
DISKC=`$GREP -v '^#' /etc/fstab | $AWK '$1~/(d0|stk|cdf)ensrv3:\/diskc/ && $2=="/backup" && $3=="nfs" && $4~/noauto/ {print $1}'`
if [ `$ECHO "$DISKC" | wc -l` -ne 1 -o "$DISKC" != "${gang}srv3:/diskc" ]; then
   msg="BAD CONFIGURATION: Check \"${gang}srv3:/diskc /backup nfs\" entry in /etc/fstab"
   logit "$msg"
   alarm "$msg" W
elif (( ! QUIET )); then
   logit "Valid \"${gang}srv3:/diskc /backup nfs\" entry in /etc/fstab, ok"
fi

for h in ~root ~enstore
do
  check_file	$h/.forward	"enstore-(admin|auto)@fnal.gov"
  check_mode	$h/.forward					0644
done

# verify ownership and permissions of enstore mover status directory
if (( MOVER )); then
  check_mode /tmp/enstore/enstore	0755	enstore
fi

# verify ownership and permissions of enstore keytab directory and file
check_mode /fnal/ups/kt			0755	enstore
check_mode /fnal/ups/kt/enstorekt	0600	enstore

# in Fermi Linux 7.3.x, $HOME is not yet defined when monitor_server starts,
# so the .output file goes in / instead of /root.
    if $GREP 'Linux 7.3' /proc/version >/dev/null; then
       monRoot=""
    else
       monRoot="/root"
    fi
# verify ownership of log files (but no alarms right after a reboot)
if [ -e /PRODUCTION ]; then
   if (( REBOOT )); then
    (
     ALARM=0
     check_owner ~enstore/${fqdn}.startup
     check_owner $monRoot/${fqdn}.monitor_server.output root
    )
   else
     check_owner ~enstore/${fqdn}.startup
     check_owner $monRoot/${fqdn}.monitor_server.output root
   fi
fi

# get open files - twice - get ps in between - only take connections that survive past this
# otherwise it is impossible to compare and see if they are allowed - this is a small hole
# also need to go through a file - because argument to echo is too large!!!
netscan_n1=`$DIRNAME $LOG`/netscan_n1
netscan_n2=`$DIRNAME $LOG`/netscan_n2
rm -f $netscan_n1
rm -f $netscan_n2
# sometimes we get no output from ps command
#let try=3
#while [ $((try-=1)) -ge 0 ]
for (( try=3; try; try-=1 ))
do
  $LSOF -i TCP -i UDP > $netscan_n1
  PSfirst=`$PS --no-headers afuwwwx | $CUT -c1-250`
  $LSOF -i TCP -i UDP > $netscan_n2
  if [ -n "${PSfirst:-}" ]; then
    break
  fi
  $SLEEP 2
done

# start with a generic base of 100 processes
let maxproc=100

today=`$DATE -I`

(( SERVER )) && case $node in

  d0ensrv1|stkensrv1|cdfensrv1|cmspnfs?|eagpnfs?)
    # check all pnfs database sizes on srv1 nodes
    #  - but don't make too much noise about it
    # also count the number of gdbm and postgres sql databases
    let ngdbm=0
    let npsql=0
    if [ -r /diska/pnfs/db/info/D-0000 ]; then
       # determine the psql database path
       if [ -d /diska/pnfs/db/psql-data/base ]; then
	 psqldb=psql-data/base
       elif [ -d /diska/pnfs/db/data/base ]; then
	 psqldb=data/base
       else
	 psqldb=
       fi
       if (( QUIET )); then
	  # loop over all current enabled databases
	  for db in `$GREP enabled /diska/pnfs/db/info/D-* | $CUT -d: -f6`
	  do
	    if [ -s $db ]; then
	       let ngdbm+=1
	    else
	       let npsql+=1
	    fi
	  done
       else
	  set +u
	  setup pnfs	   # needed for psql
	  set -u
	  # shout if we've reached the limit for pnfs databases
	  if [ `cat /diska/pnfs/db/info/shmservers` -ge "${shmservers:-0}" ]; then
	     msg="At the limit of PNFS databases"
	     logit "$msg"
	     alarm "$msg" W
	  elif (( ! QUIET )); then
	     logit "Not at the limit of PNFS databases, ok"
	  fi
	  # establish directory for database sizes
	  dbfdir=/tmp/pnfs-db-sizes
	  [ -d $dbfdir ] || $MKDIR $dbfdir
	  # loop over all current enabled databases
	  for db in `$GREP enabled /diska/pnfs/db/info/D-* | $CUT -d: -f6`
	  do
	    dbname=`$BASENAME $db`
	    dbfile=$dbfdir/$dbname
	    if [ -s $db ]; then
	       let ngdbm+=1
	       dbsize=`$LS -l $db | $AWK '{print $5}'`
	       dbszKB=$(( (dbsize+512)>>10 ))
	       dbszMB=$(( (dbsize+524288)>>20 ))
	    else
	       let npsql+=1
	       dbpgid=`psql -t -A -U enstore template1 -c "select OID from pg_database where datname='$dbname'"`
	       dbszKB=`$DU -ks /diska/pnfs/db/$psqldb/$dbpgid | $AWK '{print $1}'`
	       dbszMB=$(( (dbszKB+512)>>10 ))
	    fi
	    if [ -r $dbfile ]; then
	       if (( dbszKB > 8388608 && dbszKB > $(<$dbfile) )); then
		  msg="DATABASE TOO BIG: $dbname - $dbszMB MB, exceeds 8 GB and is growing"
		  logit "$msg"
		  alarm "$msg" W
	       else
		  logit "$dbname - $dbszMB MB, not too big or not growing, ok"
	       fi
	    fi
	    $ECHO $dbszKB > $dbfile
	  done
	  (( npsql > 0 )) && logit "number of pnfs databases (psql): $npsql"
	  (( ngdbm > 0 )) && logit "number of pnfs databases (gdbm): $ngdbm"
       fi
    fi
    # how many pnfs daemons?
    if [ -r /usr/etc/pnfsSetup ]; then
      npnfsd=`$AWK -F = '/^pnfscopies=/ {print $NF}' /usr/etc/pnfsSetup`
    fi
    reproc="${npnfsd:-0}"
    if (( reproc == 0 )); then
       msg="pnfscopies is 0 or not defined in /usr/etc/pnfsSetup"
       logit "$msg"
       alarm "$msg" W
       npnfsd="-1"
    fi
    # in Fermi Linux LTS and Scientific Linux, all java threads count as one process
    let reproc+=1
    # there are many replicated processes on pnfs servers:
    #	    pnfsd		pnfscopies in /usr/etc/pnfsSetup
    #	    dbserver		1 per gdbm or psql database
    #	    postgres		1 per psql database, plus 2
    #	    postgres		6 per psql database addt'l with slon
    #	    slon pnfs_replica	1 per psql database addt'l with slon
    #	    java pnfs.batch	many for FL 7.3.x, 1 for LTS or SL 3+
    let reproc+=$((ngdbm+2+2*npsql))
    # if present, slon adds 7 processes per psql database
    if [ -x /etc/rc.d/init.d/slon-boot ]; then
       let reproc+=$((7*npsql))
    fi
    if (( ! QUIET )); then
       logit "allowing $reproc replicated processes for pnfs server"
    fi
    let maxproc+=reproc
    # skip pnfs manager check for non-production nodes, and immediately after a reboot
    # also, there is no dcache on d0en, hence no pnfs manager process
    if (( ! REBOOT )) && [ -e /PRODUCTION ] && [ $gang != d0en ]; then
       if [ `$PS --no-headers -C pnfs | $WC -l` -ne 1 ]; then
	  msg="problem with pnfs manager process"
	  logit "$msg"
	  alarm "$msg" W
       elif (( ! QUIET )); then
	  logit "pnfs manager process found, ok"
       fi
    fi
    ;;

  d0ensrv2|stkensrv2|cdfensrv2)
    # check the largest of today's log files on srv2 nodes
    logline=`$LS -ls /diska/enstore-log/*-$today | $SORT -n | $TAIL -1`
    logtime=`$DATE +%s`
    logsize=`$ECHO $logline | $AWK '{print $6}'`
    logpath=`$ECHO $logline | $AWK '{print $10}'`
    logname=`$BASENAME $logpath`
    logfdir=/tmp/logfile-sizes
    logfile=$logfdir/$logname
    if (( logsize > 536870912 )); then
       # establish directory for logfile sizes
       [ -d $logfdir ] || $MKDIR $logfdir
       logszKB=$(( (logsize+512)>>10 ))
       if [ -r $logfile ]; then
	  let dt=logtime-`$DATE -r $logfile +%s`	# seconds
	  let ds=logszKB-$(<$logfile)			# KBytes
	  current=0
	  if (( logsize > 1073741824 )); then
	     if [ -r /tmp/logfile-too-big ]; then
		current=$(</tmp/logfile-too-big)
	     fi
	     $ECHO $((++current)) > /tmp/logfile-too-big
	     msg="LOG FILE TOO BIG: $logname - $(( (logsize+524288)>>20 )) MB, exceeds 1 GB"
	     logit "$msg"
	     if (( ALARM )); then
		complain=1
		# decreasing notification rate (Fibonacci wise)
		fminus1=$complain
		until (( complain >= current )); do
		  fminus2=$fminus1
		  fminus1=$complain
		  complain=$((fminus2 + fminus1))
		done
		if (( complain == current )); then
		   alarm "$msg" W
		fi
	     fi
	  else
	     let dt=logtime-`$DATE -r $logfile +%s`	# seconds
	     let ds=logszKB-$(<$logfile)		# KBytes
	     if (( (`$DATE -d 2359 +%s`-logtime)*ds > (1048576-logszKB)*dt )); then
		msg="LOG FILE GROWING FAST: $logname may exceed 1 GB by midnight"
		logit "$msg"
		alarm "$msg" W
	     elif (( ! QUIET )); then
		logit "$logname - $(( (logsize+524288)>>20 )) MB, not growing fast, ok"
	     fi
	  fi
       else
	  $ECHO $logszKB > $logfile
	  $RM -f /tmp/logfile-too-big
       fi
    elif (( ! QUIET )); then
       logit "$logname - $logsize not too big, ok"
    fi
    ;;

  d0ensrv3|stkensrv3|cdfensrv3)
    # check the expiration on user certs, if present
    if [ -r ~enstore/.globus/usercert.pem ]; then
       eval `$OPENSSL x509 -in ~enstore/.globus/usercert.pem -noout -dates |
	     $AWK -F= '/notBefore/ {notB=$2}
		       /notAfter/  {notA=$2}
		       END {printf "notB=\"%s\";notA=\"%s\"", notB, notA}'`
       date1=`$DATE -d "$notB" +%s`
       date2=`$DATE -d "$notA" +%s`
       incept=`$DATE -d "$notB"`
       expiry=`$DATE -d "$notA"`
       now=`$DATE +%s`
       let cutoff=(date2-now)/900
       # already expired or not yet valid
       if (( now < date1 )) || (( now > date2 )); then
	  msg="User certificate dates out of range: $incept to $expiry"
	  logit "$msg"
	  alarm "$msg" E
       # expiry approaches, or is imminent
       elif (( cutoff <= 2584 )); then
	  if ((cutoff < 96 )); then
	     msg="User certificate expires today: $expiry"
	  else
	     msg="User certificate expires soon: $expiry"
	  fi
	  logit "$msg"
	  notify=1
	  # increasing notification rate (Fibonacci wise)
	  fminus1=$notify
	  until (( notify >= cutoff )); do
	    fminus2=$fminus1
	    fminus1=$notify
	    notify=$((fminus2 + fminus1))
	  done
	  if (( notify == cutoff )); then
	     alarm "$msg" W
	  fi
       elif (( ! QUIET )); then
	  logit "User certificate good until $expiry, ok"
       fi
    fi
    ;;

  d0ensrv4|stkensrv4|cdfensrv4)
    # check the time on fntt, fntt2 or fntt-gcc
    if $ECHO $node | $EGREP '(d0|stk)en' >/dev/null; then
       SUN="fntt"
    elif $ECHO $node | $GREP 'cdfen' >/dev/null; then
       SUN="fntt2 fntt-gcc"
    fi
    for sun in $SUN
    do
      check_time $sun
    done

    # check lock status of library managers
    $ECHO "$PSfirst" | $GREP library_manager | $AWK '{print $NF}' | while read libman
    do
      lm_lock_config=`enstore config --show $libman |
	$AWK -F: '/\<lock\>/ {match($2, ".*(locked|ignore|pause|noread|nowrite).*", a); print a[1]}'`
      [ -z "$lm_lock_config" ] && continue
      lm_lock_status=`enstore lib --status  $libman |
	$AWK -F: '/LM state/ {match($2, ".*(unlocked|ignore|pause|noread|nowrite|broken).*", a); print a[1]}'`
      [ -z "$lm_lock_status" ] && continue
      if [ "$lm_lock_status" != "$lm_lock_config" ] &&
	 [ "$lm_lock_status" != ignore -o "$lm_lock_config" = locked ] &&
	 [ "$lm_lock_status" != pause  -o \( "$lm_lock_config" != noread -a "$lm_lock_config" != nowrite \) ]
      then
	 msg="LM $libman, status ($lm_lock_status) inconsistent with config ($lm_lock_config)"
	 logit "$msg"
	 alarm "$msg" W
      elif (( ! QUIET )); then
	 logit "LM $libman, status ($lm_lock_status) consistent with config ($lm_lock_config), ok"
      fi
    done
    ;;

esac

# check that we don't have too many processes running
NPROC=`$LS -d /proc/[1-9]* | $WC -l`
(( SERVER )) && let maxproc+=100
(( DCACHE )) && let maxproc+=100
if (( NPROC > maxproc )); then
   msg="$NPROC processes running. Way too many"
   logit "$msg"
   alarm "$msg"
elif (( ! QUIET )); then
   logit "$NPROC total processes, ok"
fi

# count the number of pnfsd processes running on server nodes
if (( SERVER )); then
   NPROC=`$PS --no-headers -C pnfsd | $WC -l`
   if (( NPROC > 0 )) && (( NPROC != npnfsd )); then
      msg="$NPROC pnfsd processes running. Should be $npnfsd"
      logit "$msg"
      alarm "$msg" W
   elif (( ! QUIET )); then
      logit "$NPROC pnfsd processes, ok"
   fi
fi

# check for web servers
case $node in
  # web servers should be running on these nodes (but no alarms right after a reboot)
  d0ensrv2|stkensrv2|cdfensrv2|fndca3a|stkendca3a)
    if (( ! REBOOT )) && [ -e /PRODUCTION ]; then
       if [ `$PS --no-headers -C httpd | $WC -l` -eq 0 ]; then
	  msg="httpd web server not running"
	  logit "$msg"
	  alarm "$msg"
       elif (( ! QUIET )); then
	  logit "httpd web server running, ok"
       fi
    fi
    if (( ! DCACHE )); then
       for i in $ENSTORE_DIR/src/*_cgi.py
       do
	  check_owner   /fnal/ups/prd/httpd/cgi-bin/enstore/`basename $i` wwwsrv www
	  right_file $i /fnal/ups/prd/httpd/cgi-bin/enstore		  0755
       done
    fi
    ;;
  # web servers should not be running on any other nodes
  *)
    if [ `$PS --no-headers -C httpd | $WC -l` -ne 0 ]; then
       msg="httpd web server running on illegal node"
       logit "$msg"
       alarm "$msg"
    elif (( ! QUIET )); then
       logit "httpd web server not running, ok"
    fi
    ;;
esac

# check that the keytabs are "correct"
$KEYTAB_CHECK `(( ALARM )) && $ECHO '-a'`  `(( QUIET )) && $ECHO '-q'`

# look for "lost" files - non-empty lost+found directories - in mounted local file systems
for dsk in `$AWK '$3 ~ /ext[23]/ {print $2}' /proc/mounts`
do
  # we should always find /, which is syntactically redundant
  [ $dsk = / ] && dsk=''
  if [ -d $dsk/lost+found ]; then
     if [ `$LS -1 $dsk/lost+found | $WC -l` -ne 0 ]; then
	siz=`$DU -ks $dsk/lost+found | $AWK '{print $1}'`
	msg="Files in $dsk/lost+found: $siz KB"
	logit "$msg"
	alarm "$msg" I
     elif (( ! QUIET )); then
	logit "$dsk/lost+found empty, ok"
     fi
  elif (( ! QUIET )); then
     msg="No lost+found for $dsk"
     logit "$msg"
     alarm "$msg" I
  fi
done

# look for local files hidden behind mount points where nfs file systems are not mounted
# subtract set of mounted nfs file systems from mount points where they might be mounted
fs_avail=`$AWK '$3 == "nfs" && $1 !~ /#.*/ {print $2}' /etc/fstab`
fs_mount=`$AWK '$3 == "nfs" {print $2}' /proc/mounts`
for dsk in `$ECHO $fs_avail $fs_mount $fs_mount | $TR " " "\n" | $SORT | $UNIQ -u`
do
  if [ -d $dsk ]; then
     if [ `$LS -A $dsk | $WC -l` -ne 0 ]; then
	siz=`$DU -ks $dsk | $AWK '{print $1}'`
	msg="Files hidden behind $dsk: $siz KB"
	logit "$msg"
	alarm "$msg" I
     elif (( ! QUIET )); then
	logit "$dsk empty, ok"
     fi
  elif (( ! QUIET )); then
     msg="No mount point for $dsk"
     logit "$msg"
     alarm "$msg" I
  fi
done

# skip IPMI checks for non-production nodes, and immediately after reboot
if (( ! REBOOT )) && [ -e /PRODUCTION ]; then

   if [ ${IPMISRV:-0} -eq 1 ]; then
      # we need ipmi device to make ipmisrv work
      check_mode	/dev/ipmi		0666 root
      # we need watchdog_reset file to make check_watchdog_reset work
      check_mode	/etc/watchdog_reset	0644 root
      # check that ipmisrv is running without watchdog timer
      if [ -S /dev/ipmi -a -r /etc/watchdog_reset ]; then
	 if [ `$ECHO "$PSfirst" | $GREP -c "ipmisrv NO_DOG"` -ne 1 ]; then
	    msg="ipmisrv NO_DOG is not running or misconfigured"
	    logit "$msg"
	    alarm "$msg"
	    NOIPMI=1
	 elif (( ! QUIET )); then
	    logit "ipmisrv NO_DOG running, ok"
	 fi
      else
	 NOIPMI=1
      fi
   elif [ ${IPMISRV:-1} -eq 0 ]; then
      # check that ipmisrv is not running
      if $ECHO "$PSfirst" | $GREP "ipmisrv" >/dev/null; then
	 msg="ipmisrv is running, but should not be running"
	 logit "$msg"
	 alarm "$msg"
	 NOIPMI=1
      elif (( ! QUIET )); then
	 logit "ipmisrv is not running, ok"
      fi
   fi

   if [ ${NOIPMI:-0} -ne 1 ]; then
      # check that watchdog timer action is to do nothing
      # try a few times until we read something
      #let try=3
      #while [ $((try-=1)) -ge 0 ]
      for (( try=3; try; try-=1 ))
      do
	ACTION=`$IPMI_DIR/dogread | $AWK '/^Actions:/ {print $2}'`
	if [ -n "${ACTION:-}" ]; then
	   break
	fi
	$SLEEP $((8>>try))
      done
      current=0
      if [ -z "${ACTION:-}" ]; then
	 if [ -r /tmp/watchdog-action-null ]; then
	    current=$(</tmp/watchdog-action-null)
	 fi
	 $ECHO $((++current)) > /tmp/watchdog-action-null
	 msg="watchdog action read failed $current times consecutively"
	 logit "$msg"
	 if (( ALARM )); then
	    complain=3
	    # decreasing notification rate (Fibonacci wise)
	    fminus1=$complain
	    until (( complain >= current )); do
	      fminus2=$fminus1
	      fminus1=$complain
	      complain=$((fminus2 + fminus1))
	    done
	    if (( complain == current )); then
	       enstore alarm --raise --severity "A" --root-error "$msg"
	    fi
	 fi
      elif [ "$ACTION" != "00" ]; then
	 msg="watchdog action is ${ACTION:-NULL} - should be 00"
	 logit "$msg"
	 alarm "$msg"
	 # disable the action
	 $IPMI_DIR/dogdisarm
      elif (( ! QUIET )); then
	 logit "watchdog action is $ACTION, ok"
      fi
      (( current == 0 )) && $RM -f /tmp/watchdog-action-null
   fi

fi

# scan open files and check if allowed
$SORT $netscan_n1 $netscan_n2 | $UNIQ -d | while read command pid rest
do
    [ $pid = "PID" ] && continue
    if $ECHO $rest | $GREP LISTEN >/dev/null; then
       allow LISTEN
    elif $ECHO $rest | $EGREP 'UDP|TCP' >/dev/null; then
       if (( ! QUIET )); then
	  logit "Ignoring open connection $command $pid $rest ..."
       fi
    fi
done

# once a day, check for core files in unusual places.
#CORE=`slocate -r '/core\.[1-9][0-9]*$'`

# tasks that go over network. Can hang sometimes. Do this last.

# reduce load on base nodes by doing this less frequently
# when invoked by cron, 4x a day, or after reboot,
# check that farmlets match
if (( ! (uptime % 25) )) && [ $gang != rip ]; then
   if (( ALARM )); then
     msg="`$FARMLETS -a 2>&1`"
   else
     msg="`$FARMLETS 2>&1`"
   fi
   if (( $? )); then
      logit "$msg"
   elif (( ! QUIET )); then
      logit "$msg"
   fi
fi

# if we're not in /etc/cron.d, and invoked by cron, create us there
if [ -e /PRODUCTION -a ! -r /etc/cron.d/netscan ]; then
   (( CROND )) && $ECHO "7,22,37,52 * * * * root /home/enstore/enstore/sbin/netscan -a -c -q >/dev/null 2>/dev/null" > /etc/cron.d/netscan
fi

# if we're still in the root crontab, remove us
if [ -e /PRODUCTION -a -r /var/spool/cron/root ]; then
   if $GREP -v '^#' /var/spool/cron/root | $GREP "netscan -a -q" >/dev/null; then
      $CRONTAB -l | $TAIL -$((`$CRONTAB -l | $WC -l`-3)) | $SED '/netscan -a -q/ s/^/#/' > /tmp/crontab.root
      $CRONTAB /tmp/crontab.root
   fi
fi

logit "netscan finished"
$RM -fr $ACTIVE
