transport.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. // Copyright 2020 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"
  26. "github.com/ethereum/go-ethereum/common/bitutil"
  27. "github.com/ethereum/go-ethereum/metrics"
  28. "github.com/ethereum/go-ethereum/p2p/rlpx"
  29. "github.com/ethereum/go-ethereum/rlp"
  30. )
  31. const (
  32. // total timeout for encryption handshake and protocol
  33. // handshake in both directions.
  34. handshakeTimeout = 5 * time.Second
  35. // This is the timeout for sending the disconnect reason.
  36. // This is shorter than the usual timeout because we don't want
  37. // to wait if the connection is known to be bad anyway.
  38. discWriteTimeout = 1 * time.Second
  39. )
  40. // rlpxTransport is the transport used by actual (non-test) connections.
  41. // It wraps an RLPx connection with locks and read/write deadlines.
  42. type rlpxTransport struct {
  43. rmu, wmu sync.Mutex
  44. wbuf bytes.Buffer
  45. conn *rlpx.Conn
  46. }
  47. func newRLPX(conn net.Conn, dialDest *ecdsa.PublicKey) transport {
  48. return &rlpxTransport{conn: rlpx.NewConn(conn, dialDest)}
  49. }
  50. func (t *rlpxTransport) ReadMsg() (Msg, error) {
  51. t.rmu.Lock()
  52. defer t.rmu.Unlock()
  53. var msg Msg
  54. t.conn.SetReadDeadline(time.Now().Add(frameReadTimeout))
  55. code, data, wireSize, err := t.conn.Read()
  56. if err == nil {
  57. // Protocol messages are dispatched to subprotocol handlers asynchronously,
  58. // but package rlpx may reuse the returned 'data' buffer on the next call
  59. // to Read. Copy the message data to avoid this being an issue.
  60. data = common.CopyBytes(data)
  61. msg = Msg{
  62. ReceivedAt: time.Now(),
  63. Code: code,
  64. Size: uint32(len(data)),
  65. meterSize: uint32(wireSize),
  66. Payload: bytes.NewReader(data),
  67. }
  68. }
  69. return msg, err
  70. }
  71. func (t *rlpxTransport) WriteMsg(msg Msg) error {
  72. t.wmu.Lock()
  73. defer t.wmu.Unlock()
  74. // Copy message data to write buffer.
  75. t.wbuf.Reset()
  76. if _, err := io.CopyN(&t.wbuf, msg.Payload, int64(msg.Size)); err != nil {
  77. return err
  78. }
  79. // Write the message.
  80. t.conn.SetWriteDeadline(time.Now().Add(frameWriteTimeout))
  81. size, err := t.conn.Write(msg.Code, t.wbuf.Bytes())
  82. if err != nil {
  83. return err
  84. }
  85. // Set metrics.
  86. msg.meterSize = size
  87. if metrics.Enabled && msg.meterCap.Name != "" { // don't meter non-subprotocol messages
  88. m := fmt.Sprintf("%s/%s/%d/%#02x", egressMeterName, msg.meterCap.Name, msg.meterCap.Version, msg.meterCode)
  89. metrics.GetOrRegisterMeter(m, nil).Mark(int64(msg.meterSize))
  90. metrics.GetOrRegisterMeter(m+"/packets", nil).Mark(1)
  91. }
  92. return nil
  93. }
  94. func (t *rlpxTransport) close(err error) {
  95. t.wmu.Lock()
  96. defer t.wmu.Unlock()
  97. // Tell the remote end why we're disconnecting if possible.
  98. // We only bother doing this if the underlying connection supports
  99. // setting a timeout tough.
  100. if t.conn != nil {
  101. if r, ok := err.(DiscReason); ok && r != DiscNetworkError {
  102. deadline := time.Now().Add(discWriteTimeout)
  103. if err := t.conn.SetWriteDeadline(deadline); err == nil {
  104. // Connection supports write deadline.
  105. t.wbuf.Reset()
  106. rlp.Encode(&t.wbuf, []DiscReason{r})
  107. t.conn.Write(discMsg, t.wbuf.Bytes())
  108. }
  109. }
  110. }
  111. t.conn.Close()
  112. }
  113. func (t *rlpxTransport) doEncHandshake(prv *ecdsa.PrivateKey) (*ecdsa.PublicKey, error) {
  114. t.conn.SetDeadline(time.Now().Add(handshakeTimeout))
  115. return t.conn.Handshake(prv)
  116. }
  117. func (t *rlpxTransport) doProtoHandshake(our *protoHandshake) (their *protoHandshake, err error) {
  118. // Writing our handshake happens concurrently, we prefer
  119. // returning the handshake read error. If the remote side
  120. // disconnects us early with a valid reason, we should return it
  121. // as the error so it can be tracked elsewhere.
  122. werr := make(chan error, 1)
  123. go func() { werr <- Send(t, handshakeMsg, our) }()
  124. if their, err = readProtocolHandshake(t); err != nil {
  125. <-werr // make sure the write terminates too
  126. return nil, err
  127. }
  128. if err := <-werr; err != nil {
  129. return nil, fmt.Errorf("write error: %v", err)
  130. }
  131. // If the protocol version supports Snappy encoding, upgrade immediately
  132. t.conn.SetSnappy(their.Version >= snappyProtocolVersion)
  133. return their, nil
  134. }
  135. func readProtocolHandshake(rw MsgReader) (*protoHandshake, error) {
  136. msg, err := rw.ReadMsg()
  137. if err != nil {
  138. return nil, err
  139. }
  140. if msg.Size > baseProtocolMaxMsgSize {
  141. return nil, fmt.Errorf("message too big")
  142. }
  143. if msg.Code == discMsg {
  144. // Disconnect before protocol handshake is valid according to the
  145. // spec and we send it ourself if the post-handshake checks fail.
  146. // We can't return the reason directly, though, because it is echoed
  147. // back otherwise. Wrap it in a string instead.
  148. var reason [1]DiscReason
  149. rlp.Decode(msg.Payload, &reason)
  150. return nil, reason[0]
  151. }
  152. if msg.Code != handshakeMsg {
  153. return nil, fmt.Errorf("expected handshake, got %x", msg.Code)
  154. }
  155. var hs protoHandshake
  156. if err := msg.Decode(&hs); err != nil {
  157. return nil, err
  158. }
  159. if len(hs.ID) != 64 || !bitutil.TestBytes(hs.ID) {
  160. return nil, DiscInvalidIdentity
  161. }
  162. return &hs, nil
  163. }