peer.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. func newPeer(conn *conn, protocols []Protocol) *Peer {
  137. protomap := matchProtocols(protocols, conn.caps, conn)
  138. p := &Peer{
  139. rw: conn,
  140. running: protomap,
  141. created: mclock.Now(),
  142. disc: make(chan DiscReason),
  143. protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop
  144. closed: make(chan struct{}),
  145. log: log.New("id", conn.id, "conn", conn.flags),
  146. }
  147. return p
  148. }
  149. func (p *Peer) Log() log.Logger {
  150. return p.log
  151. }
  152. func (p *Peer) run() (remoteRequested bool, err error) {
  153. var (
  154. writeStart = make(chan struct{}, 1)
  155. writeErr = make(chan error, 1)
  156. readErr = make(chan error, 1)
  157. reason DiscReason // sent to the peer
  158. )
  159. p.wg.Add(2)
  160. go p.readLoop(readErr)
  161. go p.pingLoop()
  162. // Start all protocol handlers.
  163. writeStart <- struct{}{}
  164. p.startProtocols(writeStart, writeErr)
  165. // Wait for an error or disconnect.
  166. loop:
  167. for {
  168. select {
  169. case err = <-writeErr:
  170. // A write finished. Allow the next write to start if
  171. // there was no error.
  172. if err != nil {
  173. reason = DiscNetworkError
  174. break loop
  175. }
  176. writeStart <- struct{}{}
  177. case err = <-readErr:
  178. if r, ok := err.(DiscReason); ok {
  179. remoteRequested = true
  180. reason = r
  181. } else {
  182. reason = DiscNetworkError
  183. }
  184. break loop
  185. case err = <-p.protoErr:
  186. reason = discReasonForError(err)
  187. break loop
  188. case err = <-p.disc:
  189. break loop
  190. }
  191. }
  192. close(p.closed)
  193. p.rw.close(reason)
  194. p.wg.Wait()
  195. return remoteRequested, err
  196. }
  197. func (p *Peer) pingLoop() {
  198. ping := time.NewTimer(pingInterval)
  199. defer p.wg.Done()
  200. defer ping.Stop()
  201. for {
  202. select {
  203. case <-ping.C:
  204. if err := SendItems(p.rw, pingMsg); err != nil {
  205. p.protoErr <- err
  206. return
  207. }
  208. ping.Reset(pingInterval)
  209. case <-p.closed:
  210. return
  211. }
  212. }
  213. }
  214. func (p *Peer) readLoop(errc chan<- error) {
  215. defer p.wg.Done()
  216. for {
  217. msg, err := p.rw.ReadMsg()
  218. if err != nil {
  219. errc <- err
  220. return
  221. }
  222. msg.ReceivedAt = time.Now()
  223. if err = p.handle(msg); err != nil {
  224. errc <- err
  225. return
  226. }
  227. }
  228. }
  229. func (p *Peer) handle(msg Msg) error {
  230. switch {
  231. case msg.Code == pingMsg:
  232. msg.Discard()
  233. go SendItems(p.rw, pongMsg)
  234. case msg.Code == discMsg:
  235. var reason [1]DiscReason
  236. // This is the last message. We don't need to discard or
  237. // check errors because, the connection will be closed after it.
  238. rlp.Decode(msg.Payload, &reason)
  239. return reason[0]
  240. case msg.Code < baseProtocolLength:
  241. // ignore other base protocol messages
  242. return msg.Discard()
  243. default:
  244. // it's a subprotocol message
  245. proto, err := p.getProto(msg.Code)
  246. if err != nil {
  247. return fmt.Errorf("msg code out of range: %v", msg.Code)
  248. }
  249. select {
  250. case proto.in <- msg:
  251. return nil
  252. case <-p.closed:
  253. return io.EOF
  254. }
  255. }
  256. return nil
  257. }
  258. func countMatchingProtocols(protocols []Protocol, caps []Cap) int {
  259. n := 0
  260. for _, cap := range caps {
  261. for _, proto := range protocols {
  262. if proto.Name == cap.Name && proto.Version == cap.Version {
  263. n++
  264. }
  265. }
  266. }
  267. return n
  268. }
  269. // matchProtocols creates structures for matching named subprotocols.
  270. func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW {
  271. sort.Sort(capsByNameAndVersion(caps))
  272. offset := baseProtocolLength
  273. result := make(map[string]*protoRW)
  274. outer:
  275. for _, cap := range caps {
  276. for _, proto := range protocols {
  277. if proto.Name == cap.Name && proto.Version == cap.Version {
  278. // If an old protocol version matched, revert it
  279. if old := result[cap.Name]; old != nil {
  280. offset -= old.Length
  281. }
  282. // Assign the new match
  283. result[cap.Name] = &protoRW{Protocol: proto, offset: offset, in: make(chan Msg), w: rw}
  284. offset += proto.Length
  285. continue outer
  286. }
  287. }
  288. }
  289. return result
  290. }
  291. func (p *Peer) startProtocols(writeStart <-chan struct{}, writeErr chan<- error) {
  292. p.wg.Add(len(p.running))
  293. for _, proto := range p.running {
  294. proto := proto
  295. proto.closed = p.closed
  296. proto.wstart = writeStart
  297. proto.werr = writeErr
  298. var rw MsgReadWriter = proto
  299. if p.events != nil {
  300. rw = newMsgEventer(rw, p.events, p.ID(), proto.Name)
  301. }
  302. p.log.Trace(fmt.Sprintf("Starting protocol %s/%d", proto.Name, proto.Version))
  303. go func() {
  304. err := proto.Run(p, rw)
  305. if err == nil {
  306. p.log.Trace(fmt.Sprintf("Protocol %s/%d returned", proto.Name, proto.Version))
  307. err = errProtocolReturned
  308. } else if err != io.EOF {
  309. p.log.Trace(fmt.Sprintf("Protocol %s/%d failed", proto.Name, proto.Version), "err", err)
  310. }
  311. p.protoErr <- err
  312. p.wg.Done()
  313. }()
  314. }
  315. }
  316. // getProto finds the protocol responsible for handling
  317. // the given message code.
  318. func (p *Peer) getProto(code uint64) (*protoRW, error) {
  319. for _, proto := range p.running {
  320. if code >= proto.offset && code < proto.offset+proto.Length {
  321. return proto, nil
  322. }
  323. }
  324. return nil, newPeerError(errInvalidMsgCode, "%d", code)
  325. }
  326. type protoRW struct {
  327. Protocol
  328. in chan Msg // receices read messages
  329. closed <-chan struct{} // receives when peer is shutting down
  330. wstart <-chan struct{} // receives when write may start
  331. werr chan<- error // for write results
  332. offset uint64
  333. w MsgWriter
  334. }
  335. func (rw *protoRW) WriteMsg(msg Msg) (err error) {
  336. if msg.Code >= rw.Length {
  337. return newPeerError(errInvalidMsgCode, "not handled")
  338. }
  339. msg.Code += rw.offset
  340. select {
  341. case <-rw.wstart:
  342. err = rw.w.WriteMsg(msg)
  343. // Report write status back to Peer.run. It will initiate
  344. // shutdown if the error is non-nil and unblock the next write
  345. // otherwise. The calling protocol code should exit for errors
  346. // as well but we don't want to rely on that.
  347. rw.werr <- err
  348. case <-rw.closed:
  349. err = fmt.Errorf("shutting down")
  350. }
  351. return err
  352. }
  353. func (rw *protoRW) ReadMsg() (Msg, error) {
  354. select {
  355. case msg := <-rw.in:
  356. msg.Code -= rw.offset
  357. return msg, nil
  358. case <-rw.closed:
  359. return Msg{}, io.EOF
  360. }
  361. }
  362. // PeerInfo represents a short summary of the information known about a connected
  363. // peer. Sub-protocol independent fields are contained and initialized here, with
  364. // protocol specifics delegated to all connected sub-protocols.
  365. type PeerInfo struct {
  366. ID string `json:"id"` // Unique node identifier (also the encryption key)
  367. Name string `json:"name"` // Name of the node, including client type, version, OS, custom data
  368. Caps []string `json:"caps"` // Sum-protocols advertised by this particular peer
  369. Network struct {
  370. LocalAddress string `json:"localAddress"` // Local endpoint of the TCP data connection
  371. RemoteAddress string `json:"remoteAddress"` // Remote endpoint of the TCP data connection
  372. } `json:"network"`
  373. Protocols map[string]interface{} `json:"protocols"` // Sub-protocol specific metadata fields
  374. }
  375. // Info gathers and returns a collection of metadata known about a peer.
  376. func (p *Peer) Info() *PeerInfo {
  377. // Gather the protocol capabilities
  378. var caps []string
  379. for _, cap := range p.Caps() {
  380. caps = append(caps, cap.String())
  381. }
  382. // Assemble the generic peer metadata
  383. info := &PeerInfo{
  384. ID: p.ID().String(),
  385. Name: p.Name(),
  386. Caps: caps,
  387. Protocols: make(map[string]interface{}),
  388. }
  389. info.Network.LocalAddress = p.LocalAddr().String()
  390. info.Network.RemoteAddress = p.RemoteAddr().String()
  391. // Gather all the running protocol infos
  392. for _, proto := range p.running {
  393. protoInfo := interface{}("unknown")
  394. if query := proto.Protocol.PeerInfo; query != nil {
  395. if metadata := query(p.ID()); metadata != nil {
  396. protoInfo = metadata
  397. } else {
  398. protoInfo = "handshake"
  399. }
  400. }
  401. info.Protocols[proto.Name] = protoInfo
  402. }
  403. return info
  404. }