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.

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