message.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 a message. It will block until the message's
  65. // Payload has been consumed by the other end.
  66. //
  67. // Note that messages can be sent only once.
  68. WriteMsg(Msg) error
  69. }
  70. // MsgReadWriter provides reading and writing of encoded messages.
  71. type MsgReadWriter interface {
  72. MsgReader
  73. MsgWriter
  74. }
  75. // EncodeMsg writes an RLP-encoded message with the given code and
  76. // data elements.
  77. func EncodeMsg(w MsgWriter, code uint64, data ...interface{}) error {
  78. return w.WriteMsg(NewMsg(code, data...))
  79. }
  80. var magicToken = []byte{34, 64, 8, 145}
  81. func writeMsg(w io.Writer, msg Msg) error {
  82. // TODO: handle case when Size + len(code) + len(listhdr) overflows uint32
  83. code := ethutil.Encode(uint32(msg.Code))
  84. listhdr := makeListHeader(msg.Size + uint32(len(code)))
  85. payloadLen := uint32(len(listhdr)) + uint32(len(code)) + msg.Size
  86. start := make([]byte, 8)
  87. copy(start, magicToken)
  88. binary.BigEndian.PutUint32(start[4:], payloadLen)
  89. for _, b := range [][]byte{start, listhdr, code} {
  90. if _, err := w.Write(b); err != nil {
  91. return err
  92. }
  93. }
  94. _, err := io.CopyN(w, msg.Payload, int64(msg.Size))
  95. return err
  96. }
  97. func makeListHeader(length uint32) []byte {
  98. if length < 56 {
  99. return []byte{byte(length + 0xc0)}
  100. }
  101. enc := big.NewInt(int64(length)).Bytes()
  102. lenb := byte(len(enc)) + 0xf7
  103. return append([]byte{lenb}, enc...)
  104. }
  105. // readMsg reads a message header from r.
  106. // It takes an rlp.ByteReader to ensure that the decoding doesn't buffer.
  107. func readMsg(r rlp.ByteReader) (msg Msg, err error) {
  108. // read magic and payload size
  109. start := make([]byte, 8)
  110. if _, err = io.ReadFull(r, start); err != nil {
  111. return msg, newPeerError(errRead, "%v", err)
  112. }
  113. if !bytes.HasPrefix(start, magicToken) {
  114. return msg, newPeerError(errMagicTokenMismatch, "got %x, want %x", start[:4], magicToken)
  115. }
  116. size := binary.BigEndian.Uint32(start[4:])
  117. // decode start of RLP message to get the message code
  118. posr := &postrack{r, 0}
  119. s := rlp.NewStream(posr)
  120. if _, err := s.List(); err != nil {
  121. return msg, err
  122. }
  123. code, err := s.Uint()
  124. if err != nil {
  125. return msg, err
  126. }
  127. payloadsize := size - posr.p
  128. return Msg{code, payloadsize, io.LimitReader(r, int64(payloadsize))}, nil
  129. }
  130. // postrack wraps an rlp.ByteReader with a position counter.
  131. type postrack struct {
  132. r rlp.ByteReader
  133. p uint32
  134. }
  135. func (r *postrack) Read(buf []byte) (int, error) {
  136. n, err := r.r.Read(buf)
  137. r.p += uint32(n)
  138. return n, err
  139. }
  140. func (r *postrack) ReadByte() (byte, error) {
  141. b, err := r.r.ReadByte()
  142. if err == nil {
  143. r.p++
  144. }
  145. return b, err
  146. }
  147. // MsgPipe creates a message pipe. Reads on one end are matched
  148. // with writes on the other. The pipe is full-duplex, both ends
  149. // implement MsgReadWriter.
  150. func MsgPipe() (*MsgPipeRW, *MsgPipeRW) {
  151. var (
  152. c1, c2 = make(chan Msg), make(chan Msg)
  153. closing = make(chan struct{})
  154. closed = new(int32)
  155. rw1 = &MsgPipeRW{c1, c2, closing, closed}
  156. rw2 = &MsgPipeRW{c2, c1, closing, closed}
  157. )
  158. return rw1, rw2
  159. }
  160. // ErrPipeClosed is returned from pipe operations after the
  161. // pipe has been closed.
  162. var ErrPipeClosed = errors.New("p2p: read or write on closed message pipe")
  163. // MsgPipeRW is an endpoint of a MsgReadWriter pipe.
  164. type MsgPipeRW struct {
  165. w chan<- Msg
  166. r <-chan Msg
  167. closing chan struct{}
  168. closed *int32
  169. }
  170. // WriteMsg sends a messsage on the pipe.
  171. // It blocks until the receiver has consumed the message payload.
  172. func (p *MsgPipeRW) WriteMsg(msg Msg) error {
  173. if atomic.LoadInt32(p.closed) == 0 {
  174. consumed := make(chan struct{}, 1)
  175. msg.Payload = &eofSignal{msg.Payload, int64(msg.Size), consumed}
  176. select {
  177. case p.w <- msg:
  178. if msg.Size > 0 {
  179. // wait for payload read or discard
  180. <-consumed
  181. }
  182. return nil
  183. case <-p.closing:
  184. }
  185. }
  186. return ErrPipeClosed
  187. }
  188. // ReadMsg returns a message sent on the other end of the pipe.
  189. func (p *MsgPipeRW) ReadMsg() (Msg, error) {
  190. if atomic.LoadInt32(p.closed) == 0 {
  191. select {
  192. case msg := <-p.r:
  193. return msg, nil
  194. case <-p.closing:
  195. }
  196. }
  197. return Msg{}, ErrPipeClosed
  198. }
  199. // Close unblocks any pending ReadMsg and WriteMsg calls on both ends
  200. // of the pipe. They will return ErrPipeClosed. Note that Close does
  201. // not interrupt any reads from a message payload.
  202. func (p *MsgPipeRW) Close() error {
  203. if atomic.AddInt32(p.closed, 1) != 1 {
  204. // someone else is already closing
  205. atomic.StoreInt32(p.closed, 1) // avoid overflow
  206. return nil
  207. }
  208. close(p.closing)
  209. return nil
  210. }