peer.go 12 KB

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