peer.go 10 KB

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