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.

373 lines
11 KiB

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
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. "errors"
  8. "flag"
  9. "fmt"
  10. "net"
  11. "strconv"
  12. "strings"
  13. "time"
  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. Panics if ID is invalid.
  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("127.0.0.1"), 0)
  44. netAddr.ID = id
  45. return netAddr
  46. }
  47. }
  48. if err := validateID(id); err != nil {
  49. panic(fmt.Sprintf("Invalid ID %v: %v (addr: %v)", id, err, addr))
  50. }
  51. ip := tcpAddr.IP
  52. port := uint16(tcpAddr.Port)
  53. na := NewNetAddressIPPort(ip, port)
  54. na.ID = id
  55. return na
  56. }
  57. // NewNetAddressString returns a new NetAddress using the provided address in
  58. // the form of "ID@IP:Port".
  59. // Also resolves the host if host is not an IP.
  60. // Errors are of type ErrNetAddressXxx where Xxx is in (NoID, Invalid, Lookup)
  61. func NewNetAddressString(addr string) (*NetAddress, error) {
  62. addrWithoutProtocol := removeProtocolIfDefined(addr)
  63. spl := strings.Split(addrWithoutProtocol, "@")
  64. if len(spl) != 2 {
  65. return nil, ErrNetAddressNoID{addr}
  66. }
  67. // get ID
  68. if err := validateID(ID(spl[0])); err != nil {
  69. return nil, ErrNetAddressInvalid{addrWithoutProtocol, err}
  70. }
  71. var id ID
  72. id, addrWithoutProtocol = ID(spl[0]), spl[1]
  73. // get host and port
  74. host, portStr, err := net.SplitHostPort(addrWithoutProtocol)
  75. if err != nil {
  76. return nil, ErrNetAddressInvalid{addrWithoutProtocol, err}
  77. }
  78. if len(host) == 0 {
  79. return nil, ErrNetAddressInvalid{
  80. addrWithoutProtocol,
  81. errors.New("host is empty")}
  82. }
  83. ip := net.ParseIP(host)
  84. if ip == nil {
  85. ips, err := net.LookupIP(host)
  86. if err != nil {
  87. return nil, ErrNetAddressLookup{host, err}
  88. }
  89. ip = ips[0]
  90. }
  91. port, err := strconv.ParseUint(portStr, 10, 16)
  92. if err != nil {
  93. return nil, ErrNetAddressInvalid{portStr, err}
  94. }
  95. na := NewNetAddressIPPort(ip, uint16(port))
  96. na.ID = id
  97. return na, nil
  98. }
  99. // NewNetAddressStrings returns an array of NetAddress'es build using
  100. // the provided strings.
  101. func NewNetAddressStrings(addrs []string) ([]*NetAddress, []error) {
  102. netAddrs := make([]*NetAddress, 0)
  103. errs := make([]error, 0)
  104. for _, addr := range addrs {
  105. netAddr, err := NewNetAddressString(addr)
  106. if err != nil {
  107. errs = append(errs, err)
  108. } else {
  109. netAddrs = append(netAddrs, netAddr)
  110. }
  111. }
  112. return netAddrs, errs
  113. }
  114. // NewNetAddressIPPort returns a new NetAddress using the provided IP
  115. // and port number.
  116. func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress {
  117. return &NetAddress{
  118. IP: ip,
  119. Port: port,
  120. }
  121. }
  122. // Equals reports whether na and other are the same addresses,
  123. // including their ID, IP, and Port.
  124. func (na *NetAddress) Equals(other interface{}) bool {
  125. if o, ok := other.(*NetAddress); ok {
  126. return na.String() == o.String()
  127. }
  128. return false
  129. }
  130. // Same returns true is na has the same non-empty ID or DialString as other.
  131. func (na *NetAddress) Same(other interface{}) bool {
  132. if o, ok := other.(*NetAddress); ok {
  133. if na.DialString() == o.DialString() {
  134. return true
  135. }
  136. if na.ID != "" && na.ID == o.ID {
  137. return true
  138. }
  139. }
  140. return false
  141. }
  142. // String representation: <ID>@<IP>:<PORT>
  143. func (na *NetAddress) String() string {
  144. if na == nil {
  145. return "<nil-NetAddress>"
  146. }
  147. if na.str == "" {
  148. addrStr := na.DialString()
  149. if na.ID != "" {
  150. addrStr = IDAddressString(na.ID, addrStr)
  151. }
  152. na.str = addrStr
  153. }
  154. return na.str
  155. }
  156. func (na *NetAddress) DialString() string {
  157. if na == nil {
  158. return "<nil-NetAddress>"
  159. }
  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. if err := na.Valid(); err != nil {
  184. return false
  185. }
  186. // TODO(oga) bitcoind doesn't include RFC3849 here, but should we?
  187. return !(na.RFC1918() || na.RFC3927() || na.RFC4862() ||
  188. na.RFC4193() || na.RFC4843() || na.Local())
  189. }
  190. // For IPv4 these are either a 0 or all bits set address. For IPv6 a zero
  191. // address or one that matches the RFC3849 documentation address format.
  192. func (na *NetAddress) Valid() error {
  193. if err := validateID(na.ID); err != nil {
  194. return fmt.Errorf("invalid ID: %w", err)
  195. }
  196. if na.IP == nil {
  197. return errors.New("no IP")
  198. }
  199. if na.IP.IsUnspecified() || na.RFC3849() || na.IP.Equal(net.IPv4bcast) {
  200. return errors.New("invalid IP")
  201. }
  202. return nil
  203. }
  204. // HasID returns true if the address has an ID.
  205. // NOTE: It does not check whether the ID is valid or not.
  206. func (na *NetAddress) HasID() bool {
  207. return string(na.ID) != ""
  208. }
  209. // Local returns true if it is a local address.
  210. func (na *NetAddress) Local() bool {
  211. return na.IP.IsLoopback() || zero4.Contains(na.IP)
  212. }
  213. // ReachabilityTo checks whenever o can be reached from na.
  214. func (na *NetAddress) ReachabilityTo(o *NetAddress) int {
  215. const (
  216. Unreachable = 0
  217. Default = iota
  218. Teredo
  219. Ipv6Weak
  220. Ipv4
  221. Ipv6Strong
  222. )
  223. switch {
  224. case !na.Routable():
  225. return Unreachable
  226. case na.RFC4380():
  227. switch {
  228. case !o.Routable():
  229. return Default
  230. case o.RFC4380():
  231. return Teredo
  232. case o.IP.To4() != nil:
  233. return Ipv4
  234. default: // ipv6
  235. return Ipv6Weak
  236. }
  237. case na.IP.To4() != nil:
  238. if o.Routable() && o.IP.To4() != nil {
  239. return Ipv4
  240. }
  241. return Default
  242. default: /* ipv6 */
  243. var tunnelled bool
  244. // Is our v6 is tunnelled?
  245. if o.RFC3964() || o.RFC6052() || o.RFC6145() {
  246. tunnelled = true
  247. }
  248. switch {
  249. case !o.Routable():
  250. return Default
  251. case o.RFC4380():
  252. return Teredo
  253. case o.IP.To4() != nil:
  254. return Ipv4
  255. case tunnelled:
  256. // only prioritise ipv6 if we aren't tunnelling it.
  257. return Ipv6Weak
  258. }
  259. return Ipv6Strong
  260. }
  261. }
  262. // RFC1918: IPv4 Private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12)
  263. // RFC3849: IPv6 Documentation address (2001:0DB8::/32)
  264. // RFC3927: IPv4 Autoconfig (169.254.0.0/16)
  265. // RFC3964: IPv6 6to4 (2002::/16)
  266. // RFC4193: IPv6 unique local (FC00::/7)
  267. // RFC4380: IPv6 Teredo tunneling (2001::/32)
  268. // RFC4843: IPv6 ORCHID: (2001:10::/28)
  269. // RFC4862: IPv6 Autoconfig (FE80::/64)
  270. // RFC6052: IPv6 well known prefix (64:FF9B::/96)
  271. // RFC6145: IPv6 IPv4 translated address ::FFFF:0:0:0/96
  272. var rfc1918_10 = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(8, 32)}
  273. var rfc1918_192 = net.IPNet{IP: net.ParseIP("192.168.0.0"), Mask: net.CIDRMask(16, 32)}
  274. var rfc1918_172 = net.IPNet{IP: net.ParseIP("172.16.0.0"), Mask: net.CIDRMask(12, 32)}
  275. var rfc3849 = net.IPNet{IP: net.ParseIP("2001:0DB8::"), Mask: net.CIDRMask(32, 128)}
  276. var rfc3927 = net.IPNet{IP: net.ParseIP("169.254.0.0"), Mask: net.CIDRMask(16, 32)}
  277. var rfc3964 = net.IPNet{IP: net.ParseIP("2002::"), Mask: net.CIDRMask(16, 128)}
  278. var rfc4193 = net.IPNet{IP: net.ParseIP("FC00::"), Mask: net.CIDRMask(7, 128)}
  279. var rfc4380 = net.IPNet{IP: net.ParseIP("2001::"), Mask: net.CIDRMask(32, 128)}
  280. var rfc4843 = net.IPNet{IP: net.ParseIP("2001:10::"), Mask: net.CIDRMask(28, 128)}
  281. var rfc4862 = net.IPNet{IP: net.ParseIP("FE80::"), Mask: net.CIDRMask(64, 128)}
  282. var rfc6052 = net.IPNet{IP: net.ParseIP("64:FF9B::"), Mask: net.CIDRMask(96, 128)}
  283. var rfc6145 = net.IPNet{IP: net.ParseIP("::FFFF:0:0:0"), Mask: net.CIDRMask(96, 128)}
  284. var zero4 = net.IPNet{IP: net.ParseIP("0.0.0.0"), Mask: net.CIDRMask(8, 32)}
  285. var (
  286. // onionCatNet defines the IPv6 address block used to support Tor.
  287. // bitcoind encodes a .onion address as a 16 byte number by decoding the
  288. // address prior to the .onion (i.e. the key hash) base32 into a ten
  289. // byte number. It then stores the first 6 bytes of the address as
  290. // 0xfd, 0x87, 0xd8, 0x7e, 0xeb, 0x43.
  291. //
  292. // This is the same range used by OnionCat, which is part part of the
  293. // RFC4193 unique local IPv6 range.
  294. //
  295. // In summary the format is:
  296. // { magic 6 bytes, 10 bytes base32 decode of key hash }
  297. onionCatNet = ipNet("fd87:d87e:eb43::", 48, 128)
  298. )
  299. // ipNet returns a net.IPNet struct given the passed IP address string, number
  300. // of one bits to include at the start of the mask, and the total number of bits
  301. // for the mask.
  302. func ipNet(ip string, ones, bits int) net.IPNet {
  303. return net.IPNet{IP: net.ParseIP(ip), Mask: net.CIDRMask(ones, bits)}
  304. }
  305. func (na *NetAddress) RFC1918() bool {
  306. return rfc1918_10.Contains(na.IP) ||
  307. rfc1918_192.Contains(na.IP) ||
  308. rfc1918_172.Contains(na.IP)
  309. }
  310. func (na *NetAddress) RFC3849() bool { return rfc3849.Contains(na.IP) }
  311. func (na *NetAddress) RFC3927() bool { return rfc3927.Contains(na.IP) }
  312. func (na *NetAddress) RFC3964() bool { return rfc3964.Contains(na.IP) }
  313. func (na *NetAddress) RFC4193() bool { return rfc4193.Contains(na.IP) }
  314. func (na *NetAddress) RFC4380() bool { return rfc4380.Contains(na.IP) }
  315. func (na *NetAddress) RFC4843() bool { return rfc4843.Contains(na.IP) }
  316. func (na *NetAddress) RFC4862() bool { return rfc4862.Contains(na.IP) }
  317. func (na *NetAddress) RFC6052() bool { return rfc6052.Contains(na.IP) }
  318. func (na *NetAddress) RFC6145() bool { return rfc6145.Contains(na.IP) }
  319. func (na *NetAddress) OnionCatTor() bool { return onionCatNet.Contains(na.IP) }
  320. func removeProtocolIfDefined(addr string) string {
  321. if strings.Contains(addr, "://") {
  322. return strings.Split(addr, "://")[1]
  323. }
  324. return addr
  325. }
  326. func validateID(id ID) error {
  327. if len(id) == 0 {
  328. return errors.New("no ID")
  329. }
  330. idBytes, err := hex.DecodeString(string(id))
  331. if err != nil {
  332. return err
  333. }
  334. if len(idBytes) != IDByteLength {
  335. return fmt.Errorf("invalid hex length - got %d, expected %d", len(idBytes), IDByteLength)
  336. }
  337. return nil
  338. }