message.go 9.2 KB

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