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.

317 lines
9.2 KiB

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