#
#	Split User-Name in NAI format (RFC 4282) into components
#
#  This policy writes the Username and Domain portions of the
#  NAI into the Stripped-User-Name and Stripped-User-Domain
#  attributes.
#
#  The regular expression to do this is not strictly compliant
#  with the standard, but it is not possible to write a
#  compliant regexp without perl style regular expressions (or
#  at least not a legible one).
#
nai_regexp = '^([^@]*)(@([-[:alnum:]]+\.[-[:alnum:].]+))?$'

split_username_nai {
	if (&User-Name && (&User-Name =~ /${policy.nai_regexp}/)) {
		update request {
			&Stripped-User-Name := "%{1}"
		}
		
		# Only add the Stripped-User-Domain attribute if
		# we have a domain. This means presence checks
		# for Stripped-User-Domain work.
		if ("%{3}" != '') {
			update request {
				&Stripped-User-Domain = "%{3}"
			}
		}

		# If any of the expansions result in a null
		# string, the update section may return
		# something other than updated...
		updated
	}
	else {
		noop
	}
}

#
#  If called in post-proxy we modify the proxy-reply message
#
split_username_nai.post-proxy {
	if (&proxy-reply:User-Name && (&proxy-reply:User-Name =~ /${policy.nai_regexp}/)) {
		update proxy-reply {
			&Stripped-User-Name := "%{1}"
		}
		
		# Only add the Stripped-User-Domain attribute if
		# we have a domain. This means presence checks
		# for Stripped-User-Domain work.
		if ("%{3}" != '') {
			update proxy-reply {
				&Stripped-User-Domain = "%{3}"
			}
		}
		updated
	}
	else {
		noop
	}
}

#
#  Normalize the MAC Addresses in the Calling/Called-Station-Id
#
mac-addr-regexp = '([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})'

#
#  Add "rewrite_called_station_id" in the "authorize" and
#  "preacct" sections.
#
#  Makes Called-Station-ID conform to what RFC3580 says should
#  be provided by 802.1X authenticators.
#
rewrite_called_station_id {
	if (&Called-Station-Id && (&Called-Station-Id =~ /^${policy.mac-addr-regexp}([^0-9a-f](.+))?$/i)) {
		update request {
			&Called-Station-Id := "%{toupper:%{1}-%{2}-%{3}-%{4}-%{5}-%{6}}"
		}

		# SSID component?
		if ("%{8}") {
			update request {
				&Called-Station-SSID := "%{8}"
			}
		}
		updated
	}
	else {
		noop
	}
}

#
#  Add "rewrite_calling_station_id" in the "authorize" and
#  "preacct" sections.
#
#  Makes Calling-Station-ID conform to what RFC3580 says should
#  be provided by 802.1X authenticators.
#
rewrite_calling_station_id {
	if (&Calling-Station-Id && (&Calling-Station-Id =~ /^${policy.mac-addr-regexp}$/i)) {
		update request {
			&Calling-Station-Id := "%{toupper:%{1}-%{2}-%{3}-%{4}-%{5}-%{6}}"
		}
		updated
	}
	else {
		noop
	}
}

