peer.go 11 KB

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