2016-06-15 13:50:56 +02:00
|
|
|
// Copyright (c) 2012-2014 Jeremy Latt
|
|
|
|
// Copyright (c) 2016- Daniel Oaks <daniel@danieloaks.net>
|
|
|
|
// released under the MIT license
|
|
|
|
|
2012-04-07 20:44:59 +02:00
|
|
|
package irc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
2012-12-09 07:54:58 +01:00
|
|
|
"strings"
|
2012-04-07 20:44:59 +02:00
|
|
|
)
|
|
|
|
|
2014-03-09 21:45:36 +01:00
|
|
|
func IPString(addr net.Addr) Name {
|
2012-12-09 07:54:58 +01:00
|
|
|
addrStr := addr.String()
|
|
|
|
ipaddr, _, err := net.SplitHostPort(addrStr)
|
|
|
|
if err != nil {
|
2014-03-09 21:45:36 +01:00
|
|
|
return Name(addrStr)
|
2012-12-09 07:54:58 +01:00
|
|
|
}
|
2014-03-09 21:45:36 +01:00
|
|
|
return Name(ipaddr)
|
2014-02-13 22:19:26 +01:00
|
|
|
}
|
|
|
|
|
2014-03-09 21:45:36 +01:00
|
|
|
func AddrLookupHostname(addr net.Addr) Name {
|
2014-02-13 22:19:26 +01:00
|
|
|
return LookupHostname(IPString(addr))
|
2014-02-11 04:39:53 +01:00
|
|
|
}
|
|
|
|
|
2014-03-09 21:45:36 +01:00
|
|
|
func LookupHostname(addr Name) Name {
|
|
|
|
names, err := net.LookupAddr(addr.String())
|
2012-12-09 07:54:58 +01:00
|
|
|
if err != nil {
|
2014-03-09 21:45:36 +01:00
|
|
|
return Name(addr)
|
2012-12-09 07:54:58 +01:00
|
|
|
}
|
2014-02-14 03:59:45 +01:00
|
|
|
|
|
|
|
hostname := strings.TrimSuffix(names[0], ".")
|
2014-03-09 21:45:36 +01:00
|
|
|
return Name(hostname)
|
2012-12-09 07:54:58 +01:00
|
|
|
}
|
2016-04-21 02:48:15 +02:00
|
|
|
|
|
|
|
var allowedHostnameChars = "abcdefghijklmnopqrstuvwxyz1234567890-."
|
|
|
|
|
|
|
|
func IsHostname(name string) bool {
|
|
|
|
// IRC hostnames specifically require a period
|
|
|
|
if !strings.Contains(name, ".") || len(name) < 1 || len(name) > 253 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// ensure each part of hostname is valid
|
|
|
|
for _, part := range strings.Split(name, ".") {
|
|
|
|
if len(part) < 1 || len(part) > 63 || strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ensure all chars of hostname are valid
|
|
|
|
for _, char := range strings.Split(strings.ToLower(name), "") {
|
|
|
|
if !strings.Contains(allowedHostnameChars, char) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|