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.

350 lines
9.0 KiB

9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
7 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
p2p: peer should respect errors from SetDeadline Noticed while auditing the code that we aren't respecting (*net.Conn) SetDeadline errors which return after a connection has been killed and is simultaneously being used. For example given program, without SetDeadline error checks ```go package main import ( "log" "net" "time" ) func main() { conn, err := net.Dial("tcp", "tendermint.com:443") if err != nil { log.Fatal(err) } go func() { <-time.After(400 * time.Millisecond) conn.Close() }() for i := 0; i < 5; i++ { if err := conn.SetDeadline(time.Now().Add(time.Duration(10 * time.Second))); err != nil { log.Fatalf("set deadline #%d, err: %v", i, err) } log.Printf("Successfully set deadline #%d", i) <-time.After(150 * time.Millisecond) } } ``` erraneously gives ```shell 2017/11/14 17:46:28 Successfully set deadline #0 2017/11/14 17:46:29 Successfully set deadline #1 2017/11/14 17:46:29 Successfully set deadline #2 2017/11/14 17:46:29 Successfully set deadline #3 2017/11/14 17:46:29 Successfully set deadline #4 ``` However, if we properly fix it to respect that error with ```diff --- wild.go 2017-11-14 17:44:38.000000000 -0700 +++ main.go 2017-11-14 17:45:40.000000000 -0700 @@ -16,7 +16,9 @@ conn.Close() }() for i := 0; i < 5; i++ { - conn.SetDeadline(time.Now().Add(time.Duration(10 * time.Second))) + if err := conn.SetDeadline(time.Now().Add(time.Duration(10 * time.Second))); err != nil { + log.Fatalf("set deadline #%d, err: %v", i, err) + } log.Printf("Successfully set deadline #%d", i) <-time.After(150 * time.Millisecond) } ``` properly catches any problems and gives ```shell $ go run main.go 2017/11/14 17:43:44 Successfully set deadline #0 2017/11/14 17:43:45 Successfully set deadline #1 2017/11/14 17:43:45 Successfully set deadline #2 2017/11/14 17:43:45 set deadline #3, err: set tcp 10.182.253.51:57395: use of closed network connection exit status 1 ```
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
p2p: peer should respect errors from SetDeadline Noticed while auditing the code that we aren't respecting (*net.Conn) SetDeadline errors which return after a connection has been killed and is simultaneously being used. For example given program, without SetDeadline error checks ```go package main import ( "log" "net" "time" ) func main() { conn, err := net.Dial("tcp", "tendermint.com:443") if err != nil { log.Fatal(err) } go func() { <-time.After(400 * time.Millisecond) conn.Close() }() for i := 0; i < 5; i++ { if err := conn.SetDeadline(time.Now().Add(time.Duration(10 * time.Second))); err != nil { log.Fatalf("set deadline #%d, err: %v", i, err) } log.Printf("Successfully set deadline #%d", i) <-time.After(150 * time.Millisecond) } } ``` erraneously gives ```shell 2017/11/14 17:46:28 Successfully set deadline #0 2017/11/14 17:46:29 Successfully set deadline #1 2017/11/14 17:46:29 Successfully set deadline #2 2017/11/14 17:46:29 Successfully set deadline #3 2017/11/14 17:46:29 Successfully set deadline #4 ``` However, if we properly fix it to respect that error with ```diff --- wild.go 2017-11-14 17:44:38.000000000 -0700 +++ main.go 2017-11-14 17:45:40.000000000 -0700 @@ -16,7 +16,9 @@ conn.Close() }() for i := 0; i < 5; i++ { - conn.SetDeadline(time.Now().Add(time.Duration(10 * time.Second))) + if err := conn.SetDeadline(time.Now().Add(time.Duration(10 * time.Second))); err != nil { + log.Fatalf("set deadline #%d, err: %v", i, err) + } log.Printf("Successfully set deadline #%d", i) <-time.After(150 * time.Millisecond) } ``` properly catches any problems and gives ```shell $ go run main.go 2017/11/14 17:43:44 Successfully set deadline #0 2017/11/14 17:43:45 Successfully set deadline #1 2017/11/14 17:43:45 Successfully set deadline #2 2017/11/14 17:43:45 set deadline #3, err: set tcp 10.182.253.51:57395: use of closed network connection exit status 1 ```
7 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
p2p: peer should respect errors from SetDeadline Noticed while auditing the code that we aren't respecting (*net.Conn) SetDeadline errors which return after a connection has been killed and is simultaneously being used. For example given program, without SetDeadline error checks ```go package main import ( "log" "net" "time" ) func main() { conn, err := net.Dial("tcp", "tendermint.com:443") if err != nil { log.Fatal(err) } go func() { <-time.After(400 * time.Millisecond) conn.Close() }() for i := 0; i < 5; i++ { if err := conn.SetDeadline(time.Now().Add(time.Duration(10 * time.Second))); err != nil { log.Fatalf("set deadline #%d, err: %v", i, err) } log.Printf("Successfully set deadline #%d", i) <-time.After(150 * time.Millisecond) } } ``` erraneously gives ```shell 2017/11/14 17:46:28 Successfully set deadline #0 2017/11/14 17:46:29 Successfully set deadline #1 2017/11/14 17:46:29 Successfully set deadline #2 2017/11/14 17:46:29 Successfully set deadline #3 2017/11/14 17:46:29 Successfully set deadline #4 ``` However, if we properly fix it to respect that error with ```diff --- wild.go 2017-11-14 17:44:38.000000000 -0700 +++ main.go 2017-11-14 17:45:40.000000000 -0700 @@ -16,7 +16,9 @@ conn.Close() }() for i := 0; i < 5; i++ { - conn.SetDeadline(time.Now().Add(time.Duration(10 * time.Second))) + if err := conn.SetDeadline(time.Now().Add(time.Duration(10 * time.Second))); err != nil { + log.Fatalf("set deadline #%d, err: %v", i, err) + } log.Printf("Successfully set deadline #%d", i) <-time.After(150 * time.Millisecond) } ``` properly catches any problems and gives ```shell $ go run main.go 2017/11/14 17:43:44 Successfully set deadline #0 2017/11/14 17:43:45 Successfully set deadline #1 2017/11/14 17:43:45 Successfully set deadline #2 2017/11/14 17:43:45 set deadline #3, err: set tcp 10.182.253.51:57395: use of closed network connection exit status 1 ```
7 years ago
7 years ago
7 years ago
7 years ago
9 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package p2p
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "net"
  6. "time"
  7. "github.com/pkg/errors"
  8. crypto "github.com/tendermint/go-crypto"
  9. wire "github.com/tendermint/go-wire"
  10. cmn "github.com/tendermint/tmlibs/common"
  11. "github.com/tendermint/tmlibs/log"
  12. )
  13. // Peer is an interface representing a peer connected on a reactor.
  14. type Peer interface {
  15. cmn.Service
  16. ID() ID
  17. IsOutbound() bool
  18. IsPersistent() bool
  19. NodeInfo() *NodeInfo
  20. Status() ConnectionStatus
  21. Send(byte, interface{}) bool
  22. TrySend(byte, interface{}) bool
  23. Set(string, interface{})
  24. Get(string) interface{}
  25. }
  26. // Peer could be marked as persistent, in which case you can use
  27. // Redial function to reconnect. Note that inbound peers can't be
  28. // made persistent. They should be made persistent on the other end.
  29. //
  30. // Before using a peer, you will need to perform a handshake on connection.
  31. type peer struct {
  32. cmn.BaseService
  33. outbound bool
  34. conn net.Conn // source connection
  35. mconn *MConnection // multiplex connection
  36. persistent bool
  37. config *PeerConfig
  38. nodeInfo *NodeInfo
  39. Data *cmn.CMap // User data.
  40. }
  41. // PeerConfig is a Peer configuration.
  42. type PeerConfig struct {
  43. AuthEnc bool `mapstructure:"auth_enc"` // authenticated encryption
  44. // times are in seconds
  45. HandshakeTimeout time.Duration `mapstructure:"handshake_timeout"`
  46. DialTimeout time.Duration `mapstructure:"dial_timeout"`
  47. MConfig *MConnConfig `mapstructure:"connection"`
  48. Fuzz bool `mapstructure:"fuzz"` // fuzz connection (for testing)
  49. FuzzConfig *FuzzConnConfig `mapstructure:"fuzz_config"`
  50. }
  51. // DefaultPeerConfig returns the default config.
  52. func DefaultPeerConfig() *PeerConfig {
  53. return &PeerConfig{
  54. AuthEnc: true,
  55. HandshakeTimeout: 20, // * time.Second,
  56. DialTimeout: 3, // * time.Second,
  57. MConfig: DefaultMConnConfig(),
  58. Fuzz: false,
  59. FuzzConfig: DefaultFuzzConnConfig(),
  60. }
  61. }
  62. func newOutboundPeer(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor,
  63. onPeerError func(Peer, interface{}), ourNodePrivKey crypto.PrivKey, config *PeerConfig) (*peer, error) {
  64. conn, err := dial(addr, config)
  65. if err != nil {
  66. return nil, errors.Wrap(err, "Error creating peer")
  67. }
  68. peer, err := newPeerFromConnAndConfig(conn, true, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, config)
  69. if err != nil {
  70. if err := conn.Close(); err != nil {
  71. return nil, err
  72. }
  73. return nil, err
  74. }
  75. return peer, nil
  76. }
  77. func newInboundPeer(conn net.Conn, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor,
  78. onPeerError func(Peer, interface{}), ourNodePrivKey crypto.PrivKey, config *PeerConfig) (*peer, error) {
  79. return newPeerFromConnAndConfig(conn, false, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, config)
  80. }
  81. func newPeerFromConnAndConfig(rawConn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor,
  82. onPeerError func(Peer, interface{}), ourNodePrivKey crypto.PrivKey, config *PeerConfig) (*peer, error) {
  83. conn := rawConn
  84. // Fuzz connection
  85. if config.Fuzz {
  86. // so we have time to do peer handshakes and get set up
  87. conn = FuzzConnAfterFromConfig(conn, 10*time.Second, config.FuzzConfig)
  88. }
  89. // Encrypt connection
  90. if config.AuthEnc {
  91. if err := conn.SetDeadline(time.Now().Add(config.HandshakeTimeout * time.Second)); err != nil {
  92. return nil, errors.Wrap(err, "Error setting deadline while encrypting connection")
  93. }
  94. var err error
  95. conn, err = MakeSecretConnection(conn, ourNodePrivKey)
  96. if err != nil {
  97. return nil, errors.Wrap(err, "Error creating peer")
  98. }
  99. }
  100. // Key and NodeInfo are set after Handshake
  101. p := &peer{
  102. outbound: outbound,
  103. conn: conn,
  104. config: config,
  105. Data: cmn.NewCMap(),
  106. }
  107. p.mconn = createMConnection(conn, p, reactorsByCh, chDescs, onPeerError, config.MConfig)
  108. p.BaseService = *cmn.NewBaseService(nil, "Peer", p)
  109. return p, nil
  110. }
  111. func (p *peer) SetLogger(l log.Logger) {
  112. p.Logger = l
  113. p.mconn.SetLogger(l)
  114. }
  115. // CloseConn should be used when the peer was created, but never started.
  116. func (p *peer) CloseConn() {
  117. p.conn.Close() // nolint: errcheck
  118. }
  119. // makePersistent marks the peer as persistent.
  120. func (p *peer) makePersistent() {
  121. if !p.outbound {
  122. panic("inbound peers can't be made persistent")
  123. }
  124. p.persistent = true
  125. }
  126. // IsPersistent returns true if the peer is persitent, false otherwise.
  127. func (p *peer) IsPersistent() bool {
  128. return p.persistent
  129. }
  130. // HandshakeTimeout performs a handshake between a given node and the peer.
  131. // NOTE: blocking
  132. func (p *peer) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) error {
  133. // Set deadline for handshake so we don't block forever on conn.ReadFull
  134. if err := p.conn.SetDeadline(time.Now().Add(timeout)); err != nil {
  135. return errors.Wrap(err, "Error setting deadline")
  136. }
  137. var peerNodeInfo = new(NodeInfo)
  138. var err1 error
  139. var err2 error
  140. cmn.Parallel(
  141. func() {
  142. var n int
  143. wire.WriteBinary(ourNodeInfo, p.conn, &n, &err1)
  144. },
  145. func() {
  146. var n int
  147. wire.ReadBinary(peerNodeInfo, p.conn, maxNodeInfoSize, &n, &err2)
  148. p.Logger.Info("Peer handshake", "peerNodeInfo", peerNodeInfo)
  149. })
  150. if err1 != nil {
  151. return errors.Wrap(err1, "Error during handshake/write")
  152. }
  153. if err2 != nil {
  154. return errors.Wrap(err2, "Error during handshake/read")
  155. }
  156. if p.config.AuthEnc {
  157. // Check that the professed PubKey matches the sconn's.
  158. if !peerNodeInfo.PubKey.Equals(p.PubKey().Wrap()) {
  159. return fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v",
  160. peerNodeInfo.PubKey, p.PubKey())
  161. }
  162. }
  163. // Remove deadline
  164. if err := p.conn.SetDeadline(time.Time{}); err != nil {
  165. return errors.Wrap(err, "Error removing deadline")
  166. }
  167. peerNodeInfo.RemoteAddr = p.Addr().String()
  168. p.nodeInfo = peerNodeInfo
  169. return nil
  170. }
  171. // Addr returns peer's remote network address.
  172. func (p *peer) Addr() net.Addr {
  173. return p.conn.RemoteAddr()
  174. }
  175. // PubKey returns peer's public key.
  176. func (p *peer) PubKey() crypto.PubKey {
  177. if p.config.AuthEnc {
  178. return p.conn.(*SecretConnection).RemotePubKey()
  179. }
  180. if p.NodeInfo() == nil {
  181. panic("Attempt to get peer's PubKey before calling Handshake")
  182. }
  183. return p.PubKey()
  184. }
  185. // OnStart implements BaseService.
  186. func (p *peer) OnStart() error {
  187. if err := p.BaseService.OnStart(); err != nil {
  188. return err
  189. }
  190. err := p.mconn.Start()
  191. return err
  192. }
  193. // OnStop implements BaseService.
  194. func (p *peer) OnStop() {
  195. p.BaseService.OnStop()
  196. p.mconn.Stop()
  197. }
  198. // Connection returns underlying MConnection.
  199. func (p *peer) Connection() *MConnection {
  200. return p.mconn
  201. }
  202. // IsOutbound returns true if the connection is outbound, false otherwise.
  203. func (p *peer) IsOutbound() bool {
  204. return p.outbound
  205. }
  206. // Send msg to the channel identified by chID byte. Returns false if the send
  207. // queue is full after timeout, specified by MConnection.
  208. func (p *peer) Send(chID byte, msg interface{}) bool {
  209. if !p.IsRunning() {
  210. // see Switch#Broadcast, where we fetch the list of peers and loop over
  211. // them - while we're looping, one peer may be removed and stopped.
  212. return false
  213. }
  214. return p.mconn.Send(chID, msg)
  215. }
  216. // TrySend msg to the channel identified by chID byte. Immediately returns
  217. // false if the send queue is full.
  218. func (p *peer) TrySend(chID byte, msg interface{}) bool {
  219. if !p.IsRunning() {
  220. return false
  221. }
  222. return p.mconn.TrySend(chID, msg)
  223. }
  224. // CanSend returns true if the send queue is not full, false otherwise.
  225. func (p *peer) CanSend(chID byte) bool {
  226. if !p.IsRunning() {
  227. return false
  228. }
  229. return p.mconn.CanSend(chID)
  230. }
  231. // String representation.
  232. func (p *peer) String() string {
  233. if p.outbound {
  234. return fmt.Sprintf("Peer{%v %v out}", p.mconn, p.ID())
  235. }
  236. return fmt.Sprintf("Peer{%v %v in}", p.mconn, p.ID())
  237. }
  238. // Equals reports whenever 2 peers are actually represent the same node.
  239. func (p *peer) Equals(other Peer) bool {
  240. return p.ID() == other.ID()
  241. }
  242. // Get the data for a given key.
  243. func (p *peer) Get(key string) interface{} {
  244. return p.Data.Get(key)
  245. }
  246. // Set sets the data for the given key.
  247. func (p *peer) Set(key string, data interface{}) {
  248. p.Data.Set(key, data)
  249. }
  250. // Key returns the peer's ID - the hex encoded hash of its pubkey.
  251. func (p *peer) ID() ID {
  252. return ID(hex.EncodeToString(p.nodeInfo.PubKey.Address()))
  253. }
  254. // NodeInfo returns a copy of the peer's NodeInfo.
  255. func (p *peer) NodeInfo() *NodeInfo {
  256. if p.nodeInfo == nil {
  257. return nil
  258. }
  259. n := *p.nodeInfo // copy
  260. return &n
  261. }
  262. // Status returns the peer's ConnectionStatus.
  263. func (p *peer) Status() ConnectionStatus {
  264. return p.mconn.Status()
  265. }
  266. func dial(addr *NetAddress, config *PeerConfig) (net.Conn, error) {
  267. conn, err := addr.DialTimeout(config.DialTimeout * time.Second)
  268. if err != nil {
  269. return nil, err
  270. }
  271. return conn, nil
  272. }
  273. func createMConnection(conn net.Conn, p *peer, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor,
  274. onPeerError func(Peer, interface{}), config *MConnConfig) *MConnection {
  275. onReceive := func(chID byte, msgBytes []byte) {
  276. reactor := reactorsByCh[chID]
  277. if reactor == nil {
  278. cmn.PanicSanity(cmn.Fmt("Unknown channel %X", chID))
  279. }
  280. reactor.Receive(chID, p, msgBytes)
  281. }
  282. onError := func(r interface{}) {
  283. onPeerError(p, r)
  284. }
  285. return NewMConnectionWithConfig(conn, chDescs, onReceive, onError, config)
  286. }