Skip to content

Commit d4f0a67

Browse files
committed
p2p: drop connections with no matching protocols
1 parent e45d9bb commit d4f0a67

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

p2p/peer.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,18 @@ func (p *Peer) handle(msg Msg) error {
211211
return nil
212212
}
213213

214+
func countMatchingProtocols(protocols []Protocol, caps []Cap) int {
215+
n := 0
216+
for _, cap := range caps {
217+
for _, proto := range protocols {
218+
if proto.Name == cap.Name && proto.Version == cap.Version {
219+
n++
220+
}
221+
}
222+
}
223+
return n
224+
}
225+
214226
// matchProtocols creates structures for matching named subprotocols.
215227
func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW {
216228
sort.Sort(capsByName(caps))

p2p/server.go

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -518,7 +518,7 @@ func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) {
518518
conn: fd, rtimeout: frameReadTimeout, wtimeout: frameWriteTimeout,
519519
}
520520
p := newPeer(fd, conn, srv.Protocols)
521-
if ok, reason := srv.addPeer(conn.ID, p); !ok {
521+
if ok, reason := srv.addPeer(conn, p); !ok {
522522
glog.V(logger.Detail).Infof("Not adding %v (%v)\n", p, reason)
523523
p.politeDisconnect(reason)
524524
srv.peerWG.Done()
@@ -564,13 +564,18 @@ func (srv *Server) runPeer(p *Peer) {
564564
})
565565
}
566566

567-
func (srv *Server) addPeer(id discover.NodeID, p *Peer) (bool, DiscReason) {
567+
func (srv *Server) addPeer(conn *conn, p *Peer) (bool, DiscReason) {
568+
// drop connections with no matching protocols.
569+
if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, conn.protoHandshake.Caps) == 0 {
570+
return false, DiscUselessPeer
571+
}
572+
// add the peer if it passes the other checks.
568573
srv.lock.Lock()
569574
defer srv.lock.Unlock()
570-
if ok, reason := srv.checkPeer(id); !ok {
575+
if ok, reason := srv.checkPeer(conn.ID); !ok {
571576
return false, reason
572577
}
573-
srv.peers[id] = p
578+
srv.peers[conn.ID] = p
574579
return true, 0
575580
}
576581

0 commit comments

Comments
 (0)