message.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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/rlp"
  13. )
  14. // Msg defines the structure of a p2p message.
  15. //
  16. // Note that a Msg can only be sent once since the Payload reader is
  17. // consumed during sending. It is not possible to create a Msg and
  18. // send it any number of times. If you want to reuse an encoded
  19. // structure, encode the payload into a byte array and create a
  20. // separate Msg with a bytes.Reader as Payload for each send.
  21. type Msg struct {
  22. Code uint64
  23. Size uint32 // size of the paylod
  24. Payload io.Reader
  25. ReceivedAt time.Time
  26. }
  27. // Decode parses the RLP content of a message into
  28. // the given value, which must be a pointer.
  29. //
  30. // For the decoding rules, please see package rlp.
  31. func (msg Msg) Decode(val interface{}) error {
  32. s := rlp.NewStream(msg.Payload, uint64(msg.Size))
  33. if err := s.Decode(val); err != nil {
  34. return newPeerError(errInvalidMsg, "(code %x) (size %d) %v", msg.Code, msg.Size, err)
  35. }
  36. return nil
  37. }
  38. func (msg Msg) String() string {
  39. return fmt.Sprintf("msg #%v (%v bytes)", msg.Code, msg.Size)
  40. }
  41. // Discard reads any remaining payload data into a black hole.
  42. func (msg Msg) Discard() error {
  43. _, err := io.Copy(ioutil.Discard, msg.Payload)
  44. return err
  45. }
  46. type MsgReader interface {
  47. ReadMsg() (Msg, error)
  48. }
  49. type MsgWriter interface {
  50. // WriteMsg sends a message. It will block until the message's
  51. // Payload has been consumed by the other end.
  52. //
  53. // Note that messages can be sent only once because their
  54. // payload reader is drained.
  55. WriteMsg(Msg) error
  56. }
  57. // MsgReadWriter provides reading and writing of encoded messages.
  58. // Implementations should ensure that ReadMsg and WriteMsg can be
  59. // called simultaneously from multiple goroutines.
  60. type MsgReadWriter interface {
  61. MsgReader
  62. MsgWriter
  63. }
  64. // Send writes an RLP-encoded message with the given code.
  65. // data should encode as an RLP list.
  66. func Send(w MsgWriter, msgcode uint64, data interface{}) error {
  67. size, r, err := rlp.EncodeToReader(data)
  68. if err != nil {
  69. return err
  70. }
  71. return w.WriteMsg(Msg{Code: msgcode, Size: uint32(size), Payload: r})
  72. }
  73. // SendItems writes an RLP with the given code and data elements.
  74. // For a call such as:
  75. //
  76. // SendItems(w, code, e1, e2, e3)
  77. //
  78. // the message payload will be an RLP list containing the items:
  79. //
  80. // [e1, e2, e3]
  81. //
  82. func SendItems(w MsgWriter, msgcode uint64, elems ...interface{}) error {
  83. return Send(w, msgcode, elems)
  84. }
  85. // netWrapper wraps a MsgReadWriter with locks around
  86. // ReadMsg/WriteMsg and applies read/write deadlines.
  87. type netWrapper struct {
  88. rmu, wmu sync.Mutex
  89. rtimeout, wtimeout time.Duration
  90. conn net.Conn
  91. wrapped MsgReadWriter
  92. }
  93. func (rw *netWrapper) ReadMsg() (Msg, error) {
  94. rw.rmu.Lock()
  95. defer rw.rmu.Unlock()
  96. rw.conn.SetReadDeadline(time.Now().Add(rw.rtimeout))
  97. return rw.wrapped.ReadMsg()
  98. }
  99. func (rw *netWrapper) WriteMsg(msg Msg) error {
  100. rw.wmu.Lock()
  101. defer rw.wmu.Unlock()
  102. rw.conn.SetWriteDeadline(time.Now().Add(rw.wtimeout))
  103. return rw.wrapped.WriteMsg(msg)
  104. }
  105. // eofSignal wraps a reader with eof signaling. the eof channel is
  106. // closed when the wrapped reader returns an error or when count bytes
  107. // have been read.
  108. type eofSignal struct {
  109. wrapped io.Reader
  110. count uint32 // number of bytes left
  111. eof chan<- struct{}
  112. }
  113. // note: when using eofSignal to detect whether a message payload
  114. // has been read, Read might not be called for zero sized messages.
  115. func (r *eofSignal) Read(buf []byte) (int, error) {
  116. if r.count == 0 {
  117. if r.eof != nil {
  118. r.eof <- struct{}{}
  119. r.eof = nil
  120. }
  121. return 0, io.EOF
  122. }
  123. max := len(buf)
  124. if int(r.count) < len(buf) {
  125. max = int(r.count)
  126. }
  127. n, err := r.wrapped.Read(buf[:max])
  128. r.count -= uint32(n)
  129. if (err != nil || r.count == 0) && r.eof != nil {
  130. r.eof <- struct{}{} // tell Peer that msg has been consumed
  131. r.eof = nil
  132. }
  133. return n, err
  134. }
  135. // MsgPipe creates a message pipe. Reads on one end are matched
  136. // with writes on the other. The pipe is full-duplex, both ends
  137. // implement MsgReadWriter.
  138. func MsgPipe() (*MsgPipeRW, *MsgPipeRW) {
  139. var (
  140. c1, c2 = make(chan Msg), make(chan Msg)
  141. closing = make(chan struct{})
  142. closed = new(int32)
  143. rw1 = &MsgPipeRW{c1, c2, closing, closed}
  144. rw2 = &MsgPipeRW{c2, c1, closing, closed}
  145. )
  146. return rw1, rw2
  147. }
  148. // ErrPipeClosed is returned from pipe operations after the
  149. // pipe has been closed.
  150. var ErrPipeClosed = errors.New("p2p: read or write on closed message pipe")
  151. // MsgPipeRW is an endpoint of a MsgReadWriter pipe.
  152. type MsgPipeRW struct {
  153. w chan<- Msg
  154. r <-chan Msg
  155. closing chan struct{}
  156. closed *int32
  157. }
  158. // WriteMsg sends a messsage on the pipe.
  159. // It blocks until the receiver has consumed the message payload.
  160. func (p *MsgPipeRW) WriteMsg(msg Msg) error {
  161. if atomic.LoadInt32(p.closed) == 0 {
  162. consumed := make(chan struct{}, 1)
  163. msg.Payload = &eofSignal{msg.Payload, msg.Size, consumed}
  164. select {
  165. case p.w <- msg:
  166. if msg.Size > 0 {
  167. // wait for payload read or discard
  168. select {
  169. case <-consumed:
  170. case <-p.closing:
  171. }
  172. }
  173. return nil
  174. case <-p.closing:
  175. }
  176. }
  177. return ErrPipeClosed
  178. }
  179. // ReadMsg returns a message sent on the other end of the pipe.
  180. func (p *MsgPipeRW) ReadMsg() (Msg, error) {
  181. if atomic.LoadInt32(p.closed) == 0 {
  182. select {
  183. case msg := <-p.r:
  184. return msg, nil
  185. case <-p.closing:
  186. }
  187. }
  188. return Msg{}, ErrPipeClosed
  189. }
  190. // Close unblocks any pending ReadMsg and WriteMsg calls on both ends
  191. // of the pipe. They will return ErrPipeClosed. Close also
  192. // interrupts any reads from a message payload.
  193. func (p *MsgPipeRW) Close() error {
  194. if atomic.AddInt32(p.closed, 1) != 1 {
  195. // someone else is already closing
  196. atomic.StoreInt32(p.closed, 1) // avoid overflow
  197. return nil
  198. }
  199. close(p.closing)
  200. return nil
  201. }
  202. // ExpectMsg reads a message from r and verifies that its
  203. // code and encoded RLP content match the provided values.
  204. // If content is nil, the payload is discarded and not verified.
  205. func ExpectMsg(r MsgReader, code uint64, content interface{}) error {
  206. msg, err := r.ReadMsg()
  207. if err != nil {
  208. return err
  209. }
  210. if msg.Code != code {
  211. return fmt.Errorf("message code mismatch: got %d, expected %d", msg.Code, code)
  212. }
  213. if content == nil {
  214. return msg.Discard()
  215. } else {
  216. contentEnc, err := rlp.EncodeToBytes(content)
  217. if err != nil {
  218. panic("content encode error: " + err.Error())
  219. }
  220. if int(msg.Size) != len(contentEnc) {
  221. return fmt.Errorf("message size mismatch: got %d, want %d", msg.Size, len(contentEnc))
  222. }
  223. actualContent, err := ioutil.ReadAll(msg.Payload)
  224. if err != nil {
  225. return err
  226. }
  227. if !bytes.Equal(actualContent, contentEnc) {
  228. return fmt.Errorf("message payload mismatch:\ngot: %x\nwant: %x", actualContent, contentEnc)
  229. }
  230. }
  231. return nil
  232. }