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.

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