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 (requestStrategyThree) 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(cn.torrent().duplicateRequestTimeout())/expectingTime,
411 func defaultNominalMaxRequests(cn requestStrategyConnection) int {
414 cn.stats().ChunksReadUseful.Int64()-(cn.stats().ChunksRead.Int64()-cn.stats().ChunksReadUseful.Int64())))
416 func (rs requestStrategyOne) nominalMaxRequests(cn requestStrategyConnection) int {
417 return defaultNominalMaxRequests(cn)
419 func (rs requestStrategyTwo) 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.lastRequested[r] = time.AfterFunc(cn.t._duplicateRequestTimeout, func() {
537 torrent.Add("duplicate request timeouts", 1)
539 defer cn.mu().Unlock()
540 delete(cn.t.lastRequested, r)
541 for cn := range cn.t.conns {
542 if cn.PeerHasPiece(pieceIndex(r.Index)) {
547 cn.updateExpectingChunks()
548 return mw(pp.Message{
556 func (cn *connection) fillWriteBuffer(msg func(pp.Message) bool) {
557 if !cn.t.networkingEnabled {
558 if !cn.SetInterested(false, msg) {
561 if len(cn.requests) != 0 {
562 for r := range cn.requests {
564 // log.Printf("%p: cancelling request: %v", cn, r)
565 if !msg(makeCancelMessage(r)) {
571 if len(cn.requests) <= cn.requestsLowWater {
572 filledBuffer := false
573 cn.iterPendingPieces(func(pieceIndex pieceIndex) bool {
574 cn.iterPendingRequests(pieceIndex, func(r request) bool {
575 if !cn.SetInterested(true, msg) {
579 if len(cn.requests) >= cn.nominalMaxRequests() {
582 // Choking is looked at here because our interest is dependent
583 // on whether we'd make requests in its absence.
585 if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
589 if _, ok := cn.requests[r]; ok {
592 filledBuffer = !cn.request(r, msg)
598 // If we didn't completely top up the requests, we shouldn't mark
599 // the low water, since we'll want to top up the requests as soon
600 // as we have more write buffer space.
603 cn.requestsLowWater = len(cn.requests) / 2
609 // Routine that writes to the peer. Some of what to write is buffered by
610 // activity elsewhere in the Client, and some is determined locally when the
611 // connection is writable.
612 func (cn *connection) writer(keepAliveTimeout time.Duration) {
614 lastWrite time.Time = time.Now()
615 keepAliveTimer *time.Timer
617 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
619 defer cn.mu().Unlock()
620 if time.Since(lastWrite) >= keepAliveTimeout {
623 keepAliveTimer.Reset(keepAliveTimeout)
626 defer cn.mu().Unlock()
628 defer keepAliveTimer.Stop()
629 frontBuf := new(bytes.Buffer)
631 if cn.closed.IsSet() {
634 if cn.writeBuffer.Len() == 0 {
635 cn.fillWriteBuffer(func(msg pp.Message) bool {
637 cn.writeBuffer.Write(msg.MustMarshalBinary())
638 torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
639 return cn.writeBuffer.Len() < 1<<16 // 64KiB
642 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
643 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
644 postedKeepalives.Add(1)
646 if cn.writeBuffer.Len() == 0 {
647 // TODO: Minimize wakeups....
652 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
654 n, err := cn.w.Write(frontBuf.Bytes())
657 lastWrite = time.Now()
658 keepAliveTimer.Reset(keepAliveTimeout)
663 if n != frontBuf.Len() {
670 func (cn *connection) Have(piece pieceIndex) {
671 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
676 Index: pp.Integer(piece),
678 cn.sentHaves.Add(bitmap.BitIndex(piece))
681 func (cn *connection) PostBitfield() {
682 if cn.sentHaves.Len() != 0 {
683 panic("bitfield must be first have-related message sent")
685 if !cn.t.haveAnyPieces() {
690 Bitfield: cn.t.bitfield(),
692 cn.sentHaves = cn.t._completedPieces.Copy()
695 func (cn *connection) updateRequests() {
696 // log.Print("update requests")
700 // Emits the indices in the Bitmaps bms in order, never repeating any index.
701 // skip is mutated during execution, and its initial values will never be
703 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
704 return func(cb iter.Callback) {
705 for _, bm := range bms {
707 func(i interface{}) bool {
711 bitmap.Sub(bm, *skip).Iter,
719 func iterUnbiasedPieceRequestOrder(cn requestStrategyConnection, f func(piece pieceIndex) bool) bool {
720 now, readahead := cn.torrent().readerPiecePriorities()
721 skip := bitmap.Flip(cn.peerPieces(), 0, cn.torrent().numPieces())
722 skip.Union(cn.torrent().ignorePieces())
723 // Return an iterator over the different priority classes, minus the skip pieces.
725 func(_piece interface{}) bool {
726 return f(pieceIndex(_piece.(bitmap.BitIndex)))
728 iterBitmapsDistinct(&skip, now, readahead),
729 // We have to iterate _pendingPieces separately because it isn't a Bitmap.
730 func(cb iter.Callback) {
731 cn.torrent().pendingPieces().IterTyped(func(piece int) bool {
732 if skip.Contains(piece) {
743 // The connection should download highest priority pieces first, without any inclination toward
744 // avoiding wastage. Generally we might do this if there's a single connection, or this is the
745 // fastest connection, and we have active readers that signal an ordering preference. It's
746 // conceivable that the best connection should do this, since it's least likely to waste our time if
747 // assigned to the highest priority pieces, and assigning more than one this role would cause
748 // significant wasted bandwidth.
749 func (cn *connection) shouldRequestWithoutBias() bool {
750 return cn.t.requestStrategy.shouldRequestWithoutBias(cn.requestStrategyConnection())
753 func defaultShouldRequestWithoutBias(cn requestStrategyConnection) bool {
757 func (requestStrategyTwo) shouldRequestWithoutBias(cn requestStrategyConnection) bool {
758 if cn.torrent().numReaders() == 0 {
761 if cn.torrent().numConns() == 1 {
770 func (requestStrategyOne) shouldRequestWithoutBias(cn requestStrategyConnection) bool {
771 return defaultShouldRequestWithoutBias(cn)
774 func (requestStrategyThree) shouldRequestWithoutBias(cn requestStrategyConnection) bool {
775 return defaultShouldRequestWithoutBias(cn)
778 func (cn *connection) iterPendingPieces(f func(pieceIndex) bool) bool {
779 if !cn.t.haveInfo() {
782 return cn.t.requestStrategy.iterPendingPieces(cn, f)
784 func (requestStrategyThree) iterPendingPieces(cn requestStrategyConnection, f func(pieceIndex) bool) bool {
785 return iterUnbiasedPieceRequestOrder(cn, f)
787 func defaultIterPendingPieces(rs requestStrategy, cn requestStrategyConnection, f func(pieceIndex) bool) bool {
788 if rs.shouldRequestWithoutBias(cn) {
789 return iterUnbiasedPieceRequestOrder(cn, f)
791 return cn.pieceRequestOrder().IterTyped(func(i int) bool {
792 return f(pieceIndex(i))
796 func (rs requestStrategyOne) iterPendingPieces(cn requestStrategyConnection, cb func(pieceIndex) bool) bool {
797 return defaultIterPendingPieces(rs, cn, cb)
799 func (rs requestStrategyTwo) iterPendingPieces(cn requestStrategyConnection, cb func(pieceIndex) bool) bool {
800 return defaultIterPendingPieces(rs, cn, cb)
803 func (cn *connection) iterPendingPiecesUntyped(f iter.Callback) {
804 cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
807 func (cn *connection) iterPendingRequests(piece pieceIndex, f func(request) bool) bool {
808 return cn.t.requestStrategy.iterUndirtiedChunks(cn.t.piece(piece).requestStrategyPiece(),
809 func(cs chunkSpec) bool {
810 return f(request{pp.Integer(piece), cs})
814 func (requestStrategyThree) iterUndirtiedChunks(p requestStrategyPiece, f func(chunkSpec) bool) bool {
815 for i := pp.Integer(0); i < pp.Integer(p.numChunks()); i++ {
816 if p.dirtyChunks().Get(bitmap.BitIndex(i)) {
819 ci := p.chunkIndexSpec(i)
820 if p.wouldDuplicateRecent(ci) {
823 if !f(p.chunkIndexSpec(i)) {
830 func defaultIterUndirtiedChunks(p requestStrategyPiece, f func(chunkSpec) bool) bool {
831 chunkIndices := p.dirtyChunks().Copy()
832 chunkIndices.FlipRange(0, bitmap.BitIndex(p.numChunks()))
833 return iter.ForPerm(chunkIndices.Len(), func(i int) bool {
834 ci, err := chunkIndices.RB.Select(uint32(i))
838 return f(p.chunkIndexSpec(pp.Integer(ci)))
842 func (rs requestStrategyOne) iterUndirtiedChunks(p requestStrategyPiece, f func(chunkSpec) bool) bool {
843 return defaultIterUndirtiedChunks(p, f)
846 func (rs requestStrategyTwo) iterUndirtiedChunks(p requestStrategyPiece, f func(chunkSpec) bool) bool {
847 return defaultIterUndirtiedChunks(p, f)
850 // check callers updaterequests
851 func (cn *connection) stopRequestingPiece(piece pieceIndex) bool {
852 return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
855 // This is distinct from Torrent piece priority, which is the user's
856 // preference. Connection piece priority is specific to a connection and is
857 // used to pseudorandomly avoid connections always requesting the same pieces
858 // and thus wasting effort.
859 func (cn *connection) updatePiecePriority(piece pieceIndex) bool {
860 tpp := cn.t.piecePriority(piece)
861 if !cn.PeerHasPiece(piece) {
862 tpp = PiecePriorityNone
864 if tpp == PiecePriorityNone {
865 return cn.stopRequestingPiece(piece)
867 prio := cn.getPieceInclination()[piece]
868 prio = cn.t.requestStrategy.piecePriority(cn, piece, tpp, prio)
869 return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
872 func (requestStrategyOne) piecePriority(cn requestStrategyConnection, piece pieceIndex, tpp piecePriority, prio int) int {
874 case PiecePriorityNormal:
875 case PiecePriorityReadahead:
876 prio -= int(cn.torrent().numPieces())
877 case PiecePriorityNext, PiecePriorityNow:
878 prio -= 2 * int(cn.torrent().numPieces())
882 prio += int(piece / 3)
886 func defaultPiecePriority(cn requestStrategyConnection, piece pieceIndex, tpp piecePriority, prio int) int {
890 func (requestStrategyTwo) piecePriority(cn requestStrategyConnection, piece pieceIndex, tpp piecePriority, prio int) int {
891 return defaultPiecePriority(cn, piece, tpp, prio)
894 func (requestStrategyThree) piecePriority(cn requestStrategyConnection, piece pieceIndex, tpp piecePriority, prio int) int {
895 return defaultPiecePriority(cn, piece, tpp, prio)
898 func (cn *connection) getPieceInclination() []int {
899 if cn.pieceInclination == nil {
900 cn.pieceInclination = cn.t.getConnPieceInclination()
902 return cn.pieceInclination
905 func (cn *connection) discardPieceInclination() {
906 if cn.pieceInclination == nil {
909 cn.t.putPieceInclination(cn.pieceInclination)
910 cn.pieceInclination = nil
913 func (cn *connection) peerPiecesChanged() {
915 prioritiesChanged := false
916 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
917 if cn.updatePiecePriority(i) {
918 prioritiesChanged = true
921 if prioritiesChanged {
927 func (cn *connection) raisePeerMinPieces(newMin pieceIndex) {
928 if newMin > cn.peerMinPieces {
929 cn.peerMinPieces = newMin
933 func (cn *connection) peerSentHave(piece pieceIndex) error {
934 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
935 return errors.New("invalid piece")
937 if cn.PeerHasPiece(piece) {
940 cn.raisePeerMinPieces(piece + 1)
941 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
942 if cn.updatePiecePriority(piece) {
948 func (cn *connection) peerSentBitfield(bf []bool) error {
949 cn.peerSentHaveAll = false
951 panic("expected bitfield length divisible by 8")
953 // We know that the last byte means that at most the last 7 bits are
955 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
956 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
957 // Ignore known excess pieces.
958 bf = bf[:cn.t.numPieces()]
960 for i, have := range bf {
962 cn.raisePeerMinPieces(pieceIndex(i) + 1)
964 cn._peerPieces.Set(i, have)
966 cn.peerPiecesChanged()
970 func (cn *connection) onPeerSentHaveAll() error {
971 cn.peerSentHaveAll = true
972 cn._peerPieces.Clear()
973 cn.peerPiecesChanged()
977 func (cn *connection) peerSentHaveNone() error {
978 cn._peerPieces.Clear()
979 cn.peerSentHaveAll = false
980 cn.peerPiecesChanged()
984 func (c *connection) requestPendingMetadata() {
988 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
989 // Peer doesn't support this.
992 // Request metadata pieces that we don't have in a random order.
994 for index := 0; index < c.t.metadataPieceCount(); index++ {
995 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
996 pending = append(pending, index)
999 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
1000 for _, i := range pending {
1001 c.requestMetadataPiece(i)
1005 func (cn *connection) wroteMsg(msg *pp.Message) {
1006 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
1007 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
1010 func (cn *connection) readMsg(msg *pp.Message) {
1011 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
1014 // After handshake, we know what Torrent and Client stats to include for a
1016 func (cn *connection) postHandshakeStats(f func(*ConnStats)) {
1022 // All ConnStats that include this connection. Some objects are not known
1023 // until the handshake is complete, after which it's expected to reconcile the
1025 func (cn *connection) allStats(f func(*ConnStats)) {
1027 if cn.reconciledHandshakeStats {
1028 cn.postHandshakeStats(f)
1032 func (cn *connection) wroteBytes(n int64) {
1033 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
1036 func (cn *connection) readBytes(n int64) {
1037 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
1040 // Returns whether the connection could be useful to us. We're seeding and
1041 // they want data, we don't have metainfo and they can provide it, etc.
1042 func (c *connection) useful() bool {
1044 if c.closed.IsSet() {
1048 return c.supportsExtension("ut_metadata")
1050 if t.seeding() && c.PeerInterested {
1053 if c.peerHasWantedPieces() {
1059 func (c *connection) lastHelpful() (ret time.Time) {
1060 ret = c.lastUsefulChunkReceived
1061 if c.t.seeding() && c.lastChunkSent.After(ret) {
1062 ret = c.lastChunkSent
1067 func (c *connection) fastEnabled() bool {
1068 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.extensionBytes.SupportsFast()
1071 func (c *connection) reject(r request) {
1072 if !c.fastEnabled() {
1073 panic("fast not enabled")
1075 c.Post(r.ToMsg(pp.Reject))
1076 delete(c.PeerRequests, r)
1079 func (c *connection) onReadRequest(r request) error {
1080 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
1081 if _, ok := c.PeerRequests[r]; ok {
1082 torrent.Add("duplicate requests received", 1)
1086 torrent.Add("requests received while choking", 1)
1087 if c.fastEnabled() {
1088 torrent.Add("requests rejected while choking", 1)
1093 if len(c.PeerRequests) >= maxRequests {
1094 torrent.Add("requests received while queue full", 1)
1095 if c.fastEnabled() {
1098 // BEP 6 says we may close here if we choose.
1101 if !c.t.havePiece(pieceIndex(r.Index)) {
1102 // This isn't necessarily them screwing up. We can drop pieces
1103 // from our storage, and can't communicate this to peers
1104 // except by reconnecting.
1105 requestsReceivedForMissingPieces.Add(1)
1106 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1108 // Check this after we know we have the piece, so that the piece length will be known.
1109 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1110 torrent.Add("bad requests received", 1)
1111 return errors.New("bad request")
1113 if c.PeerRequests == nil {
1114 c.PeerRequests = make(map[request]struct{}, maxRequests)
1116 c.PeerRequests[r] = struct{}{}
1121 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1122 // exit. Returning will end the connection.
1123 func (c *connection) mainReadLoop() (err error) {
1126 torrent.Add("connection.mainReadLoop returned with error", 1)
1128 torrent.Add("connection.mainReadLoop returned with no error", 1)
1134 decoder := pp.Decoder{
1135 R: bufio.NewReaderSize(c.r, 1<<17),
1136 MaxLength: 256 * 1024,
1144 err = decoder.Decode(&msg)
1146 if t.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1153 c.lastMessageReceived = time.Now()
1155 receivedKeepalives.Add(1)
1158 messageTypesReceived.Add(msg.Type.String(), 1)
1159 if msg.Type.FastExtension() && !c.fastEnabled() {
1160 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1165 c.deleteAllRequests()
1166 // We can then reset our interest.
1168 c.updateExpectingChunks()
1170 c.PeerChoked = false
1172 c.updateExpectingChunks()
1174 c.PeerInterested = true
1176 case pp.NotInterested:
1177 c.PeerInterested = false
1178 // We don't clear their requests since it isn't clear in the spec.
1179 // We'll probably choke them for this, which will clear them if
1180 // appropriate, and is clearly specified.
1182 err = c.peerSentHave(pieceIndex(msg.Index))
1184 err = c.peerSentBitfield(msg.Bitfield)
1186 r := newRequestFromMessage(&msg)
1187 err = c.onReadRequest(r)
1189 err = c.receiveChunk(&msg)
1190 if len(msg.Piece) == int(t.chunkSize) {
1191 t.chunkPool.Put(&msg.Piece)
1194 err = fmt.Errorf("receiving chunk: %s", err)
1197 req := newRequestFromMessage(&msg)
1198 c.onPeerSentCancel(req)
1200 pingAddr := net.UDPAddr{
1201 IP: c.remoteAddr.IP,
1202 Port: int(c.remoteAddr.Port),
1205 pingAddr.Port = int(msg.Port)
1207 cl.eachDhtServer(func(s *dht.Server) {
1208 go s.Ping(&pingAddr, nil)
1211 torrent.Add("suggests received", 1)
1212 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index, debugLogValue).Log(c.t.logger)
1215 err = c.onPeerSentHaveAll()
1217 err = c.peerSentHaveNone()
1219 c.deleteRequest(newRequestFromMessage(&msg))
1220 delete(c.validReceiveChunks, newRequestFromMessage(&msg))
1221 case pp.AllowedFast:
1222 torrent.Add("allowed fasts received", 1)
1223 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c, debugLogValue).Log(c.t.logger)
1224 c.peerAllowedFast.Add(int(msg.Index))
1227 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1229 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1237 func (c *connection) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1239 // TODO: Should we still do this?
1241 // These clients use their own extension IDs for outgoing message
1242 // types, which is incorrect.
1243 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1251 case pp.HandshakeExtendedID:
1252 var d pp.ExtendedHandshakeMessage
1253 if err := bencode.Unmarshal(payload, &d); err != nil {
1254 c.t.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1255 return errors.Wrap(err, "unmarshalling extended handshake payload")
1258 c.PeerMaxRequests = d.Reqq
1260 c.PeerClientName = d.V
1261 if c.PeerExtensionIDs == nil {
1262 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1264 for name, id := range d.M {
1265 if _, ok := c.PeerExtensionIDs[name]; !ok {
1266 torrent.Add(fmt.Sprintf("peers supporting extension %q", name), 1)
1268 c.PeerExtensionIDs[name] = id
1270 if d.MetadataSize != 0 {
1271 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1272 return errors.Wrapf(err, "setting metadata size to %d", d.MetadataSize)
1275 c.requestPendingMetadata()
1277 case metadataExtendedId:
1278 err := cl.gotMetadataExtensionMsg(payload, t, c)
1280 return fmt.Errorf("handling metadata extension message: %w", err)
1284 if cl.config.DisablePEX {
1285 // TODO: Maybe close the connection. Check that we're not
1286 // advertising that we support PEX if it's disabled.
1289 var pexMsg pp.PexMsg
1290 err := bencode.Unmarshal(payload, &pexMsg)
1292 return fmt.Errorf("error unmarshalling PEX message: %s", err)
1294 torrent.Add("pex added6 peers received", int64(len(pexMsg.Added6)))
1296 peers.AppendFromPex(pexMsg.Added6, pexMsg.Added6Flags)
1297 peers.AppendFromPex(pexMsg.Added, pexMsg.AddedFlags)
1301 return fmt.Errorf("unexpected extended message ID: %v", id)
1305 // Set both the Reader and Writer for the connection from a single ReadWriter.
1306 func (cn *connection) setRW(rw io.ReadWriter) {
1311 // Returns the Reader and Writer as a combined ReadWriter.
1312 func (cn *connection) rw() io.ReadWriter {
1319 // Handle a received chunk from a peer.
1320 func (c *connection) receiveChunk(msg *pp.Message) error {
1323 torrent.Add("chunks received", 1)
1325 req := newRequestFromMessage(msg)
1328 torrent.Add("chunks received while choked", 1)
1331 if _, ok := c.validReceiveChunks[req]; !ok {
1332 torrent.Add("chunks received unexpected", 1)
1333 return errors.New("received unexpected chunk")
1335 delete(c.validReceiveChunks, req)
1337 if c.PeerChoked && c.peerAllowedFast.Get(int(req.Index)) {
1338 torrent.Add("chunks received due to allowed fast", 1)
1341 // Request has been satisfied.
1342 if c.deleteRequest(req) {
1343 if c.expectingChunks() {
1344 c._chunksReceivedWhileExpecting++
1347 torrent.Add("chunks received unwanted", 1)
1350 // Do we actually want this chunk?
1351 if t.haveChunk(req) {
1352 torrent.Add("chunks received wasted", 1)
1353 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1357 piece := &t.pieces[req.Index]
1359 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1360 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1361 c.lastUsefulChunkReceived = time.Now()
1362 // if t.fastestConn != c {
1363 // log.Printf("setting fastest connection %p", c)
1367 // Need to record that it hasn't been written yet, before we attempt to do
1368 // anything with it.
1369 piece.incrementPendingWrites()
1370 // Record that we have the chunk, so we aren't trying to download it while
1371 // waiting for it to be written to storage.
1372 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1374 // Cancel pending requests for this chunk.
1375 for c := range t.conns {
1379 err := func() error {
1382 concurrentChunkWrites.Add(1)
1383 defer concurrentChunkWrites.Add(-1)
1384 // Write the chunk out. Note that the upper bound on chunk writing
1385 // concurrency will be the number of connections. We write inline with
1386 // receiving the chunk (with this lock dance), because we want to
1387 // handle errors synchronously and I haven't thought of a nice way to
1388 // defer any concurrency to the storage and have that notify the
1389 // client of errors. TODO: Do that instead.
1390 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1393 piece.decrementPendingWrites()
1396 panic(fmt.Sprintf("error writing chunk: %v", err))
1398 t.updatePieceCompletion(pieceIndex(msg.Index))
1402 // It's important that the piece is potentially queued before we check if
1403 // the piece is still wanted, because if it is queued, it won't be wanted.
1404 if t.pieceAllDirty(pieceIndex(req.Index)) {
1405 t.queuePieceCheck(pieceIndex(req.Index))
1406 t.pendAllChunkSpecs(pieceIndex(req.Index))
1409 c.onDirtiedPiece(pieceIndex(req.Index))
1411 cl.event.Broadcast()
1412 t.publishPieceChange(pieceIndex(req.Index))
1417 func (c *connection) onDirtiedPiece(piece pieceIndex) {
1418 if c.peerTouchedPieces == nil {
1419 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1421 c.peerTouchedPieces[piece] = struct{}{}
1422 ds := &c.t.pieces[piece].dirtiers
1424 *ds = make(map[*connection]struct{})
1426 (*ds)[c] = struct{}{}
1429 func (c *connection) uploadAllowed() bool {
1430 if c.t.cl.config.NoUpload {
1436 if !c.peerHasWantedPieces() {
1439 // Don't upload more than 100 KiB more than we download.
1440 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1446 func (c *connection) setRetryUploadTimer(delay time.Duration) {
1447 if c.uploadTimer == nil {
1448 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1450 c.uploadTimer.Reset(delay)
1454 // Also handles choking and unchoking of the remote peer.
1455 func (c *connection) upload(msg func(pp.Message) bool) bool {
1456 // Breaking or completing this loop means we don't want to upload to the
1457 // peer anymore, and we choke them.
1459 for c.uploadAllowed() {
1460 // We want to upload to the peer.
1461 if !c.Unchoke(msg) {
1464 for r := range c.PeerRequests {
1465 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1467 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1469 delay := res.Delay()
1472 c.setRetryUploadTimer(delay)
1473 // Hard to say what to return here.
1476 more, err := c.sendChunk(r, msg)
1478 i := pieceIndex(r.Index)
1479 if c.t.pieceComplete(i) {
1480 c.t.updatePieceCompletion(i)
1481 if !c.t.pieceComplete(i) {
1482 // We had the piece, but not anymore.
1486 log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
1487 // If we failed to send a chunk, choke the peer to ensure they
1488 // flush all their requests. We've probably dropped a piece,
1489 // but there's no way to communicate this to the peer. If they
1490 // ask for it again, we'll kick them to allow us to send them
1491 // an updated bitfield.
1494 delete(c.PeerRequests, r)
1505 func (cn *connection) Drop() {
1506 cn.t.dropConnection(cn)
1509 func (cn *connection) netGoodPiecesDirtied() int64 {
1510 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1513 func (c *connection) peerHasWantedPieces() bool {
1514 return !c._pieceRequestOrder.IsEmpty()
1517 func (c *connection) numLocalRequests() int {
1518 return len(c.requests)
1521 func (c *connection) deleteRequest(r request) bool {
1522 if _, ok := c.requests[r]; !ok {
1525 delete(c.requests, r)
1526 c.updateExpectingChunks()
1527 if t, ok := c.t.lastRequested[r]; ok {
1529 delete(c.t.lastRequested, 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()