message.go 9.0 KB

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