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/pkg/errors"
23 "github.com/anacrolix/torrent/bencode"
24 "github.com/anacrolix/torrent/mse"
25 pp "github.com/anacrolix/torrent/peer_protocol"
28 type PeerSource string
31 PeerSourceTracker = "Tr"
32 PeerSourceIncoming = "I"
33 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
34 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
38 // Maintains the state of a connection with a peer.
39 type PeerConn struct {
40 // First to ensure 64-bit alignment for atomics. See #262.
44 // The actual Conn, used for closing, and setting socket options.
49 // The Reader and Writer for this Conn, with hooks installed for stats,
50 // limiting, deadlines etc.
53 // True if the connection is operating over MSE obfuscation.
55 cryptoMethod mse.CryptoMethod
58 closed missinggo.Event
59 // Set true after we've added our ConnStats generated during handshake to
60 // other ConnStat instances as determined when the *Torrent became known.
61 reconciledHandshakeStats bool
63 lastMessageReceived time.Time
64 completedHandshake time.Time
65 lastUsefulChunkReceived time.Time
66 lastChunkSent time.Time
68 // Stuff controlled by the local peer.
70 lastBecameInterested time.Time
71 priorInterest time.Duration
73 lastStartedExpectingToReceiveChunks time.Time
74 cumulativeExpectedToReceiveChunks time.Duration
75 _chunksReceivedWhileExpecting int64
78 requests map[request]struct{}
80 // Chunks that we might reasonably expect to receive from the peer. Due to
81 // latency, buffering, and implementation differences, we may receive
82 // chunks that are no longer in the set of requests actually want.
83 validReceiveChunks map[request]struct{}
84 // Indexed by metadata piece, set to true if posted and pending a
86 metadataRequests []bool
87 sentHaves bitmap.Bitmap
89 // Stuff controlled by the remote peer.
93 peerRequests map[request]struct{}
94 PeerExtensionBytes pp.PeerExtensionBits
95 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
97 // The pieces the peer has claimed to have.
98 _peerPieces bitmap.Bitmap
99 // The peer has everything. This can occur due to a special message, when
100 // we may not even know the number of pieces in the torrent yet.
102 // The highest possible number of pieces the torrent could have based on
103 // communication with the peer. Generally only useful until we have the
105 peerMinPieces pieceIndex
106 // Pieces we've accepted chunks for from the peer.
107 peerTouchedPieces map[pieceIndex]struct{}
108 peerAllowedFast bitmap.Bitmap
110 PeerMaxRequests int // Maximum pending requests the peer allows.
111 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
112 PeerClientName string
114 pieceInclination []int
115 _pieceRequestOrder prioritybitmap.PriorityBitmap
117 writeBuffer *bytes.Buffer
118 uploadTimer *time.Timer
124 func (cn *PeerConn) updateExpectingChunks() {
125 if cn.expectingChunks() {
126 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
127 cn.lastStartedExpectingToReceiveChunks = time.Now()
130 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
131 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
132 cn.lastStartedExpectingToReceiveChunks = time.Time{}
137 func (cn *PeerConn) expectingChunks() bool {
138 return cn.interested && !cn.peerChoking
141 // Returns true if the connection is over IPv6.
142 func (cn *PeerConn) ipv6() bool {
143 ip := addrIpOrNil(cn.remoteAddr)
147 return len(ip) == net.IPv6len
150 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
151 // specification for this.
152 func (cn *PeerConn) isPreferredDirection() bool {
153 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
156 // Returns whether the left connection should be preferred over the right one,
157 // considering only their networking properties. If ok is false, we can't
159 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
161 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
162 ml.NextBool(!l.utp(), !r.utp())
163 ml.NextBool(l.ipv6(), r.ipv6())
167 func (cn *PeerConn) cumInterest() time.Duration {
168 ret := cn.priorInterest
170 ret += time.Since(cn.lastBecameInterested)
175 func (cn *PeerConn) peerHasAllPieces() (all bool, known bool) {
176 if cn.peerSentHaveAll {
179 if !cn.t.haveInfo() {
182 return bitmap.Flip(cn._peerPieces, 0, bitmap.BitIndex(cn.t.numPieces())).IsEmpty(), true
185 func (cn *PeerConn) locker() *lockWithDeferreds {
186 return cn.t.cl.locker()
189 func (cn *PeerConn) localAddr() net.Addr {
190 return cn.conn.LocalAddr()
193 func (cn *PeerConn) supportsExtension(ext pp.ExtensionName) bool {
194 _, ok := cn.PeerExtensionIDs[ext]
198 // The best guess at number of pieces in the torrent for this peer.
199 func (cn *PeerConn) bestPeerNumPieces() pieceIndex {
201 return cn.t.numPieces()
203 return cn.peerMinPieces
206 func (cn *PeerConn) completedString() string {
207 have := pieceIndex(cn._peerPieces.Len())
208 if cn.peerSentHaveAll {
209 have = cn.bestPeerNumPieces()
211 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
214 // Correct the PeerPieces slice length. Return false if the existing slice is
215 // invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
217 func (cn *PeerConn) setNumPieces(num pieceIndex) error {
218 cn._peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
219 cn.peerPiecesChanged()
223 func eventAgeString(t time.Time) string {
227 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
230 func (cn *PeerConn) connectionFlags() (ret string) {
232 ret += string([]byte{b})
234 if cn.cryptoMethod == mse.CryptoMethodRC4 {
236 } else if cn.headerEncrypted {
239 ret += string(cn.Discovery)
246 func (cn *PeerConn) utp() bool {
247 return parseNetworkString(cn.network).Udp
250 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
251 func (cn *PeerConn) statusFlags() (ret string) {
253 ret += string([]byte{b})
262 ret += cn.connectionFlags()
264 if cn.peerInterested {
273 // func (cn *connection) String() string {
274 // var buf bytes.Buffer
275 // cn.writeStatus(&buf, nil)
276 // return buf.String()
279 func (cn *PeerConn) downloadRate() float64 {
280 return float64(cn._stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds()
283 func (cn *PeerConn) writeStatus(w io.Writer, t *Torrent) {
284 // \t isn't preserved in <pre> blocks?
285 fmt.Fprintf(w, "%+-55q %s %s-%s\n", cn.PeerID, cn.PeerExtensionBytes, cn.localAddr(), cn.remoteAddr)
286 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
287 eventAgeString(cn.lastMessageReceived),
288 eventAgeString(cn.completedHandshake),
289 eventAgeString(cn.lastHelpful()),
291 cn.totalExpectingTime(),
294 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: (%d,%d,%d]-%d, flags: %s, dr: %.1f KiB/s\n",
295 cn.completedString(),
296 len(cn.peerTouchedPieces),
297 &cn._stats.ChunksReadUseful,
298 &cn._stats.ChunksRead,
299 &cn._stats.ChunksWritten,
301 cn.numLocalRequests(),
302 cn.nominalMaxRequests(),
303 len(cn.peerRequests),
305 cn.downloadRate()/(1<<10),
307 fmt.Fprintf(w, " next pieces: %v%s\n",
308 iter.ToSlice(iter.Head(10, cn.iterPendingPiecesUntyped)),
310 if cn == t.fastestConn {
319 func (cn *PeerConn) close() {
320 if !cn.closed.Set() {
324 cn.discardPieceInclination()
325 cn._pieceRequestOrder.Clear()
331 func (cn *PeerConn) peerHasPiece(piece pieceIndex) bool {
332 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
335 // Writes a message into the write buffer.
336 func (cn *PeerConn) post(msg pp.Message) {
337 torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
338 // We don't need to track bytes here because a connection.w Writer wrapper
339 // takes care of that (although there's some delay between us recording
340 // the message, and the connection writer flushing it out.).
341 cn.writeBuffer.Write(msg.MustMarshalBinary())
342 // Last I checked only Piece messages affect stats, and we don't post
348 func (cn *PeerConn) requestMetadataPiece(index int) {
349 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
353 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
356 cn.logger.Printf("requesting metadata piece %d", index)
360 ExtendedPayload: func() []byte {
361 b, err := bencode.Marshal(map[string]int{
362 "msg_type": pp.RequestMetadataExtensionMsgType,
371 for index >= len(cn.metadataRequests) {
372 cn.metadataRequests = append(cn.metadataRequests, false)
374 cn.metadataRequests[index] = true
377 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
378 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
381 // The actual value to use as the maximum outbound requests.
382 func (cn *PeerConn) nominalMaxRequests() (ret int) {
385 int64(cn.PeerMaxRequests),
386 int64(cn.t.requestStrategy.nominalMaxRequests(cn.requestStrategyConnection())),
390 func (cn *PeerConn) totalExpectingTime() (ret time.Duration) {
391 ret = cn.cumulativeExpectedToReceiveChunks
392 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
393 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
399 func (cn *PeerConn) onPeerSentCancel(r request) {
400 if _, ok := cn.peerRequests[r]; !ok {
401 torrent.Add("unexpected cancels received", 1)
404 if cn.fastEnabled() {
407 delete(cn.peerRequests, r)
411 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
416 more = msg(pp.Message{
419 if cn.fastEnabled() {
420 for r := range cn.peerRequests {
421 // TODO: Don't reject pieces in allowed fast set.
425 cn.peerRequests = nil
430 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
435 return msg(pp.Message{
440 func (cn *PeerConn) setInterested(interested bool, msg func(pp.Message) bool) bool {
441 if cn.interested == interested {
444 cn.interested = interested
446 cn.lastBecameInterested = time.Now()
447 } else if !cn.lastBecameInterested.IsZero() {
448 cn.priorInterest += time.Since(cn.lastBecameInterested)
450 cn.updateExpectingChunks()
451 // log.Printf("%p: setting interest: %v", cn, interested)
452 return msg(pp.Message{
453 Type: func() pp.MessageType {
457 return pp.NotInterested
463 // The function takes a message to be sent, and returns true if more messages
465 type messageWriter func(pp.Message) bool
467 // Proxies the messageWriter's response.
468 func (cn *PeerConn) request(r request, mw messageWriter) bool {
469 if _, ok := cn.requests[r]; ok {
470 panic("chunk already requested")
472 if !cn.peerHasPiece(pieceIndex(r.Index)) {
473 panic("requesting piece peer doesn't have")
475 if _, ok := cn.t.conns[cn]; !ok {
476 panic("requesting but not in active conns")
478 if cn.closed.IsSet() {
479 panic("requesting when connection is closed")
482 if cn.peerAllowedFast.Get(int(r.Index)) {
483 torrent.Add("allowed fast requests sent", 1)
485 panic("requesting while choking and not allowed fast")
488 if cn.t.hashingPiece(pieceIndex(r.Index)) {
489 panic("piece is being hashed")
491 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
492 panic("piece is queued for hash")
494 if cn.requests == nil {
495 cn.requests = make(map[request]struct{})
497 cn.requests[r] = struct{}{}
498 if cn.validReceiveChunks == nil {
499 cn.validReceiveChunks = make(map[request]struct{})
501 cn.validReceiveChunks[r] = struct{}{}
502 cn.t.pendingRequests[r]++
503 cn.t.requestStrategy.hooks().sentRequest(r)
504 cn.updateExpectingChunks()
505 return mw(pp.Message{
513 func (cn *PeerConn) fillWriteBuffer(msg func(pp.Message) bool) {
514 if !cn.t.networkingEnabled || cn.t.dataDownloadDisallowed {
515 if !cn.setInterested(false, msg) {
518 if len(cn.requests) != 0 {
519 for r := range cn.requests {
521 // log.Printf("%p: cancelling request: %v", cn, r)
522 if !msg(makeCancelMessage(r)) {
527 } else if len(cn.requests) <= cn.requestsLowWater {
528 filledBuffer := false
529 cn.iterPendingPieces(func(pieceIndex pieceIndex) bool {
530 cn.iterPendingRequests(pieceIndex, func(r request) bool {
531 if !cn.setInterested(true, msg) {
535 if len(cn.requests) >= cn.nominalMaxRequests() {
538 // Choking is looked at here because our interest is dependent
539 // on whether we'd make requests in its absence.
541 if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
545 if _, ok := cn.requests[r]; ok {
548 filledBuffer = !cn.request(r, msg)
554 // If we didn't completely top up the requests, we shouldn't mark
555 // the low water, since we'll want to top up the requests as soon
556 // as we have more write buffer space.
559 cn.requestsLowWater = len(cn.requests) / 2
565 // Routine that writes to the peer. Some of what to write is buffered by
566 // activity elsewhere in the Client, and some is determined locally when the
567 // connection is writable.
568 func (cn *PeerConn) writer(keepAliveTimeout time.Duration) {
570 lastWrite time.Time = time.Now()
571 keepAliveTimer *time.Timer
573 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
575 defer cn.locker().Unlock()
576 if time.Since(lastWrite) >= keepAliveTimeout {
579 keepAliveTimer.Reset(keepAliveTimeout)
582 defer cn.locker().Unlock()
584 defer keepAliveTimer.Stop()
585 frontBuf := new(bytes.Buffer)
587 if cn.closed.IsSet() {
590 if cn.writeBuffer.Len() == 0 {
591 cn.fillWriteBuffer(func(msg pp.Message) bool {
593 cn.writeBuffer.Write(msg.MustMarshalBinary())
594 torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
595 return cn.writeBuffer.Len() < 1<<16 // 64KiB
598 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
599 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
600 postedKeepalives.Add(1)
602 if cn.writeBuffer.Len() == 0 {
603 // TODO: Minimize wakeups....
608 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
610 n, err := cn.w.Write(frontBuf.Bytes())
613 lastWrite = time.Now()
614 keepAliveTimer.Reset(keepAliveTimeout)
619 if n != frontBuf.Len() {
626 func (cn *PeerConn) have(piece pieceIndex) {
627 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
632 Index: pp.Integer(piece),
634 cn.sentHaves.Add(bitmap.BitIndex(piece))
637 func (cn *PeerConn) postBitfield() {
638 if cn.sentHaves.Len() != 0 {
639 panic("bitfield must be first have-related message sent")
641 if !cn.t.haveAnyPieces() {
646 Bitfield: cn.t.bitfield(),
648 cn.sentHaves = cn.t._completedPieces.Copy()
651 func (cn *PeerConn) updateRequests() {
652 // log.Print("update requests")
656 // Emits the indices in the Bitmaps bms in order, never repeating any index.
657 // skip is mutated during execution, and its initial values will never be
659 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
660 return func(cb iter.Callback) {
661 for _, bm := range bms {
663 func(i interface{}) bool {
667 bitmap.Sub(bm, *skip).Iter,
675 func iterUnbiasedPieceRequestOrder(cn requestStrategyConnection, f func(piece pieceIndex) bool) bool {
676 now, readahead := cn.torrent().readerPiecePriorities()
677 skip := bitmap.Flip(cn.peerPieces(), 0, cn.torrent().numPieces())
678 skip.Union(cn.torrent().ignorePieces())
679 // Return an iterator over the different priority classes, minus the skip pieces.
681 func(_piece interface{}) bool {
682 return f(pieceIndex(_piece.(bitmap.BitIndex)))
684 iterBitmapsDistinct(&skip, now, readahead),
685 // We have to iterate _pendingPieces separately because it isn't a Bitmap.
686 func(cb iter.Callback) {
687 cn.torrent().pendingPieces().IterTyped(func(piece int) bool {
688 if skip.Contains(piece) {
699 // The connection should download highest priority pieces first, without any inclination toward
700 // avoiding wastage. Generally we might do this if there's a single connection, or this is the
701 // fastest connection, and we have active readers that signal an ordering preference. It's
702 // conceivable that the best connection should do this, since it's least likely to waste our time if
703 // assigned to the highest priority pieces, and assigning more than one this role would cause
704 // significant wasted bandwidth.
705 func (cn *PeerConn) shouldRequestWithoutBias() bool {
706 return cn.t.requestStrategy.shouldRequestWithoutBias(cn.requestStrategyConnection())
709 func (cn *PeerConn) iterPendingPieces(f func(pieceIndex) bool) bool {
710 if !cn.t.haveInfo() {
713 return cn.t.requestStrategy.iterPendingPieces(cn, f)
715 func (cn *PeerConn) iterPendingPiecesUntyped(f iter.Callback) {
716 cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
719 func (cn *PeerConn) iterPendingRequests(piece pieceIndex, f func(request) bool) bool {
720 return cn.t.requestStrategy.iterUndirtiedChunks(
721 cn.t.piece(piece).requestStrategyPiece(),
722 func(cs chunkSpec) bool {
723 return f(request{pp.Integer(piece), cs})
728 // check callers updaterequests
729 func (cn *PeerConn) stopRequestingPiece(piece pieceIndex) bool {
730 return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
733 // This is distinct from Torrent piece priority, which is the user's
734 // preference. Connection piece priority is specific to a connection and is
735 // used to pseudorandomly avoid connections always requesting the same pieces
736 // and thus wasting effort.
737 func (cn *PeerConn) updatePiecePriority(piece pieceIndex) bool {
738 tpp := cn.t.piecePriority(piece)
739 if !cn.peerHasPiece(piece) {
740 tpp = PiecePriorityNone
742 if tpp == PiecePriorityNone {
743 return cn.stopRequestingPiece(piece)
745 prio := cn.getPieceInclination()[piece]
746 prio = cn.t.requestStrategy.piecePriority(cn, piece, tpp, prio)
747 return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
750 func (cn *PeerConn) getPieceInclination() []int {
751 if cn.pieceInclination == nil {
752 cn.pieceInclination = cn.t.getConnPieceInclination()
754 return cn.pieceInclination
757 func (cn *PeerConn) discardPieceInclination() {
758 if cn.pieceInclination == nil {
761 cn.t.putPieceInclination(cn.pieceInclination)
762 cn.pieceInclination = nil
765 func (cn *PeerConn) peerPiecesChanged() {
767 prioritiesChanged := false
768 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
769 if cn.updatePiecePriority(i) {
770 prioritiesChanged = true
773 if prioritiesChanged {
779 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
780 if newMin > cn.peerMinPieces {
781 cn.peerMinPieces = newMin
785 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
786 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
787 return errors.New("invalid piece")
789 if cn.peerHasPiece(piece) {
792 cn.raisePeerMinPieces(piece + 1)
793 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
794 if cn.updatePiecePriority(piece) {
800 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
801 cn.peerSentHaveAll = false
803 panic("expected bitfield length divisible by 8")
805 // We know that the last byte means that at most the last 7 bits are
807 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
808 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
809 // Ignore known excess pieces.
810 bf = bf[:cn.t.numPieces()]
812 for i, have := range bf {
814 cn.raisePeerMinPieces(pieceIndex(i) + 1)
816 cn._peerPieces.Set(i, have)
818 cn.peerPiecesChanged()
822 func (cn *PeerConn) onPeerSentHaveAll() error {
823 cn.peerSentHaveAll = true
824 cn._peerPieces.Clear()
825 cn.peerPiecesChanged()
829 func (cn *PeerConn) peerSentHaveNone() error {
830 cn._peerPieces.Clear()
831 cn.peerSentHaveAll = false
832 cn.peerPiecesChanged()
836 func (c *PeerConn) requestPendingMetadata() {
840 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
841 // Peer doesn't support this.
844 // Request metadata pieces that we don't have in a random order.
846 for index := 0; index < c.t.metadataPieceCount(); index++ {
847 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
848 pending = append(pending, index)
851 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
852 for _, i := range pending {
853 c.requestMetadataPiece(i)
857 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
858 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
859 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
862 func (cn *PeerConn) readMsg(msg *pp.Message) {
863 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
866 // After handshake, we know what Torrent and Client stats to include for a
868 func (cn *PeerConn) postHandshakeStats(f func(*ConnStats)) {
874 // All ConnStats that include this connection. Some objects are not known
875 // until the handshake is complete, after which it's expected to reconcile the
877 func (cn *PeerConn) allStats(f func(*ConnStats)) {
879 if cn.reconciledHandshakeStats {
880 cn.postHandshakeStats(f)
884 func (cn *PeerConn) wroteBytes(n int64) {
885 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
888 func (cn *PeerConn) readBytes(n int64) {
889 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
892 // Returns whether the connection could be useful to us. We're seeding and
893 // they want data, we don't have metainfo and they can provide it, etc.
894 func (c *PeerConn) useful() bool {
896 if c.closed.IsSet() {
900 return c.supportsExtension("ut_metadata")
902 if t.seeding() && c.peerInterested {
905 if c.peerHasWantedPieces() {
911 func (c *PeerConn) lastHelpful() (ret time.Time) {
912 ret = c.lastUsefulChunkReceived
913 if c.t.seeding() && c.lastChunkSent.After(ret) {
914 ret = c.lastChunkSent
919 func (c *PeerConn) fastEnabled() bool {
920 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.extensionBytes.SupportsFast()
923 func (c *PeerConn) reject(r request) {
924 if !c.fastEnabled() {
925 panic("fast not enabled")
927 c.post(r.ToMsg(pp.Reject))
928 delete(c.peerRequests, r)
931 func (c *PeerConn) onReadRequest(r request) error {
932 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
933 if _, ok := c.peerRequests[r]; ok {
934 torrent.Add("duplicate requests received", 1)
938 torrent.Add("requests received while choking", 1)
940 torrent.Add("requests rejected while choking", 1)
945 if len(c.peerRequests) >= maxRequests {
946 torrent.Add("requests received while queue full", 1)
950 // BEP 6 says we may close here if we choose.
953 if !c.t.havePiece(pieceIndex(r.Index)) {
954 // This isn't necessarily them screwing up. We can drop pieces
955 // from our storage, and can't communicate this to peers
956 // except by reconnecting.
957 requestsReceivedForMissingPieces.Add(1)
958 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
960 // Check this after we know we have the piece, so that the piece length will be known.
961 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
962 torrent.Add("bad requests received", 1)
963 return errors.New("bad request")
965 if c.peerRequests == nil {
966 c.peerRequests = make(map[request]struct{}, maxRequests)
968 c.peerRequests[r] = struct{}{}
973 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
974 // exit. Returning will end the connection.
975 func (c *PeerConn) mainReadLoop() (err error) {
978 torrent.Add("connection.mainReadLoop returned with error", 1)
980 torrent.Add("connection.mainReadLoop returned with no error", 1)
986 decoder := pp.Decoder{
987 R: bufio.NewReaderSize(c.r, 1<<17),
988 MaxLength: 256 * 1024,
996 err = decoder.Decode(&msg)
998 if t.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1005 c.lastMessageReceived = time.Now()
1007 receivedKeepalives.Add(1)
1010 messageTypesReceived.Add(msg.Type.String(), 1)
1011 if msg.Type.FastExtension() && !c.fastEnabled() {
1012 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1016 c.peerChoking = true
1017 c.deleteAllRequests()
1018 // We can then reset our interest.
1020 c.updateExpectingChunks()
1022 c.peerChoking = false
1024 c.updateExpectingChunks()
1026 c.peerInterested = true
1028 case pp.NotInterested:
1029 c.peerInterested = false
1030 // We don't clear their requests since it isn't clear in the spec.
1031 // We'll probably choke them for this, which will clear them if
1032 // appropriate, and is clearly specified.
1034 err = c.peerSentHave(pieceIndex(msg.Index))
1036 err = c.peerSentBitfield(msg.Bitfield)
1038 r := newRequestFromMessage(&msg)
1039 err = c.onReadRequest(r)
1041 err = c.receiveChunk(&msg)
1042 if len(msg.Piece) == int(t.chunkSize) {
1043 t.chunkPool.Put(&msg.Piece)
1046 err = fmt.Errorf("receiving chunk: %s", err)
1049 req := newRequestFromMessage(&msg)
1050 c.onPeerSentCancel(req)
1052 ipa, ok := tryIpPortFromNetAddr(c.remoteAddr)
1056 pingAddr := net.UDPAddr{
1061 pingAddr.Port = int(msg.Port)
1063 cl.eachDhtServer(func(s DhtServer) {
1064 go s.Ping(&pingAddr)
1067 torrent.Add("suggests received", 1)
1068 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index, debugLogValue).Log(c.t.logger)
1071 err = c.onPeerSentHaveAll()
1073 err = c.peerSentHaveNone()
1075 c.deleteRequest(newRequestFromMessage(&msg))
1076 delete(c.validReceiveChunks, newRequestFromMessage(&msg))
1077 case pp.AllowedFast:
1078 torrent.Add("allowed fasts received", 1)
1079 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c, debugLogValue).Log(c.t.logger)
1080 c.peerAllowedFast.Add(int(msg.Index))
1083 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1085 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1093 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1095 // TODO: Should we still do this?
1097 // These clients use their own extension IDs for outgoing message
1098 // types, which is incorrect.
1099 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1107 case pp.HandshakeExtendedID:
1108 var d pp.ExtendedHandshakeMessage
1109 if err := bencode.Unmarshal(payload, &d); err != nil {
1110 c.t.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1111 return errors.Wrap(err, "unmarshalling extended handshake payload")
1114 c.PeerMaxRequests = d.Reqq
1116 c.PeerClientName = d.V
1117 if c.PeerExtensionIDs == nil {
1118 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1120 c.PeerListenPort = d.Port
1121 c.PeerPrefersEncryption = d.Encryption
1122 for name, id := range d.M {
1123 if _, ok := c.PeerExtensionIDs[name]; !ok {
1124 torrent.Add(fmt.Sprintf("peers supporting extension %q", name), 1)
1126 c.PeerExtensionIDs[name] = id
1128 if d.MetadataSize != 0 {
1129 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1130 return errors.Wrapf(err, "setting metadata size to %d", d.MetadataSize)
1133 c.requestPendingMetadata()
1134 if !cl.config.DisablePEX {
1135 cl.sendInitialPEX(c, t)
1136 // BUG no sending PEX updates yet
1139 case metadataExtendedId:
1140 err := cl.gotMetadataExtensionMsg(payload, t, c)
1142 return fmt.Errorf("handling metadata extension message: %w", err)
1146 if cl.config.DisablePEX {
1147 // TODO: Maybe close the connection. Check that we're not
1148 // advertising that we support PEX if it's disabled.
1151 c.logger.Printf("incoming PEX message")
1152 var pexMsg pp.PexMsg
1153 err := bencode.Unmarshal(payload, &pexMsg)
1155 return fmt.Errorf("error unmarshalling PEX message: %s", err)
1157 npeers := len(pexMsg.Added6) + len(pexMsg.Added)
1158 c.logger.Printf("adding %d peers from PEX", npeers)
1159 torrent.Add("pex added6 peers received", int64(len(pexMsg.Added6)))
1161 peers.AppendFromPex(pexMsg.Added6, pexMsg.Added6Flags)
1162 peers.AppendFromPex(pexMsg.Added, pexMsg.AddedFlags)
1166 return fmt.Errorf("unexpected extended message ID: %v", id)
1170 // Set both the Reader and Writer for the connection from a single ReadWriter.
1171 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1176 // Returns the Reader and Writer as a combined ReadWriter.
1177 func (cn *PeerConn) rw() io.ReadWriter {
1184 // Handle a received chunk from a peer.
1185 func (c *PeerConn) receiveChunk(msg *pp.Message) error {
1188 torrent.Add("chunks received", 1)
1190 req := newRequestFromMessage(msg)
1193 torrent.Add("chunks received while choking", 1)
1196 if _, ok := c.validReceiveChunks[req]; !ok {
1197 torrent.Add("chunks received unexpected", 1)
1198 return errors.New("received unexpected chunk")
1200 delete(c.validReceiveChunks, req)
1202 if c.peerChoking && c.peerAllowedFast.Get(int(req.Index)) {
1203 torrent.Add("chunks received due to allowed fast", 1)
1206 // Request has been satisfied.
1207 if c.deleteRequest(req) {
1208 if c.expectingChunks() {
1209 c._chunksReceivedWhileExpecting++
1212 torrent.Add("chunks received unwanted", 1)
1215 // Do we actually want this chunk?
1216 if t.haveChunk(req) {
1217 torrent.Add("chunks received wasted", 1)
1218 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1222 piece := &t.pieces[req.Index]
1224 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1225 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1226 c.lastUsefulChunkReceived = time.Now()
1227 // if t.fastestConn != c {
1228 // log.Printf("setting fastest connection %p", c)
1232 // Need to record that it hasn't been written yet, before we attempt to do
1233 // anything with it.
1234 piece.incrementPendingWrites()
1235 // Record that we have the chunk, so we aren't trying to download it while
1236 // waiting for it to be written to storage.
1237 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1239 // Cancel pending requests for this chunk.
1240 for c := range t.conns {
1244 err := func() error {
1247 concurrentChunkWrites.Add(1)
1248 defer concurrentChunkWrites.Add(-1)
1249 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1250 // number of connections. We write inline with receiving the chunk (with this lock dance),
1251 // because we want to handle errors synchronously and I haven't thought of a nice way to
1252 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1254 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1257 piece.decrementPendingWrites()
1260 c.logger.Printf("error writing received chunk %v: %v", req, err)
1262 //t.updatePieceCompletion(pieceIndex(msg.Index))
1263 t.onWriteChunkErr(err)
1267 c.onDirtiedPiece(pieceIndex(req.Index))
1269 if t.pieceAllDirty(pieceIndex(req.Index)) {
1270 t.queuePieceCheck(pieceIndex(req.Index))
1271 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1272 // chunk status (such as the haveChunk call above) to have to check all the various other
1273 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1274 // that chunk pieces are pended at an appropriate time later however.
1277 cl.event.Broadcast()
1278 // We do this because we've written a chunk, and may change PieceState.Partial.
1279 t.publishPieceChange(pieceIndex(req.Index))
1284 func (c *PeerConn) onDirtiedPiece(piece pieceIndex) {
1285 if c.peerTouchedPieces == nil {
1286 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1288 c.peerTouchedPieces[piece] = struct{}{}
1289 ds := &c.t.pieces[piece].dirtiers
1291 *ds = make(map[*PeerConn]struct{})
1293 (*ds)[c] = struct{}{}
1296 func (c *PeerConn) uploadAllowed() bool {
1297 if c.t.cl.config.NoUpload {
1303 if !c.peerHasWantedPieces() {
1306 // Don't upload more than 100 KiB more than we download.
1307 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1313 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1314 if c.uploadTimer == nil {
1315 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1317 c.uploadTimer.Reset(delay)
1321 // Also handles choking and unchoking of the remote peer.
1322 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1323 // Breaking or completing this loop means we don't want to upload to the
1324 // peer anymore, and we choke them.
1326 for c.uploadAllowed() {
1327 // We want to upload to the peer.
1328 if !c.unchoke(msg) {
1331 for r := range c.peerRequests {
1332 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1334 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1336 delay := res.Delay()
1339 c.setRetryUploadTimer(delay)
1340 // Hard to say what to return here.
1343 more, err := c.sendChunk(r, msg)
1345 i := pieceIndex(r.Index)
1346 if c.t.pieceComplete(i) {
1347 c.t.updatePieceCompletion(i)
1348 if !c.t.pieceComplete(i) {
1349 // We had the piece, but not anymore.
1353 log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
1354 // If we failed to send a chunk, choke the peer to ensure they
1355 // flush all their requests. We've probably dropped a piece,
1356 // but there's no way to communicate this to the peer. If they
1357 // ask for it again, we'll kick them to allow us to send them
1358 // an updated bitfield.
1361 delete(c.peerRequests, r)
1372 func (cn *PeerConn) drop() {
1373 cn.t.dropConnection(cn)
1376 func (cn *PeerConn) netGoodPiecesDirtied() int64 {
1377 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1380 func (c *PeerConn) peerHasWantedPieces() bool {
1381 return !c._pieceRequestOrder.IsEmpty()
1384 func (c *PeerConn) numLocalRequests() int {
1385 return len(c.requests)
1388 func (c *PeerConn) deleteRequest(r request) bool {
1389 if _, ok := c.requests[r]; !ok {
1392 delete(c.requests, r)
1393 c.updateExpectingChunks()
1394 c.t.requestStrategy.hooks().deletedRequest(r)
1395 pr := c.t.pendingRequests
1405 for _c := range c.t.conns {
1406 if !_c.interested && _c != c && c.peerHasPiece(pieceIndex(r.Index)) {
1413 func (c *PeerConn) deleteAllRequests() {
1414 for r := range c.requests {
1417 if len(c.requests) != 0 {
1418 panic(len(c.requests))
1420 // for c := range c.t.conns {
1425 func (c *PeerConn) tickleWriter() {
1426 c.writerCond.Broadcast()
1429 func (c *PeerConn) postCancel(r request) bool {
1430 if !c.deleteRequest(r) {
1433 c.post(makeCancelMessage(r))
1437 func (c *PeerConn) sendChunk(r request, msg func(pp.Message) bool) (more bool, err error) {
1438 // Count the chunk being sent, even if it isn't.
1439 b := make([]byte, r.Length)
1440 p := c.t.info.Piece(int(r.Index))
1441 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1444 panic("expected error")
1447 } else if err == io.EOF {
1450 more = msg(pp.Message{
1456 c.lastChunkSent = time.Now()
1460 func (c *PeerConn) setTorrent(t *Torrent) {
1462 panic("connection already associated with a torrent")
1465 c.logger.Printf("torrent=%v", t)
1466 t.reconcileHandshakeStats(c)
1469 func (c *PeerConn) peerPriority() peerPriority {
1470 return bep40PriorityIgnoreError(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1473 func (c *PeerConn) remoteIp() net.IP {
1474 return addrIpOrNil(c.remoteAddr)
1477 func (c *PeerConn) remoteIpPort() IpPort {
1478 ipa, _ := tryIpPortFromNetAddr(c.remoteAddr)
1479 return IpPort{ipa.IP, uint16(ipa.Port)}
1482 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1483 f := pp.PexPeerFlags(0)
1484 if c.PeerPrefersEncryption {
1485 f |= pp.PexPrefersEncryption
1488 f |= pp.PexOutgoingConn
1491 f |= pp.PexSupportsUtp
1496 func (c *PeerConn) String() string {
1497 return fmt.Sprintf("connection %p", c)
1500 func (c *PeerConn) trust() connectionTrust {
1501 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1504 type connectionTrust struct {
1506 NetGoodPiecesDirted int64
1509 func (l connectionTrust) Less(r connectionTrust) bool {
1510 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1513 func (cn *PeerConn) requestStrategyConnection() requestStrategyConnection {
1517 func (cn *PeerConn) chunksReceivedWhileExpecting() int64 {
1518 return cn._chunksReceivedWhileExpecting
1521 func (cn *PeerConn) fastest() bool {
1522 return cn == cn.t.fastestConn
1525 func (cn *PeerConn) peerMaxRequests() int {
1526 return cn.PeerMaxRequests
1529 // Returns the pieces the peer has claimed to have.
1530 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1532 defer cn.locker().RUnlock()
1533 return cn.peerPieces()
1536 func (cn *PeerConn) peerPieces() bitmap.Bitmap {
1537 ret := cn._peerPieces.Copy()
1538 if cn.peerSentHaveAll {
1539 ret.AddRange(0, cn.t.numPieces())
1544 func (cn *PeerConn) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1545 return &cn._pieceRequestOrder
1548 func (cn *PeerConn) stats() *ConnStats {
1552 func (cn *PeerConn) torrent() requestStrategyTorrent {
1553 return cn.t.requestStrategyTorrent()