You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

net.go 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2016 Daniel Oaks <daniel@danieloaks.net>
  3. // released under the MIT license
  4. package irc
  5. import (
  6. "net"
  7. "strings"
  8. )
  9. // IPString returns a simple IP string from the given net.Addr.
  10. func IPString(addr net.Addr) string {
  11. addrStr := addr.String()
  12. ipaddr, _, err := net.SplitHostPort(addrStr)
  13. //TODO(dan): Why is this needed, does this happen?
  14. if err != nil {
  15. return addrStr
  16. }
  17. return ipaddr
  18. }
  19. // AddrLookupHostname returns the hostname (if possible) or address for the given `net.Addr`.
  20. func AddrLookupHostname(addr net.Addr) string {
  21. return LookupHostname(IPString(addr))
  22. }
  23. // LookupHostname returns the hostname for `addr` if it has one. Otherwise, just returns `addr`.
  24. func LookupHostname(addr string) string {
  25. names, err := net.LookupAddr(addr)
  26. if err != nil || len(names) < 1 || !IsHostname(names[0]) {
  27. // return original address if no hostname found
  28. if len(addr) > 0 && addr[0] == ':' {
  29. // fix for IPv6 hostnames (so they don't start with a colon), same as all other IRCds
  30. addr = "0" + addr
  31. }
  32. return addr
  33. }
  34. return names[0]
  35. }
  36. var allowedHostnameChars = "abcdefghijklmnopqrstuvwxyz1234567890-."
  37. // IsHostname returns whether we consider `name` a valid hostname.
  38. func IsHostname(name string) bool {
  39. // IRC hostnames specifically require a period
  40. if !strings.Contains(name, ".") || len(name) < 1 || len(name) > 253 {
  41. return false
  42. }
  43. // ensure each part of hostname is valid
  44. for _, part := range strings.Split(name, ".") {
  45. if len(part) < 1 || len(part) > 63 || strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  46. return false
  47. }
  48. }
  49. // ensure all chars of hostname are valid
  50. for _, char := range strings.Split(strings.ToLower(name), "") {
  51. if !strings.Contains(allowedHostnameChars, char) {
  52. return false
  53. }
  54. }
  55. return true
  56. }