message.go 6.3 KB

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