message.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. "sync/atomic"
  24. "time"
  25. "github.com/ethereum/go-ethereum/event"
  26. "github.com/ethereum/go-ethereum/p2p/discover"
  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. // eofSignal wraps a reader with eof signaling. the eof channel is
  101. // closed when the wrapped reader returns an error or when count bytes
  102. // have been read.
  103. type eofSignal struct {
  104. wrapped io.Reader
  105. count uint32 // number of bytes left
  106. eof chan<- struct{}
  107. }
  108. // note: when using eofSignal to detect whether a message payload
  109. // has been read, Read might not be called for zero sized messages.
  110. func (r *eofSignal) Read(buf []byte) (int, error) {
  111. if r.count == 0 {
  112. if r.eof != nil {
  113. r.eof <- struct{}{}
  114. r.eof = nil
  115. }
  116. return 0, io.EOF
  117. }
  118. max := len(buf)
  119. if int(r.count) < len(buf) {
  120. max = int(r.count)
  121. }
  122. n, err := r.wrapped.Read(buf[:max])
  123. r.count -= uint32(n)
  124. if (err != nil || r.count == 0) && r.eof != nil {
  125. r.eof <- struct{}{} // tell Peer that msg has been consumed
  126. r.eof = nil
  127. }
  128. return n, err
  129. }
  130. // MsgPipe creates a message pipe. Reads on one end are matched
  131. // with writes on the other. The pipe is full-duplex, both ends
  132. // implement MsgReadWriter.
  133. func MsgPipe() (*MsgPipeRW, *MsgPipeRW) {
  134. var (
  135. c1, c2 = make(chan Msg), make(chan Msg)
  136. closing = make(chan struct{})
  137. closed = new(int32)
  138. rw1 = &MsgPipeRW{c1, c2, closing, closed}
  139. rw2 = &MsgPipeRW{c2, c1, closing, closed}
  140. )
  141. return rw1, rw2
  142. }
  143. // ErrPipeClosed is returned from pipe operations after the
  144. // pipe has been closed.
  145. var ErrPipeClosed = errors.New("p2p: read or write on closed message pipe")
  146. // MsgPipeRW is an endpoint of a MsgReadWriter pipe.
  147. type MsgPipeRW struct {
  148. w chan<- Msg
  149. r <-chan Msg
  150. closing chan struct{}
  151. closed *int32
  152. }
  153. // WriteMsg sends a messsage on the pipe.
  154. // It blocks until the receiver has consumed the message payload.
  155. func (p *MsgPipeRW) WriteMsg(msg Msg) error {
  156. if atomic.LoadInt32(p.closed) == 0 {
  157. consumed := make(chan struct{}, 1)
  158. msg.Payload = &eofSignal{msg.Payload, msg.Size, consumed}
  159. select {
  160. case p.w <- msg:
  161. if msg.Size > 0 {
  162. // wait for payload read or discard
  163. select {
  164. case <-consumed:
  165. case <-p.closing:
  166. }
  167. }
  168. return nil
  169. case <-p.closing:
  170. }
  171. }
  172. return ErrPipeClosed
  173. }
  174. // ReadMsg returns a message sent on the other end of the pipe.
  175. func (p *MsgPipeRW) ReadMsg() (Msg, error) {
  176. if atomic.LoadInt32(p.closed) == 0 {
  177. select {
  178. case msg := <-p.r:
  179. return msg, nil
  180. case <-p.closing:
  181. }
  182. }
  183. return Msg{}, ErrPipeClosed
  184. }
  185. // Close unblocks any pending ReadMsg and WriteMsg calls on both ends
  186. // of the pipe. They will return ErrPipeClosed. Close also
  187. // interrupts any reads from a message payload.
  188. func (p *MsgPipeRW) Close() error {
  189. if atomic.AddInt32(p.closed, 1) != 1 {
  190. // someone else is already closing
  191. atomic.StoreInt32(p.closed, 1) // avoid overflow
  192. return nil
  193. }
  194. close(p.closing)
  195. return nil
  196. }
  197. // ExpectMsg reads a message from r and verifies that its
  198. // code and encoded RLP content match the provided values.
  199. // If content is nil, the payload is discarded and not verified.
  200. func ExpectMsg(r MsgReader, code uint64, content interface{}) error {
  201. msg, err := r.ReadMsg()
  202. if err != nil {
  203. return err
  204. }
  205. if msg.Code != code {
  206. return fmt.Errorf("message code mismatch: got %d, expected %d", msg.Code, code)
  207. }
  208. if content == nil {
  209. return msg.Discard()
  210. }
  211. contentEnc, err := rlp.EncodeToBytes(content)
  212. if err != nil {
  213. panic("content encode error: " + err.Error())
  214. }
  215. if int(msg.Size) != len(contentEnc) {
  216. return fmt.Errorf("message size mismatch: got %d, want %d", msg.Size, len(contentEnc))
  217. }
  218. actualContent, err := ioutil.ReadAll(msg.Payload)
  219. if err != nil {
  220. return err
  221. }
  222. if !bytes.Equal(actualContent, contentEnc) {
  223. return fmt.Errorf("message payload mismatch:\ngot: %x\nwant: %x", actualContent, contentEnc)
  224. }
  225. return nil
  226. }
  227. // msgEventer wraps a MsgReadWriter and sends events whenever a message is sent
  228. // or received
  229. type msgEventer struct {
  230. MsgReadWriter
  231. feed *event.Feed
  232. peerID discover.NodeID
  233. Protocol string
  234. }
  235. // newMsgEventer returns a msgEventer which sends message events to the given
  236. // feed
  237. func newMsgEventer(rw MsgReadWriter, feed *event.Feed, peerID discover.NodeID, proto string) *msgEventer {
  238. return &msgEventer{
  239. MsgReadWriter: rw,
  240. feed: feed,
  241. peerID: peerID,
  242. Protocol: proto,
  243. }
  244. }
  245. // ReadMsg reads a message from the underlying MsgReadWriter and emits a
  246. // "message received" event
  247. func (ev *msgEventer) ReadMsg() (Msg, error) {
  248. msg, err := ev.MsgReadWriter.ReadMsg()
  249. if err != nil {
  250. return msg, err
  251. }
  252. ev.feed.Send(&PeerEvent{
  253. Type: PeerEventTypeMsgRecv,
  254. Peer: ev.peerID,
  255. Protocol: ev.Protocol,
  256. MsgCode: &msg.Code,
  257. MsgSize: &msg.Size,
  258. })
  259. return msg, nil
  260. }
  261. // WriteMsg writes a message to the underlying MsgReadWriter and emits a
  262. // "message sent" event
  263. func (ev *msgEventer) WriteMsg(msg Msg) error {
  264. err := ev.MsgReadWriter.WriteMsg(msg)
  265. if err != nil {
  266. return err
  267. }
  268. ev.feed.Send(&PeerEvent{
  269. Type: PeerEventTypeMsgSend,
  270. Peer: ev.peerID,
  271. Protocol: ev.Protocol,
  272. MsgCode: &msg.Code,
  273. MsgSize: &msg.Size,
  274. })
  275. return nil
  276. }
  277. // Close closes the underlying MsgReadWriter if it implements the io.Closer
  278. // interface
  279. func (ev *msgEventer) Close() error {
  280. if v, ok := ev.MsgReadWriter.(io.Closer); ok {
  281. return v.Close()
  282. }
  283. return nil
  284. }