message.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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/enode"
  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 raw payload
  39. Payload io.Reader
  40. ReceivedAt time.Time
  41. meterCap Cap // Protocol name and version for egress metering
  42. meterCode uint64 // Message within protocol for egress metering
  43. meterSize uint32 // Compressed message size for ingress metering
  44. }
  45. // Decode parses the RLP content of a message into
  46. // the given value, which must be a pointer.
  47. //
  48. // For the decoding rules, please see package rlp.
  49. func (msg Msg) Decode(val interface{}) error {
  50. s := rlp.NewStream(msg.Payload, uint64(msg.Size))
  51. if err := s.Decode(val); err != nil {
  52. return newPeerError(errInvalidMsg, "(code %x) (size %d) %v", msg.Code, msg.Size, err)
  53. }
  54. return nil
  55. }
  56. func (msg Msg) String() string {
  57. return fmt.Sprintf("msg #%v (%v bytes)", msg.Code, msg.Size)
  58. }
  59. // Discard reads any remaining payload data into a black hole.
  60. func (msg Msg) Discard() error {
  61. _, err := io.Copy(ioutil.Discard, msg.Payload)
  62. return err
  63. }
  64. type MsgReader interface {
  65. ReadMsg() (Msg, error)
  66. }
  67. type MsgWriter interface {
  68. // WriteMsg sends a message. It will block until the message's
  69. // Payload has been consumed by the other end.
  70. //
  71. // Note that messages can be sent only once because their
  72. // payload reader is drained.
  73. WriteMsg(Msg) error
  74. }
  75. // MsgReadWriter provides reading and writing of encoded messages.
  76. // Implementations should ensure that ReadMsg and WriteMsg can be
  77. // called simultaneously from multiple goroutines.
  78. type MsgReadWriter interface {
  79. MsgReader
  80. MsgWriter
  81. }
  82. // Send writes an RLP-encoded message with the given code.
  83. // data should encode as an RLP list.
  84. func Send(w MsgWriter, msgcode uint64, data interface{}) error {
  85. size, r, err := rlp.EncodeToReader(data)
  86. if err != nil {
  87. return err
  88. }
  89. return w.WriteMsg(Msg{Code: msgcode, Size: uint32(size), Payload: r})
  90. }
  91. // SendItems writes an RLP with the given code and data elements.
  92. // For a call such as:
  93. //
  94. // SendItems(w, code, e1, e2, e3)
  95. //
  96. // the message payload will be an RLP list containing the items:
  97. //
  98. // [e1, e2, e3]
  99. //
  100. func SendItems(w MsgWriter, msgcode uint64, elems ...interface{}) error {
  101. return Send(w, msgcode, elems)
  102. }
  103. // eofSignal wraps a reader with eof signaling. the eof channel is
  104. // closed when the wrapped reader returns an error or when count bytes
  105. // have been read.
  106. type eofSignal struct {
  107. wrapped io.Reader
  108. count uint32 // number of bytes left
  109. eof chan<- struct{}
  110. }
  111. // note: when using eofSignal to detect whether a message payload
  112. // has been read, Read might not be called for zero sized messages.
  113. func (r *eofSignal) Read(buf []byte) (int, error) {
  114. if r.count == 0 {
  115. if r.eof != nil {
  116. r.eof <- struct{}{}
  117. r.eof = nil
  118. }
  119. return 0, io.EOF
  120. }
  121. max := len(buf)
  122. if int(r.count) < len(buf) {
  123. max = int(r.count)
  124. }
  125. n, err := r.wrapped.Read(buf[:max])
  126. r.count -= uint32(n)
  127. if (err != nil || r.count == 0) && r.eof != nil {
  128. r.eof <- struct{}{} // tell Peer that msg has been consumed
  129. r.eof = nil
  130. }
  131. return n, err
  132. }
  133. // MsgPipe creates a message pipe. Reads on one end are matched
  134. // with writes on the other. The pipe is full-duplex, both ends
  135. // implement MsgReadWriter.
  136. func MsgPipe() (*MsgPipeRW, *MsgPipeRW) {
  137. var (
  138. c1, c2 = make(chan Msg), make(chan Msg)
  139. closing = make(chan struct{})
  140. closed = new(int32)
  141. rw1 = &MsgPipeRW{c1, c2, closing, closed}
  142. rw2 = &MsgPipeRW{c2, c1, closing, closed}
  143. )
  144. return rw1, rw2
  145. }
  146. // ErrPipeClosed is returned from pipe operations after the
  147. // pipe has been closed.
  148. var ErrPipeClosed = errors.New("p2p: read or write on closed message pipe")
  149. // MsgPipeRW is an endpoint of a MsgReadWriter pipe.
  150. type MsgPipeRW struct {
  151. w chan<- Msg
  152. r <-chan Msg
  153. closing chan struct{}
  154. closed *int32
  155. }
  156. // WriteMsg sends a message on the pipe.
  157. // It blocks until the receiver has consumed the message payload.
  158. func (p *MsgPipeRW) WriteMsg(msg Msg) error {
  159. if atomic.LoadInt32(p.closed) == 0 {
  160. consumed := make(chan struct{}, 1)
  161. msg.Payload = &eofSignal{msg.Payload, msg.Size, consumed}
  162. select {
  163. case p.w <- msg:
  164. if msg.Size > 0 {
  165. // wait for payload read or discard
  166. select {
  167. case <-consumed:
  168. case <-p.closing:
  169. }
  170. }
  171. return nil
  172. case <-p.closing:
  173. }
  174. }
  175. return ErrPipeClosed
  176. }
  177. // ReadMsg returns a message sent on the other end of the pipe.
  178. func (p *MsgPipeRW) ReadMsg() (Msg, error) {
  179. if atomic.LoadInt32(p.closed) == 0 {
  180. select {
  181. case msg := <-p.r:
  182. return msg, nil
  183. case <-p.closing:
  184. }
  185. }
  186. return Msg{}, ErrPipeClosed
  187. }
  188. // Close unblocks any pending ReadMsg and WriteMsg calls on both ends
  189. // of the pipe. They will return ErrPipeClosed. Close also
  190. // interrupts any reads from a message payload.
  191. func (p *MsgPipeRW) Close() error {
  192. if atomic.AddInt32(p.closed, 1) != 1 {
  193. // someone else is already closing
  194. atomic.StoreInt32(p.closed, 1) // avoid overflow
  195. return nil
  196. }
  197. close(p.closing)
  198. return nil
  199. }
  200. // ExpectMsg reads a message from r and verifies that its
  201. // code and encoded RLP content match the provided values.
  202. // If content is nil, the payload is discarded and not verified.
  203. func ExpectMsg(r MsgReader, code uint64, content interface{}) error {
  204. msg, err := r.ReadMsg()
  205. if err != nil {
  206. return err
  207. }
  208. if msg.Code != code {
  209. return fmt.Errorf("message code mismatch: got %d, expected %d", msg.Code, code)
  210. }
  211. if content == nil {
  212. return msg.Discard()
  213. }
  214. contentEnc, err := rlp.EncodeToBytes(content)
  215. if err != nil {
  216. panic("content encode error: " + err.Error())
  217. }
  218. if int(msg.Size) != len(contentEnc) {
  219. return fmt.Errorf("message size mismatch: got %d, want %d", msg.Size, len(contentEnc))
  220. }
  221. actualContent, err := ioutil.ReadAll(msg.Payload)
  222. if err != nil {
  223. return err
  224. }
  225. if !bytes.Equal(actualContent, contentEnc) {
  226. return fmt.Errorf("message payload mismatch:\ngot: %x\nwant: %x", actualContent, contentEnc)
  227. }
  228. return nil
  229. }
  230. // msgEventer wraps a MsgReadWriter and sends events whenever a message is sent
  231. // or received
  232. type msgEventer struct {
  233. MsgReadWriter
  234. feed *event.Feed
  235. peerID enode.ID
  236. Protocol string
  237. localAddress string
  238. remoteAddress string
  239. }
  240. // newMsgEventer returns a msgEventer which sends message events to the given
  241. // feed
  242. func newMsgEventer(rw MsgReadWriter, feed *event.Feed, peerID enode.ID, proto, remote, local string) *msgEventer {
  243. return &msgEventer{
  244. MsgReadWriter: rw,
  245. feed: feed,
  246. peerID: peerID,
  247. Protocol: proto,
  248. remoteAddress: remote,
  249. localAddress: local,
  250. }
  251. }
  252. // ReadMsg reads a message from the underlying MsgReadWriter and emits a
  253. // "message received" event
  254. func (ev *msgEventer) ReadMsg() (Msg, error) {
  255. msg, err := ev.MsgReadWriter.ReadMsg()
  256. if err != nil {
  257. return msg, err
  258. }
  259. ev.feed.Send(&PeerEvent{
  260. Type: PeerEventTypeMsgRecv,
  261. Peer: ev.peerID,
  262. Protocol: ev.Protocol,
  263. MsgCode: &msg.Code,
  264. MsgSize: &msg.Size,
  265. LocalAddress: ev.localAddress,
  266. RemoteAddress: ev.remoteAddress,
  267. })
  268. return msg, nil
  269. }
  270. // WriteMsg writes a message to the underlying MsgReadWriter and emits a
  271. // "message sent" event
  272. func (ev *msgEventer) WriteMsg(msg Msg) error {
  273. err := ev.MsgReadWriter.WriteMsg(msg)
  274. if err != nil {
  275. return err
  276. }
  277. ev.feed.Send(&PeerEvent{
  278. Type: PeerEventTypeMsgSend,
  279. Peer: ev.peerID,
  280. Protocol: ev.Protocol,
  281. MsgCode: &msg.Code,
  282. MsgSize: &msg.Size,
  283. LocalAddress: ev.localAddress,
  284. RemoteAddress: ev.remoteAddress,
  285. })
  286. return nil
  287. }
  288. // Close closes the underlying MsgReadWriter if it implements the io.Closer
  289. // interface
  290. func (ev *msgEventer) Close() error {
  291. if v, ok := ev.MsgReadWriter.(io.Closer); ok {
  292. return v.Close()
  293. }
  294. return nil
  295. }