peer.go 12 KB

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