peer.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. glog.V(logger.Debug).Infof("%v: remote requested disconnect: %v\n", p, r)
  129. requested = true
  130. reason = r
  131. } else {
  132. glog.V(logger.Detail).Infof("%v: read error: %v\n", p, err)
  133. reason = DiscNetworkError
  134. }
  135. break loop
  136. case err := <-p.protoErr:
  137. reason = discReasonForError(err)
  138. glog.V(logger.Debug).Infof("%v: protocol error: %v (%v)\n", p, err, reason)
  139. break loop
  140. case reason = <-p.disc:
  141. glog.V(logger.Debug).Infof("%v: locally requested disconnect: %v\n", p, reason)
  142. break loop
  143. }
  144. }
  145. close(p.closed)
  146. p.rw.close(reason)
  147. p.wg.Wait()
  148. if requested {
  149. reason = DiscRequested
  150. }
  151. return reason
  152. }
  153. func (p *Peer) pingLoop() {
  154. ping := time.NewTicker(pingInterval)
  155. defer p.wg.Done()
  156. defer ping.Stop()
  157. for {
  158. select {
  159. case <-ping.C:
  160. if err := SendItems(p.rw, pingMsg); err != nil {
  161. p.protoErr <- err
  162. return
  163. }
  164. case <-p.closed:
  165. return
  166. }
  167. }
  168. }
  169. func (p *Peer) readLoop(errc chan<- error) {
  170. defer p.wg.Done()
  171. for {
  172. msg, err := p.rw.ReadMsg()
  173. if err != nil {
  174. errc <- err
  175. return
  176. }
  177. msg.ReceivedAt = time.Now()
  178. if err = p.handle(msg); err != nil {
  179. errc <- err
  180. return
  181. }
  182. }
  183. }
  184. func (p *Peer) handle(msg Msg) error {
  185. switch {
  186. case msg.Code == pingMsg:
  187. msg.Discard()
  188. go SendItems(p.rw, pongMsg)
  189. case msg.Code == discMsg:
  190. var reason [1]DiscReason
  191. // This is the last message. We don't need to discard or
  192. // check errors because, the connection will be closed after it.
  193. rlp.Decode(msg.Payload, &reason)
  194. return reason[0]
  195. case msg.Code < baseProtocolLength:
  196. // ignore other base protocol messages
  197. return msg.Discard()
  198. default:
  199. // it's a subprotocol message
  200. proto, err := p.getProto(msg.Code)
  201. if err != nil {
  202. return fmt.Errorf("msg code out of range: %v", msg.Code)
  203. }
  204. select {
  205. case proto.in <- msg:
  206. return nil
  207. case <-p.closed:
  208. return io.EOF
  209. }
  210. }
  211. return nil
  212. }
  213. func countMatchingProtocols(protocols []Protocol, caps []Cap) int {
  214. n := 0
  215. for _, cap := range caps {
  216. for _, proto := range protocols {
  217. if proto.Name == cap.Name && proto.Version == cap.Version {
  218. n++
  219. }
  220. }
  221. }
  222. return n
  223. }
  224. // matchProtocols creates structures for matching named subprotocols.
  225. func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW {
  226. sort.Sort(capsByNameAndVersion(caps))
  227. offset := baseProtocolLength
  228. result := make(map[string]*protoRW)
  229. outer:
  230. for _, cap := range caps {
  231. for _, proto := range protocols {
  232. if proto.Name == cap.Name && proto.Version == cap.Version {
  233. // If an old protocol version matched, revert it
  234. if old := result[cap.Name]; old != nil {
  235. offset -= old.Length
  236. }
  237. // Assign the new match
  238. result[cap.Name] = &protoRW{Protocol: proto, offset: offset, in: make(chan Msg), w: rw}
  239. offset += proto.Length
  240. continue outer
  241. }
  242. }
  243. }
  244. return result
  245. }
  246. func (p *Peer) startProtocols(writeStart <-chan struct{}, writeErr chan<- error) {
  247. p.wg.Add(len(p.running))
  248. for _, proto := range p.running {
  249. proto := proto
  250. proto.closed = p.closed
  251. proto.wstart = writeStart
  252. proto.werr = writeErr
  253. glog.V(logger.Detail).Infof("%v: Starting protocol %s/%d\n", p, proto.Name, proto.Version)
  254. go func() {
  255. err := proto.Run(p, proto)
  256. if err == nil {
  257. glog.V(logger.Detail).Infof("%v: Protocol %s/%d returned\n", p, proto.Name, proto.Version)
  258. err = errors.New("protocol returned")
  259. } else if err != io.EOF {
  260. glog.V(logger.Detail).Infof("%v: Protocol %s/%d error: %v\n", p, proto.Name, proto.Version, err)
  261. }
  262. p.protoErr <- err
  263. p.wg.Done()
  264. }()
  265. }
  266. }
  267. // getProto finds the protocol responsible for handling
  268. // the given message code.
  269. func (p *Peer) getProto(code uint64) (*protoRW, error) {
  270. for _, proto := range p.running {
  271. if code >= proto.offset && code < proto.offset+proto.Length {
  272. return proto, nil
  273. }
  274. }
  275. return nil, newPeerError(errInvalidMsgCode, "%d", code)
  276. }
  277. type protoRW struct {
  278. Protocol
  279. in chan Msg // receices read messages
  280. closed <-chan struct{} // receives when peer is shutting down
  281. wstart <-chan struct{} // receives when write may start
  282. werr chan<- error // for write results
  283. offset uint64
  284. w MsgWriter
  285. }
  286. func (rw *protoRW) WriteMsg(msg Msg) (err error) {
  287. if msg.Code >= rw.Length {
  288. return newPeerError(errInvalidMsgCode, "not handled")
  289. }
  290. msg.Code += rw.offset
  291. select {
  292. case <-rw.wstart:
  293. err = rw.w.WriteMsg(msg)
  294. // Report write status back to Peer.run. It will initiate
  295. // shutdown if the error is non-nil and unblock the next write
  296. // otherwise. The calling protocol code should exit for errors
  297. // as well but we don't want to rely on that.
  298. rw.werr <- err
  299. case <-rw.closed:
  300. err = fmt.Errorf("shutting down")
  301. }
  302. return err
  303. }
  304. func (rw *protoRW) ReadMsg() (Msg, error) {
  305. select {
  306. case msg := <-rw.in:
  307. msg.Code -= rw.offset
  308. return msg, nil
  309. case <-rw.closed:
  310. return Msg{}, io.EOF
  311. }
  312. }