16 "github.com/anacrolix/dht/v2"
17 "github.com/anacrolix/log"
18 "github.com/anacrolix/missinggo"
19 "github.com/anacrolix/missinggo/bitmap"
20 "github.com/anacrolix/missinggo/iter"
21 "github.com/anacrolix/missinggo/prioritybitmap"
22 "github.com/pkg/errors"
24 "github.com/anacrolix/torrent/bencode"
25 "github.com/anacrolix/torrent/mse"
26 pp "github.com/anacrolix/torrent/peer_protocol"
29 type peerSource string
32 peerSourceTracker = "Tr"
33 peerSourceIncoming = "I"
34 peerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
35 peerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
39 // Maintains the state of a connection with a peer.
40 type connection struct {
41 // First to ensure 64-bit alignment for atomics. See #262.
45 // The actual Conn, used for closing, and setting socket options.
50 // The Reader and Writer for this Conn, with hooks installed for stats,
51 // limiting, deadlines etc.
54 // True if the connection is operating over MSE obfuscation.
56 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 // The pieces the peer has claimed to have.
96 peerPieces bitmap.Bitmap
97 // The peer has everything. This can occur due to a special message, when
98 // we may not even know the number of pieces in the torrent yet.
100 // The highest possible number of pieces the torrent could have based on
101 // communication with the peer. Generally only useful until we have the
103 peerMinPieces pieceIndex
104 // Pieces we've accepted chunks for from the peer.
105 peerTouchedPieces map[pieceIndex]struct{}
106 peerAllowedFast bitmap.Bitmap
108 PeerMaxRequests int // Maximum pending requests the peer allows.
109 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
110 PeerClientName string
112 pieceInclination []int
113 pieceRequestOrder prioritybitmap.PriorityBitmap
115 writeBuffer *bytes.Buffer
116 uploadTimer *time.Timer
122 func (cn *connection) updateExpectingChunks() {
123 if cn.expectingChunks() {
124 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
125 cn.lastStartedExpectingToReceiveChunks = time.Now()
128 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
129 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
130 cn.lastStartedExpectingToReceiveChunks = time.Time{}
135 func (cn *connection) expectingChunks() bool {
136 return cn.Interested && !cn.PeerChoked
139 // Returns true if the connection is over IPv6.
140 func (cn *connection) ipv6() bool {
141 ip := cn.remoteAddr.IP
145 return len(ip) == net.IPv6len
148 // Returns true the dialer has the lower client peer ID. TODO: Find the
149 // specification for this.
150 func (cn *connection) isPreferredDirection() bool {
151 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
154 // Returns whether the left connection should be preferred over the right one,
155 // considering only their networking properties. If ok is false, we can't
157 func (l *connection) hasPreferredNetworkOver(r *connection) (left, ok bool) {
159 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
160 ml.NextBool(!l.utp(), !r.utp())
161 ml.NextBool(l.ipv6(), r.ipv6())
165 func (cn *connection) cumInterest() time.Duration {
166 ret := cn.priorInterest
168 ret += time.Since(cn.lastBecameInterested)
173 func (cn *connection) peerHasAllPieces() (all bool, known bool) {
174 if cn.peerSentHaveAll {
177 if !cn.t.haveInfo() {
180 return bitmap.Flip(cn.peerPieces, 0, bitmap.BitIndex(cn.t.numPieces())).IsEmpty(), true
183 func (cn *connection) mu() sync.Locker {
184 return cn.t.cl.locker()
187 func (cn *connection) localAddr() net.Addr {
188 return cn.conn.LocalAddr()
191 func (cn *connection) supportsExtension(ext pp.ExtensionName) bool {
192 _, ok := cn.PeerExtensionIDs[ext]
196 // The best guess at number of pieces in the torrent for this peer.
197 func (cn *connection) bestPeerNumPieces() pieceIndex {
199 return cn.t.numPieces()
201 return cn.peerMinPieces
204 func (cn *connection) completedString() string {
205 have := pieceIndex(cn.peerPieces.Len())
206 if cn.peerSentHaveAll {
207 have = cn.bestPeerNumPieces()
209 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
212 // Correct the PeerPieces slice length. Return false if the existing slice is
213 // invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
215 func (cn *connection) setNumPieces(num pieceIndex) error {
216 cn.peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
217 cn.peerPiecesChanged()
221 func eventAgeString(t time.Time) string {
225 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
228 func (cn *connection) connectionFlags() (ret string) {
230 ret += string([]byte{b})
232 if cn.cryptoMethod == mse.CryptoMethodRC4 {
234 } else if cn.headerEncrypted {
237 ret += string(cn.Discovery)
244 func (cn *connection) utp() bool {
245 return parseNetworkString(cn.network).Udp
248 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
249 func (cn *connection) statusFlags() (ret string) {
251 ret += string([]byte{b})
260 ret += cn.connectionFlags()
262 if cn.PeerInterested {
271 // func (cn *connection) String() string {
272 // var buf bytes.Buffer
273 // cn.WriteStatus(&buf, nil)
274 // return buf.String()
277 func (cn *connection) downloadRate() float64 {
278 return float64(cn.stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds()
281 func (cn *connection) WriteStatus(w io.Writer, t *Torrent) {
282 // \t isn't preserved in <pre> blocks?
283 fmt.Fprintf(w, "%+-55q %s %s-%s\n", cn.PeerID, cn.PeerExtensionBytes, cn.localAddr(), cn.remoteAddr)
284 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
285 eventAgeString(cn.lastMessageReceived),
286 eventAgeString(cn.completedHandshake),
287 eventAgeString(cn.lastHelpful()),
289 cn.totalExpectingTime(),
292 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: (%d,%d,%d]-%d, flags: %s, dr: %.1f KiB/s\n",
293 cn.completedString(),
294 len(cn.peerTouchedPieces),
295 &cn.stats.ChunksReadUseful,
296 &cn.stats.ChunksRead,
297 &cn.stats.ChunksWritten,
299 cn.numLocalRequests(),
300 cn.nominalMaxRequests(),
301 len(cn.PeerRequests),
303 cn.downloadRate()/(1<<10),
305 fmt.Fprintf(w, " next pieces: %v%s\n",
306 iter.ToSlice(iter.Head(10, cn.iterPendingPiecesUntyped)),
308 if cn.shouldRequestWithoutBias() {
316 func (cn *connection) Close() {
317 if !cn.closed.Set() {
321 cn.discardPieceInclination()
322 cn.pieceRequestOrder.Clear()
328 func (cn *connection) PeerHasPiece(piece pieceIndex) bool {
329 return cn.peerSentHaveAll || cn.peerPieces.Contains(bitmap.BitIndex(piece))
332 // Writes a message into the write buffer.
333 func (cn *connection) Post(msg pp.Message) {
334 torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
335 // We don't need to track bytes here because a connection.w Writer wrapper
336 // takes care of that (although there's some delay between us recording
337 // the message, and the connection writer flushing it out.).
338 cn.writeBuffer.Write(msg.MustMarshalBinary())
339 // Last I checked only Piece messages affect stats, and we don't post
345 func (cn *connection) requestMetadataPiece(index int) {
346 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
350 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
353 cn.logger.Printf("requesting metadata piece %d", index)
357 ExtendedPayload: func() []byte {
358 b, err := bencode.Marshal(map[string]int{
359 "msg_type": pp.RequestMetadataExtensionMsgType,
368 for index >= len(cn.metadataRequests) {
369 cn.metadataRequests = append(cn.metadataRequests, false)
371 cn.metadataRequests[index] = true
374 func (cn *connection) requestedMetadataPiece(index int) bool {
375 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
378 // The actual value to use as the maximum outbound requests.
379 func (cn *connection) nominalMaxRequests() (ret int) {
380 if cn.t.requestStrategy == 3 {
381 expectingTime := int64(cn.totalExpectingTime())
382 if expectingTime == 0 {
383 expectingTime = math.MaxInt64
389 int64(cn.PeerMaxRequests),
391 // It makes sense to always pipeline at least one connection,
392 // since latency must be non-zero.
394 // Request only as many as we expect to receive in the
395 // dupliateRequestTimeout window. We are trying to avoid having to
396 // duplicate requests.
397 cn.chunksReceivedWhileExpecting*int64(cn.t.duplicateRequestTimeout)/expectingTime,
403 int64(cn.PeerMaxRequests),
405 cn.stats.ChunksReadUseful.Int64()-(cn.stats.ChunksRead.Int64()-cn.stats.ChunksReadUseful.Int64()))))
408 func (cn *connection) totalExpectingTime() (ret time.Duration) {
409 ret = cn.cumulativeExpectedToReceiveChunks
410 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
411 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
417 func (cn *connection) onPeerSentCancel(r request) {
418 if _, ok := cn.PeerRequests[r]; !ok {
419 torrent.Add("unexpected cancels received", 1)
422 if cn.fastEnabled() {
425 delete(cn.PeerRequests, r)
429 func (cn *connection) Choke(msg messageWriter) (more bool) {
434 more = msg(pp.Message{
437 if cn.fastEnabled() {
438 for r := range cn.PeerRequests {
439 // TODO: Don't reject pieces in allowed fast set.
443 cn.PeerRequests = nil
448 func (cn *connection) Unchoke(msg func(pp.Message) bool) bool {
453 return msg(pp.Message{
458 func (cn *connection) SetInterested(interested bool, msg func(pp.Message) bool) bool {
459 if cn.Interested == interested {
462 cn.Interested = interested
464 cn.lastBecameInterested = time.Now()
465 } else if !cn.lastBecameInterested.IsZero() {
466 cn.priorInterest += time.Since(cn.lastBecameInterested)
468 cn.updateExpectingChunks()
469 // log.Printf("%p: setting interest: %v", cn, interested)
470 return msg(pp.Message{
471 Type: func() pp.MessageType {
475 return pp.NotInterested
481 // The function takes a message to be sent, and returns true if more messages
483 type messageWriter func(pp.Message) bool
485 // Proxies the messageWriter's response.
486 func (cn *connection) request(r request, mw messageWriter) bool {
487 if _, ok := cn.requests[r]; ok {
488 panic("chunk already requested")
490 if !cn.PeerHasPiece(pieceIndex(r.Index)) {
491 panic("requesting piece peer doesn't have")
493 if _, ok := cn.t.conns[cn]; !ok {
494 panic("requesting but not in active conns")
496 if cn.closed.IsSet() {
497 panic("requesting when connection is closed")
500 if cn.peerAllowedFast.Get(int(r.Index)) {
501 torrent.Add("allowed fast requests sent", 1)
503 panic("requesting while choked and not allowed fast")
506 if cn.t.hashingPiece(pieceIndex(r.Index)) {
507 panic("piece is being hashed")
509 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
510 panic("piece is queued for hash")
512 if cn.requests == nil {
513 cn.requests = make(map[request]struct{})
515 cn.requests[r] = struct{}{}
516 if cn.validReceiveChunks == nil {
517 cn.validReceiveChunks = make(map[request]struct{})
519 cn.validReceiveChunks[r] = struct{}{}
520 cn.t.pendingRequests[r]++
521 cn.t.lastRequested[r] = time.AfterFunc(cn.t.duplicateRequestTimeout, func() {
522 torrent.Add("duplicate request timeouts", 1)
524 defer cn.mu().Unlock()
525 delete(cn.t.lastRequested, r)
526 for cn := range cn.t.conns {
527 if cn.PeerHasPiece(pieceIndex(r.Index)) {
532 cn.updateExpectingChunks()
533 return mw(pp.Message{
541 func (cn *connection) fillWriteBuffer(msg func(pp.Message) bool) {
542 if !cn.t.networkingEnabled {
543 if !cn.SetInterested(false, msg) {
546 if len(cn.requests) != 0 {
547 for r := range cn.requests {
549 // log.Printf("%p: cancelling request: %v", cn, r)
550 if !msg(makeCancelMessage(r)) {
556 if len(cn.requests) <= cn.requestsLowWater {
557 filledBuffer := false
558 cn.iterPendingPieces(func(pieceIndex pieceIndex) bool {
559 cn.iterPendingRequests(pieceIndex, func(r request) bool {
560 if !cn.SetInterested(true, msg) {
564 if len(cn.requests) >= cn.nominalMaxRequests() {
567 // Choking is looked at here because our interest is dependent
568 // on whether we'd make requests in its absence.
570 if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
574 if _, ok := cn.requests[r]; ok {
577 filledBuffer = !cn.request(r, msg)
583 // If we didn't completely top up the requests, we shouldn't mark
584 // the low water, since we'll want to top up the requests as soon
585 // as we have more write buffer space.
588 cn.requestsLowWater = len(cn.requests) / 2
594 // Routine that writes to the peer. Some of what to write is buffered by
595 // activity elsewhere in the Client, and some is determined locally when the
596 // connection is writable.
597 func (cn *connection) writer(keepAliveTimeout time.Duration) {
599 lastWrite time.Time = time.Now()
600 keepAliveTimer *time.Timer
602 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
604 defer cn.mu().Unlock()
605 if time.Since(lastWrite) >= keepAliveTimeout {
608 keepAliveTimer.Reset(keepAliveTimeout)
611 defer cn.mu().Unlock()
613 defer keepAliveTimer.Stop()
614 frontBuf := new(bytes.Buffer)
616 if cn.closed.IsSet() {
619 if cn.writeBuffer.Len() == 0 {
620 cn.fillWriteBuffer(func(msg pp.Message) bool {
622 cn.writeBuffer.Write(msg.MustMarshalBinary())
623 torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
624 return cn.writeBuffer.Len() < 1<<16 // 64KiB
627 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
628 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
629 postedKeepalives.Add(1)
631 if cn.writeBuffer.Len() == 0 {
632 // TODO: Minimize wakeups....
637 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
639 n, err := cn.w.Write(frontBuf.Bytes())
642 lastWrite = time.Now()
643 keepAliveTimer.Reset(keepAliveTimeout)
648 if n != frontBuf.Len() {
655 func (cn *connection) Have(piece pieceIndex) {
656 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
661 Index: pp.Integer(piece),
663 cn.sentHaves.Add(bitmap.BitIndex(piece))
666 func (cn *connection) PostBitfield() {
667 if cn.sentHaves.Len() != 0 {
668 panic("bitfield must be first have-related message sent")
670 if !cn.t.haveAnyPieces() {
675 Bitfield: cn.t.bitfield(),
677 cn.sentHaves = cn.t.completedPieces.Copy()
680 func (cn *connection) updateRequests() {
681 // log.Print("update requests")
685 // Emits the indices in the Bitmaps bms in order, never repeating any index.
686 // skip is mutated during execution, and its initial values will never be
688 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
689 return func(cb iter.Callback) {
690 for _, bm := range bms {
691 if !iter.All(func(i interface{}) bool {
694 }, bitmap.Sub(bm, *skip).Iter) {
701 func (cn *connection) iterUnbiasedPieceRequestOrder(f func(piece pieceIndex) bool) bool {
702 now, readahead := cn.t.readerPiecePriorities()
703 var skip bitmap.Bitmap
704 if !cn.peerSentHaveAll {
705 // Pieces to skip include pieces the peer doesn't have.
706 skip = bitmap.Flip(cn.peerPieces, 0, bitmap.BitIndex(cn.t.numPieces()))
708 // And pieces that we already have.
709 skip.Union(cn.t.completedPieces)
710 skip.Union(cn.t.piecesQueuedForHash)
711 // Return an iterator over the different priority classes, minus the skip
714 func(_piece interface{}) bool {
715 i := _piece.(bitmap.BitIndex)
716 if cn.t.hashingPiece(pieceIndex(i)) {
719 return f(pieceIndex(i))
721 iterBitmapsDistinct(&skip, now, readahead),
722 func(cb iter.Callback) {
723 cn.t.pendingPieces.IterTyped(func(piece int) bool {
724 if skip.Contains(piece) {
735 // The connection should download highest priority pieces first, without any
736 // inclination toward avoiding wastage. Generally we might do this if there's
737 // a single connection, or this is the fastest connection, and we have active
738 // readers that signal an ordering preference. It's conceivable that the best
739 // connection should do this, since it's least likely to waste our time if
740 // assigned to the highest priority pieces, and assigning more than one this
741 // role would cause significant wasted bandwidth.
742 func (cn *connection) shouldRequestWithoutBias() bool {
743 if cn.t.requestStrategy != 2 {
746 if len(cn.t.readers) == 0 {
749 if len(cn.t.conns) == 1 {
752 if cn == cn.t.fastestConn {
758 func (cn *connection) iterPendingPieces(f func(pieceIndex) bool) bool {
759 if !cn.t.haveInfo() {
762 if cn.t.requestStrategy == 3 {
763 return cn.iterUnbiasedPieceRequestOrder(f)
765 if cn.shouldRequestWithoutBias() {
766 return cn.iterUnbiasedPieceRequestOrder(f)
768 return cn.pieceRequestOrder.IterTyped(func(i int) bool {
769 return f(pieceIndex(i))
774 func (cn *connection) iterPendingPiecesUntyped(f iter.Callback) {
775 cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
778 func (cn *connection) iterPendingRequests(piece pieceIndex, f func(request) bool) bool {
779 return iterUndirtiedChunks(piece, cn.t, func(cs chunkSpec) bool {
780 r := request{pp.Integer(piece), cs}
781 if cn.t.requestStrategy == 3 {
782 if _, ok := cn.t.lastRequested[r]; ok {
783 // This piece has been requested on another connection, and
784 // the duplicate request timer is still running.
792 func iterUndirtiedChunks(piece pieceIndex, t *Torrent, f func(chunkSpec) bool) bool {
793 p := &t.pieces[piece]
794 if t.requestStrategy == 3 {
795 for i := pp.Integer(0); i < p.numChunks(); i++ {
796 if !p.dirtyChunks.Get(bitmap.BitIndex(i)) {
797 if !f(t.chunkIndexSpec(i, piece)) {
804 chunkIndices := t.pieces[piece].undirtiedChunkIndices()
805 return iter.ForPerm(chunkIndices.Len(), func(i int) bool {
806 ci, err := chunkIndices.RB.Select(uint32(i))
810 return f(t.chunkIndexSpec(pp.Integer(ci), piece))
814 // check callers updaterequests
815 func (cn *connection) stopRequestingPiece(piece pieceIndex) bool {
816 return cn.pieceRequestOrder.Remove(bitmap.BitIndex(piece))
819 // This is distinct from Torrent piece priority, which is the user's
820 // preference. Connection piece priority is specific to a connection and is
821 // used to pseudorandomly avoid connections always requesting the same pieces
822 // and thus wasting effort.
823 func (cn *connection) updatePiecePriority(piece pieceIndex) bool {
824 tpp := cn.t.piecePriority(piece)
825 if !cn.PeerHasPiece(piece) {
826 tpp = PiecePriorityNone
828 if tpp == PiecePriorityNone {
829 return cn.stopRequestingPiece(piece)
831 prio := cn.getPieceInclination()[piece]
832 switch cn.t.requestStrategy {
835 case PiecePriorityNormal:
836 case PiecePriorityReadahead:
837 prio -= int(cn.t.numPieces())
838 case PiecePriorityNext, PiecePriorityNow:
839 prio -= 2 * int(cn.t.numPieces())
843 prio += int(piece / 3)
846 return cn.pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
849 func (cn *connection) getPieceInclination() []int {
850 if cn.pieceInclination == nil {
851 cn.pieceInclination = cn.t.getConnPieceInclination()
853 return cn.pieceInclination
856 func (cn *connection) discardPieceInclination() {
857 if cn.pieceInclination == nil {
860 cn.t.putPieceInclination(cn.pieceInclination)
861 cn.pieceInclination = nil
864 func (cn *connection) peerPiecesChanged() {
866 prioritiesChanged := false
867 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
868 if cn.updatePiecePriority(i) {
869 prioritiesChanged = true
872 if prioritiesChanged {
878 func (cn *connection) raisePeerMinPieces(newMin pieceIndex) {
879 if newMin > cn.peerMinPieces {
880 cn.peerMinPieces = newMin
884 func (cn *connection) peerSentHave(piece pieceIndex) error {
885 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
886 return errors.New("invalid piece")
888 if cn.PeerHasPiece(piece) {
891 cn.raisePeerMinPieces(piece + 1)
892 cn.peerPieces.Set(bitmap.BitIndex(piece), true)
893 if cn.updatePiecePriority(piece) {
899 func (cn *connection) peerSentBitfield(bf []bool) error {
900 cn.peerSentHaveAll = false
902 panic("expected bitfield length divisible by 8")
904 // We know that the last byte means that at most the last 7 bits are
906 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
907 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
908 // Ignore known excess pieces.
909 bf = bf[:cn.t.numPieces()]
911 for i, have := range bf {
913 cn.raisePeerMinPieces(pieceIndex(i) + 1)
915 cn.peerPieces.Set(i, have)
917 cn.peerPiecesChanged()
921 func (cn *connection) onPeerSentHaveAll() error {
922 cn.peerSentHaveAll = true
923 cn.peerPieces.Clear()
924 cn.peerPiecesChanged()
928 func (cn *connection) peerSentHaveNone() error {
929 cn.peerPieces.Clear()
930 cn.peerSentHaveAll = false
931 cn.peerPiecesChanged()
935 func (c *connection) requestPendingMetadata() {
939 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
940 // Peer doesn't support this.
943 // Request metadata pieces that we don't have in a random order.
945 for index := 0; index < c.t.metadataPieceCount(); index++ {
946 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
947 pending = append(pending, index)
950 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
951 for _, i := range pending {
952 c.requestMetadataPiece(i)
956 func (cn *connection) wroteMsg(msg *pp.Message) {
957 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
958 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
961 func (cn *connection) readMsg(msg *pp.Message) {
962 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
965 // After handshake, we know what Torrent and Client stats to include for a
967 func (cn *connection) postHandshakeStats(f func(*ConnStats)) {
973 // All ConnStats that include this connection. Some objects are not known
974 // until the handshake is complete, after which it's expected to reconcile the
976 func (cn *connection) allStats(f func(*ConnStats)) {
978 if cn.reconciledHandshakeStats {
979 cn.postHandshakeStats(f)
983 func (cn *connection) wroteBytes(n int64) {
984 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
987 func (cn *connection) readBytes(n int64) {
988 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
991 // Returns whether the connection could be useful to us. We're seeding and
992 // they want data, we don't have metainfo and they can provide it, etc.
993 func (c *connection) useful() bool {
995 if c.closed.IsSet() {
999 return c.supportsExtension("ut_metadata")
1001 if t.seeding() && c.PeerInterested {
1004 if c.peerHasWantedPieces() {
1010 func (c *connection) lastHelpful() (ret time.Time) {
1011 ret = c.lastUsefulChunkReceived
1012 if c.t.seeding() && c.lastChunkSent.After(ret) {
1013 ret = c.lastChunkSent
1018 func (c *connection) fastEnabled() bool {
1019 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.extensionBytes.SupportsFast()
1022 func (c *connection) reject(r request) {
1023 if !c.fastEnabled() {
1024 panic("fast not enabled")
1026 c.Post(r.ToMsg(pp.Reject))
1027 delete(c.PeerRequests, r)
1030 func (c *connection) onReadRequest(r request) error {
1031 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
1032 if _, ok := c.PeerRequests[r]; ok {
1033 torrent.Add("duplicate requests received", 1)
1037 torrent.Add("requests received while choking", 1)
1038 if c.fastEnabled() {
1039 torrent.Add("requests rejected while choking", 1)
1044 if len(c.PeerRequests) >= maxRequests {
1045 torrent.Add("requests received while queue full", 1)
1046 if c.fastEnabled() {
1049 // BEP 6 says we may close here if we choose.
1052 if !c.t.havePiece(pieceIndex(r.Index)) {
1053 // This isn't necessarily them screwing up. We can drop pieces
1054 // from our storage, and can't communicate this to peers
1055 // except by reconnecting.
1056 requestsReceivedForMissingPieces.Add(1)
1057 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1059 // Check this after we know we have the piece, so that the piece length will be known.
1060 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1061 torrent.Add("bad requests received", 1)
1062 return errors.New("bad request")
1064 if c.PeerRequests == nil {
1065 c.PeerRequests = make(map[request]struct{}, maxRequests)
1067 c.PeerRequests[r] = struct{}{}
1072 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1073 // exit. Returning will end the connection.
1074 func (c *connection) mainReadLoop() (err error) {
1077 torrent.Add("connection.mainReadLoop returned with error", 1)
1079 torrent.Add("connection.mainReadLoop returned with no error", 1)
1085 decoder := pp.Decoder{
1086 R: bufio.NewReaderSize(c.r, 1<<17),
1087 MaxLength: 256 * 1024,
1095 err = decoder.Decode(&msg)
1097 if t.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1104 c.lastMessageReceived = time.Now()
1106 receivedKeepalives.Add(1)
1109 messageTypesReceived.Add(msg.Type.String(), 1)
1110 if msg.Type.FastExtension() && !c.fastEnabled() {
1111 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1116 c.deleteAllRequests()
1117 // We can then reset our interest.
1119 c.updateExpectingChunks()
1121 c.PeerChoked = false
1123 c.updateExpectingChunks()
1125 c.PeerInterested = true
1127 case pp.NotInterested:
1128 c.PeerInterested = false
1129 // We don't clear their requests since it isn't clear in the spec.
1130 // We'll probably choke them for this, which will clear them if
1131 // appropriate, and is clearly specified.
1133 err = c.peerSentHave(pieceIndex(msg.Index))
1135 err = c.peerSentBitfield(msg.Bitfield)
1137 r := newRequestFromMessage(&msg)
1138 err = c.onReadRequest(r)
1140 err = c.receiveChunk(&msg)
1141 if len(msg.Piece) == int(t.chunkSize) {
1142 t.chunkPool.Put(&msg.Piece)
1145 err = fmt.Errorf("receiving chunk: %s", err)
1148 req := newRequestFromMessage(&msg)
1149 c.onPeerSentCancel(req)
1151 pingAddr := net.UDPAddr{
1152 IP: c.remoteAddr.IP,
1153 Port: int(c.remoteAddr.Port),
1156 pingAddr.Port = int(msg.Port)
1158 cl.eachDhtServer(func(s *dht.Server) {
1159 go s.Ping(&pingAddr, nil)
1162 torrent.Add("suggests received", 1)
1163 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index, debugLogValue).Log(c.t.logger)
1166 err = c.onPeerSentHaveAll()
1168 err = c.peerSentHaveNone()
1170 c.deleteRequest(newRequestFromMessage(&msg))
1171 delete(c.validReceiveChunks, newRequestFromMessage(&msg))
1172 case pp.AllowedFast:
1173 torrent.Add("allowed fasts received", 1)
1174 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c, debugLogValue).Log(c.t.logger)
1175 c.peerAllowedFast.Add(int(msg.Index))
1178 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1180 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1188 func (c *connection) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1190 // TODO: Should we still do this?
1192 // These clients use their own extension IDs for outgoing message
1193 // types, which is incorrect.
1194 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1202 case pp.HandshakeExtendedID:
1203 var d pp.ExtendedHandshakeMessage
1204 if err := bencode.Unmarshal(payload, &d); err != nil {
1205 c.t.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1206 return errors.Wrap(err, "unmarshalling extended handshake payload")
1209 c.PeerMaxRequests = d.Reqq
1211 c.PeerClientName = d.V
1212 if c.PeerExtensionIDs == nil {
1213 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1215 for name, id := range d.M {
1216 if _, ok := c.PeerExtensionIDs[name]; !ok {
1217 torrent.Add(fmt.Sprintf("peers supporting extension %q", name), 1)
1219 c.PeerExtensionIDs[name] = id
1221 if d.MetadataSize != 0 {
1222 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1223 return errors.Wrapf(err, "setting metadata size to %d", d.MetadataSize)
1226 c.requestPendingMetadata()
1228 case metadataExtendedId:
1229 err := cl.gotMetadataExtensionMsg(payload, t, c)
1231 return fmt.Errorf("handling metadata extension message: %w", err)
1235 if cl.config.DisablePEX {
1236 // TODO: Maybe close the connection. Check that we're not
1237 // advertising that we support PEX if it's disabled.
1240 var pexMsg pp.PexMsg
1241 err := bencode.Unmarshal(payload, &pexMsg)
1243 return fmt.Errorf("error unmarshalling PEX message: %s", err)
1245 torrent.Add("pex added6 peers received", int64(len(pexMsg.Added6)))
1247 peers.AppendFromPex(pexMsg.Added6, pexMsg.Added6Flags)
1248 peers.AppendFromPex(pexMsg.Added, pexMsg.AddedFlags)
1252 return fmt.Errorf("unexpected extended message ID: %v", id)
1256 // Set both the Reader and Writer for the connection from a single ReadWriter.
1257 func (cn *connection) setRW(rw io.ReadWriter) {
1262 // Returns the Reader and Writer as a combined ReadWriter.
1263 func (cn *connection) rw() io.ReadWriter {
1270 // Handle a received chunk from a peer.
1271 func (c *connection) receiveChunk(msg *pp.Message) error {
1274 torrent.Add("chunks received", 1)
1276 req := newRequestFromMessage(msg)
1279 torrent.Add("chunks received while choked", 1)
1282 if _, ok := c.validReceiveChunks[req]; !ok {
1283 torrent.Add("chunks received unexpected", 1)
1284 return errors.New("received unexpected chunk")
1286 delete(c.validReceiveChunks, req)
1288 if c.PeerChoked && c.peerAllowedFast.Get(int(req.Index)) {
1289 torrent.Add("chunks received due to allowed fast", 1)
1292 // Request has been satisfied.
1293 if c.deleteRequest(req) {
1294 if c.expectingChunks() {
1295 c.chunksReceivedWhileExpecting++
1298 torrent.Add("chunks received unwanted", 1)
1301 // Do we actually want this chunk?
1302 if t.haveChunk(req) {
1303 torrent.Add("chunks received wasted", 1)
1304 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1308 piece := &t.pieces[req.Index]
1310 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1311 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1312 c.lastUsefulChunkReceived = time.Now()
1313 // if t.fastestConn != c {
1314 // log.Printf("setting fastest connection %p", c)
1318 // Need to record that it hasn't been written yet, before we attempt to do
1319 // anything with it.
1320 piece.incrementPendingWrites()
1321 // Record that we have the chunk, so we aren't trying to download it while
1322 // waiting for it to be written to storage.
1323 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1325 // Cancel pending requests for this chunk.
1326 for c := range t.conns {
1330 err := func() error {
1333 concurrentChunkWrites.Add(1)
1334 defer concurrentChunkWrites.Add(-1)
1335 // Write the chunk out. Note that the upper bound on chunk writing
1336 // concurrency will be the number of connections. We write inline with
1337 // receiving the chunk (with this lock dance), because we want to
1338 // handle errors synchronously and I haven't thought of a nice way to
1339 // defer any concurrency to the storage and have that notify the
1340 // client of errors. TODO: Do that instead.
1341 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1344 piece.decrementPendingWrites()
1347 panic(fmt.Sprintf("error writing chunk: %v", err))
1349 t.updatePieceCompletion(pieceIndex(msg.Index))
1353 // It's important that the piece is potentially queued before we check if
1354 // the piece is still wanted, because if it is queued, it won't be wanted.
1355 if t.pieceAllDirty(pieceIndex(req.Index)) {
1356 t.queuePieceCheck(pieceIndex(req.Index))
1357 t.pendAllChunkSpecs(pieceIndex(req.Index))
1360 c.onDirtiedPiece(pieceIndex(req.Index))
1362 cl.event.Broadcast()
1363 t.publishPieceChange(pieceIndex(req.Index))
1368 func (c *connection) onDirtiedPiece(piece pieceIndex) {
1369 if c.peerTouchedPieces == nil {
1370 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1372 c.peerTouchedPieces[piece] = struct{}{}
1373 ds := &c.t.pieces[piece].dirtiers
1375 *ds = make(map[*connection]struct{})
1377 (*ds)[c] = struct{}{}
1380 func (c *connection) uploadAllowed() bool {
1381 if c.t.cl.config.NoUpload {
1387 if !c.peerHasWantedPieces() {
1390 // Don't upload more than 100 KiB more than we download.
1391 if c.stats.BytesWrittenData.Int64() >= c.stats.BytesReadData.Int64()+100<<10 {
1397 func (c *connection) setRetryUploadTimer(delay time.Duration) {
1398 if c.uploadTimer == nil {
1399 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1401 c.uploadTimer.Reset(delay)
1405 // Also handles choking and unchoking of the remote peer.
1406 func (c *connection) upload(msg func(pp.Message) bool) bool {
1407 // Breaking or completing this loop means we don't want to upload to the
1408 // peer anymore, and we choke them.
1410 for c.uploadAllowed() {
1411 // We want to upload to the peer.
1412 if !c.Unchoke(msg) {
1415 for r := range c.PeerRequests {
1416 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1418 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1420 delay := res.Delay()
1423 c.setRetryUploadTimer(delay)
1424 // Hard to say what to return here.
1427 more, err := c.sendChunk(r, msg)
1429 i := pieceIndex(r.Index)
1430 if c.t.pieceComplete(i) {
1431 c.t.updatePieceCompletion(i)
1432 if !c.t.pieceComplete(i) {
1433 // We had the piece, but not anymore.
1437 log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
1438 // If we failed to send a chunk, choke the peer to ensure they
1439 // flush all their requests. We've probably dropped a piece,
1440 // but there's no way to communicate this to the peer. If they
1441 // ask for it again, we'll kick them to allow us to send them
1442 // an updated bitfield.
1445 delete(c.PeerRequests, r)
1456 func (cn *connection) Drop() {
1457 cn.t.dropConnection(cn)
1460 func (cn *connection) netGoodPiecesDirtied() int64 {
1461 return cn.stats.PiecesDirtiedGood.Int64() - cn.stats.PiecesDirtiedBad.Int64()
1464 func (c *connection) peerHasWantedPieces() bool {
1465 return !c.pieceRequestOrder.IsEmpty()
1468 func (c *connection) numLocalRequests() int {
1469 return len(c.requests)
1472 func (c *connection) deleteRequest(r request) bool {
1473 if _, ok := c.requests[r]; !ok {
1476 delete(c.requests, r)
1477 c.updateExpectingChunks()
1478 if t, ok := c.t.lastRequested[r]; ok {
1480 delete(c.t.lastRequested, r)
1482 pr := c.t.pendingRequests
1492 for _c := range c.t.conns {
1493 if !_c.Interested && _c != c && c.PeerHasPiece(pieceIndex(r.Index)) {
1500 func (c *connection) deleteAllRequests() {
1501 for r := range c.requests {
1504 if len(c.requests) != 0 {
1505 panic(len(c.requests))
1507 // for c := range c.t.conns {
1512 func (c *connection) tickleWriter() {
1513 c.writerCond.Broadcast()
1516 func (c *connection) postCancel(r request) bool {
1517 if !c.deleteRequest(r) {
1520 c.Post(makeCancelMessage(r))
1524 func (c *connection) sendChunk(r request, msg func(pp.Message) bool) (more bool, err error) {
1525 // Count the chunk being sent, even if it isn't.
1526 b := make([]byte, r.Length)
1527 p := c.t.info.Piece(int(r.Index))
1528 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1531 panic("expected error")
1534 } else if err == io.EOF {
1537 more = msg(pp.Message{
1543 c.lastChunkSent = time.Now()
1547 func (c *connection) setTorrent(t *Torrent) {
1549 panic("connection already associated with a torrent")
1552 c.logger.Printf("torrent=%v", t)
1553 t.reconcileHandshakeStats(c)
1556 func (c *connection) peerPriority() peerPriority {
1557 return bep40PriorityIgnoreError(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1560 func (c *connection) remoteIp() net.IP {
1561 return c.remoteAddr.IP
1564 func (c *connection) remoteIpPort() IpPort {
1568 func (c *connection) String() string {
1569 return fmt.Sprintf("connection %p", c)