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.

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