message.go 7.4 KB

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