peer.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. package p2p
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net"
  7. "sort"
  8. "sync"
  9. "time"
  10. "github.com/ethereum/go-ethereum/logger"
  11. "github.com/ethereum/go-ethereum/logger/glog"
  12. "github.com/ethereum/go-ethereum/p2p/discover"
  13. "github.com/ethereum/go-ethereum/rlp"
  14. )
  15. const (
  16. baseProtocolVersion = 4
  17. baseProtocolLength = uint64(16)
  18. baseProtocolMaxMsgSize = 2 * 1024
  19. pingInterval = 15 * time.Second
  20. )
  21. const (
  22. // devp2p message codes
  23. handshakeMsg = 0x00
  24. discMsg = 0x01
  25. pingMsg = 0x02
  26. pongMsg = 0x03
  27. getPeersMsg = 0x04
  28. peersMsg = 0x05
  29. )
  30. // protoHandshake is the RLP structure of the protocol handshake.
  31. type protoHandshake struct {
  32. Version uint64
  33. Name string
  34. Caps []Cap
  35. ListenPort uint64
  36. ID discover.NodeID
  37. }
  38. // Peer represents a connected remote node.
  39. type Peer struct {
  40. rw *conn
  41. running map[string]*protoRW
  42. wg sync.WaitGroup
  43. protoErr chan error
  44. closed chan struct{}
  45. disc chan DiscReason
  46. }
  47. // NewPeer returns a peer for testing purposes.
  48. func NewPeer(id discover.NodeID, name string, caps []Cap) *Peer {
  49. pipe, _ := net.Pipe()
  50. conn := &conn{fd: pipe, transport: nil, id: id, caps: caps, name: name}
  51. peer := newPeer(conn, nil)
  52. close(peer.closed) // ensures Disconnect doesn't block
  53. return peer
  54. }
  55. // ID returns the node's public key.
  56. func (p *Peer) ID() discover.NodeID {
  57. return p.rw.id
  58. }
  59. // Name returns the node name that the remote node advertised.
  60. func (p *Peer) Name() string {
  61. return p.rw.name
  62. }
  63. // Caps returns the capabilities (supported subprotocols) of the remote peer.
  64. func (p *Peer) Caps() []Cap {
  65. // TODO: maybe return copy
  66. return p.rw.caps
  67. }
  68. // RemoteAddr returns the remote address of the network connection.
  69. func (p *Peer) RemoteAddr() net.Addr {
  70. return p.rw.fd.RemoteAddr()
  71. }
  72. // LocalAddr returns the local address of the network connection.
  73. func (p *Peer) LocalAddr() net.Addr {
  74. return p.rw.fd.LocalAddr()
  75. }
  76. // Disconnect terminates the peer connection with the given reason.
  77. // It returns immediately and does not wait until the connection is closed.
  78. func (p *Peer) Disconnect(reason DiscReason) {
  79. select {
  80. case p.disc <- reason:
  81. case <-p.closed:
  82. }
  83. }
  84. // String implements fmt.Stringer.
  85. func (p *Peer) String() string {
  86. return fmt.Sprintf("Peer %x %v", p.rw.id[:8], p.RemoteAddr())
  87. }
  88. func newPeer(conn *conn, protocols []Protocol) *Peer {
  89. protomap := matchProtocols(protocols, conn.caps, conn)
  90. p := &Peer{
  91. rw: conn,
  92. running: protomap,
  93. disc: make(chan DiscReason),
  94. protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop
  95. closed: make(chan struct{}),
  96. }
  97. return p
  98. }
  99. func (p *Peer) run() DiscReason {
  100. var (
  101. writeStart = make(chan struct{}, 1)
  102. writeErr = make(chan error, 1)
  103. readErr = make(chan error, 1)
  104. reason DiscReason
  105. requested bool
  106. )
  107. p.wg.Add(2)
  108. go p.readLoop(readErr)
  109. go p.pingLoop()
  110. // Start all protocol handlers.
  111. writeStart <- struct{}{}
  112. p.startProtocols(writeStart, writeErr)
  113. // Wait for an error or disconnect.
  114. loop:
  115. for {
  116. select {
  117. case err := <-writeErr:
  118. // A write finished. Allow the next write to start if
  119. // there was no error.
  120. if err != nil {
  121. glog.V(logger.Detail).Infof("%v: Write error: %v\n", p, err)
  122. reason = DiscNetworkError
  123. break loop
  124. }
  125. writeStart <- struct{}{}
  126. case err := <-readErr:
  127. if r, ok := err.(DiscReason); ok {
  128. reason = r
  129. } else {
  130. glog.V(logger.Detail).Infof("%v: Read error: %v\n", p, err)
  131. reason = DiscNetworkError
  132. }
  133. break loop
  134. case err := <-p.protoErr:
  135. reason = discReasonForError(err)
  136. break loop
  137. case reason = <-p.disc:
  138. requested = true
  139. break loop
  140. }
  141. }
  142. close(p.closed)
  143. p.rw.close(reason)
  144. p.wg.Wait()
  145. if requested {
  146. reason = DiscRequested
  147. }
  148. glog.V(logger.Debug).Infof("%v: Disconnected: %v\n", p, reason)
  149. return reason
  150. }
  151. func (p *Peer) pingLoop() {
  152. ping := time.NewTicker(pingInterval)
  153. defer p.wg.Done()
  154. defer ping.Stop()
  155. for {
  156. select {
  157. case <-ping.C:
  158. if err := SendItems(p.rw, pingMsg); err != nil {
  159. p.protoErr <- err
  160. return
  161. }
  162. case <-p.closed:
  163. return
  164. }
  165. }
  166. }
  167. func (p *Peer) readLoop(errc chan<- error) {
  168. defer p.wg.Done()
  169. for {
  170. msg, err := p.rw.ReadMsg()
  171. if err != nil {
  172. errc <- err
  173. return
  174. }
  175. msg.ReceivedAt = time.Now()
  176. if err = p.handle(msg); err != nil {
  177. errc <- err
  178. return
  179. }
  180. }
  181. }
  182. func (p *Peer) handle(msg Msg) error {
  183. switch {
  184. case msg.Code == pingMsg:
  185. msg.Discard()
  186. go SendItems(p.rw, pongMsg)
  187. case msg.Code == discMsg:
  188. var reason [1]DiscReason
  189. // This is the last message. We don't need to discard or
  190. // check errors because, the connection will be closed after it.
  191. rlp.Decode(msg.Payload, &reason)
  192. glog.V(logger.Debug).Infof("%v: Disconnect Requested: %v\n", p, reason[0])
  193. return reason[0]
  194. case msg.Code < baseProtocolLength:
  195. // ignore other base protocol messages
  196. return msg.Discard()
  197. default:
  198. // it's a subprotocol message
  199. proto, err := p.getProto(msg.Code)
  200. if err != nil {
  201. return fmt.Errorf("msg code out of range: %v", msg.Code)
  202. }
  203. select {
  204. case proto.in <- msg:
  205. return nil
  206. case <-p.closed:
  207. return io.EOF
  208. }
  209. }
  210. return nil
  211. }
  212. func countMatchingProtocols(protocols []Protocol, caps []Cap) int {
  213. n := 0
  214. for _, cap := range caps {
  215. for _, proto := range protocols {
  216. if proto.Name == cap.Name && proto.Version == cap.Version {
  217. n++
  218. }
  219. }
  220. }
  221. return n
  222. }
  223. // matchProtocols creates structures for matching named subprotocols.
  224. func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW {
  225. sort.Sort(capsByName(caps))
  226. offset := baseProtocolLength
  227. result := make(map[string]*protoRW)
  228. outer:
  229. for _, cap := range caps {
  230. for _, proto := range protocols {
  231. if proto.Name == cap.Name && proto.Version == cap.Version && result[cap.Name] == nil {
  232. result[cap.Name] = &protoRW{Protocol: proto, offset: offset, in: make(chan Msg), w: rw}
  233. offset += proto.Length
  234. continue outer
  235. }
  236. }
  237. }
  238. return result
  239. }
  240. func (p *Peer) startProtocols(writeStart <-chan struct{}, writeErr chan<- error) {
  241. p.wg.Add(len(p.running))
  242. for _, proto := range p.running {
  243. proto := proto
  244. proto.closed = p.closed
  245. proto.wstart = writeStart
  246. proto.werr = writeErr
  247. glog.V(logger.Detail).Infof("%v: Starting protocol %s/%d\n", p, proto.Name, proto.Version)
  248. go func() {
  249. err := proto.Run(p, proto)
  250. if err == nil {
  251. glog.V(logger.Detail).Infof("%v: Protocol %s/%d returned\n", p, proto.Name, proto.Version)
  252. err = errors.New("protocol returned")
  253. } else if err != io.EOF {
  254. glog.V(logger.Detail).Infof("%v: Protocol %s/%d error: %v\n", p, proto.Name, proto.Version, err)
  255. }
  256. p.protoErr <- err
  257. p.wg.Done()
  258. }()
  259. }
  260. }
  261. // getProto finds the protocol responsible for handling
  262. // the given message code.
  263. func (p *Peer) getProto(code uint64) (*protoRW, error) {
  264. for _, proto := range p.running {
  265. if code >= proto.offset && code < proto.offset+proto.Length {
  266. return proto, nil
  267. }
  268. }
  269. return nil, newPeerError(errInvalidMsgCode, "%d", code)
  270. }
  271. type protoRW struct {
  272. Protocol
  273. in chan Msg // receices read messages
  274. closed <-chan struct{} // receives when peer is shutting down
  275. wstart <-chan struct{} // receives when write may start
  276. werr chan<- error // for write results
  277. offset uint64
  278. w MsgWriter
  279. }
  280. func (rw *protoRW) WriteMsg(msg Msg) (err error) {
  281. if msg.Code >= rw.Length {
  282. return newPeerError(errInvalidMsgCode, "not handled")
  283. }
  284. msg.Code += rw.offset
  285. select {
  286. case <-rw.wstart:
  287. err = rw.w.WriteMsg(msg)
  288. // Report write status back to Peer.run. It will initiate
  289. // shutdown if the error is non-nil and unblock the next write
  290. // otherwise. The calling protocol code should exit for errors
  291. // as well but we don't want to rely on that.
  292. rw.werr <- err
  293. case <-rw.closed:
  294. err = fmt.Errorf("shutting down")
  295. }
  296. return err
  297. }
  298. func (rw *protoRW) ReadMsg() (Msg, error) {
  299. select {
  300. case msg := <-rw.in:
  301. msg.Code -= rw.offset
  302. return msg, nil
  303. case <-rw.closed:
  304. return Msg{}, io.EOF
  305. }
  306. }