transport.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package p2p
  17. import (
  18. "bytes"
  19. "crypto/ecdsa"
  20. "fmt"
  21. "io"
  22. "net"
  23. "sync"
  24. "time"
  25. "github.com/ethereum/go-ethereum/common/bitutil"
  26. "github.com/ethereum/go-ethereum/metrics"
  27. "github.com/ethereum/go-ethereum/p2p/rlpx"
  28. "github.com/ethereum/go-ethereum/rlp"
  29. )
  30. const (
  31. // total timeout for encryption handshake and protocol
  32. // handshake in both directions.
  33. handshakeTimeout = 5 * time.Second
  34. // This is the timeout for sending the disconnect reason.
  35. // This is shorter than the usual timeout because we don't want
  36. // to wait if the connection is known to be bad anyway.
  37. discWriteTimeout = 1 * time.Second
  38. )
  39. // rlpxTransport is the transport used by actual (non-test) connections.
  40. // It wraps an RLPx connection with locks and read/write deadlines.
  41. type rlpxTransport struct {
  42. rmu, wmu sync.Mutex
  43. wbuf bytes.Buffer
  44. conn *rlpx.Conn
  45. }
  46. func newRLPX(conn net.Conn, dialDest *ecdsa.PublicKey) transport {
  47. return &rlpxTransport{conn: rlpx.NewConn(conn, dialDest)}
  48. }
  49. func (t *rlpxTransport) ReadMsg() (Msg, error) {
  50. t.rmu.Lock()
  51. defer t.rmu.Unlock()
  52. var msg Msg
  53. t.conn.SetReadDeadline(time.Now().Add(frameReadTimeout))
  54. code, data, wireSize, err := t.conn.Read()
  55. if err == nil {
  56. msg = Msg{
  57. ReceivedAt: time.Now(),
  58. Code: code,
  59. Size: uint32(len(data)),
  60. meterSize: uint32(wireSize),
  61. Payload: bytes.NewReader(data),
  62. }
  63. }
  64. return msg, err
  65. }
  66. func (t *rlpxTransport) WriteMsg(msg Msg) error {
  67. t.wmu.Lock()
  68. defer t.wmu.Unlock()
  69. // Copy message data to write buffer.
  70. t.wbuf.Reset()
  71. if _, err := io.CopyN(&t.wbuf, msg.Payload, int64(msg.Size)); err != nil {
  72. return err
  73. }
  74. // Write the message.
  75. t.conn.SetWriteDeadline(time.Now().Add(frameWriteTimeout))
  76. size, err := t.conn.Write(msg.Code, t.wbuf.Bytes())
  77. if err != nil {
  78. return err
  79. }
  80. // Set metrics.
  81. msg.meterSize = size
  82. if metrics.Enabled && msg.meterCap.Name != "" { // don't meter non-subprotocol messages
  83. m := fmt.Sprintf("%s/%s/%d/%#02x", egressMeterName, msg.meterCap.Name, msg.meterCap.Version, msg.meterCode)
  84. metrics.GetOrRegisterMeter(m, nil).Mark(int64(msg.meterSize))
  85. metrics.GetOrRegisterMeter(m+"/packets", nil).Mark(1)
  86. }
  87. return nil
  88. }
  89. func (t *rlpxTransport) close(err error) {
  90. t.wmu.Lock()
  91. defer t.wmu.Unlock()
  92. // Tell the remote end why we're disconnecting if possible.
  93. // We only bother doing this if the underlying connection supports
  94. // setting a timeout tough.
  95. if t.conn != nil {
  96. if r, ok := err.(DiscReason); ok && r != DiscNetworkError {
  97. deadline := time.Now().Add(discWriteTimeout)
  98. if err := t.conn.SetWriteDeadline(deadline); err == nil {
  99. // Connection supports write deadline.
  100. t.wbuf.Reset()
  101. rlp.Encode(&t.wbuf, []DiscReason{r})
  102. t.conn.Write(discMsg, t.wbuf.Bytes())
  103. }
  104. }
  105. }
  106. t.conn.Close()
  107. }
  108. func (t *rlpxTransport) doEncHandshake(prv *ecdsa.PrivateKey) (*ecdsa.PublicKey, error) {
  109. t.conn.SetDeadline(time.Now().Add(handshakeTimeout))
  110. return t.conn.Handshake(prv)
  111. }
  112. func (t *rlpxTransport) doProtoHandshake(our *protoHandshake) (their *protoHandshake, err error) {
  113. // Writing our handshake happens concurrently, we prefer
  114. // returning the handshake read error. If the remote side
  115. // disconnects us early with a valid reason, we should return it
  116. // as the error so it can be tracked elsewhere.
  117. werr := make(chan error, 1)
  118. go func() { werr <- Send(t, handshakeMsg, our) }()
  119. if their, err = readProtocolHandshake(t); err != nil {
  120. <-werr // make sure the write terminates too
  121. return nil, err
  122. }
  123. if err := <-werr; err != nil {
  124. return nil, fmt.Errorf("write error: %v", err)
  125. }
  126. // If the protocol version supports Snappy encoding, upgrade immediately
  127. t.conn.SetSnappy(their.Version >= snappyProtocolVersion)
  128. return their, nil
  129. }
  130. func readProtocolHandshake(rw MsgReader) (*protoHandshake, error) {
  131. msg, err := rw.ReadMsg()
  132. if err != nil {
  133. return nil, err
  134. }
  135. if msg.Size > baseProtocolMaxMsgSize {
  136. return nil, fmt.Errorf("message too big")
  137. }
  138. if msg.Code == discMsg {
  139. // Disconnect before protocol handshake is valid according to the
  140. // spec and we send it ourself if the post-handshake checks fail.
  141. // We can't return the reason directly, though, because it is echoed
  142. // back otherwise. Wrap it in a string instead.
  143. var reason [1]DiscReason
  144. rlp.Decode(msg.Payload, &reason)
  145. return nil, reason[0]
  146. }
  147. if msg.Code != handshakeMsg {
  148. return nil, fmt.Errorf("expected handshake, got %x", msg.Code)
  149. }
  150. var hs protoHandshake
  151. if err := msg.Decode(&hs); err != nil {
  152. return nil, err
  153. }
  154. if len(hs.ID) != 64 || !bitutil.TestBytes(hs.ID) {
  155. return nil, DiscInvalidIdentity
  156. }
  157. return &hs, nil
  158. }