message.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. package p2p
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. "github.com/ethereum/go-ethereum/common"
  13. "github.com/ethereum/go-ethereum/rlp"
  14. )
  15. // Msg defines the structure of a p2p message.
  16. //
  17. // Note that a Msg can only be sent once since the Payload reader is
  18. // consumed during sending. It is not possible to create a Msg and
  19. // send it any number of times. If you want to reuse an encoded
  20. // structure, encode the payload into a byte array and create a
  21. // separate Msg with a bytes.Reader as Payload for each send.
  22. type Msg struct {
  23. Code uint64
  24. Size uint32 // size of the paylod
  25. Payload io.Reader
  26. }
  27. // NewMsg creates an RLP-encoded message with the given code.
  28. func NewMsg(code uint64, params ...interface{}) Msg {
  29. p := bytes.NewReader(common.Encode(params))
  30. return Msg{Code: code, Size: uint32(p.Len()), Payload: p}
  31. }
  32. // Decode parse the RLP content of a message into
  33. // the given value, which must be a pointer.
  34. //
  35. // For the decoding rules, please see package rlp.
  36. func (msg Msg) Decode(val interface{}) error {
  37. if err := rlp.Decode(msg.Payload, val); err != nil {
  38. return newPeerError(errInvalidMsg, "(code %#x) (size %d) %v", msg.Code, msg.Size, err)
  39. }
  40. return nil
  41. }
  42. func (msg Msg) String() string {
  43. return fmt.Sprintf("msg #%v (%v bytes)", msg.Code, msg.Size)
  44. }
  45. // Discard reads any remaining payload data into a black hole.
  46. func (msg Msg) Discard() error {
  47. _, err := io.Copy(ioutil.Discard, msg.Payload)
  48. return err
  49. }
  50. type MsgReader interface {
  51. ReadMsg() (Msg, error)
  52. }
  53. type MsgWriter interface {
  54. // WriteMsg sends a message. It will block until the message's
  55. // Payload has been consumed by the other end.
  56. //
  57. // Note that messages can be sent only once because their
  58. // payload reader is drained.
  59. WriteMsg(Msg) error
  60. }
  61. // MsgReadWriter provides reading and writing of encoded messages.
  62. // Implementations should ensure that ReadMsg and WriteMsg can be
  63. // called simultaneously from multiple goroutines.
  64. type MsgReadWriter interface {
  65. MsgReader
  66. MsgWriter
  67. }
  68. // EncodeMsg writes an RLP-encoded message with the given code and
  69. // data elements.
  70. func EncodeMsg(w MsgWriter, code uint64, data ...interface{}) error {
  71. return w.WriteMsg(NewMsg(code, data...))
  72. }
  73. // netWrapper wrapsa MsgReadWriter with locks around
  74. // ReadMsg/WriteMsg and applies read/write deadlines.
  75. type netWrapper struct {
  76. rmu, wmu sync.Mutex
  77. rtimeout, wtimeout time.Duration
  78. conn net.Conn
  79. wrapped MsgReadWriter
  80. }
  81. func (rw *netWrapper) ReadMsg() (Msg, error) {
  82. rw.rmu.Lock()
  83. defer rw.rmu.Unlock()
  84. rw.conn.SetReadDeadline(time.Now().Add(rw.rtimeout))
  85. return rw.wrapped.ReadMsg()
  86. }
  87. func (rw *netWrapper) WriteMsg(msg Msg) error {
  88. rw.wmu.Lock()
  89. defer rw.wmu.Unlock()
  90. rw.conn.SetWriteDeadline(time.Now().Add(rw.wtimeout))
  91. return rw.wrapped.WriteMsg(msg)
  92. }
  93. // eofSignal wraps a reader with eof signaling. the eof channel is
  94. // closed when the wrapped reader returns an error or when count bytes
  95. // have been read.
  96. type eofSignal struct {
  97. wrapped io.Reader
  98. count uint32 // number of bytes left
  99. eof chan<- struct{}
  100. }
  101. // note: when using eofSignal to detect whether a message payload
  102. // has been read, Read might not be called for zero sized messages.
  103. func (r *eofSignal) Read(buf []byte) (int, error) {
  104. if r.count == 0 {
  105. if r.eof != nil {
  106. r.eof <- struct{}{}
  107. r.eof = nil
  108. }
  109. return 0, io.EOF
  110. }
  111. max := len(buf)
  112. if int(r.count) < len(buf) {
  113. max = int(r.count)
  114. }
  115. n, err := r.wrapped.Read(buf[:max])
  116. r.count -= uint32(n)
  117. if (err != nil || r.count == 0) && r.eof != nil {
  118. r.eof <- struct{}{} // tell Peer that msg has been consumed
  119. r.eof = nil
  120. }
  121. return n, err
  122. }
  123. // MsgPipe creates a message pipe. Reads on one end are matched
  124. // with writes on the other. The pipe is full-duplex, both ends
  125. // implement MsgReadWriter.
  126. func MsgPipe() (*MsgPipeRW, *MsgPipeRW) {
  127. var (
  128. c1, c2 = make(chan Msg), make(chan Msg)
  129. closing = make(chan struct{})
  130. closed = new(int32)
  131. rw1 = &MsgPipeRW{c1, c2, closing, closed}
  132. rw2 = &MsgPipeRW{c2, c1, closing, closed}
  133. )
  134. return rw1, rw2
  135. }
  136. // ErrPipeClosed is returned from pipe operations after the
  137. // pipe has been closed.
  138. var ErrPipeClosed = errors.New("p2p: read or write on closed message pipe")
  139. // MsgPipeRW is an endpoint of a MsgReadWriter pipe.
  140. type MsgPipeRW struct {
  141. w chan<- Msg
  142. r <-chan Msg
  143. closing chan struct{}
  144. closed *int32
  145. }
  146. // WriteMsg sends a messsage on the pipe.
  147. // It blocks until the receiver has consumed the message payload.
  148. func (p *MsgPipeRW) WriteMsg(msg Msg) error {
  149. if atomic.LoadInt32(p.closed) == 0 {
  150. consumed := make(chan struct{}, 1)
  151. msg.Payload = &eofSignal{msg.Payload, msg.Size, consumed}
  152. select {
  153. case p.w <- msg:
  154. if msg.Size > 0 {
  155. // wait for payload read or discard
  156. <-consumed
  157. }
  158. return nil
  159. case <-p.closing:
  160. }
  161. }
  162. return ErrPipeClosed
  163. }
  164. // ReadMsg returns a message sent on the other end of the pipe.
  165. func (p *MsgPipeRW) ReadMsg() (Msg, error) {
  166. if atomic.LoadInt32(p.closed) == 0 {
  167. select {
  168. case msg := <-p.r:
  169. return msg, nil
  170. case <-p.closing:
  171. }
  172. }
  173. return Msg{}, ErrPipeClosed
  174. }
  175. // Close unblocks any pending ReadMsg and WriteMsg calls on both ends
  176. // of the pipe. They will return ErrPipeClosed. Note that Close does
  177. // not interrupt any reads from a message payload.
  178. func (p *MsgPipeRW) Close() error {
  179. if atomic.AddInt32(p.closed, 1) != 1 {
  180. // someone else is already closing
  181. atomic.StoreInt32(p.closed, 1) // avoid overflow
  182. return nil
  183. }
  184. close(p.closing)
  185. return nil
  186. }