transport.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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/common/gopool"
  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. msg = Msg{
  58. ReceivedAt: time.Now(),
  59. Code: code,
  60. Size: uint32(len(data)),
  61. meterSize: uint32(wireSize),
  62. Payload: bytes.NewReader(data),
  63. }
  64. }
  65. return msg, err
  66. }
  67. func (t *rlpxTransport) WriteMsg(msg Msg) error {
  68. t.wmu.Lock()
  69. defer t.wmu.Unlock()
  70. // Copy message data to write buffer.
  71. t.wbuf.Reset()
  72. if _, err := io.CopyN(&t.wbuf, msg.Payload, int64(msg.Size)); err != nil {
  73. return err
  74. }
  75. // Write the message.
  76. t.conn.SetWriteDeadline(time.Now().Add(frameWriteTimeout))
  77. size, err := t.conn.Write(msg.Code, t.wbuf.Bytes())
  78. if err != nil {
  79. return err
  80. }
  81. // Set metrics.
  82. msg.meterSize = size
  83. if metrics.Enabled && msg.meterCap.Name != "" { // don't meter non-subprotocol messages
  84. m := fmt.Sprintf("%s/%s/%d/%#02x", egressMeterName, msg.meterCap.Name, msg.meterCap.Version, msg.meterCode)
  85. metrics.GetOrRegisterMeter(m, nil).Mark(int64(msg.meterSize))
  86. metrics.GetOrRegisterMeter(m+"/packets", nil).Mark(1)
  87. }
  88. return nil
  89. }
  90. func (t *rlpxTransport) close(err error) {
  91. t.wmu.Lock()
  92. defer t.wmu.Unlock()
  93. // Tell the remote end why we're disconnecting if possible.
  94. // We only bother doing this if the underlying connection supports
  95. // setting a timeout tough.
  96. if t.conn != nil {
  97. if r, ok := err.(DiscReason); ok && r != DiscNetworkError {
  98. deadline := time.Now().Add(discWriteTimeout)
  99. if err := t.conn.SetWriteDeadline(deadline); err == nil {
  100. // Connection supports write deadline.
  101. t.wbuf.Reset()
  102. rlp.Encode(&t.wbuf, []DiscReason{r})
  103. t.conn.Write(discMsg, t.wbuf.Bytes())
  104. }
  105. }
  106. }
  107. t.conn.Close()
  108. }
  109. func (t *rlpxTransport) doEncHandshake(prv *ecdsa.PrivateKey) (*ecdsa.PublicKey, error) {
  110. t.conn.SetDeadline(time.Now().Add(handshakeTimeout))
  111. return t.conn.Handshake(prv)
  112. }
  113. func (t *rlpxTransport) doProtoHandshake(our *protoHandshake) (their *protoHandshake, err error) {
  114. // Writing our handshake happens concurrently, we prefer
  115. // returning the handshake read error. If the remote side
  116. // disconnects us early with a valid reason, we should return it
  117. // as the error so it can be tracked elsewhere.
  118. werr := make(chan error, 1)
  119. gopool.Submit(func() { werr <- Send(t, handshakeMsg, our) })
  120. if their, err = readProtocolHandshake(t); err != nil {
  121. <-werr // make sure the write terminates too
  122. return nil, err
  123. }
  124. if err := <-werr; err != nil {
  125. return nil, fmt.Errorf("write error: %v", err)
  126. }
  127. // If the protocol version supports Snappy encoding, upgrade immediately
  128. t.conn.SetSnappy(their.Version >= snappyProtocolVersion)
  129. return their, nil
  130. }
  131. func readProtocolHandshake(rw MsgReader) (*protoHandshake, error) {
  132. msg, err := rw.ReadMsg()
  133. if err != nil {
  134. return nil, err
  135. }
  136. if msg.Size > baseProtocolMaxMsgSize {
  137. return nil, fmt.Errorf("message too big")
  138. }
  139. if msg.Code == discMsg {
  140. // Disconnect before protocol handshake is valid according to the
  141. // spec and we send it ourself if the post-handshake checks fail.
  142. // We can't return the reason directly, though, because it is echoed
  143. // back otherwise. Wrap it in a string instead.
  144. var reason [1]DiscReason
  145. rlp.Decode(msg.Payload, &reason)
  146. return nil, reason[0]
  147. }
  148. if msg.Code != handshakeMsg {
  149. return nil, fmt.Errorf("expected handshake, got %x", msg.Code)
  150. }
  151. var hs protoHandshake
  152. if err := msg.Decode(&hs); err != nil {
  153. return nil, err
  154. }
  155. if len(hs.ID) != 64 || !bitutil.TestBytes(hs.ID) {
  156. return nil, DiscInvalidIdentity
  157. }
  158. return &hs, nil
  159. }