16 "github.com/anacrolix/dht/v2"
17 "github.com/anacrolix/log"
18 "github.com/anacrolix/missinggo"
19 "github.com/anacrolix/missinggo/iter"
20 "github.com/anacrolix/missinggo/v2/bitmap"
21 "github.com/anacrolix/missinggo/v2/prioritybitmap"
22 "github.com/anacrolix/multiless"
23 "github.com/pkg/errors"
25 "github.com/anacrolix/torrent/bencode"
26 "github.com/anacrolix/torrent/mse"
27 pp "github.com/anacrolix/torrent/peer_protocol"
30 type peerSource string
33 peerSourceTracker = "Tr"
34 peerSourceIncoming = "I"
35 peerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
36 peerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
40 // Maintains the state of a connection with a peer.
41 type connection struct {
42 // First to ensure 64-bit alignment for atomics. See #262.
46 // The actual Conn, used for closing, and setting socket options.
51 // The Reader and Writer for this Conn, with hooks installed for stats,
52 // limiting, deadlines etc.
55 // True if the connection is operating over MSE obfuscation.
57 cryptoMethod mse.CryptoMethod
60 closed missinggo.Event
61 // Set true after we've added our ConnStats generated during handshake to
62 // other ConnStat instances as determined when the *Torrent became known.
63 reconciledHandshakeStats bool
65 lastMessageReceived time.Time
66 completedHandshake time.Time
67 lastUsefulChunkReceived time.Time
68 lastChunkSent time.Time
70 // Stuff controlled by the local peer.
72 lastBecameInterested time.Time
73 priorInterest time.Duration
75 lastStartedExpectingToReceiveChunks time.Time
76 cumulativeExpectedToReceiveChunks time.Duration
77 _chunksReceivedWhileExpecting int64
80 requests map[request]struct{}
82 // Chunks that we might reasonably expect to receive from the peer. Due to
83 // latency, buffering, and implementation differences, we may receive
84 // chunks that are no longer in the set of requests actually want.
85 validReceiveChunks map[request]struct{}
86 // Indexed by metadata piece, set to true if posted and pending a
88 metadataRequests []bool
89 sentHaves bitmap.Bitmap
91 // Stuff controlled by the remote peer.
95 PeerRequests map[request]struct{}
96 PeerExtensionBytes pp.PeerExtensionBits
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 *connection) 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 *connection) expectingChunks() bool {
138 return cn.Interested && !cn.PeerChoked
141 // Returns true if the connection is over IPv6.
142 func (cn *connection) ipv6() bool {
143 ip := cn.remoteAddr.IP
147 return len(ip) == net.IPv6len
150 // Returns true the dialer has the lower client peer ID. TODO: Find the
151 // specification for this.
152 func (cn *connection) 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 *connection) hasPreferredNetworkOver(r *connection) (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 *connection) cumInterest() time.Duration {
168 ret := cn.priorInterest
170 ret += time.Since(cn.lastBecameInterested)
175 func (cn *connection) 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 *connection) mu() sync.Locker {
186 return cn.t.cl.locker()
189 func (cn *connection) localAddr() net.Addr {
190 return cn.conn.LocalAddr()
193 func (cn *connection) 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 *connection) bestPeerNumPieces() pieceIndex {
201 return cn.t.numPieces()
203 return cn.peerMinPieces
206 func (cn *connection) 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 *connection) 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 *connection) 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 *connection) utp() bool {
247 return parseNetworkString(cn.network).Udp
250 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
251 func (cn *connection) 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 *connection) downloadRate() float64 {
280 return float64(cn._stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds()
283 func (cn *connection) 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 *connection) Close() {
320 if !cn.closed.Set() {
324 cn.discardPieceInclination()
325 cn._pieceRequestOrder.Clear()
331 func (cn *connection) 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 *connection) 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 *connection) 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 *connection) 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 *connection) nominalMaxRequests() (ret int) {
385 int64(cn.PeerMaxRequests),
386 int64(cn.t.requestStrategy.nominalMaxRequests(cn.requestStrategyConnection())),
390 // The actual value to use as the maximum outbound requests.
391 func (rs requestStrategyDuplicateRequestTimeout) nominalMaxRequests(cn requestStrategyConnection) (ret int) {
392 expectingTime := int64(cn.totalExpectingTime())
393 if expectingTime == 0 {
394 expectingTime = math.MaxInt64
400 int64(cn.peerMaxRequests()),
402 // It makes sense to always pipeline at least one connection, since latency must be
405 // Request only as many as we expect to receive in the duplicateRequestTimeout
406 // window. We are trying to avoid having to duplicate requests.
407 cn.chunksReceivedWhileExpecting()*int64(rs.duplicateRequestTimeout)/expectingTime,
411 func defaultNominalMaxRequests(cn requestStrategyConnection) int {
414 cn.stats().ChunksReadUseful.Int64()-(cn.stats().ChunksRead.Int64()-cn.stats().ChunksReadUseful.Int64())))
416 func (rs requestStrategyFuzzing) nominalMaxRequests(cn requestStrategyConnection) int {
417 return defaultNominalMaxRequests(cn)
419 func (rs requestStrategyFastest) nominalMaxRequests(cn requestStrategyConnection) int {
420 return defaultNominalMaxRequests(cn)
423 func (cn *connection) totalExpectingTime() (ret time.Duration) {
424 ret = cn.cumulativeExpectedToReceiveChunks
425 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
426 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
432 func (cn *connection) onPeerSentCancel(r request) {
433 if _, ok := cn.PeerRequests[r]; !ok {
434 torrent.Add("unexpected cancels received", 1)
437 if cn.fastEnabled() {
440 delete(cn.PeerRequests, r)
444 func (cn *connection) Choke(msg messageWriter) (more bool) {
449 more = msg(pp.Message{
452 if cn.fastEnabled() {
453 for r := range cn.PeerRequests {
454 // TODO: Don't reject pieces in allowed fast set.
458 cn.PeerRequests = nil
463 func (cn *connection) Unchoke(msg func(pp.Message) bool) bool {
468 return msg(pp.Message{
473 func (cn *connection) SetInterested(interested bool, msg func(pp.Message) bool) bool {
474 if cn.Interested == interested {
477 cn.Interested = interested
479 cn.lastBecameInterested = time.Now()
480 } else if !cn.lastBecameInterested.IsZero() {
481 cn.priorInterest += time.Since(cn.lastBecameInterested)
483 cn.updateExpectingChunks()
484 // log.Printf("%p: setting interest: %v", cn, interested)
485 return msg(pp.Message{
486 Type: func() pp.MessageType {
490 return pp.NotInterested
496 // The function takes a message to be sent, and returns true if more messages
498 type messageWriter func(pp.Message) bool
500 // Proxies the messageWriter's response.
501 func (cn *connection) request(r request, mw messageWriter) bool {
502 if _, ok := cn.requests[r]; ok {
503 panic("chunk already requested")
505 if !cn.PeerHasPiece(pieceIndex(r.Index)) {
506 panic("requesting piece peer doesn't have")
508 if _, ok := cn.t.conns[cn]; !ok {
509 panic("requesting but not in active conns")
511 if cn.closed.IsSet() {
512 panic("requesting when connection is closed")
515 if cn.peerAllowedFast.Get(int(r.Index)) {
516 torrent.Add("allowed fast requests sent", 1)
518 panic("requesting while choked and not allowed fast")
521 if cn.t.hashingPiece(pieceIndex(r.Index)) {
522 panic("piece is being hashed")
524 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
525 panic("piece is queued for hash")
527 if cn.requests == nil {
528 cn.requests = make(map[request]struct{})
530 cn.requests[r] = struct{}{}
531 if cn.validReceiveChunks == nil {
532 cn.validReceiveChunks = make(map[request]struct{})
534 cn.validReceiveChunks[r] = struct{}{}
535 cn.t.pendingRequests[r]++
536 cn.t.requestStrategy.hooks().sentRequest(r)
537 cn.updateExpectingChunks()
538 return mw(pp.Message{
546 func (rs requestStrategyDuplicateRequestTimeout) onSentRequest(r request) {
547 rs.lastRequested[r] = time.AfterFunc(rs.duplicateRequestTimeout, func() {
548 rs.timeoutLocker.Lock()
549 delete(rs.lastRequested, r)
550 rs.timeoutLocker.Unlock()
551 rs.callbacks.requestTimedOut(r)
555 func (cn *connection) fillWriteBuffer(msg func(pp.Message) bool) {
556 if !cn.t.networkingEnabled {
557 if !cn.SetInterested(false, msg) {
560 if len(cn.requests) != 0 {
561 for r := range cn.requests {
563 // log.Printf("%p: cancelling request: %v", cn, r)
564 if !msg(makeCancelMessage(r)) {
570 if len(cn.requests) <= cn.requestsLowWater {
571 filledBuffer := false
572 cn.iterPendingPieces(func(pieceIndex pieceIndex) bool {
573 cn.iterPendingRequests(pieceIndex, func(r request) bool {
574 if !cn.SetInterested(true, msg) {
578 if len(cn.requests) >= cn.nominalMaxRequests() {
581 // Choking is looked at here because our interest is dependent
582 // on whether we'd make requests in its absence.
584 if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
588 if _, ok := cn.requests[r]; ok {
591 filledBuffer = !cn.request(r, msg)
597 // If we didn't completely top up the requests, we shouldn't mark
598 // the low water, since we'll want to top up the requests as soon
599 // as we have more write buffer space.
602 cn.requestsLowWater = len(cn.requests) / 2
608 // Routine that writes to the peer. Some of what to write is buffered by
609 // activity elsewhere in the Client, and some is determined locally when the
610 // connection is writable.
611 func (cn *connection) writer(keepAliveTimeout time.Duration) {
613 lastWrite time.Time = time.Now()
614 keepAliveTimer *time.Timer
616 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
618 defer cn.mu().Unlock()
619 if time.Since(lastWrite) >= keepAliveTimeout {
622 keepAliveTimer.Reset(keepAliveTimeout)
625 defer cn.mu().Unlock()
627 defer keepAliveTimer.Stop()
628 frontBuf := new(bytes.Buffer)
630 if cn.closed.IsSet() {
633 if cn.writeBuffer.Len() == 0 {
634 cn.fillWriteBuffer(func(msg pp.Message) bool {
636 cn.writeBuffer.Write(msg.MustMarshalBinary())
637 torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
638 return cn.writeBuffer.Len() < 1<<16 // 64KiB
641 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
642 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
643 postedKeepalives.Add(1)
645 if cn.writeBuffer.Len() == 0 {
646 // TODO: Minimize wakeups....
651 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
653 n, err := cn.w.Write(frontBuf.Bytes())
656 lastWrite = time.Now()
657 keepAliveTimer.Reset(keepAliveTimeout)
662 if n != frontBuf.Len() {
669 func (cn *connection) Have(piece pieceIndex) {
670 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
675 Index: pp.Integer(piece),
677 cn.sentHaves.Add(bitmap.BitIndex(piece))
680 func (cn *connection) PostBitfield() {
681 if cn.sentHaves.Len() != 0 {
682 panic("bitfield must be first have-related message sent")
684 if !cn.t.haveAnyPieces() {
689 Bitfield: cn.t.bitfield(),
691 cn.sentHaves = cn.t._completedPieces.Copy()
694 func (cn *connection) updateRequests() {
695 // log.Print("update requests")
699 // Emits the indices in the Bitmaps bms in order, never repeating any index.
700 // skip is mutated during execution, and its initial values will never be
702 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
703 return func(cb iter.Callback) {
704 for _, bm := range bms {
706 func(i interface{}) bool {
710 bitmap.Sub(bm, *skip).Iter,
718 func iterUnbiasedPieceRequestOrder(cn requestStrategyConnection, f func(piece pieceIndex) bool) bool {
719 now, readahead := cn.torrent().readerPiecePriorities()
720 skip := bitmap.Flip(cn.peerPieces(), 0, cn.torrent().numPieces())
721 skip.Union(cn.torrent().ignorePieces())
722 // Return an iterator over the different priority classes, minus the skip pieces.
724 func(_piece interface{}) bool {
725 return f(pieceIndex(_piece.(bitmap.BitIndex)))
727 iterBitmapsDistinct(&skip, now, readahead),
728 // We have to iterate _pendingPieces separately because it isn't a Bitmap.
729 func(cb iter.Callback) {
730 cn.torrent().pendingPieces().IterTyped(func(piece int) bool {
731 if skip.Contains(piece) {
742 // The connection should download highest priority pieces first, without any inclination toward
743 // avoiding wastage. Generally we might do this if there's a single connection, or this is the
744 // fastest connection, and we have active readers that signal an ordering preference. It's
745 // conceivable that the best connection should do this, since it's least likely to waste our time if
746 // assigned to the highest priority pieces, and assigning more than one this role would cause
747 // significant wasted bandwidth.
748 func (cn *connection) shouldRequestWithoutBias() bool {
749 return cn.t.requestStrategy.shouldRequestWithoutBias(cn.requestStrategyConnection())
752 func defaultShouldRequestWithoutBias(cn requestStrategyConnection) bool {
756 func (requestStrategyFastest) shouldRequestWithoutBias(cn requestStrategyConnection) bool {
757 if cn.torrent().numReaders() == 0 {
760 if cn.torrent().numConns() == 1 {
769 func (requestStrategyFuzzing) shouldRequestWithoutBias(cn requestStrategyConnection) bool {
770 return defaultShouldRequestWithoutBias(cn)
773 func (requestStrategyDuplicateRequestTimeout) shouldRequestWithoutBias(cn requestStrategyConnection) bool {
774 return defaultShouldRequestWithoutBias(cn)
777 func (cn *connection) iterPendingPieces(f func(pieceIndex) bool) bool {
778 if !cn.t.haveInfo() {
781 return cn.t.requestStrategy.iterPendingPieces(cn, f)
783 func (requestStrategyDuplicateRequestTimeout) iterPendingPieces(cn requestStrategyConnection, f func(pieceIndex) bool) bool {
784 return iterUnbiasedPieceRequestOrder(cn, f)
786 func defaultIterPendingPieces(rs requestStrategy, cn requestStrategyConnection, f func(pieceIndex) bool) bool {
787 if rs.shouldRequestWithoutBias(cn) {
788 return iterUnbiasedPieceRequestOrder(cn, f)
790 return cn.pieceRequestOrder().IterTyped(func(i int) bool {
791 return f(pieceIndex(i))
795 func (rs requestStrategyFuzzing) iterPendingPieces(cn requestStrategyConnection, cb func(pieceIndex) bool) bool {
796 return defaultIterPendingPieces(rs, cn, cb)
798 func (rs requestStrategyFastest) iterPendingPieces(cn requestStrategyConnection, cb func(pieceIndex) bool) bool {
799 return defaultIterPendingPieces(rs, cn, cb)
802 func (cn *connection) iterPendingPiecesUntyped(f iter.Callback) {
803 cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
806 func (cn *connection) 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 func (rs requestStrategyDuplicateRequestTimeout) iterUndirtiedChunks(p requestStrategyPiece, f func(chunkSpec) bool) bool {
816 for i := pp.Integer(0); i < pp.Integer(p.numChunks()); i++ {
817 if p.dirtyChunks().Get(bitmap.BitIndex(i)) {
820 r := p.chunkIndexRequest(i)
821 if rs.wouldDuplicateRecent(r) {
831 func defaultIterUndirtiedChunks(p requestStrategyPiece, f func(chunkSpec) bool) bool {
832 chunkIndices := p.dirtyChunks().Copy()
833 chunkIndices.FlipRange(0, bitmap.BitIndex(p.numChunks()))
834 return iter.ForPerm(chunkIndices.Len(), func(i int) bool {
835 ci, err := chunkIndices.RB.Select(uint32(i))
839 return f(p.chunkIndexRequest(pp.Integer(ci)).chunkSpec)
843 func (rs requestStrategyFuzzing) iterUndirtiedChunks(p requestStrategyPiece, f func(chunkSpec) bool) bool {
844 return defaultIterUndirtiedChunks(p, f)
847 func (rs requestStrategyFastest) iterUndirtiedChunks(p requestStrategyPiece, f func(chunkSpec) bool) bool {
848 return defaultIterUndirtiedChunks(p, f)
851 // check callers updaterequests
852 func (cn *connection) stopRequestingPiece(piece pieceIndex) bool {
853 return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
856 // This is distinct from Torrent piece priority, which is the user's
857 // preference. Connection piece priority is specific to a connection and is
858 // used to pseudorandomly avoid connections always requesting the same pieces
859 // and thus wasting effort.
860 func (cn *connection) updatePiecePriority(piece pieceIndex) bool {
861 tpp := cn.t.piecePriority(piece)
862 if !cn.PeerHasPiece(piece) {
863 tpp = PiecePriorityNone
865 if tpp == PiecePriorityNone {
866 return cn.stopRequestingPiece(piece)
868 prio := cn.getPieceInclination()[piece]
869 prio = cn.t.requestStrategy.piecePriority(cn, piece, tpp, prio)
870 return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
873 func (requestStrategyFuzzing) piecePriority(cn requestStrategyConnection, piece pieceIndex, tpp piecePriority, prio int) int {
875 case PiecePriorityNormal:
876 case PiecePriorityReadahead:
877 prio -= int(cn.torrent().numPieces())
878 case PiecePriorityNext, PiecePriorityNow:
879 prio -= 2 * int(cn.torrent().numPieces())
883 prio += int(piece / 3)
887 func defaultPiecePriority(cn requestStrategyConnection, piece pieceIndex, tpp piecePriority, prio int) int {
891 func (requestStrategyFastest) piecePriority(cn requestStrategyConnection, piece pieceIndex, tpp piecePriority, prio int) int {
892 return defaultPiecePriority(cn, piece, tpp, prio)
895 func (requestStrategyDuplicateRequestTimeout) piecePriority(cn requestStrategyConnection, piece pieceIndex, tpp piecePriority, prio int) int {
896 return defaultPiecePriority(cn, piece, tpp, prio)
899 func (cn *connection) getPieceInclination() []int {
900 if cn.pieceInclination == nil {
901 cn.pieceInclination = cn.t.getConnPieceInclination()
903 return cn.pieceInclination
906 func (cn *connection) discardPieceInclination() {
907 if cn.pieceInclination == nil {
910 cn.t.putPieceInclination(cn.pieceInclination)
911 cn.pieceInclination = nil
914 func (cn *connection) peerPiecesChanged() {
916 prioritiesChanged := false
917 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
918 if cn.updatePiecePriority(i) {
919 prioritiesChanged = true
922 if prioritiesChanged {
928 func (cn *connection) raisePeerMinPieces(newMin pieceIndex) {
929 if newMin > cn.peerMinPieces {
930 cn.peerMinPieces = newMin
934 func (cn *connection) peerSentHave(piece pieceIndex) error {
935 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
936 return errors.New("invalid piece")
938 if cn.PeerHasPiece(piece) {
941 cn.raisePeerMinPieces(piece + 1)
942 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
943 if cn.updatePiecePriority(piece) {
949 func (cn *connection) peerSentBitfield(bf []bool) error {
950 cn.peerSentHaveAll = false
952 panic("expected bitfield length divisible by 8")
954 // We know that the last byte means that at most the last 7 bits are
956 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
957 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
958 // Ignore known excess pieces.
959 bf = bf[:cn.t.numPieces()]
961 for i, have := range bf {
963 cn.raisePeerMinPieces(pieceIndex(i) + 1)
965 cn._peerPieces.Set(i, have)
967 cn.peerPiecesChanged()
971 func (cn *connection) onPeerSentHaveAll() error {
972 cn.peerSentHaveAll = true
973 cn._peerPieces.Clear()
974 cn.peerPiecesChanged()
978 func (cn *connection) peerSentHaveNone() error {
979 cn._peerPieces.Clear()
980 cn.peerSentHaveAll = false
981 cn.peerPiecesChanged()
985 func (c *connection) requestPendingMetadata() {
989 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
990 // Peer doesn't support this.
993 // Request metadata pieces that we don't have in a random order.
995 for index := 0; index < c.t.metadataPieceCount(); index++ {
996 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
997 pending = append(pending, index)
1000 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
1001 for _, i := range pending {
1002 c.requestMetadataPiece(i)
1006 func (cn *connection) wroteMsg(msg *pp.Message) {
1007 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
1008 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
1011 func (cn *connection) readMsg(msg *pp.Message) {
1012 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
1015 // After handshake, we know what Torrent and Client stats to include for a
1017 func (cn *connection) postHandshakeStats(f func(*ConnStats)) {
1023 // All ConnStats that include this connection. Some objects are not known
1024 // until the handshake is complete, after which it's expected to reconcile the
1026 func (cn *connection) allStats(f func(*ConnStats)) {
1028 if cn.reconciledHandshakeStats {
1029 cn.postHandshakeStats(f)
1033 func (cn *connection) wroteBytes(n int64) {
1034 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
1037 func (cn *connection) readBytes(n int64) {
1038 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
1041 // Returns whether the connection could be useful to us. We're seeding and
1042 // they want data, we don't have metainfo and they can provide it, etc.
1043 func (c *connection) useful() bool {
1045 if c.closed.IsSet() {
1049 return c.supportsExtension("ut_metadata")
1051 if t.seeding() && c.PeerInterested {
1054 if c.peerHasWantedPieces() {
1060 func (c *connection) lastHelpful() (ret time.Time) {
1061 ret = c.lastUsefulChunkReceived
1062 if c.t.seeding() && c.lastChunkSent.After(ret) {
1063 ret = c.lastChunkSent
1068 func (c *connection) fastEnabled() bool {
1069 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.extensionBytes.SupportsFast()
1072 func (c *connection) reject(r request) {
1073 if !c.fastEnabled() {
1074 panic("fast not enabled")
1076 c.Post(r.ToMsg(pp.Reject))
1077 delete(c.PeerRequests, r)
1080 func (c *connection) onReadRequest(r request) error {
1081 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
1082 if _, ok := c.PeerRequests[r]; ok {
1083 torrent.Add("duplicate requests received", 1)
1087 torrent.Add("requests received while choking", 1)
1088 if c.fastEnabled() {
1089 torrent.Add("requests rejected while choking", 1)
1094 if len(c.PeerRequests) >= maxRequests {
1095 torrent.Add("requests received while queue full", 1)
1096 if c.fastEnabled() {
1099 // BEP 6 says we may close here if we choose.
1102 if !c.t.havePiece(pieceIndex(r.Index)) {
1103 // This isn't necessarily them screwing up. We can drop pieces
1104 // from our storage, and can't communicate this to peers
1105 // except by reconnecting.
1106 requestsReceivedForMissingPieces.Add(1)
1107 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1109 // Check this after we know we have the piece, so that the piece length will be known.
1110 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1111 torrent.Add("bad requests received", 1)
1112 return errors.New("bad request")
1114 if c.PeerRequests == nil {
1115 c.PeerRequests = make(map[request]struct{}, maxRequests)
1117 c.PeerRequests[r] = struct{}{}
1122 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1123 // exit. Returning will end the connection.
1124 func (c *connection) mainReadLoop() (err error) {
1127 torrent.Add("connection.mainReadLoop returned with error", 1)
1129 torrent.Add("connection.mainReadLoop returned with no error", 1)
1135 decoder := pp.Decoder{
1136 R: bufio.NewReaderSize(c.r, 1<<17),
1137 MaxLength: 256 * 1024,
1145 err = decoder.Decode(&msg)
1147 if t.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1154 c.lastMessageReceived = time.Now()
1156 receivedKeepalives.Add(1)
1159 messageTypesReceived.Add(msg.Type.String(), 1)
1160 if msg.Type.FastExtension() && !c.fastEnabled() {
1161 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1166 c.deleteAllRequests()
1167 // We can then reset our interest.
1169 c.updateExpectingChunks()
1171 c.PeerChoked = false
1173 c.updateExpectingChunks()
1175 c.PeerInterested = true
1177 case pp.NotInterested:
1178 c.PeerInterested = false
1179 // We don't clear their requests since it isn't clear in the spec.
1180 // We'll probably choke them for this, which will clear them if
1181 // appropriate, and is clearly specified.
1183 err = c.peerSentHave(pieceIndex(msg.Index))
1185 err = c.peerSentBitfield(msg.Bitfield)
1187 r := newRequestFromMessage(&msg)
1188 err = c.onReadRequest(r)
1190 err = c.receiveChunk(&msg)
1191 if len(msg.Piece) == int(t.chunkSize) {
1192 t.chunkPool.Put(&msg.Piece)
1195 err = fmt.Errorf("receiving chunk: %s", err)
1198 req := newRequestFromMessage(&msg)
1199 c.onPeerSentCancel(req)
1201 pingAddr := net.UDPAddr{
1202 IP: c.remoteAddr.IP,
1203 Port: int(c.remoteAddr.Port),
1206 pingAddr.Port = int(msg.Port)
1208 cl.eachDhtServer(func(s *dht.Server) {
1209 go s.Ping(&pingAddr, nil)
1212 torrent.Add("suggests received", 1)
1213 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index, debugLogValue).Log(c.t.logger)
1216 err = c.onPeerSentHaveAll()
1218 err = c.peerSentHaveNone()
1220 c.deleteRequest(newRequestFromMessage(&msg))
1221 delete(c.validReceiveChunks, newRequestFromMessage(&msg))
1222 case pp.AllowedFast:
1223 torrent.Add("allowed fasts received", 1)
1224 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c, debugLogValue).Log(c.t.logger)
1225 c.peerAllowedFast.Add(int(msg.Index))
1228 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1230 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1238 func (c *connection) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1240 // TODO: Should we still do this?
1242 // These clients use their own extension IDs for outgoing message
1243 // types, which is incorrect.
1244 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1252 case pp.HandshakeExtendedID:
1253 var d pp.ExtendedHandshakeMessage
1254 if err := bencode.Unmarshal(payload, &d); err != nil {
1255 c.t.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1256 return errors.Wrap(err, "unmarshalling extended handshake payload")
1259 c.PeerMaxRequests = d.Reqq
1261 c.PeerClientName = d.V
1262 if c.PeerExtensionIDs == nil {
1263 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1265 for name, id := range d.M {
1266 if _, ok := c.PeerExtensionIDs[name]; !ok {
1267 torrent.Add(fmt.Sprintf("peers supporting extension %q", name), 1)
1269 c.PeerExtensionIDs[name] = id
1271 if d.MetadataSize != 0 {
1272 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1273 return errors.Wrapf(err, "setting metadata size to %d", d.MetadataSize)
1276 c.requestPendingMetadata()
1278 case metadataExtendedId:
1279 err := cl.gotMetadataExtensionMsg(payload, t, c)
1281 return fmt.Errorf("handling metadata extension message: %w", err)
1285 if cl.config.DisablePEX {
1286 // TODO: Maybe close the connection. Check that we're not
1287 // advertising that we support PEX if it's disabled.
1290 var pexMsg pp.PexMsg
1291 err := bencode.Unmarshal(payload, &pexMsg)
1293 return fmt.Errorf("error unmarshalling PEX message: %s", err)
1295 torrent.Add("pex added6 peers received", int64(len(pexMsg.Added6)))
1297 peers.AppendFromPex(pexMsg.Added6, pexMsg.Added6Flags)
1298 peers.AppendFromPex(pexMsg.Added, pexMsg.AddedFlags)
1302 return fmt.Errorf("unexpected extended message ID: %v", id)
1306 // Set both the Reader and Writer for the connection from a single ReadWriter.
1307 func (cn *connection) setRW(rw io.ReadWriter) {
1312 // Returns the Reader and Writer as a combined ReadWriter.
1313 func (cn *connection) rw() io.ReadWriter {
1320 // Handle a received chunk from a peer.
1321 func (c *connection) receiveChunk(msg *pp.Message) error {
1324 torrent.Add("chunks received", 1)
1326 req := newRequestFromMessage(msg)
1329 torrent.Add("chunks received while choked", 1)
1332 if _, ok := c.validReceiveChunks[req]; !ok {
1333 torrent.Add("chunks received unexpected", 1)
1334 return errors.New("received unexpected chunk")
1336 delete(c.validReceiveChunks, req)
1338 if c.PeerChoked && c.peerAllowedFast.Get(int(req.Index)) {
1339 torrent.Add("chunks received due to allowed fast", 1)
1342 // Request has been satisfied.
1343 if c.deleteRequest(req) {
1344 if c.expectingChunks() {
1345 c._chunksReceivedWhileExpecting++
1348 torrent.Add("chunks received unwanted", 1)
1351 // Do we actually want this chunk?
1352 if t.haveChunk(req) {
1353 torrent.Add("chunks received wasted", 1)
1354 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1358 piece := &t.pieces[req.Index]
1360 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1361 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1362 c.lastUsefulChunkReceived = time.Now()
1363 // if t.fastestConn != c {
1364 // log.Printf("setting fastest connection %p", c)
1368 // Need to record that it hasn't been written yet, before we attempt to do
1369 // anything with it.
1370 piece.incrementPendingWrites()
1371 // Record that we have the chunk, so we aren't trying to download it while
1372 // waiting for it to be written to storage.
1373 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1375 // Cancel pending requests for this chunk.
1376 for c := range t.conns {
1380 err := func() error {
1383 concurrentChunkWrites.Add(1)
1384 defer concurrentChunkWrites.Add(-1)
1385 // Write the chunk out. Note that the upper bound on chunk writing
1386 // concurrency will be the number of connections. We write inline with
1387 // receiving the chunk (with this lock dance), because we want to
1388 // handle errors synchronously and I haven't thought of a nice way to
1389 // defer any concurrency to the storage and have that notify the
1390 // client of errors. TODO: Do that instead.
1391 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1394 piece.decrementPendingWrites()
1397 panic(fmt.Sprintf("error writing chunk: %v", err))
1399 t.updatePieceCompletion(pieceIndex(msg.Index))
1403 c.onDirtiedPiece(pieceIndex(req.Index))
1405 if t.pieceAllDirty(pieceIndex(req.Index)) {
1406 t.queuePieceCheck(pieceIndex(req.Index))
1407 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1408 // chunk status (such as the haveChunk call above) to have to check all the various other
1409 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1410 // that chunk pieces are pended at an appropriate time later however.
1413 cl.event.Broadcast()
1414 // We do this because we've written a chunk, and may change PieceState.Partial.
1415 t.publishPieceChange(pieceIndex(req.Index))
1420 func (c *connection) onDirtiedPiece(piece pieceIndex) {
1421 if c.peerTouchedPieces == nil {
1422 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1424 c.peerTouchedPieces[piece] = struct{}{}
1425 ds := &c.t.pieces[piece].dirtiers
1427 *ds = make(map[*connection]struct{})
1429 (*ds)[c] = struct{}{}
1432 func (c *connection) uploadAllowed() bool {
1433 if c.t.cl.config.NoUpload {
1439 if !c.peerHasWantedPieces() {
1442 // Don't upload more than 100 KiB more than we download.
1443 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1449 func (c *connection) setRetryUploadTimer(delay time.Duration) {
1450 if c.uploadTimer == nil {
1451 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1453 c.uploadTimer.Reset(delay)
1457 // Also handles choking and unchoking of the remote peer.
1458 func (c *connection) upload(msg func(pp.Message) bool) bool {
1459 // Breaking or completing this loop means we don't want to upload to the
1460 // peer anymore, and we choke them.
1462 for c.uploadAllowed() {
1463 // We want to upload to the peer.
1464 if !c.Unchoke(msg) {
1467 for r := range c.PeerRequests {
1468 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1470 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1472 delay := res.Delay()
1475 c.setRetryUploadTimer(delay)
1476 // Hard to say what to return here.
1479 more, err := c.sendChunk(r, msg)
1481 i := pieceIndex(r.Index)
1482 if c.t.pieceComplete(i) {
1483 c.t.updatePieceCompletion(i)
1484 if !c.t.pieceComplete(i) {
1485 // We had the piece, but not anymore.
1489 log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
1490 // If we failed to send a chunk, choke the peer to ensure they
1491 // flush all their requests. We've probably dropped a piece,
1492 // but there's no way to communicate this to the peer. If they
1493 // ask for it again, we'll kick them to allow us to send them
1494 // an updated bitfield.
1497 delete(c.PeerRequests, r)
1508 func (cn *connection) Drop() {
1509 cn.t.dropConnection(cn)
1512 func (cn *connection) netGoodPiecesDirtied() int64 {
1513 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1516 func (c *connection) peerHasWantedPieces() bool {
1517 return !c._pieceRequestOrder.IsEmpty()
1520 func (c *connection) numLocalRequests() int {
1521 return len(c.requests)
1524 func (c *connection) deleteRequest(r request) bool {
1525 if _, ok := c.requests[r]; !ok {
1528 delete(c.requests, r)
1529 c.updateExpectingChunks()
1530 c.t.requestStrategy.hooks().deletedRequest(r)
1531 pr := c.t.pendingRequests
1541 for _c := range c.t.conns {
1542 if !_c.Interested && _c != c && c.PeerHasPiece(pieceIndex(r.Index)) {
1549 func (c *connection) deleteAllRequests() {
1550 for r := range c.requests {
1553 if len(c.requests) != 0 {
1554 panic(len(c.requests))
1556 // for c := range c.t.conns {
1561 func (c *connection) tickleWriter() {
1562 c.writerCond.Broadcast()
1565 func (c *connection) postCancel(r request) bool {
1566 if !c.deleteRequest(r) {
1569 c.Post(makeCancelMessage(r))
1573 func (c *connection) sendChunk(r request, msg func(pp.Message) bool) (more bool, err error) {
1574 // Count the chunk being sent, even if it isn't.
1575 b := make([]byte, r.Length)
1576 p := c.t.info.Piece(int(r.Index))
1577 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1580 panic("expected error")
1583 } else if err == io.EOF {
1586 more = msg(pp.Message{
1592 c.lastChunkSent = time.Now()
1596 func (c *connection) setTorrent(t *Torrent) {
1598 panic("connection already associated with a torrent")
1601 c.logger.Printf("torrent=%v", t)
1602 t.reconcileHandshakeStats(c)
1605 func (c *connection) peerPriority() peerPriority {
1606 return bep40PriorityIgnoreError(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1609 func (c *connection) remoteIp() net.IP {
1610 return c.remoteAddr.IP
1613 func (c *connection) remoteIpPort() IpPort {
1617 func (c *connection) String() string {
1618 return fmt.Sprintf("connection %p", c)
1621 func (c *connection) trust() connectionTrust {
1622 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1625 type connectionTrust struct {
1627 NetGoodPiecesDirted int64
1630 func (l connectionTrust) Less(r connectionTrust) bool {
1631 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1634 func (cn *connection) requestStrategyConnection() requestStrategyConnection {
1638 func (cn *connection) chunksReceivedWhileExpecting() int64 {
1639 return cn._chunksReceivedWhileExpecting
1642 func (cn *connection) fastest() bool {
1643 return cn == cn.t.fastestConn
1646 func (cn *connection) peerMaxRequests() int {
1647 return cn.PeerMaxRequests
1650 func (cn *connection) peerPieces() bitmap.Bitmap {
1651 ret := cn._peerPieces.Copy()
1652 if cn.peerSentHaveAll {
1653 ret.AddRange(0, cn.t.numPieces())
1658 func (cn *connection) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1659 return &cn._pieceRequestOrder
1662 func (cn *connection) stats() *ConnStats {
1666 func (cn *connection) torrent() requestStrategyTorrent {
1667 return cn.t.requestStrategyTorrent()