#!/usr/bin/ksh -
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# bos720 src/bos/usr/sbin/sliplogin/slipcall 1.7 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 1994,2002 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# @(#)35  1.7  src/bos/usr/sbin/sliplogin/slipcall, cmdnet, bos720 7/31/02 15:25:16
# 
# COMPONENT_NAME: CMDNET
# 
# FUNCTIONS: 
#
# ORIGINS: 27
#
# (C) COPYRIGHT International Business Machines Corp. 1994
# All Rights Reserved
# Licensed Materials - Property of IBM
#
# US Government Users Restricted Rights - Use, duplication or
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
#
# A sample shell front-end for slattach when calling a remote system which
# dynamically assigns IP addresses (e.g., uses sliplogin).  The local
# and remote IP addresses to use which are displayed by the remote service 
# after login has completed.  These addresses are used by this script to 
# configure the appropriate slip network interface on the local (calling) 
# system.  Only a privileged user may modify the network interface
# structures.  This script will not update the slip interface appropriately
# if invoked by a non-root user.

usage(){
	echo "Usage: slipcall [phonenumber] ttyx speed username password"
	echo
	echo "Where	phonenumber is an optional phone number"
	echo "	ttyx is a valid tty name"
	echo "	speed represents a valid baud rate"
	echo "	username is the username to login as on the slip server"
	echo "	password is the password to use"
	exit
}

umask 077
unset PATH
export PATH=/usr/bin:/etc:/usr/sbin:/usr/ucb

DIAL=0
if [ $# -eq 5 ] ; then
	DIAL=1
	NUMBER=$1
	shift
elif [ $# -ne 4 ] ; then
	echo "You didn't specify the proper number of arguments."
	usage
fi

basename $1 | grep "tty[0-9]" 2>&1 > /dev/null || usage
TTYNUM=`basename $1 | sed "s/tty//"`
echo tty number is $TTYNUM

if [ \( "$2" != "300" \) -a \( "$2" != "600" \) -a \( "$2" != "1200" \) \
  -a \( "$2" != "2400" \) -a \( "$2" != "4800" \) -a \( "$2" != "9600" \) \
  -a \( "$2" != "19200" \) -a \( "$2" != "38400" \)  ] ; then
	echo "An unknown baud rate was specified."
	usage
else
	SPEED=$2
fi

USER=$3
PASSWD=$4

EXT=`date +"%T"`
SAVEFILE=slipmon.${EXT}
SAVEDIR=/tmp/$SAVEFILE

typeset TMPDIR=${TMPDIR:-/tmp}/${0##*/}.$$
typeset rc tmp

[[ ! -w ${TMPDIR%/*} ]] && {
	# Don't loop forever if our parent directory is not
	# writable.
	print -u2 "${0##*/}: could not write to directory \"${TMPDIR%/*}\""
	exit 1
}
while ! mkdir -m 0700 $TMPDIR 2>/dev/null ; do
	TMPDIR=${SAVEDIR%.*}.$(( $$ + $RANDOM ))
done

function cleanup {
	cd /
	/bin/rm -rf $TMPDIR 2>/dev/null
}
trap 'rc=$?; trap "" EXIT; cleanup; exit $rc' INT TERM QUIT HUP
trap 'cleanup; exit' EXIT

#
# To create a logfile in /tmp (or other directory with 1777
# permissions), create a hard link from $TMPDIR.  (Make sure that
# $TMPDIR is on the same partition as the log file.)
#

typeset LOGDIR LOGFILE LOG

LOGDIR=${TMPDIR%/*}
LOGFILE=$SAVEFILE
LOG=$LOGDIR/$LOGFILE
touch $TMPDIR/$LOGFILE
while ! ln -f $TMPDIR/$LOGFILE $LOG 2>/dev/null ; do
    LOG=$LOGDIR/${LOGFILE}_$(( $$ + $RANDOM ))
done
[[ $LOG != $LOGDIR/$LOGFILE ]] &&
    print "Possible attack on log file:\n$(ls -l $LOGDIR/$LOGFILE)"

print "Created logfile \"$LOG\""
print "Created logfile \"$LOG\"" > $LOG

# Pattern displayed after IP addresses
TRAILER=discipline

# Portion of login prompt to look for
LOGIN_PROMPT=ogin:

# Portion of password prompt to look for
PASS_PROMPT=word:

# Number of seconds to wait for slattach to complete the connection.
CONN_TIMEOUT=45

# The following two slattach dialing chats assume that the pattern reflected
# by the $TRAILER variable is displayed by the called system after the IP 
# addresses and netmask have been displayed.
if [ $DIAL -eq 0 ] ; then
	# Calling on a direct RS232 connection
	CHAT="\"\" \"\" $LOGIN_PROMPT $USER $PASS_PROMPT $PASSWD $TRAILER \"\""
else
	# Calling on a hayes compatible modem
	CHAT="\"\" AT OK ATDT${NUMBER} CONNECT \"\" $LOGIN_PROMPT $USER $PASS_PROMPT $PASSWD $TRAILER \"\""
fi

ifconfig sl${TTYNUM}
strinfo -m | grep "'slip'" || strload -m /usr/lib/drivers/slip
slattach tty${TTYNUM} $SPEED "$CHAT" 4 2>&1 | tee $TMPDIR/$LOGFILE &

echo "Slipcall waiting on slattach to connect..."
i=0; CONNECTED=0
while [ $i -le $CONN_TIMEOUT -a $CONNECTED -eq 0 ] ; do
	sleep 1
	if [ `ps -ef | grep -v grep | grep "slattach tty${TTYNUM} $SPEED" | \
		wc -l` -eq 0 ] ; then
		echo "Slattach terminated for some reason. The results of"
		echo "the login dialog can be found in the file $TMPDIR/$LOGFILE."
		echo "Slipcall is exiting."
		kill `ps | grep "tee.*$TMPDIR/$LOGFILE" | grep -v grep | \
			awk '{print $1}'`
		exit
	fi
	if grep "slattach.*onnect.*estab" $TMPDIR/$LOGFILE > /dev/null ; then
		CONNECTED=1;
	fi
	i=`expr $i + 1`
done
		
if [ $CONNECTED -eq 0 ] ; then
	echo "slipcall timed out while waiting for slattach to finish \
connecting. Exiting."
	echo "slattach may still be running."
	echo "slattach chat output was saved in $TMPDIR/$LOGFILE."
	kill `ps | grep "tee.*$TMPDIR/$LOGFILE" | grep -v grep | awk '{print $1}'`
	exit
fi

echo "Slattach has connected.  Deriving local and remote addresses..."

# This sample program assumes that when logging in to a slip server, 
# the addresses are displayed something like the following:
# "Called system's address is 123.123.123.123"
# "Calling system's address is 123.123.123.124"
RADDR=""
if grep "Called system" $TMPDIR/$LOGFILE > /dev/null ; then
	RADDR=`grep "Called system" $TMPDIR/$LOGFILE | \
		awk '{offset=match($0, "Called system.*") ; \
			remnant=substr($0, offset, RLENGTH); \
			offset=match(remnant,"([0-9]{1,3}\\\.){3}[0-9]{1,3}");\
			raddr=substr(remnant, offset, RLENGTH); print raddr }'`
fi

LADDR=""
if grep "Calling system" $TMPDIR/$LOGFILE > /dev/null ; then
	LADDR=`grep "Calling system" $TMPDIR/$LOGFILE | \
		awk '{offset=match($0, "Calling system.*") ; \
			remnant=substr($0, offset, RLENGTH); \
			offset=match(remnant,"([0-9]{1,3}\\\.){3}[0-9]{1,3}");\
			laddr=substr(remnant, offset, RLENGTH); print laddr }'`
fi

if [ \"$LADDR\" = \"\" -o \"$RADDR\" = \"\" ] ; then
	echo "Cannot parse assigned addresses from $TMPDIR/$LOGFILE.  Exiting."
	echo "slattach may still be running."
	echo "slattach chat output was saved in $TMPDIR/$LOGFILE."
	kill `ps | grep "tee.*$TMPDIR/$LOGFILE" | grep -v grep | awk '{print $1}'`
	exit
fi

# This assumes that the netmask value is prefaced by the string "netmask";
# e.g., Something like "The netmask is 0xffffff00" or "netmask = 255.255.255.0"
NETMASK=`grep "netmask" $TMPDIR/$LOGFILE | awk '{offset=match($0, "netmask.*") ; \
					remnant=substr($0, offset, RLENGTH); \
					offset=match(remnant, \
		"(0x([0-9|a-f]){1,8})|(([0-9]{1,3}\\\.){3}[0-9]{1,3})") ;\
					netmask=substr(remnant,offset,RLENGTH);\
					print netmask }'`

# Clean up any other slip interfaces which may have had this address but
# are no longer up and running.
IFLIST=`netstat -f inet -i |grep -v "<Link>" |awk '{print $1}' |grep -v Name`
for IFACE in $IFLIST ; do
	THISIF=`ifconfig $IFACE`
	THISIFADDR=`echo $THISIF | awk '{offset=match($0, \
					"([0-9]{1,3}\\\.){3}[0-9]{1,3}") ;\
					laddr=substr($0, offset, RLENGTH); \
					print laddr }'`

	THISIFRADDR=`echo $THISIF | awk '{offset=match($0, "->.*") ; \
			remnant=substr($0, offset, RLENGTH); \
			offset=match(remnant,"([0-9]{1,3}\\\.){3}[0-9]{1,3}");\
			raddr=substr(remnant, offset, RLENGTH); print raddr }'`

	FLAGS=`echo $THISIF | awk '{offset=match($0, "<.*>") ; \
					flags=substr($0, offset, RLENGTH); \
					print flags}'`

	if echo $IFACE | grep "sl[0-9]" > /dev/null; then
		if    [ "$IFACE" != "sl${TTYNUM}" -a \
			"$THISIFADDR" = "$LADDR" ] ; then

			if echo $FLAGS|grep -v "UP.*RUNNING" > /dev/null ; then
				ifconfig $IFACE delete $LADDR $THISIFRADDR up
			fi
		fi
	fi
done
ifconfig sl${TTYNUM} $LADDR $RADDR netmask $NETMASK up

echo IP address for local interface is $LADDR 
echo IP address for remote interface is $RADDR 
echo Network mask is $NETMASK
echo "Slip interface sl${TTYNUM} has been configured for these values."
echo "Slipcall terminating tee of $TMPDIR/$LOGFILE..."
kill `ps | grep "tee.*$TMPDIR/$LOGFILE"|grep -v grep| awk '{print $1}'` 2>/dev/null
rm -f $LOG
echo "slipcall completed."