message.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. package p2p
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "math/big"
  10. "sync/atomic"
  11. "github.com/ethereum/go-ethereum/ethutil"
  12. "github.com/ethereum/go-ethereum/rlp"
  13. )
  14. // Msg defines the structure of a p2p message.
  15. //
  16. // Note that a Msg can only be sent once since the Payload reader is
  17. // consumed during sending. It is not possible to create a Msg and
  18. // send it any number of times. If you want to reuse an encoded
  19. // structure, encode the payload into a byte array and create a
  20. // separate Msg with a bytes.Reader as Payload for each send.
  21. type Msg struct {
  22. Code uint64
  23. Size uint32 // size of the paylod
  24. Payload io.Reader
  25. }
  26. // NewMsg creates an RLP-encoded message with the given code.
  27. func NewMsg(code uint64, params ...interface{}) Msg {
  28. buf := new(bytes.Buffer)
  29. for _, p := range params {
  30. buf.Write(ethutil.Encode(p))
  31. }
  32. return Msg{Code: code, Size: uint32(buf.Len()), Payload: buf}
  33. }
  34. func encodePayload(params ...interface{}) []byte {
  35. buf := new(bytes.Buffer)
  36. for _, p := range params {
  37. buf.Write(ethutil.Encode(p))
  38. }
  39. return buf.Bytes()
  40. }
  41. // Decode parse the RLP content of a message into
  42. // the given value, which must be a pointer.
  43. //
  44. // For the decoding rules, please see package rlp.
  45. func (msg Msg) Decode(val interface{}) error {
  46. s := rlp.NewListStream(msg.Payload, uint64(msg.Size))
  47. if err := s.Decode(val); err != nil {
  48. return newPeerError(errInvalidMsg, "(code %#x) (size %d) %v", msg.Code, msg.Size, err)
  49. }
  50. return nil
  51. }
  52. func (msg Msg) String() string {
  53. return fmt.Sprintf("msg #%v (%v bytes)", msg.Code, msg.Size)
  54. }
  55. // Discard reads any remaining payload data into a black hole.
  56. func (msg Msg) Discard() error {
  57. _, err := io.Copy(ioutil.Discard, msg.Payload)
  58. return err
  59. }
  60. type MsgReader interface {
  61. ReadMsg() (Msg, error)
  62. }
  63. type MsgWriter interface {
  64. // WriteMsg sends an existing message.
  65. // The Payload reader of the message is consumed.
  66. // Note that messages can be sent only once.
  67. WriteMsg(Msg) error
  68. // EncodeMsg writes an RLP-encoded message with the given
  69. // code and data elements.
  70. EncodeMsg(code uint64, data ...interface{}) error
  71. }
  72. // MsgReadWriter provides reading and writing of encoded messages.
  73. type MsgReadWriter interface {
  74. MsgReader
  75. MsgWriter
  76. }
  77. var magicToken = []byte{34, 64, 8, 145}
  78. func writeMsg(w io.Writer, msg Msg) error {
  79. // TODO: handle case when Size + len(code) + len(listhdr) overflows uint32
  80. code := ethutil.Encode(uint32(msg.Code))
  81. listhdr := makeListHeader(msg.Size + uint32(len(code)))
  82. payloadLen := uint32(len(listhdr)) + uint32(len(code)) + msg.Size
  83. start := make([]byte, 8)
  84. copy(start, magicToken)
  85. binary.BigEndian.PutUint32(start[4:], payloadLen)
  86. for _, b := range [][]byte{start, listhdr, code} {
  87. if _, err := w.Write(b); err != nil {
  88. return err
  89. }
  90. }
  91. _, err := io.CopyN(w, msg.Payload, int64(msg.Size))
  92. return err
  93. }
  94. func makeListHeader(length uint32) []byte {
  95. if length < 56 {
  96. return []byte{byte(length + 0xc0)}
  97. }
  98. enc := big.NewInt(int64(length)).Bytes()
  99. lenb := byte(len(enc)) + 0xf7
  100. return append([]byte{lenb}, enc...)
  101. }
  102. // readMsg reads a message header from r.
  103. // It takes an rlp.ByteReader to ensure that the decoding doesn't buffer.
  104. func readMsg(r rlp.ByteReader) (msg Msg, err error) {
  105. // read magic and payload size
  106. start := make([]byte, 8)
  107. if _, err = io.ReadFull(r, start); err != nil {
  108. return msg, newPeerError(errRead, "%v", err)
  109. }
  110. if !bytes.HasPrefix(start, magicToken) {
  111. return msg, newPeerError(errMagicTokenMismatch, "got %x, want %x", start[:4], magicToken)
  112. }
  113. size := binary.BigEndian.Uint32(start[4:])
  114. // decode start of RLP message to get the message code
  115. posr := &postrack{r, 0}
  116. s := rlp.NewStream(posr)
  117. if _, err := s.List(); err != nil {
  118. return msg, err
  119. }
  120. code, err := s.Uint()
  121. if err != nil {
  122. return msg, err
  123. }
  124. payloadsize := size - posr.p
  125. return Msg{code, payloadsize, io.LimitReader(r, int64(payloadsize))}, nil
  126. }
  127. // postrack wraps an rlp.ByteReader with a position counter.
  128. type postrack struct {
  129. r rlp.ByteReader
  130. p uint32
  131. }
  132. func (r *postrack) Read(buf []byte) (int, error) {
  133. n, err := r.r.Read(buf)
  134. r.p += uint32(n)
  135. return n, err
  136. }
  137. func (r *postrack) ReadByte() (byte, error) {
  138. b, err := r.r.ReadByte()
  139. if err == nil {
  140. r.p++
  141. }
  142. return b, err
  143. }
  144. // MsgPipe creates a message pipe. Reads on one end are matched
  145. // with writes on the other. The pipe is full-duplex, both ends
  146. // implement MsgReadWriter.
  147. func MsgPipe() (*MsgPipeRW, *MsgPipeRW) {
  148. var (
  149. c1, c2 = make(chan Msg), make(chan Msg)
  150. closing = make(chan struct{})
  151. closed = new(int32)
  152. rw1 = &MsgPipeRW{c1, c2, closing, closed}
  153. rw2 = &MsgPipeRW{c2, c1, closing, closed}
  154. )
  155. return rw1, rw2
  156. }
  157. // ErrPipeClosed is returned from pipe operations after the
  158. // pipe has been closed.
  159. var ErrPipeClosed = errors.New("p2p: read or write on closed message pipe")
  160. // MsgPipeRW is an endpoint of a MsgReadWriter pipe.
  161. type MsgPipeRW struct {
  162. w chan<- Msg
  163. r <-chan Msg
  164. closing chan struct{}
  165. closed *int32
  166. }
  167. // WriteMsg sends a messsage on the pipe.
  168. // It blocks until the receiver has consumed the message payload.
  169. func (p *MsgPipeRW) WriteMsg(msg Msg) error {
  170. if atomic.LoadInt32(p.closed) == 0 {
  171. consumed := make(chan struct{}, 1)
  172. msg.Payload = &eofSignal{msg.Payload, int64(msg.Size), consumed}
  173. select {
  174. case p.w <- msg:
  175. if msg.Size > 0 {
  176. // wait for payload read or discard
  177. <-consumed
  178. }
  179. return nil
  180. case <-p.closing:
  181. }
  182. }
  183. return ErrPipeClosed
  184. }
  185. // EncodeMsg is a convenient shorthand for sending an RLP-encoded message.
  186. func (p *MsgPipeRW) EncodeMsg(code uint64, data ...interface{}) error {
  187. return p.WriteMsg(NewMsg(code, data...))
  188. }
  189. // ReadMsg returns a message sent on the other end of the pipe.
  190. func (p *MsgPipeRW) ReadMsg() (Msg, error) {
  191. if atomic.LoadInt32(p.closed) == 0 {
  192. select {
  193. case msg := <-p.r:
  194. return msg, nil
  195. case <-p.closing:
  196. }
  197. }
  198. return Msg{}, ErrPipeClosed
  199. }
  200. // Close unblocks any pending ReadMsg and WriteMsg calls on both ends
  201. // of the pipe. They will return ErrPipeClosed. Note that Close does
  202. // not interrupt any reads from a message payload.
  203. func (p *MsgPipeRW) Close() error {
  204. if atomic.AddInt32(p.closed, 1) != 1 {
  205. // someone else is already closing
  206. atomic.StoreInt32(p.closed, 1) // avoid overflow
  207. return nil
  208. }
  209. close(p.closing)
  210. return nil
  211. }