peer.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. "errors"
  19. "fmt"
  20. "io"
  21. "net"
  22. "sort"
  23. "sync"
  24. "time"
  25. "github.com/ethereum/go-ethereum/logger"
  26. "github.com/ethereum/go-ethereum/logger/glog"
  27. "github.com/ethereum/go-ethereum/p2p/discover"
  28. "github.com/ethereum/go-ethereum/rlp"
  29. )
  30. const (
  31. baseProtocolVersion = 4
  32. baseProtocolLength = uint64(16)
  33. baseProtocolMaxMsgSize = 2 * 1024
  34. pingInterval = 15 * time.Second
  35. )
  36. const (
  37. // devp2p message codes
  38. handshakeMsg = 0x00
  39. discMsg = 0x01
  40. pingMsg = 0x02
  41. pongMsg = 0x03
  42. getPeersMsg = 0x04
  43. peersMsg = 0x05
  44. )
  45. // protoHandshake is the RLP structure of the protocol handshake.
  46. type protoHandshake struct {
  47. Version uint64
  48. Name string
  49. Caps []Cap
  50. ListenPort uint64
  51. ID discover.NodeID
  52. }
  53. // Peer represents a connected remote node.
  54. type Peer struct {
  55. rw *conn
  56. running map[string]*protoRW
  57. wg sync.WaitGroup
  58. protoErr chan error
  59. closed chan struct{}
  60. disc chan DiscReason
  61. }
  62. // NewPeer returns a peer for testing purposes.
  63. func NewPeer(id discover.NodeID, name string, caps []Cap) *Peer {
  64. pipe, _ := net.Pipe()
  65. conn := &conn{fd: pipe, transport: nil, id: id, caps: caps, name: name}
  66. peer := newPeer(conn, nil)
  67. close(peer.closed) // ensures Disconnect doesn't block
  68. return peer
  69. }
  70. // ID returns the node's public key.
  71. func (p *Peer) ID() discover.NodeID {
  72. return p.rw.id
  73. }
  74. // Name returns the node name that the remote node advertised.
  75. func (p *Peer) Name() string {
  76. return p.rw.name
  77. }
  78. // Caps returns the capabilities (supported subprotocols) of the remote peer.
  79. func (p *Peer) Caps() []Cap {
  80. // TODO: maybe return copy
  81. return p.rw.caps
  82. }
  83. // RemoteAddr returns the remote address of the network connection.
  84. func (p *Peer) RemoteAddr() net.Addr {
  85. return p.rw.fd.RemoteAddr()
  86. }
  87. // LocalAddr returns the local address of the network connection.
  88. func (p *Peer) LocalAddr() net.Addr {
  89. return p.rw.fd.LocalAddr()
  90. }
  91. // Disconnect terminates the peer connection with the given reason.
  92. // It returns immediately and does not wait until the connection is closed.
  93. func (p *Peer) Disconnect(reason DiscReason) {
  94. select {
  95. case p.disc <- reason:
  96. case <-p.closed:
  97. }
  98. }
  99. // String implements fmt.Stringer.
  100. func (p *Peer) String() string {
  101. return fmt.Sprintf("Peer %x %v", p.rw.id[:8], p.RemoteAddr())
  102. }
  103. func newPeer(conn *conn, protocols []Protocol) *Peer {
  104. protomap := matchProtocols(protocols, conn.caps, conn)
  105. p := &Peer{
  106. rw: conn,
  107. running: protomap,
  108. disc: make(chan DiscReason),
  109. protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop
  110. closed: make(chan struct{}),
  111. }
  112. return p
  113. }
  114. func (p *Peer) run() DiscReason {
  115. var (
  116. writeStart = make(chan struct{}, 1)
  117. writeErr = make(chan error, 1)
  118. readErr = make(chan error, 1)
  119. reason DiscReason
  120. requested bool
  121. )
  122. p.wg.Add(2)
  123. go p.readLoop(readErr)
  124. go p.pingLoop()
  125. // Start all protocol handlers.
  126. writeStart <- struct{}{}
  127. p.startProtocols(writeStart, writeErr)
  128. // Wait for an error or disconnect.
  129. loop:
  130. for {
  131. select {
  132. case err := <-writeErr:
  133. // A write finished. Allow the next write to start if
  134. // there was no error.
  135. if err != nil {
  136. glog.V(logger.Detail).Infof("%v: write error: %v\n", p, err)
  137. reason = DiscNetworkError
  138. break loop
  139. }
  140. writeStart <- struct{}{}
  141. case err := <-readErr:
  142. if r, ok := err.(DiscReason); ok {
  143. glog.V(logger.Debug).Infof("%v: remote requested disconnect: %v\n", p, r)
  144. requested = true
  145. reason = r
  146. } else {
  147. glog.V(logger.Detail).Infof("%v: read error: %v\n", p, err)
  148. reason = DiscNetworkError
  149. }
  150. break loop
  151. case err := <-p.protoErr:
  152. reason = discReasonForError(err)
  153. glog.V(logger.Debug).Infof("%v: protocol error: %v (%v)\n", p, err, reason)
  154. break loop
  155. case reason = <-p.disc:
  156. glog.V(logger.Debug).Infof("%v: locally requested disconnect: %v\n", p, reason)
  157. break loop
  158. }
  159. }
  160. close(p.closed)
  161. p.rw.close(reason)
  162. p.wg.Wait()
  163. if requested {
  164. reason = DiscRequested
  165. }
  166. return reason
  167. }
  168. func (p *Peer) pingLoop() {
  169. ping := time.NewTicker(pingInterval)
  170. defer p.wg.Done()
  171. defer ping.Stop()
  172. for {
  173. select {
  174. case <-ping.C:
  175. if err := SendItems(p.rw, pingMsg); err != nil {
  176. p.protoErr <- err
  177. return
  178. }
  179. case <-p.closed:
  180. return
  181. }
  182. }
  183. }
  184. func (p *Peer) readLoop(errc chan<- error) {
  185. defer p.wg.Done()
  186. for {
  187. msg, err := p.rw.ReadMsg()
  188. if err != nil {
  189. errc <- err
  190. return
  191. }
  192. msg.ReceivedAt = time.Now()
  193. if err = p.handle(msg); err != nil {
  194. errc <- err
  195. return
  196. }
  197. }
  198. }
  199. func (p *Peer) handle(msg Msg) error {
  200. switch {
  201. case msg.Code == pingMsg:
  202. msg.Discard()
  203. go SendItems(p.rw, pongMsg)
  204. case msg.Code == discMsg:
  205. var reason [1]DiscReason
  206. // This is the last message. We don't need to discard or
  207. // check errors because, the connection will be closed after it.
  208. rlp.Decode(msg.Payload, &reason)
  209. return reason[0]
  210. case msg.Code < baseProtocolLength:
  211. // ignore other base protocol messages
  212. return msg.Discard()
  213. default:
  214. // it's a subprotocol message
  215. proto, err := p.getProto(msg.Code)
  216. if err != nil {
  217. return fmt.Errorf("msg code out of range: %v", msg.Code)
  218. }
  219. select {
  220. case proto.in <- msg:
  221. return nil
  222. case <-p.closed:
  223. return io.EOF
  224. }
  225. }
  226. return nil
  227. }
  228. func countMatchingProtocols(protocols []Protocol, caps []Cap) int {
  229. n := 0
  230. for _, cap := range caps {
  231. for _, proto := range protocols {
  232. if proto.Name == cap.Name && proto.Version == cap.Version {
  233. n++
  234. }
  235. }
  236. }
  237. return n
  238. }
  239. // matchProtocols creates structures for matching named subprotocols.
  240. func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW {
  241. sort.Sort(capsByNameAndVersion(caps))
  242. offset := baseProtocolLength
  243. result := make(map[string]*protoRW)
  244. outer:
  245. for _, cap := range caps {
  246. for _, proto := range protocols {
  247. if proto.Name == cap.Name && proto.Version == cap.Version {
  248. // If an old protocol version matched, revert it
  249. if old := result[cap.Name]; old != nil {
  250. offset -= old.Length
  251. }
  252. // Assign the new match
  253. result[cap.Name] = &protoRW{Protocol: proto, offset: offset, in: make(chan Msg), w: rw}
  254. offset += proto.Length
  255. continue outer
  256. }
  257. }
  258. }
  259. return result
  260. }
  261. func (p *Peer) startProtocols(writeStart <-chan struct{}, writeErr chan<- error) {
  262. p.wg.Add(len(p.running))
  263. for _, proto := range p.running {
  264. proto := proto
  265. proto.closed = p.closed
  266. proto.wstart = writeStart
  267. proto.werr = writeErr
  268. glog.V(logger.Detail).Infof("%v: Starting protocol %s/%d\n", p, proto.Name, proto.Version)
  269. go func() {
  270. err := proto.Run(p, proto)
  271. if err == nil {
  272. glog.V(logger.Detail).Infof("%v: Protocol %s/%d returned\n", p, proto.Name, proto.Version)
  273. err = errors.New("protocol returned")
  274. } else if err != io.EOF {
  275. glog.V(logger.Detail).Infof("%v: Protocol %s/%d error: %v\n", p, proto.Name, proto.Version, err)
  276. }
  277. p.protoErr <- err
  278. p.wg.Done()
  279. }()
  280. }
  281. }
  282. // getProto finds the protocol responsible for handling
  283. // the given message code.
  284. func (p *Peer) getProto(code uint64) (*protoRW, error) {
  285. for _, proto := range p.running {
  286. if code >= proto.offset && code < proto.offset+proto.Length {
  287. return proto, nil
  288. }
  289. }
  290. return nil, newPeerError(errInvalidMsgCode, "%d", code)
  291. }
  292. type protoRW struct {
  293. Protocol
  294. in chan Msg // receices read messages
  295. closed <-chan struct{} // receives when peer is shutting down
  296. wstart <-chan struct{} // receives when write may start
  297. werr chan<- error // for write results
  298. offset uint64
  299. w MsgWriter
  300. }
  301. func (rw *protoRW) WriteMsg(msg Msg) (err error) {
  302. if msg.Code >= rw.Length {
  303. return newPeerError(errInvalidMsgCode, "not handled")
  304. }
  305. msg.Code += rw.offset
  306. select {
  307. case <-rw.wstart:
  308. err = rw.w.WriteMsg(msg)
  309. // Report write status back to Peer.run. It will initiate
  310. // shutdown if the error is non-nil and unblock the next write
  311. // otherwise. The calling protocol code should exit for errors
  312. // as well but we don't want to rely on that.
  313. rw.werr <- err
  314. case <-rw.closed:
  315. err = fmt.Errorf("shutting down")
  316. }
  317. return err
  318. }
  319. func (rw *protoRW) ReadMsg() (Msg, error) {
  320. select {
  321. case msg := <-rw.in:
  322. msg.Code -= rw.offset
  323. return msg, nil
  324. case <-rw.closed:
  325. return Msg{}, io.EOF
  326. }
  327. }
  328. // PeerInfo represents a short summary of the information known about a connected
  329. // peer. Sub-protocol independent fields are contained and initialized here, with
  330. // protocol specifics delegated to all connected sub-protocols.
  331. type PeerInfo struct {
  332. ID string `json:"id"` // Unique node identifier (also the encryption key)
  333. Name string `json:"name"` // Name of the node, including client type, version, OS, custom data
  334. Caps []string `json:"caps"` // Sum-protocols advertised by this particular peer
  335. Network struct {
  336. LocalAddress string `json:"localAddress"` // Local endpoint of the TCP data connection
  337. RemoteAddress string `json:"remoteAddress"` // Remote endpoint of the TCP data connection
  338. } `json:"network"`
  339. Protocols map[string]interface{} `json:"protocols"` // Sub-protocol specific metadata fields
  340. }
  341. // Info gathers and returns a collection of metadata known about a peer.
  342. func (p *Peer) Info() *PeerInfo {
  343. // Gather the protocol capabilities
  344. var caps []string
  345. for _, cap := range p.Caps() {
  346. caps = append(caps, cap.String())
  347. }
  348. // Assemble the generic peer metadata
  349. info := &PeerInfo{
  350. ID: p.ID().String(),
  351. Name: p.Name(),
  352. Caps: caps,
  353. Protocols: make(map[string]interface{}),
  354. }
  355. info.Network.LocalAddress = p.LocalAddr().String()
  356. info.Network.RemoteAddress = p.RemoteAddr().String()
  357. // Gather all the running protocol infos
  358. for _, proto := range p.running {
  359. protoInfo := interface{}("unknown")
  360. if query := proto.Protocol.PeerInfo; query != nil {
  361. if metadata := query(p.ID()); metadata != nil {
  362. protoInfo = metadata
  363. } else {
  364. protoInfo = "handshake"
  365. }
  366. }
  367. info.Protocols[proto.Name] = protoInfo
  368. }
  369. return info
  370. }