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.

361 lines
9.2 KiB

9 years ago
9 years ago
9 years ago
7 years ago
7 years ago
9 years ago
8 years ago
9 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 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
8 years ago
8 years ago
7 years ago
8 years ago
8 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
8 years ago
9 years ago
9 years ago
9 years ago
8 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
8 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
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
7 years ago
7 years ago
8 years ago
7 years ago
8 years ago
  1. package p2p
  2. import (
  3. "fmt"
  4. "io"
  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. Key() string
  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. key string
  40. Data *cmn.CMap // User data.
  41. }
  42. // PeerConfig is a Peer configuration.
  43. type PeerConfig struct {
  44. AuthEnc bool `mapstructure:"auth_enc"` // authenticated encryption
  45. // times are in seconds
  46. HandshakeTimeout time.Duration `mapstructure:"handshake_timeout"`
  47. DialTimeout time.Duration `mapstructure:"dial_timeout"`
  48. MConfig *MConnConfig `mapstructure:"connection"`
  49. Fuzz bool `mapstructure:"fuzz"` // fuzz connection (for testing)
  50. FuzzConfig *FuzzConnConfig `mapstructure:"fuzz_config"`
  51. }
  52. // DefaultPeerConfig returns the default config.
  53. func DefaultPeerConfig() *PeerConfig {
  54. return &PeerConfig{
  55. AuthEnc: true,
  56. HandshakeTimeout: 20, // * time.Second,
  57. DialTimeout: 3, // * time.Second,
  58. MConfig: DefaultMConnConfig(),
  59. Fuzz: false,
  60. FuzzConfig: DefaultFuzzConnConfig(),
  61. }
  62. }
  63. func newOutboundPeer(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor,
  64. onPeerError func(Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*peer, error) {
  65. conn, err := dial(addr, config)
  66. if err != nil {
  67. return nil, errors.Wrap(err, "Error creating peer")
  68. }
  69. peer, err := newPeerFromConnAndConfig(conn, true, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, config)
  70. if err != nil {
  71. if err := conn.Close(); err != nil {
  72. return nil, err
  73. }
  74. return nil, err
  75. }
  76. return peer, nil
  77. }
  78. func newInboundPeer(conn net.Conn, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor,
  79. onPeerError func(Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*peer, error) {
  80. return newPeerFromConnAndConfig(conn, false, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, config)
  81. }
  82. func newPeerFromConnAndConfig(rawConn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor,
  83. onPeerError func(Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*peer, error) {
  84. conn := rawConn
  85. // Fuzz connection
  86. if config.Fuzz {
  87. // so we have time to do peer handshakes and get set up
  88. conn = FuzzConnAfterFromConfig(conn, 10*time.Second, config.FuzzConfig)
  89. }
  90. // Encrypt connection
  91. if config.AuthEnc {
  92. if err := conn.SetDeadline(time.Now().Add(config.HandshakeTimeout * time.Second)); err != nil {
  93. return nil, errors.Wrap(err, "Error setting deadline while encrypting connection")
  94. }
  95. var err error
  96. conn, err = MakeSecretConnection(conn, ourNodePrivKey)
  97. if err != nil {
  98. return nil, errors.Wrap(err, "Error creating peer")
  99. }
  100. }
  101. // Key and NodeInfo are set after Handshake
  102. p := &peer{
  103. outbound: outbound,
  104. conn: conn,
  105. config: config,
  106. Data: cmn.NewCMap(),
  107. }
  108. p.mconn = createMConnection(conn, p, reactorsByCh, chDescs, onPeerError, config.MConfig)
  109. p.BaseService = *cmn.NewBaseService(nil, "Peer", p)
  110. return p, nil
  111. }
  112. func (p *peer) SetLogger(l log.Logger) {
  113. p.Logger = l
  114. p.mconn.SetLogger(l)
  115. }
  116. // CloseConn should be used when the peer was created, but never started.
  117. func (p *peer) CloseConn() {
  118. p.conn.Close() // nolint: errcheck
  119. }
  120. // makePersistent marks the peer as persistent.
  121. func (p *peer) makePersistent() {
  122. if !p.outbound {
  123. panic("inbound peers can't be made persistent")
  124. }
  125. p.persistent = true
  126. }
  127. // IsPersistent returns true if the peer is persitent, false otherwise.
  128. func (p *peer) IsPersistent() bool {
  129. return p.persistent
  130. }
  131. // HandshakeTimeout performs a handshake between a given node and the peer.
  132. // NOTE: blocking
  133. func (p *peer) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) error {
  134. // Set deadline for handshake so we don't block forever on conn.ReadFull
  135. if err := p.conn.SetDeadline(time.Now().Add(timeout)); err != nil {
  136. return errors.Wrap(err, "Error setting deadline")
  137. }
  138. var peerNodeInfo = new(NodeInfo)
  139. var err1 error
  140. var err2 error
  141. cmn.Parallel(
  142. func() {
  143. var n int
  144. wire.WriteBinary(ourNodeInfo, p.conn, &n, &err1)
  145. },
  146. func() {
  147. var n int
  148. wire.ReadBinary(peerNodeInfo, p.conn, maxNodeInfoSize, &n, &err2)
  149. p.Logger.Info("Peer handshake", "peerNodeInfo", peerNodeInfo)
  150. })
  151. if err1 != nil {
  152. return errors.Wrap(err1, "Error during handshake/write")
  153. }
  154. if err2 != nil {
  155. return errors.Wrap(err2, "Error during handshake/read")
  156. }
  157. if p.config.AuthEnc {
  158. // Check that the professed PubKey matches the sconn's.
  159. if !peerNodeInfo.PubKey.Equals(p.PubKey().Wrap()) {
  160. return fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v",
  161. peerNodeInfo.PubKey, p.PubKey())
  162. }
  163. }
  164. // Remove deadline
  165. if err := p.conn.SetDeadline(time.Time{}); err != nil {
  166. return errors.Wrap(err, "Error removing deadline")
  167. }
  168. peerNodeInfo.RemoteAddr = p.Addr().String()
  169. p.nodeInfo = peerNodeInfo
  170. p.key = peerNodeInfo.PubKey.KeyString()
  171. return nil
  172. }
  173. // Addr returns peer's remote network address.
  174. func (p *peer) Addr() net.Addr {
  175. return p.conn.RemoteAddr()
  176. }
  177. // PubKey returns peer's public key.
  178. func (p *peer) PubKey() crypto.PubKeyEd25519 {
  179. if p.config.AuthEnc {
  180. return p.conn.(*SecretConnection).RemotePubKey()
  181. }
  182. if p.NodeInfo() == nil {
  183. panic("Attempt to get peer's PubKey before calling Handshake")
  184. }
  185. return p.PubKey()
  186. }
  187. // OnStart implements BaseService.
  188. func (p *peer) OnStart() error {
  189. if err := p.BaseService.OnStart(); err != nil {
  190. return err
  191. }
  192. err := p.mconn.Start()
  193. return err
  194. }
  195. // OnStop implements BaseService.
  196. func (p *peer) OnStop() {
  197. p.BaseService.OnStop()
  198. p.mconn.Stop()
  199. }
  200. // Connection returns underlying MConnection.
  201. func (p *peer) Connection() *MConnection {
  202. return p.mconn
  203. }
  204. // IsOutbound returns true if the connection is outbound, false otherwise.
  205. func (p *peer) IsOutbound() bool {
  206. return p.outbound
  207. }
  208. // Send msg to the channel identified by chID byte. Returns false if the send
  209. // queue is full after timeout, specified by MConnection.
  210. func (p *peer) Send(chID byte, msg interface{}) bool {
  211. if !p.IsRunning() {
  212. // see Switch#Broadcast, where we fetch the list of peers and loop over
  213. // them - while we're looping, one peer may be removed and stopped.
  214. return false
  215. }
  216. return p.mconn.Send(chID, msg)
  217. }
  218. // TrySend msg to the channel identified by chID byte. Immediately returns
  219. // false if the send queue is full.
  220. func (p *peer) TrySend(chID byte, msg interface{}) bool {
  221. if !p.IsRunning() {
  222. return false
  223. }
  224. return p.mconn.TrySend(chID, msg)
  225. }
  226. // CanSend returns true if the send queue is not full, false otherwise.
  227. func (p *peer) CanSend(chID byte) bool {
  228. if !p.IsRunning() {
  229. return false
  230. }
  231. return p.mconn.CanSend(chID)
  232. }
  233. // WriteTo writes the peer's public key to w.
  234. func (p *peer) WriteTo(w io.Writer) (int64, error) {
  235. var n int
  236. var err error
  237. wire.WriteString(p.key, w, &n, &err)
  238. return int64(n), err
  239. }
  240. // String representation.
  241. func (p *peer) String() string {
  242. if p.outbound {
  243. return fmt.Sprintf("Peer{%v %v out}", p.mconn, p.key[:12])
  244. }
  245. return fmt.Sprintf("Peer{%v %v in}", p.mconn, p.key[:12])
  246. }
  247. // Equals reports whenever 2 peers are actually represent the same node.
  248. func (p *peer) Equals(other Peer) bool {
  249. return p.key == other.Key()
  250. }
  251. // Get the data for a given key.
  252. func (p *peer) Get(key string) interface{} {
  253. return p.Data.Get(key)
  254. }
  255. // Set sets the data for the given key.
  256. func (p *peer) Set(key string, data interface{}) {
  257. p.Data.Set(key, data)
  258. }
  259. // Key returns the peer's id key.
  260. func (p *peer) Key() string {
  261. return p.key
  262. }
  263. // NodeInfo returns a copy of the peer's NodeInfo.
  264. func (p *peer) NodeInfo() *NodeInfo {
  265. if p.nodeInfo == nil {
  266. return nil
  267. }
  268. n := *p.nodeInfo // copy
  269. return &n
  270. }
  271. // Status returns the peer's ConnectionStatus.
  272. func (p *peer) Status() ConnectionStatus {
  273. return p.mconn.Status()
  274. }
  275. func dial(addr *NetAddress, config *PeerConfig) (net.Conn, error) {
  276. conn, err := addr.DialTimeout(config.DialTimeout * time.Second)
  277. if err != nil {
  278. return nil, err
  279. }
  280. return conn, nil
  281. }
  282. func createMConnection(conn net.Conn, p *peer, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor,
  283. onPeerError func(Peer, interface{}), config *MConnConfig) *MConnection {
  284. onReceive := func(chID byte, msgBytes []byte) {
  285. reactor := reactorsByCh[chID]
  286. if reactor == nil {
  287. cmn.PanicSanity(cmn.Fmt("Unknown channel %X", chID))
  288. }
  289. reactor.Receive(chID, p, msgBytes)
  290. }
  291. onError := func(r interface{}) {
  292. onPeerError(p, r)
  293. }
  294. return NewMConnectionWithConfig(conn, chDescs, onReceive, onError, config)
  295. }