#
# Zmailer Copyright 1988 by Rayan S. Zachariassen, all rights reserved
# Zmailer Copyright 1992-1997 by Matti Aarnio
#
# $Id: canonicalize.cf,v 1.1.1.1 1998/02/10 21:01:44 mea Exp $
#
# Alexis Yushin, NLnet Development, 1997
#
# Name Canonicalization
#
provide canonicalize

#
# Canonicalizes an RFC822/RFC976 address.
#
# Returns RFC822 focused and canonicalized address.
#
canonicalize (address) {
	address="$(dequote \"$address\")"
#
# We need string shift to detect '|' because '|' is not RFC822 special
#
	ssift "$address" in
	((\|.+)|(/.+)|(:include:.+))		# unqouted pipes and files
		echo "$address"			# pass through
		return
		;;
	tfiss

	tsift "$address" in
	((<>)|(:;))
		address="@"			# special case
		break
		;;
	(.*)<@(.*)>(.*)				# defocus
		address="\1@\2\3"
		continue
		;;
#
# RFC822 source routing
#
# @host3,@host2,@host1:user@host
#
	(@.+),(.+)				# RFC822 source routing
		address="\1:\2"			# change all "," to ":"
		continue
		;;
	(@.+):(.+:.+)
		address="\1,\2"			# undo all but the last one
		continue
		;;
	@([^,:]+)([,:].+)			# route-addr
		address="<@$(canonical \"\1\")>\2\3"
		break
		;;
#
# RFC822 addr-spec (localpart@domain) and variations
#
	(.*)::(.*)
		address="\2@\1"			# turn into localpart@domain
		continue
		;;
	(.*)@([^@]*.uucp)			# addr-spec host.uucp
		address="\1<@\2>"		# comment out if you want
		break				# canonical uucp names
		;;
	(.*)@([^@]*)				# addr-spec, rightmost '@'
		address="\1<@$(canonical \"\2\")>"
		break
		;;
#
# By this time localpart only
#
# RFC976 processing: '!' and '%' kludges
#
# a!b!c -> b!c@a
# a!b%c -> b%c@a
# a%b!c -> a!c@b	leading "%" has more priority than "!"
# a%b%c -> a%b@c
#
# We do not want people to start relying on this really weird routing.
# Comment it out if you do.
#
##	([^!%]*)%([^!%]*)\.([^!%]*)!(.*)	# very unusual case
##		canonicalize "\1!\4@\2.\3"
##		return
##		;;
##	([^!%]*)%([^.!%]*)!(.*)			# very unusual case (uucp node)
##		canonicalize "\1!\3@\2"
##		return
##		;;
	\[(.*)\]!(.*)				# leftmost '!', domain-literal
		canonicalize "\2@\[\1\]"
		return
		;;
	([^!.]*)!(.*)				# leftmost '!', pure uucp
		canonicalize "\2@\1.uucp"
		return
		;;
	([^!]*)!(.*)				# leftmost '!', domain uucp
		canonicalize "\2@\1"
		return
		;;
	(.*)%([^%]*)				# rightmost '%', source routing
		canonicalize "\1@\2"
		return
		;;
	tfist

	echo "$address"
}

#
# Returns canonical name of the given host
#
canonical (host) {
	local tmp
	tmp="$(deliver \"$host\")" || tmp="$(canon \"$host\")" || tmp="$host"
	echo "$tmp"
}

#
# Safeguard if canon() is not there
#
case "$(type canon)" in
*"not found")
	canon () { echo "$@" } ;;
esac
#
# Safeguard if deliver() is not there
#
case "$(type deliver)" in
*"not found")
	deliver () { return 1 } ;;
esac
