#@package: rfc931 rfc931

#
# Copyright (C) 1992-1997 NeoSoft.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted, provided
# that the above copyright notice appear in all copies.  NeoSoft makes no 
# representations about the suitability of this software for any purpose.
# It is provided "as is" without express or implied warranty.

#
# Perform an rfc931 authentication request on the socket bound to the
# specified filehandle.  Returns username and hostname if found,
# username and ip if no hostname is found, or an empty string if
# the remote site isn't running an rfc931 authentication server.
#
# $Id: rfc931.tcl,v 1.1.1.1 1999/03/31 20:34:40 damon Exp $
#

proc rfc931 {fp resultVar} {
    upvar $resultVar result

    lassign [fstat $fp localhost] localAddr localPort
    lassign [fstat $fp remotehost] remoteAddr remotePort

    if {[catch {lassign [server_open -myip $localAddr $remoteAddr ident] readIdent writeIdent} result] == 1} {
	global errorCode errorInfo
	if {[lindex $errorCode 1] == "ECONNREFUSED"} {return 0}
	error $result $errorInfo $errorCode
    }
    set remoteName [server_info address_name $remoteAddr]

    puts $writeIdent "$remotePort,$localPort\r"
    close $writeIdent

    if {[gets $readIdent authLine] < 0} {
	close $readIdent
	set result "read failed"
	return 0
    }

    set result $authLine
    if {[scan $authLine {%u , %u : USERID :%*[^:]:%s} remote local user] != 3} {
	close $readIdent
	return 0
    }

    if {$remote != $remotePort || $local != $localPort} {
	close $readIdent
	set result "ports didn't match"
	return 0
    }

    if {[cindex $user end] == "\r"} {
	set user [crange $user 0 end-1]
    }
    set result $user@$remoteName
    close $readIdent
    return 1
}
