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.

311 lines
9.0 KiB

9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. // Modified for Tendermint
  2. // Originally Copyright (c) 2013-2014 Conformal Systems LLC.
  3. // https://github.com/conformal/btcd/blob/master/LICENSE
  4. package p2p
  5. import (
  6. "encoding/hex"
  7. "flag"
  8. "fmt"
  9. "net"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/pkg/errors"
  14. cmn "github.com/tendermint/tmlibs/common"
  15. )
  16. // NetAddress defines information about a peer on the network
  17. // including its ID, IP address, and port.
  18. type NetAddress struct {
  19. ID ID
  20. IP net.IP
  21. Port uint16
  22. str string
  23. }
  24. // IDAddressString returns id@hostPort.
  25. func IDAddressString(id ID, hostPort string) string {
  26. return fmt.Sprintf("%s@%s", id, hostPort)
  27. }
  28. // NewNetAddress returns a new NetAddress using the provided TCP
  29. // address. When testing, other net.Addr (except TCP) will result in
  30. // using 0.0.0.0:0. When normal run, other net.Addr (except TCP) will
  31. // panic.
  32. // TODO: socks proxies?
  33. func NewNetAddress(id ID, addr net.Addr) *NetAddress {
  34. tcpAddr, ok := addr.(*net.TCPAddr)
  35. if !ok {
  36. if flag.Lookup("test.v") == nil { // normal run
  37. cmn.PanicSanity(cmn.Fmt("Only TCPAddrs are supported. Got: %v", addr))
  38. } else { // in testing
  39. netAddr := NewNetAddressIPPort(net.IP("0.0.0.0"), 0)
  40. netAddr.ID = id
  41. return netAddr
  42. }
  43. }
  44. ip := tcpAddr.IP
  45. port := uint16(tcpAddr.Port)
  46. na := NewNetAddressIPPort(ip, port)
  47. na.ID = id
  48. return na
  49. }
  50. // NewNetAddressString returns a new NetAddress using the provided address in
  51. // the form of "ID@IP:Port".
  52. // Also resolves the host if host is not an IP.
  53. func NewNetAddressString(addr string) (*NetAddress, error) {
  54. spl := strings.Split(addr, "@")
  55. if len(spl) < 2 {
  56. return nil, fmt.Errorf("Address (%s) does not contain ID", addr)
  57. }
  58. return NewNetAddressStringWithOptionalID(addr)
  59. }
  60. // NewNetAddressStringWithOptionalID returns a new NetAddress using the
  61. // provided address in the form of "ID@IP:Port", where the ID is optional.
  62. // Also resolves the host if host is not an IP.
  63. func NewNetAddressStringWithOptionalID(addr string) (*NetAddress, error) {
  64. addrWithoutProtocol := removeProtocolIfDefined(addr)
  65. var id ID
  66. spl := strings.Split(addrWithoutProtocol, "@")
  67. if len(spl) == 2 {
  68. idStr := spl[0]
  69. idBytes, err := hex.DecodeString(idStr)
  70. if err != nil {
  71. return nil, errors.Wrapf(err, "Address (%s) contains invalid ID", addrWithoutProtocol)
  72. }
  73. if len(idBytes) != IDByteLength {
  74. return nil, fmt.Errorf("Address (%s) contains ID of invalid length (%d). Should be %d hex-encoded bytes",
  75. addrWithoutProtocol, len(idBytes), IDByteLength)
  76. }
  77. id, addrWithoutProtocol = ID(idStr), spl[1]
  78. }
  79. host, portStr, err := net.SplitHostPort(addrWithoutProtocol)
  80. if err != nil {
  81. return nil, err
  82. }
  83. ip := net.ParseIP(host)
  84. if ip == nil {
  85. if len(host) > 0 {
  86. ips, err := net.LookupIP(host)
  87. if err != nil {
  88. return nil, err
  89. }
  90. ip = ips[0]
  91. }
  92. }
  93. port, err := strconv.ParseUint(portStr, 10, 16)
  94. if err != nil {
  95. return nil, err
  96. }
  97. na := NewNetAddressIPPort(ip, uint16(port))
  98. na.ID = id
  99. return na, nil
  100. }
  101. // NewNetAddressStrings returns an array of NetAddress'es build using
  102. // the provided strings.
  103. func NewNetAddressStrings(addrs []string) ([]*NetAddress, []error) {
  104. netAddrs := make([]*NetAddress, 0)
  105. errs := make([]error, 0)
  106. for _, addr := range addrs {
  107. netAddr, err := NewNetAddressString(addr)
  108. if err != nil {
  109. errs = append(errs, fmt.Errorf("Error in address %s: %v", addr, err))
  110. } else {
  111. netAddrs = append(netAddrs, netAddr)
  112. }
  113. }
  114. return netAddrs, errs
  115. }
  116. // NewNetAddressIPPort returns a new NetAddress using the provided IP
  117. // and port number.
  118. func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress {
  119. return &NetAddress{
  120. IP: ip,
  121. Port: port,
  122. }
  123. }
  124. // Equals reports whether na and other are the same addresses,
  125. // including their ID, IP, and Port.
  126. func (na *NetAddress) Equals(other interface{}) bool {
  127. if o, ok := other.(*NetAddress); ok {
  128. return na.String() == o.String()
  129. }
  130. return false
  131. }
  132. // Same returns true is na has the same non-empty ID or DialString as other.
  133. func (na *NetAddress) Same(other interface{}) bool {
  134. if o, ok := other.(*NetAddress); ok {
  135. if na.DialString() == o.DialString() {
  136. return true
  137. }
  138. if na.ID != "" && na.ID == o.ID {
  139. return true
  140. }
  141. }
  142. return false
  143. }
  144. // String representation: <ID>@<IP>:<PORT>
  145. func (na *NetAddress) String() string {
  146. if na.str == "" {
  147. addrStr := na.DialString()
  148. if na.ID != "" {
  149. addrStr = IDAddressString(na.ID, addrStr)
  150. }
  151. na.str = addrStr
  152. }
  153. return na.str
  154. }
  155. func (na *NetAddress) DialString() string {
  156. return net.JoinHostPort(
  157. na.IP.String(),
  158. strconv.FormatUint(uint64(na.Port), 10),
  159. )
  160. }
  161. // Dial calls net.Dial on the address.
  162. func (na *NetAddress) Dial() (net.Conn, error) {
  163. conn, err := net.Dial("tcp", na.DialString())
  164. if err != nil {
  165. return nil, err
  166. }
  167. return conn, nil
  168. }
  169. // DialTimeout calls net.DialTimeout on the address.
  170. func (na *NetAddress) DialTimeout(timeout time.Duration) (net.Conn, error) {
  171. conn, err := net.DialTimeout("tcp", na.DialString(), timeout)
  172. if err != nil {
  173. return nil, err
  174. }
  175. return conn, nil
  176. }
  177. // Routable returns true if the address is routable.
  178. func (na *NetAddress) Routable() bool {
  179. // TODO(oga) bitcoind doesn't include RFC3849 here, but should we?
  180. return na.Valid() && !(na.RFC1918() || na.RFC3927() || na.RFC4862() ||
  181. na.RFC4193() || na.RFC4843() || na.Local())
  182. }
  183. // For IPv4 these are either a 0 or all bits set address. For IPv6 a zero
  184. // address or one that matches the RFC3849 documentation address format.
  185. func (na *NetAddress) Valid() bool {
  186. return na.IP != nil && !(na.IP.IsUnspecified() || na.RFC3849() ||
  187. na.IP.Equal(net.IPv4bcast))
  188. }
  189. // Local returns true if it is a local address.
  190. func (na *NetAddress) Local() bool {
  191. return na.IP.IsLoopback() || zero4.Contains(na.IP)
  192. }
  193. // ReachabilityTo checks whenever o can be reached from na.
  194. func (na *NetAddress) ReachabilityTo(o *NetAddress) int {
  195. const (
  196. Unreachable = 0
  197. Default = iota
  198. Teredo
  199. Ipv6_weak
  200. Ipv4
  201. Ipv6_strong
  202. )
  203. if !na.Routable() {
  204. return Unreachable
  205. } else if na.RFC4380() {
  206. if !o.Routable() {
  207. return Default
  208. } else if o.RFC4380() {
  209. return Teredo
  210. } else if o.IP.To4() != nil {
  211. return Ipv4
  212. } else { // ipv6
  213. return Ipv6_weak
  214. }
  215. } else if na.IP.To4() != nil {
  216. if o.Routable() && o.IP.To4() != nil {
  217. return Ipv4
  218. }
  219. return Default
  220. } else /* ipv6 */ {
  221. var tunnelled bool
  222. // Is our v6 is tunnelled?
  223. if o.RFC3964() || o.RFC6052() || o.RFC6145() {
  224. tunnelled = true
  225. }
  226. if !o.Routable() {
  227. return Default
  228. } else if o.RFC4380() {
  229. return Teredo
  230. } else if o.IP.To4() != nil {
  231. return Ipv4
  232. } else if tunnelled {
  233. // only prioritise ipv6 if we aren't tunnelling it.
  234. return Ipv6_weak
  235. }
  236. return Ipv6_strong
  237. }
  238. }
  239. // RFC1918: IPv4 Private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12)
  240. // RFC3849: IPv6 Documentation address (2001:0DB8::/32)
  241. // RFC3927: IPv4 Autoconfig (169.254.0.0/16)
  242. // RFC3964: IPv6 6to4 (2002::/16)
  243. // RFC4193: IPv6 unique local (FC00::/7)
  244. // RFC4380: IPv6 Teredo tunneling (2001::/32)
  245. // RFC4843: IPv6 ORCHID: (2001:10::/28)
  246. // RFC4862: IPv6 Autoconfig (FE80::/64)
  247. // RFC6052: IPv6 well known prefix (64:FF9B::/96)
  248. // RFC6145: IPv6 IPv4 translated address ::FFFF:0:0:0/96
  249. var rfc1918_10 = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(8, 32)}
  250. var rfc1918_192 = net.IPNet{IP: net.ParseIP("192.168.0.0"), Mask: net.CIDRMask(16, 32)}
  251. var rfc1918_172 = net.IPNet{IP: net.ParseIP("172.16.0.0"), Mask: net.CIDRMask(12, 32)}
  252. var rfc3849 = net.IPNet{IP: net.ParseIP("2001:0DB8::"), Mask: net.CIDRMask(32, 128)}
  253. var rfc3927 = net.IPNet{IP: net.ParseIP("169.254.0.0"), Mask: net.CIDRMask(16, 32)}
  254. var rfc3964 = net.IPNet{IP: net.ParseIP("2002::"), Mask: net.CIDRMask(16, 128)}
  255. var rfc4193 = net.IPNet{IP: net.ParseIP("FC00::"), Mask: net.CIDRMask(7, 128)}
  256. var rfc4380 = net.IPNet{IP: net.ParseIP("2001::"), Mask: net.CIDRMask(32, 128)}
  257. var rfc4843 = net.IPNet{IP: net.ParseIP("2001:10::"), Mask: net.CIDRMask(28, 128)}
  258. var rfc4862 = net.IPNet{IP: net.ParseIP("FE80::"), Mask: net.CIDRMask(64, 128)}
  259. var rfc6052 = net.IPNet{IP: net.ParseIP("64:FF9B::"), Mask: net.CIDRMask(96, 128)}
  260. var rfc6145 = net.IPNet{IP: net.ParseIP("::FFFF:0:0:0"), Mask: net.CIDRMask(96, 128)}
  261. var zero4 = net.IPNet{IP: net.ParseIP("0.0.0.0"), Mask: net.CIDRMask(8, 32)}
  262. func (na *NetAddress) RFC1918() bool {
  263. return rfc1918_10.Contains(na.IP) ||
  264. rfc1918_192.Contains(na.IP) ||
  265. rfc1918_172.Contains(na.IP)
  266. }
  267. func (na *NetAddress) RFC3849() bool { return rfc3849.Contains(na.IP) }
  268. func (na *NetAddress) RFC3927() bool { return rfc3927.Contains(na.IP) }
  269. func (na *NetAddress) RFC3964() bool { return rfc3964.Contains(na.IP) }
  270. func (na *NetAddress) RFC4193() bool { return rfc4193.Contains(na.IP) }
  271. func (na *NetAddress) RFC4380() bool { return rfc4380.Contains(na.IP) }
  272. func (na *NetAddress) RFC4843() bool { return rfc4843.Contains(na.IP) }
  273. func (na *NetAddress) RFC4862() bool { return rfc4862.Contains(na.IP) }
  274. func (na *NetAddress) RFC6052() bool { return rfc6052.Contains(na.IP) }
  275. func (na *NetAddress) RFC6145() bool { return rfc6145.Contains(na.IP) }
  276. func removeProtocolIfDefined(addr string) string {
  277. if strings.Contains(addr, "://") {
  278. return strings.Split(addr, "://")[1]
  279. }
  280. return addr
  281. }