7 "github.com/anacrolix/log"
9 pp "github.com/anacrolix/torrent/peer_protocol"
13 pexRetryDelay = 10 * time.Second
14 pexInterval = 1 * time.Minute
17 // per-connection PEX state
18 type pexConnState struct {
20 xid pp.ExtensionNumber
31 func (s *pexConnState) IsEnabled() bool {
35 // Init is called from the reader goroutine upon the extended handshake completion
36 func (s *pexConnState) Init(c *PeerConn) {
37 xid, ok := c.PeerExtensionIDs[pp.ExtensionNamePex]
38 if !ok || xid == 0 || c.t.cl.config.DisablePEX {
44 s.info = c.t.cl.logger
46 s.readyfn = c.tickleWriter
47 s.gate = make(chan struct{}, 1)
48 s.timer = time.AfterFunc(0, func() {
50 s.readyfn() // wake up the writer
55 // schedule next PEX message
56 func (s *pexConnState) sched(delay time.Duration) {
60 // generate next PEX message for the peer; returns nil if nothing yet to send
61 func (s *pexConnState) genmsg() *pp.PexMsg {
62 tx, seq := s.torrent.pex.Genmsg(s.seq)
70 // Share is called from the writer goroutine if when it is woken up with the write buffers empty
71 func (s *pexConnState) Share(postfn messageWriter) {
74 if tx := s.genmsg(); tx != nil {
75 s.dbg.Print("sending PEX message: ", tx)
76 postfn(tx.Message(s.xid))
79 // no PEX to send this time - try again shortly
80 s.sched(pexRetryDelay)
87 // Recv is called from the reader goroutine
88 func (s *pexConnState) Recv(payload []byte) error {
89 rx, err := pp.LoadPexMsg(payload)
91 return fmt.Errorf("error unmarshalling PEX message: %s", err)
93 s.dbg.Print("incoming PEX message: ", rx)
94 torrent.Add("pex added peers received", int64(len(rx.Added)))
95 torrent.Add("pex added6 peers received", int64(len(rx.Added6)))
98 peers.AppendFromPex(rx.Added6, rx.Added6Flags)
99 peers.AppendFromPex(rx.Added, rx.AddedFlags)
100 s.dbg.Printf("adding %d peers from PEX", len(peers))
101 s.torrent.addPeers(peers)
102 // s.dbg.Print("known swarm now:", s.torrent.KnownSwarm())
104 // one day we may also want to:
105 // - check if the peer is not flooding us with PEX updates
106 // - handle drops somehow
107 // - detect malicious peers
112 func (s *pexConnState) Close() {