15 "github.com/anacrolix/log"
16 "github.com/anacrolix/missinggo"
17 "github.com/anacrolix/missinggo/iter"
18 "github.com/anacrolix/missinggo/v2/bitmap"
19 "github.com/anacrolix/missinggo/v2/prioritybitmap"
20 "github.com/anacrolix/multiless"
21 "github.com/anacrolix/torrent/metainfo"
22 "github.com/pkg/errors"
24 "github.com/anacrolix/torrent/bencode"
25 "github.com/anacrolix/torrent/mse"
26 pp "github.com/anacrolix/torrent/peer_protocol"
29 type PeerSource string
32 PeerSourceTracker = "Tr"
33 PeerSourceIncoming = "I"
34 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
35 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
37 // The peer was given directly, such as through a magnet link.
38 PeerSourceDirect = "M"
41 type peerRequestState struct {
45 type PeerRemoteAddr interface {
50 // First to ensure 64-bit alignment for atomics. See #262.
60 RemoteAddr PeerRemoteAddr
61 // True if the connection is operating over MSE obfuscation.
63 cryptoMethod mse.CryptoMethod
66 closed missinggo.Event
67 // Set true after we've added our ConnStats generated during handshake to
68 // other ConnStat instances as determined when the *Torrent became known.
69 reconciledHandshakeStats bool
71 lastMessageReceived time.Time
72 completedHandshake time.Time
73 lastUsefulChunkReceived time.Time
74 lastChunkSent time.Time
76 // Stuff controlled by the local peer.
78 lastBecameInterested time.Time
79 priorInterest time.Duration
81 lastStartedExpectingToReceiveChunks time.Time
82 cumulativeExpectedToReceiveChunks time.Duration
83 _chunksReceivedWhileExpecting int64
86 requests map[Request]struct{}
88 // Chunks that we might reasonably expect to receive from the peer. Due to
89 // latency, buffering, and implementation differences, we may receive
90 // chunks that are no longer in the set of requests actually want.
91 validReceiveChunks map[Request]int
92 // Indexed by metadata piece, set to true if posted and pending a
94 metadataRequests []bool
95 sentHaves bitmap.Bitmap
97 // Stuff controlled by the remote peer.
100 peerRequests map[Request]*peerRequestState
101 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
103 // The pieces the peer has claimed to have.
104 _peerPieces bitmap.Bitmap
105 // The peer has everything. This can occur due to a special message, when
106 // we may not even know the number of pieces in the torrent yet.
108 // The highest possible number of pieces the torrent could have based on
109 // communication with the peer. Generally only useful until we have the
111 peerMinPieces pieceIndex
112 // Pieces we've accepted chunks for from the peer.
113 peerTouchedPieces map[pieceIndex]struct{}
114 peerAllowedFast bitmap.Bitmap
116 PeerMaxRequests int // Maximum pending requests the peer allows.
117 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
118 PeerClientName string
120 pieceInclination []int
121 _pieceRequestOrder prioritybitmap.PriorityBitmap
126 // Maintains the state of a BitTorrent-protocol based connection with a peer.
127 type PeerConn struct {
130 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
131 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
136 PeerExtensionBytes pp.PeerExtensionBits
138 // The actual Conn, used for closing, and setting socket options.
140 // The Reader and Writer for this Conn, with hooks installed for stats,
141 // limiting, deadlines etc.
145 writeBuffer *bytes.Buffer
146 uploadTimer *time.Timer
152 func (cn *PeerConn) connStatusString() string {
153 return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
156 func (cn *Peer) updateExpectingChunks() {
157 if cn.expectingChunks() {
158 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
159 cn.lastStartedExpectingToReceiveChunks = time.Now()
162 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
163 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
164 cn.lastStartedExpectingToReceiveChunks = time.Time{}
169 func (cn *Peer) expectingChunks() bool {
170 return len(cn.requests) != 0 && !cn.peerChoking
173 // Returns true if the connection is over IPv6.
174 func (cn *PeerConn) ipv6() bool {
179 return len(ip) == net.IPv6len
182 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
183 // specification for this.
184 func (cn *PeerConn) isPreferredDirection() bool {
185 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
188 // Returns whether the left connection should be preferred over the right one,
189 // considering only their networking properties. If ok is false, we can't
191 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
193 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
194 ml.NextBool(!l.utp(), !r.utp())
195 ml.NextBool(l.ipv6(), r.ipv6())
199 func (cn *Peer) cumInterest() time.Duration {
200 ret := cn.priorInterest
202 ret += time.Since(cn.lastBecameInterested)
207 func (cn *Peer) peerHasAllPieces() (all bool, known bool) {
208 if cn.peerSentHaveAll {
211 if !cn.t.haveInfo() {
214 return bitmap.Flip(cn._peerPieces, 0, bitmap.BitIndex(cn.t.numPieces())).IsEmpty(), true
217 func (cn *PeerConn) locker() *lockWithDeferreds {
218 return cn.t.cl.locker()
221 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
222 _, ok := cn.PeerExtensionIDs[ext]
226 // The best guess at number of pieces in the torrent for this peer.
227 func (cn *Peer) bestPeerNumPieces() pieceIndex {
229 return cn.t.numPieces()
231 return cn.peerMinPieces
234 func (cn *Peer) completedString() string {
235 have := pieceIndex(cn._peerPieces.Len())
236 if cn.peerSentHaveAll {
237 have = cn.bestPeerNumPieces()
239 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
242 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
243 cn.setNumPieces(info.NumPieces())
246 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
247 // receiving badly sized BITFIELD, or invalid HAVE messages.
248 func (cn *PeerConn) setNumPieces(num pieceIndex) {
249 cn._peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
250 cn.peerPiecesChanged()
253 func eventAgeString(t time.Time) string {
257 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
260 func (cn *PeerConn) connectionFlags() (ret string) {
262 ret += string([]byte{b})
264 if cn.cryptoMethod == mse.CryptoMethodRC4 {
266 } else if cn.headerEncrypted {
269 ret += string(cn.Discovery)
276 func (cn *PeerConn) utp() bool {
277 return parseNetworkString(cn.Network).Udp
280 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
281 func (cn *Peer) statusFlags() (ret string) {
283 ret += string([]byte{b})
292 ret += cn.connectionFlags()
294 if cn.peerInterested {
303 // func (cn *connection) String() string {
304 // var buf bytes.Buffer
305 // cn.writeStatus(&buf, nil)
306 // return buf.String()
309 func (cn *Peer) downloadRate() float64 {
310 return float64(cn._stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds()
313 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
314 // \t isn't preserved in <pre> blocks?
315 if cn.closed.IsSet() {
316 fmt.Fprint(w, "CLOSED: ")
318 fmt.Fprintln(w, cn.connStatusString())
319 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
320 eventAgeString(cn.lastMessageReceived),
321 eventAgeString(cn.completedHandshake),
322 eventAgeString(cn.lastHelpful()),
324 cn.totalExpectingTime(),
327 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: (%d,%d,%d]-%d, flags: %s, dr: %.1f KiB/s\n",
328 cn.completedString(),
329 len(cn.peerTouchedPieces),
330 &cn._stats.ChunksReadUseful,
331 &cn._stats.ChunksRead,
332 &cn._stats.ChunksWritten,
334 cn.numLocalRequests(),
335 cn.nominalMaxRequests(),
336 len(cn.peerRequests),
338 cn.downloadRate()/(1<<10),
340 fmt.Fprintf(w, " next pieces: %v%s\n",
341 iter.ToSlice(iter.Head(10, cn.iterPendingPiecesUntyped)),
343 if cn == t.fastestPeer {
352 func (cn *Peer) close() {
353 if !cn.closed.Set() {
356 cn.discardPieceInclination()
357 cn._pieceRequestOrder.Clear()
358 cn.peerImpl.onClose()
359 for _, f := range cn.callbacks.PeerClosed {
364 func (cn *PeerConn) onClose() {
365 if cn.pex.IsEnabled() {
372 if cb := cn.callbacks.PeerConnClosed; cb != nil {
377 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
378 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
381 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
382 // https://github.com/pion/datachannel/issues/59 is fixed.
383 const writeBufferHighWaterLen = 1 << 15
385 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Posting is
386 // done asynchronously, so it may be that we're not able to honour backpressure from this method. It
387 // might be possible to merge this with PeerConn.write down the track? They seem to be very similar.
388 func (cn *PeerConn) post(msg pp.Message) bool {
389 torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
390 // We don't need to track bytes here because a connection.w Writer wrapper takes care of that
391 // (although there's some delay between us recording the message, and the connection writer
392 // flushing it out.).
393 cn.writeBuffer.Write(msg.MustMarshalBinary())
394 // Last I checked only Piece messages affect stats, and we don't post those.
397 return cn.writeBuffer.Len() < writeBufferHighWaterLen
400 // Returns true if there's room to write more.
401 func (cn *PeerConn) write(msg pp.Message) bool {
403 cn.writeBuffer.Write(msg.MustMarshalBinary())
404 torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
405 return cn.writeBuffer.Len() < writeBufferHighWaterLen
408 func (cn *PeerConn) requestMetadataPiece(index int) {
409 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
413 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
416 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
420 ExtendedPayload: func() []byte {
421 b, err := bencode.Marshal(map[string]int{
422 "msg_type": pp.RequestMetadataExtensionMsgType,
431 for index >= len(cn.metadataRequests) {
432 cn.metadataRequests = append(cn.metadataRequests, false)
434 cn.metadataRequests[index] = true
437 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
438 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
441 // The actual value to use as the maximum outbound requests.
442 func (cn *Peer) nominalMaxRequests() (ret int) {
445 int64(cn.PeerMaxRequests),
446 int64(cn.t.requestStrategy.nominalMaxRequests(cn.requestStrategyConnection())),
450 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
451 ret = cn.cumulativeExpectedToReceiveChunks
452 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
453 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
459 func (cn *PeerConn) onPeerSentCancel(r Request) {
460 if _, ok := cn.peerRequests[r]; !ok {
461 torrent.Add("unexpected cancels received", 1)
464 if cn.fastEnabled() {
467 delete(cn.peerRequests, r)
471 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
476 more = msg(pp.Message{
479 if cn.fastEnabled() {
480 for r := range cn.peerRequests {
481 // TODO: Don't reject pieces in allowed fast set.
485 cn.peerRequests = nil
490 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
495 return msg(pp.Message{
500 func (cn *Peer) setInterested(interested bool) bool {
501 if cn.interested == interested {
504 cn.interested = interested
506 cn.lastBecameInterested = time.Now()
507 } else if !cn.lastBecameInterested.IsZero() {
508 cn.priorInterest += time.Since(cn.lastBecameInterested)
510 cn.updateExpectingChunks()
511 // log.Printf("%p: setting interest: %v", cn, interested)
512 return cn.writeInterested(interested)
515 func (pc *PeerConn) writeInterested(interested bool) bool {
516 return pc.write(pp.Message{
517 Type: func() pp.MessageType {
521 return pp.NotInterested
527 // The function takes a message to be sent, and returns true if more messages
529 type messageWriter func(pp.Message) bool
531 func (cn *Peer) request(r Request) bool {
532 if _, ok := cn.requests[r]; ok {
533 panic("chunk already requested")
535 if !cn.peerHasPiece(pieceIndex(r.Index)) {
536 panic("requesting piece peer doesn't have")
538 if !cn.t.peerIsActive(cn) {
539 panic("requesting but not in active conns")
541 if cn.closed.IsSet() {
542 panic("requesting when connection is closed")
545 if cn.peerAllowedFast.Get(int(r.Index)) {
546 torrent.Add("allowed fast requests sent", 1)
548 panic("requesting while choking and not allowed fast")
551 if cn.t.hashingPiece(pieceIndex(r.Index)) {
552 panic("piece is being hashed")
554 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
555 panic("piece is queued for hash")
557 if cn.requests == nil {
558 cn.requests = make(map[Request]struct{})
560 cn.requests[r] = struct{}{}
561 if cn.validReceiveChunks == nil {
562 cn.validReceiveChunks = make(map[Request]int)
564 cn.validReceiveChunks[r]++
565 cn.t.pendingRequests[r]++
566 cn.t.requestStrategy.hooks().sentRequest(r)
567 cn.updateExpectingChunks()
568 for _, f := range cn.callbacks.SentRequest {
569 f(PeerRequestEvent{cn, r})
571 return cn.peerImpl.request(r)
574 func (me *PeerConn) request(r Request) bool {
575 return me.write(pp.Message{
583 func (me *PeerConn) cancel(r Request) bool {
584 return me.write(makeCancelMessage(r))
587 func (cn *Peer) doRequestState() bool {
588 if !cn.t.networkingEnabled || cn.t.dataDownloadDisallowed {
589 if !cn.setInterested(false) {
592 if len(cn.requests) != 0 {
593 for r := range cn.requests {
595 // log.Printf("%p: cancelling request: %v", cn, r)
596 if !cn.peerImpl.cancel(r) {
601 } else if len(cn.requests) <= cn.requestsLowWater {
602 filledBuffer := false
603 cn.iterPendingPieces(func(pieceIndex pieceIndex) bool {
604 cn.iterPendingRequests(pieceIndex, func(r Request) bool {
605 if !cn.setInterested(true) {
609 if len(cn.requests) >= cn.nominalMaxRequests() {
612 // Choking is looked at here because our interest is dependent
613 // on whether we'd make requests in its absence.
615 if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
619 if _, ok := cn.requests[r]; ok {
622 filledBuffer = !cn.request(r)
628 // If we didn't completely top up the requests, we shouldn't mark
629 // the low water, since we'll want to top up the requests as soon
630 // as we have more write buffer space.
633 cn.requestsLowWater = len(cn.requests) / 2
634 if len(cn.requests) == 0 {
635 return cn.setInterested(false)
641 func (cn *PeerConn) fillWriteBuffer() {
642 if !cn.doRequestState() {
645 if cn.pex.IsEnabled() {
646 if flow := cn.pex.Share(cn.write); !flow {
653 // Routine that writes to the peer. Some of what to write is buffered by
654 // activity elsewhere in the Client, and some is determined locally when the
655 // connection is writable.
656 func (cn *PeerConn) writer(keepAliveTimeout time.Duration) {
658 lastWrite time.Time = time.Now()
659 keepAliveTimer *time.Timer
661 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
663 defer cn.locker().Unlock()
664 if time.Since(lastWrite) >= keepAliveTimeout {
667 keepAliveTimer.Reset(keepAliveTimeout)
670 defer cn.locker().Unlock()
672 defer keepAliveTimer.Stop()
673 frontBuf := new(bytes.Buffer)
675 if cn.closed.IsSet() {
678 if cn.writeBuffer.Len() == 0 {
681 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout && cn.useful() {
682 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
683 postedKeepalives.Add(1)
685 if cn.writeBuffer.Len() == 0 {
686 // TODO: Minimize wakeups....
691 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
693 n, err := cn.w.Write(frontBuf.Bytes())
696 lastWrite = time.Now()
697 keepAliveTimer.Reset(keepAliveTimeout)
700 cn.logger.WithDefaultLevel(log.Debug).Printf("error writing: %v", err)
703 if n != frontBuf.Len() {
710 func (cn *PeerConn) have(piece pieceIndex) {
711 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
716 Index: pp.Integer(piece),
718 cn.sentHaves.Add(bitmap.BitIndex(piece))
721 func (cn *PeerConn) postBitfield() {
722 if cn.sentHaves.Len() != 0 {
723 panic("bitfield must be first have-related message sent")
725 if !cn.t.haveAnyPieces() {
730 Bitfield: cn.t.bitfield(),
732 cn.sentHaves = cn.t._completedPieces.Copy()
735 func (cn *PeerConn) updateRequests() {
736 // log.Print("update requests")
740 // Emits the indices in the Bitmaps bms in order, never repeating any index.
741 // skip is mutated during execution, and its initial values will never be
743 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
744 return func(cb iter.Callback) {
745 for _, bm := range bms {
747 func(i interface{}) bool {
751 bitmap.Sub(bm, *skip).Iter,
759 func iterUnbiasedPieceRequestOrder(cn requestStrategyConnection, f func(piece pieceIndex) bool) bool {
760 now, readahead := cn.torrent().readerPiecePriorities()
761 skip := bitmap.Flip(cn.peerPieces(), 0, cn.torrent().numPieces())
762 skip.Union(cn.torrent().ignorePieces())
763 // Return an iterator over the different priority classes, minus the skip pieces.
765 func(_piece interface{}) bool {
766 return f(pieceIndex(_piece.(bitmap.BitIndex)))
768 iterBitmapsDistinct(&skip, now, readahead),
769 // We have to iterate _pendingPieces separately because it isn't a Bitmap.
770 func(cb iter.Callback) {
771 cn.torrent().pendingPieces().IterTyped(func(piece int) bool {
772 if skip.Contains(piece) {
783 // The connection should download highest priority pieces first, without any inclination toward
784 // avoiding wastage. Generally we might do this if there's a single connection, or this is the
785 // fastest connection, and we have active readers that signal an ordering preference. It's
786 // conceivable that the best connection should do this, since it's least likely to waste our time if
787 // assigned to the highest priority pieces, and assigning more than one this role would cause
788 // significant wasted bandwidth.
789 func (cn *Peer) shouldRequestWithoutBias() bool {
790 return cn.t.requestStrategy.shouldRequestWithoutBias(cn.requestStrategyConnection())
793 func (cn *Peer) iterPendingPieces(f func(pieceIndex) bool) {
794 if !cn.t.haveInfo() {
797 if cn.closed.IsSet() {
800 cn.t.requestStrategy.iterPendingPieces(cn, f)
802 func (cn *Peer) iterPendingPiecesUntyped(f iter.Callback) {
803 cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
806 func (cn *Peer) iterPendingRequests(piece pieceIndex, f func(Request) bool) bool {
807 return cn.t.requestStrategy.iterUndirtiedChunks(
808 cn.t.piece(piece).requestStrategyPiece(),
809 func(cs ChunkSpec) bool {
810 return f(Request{pp.Integer(piece), cs})
815 // check callers updaterequests
816 func (cn *Peer) stopRequestingPiece(piece pieceIndex) bool {
817 return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
820 // This is distinct from Torrent piece priority, which is the user's
821 // preference. Connection piece priority is specific to a connection and is
822 // used to pseudorandomly avoid connections always requesting the same pieces
823 // and thus wasting effort.
824 func (cn *Peer) updatePiecePriority(piece pieceIndex) bool {
825 tpp := cn.t.piecePriority(piece)
826 if !cn.peerHasPiece(piece) {
827 tpp = PiecePriorityNone
829 if tpp == PiecePriorityNone {
830 return cn.stopRequestingPiece(piece)
832 prio := cn.getPieceInclination()[piece]
833 prio = cn.t.requestStrategy.piecePriority(cn, piece, tpp, prio)
834 return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
837 func (cn *Peer) getPieceInclination() []int {
838 if cn.pieceInclination == nil {
839 cn.pieceInclination = cn.t.getConnPieceInclination()
841 return cn.pieceInclination
844 func (cn *Peer) discardPieceInclination() {
845 if cn.pieceInclination == nil {
848 cn.t.putPieceInclination(cn.pieceInclination)
849 cn.pieceInclination = nil
852 func (cn *PeerConn) peerPiecesChanged() {
854 prioritiesChanged := false
855 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
856 if cn.updatePiecePriority(i) {
857 prioritiesChanged = true
860 if prioritiesChanged {
864 cn.t.maybeDropMutuallyCompletePeer(&cn.Peer)
867 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
868 if newMin > cn.peerMinPieces {
869 cn.peerMinPieces = newMin
873 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
874 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
875 return errors.New("invalid piece")
877 if cn.peerHasPiece(piece) {
880 cn.raisePeerMinPieces(piece + 1)
881 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
882 cn.t.maybeDropMutuallyCompletePeer(&cn.Peer)
883 if cn.updatePiecePriority(piece) {
889 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
890 cn.peerSentHaveAll = false
892 panic("expected bitfield length divisible by 8")
894 // We know that the last byte means that at most the last 7 bits are
896 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
897 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
898 // Ignore known excess pieces.
899 bf = bf[:cn.t.numPieces()]
901 for i, have := range bf {
903 cn.raisePeerMinPieces(pieceIndex(i) + 1)
905 cn._peerPieces.Set(i, have)
907 cn.peerPiecesChanged()
911 func (cn *PeerConn) onPeerSentHaveAll() error {
912 cn.peerSentHaveAll = true
913 cn._peerPieces.Clear()
914 cn.peerPiecesChanged()
918 func (cn *PeerConn) peerSentHaveNone() error {
919 cn._peerPieces.Clear()
920 cn.peerSentHaveAll = false
921 cn.peerPiecesChanged()
925 func (c *PeerConn) requestPendingMetadata() {
929 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
930 // Peer doesn't support this.
933 // Request metadata pieces that we don't have in a random order.
935 for index := 0; index < c.t.metadataPieceCount(); index++ {
936 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
937 pending = append(pending, index)
940 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
941 for _, i := range pending {
942 c.requestMetadataPiece(i)
946 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
947 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
948 if msg.Type == pp.Extended {
949 for name, id := range cn.PeerExtensionIDs {
950 if id != msg.ExtendedID {
953 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
956 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
959 func (cn *PeerConn) readMsg(msg *pp.Message) {
960 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
963 // After handshake, we know what Torrent and Client stats to include for a
965 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
971 // All ConnStats that include this connection. Some objects are not known
972 // until the handshake is complete, after which it's expected to reconcile the
974 func (cn *Peer) allStats(f func(*ConnStats)) {
976 if cn.reconciledHandshakeStats {
977 cn.postHandshakeStats(f)
981 func (cn *PeerConn) wroteBytes(n int64) {
982 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
985 func (cn *PeerConn) readBytes(n int64) {
986 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
989 // Returns whether the connection could be useful to us. We're seeding and
990 // they want data, we don't have metainfo and they can provide it, etc.
991 func (c *Peer) useful() bool {
993 if c.closed.IsSet() {
997 return c.supportsExtension("ut_metadata")
999 if t.seeding() && c.peerInterested {
1002 if c.peerHasWantedPieces() {
1008 func (c *Peer) lastHelpful() (ret time.Time) {
1009 ret = c.lastUsefulChunkReceived
1010 if c.t.seeding() && c.lastChunkSent.After(ret) {
1011 ret = c.lastChunkSent
1016 func (c *PeerConn) fastEnabled() bool {
1017 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
1020 func (c *PeerConn) reject(r Request) {
1021 if !c.fastEnabled() {
1022 panic("fast not enabled")
1024 c.post(r.ToMsg(pp.Reject))
1025 delete(c.peerRequests, r)
1028 func (c *PeerConn) onReadRequest(r Request) error {
1029 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
1030 if _, ok := c.peerRequests[r]; ok {
1031 torrent.Add("duplicate requests received", 1)
1035 torrent.Add("requests received while choking", 1)
1036 if c.fastEnabled() {
1037 torrent.Add("requests rejected while choking", 1)
1042 if len(c.peerRequests) >= maxRequests {
1043 torrent.Add("requests received while queue full", 1)
1044 if c.fastEnabled() {
1047 // BEP 6 says we may close here if we choose.
1050 if !c.t.havePiece(pieceIndex(r.Index)) {
1051 // This isn't necessarily them screwing up. We can drop pieces
1052 // from our storage, and can't communicate this to peers
1053 // except by reconnecting.
1054 requestsReceivedForMissingPieces.Add(1)
1055 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1057 // Check this after we know we have the piece, so that the piece length will be known.
1058 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1059 torrent.Add("bad requests received", 1)
1060 return errors.New("bad Request")
1062 if c.peerRequests == nil {
1063 c.peerRequests = make(map[Request]*peerRequestState, maxRequests)
1065 value := &peerRequestState{}
1066 c.peerRequests[r] = value
1067 go c.peerRequestDataReader(r, value)
1072 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1073 b, err := readPeerRequestData(r, c)
1075 defer c.locker().Unlock()
1077 c.peerRequestDataReadFailed(err, r)
1080 panic("data must be non-nil to trigger send")
1087 // If this is maintained correctly, we might be able to support optional synchronous reading for
1088 // chunk sending, the way it used to work.
1089 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1090 c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
1091 i := pieceIndex(r.Index)
1092 if c.t.pieceComplete(i) {
1093 // There used to be more code here that just duplicated the following break. Piece
1094 // completions are currently cached, so I'm not sure how helpful this update is, except to
1095 // pull any completion changes pushed to the storage backend in failed reads that got us
1097 c.t.updatePieceCompletion(i)
1099 // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
1100 // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
1101 // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
1102 // next connect. TODO: Support rejecting here too.
1104 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1109 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1110 b := make([]byte, r.Length)
1111 p := c.t.info.Piece(int(r.Index))
1112 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1119 panic("expected error")
1125 func runSafeExtraneous(f func()) {
1133 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1134 // exit. Returning will end the connection.
1135 func (c *PeerConn) mainReadLoop() (err error) {
1138 torrent.Add("connection.mainReadLoop returned with error", 1)
1140 torrent.Add("connection.mainReadLoop returned with no error", 1)
1146 decoder := pp.Decoder{
1147 R: bufio.NewReaderSize(c.r, 1<<17),
1148 MaxLength: 256 * 1024,
1156 err = decoder.Decode(&msg)
1158 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1161 if t.closed.IsSet() || c.closed.IsSet() {
1168 c.lastMessageReceived = time.Now()
1170 receivedKeepalives.Add(1)
1173 messageTypesReceived.Add(msg.Type.String(), 1)
1174 if msg.Type.FastExtension() && !c.fastEnabled() {
1175 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1176 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1180 c.peerChoking = true
1181 if !c.fastEnabled() {
1182 c.deleteAllRequests()
1184 // We can then reset our interest.
1186 c.updateExpectingChunks()
1188 c.peerChoking = false
1190 c.updateExpectingChunks()
1192 c.peerInterested = true
1194 case pp.NotInterested:
1195 c.peerInterested = false
1196 // We don't clear their requests since it isn't clear in the spec.
1197 // We'll probably choke them for this, which will clear them if
1198 // appropriate, and is clearly specified.
1200 err = c.peerSentHave(pieceIndex(msg.Index))
1202 err = c.peerSentBitfield(msg.Bitfield)
1204 r := newRequestFromMessage(&msg)
1205 err = c.onReadRequest(r)
1207 err = c.receiveChunk(&msg)
1208 if len(msg.Piece) == int(t.chunkSize) {
1209 t.chunkPool.Put(&msg.Piece)
1212 err = fmt.Errorf("receiving chunk: %s", err)
1215 req := newRequestFromMessage(&msg)
1216 c.onPeerSentCancel(req)
1218 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1222 pingAddr := net.UDPAddr{
1227 pingAddr.Port = int(msg.Port)
1229 cl.eachDhtServer(func(s DhtServer) {
1230 go s.Ping(&pingAddr)
1233 torrent.Add("suggests received", 1)
1234 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1237 err = c.onPeerSentHaveAll()
1239 err = c.peerSentHaveNone()
1241 c.remoteRejectedRequest(newRequestFromMessage(&msg))
1242 case pp.AllowedFast:
1243 torrent.Add("allowed fasts received", 1)
1244 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1245 c.peerAllowedFast.Add(int(msg.Index))
1248 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1250 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1258 func (c *Peer) remoteRejectedRequest(r Request) {
1259 if c.deleteRequest(r) {
1260 c.decExpectedChunkReceive(r)
1264 func (c *Peer) decExpectedChunkReceive(r Request) {
1265 count := c.validReceiveChunks[r]
1267 delete(c.validReceiveChunks, r)
1268 } else if count > 1 {
1269 c.validReceiveChunks[r] = count - 1
1275 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1277 // TODO: Should we still do this?
1279 // These clients use their own extension IDs for outgoing message
1280 // types, which is incorrect.
1281 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1289 case pp.HandshakeExtendedID:
1290 var d pp.ExtendedHandshakeMessage
1291 if err := bencode.Unmarshal(payload, &d); err != nil {
1292 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1293 return errors.Wrap(err, "unmarshalling extended handshake payload")
1295 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1298 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1300 c.PeerMaxRequests = d.Reqq
1302 c.PeerClientName = d.V
1303 if c.PeerExtensionIDs == nil {
1304 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1306 c.PeerListenPort = d.Port
1307 c.PeerPrefersEncryption = d.Encryption
1308 for name, id := range d.M {
1309 if _, ok := c.PeerExtensionIDs[name]; !ok {
1310 torrent.Add(fmt.Sprintf("peers supporting extension %q", name), 1)
1312 c.PeerExtensionIDs[name] = id
1314 if d.MetadataSize != 0 {
1315 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1316 return errors.Wrapf(err, "setting metadata size to %d", d.MetadataSize)
1319 c.requestPendingMetadata()
1320 if !t.cl.config.DisablePEX {
1321 t.pex.Add(c) // we learnt enough now
1325 case metadataExtendedId:
1326 err := cl.gotMetadataExtensionMsg(payload, t, c)
1328 return fmt.Errorf("handling metadata extension message: %w", err)
1332 if !c.pex.IsEnabled() {
1333 return nil // or hang-up maybe?
1335 return c.pex.Recv(payload)
1337 return fmt.Errorf("unexpected extended message ID: %v", id)
1341 // Set both the Reader and Writer for the connection from a single ReadWriter.
1342 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1347 // Returns the Reader and Writer as a combined ReadWriter.
1348 func (cn *PeerConn) rw() io.ReadWriter {
1355 // Handle a received chunk from a peer.
1356 func (c *Peer) receiveChunk(msg *pp.Message) error {
1359 torrent.Add("chunks received", 1)
1361 req := newRequestFromMessage(msg)
1364 torrent.Add("chunks received while choking", 1)
1367 if c.validReceiveChunks[req] <= 0 {
1368 torrent.Add("chunks received unexpected", 1)
1369 return errors.New("received unexpected chunk")
1371 c.decExpectedChunkReceive(req)
1373 if c.peerChoking && c.peerAllowedFast.Get(int(req.Index)) {
1374 torrent.Add("chunks received due to allowed fast", 1)
1377 // TODO: This needs to happen immediately, to prevent cancels occurring asynchronously when have
1378 // actually already received the piece, while we have the Client unlocked to write the data out.
1380 if _, ok := c.requests[req]; ok {
1381 for _, f := range c.callbacks.ReceivedRequested {
1382 f(PeerMessageEvent{c, msg})
1385 // Request has been satisfied.
1386 if c.deleteRequest(req) {
1387 if c.expectingChunks() {
1388 c._chunksReceivedWhileExpecting++
1391 torrent.Add("chunks received unwanted", 1)
1395 // Do we actually want this chunk?
1396 if t.haveChunk(req) {
1397 torrent.Add("chunks received wasted", 1)
1398 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1402 piece := &t.pieces[req.Index]
1404 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1405 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1406 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1407 f(ReceivedUsefulDataEvent{c, msg})
1409 c.lastUsefulChunkReceived = time.Now()
1410 // if t.fastestPeer != c {
1411 // log.Printf("setting fastest connection %p", c)
1415 // Need to record that it hasn't been written yet, before we attempt to do
1416 // anything with it.
1417 piece.incrementPendingWrites()
1418 // Record that we have the chunk, so we aren't trying to download it while
1419 // waiting for it to be written to storage.
1420 piece.unpendChunkIndex(chunkIndex(req.ChunkSpec, t.chunkSize))
1422 // Cancel pending requests for this chunk from *other* peers.
1423 t.iterPeers(func(p *Peer) {
1430 err := func() error {
1433 concurrentChunkWrites.Add(1)
1434 defer concurrentChunkWrites.Add(-1)
1435 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1436 // number of connections. We write inline with receiving the chunk (with this lock dance),
1437 // because we want to handle errors synchronously and I haven't thought of a nice way to
1438 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1440 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1443 piece.decrementPendingWrites()
1446 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1448 //t.updatePieceCompletion(pieceIndex(msg.Index))
1449 t.onWriteChunkErr(err)
1453 c.onDirtiedPiece(pieceIndex(req.Index))
1455 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1456 if t.pieceAllDirty(pieceIndex(req.Index)) && piece.pendingWrites == 0 {
1457 t.queuePieceCheck(pieceIndex(req.Index))
1458 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1459 // chunk status (such as the haveChunk call above) to have to check all the various other
1460 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1461 // that chunk pieces are pended at an appropriate time later however.
1464 cl.event.Broadcast()
1465 // We do this because we've written a chunk, and may change PieceState.Partial.
1466 t.publishPieceChange(pieceIndex(req.Index))
1471 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1472 if c.peerTouchedPieces == nil {
1473 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1475 c.peerTouchedPieces[piece] = struct{}{}
1476 ds := &c.t.pieces[piece].dirtiers
1478 *ds = make(map[*Peer]struct{})
1480 (*ds)[c] = struct{}{}
1483 func (c *PeerConn) uploadAllowed() bool {
1484 if c.t.cl.config.NoUpload {
1487 if c.t.dataUploadDisallowed {
1493 if !c.peerHasWantedPieces() {
1496 // Don't upload more than 100 KiB more than we download.
1497 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1503 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1504 if c.uploadTimer == nil {
1505 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1507 c.uploadTimer.Reset(delay)
1511 // Also handles choking and unchoking of the remote peer.
1512 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1513 // Breaking or completing this loop means we don't want to upload to the
1514 // peer anymore, and we choke them.
1516 for c.uploadAllowed() {
1517 // We want to upload to the peer.
1518 if !c.unchoke(msg) {
1521 for r, state := range c.peerRequests {
1522 if state.data == nil {
1525 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1527 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1529 delay := res.Delay()
1532 c.setRetryUploadTimer(delay)
1533 // Hard to say what to return here.
1536 more := c.sendChunk(r, msg, state)
1537 delete(c.peerRequests, r)
1548 func (cn *PeerConn) drop() {
1549 cn.t.dropConnection(cn)
1552 func (cn *Peer) netGoodPiecesDirtied() int64 {
1553 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1556 func (c *Peer) peerHasWantedPieces() bool {
1557 return !c._pieceRequestOrder.IsEmpty()
1560 func (c *Peer) numLocalRequests() int {
1561 return len(c.requests)
1564 func (c *Peer) deleteRequest(r Request) bool {
1565 if _, ok := c.requests[r]; !ok {
1568 delete(c.requests, r)
1569 for _, f := range c.callbacks.DeletedRequest {
1570 f(PeerRequestEvent{c, r})
1572 c.updateExpectingChunks()
1573 c.t.requestStrategy.hooks().deletedRequest(r)
1574 pr := c.t.pendingRequests
1583 // If a request fails, updating the requests for the current peer first may miss the opportunity
1584 // to try other peers for that request instead, depending on the request strategy. This might
1585 // only affect webseed peers though, since they synchronously issue new requests: PeerConns do
1586 // it in the writer routine.
1587 const updateCurrentConnRequestsFirst = false
1588 if updateCurrentConnRequestsFirst {
1591 // Give other conns a chance to pick up the request.
1592 c.t.iterPeers(func(_c *Peer) {
1593 // We previously checked that the peer wasn't interested to to only wake connections that
1594 // were unable to issue requests due to starvation by the request strategy. There could be
1595 // performance ramifications.
1596 if _c != c && c.peerHasPiece(pieceIndex(r.Index)) {
1600 if !updateCurrentConnRequestsFirst {
1606 func (c *Peer) deleteAllRequests() {
1607 for r := range c.requests {
1610 if len(c.requests) != 0 {
1611 panic(len(c.requests))
1613 // for c := range c.t.conns {
1618 // This is called when something has changed that should wake the writer, such as putting stuff into
1619 // the writeBuffer, or changing some state that the writer can act on.
1620 func (c *PeerConn) tickleWriter() {
1621 c.writerCond.Broadcast()
1624 func (c *Peer) postCancel(r Request) bool {
1625 if !c.deleteRequest(r) {
1628 c.peerImpl._postCancel(r)
1632 func (c *PeerConn) _postCancel(r Request) {
1633 c.post(makeCancelMessage(r))
1636 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1637 c.lastChunkSent = time.Now()
1638 return msg(pp.Message{
1646 func (c *PeerConn) setTorrent(t *Torrent) {
1648 panic("connection already associated with a torrent")
1651 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1652 t.reconcileHandshakeStats(c)
1655 func (c *Peer) peerPriority() (peerPriority, error) {
1656 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1659 func (c *Peer) remoteIp() net.IP {
1660 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1661 return net.ParseIP(host)
1664 func (c *Peer) remoteIpPort() IpPort {
1665 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1666 return IpPort{ipa.IP, uint16(ipa.Port)}
1669 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1670 f := pp.PexPeerFlags(0)
1671 if c.PeerPrefersEncryption {
1672 f |= pp.PexPrefersEncryption
1675 f |= pp.PexOutgoingConn
1678 f |= pp.PexSupportsUtp
1683 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1684 // advertised listen port.
1685 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1686 if !c.outgoing && c.PeerListenPort != 0 {
1687 switch addr := c.RemoteAddr.(type) {
1690 dialAddr.Port = c.PeerListenPort
1694 dialAddr.Port = c.PeerListenPort
1701 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1702 f := c.pexPeerFlags()
1703 addr := c.dialAddr()
1704 return pexEvent{t, addr, f}
1707 func (c *PeerConn) String() string {
1708 return fmt.Sprintf("connection %p", c)
1711 func (c *Peer) trust() connectionTrust {
1712 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1715 type connectionTrust struct {
1717 NetGoodPiecesDirted int64
1720 func (l connectionTrust) Less(r connectionTrust) bool {
1721 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1724 func (cn *Peer) requestStrategyConnection() requestStrategyConnection {
1728 func (cn *Peer) chunksReceivedWhileExpecting() int64 {
1729 return cn._chunksReceivedWhileExpecting
1732 func (cn *Peer) fastest() bool {
1733 return cn == cn.t.fastestPeer
1736 func (cn *Peer) peerMaxRequests() int {
1737 return cn.PeerMaxRequests
1740 // Returns the pieces the peer has claimed to have.
1741 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1743 defer cn.locker().RUnlock()
1744 return cn.peerPieces()
1747 func (cn *Peer) peerPieces() bitmap.Bitmap {
1748 ret := cn._peerPieces.Copy()
1749 if cn.peerSentHaveAll {
1750 ret.AddRange(0, cn.t.numPieces())
1755 func (cn *Peer) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1756 return &cn._pieceRequestOrder
1759 func (cn *Peer) stats() *ConnStats {
1763 func (cn *Peer) torrent() requestStrategyTorrent {
1764 return cn.t.requestStrategyTorrent()
1767 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1768 pc, ok := p.peerImpl.(*PeerConn)