#!/bin/ksh
#
# X11 MIT-MAGIC-COOKIE to SUN-DES-1 auth. 
# this script switched the current Xservers authentification 
# (usually MIT-MAGIC-COOKIE-1) to SUN-DES-1.
# Requirements:
# - Solaris/Linux/AIX running as NIS+ client (YP/LDAP not supported yet)
# - user must have proper credentials
# - script must be able to "guess" the UID of the Xserver
# Advantages:
# User may allow other users to gain access via
# % xhost +jigsaw@
# instead of moving 128bit cookies
#
# Written by roland.mainz@informatik.med.uni-giessen.de

export PATH=/usr/xpg4/bin:/usr/bin:/usr/dt/bin:/usr/openwin/bin # force POSIX binaries

# get full qualified domain name
getFQDN()
{
    getent hosts ${1} | awk "{print \$2}" - 
}

HOSTNAME=$(hostname)
FQDN=$(getFQDN $HOSTNAME)

user2netname()
{
    UID=$(id -u $1)
    DOMAINNAME=$(domainname)
    if [ $UID != 0 ] ; then
        netname=unix.$UID@$DOMAINNAME
    else
        netname=unix.$HOSTNAME@$DOMAINNAME
    fi

    # BUG: SecureRPC isn't limited to NIS+ 
    #      (but there is no "getent publickey ...")...
    if [ "`nismatch "auth_name=$netname" cred.org_dir`" != "" ] ; then
        echo "$netname"
    else
        echo "user has no entry in cred.org_dir"
        return 1
    fi
    
    return 0
}    


# todo: using /proc may be easier
getUserOfPID()
{
    pid=$1
    ps -p $pid -o user,pid | fgrep $pid | awk "{print \$1}" - 
}

# be sure that DISPLAY contains the host name
# BUG: this does _not_ catch non-tcp connections (like DECnet).
# BUG: this may not work with IPv6 addresses
displayhost=$(echo $DISPLAY | cut -f 1,1 -d ':')
displaynum=$(echo $DISPLAY | cut -f 2,2 -d ':' | cut -f 1,1 -d '.')
if [ "$displayhost" == "" -o "$displayhost" == "localhost" ] ; then
    # fix DISPLAY
    export DISPLAY="${FQDN}${DISPLAY}"
fi

# get X server user
# this may fail if user isn't local
xpid=$(pgrep -f ".*X.* :$displaynum*")

if [ "$xpid" = "" ] ; then
    echo "couldn't obtain X server PID"
    exit 1
fi

    
PRINCIPAL=$(user2netname `getUserOfPID $xpid` || (echo "netname not found"; exit 1))


# grant acceess for user
xhost +$LOGNAME@
# grant access for user root (a bug in /usr/dt/bin/dtaction requires this)
xhost +$(user2netname root)

# remove old MIT-MAGIC-COOKIES and insert SUN-DES-1 cookies
# Users ~/.Xauthority _must_ be changed in _one_ step to avoid
# possible race conditions...
(echo "\
    remove $HOSTNAME/unix:$displaynum \n\
    remove $FQDN:$displaynum \n\
    add $HOSTNAME/unix:$displaynum SUN-DES-1 $PRINCIPAL \n\
    add $FQDN:$displaynum SUN-DES-1 $PRINCIPAL\n"
) | xauth source -

exit 0
# EOF.

