]> Sergey Matveev's repositories - btrtrc.git/blob - torrent.go
e2afb3e3f2513c495018234b6edb3f810c9118c1
[btrtrc.git] / torrent.go
1 package torrent
2
3 import (
4         "bytes"
5         "container/heap"
6         "context"
7         "crypto/sha1"
8         "errors"
9         "fmt"
10         "github.com/anacrolix/torrent/merkle"
11         infohash_v2 "github.com/anacrolix/torrent/types/infohash-v2"
12         "io"
13         "math/rand"
14         "net/netip"
15         "net/url"
16         "sort"
17         "strings"
18         "text/tabwriter"
19         "time"
20         "unsafe"
21
22         "github.com/RoaringBitmap/roaring"
23         "github.com/anacrolix/chansync"
24         "github.com/anacrolix/chansync/events"
25         "github.com/anacrolix/dht/v2"
26         . "github.com/anacrolix/generics"
27         g "github.com/anacrolix/generics"
28         "github.com/anacrolix/log"
29         "github.com/anacrolix/missinggo/slices"
30         "github.com/anacrolix/missinggo/v2"
31         "github.com/anacrolix/missinggo/v2/bitmap"
32         "github.com/anacrolix/missinggo/v2/pubsub"
33         "github.com/anacrolix/multiless"
34         "github.com/anacrolix/sync"
35         "github.com/pion/datachannel"
36         "golang.org/x/exp/maps"
37
38         "github.com/anacrolix/torrent/bencode"
39         "github.com/anacrolix/torrent/internal/check"
40         "github.com/anacrolix/torrent/internal/nestedmaps"
41         "github.com/anacrolix/torrent/metainfo"
42         pp "github.com/anacrolix/torrent/peer_protocol"
43         utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
44         request_strategy "github.com/anacrolix/torrent/request-strategy"
45         "github.com/anacrolix/torrent/storage"
46         "github.com/anacrolix/torrent/tracker"
47         typedRoaring "github.com/anacrolix/torrent/typed-roaring"
48         "github.com/anacrolix/torrent/webseed"
49         "github.com/anacrolix/torrent/webtorrent"
50 )
51
52 // Maintains state of torrent within a Client. Many methods should not be called before the info is
53 // available, see .Info and .GotInfo.
54 type Torrent struct {
55         // Torrent-level aggregate statistics. First in struct to ensure 64-bit
56         // alignment. See #262.
57         stats  ConnStats
58         cl     *Client
59         logger log.Logger
60
61         networkingEnabled      chansync.Flag
62         dataDownloadDisallowed chansync.Flag
63         dataUploadDisallowed   bool
64         userOnWriteChunkErr    func(error)
65
66         closed  chansync.SetOnce
67         onClose []func()
68
69         infoHash   metainfo.Hash
70         infoHashV2 g.Option[infohash_v2.T]
71
72         pieces []Piece
73
74         // The order pieces are requested if there's no stronger reason like availability or priority.
75         pieceRequestOrder []int
76         // Values are the piece indices that changed.
77         pieceStateChanges pubsub.PubSub[PieceStateChange]
78         // The size of chunks to request from peers over the wire. This is
79         // normally 16KiB by convention these days.
80         chunkSize pp.Integer
81         chunkPool sync.Pool
82         // Total length of the torrent in bytes. Stored because it's not O(1) to
83         // get this from the info dict.
84         _length Option[int64]
85
86         // The storage to open when the info dict becomes available.
87         storageOpener *storage.Client
88         // Storage for torrent data.
89         storage *storage.Torrent
90         // Read-locked for using storage, and write-locked for Closing.
91         storageLock sync.RWMutex
92
93         // TODO: Only announce stuff is used?
94         metainfo metainfo.MetaInfo
95
96         // The info dict. nil if we don't have it (yet).
97         info  *metainfo.Info
98         files *[]*File
99
100         _chunksPerRegularPiece chunkIndexType
101
102         webSeeds map[string]*Peer
103         // Active peer connections, running message stream loops. TODO: Make this
104         // open (not-closed) connections only.
105         conns               map[*PeerConn]struct{}
106         maxEstablishedConns int
107         // Set of addrs to which we're attempting to connect. Connections are
108         // half-open until all handshakes are completed.
109         halfOpen map[string]map[outgoingConnAttemptKey]*PeerInfo
110
111         // Reserve of peers to connect to. A peer can be both here and in the
112         // active connections if were told about the peer after connecting with
113         // them. That encourages us to reconnect to peers that are well known in
114         // the swarm.
115         peers prioritizedPeers
116         // Whether we want to know more peers.
117         wantPeersEvent missinggo.Event
118         // An announcer for each tracker URL.
119         trackerAnnouncers map[string]torrentTrackerAnnouncer
120         // How many times we've initiated a DHT announce. TODO: Move into stats.
121         numDHTAnnounces int
122
123         // Name used if the info name isn't available. Should be cleared when the
124         // Info does become available.
125         nameMu      sync.RWMutex
126         displayName string
127
128         // The bencoded bytes of the info dict. This is actively manipulated if
129         // the info bytes aren't initially available, and we try to fetch them
130         // from peers.
131         metadataBytes []byte
132         // Each element corresponds to the 16KiB metadata pieces. If true, we have
133         // received that piece.
134         metadataCompletedChunks []bool
135         metadataChanged         sync.Cond
136
137         // Closed when .Info is obtained.
138         gotMetainfoC chan struct{}
139
140         readers                map[*reader]struct{}
141         _readerNowPieces       bitmap.Bitmap
142         _readerReadaheadPieces bitmap.Bitmap
143
144         // A cache of pieces we need to get. Calculated from various piece and
145         // file priorities and completion states elsewhere.
146         _pendingPieces roaring.Bitmap
147         // A cache of completed piece indices.
148         _completedPieces roaring.Bitmap
149         // Pieces that need to be hashed.
150         piecesQueuedForHash       bitmap.Bitmap
151         activePieceHashes         int
152         initialPieceCheckDisabled bool
153
154         connsWithAllPieces map[*Peer]struct{}
155
156         requestState map[RequestIndex]requestState
157         // Chunks we've written to since the corresponding piece was last checked.
158         dirtyChunks typedRoaring.Bitmap[RequestIndex]
159
160         pex pexState
161
162         // Is On when all pieces are complete.
163         Complete chansync.Flag
164
165         // Torrent sources in use keyed by the source string.
166         activeSources sync.Map
167         sourcesLogger log.Logger
168
169         smartBanCache smartBanCache
170
171         // Large allocations reused between request state updates.
172         requestPieceStates []request_strategy.PieceRequestOrderState
173         requestIndexes     []RequestIndex
174
175         disableTriggers bool
176 }
177
178 type outgoingConnAttemptKey = *PeerInfo
179
180 func (t *Torrent) length() int64 {
181         return t._length.Value
182 }
183
184 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
185         // This could be done with roaring.BitSliceIndexing.
186         t.iterPeers(func(peer *Peer) {
187                 if _, ok := t.connsWithAllPieces[peer]; ok {
188                         return
189                 }
190                 if peer.peerHasPiece(i) {
191                         count++
192                 }
193         })
194         return
195 }
196
197 func (t *Torrent) decPieceAvailability(i pieceIndex) {
198         if !t.haveInfo() {
199                 return
200         }
201         p := t.piece(i)
202         if p.relativeAvailability <= 0 {
203                 panic(p.relativeAvailability)
204         }
205         p.relativeAvailability--
206         t.updatePieceRequestOrderPiece(i)
207 }
208
209 func (t *Torrent) incPieceAvailability(i pieceIndex) {
210         // If we don't the info, this should be reconciled when we do.
211         if t.haveInfo() {
212                 p := t.piece(i)
213                 p.relativeAvailability++
214                 t.updatePieceRequestOrderPiece(i)
215         }
216 }
217
218 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
219         return t._readerNowPieces
220 }
221
222 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
223         return t._readerReadaheadPieces
224 }
225
226 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
227         return !t.wantPieceIndex(i)
228 }
229
230 // Returns a channel that is closed when the Torrent is closed.
231 func (t *Torrent) Closed() events.Done {
232         return t.closed.Done()
233 }
234
235 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
236 // pending, and half-open peers.
237 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
238         // Add pending peers to the list
239         t.peers.Each(func(peer PeerInfo) {
240                 ks = append(ks, peer)
241         })
242
243         // Add half-open peers to the list
244         for _, attempts := range t.halfOpen {
245                 for _, peer := range attempts {
246                         ks = append(ks, *peer)
247                 }
248         }
249
250         // Add active peers to the list
251         t.cl.rLock()
252         defer t.cl.rUnlock()
253         for conn := range t.conns {
254                 ks = append(ks, PeerInfo{
255                         Id:     conn.PeerID,
256                         Addr:   conn.RemoteAddr,
257                         Source: conn.Discovery,
258                         // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
259                         // > But if we're not connected to them with an encrypted connection, I couldn't say
260                         // > what's appropriate. We can carry forward the SupportsEncryption value as we
261                         // > received it from trackers/DHT/PEX, or just use the encryption state for the
262                         // > connection. It's probably easiest to do the latter for now.
263                         // https://github.com/anacrolix/torrent/pull/188
264                         SupportsEncryption: conn.headerEncrypted,
265                 })
266         }
267
268         return
269 }
270
271 func (t *Torrent) setChunkSize(size pp.Integer) {
272         t.chunkSize = size
273         t.chunkPool = sync.Pool{
274                 New: func() interface{} {
275                         b := make([]byte, size)
276                         return &b
277                 },
278         }
279 }
280
281 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
282         return t._completedPieces.Contains(bitmap.BitIndex(piece))
283 }
284
285 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
286         if t.storage == nil {
287                 return storage.Completion{Complete: false, Ok: true}
288         }
289         return t.pieces[piece].Storage().Completion()
290 }
291
292 // There's a connection to that address already.
293 func (t *Torrent) addrActive(addr string) bool {
294         if _, ok := t.halfOpen[addr]; ok {
295                 return true
296         }
297         for c := range t.conns {
298                 ra := c.RemoteAddr
299                 if ra.String() == addr {
300                         return true
301                 }
302         }
303         return false
304 }
305
306 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
307         return t.appendConns(ret, func(conn *PeerConn) bool {
308                 return !conn.closed.IsSet()
309         })
310 }
311
312 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
313         for c := range t.conns {
314                 if f(c) {
315                         ret = append(ret, c)
316                 }
317         }
318         return ret
319 }
320
321 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
322         cl := t.cl
323         torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
324         if t.closed.IsSet() {
325                 return false
326         }
327         if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
328                 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
329                         torrent.Add("peers not added because of bad addr", 1)
330                         // cl.logger.Printf("peers not added because of bad addr: %v", p)
331                         return false
332                 }
333         }
334         if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
335                 torrent.Add("peers replaced", 1)
336                 if !replaced.equal(p) {
337                         t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
338                         added = true
339                 }
340         } else {
341                 added = true
342         }
343         t.openNewConns()
344         for t.peers.Len() > cl.config.TorrentPeersHighWater {
345                 _, ok := t.peers.DeleteMin()
346                 if ok {
347                         torrent.Add("excess reserve peers discarded", 1)
348                 }
349         }
350         return
351 }
352
353 func (t *Torrent) invalidateMetadata() {
354         for i := 0; i < len(t.metadataCompletedChunks); i++ {
355                 t.metadataCompletedChunks[i] = false
356         }
357         t.nameMu.Lock()
358         t.gotMetainfoC = make(chan struct{})
359         t.info = nil
360         t.nameMu.Unlock()
361 }
362
363 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
364         if t.haveInfo() {
365                 return
366         }
367         if index >= len(t.metadataCompletedChunks) {
368                 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
369                 return
370         }
371         copy(t.metadataBytes[(1<<14)*index:], data)
372         t.metadataCompletedChunks[index] = true
373 }
374
375 func (t *Torrent) metadataPieceCount() int {
376         return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
377 }
378
379 func (t *Torrent) haveMetadataPiece(piece int) bool {
380         if t.haveInfo() {
381                 return (1<<14)*piece < len(t.metadataBytes)
382         } else {
383                 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
384         }
385 }
386
387 func (t *Torrent) metadataSize() int {
388         return len(t.metadataBytes)
389 }
390
391 func (t *Torrent) makePieces() {
392         t.pieces = make([]Piece, t.info.NumPieces())
393         for i := range t.pieces {
394                 piece := &t.pieces[i]
395                 piece.t = t
396                 piece.index = i
397                 piece.noPendingWrites.L = &piece.pendingWritesMutex
398                 if t.info.HasV1() {
399                         piece.hash = (*metainfo.Hash)(unsafe.Pointer(
400                                 unsafe.SliceData(t.info.Pieces[i*sha1.Size : (i+1)*sha1.Size])))
401                 }
402                 files := *t.files
403                 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
404                 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
405                 piece.files = files[beginFile:endFile]
406                 if t.info.FilesArePieceAligned() {
407                         numFiles := len(piece.files)
408                         if numFiles != 1 {
409                                 panic(fmt.Sprintf("%v:%v", beginFile, endFile))
410                         }
411                 }
412         }
413 }
414
415 func (t *Torrent) AddPieceLayers(layers map[string]string) (err error) {
416         if layers == nil {
417                 return
418         }
419         for _, f := range *t.files {
420                 if !f.piecesRoot.Ok {
421                         err = fmt.Errorf("no piece root set for file %v", f)
422                         return
423                 }
424                 compactLayer, ok := layers[string(f.piecesRoot.Value[:])]
425                 if !ok {
426                         continue
427                 }
428                 var hashes [][32]byte
429                 hashes, err = merkle.CompactLayerToSliceHashes(compactLayer)
430                 if err != nil {
431                         err = fmt.Errorf("bad piece layers for file %q: %w", f, err)
432                         return
433                 }
434                 if len(hashes) != f.numPieces() {
435                         err = fmt.Errorf("file %q: got %v hashes expected %v", f, len(hashes), f.numPieces())
436                         return
437                 }
438                 for i := range f.numPieces() {
439                         p := t.piece(f.BeginPieceIndex() + i)
440                         p.hashV2.Set(hashes[i])
441                 }
442         }
443         return nil
444 }
445
446 // Returns the index of the first file containing the piece. files must be
447 // ordered by offset.
448 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
449         for i, f := range files {
450                 if f.offset+f.length > pieceOffset {
451                         return i
452                 }
453         }
454         return 0
455 }
456
457 // Returns the index after the last file containing the piece. files must be
458 // ordered by offset.
459 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
460         for i, f := range files {
461                 if f.offset >= pieceEndOffset {
462                         return i
463                 }
464         }
465         return len(files)
466 }
467
468 func (t *Torrent) cacheLength() {
469         var l int64
470         for _, f := range t.info.UpvertedFiles() {
471                 l += f.Length
472         }
473         t._length = Some(l)
474 }
475
476 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
477 // separately.
478 func (t *Torrent) setInfo(info *metainfo.Info) error {
479         if err := validateInfo(info); err != nil {
480                 return fmt.Errorf("bad info: %s", err)
481         }
482         if t.storageOpener != nil {
483                 var err error
484                 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
485                 if err != nil {
486                         return fmt.Errorf("error opening torrent storage: %s", err)
487                 }
488         }
489         t.nameMu.Lock()
490         t.info = info
491         t.nameMu.Unlock()
492         t._chunksPerRegularPiece = chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
493         t.updateComplete()
494         t.displayName = "" // Save a few bytes lol.
495         t.initFiles()
496         t.cacheLength()
497         t.makePieces()
498         return nil
499 }
500
501 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
502         return request_strategy.PieceRequestOrderKey{
503                 InfoHash: t.infoHash,
504                 Index:    i,
505         }
506 }
507
508 // This seems to be all the follow-up tasks after info is set, that can't fail.
509 func (t *Torrent) onSetInfo() {
510         t.pieceRequestOrder = rand.Perm(t.numPieces())
511         t.initPieceRequestOrder()
512         MakeSliceWithLength(&t.requestPieceStates, t.numPieces())
513         for i := range t.pieces {
514                 p := &t.pieces[i]
515                 // Need to add relativeAvailability before updating piece completion, as that may result in conns
516                 // being dropped.
517                 if p.relativeAvailability != 0 {
518                         panic(p.relativeAvailability)
519                 }
520                 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
521                 t.addRequestOrderPiece(i)
522                 t.updatePieceCompletion(i)
523                 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
524                         // t.logger.Printf("piece %s completion unknown, queueing check", p)
525                         t.queuePieceCheck(i)
526                 }
527         }
528         t.cl.event.Broadcast()
529         close(t.gotMetainfoC)
530         t.updateWantPeersEvent()
531         t.requestState = make(map[RequestIndex]requestState)
532         t.tryCreateMorePieceHashers()
533         t.iterPeers(func(p *Peer) {
534                 p.onGotInfo(t.info)
535                 p.updateRequests("onSetInfo")
536         })
537 }
538
539 // Called when metadata for a torrent becomes available.
540 func (t *Torrent) setInfoBytesLocked(b []byte) error {
541         if metainfo.HashBytes(b) != t.infoHash {
542                 return errors.New("info bytes have wrong hash")
543         }
544         var info metainfo.Info
545         if err := bencode.Unmarshal(b, &info); err != nil {
546                 return fmt.Errorf("error unmarshalling info bytes: %s", err)
547         }
548         t.metadataBytes = b
549         t.metadataCompletedChunks = nil
550         if t.info != nil {
551                 return nil
552         }
553         if err := t.setInfo(&info); err != nil {
554                 return err
555         }
556         t.onSetInfo()
557         return nil
558 }
559
560 func (t *Torrent) haveAllMetadataPieces() bool {
561         if t.haveInfo() {
562                 return true
563         }
564         if t.metadataCompletedChunks == nil {
565                 return false
566         }
567         for _, have := range t.metadataCompletedChunks {
568                 if !have {
569                         return false
570                 }
571         }
572         return true
573 }
574
575 // TODO: Propagate errors to disconnect peer.
576 func (t *Torrent) setMetadataSize(size int) (err error) {
577         if t.haveInfo() {
578                 // We already know the correct metadata size.
579                 return
580         }
581         if uint32(size) > maxMetadataSize {
582                 return log.WithLevel(log.Warning, errors.New("bad size"))
583         }
584         if len(t.metadataBytes) == size {
585                 return
586         }
587         t.metadataBytes = make([]byte, size)
588         t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
589         t.metadataChanged.Broadcast()
590         for c := range t.conns {
591                 c.requestPendingMetadata()
592         }
593         return
594 }
595
596 // The current working name for the torrent. Either the name in the info dict,
597 // or a display name given such as by the dn value in a magnet link, or "".
598 func (t *Torrent) name() string {
599         t.nameMu.RLock()
600         defer t.nameMu.RUnlock()
601         if t.haveInfo() {
602                 return t.info.BestName()
603         }
604         if t.displayName != "" {
605                 return t.displayName
606         }
607         return "infohash:" + t.infoHash.HexString()
608 }
609
610 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
611         p := &t.pieces[index]
612         ret.Priority = t.piecePriority(index)
613         ret.Completion = p.completion()
614         ret.QueuedForHash = p.queuedForHash()
615         ret.Hashing = p.hashing
616         ret.Checking = ret.QueuedForHash || ret.Hashing
617         ret.Marking = p.marking
618         if !ret.Complete && t.piecePartiallyDownloaded(index) {
619                 ret.Partial = true
620         }
621         return
622 }
623
624 func (t *Torrent) metadataPieceSize(piece int) int {
625         return metadataPieceSize(len(t.metadataBytes), piece)
626 }
627
628 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
629         return pp.Message{
630                 Type:       pp.Extended,
631                 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
632                 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
633                         Piece:     piece,
634                         TotalSize: len(t.metadataBytes),
635                         Type:      msgType,
636                 }), data...),
637         }
638 }
639
640 type pieceAvailabilityRun struct {
641         Count        pieceIndex
642         Availability int
643 }
644
645 func (me pieceAvailabilityRun) String() string {
646         return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
647 }
648
649 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
650         rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
651                 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
652         })
653         for i := range t.pieces {
654                 rle.Append(t.pieces[i].availability(), 1)
655         }
656         rle.Flush()
657         return
658 }
659
660 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
661         freqs = make([]int, t.numActivePeers()+1)
662         for i := range t.pieces {
663                 freqs[t.piece(i).availability()]++
664         }
665         return
666 }
667
668 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
669         rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
670                 ret = append(ret, PieceStateRun{
671                         PieceState: el.(PieceState),
672                         Length:     int(count),
673                 })
674         })
675         for index := range t.pieces {
676                 rle.Append(t.pieceState(pieceIndex(index)), 1)
677         }
678         rle.Flush()
679         return
680 }
681
682 // Produces a small string representing a PieceStateRun.
683 func (psr PieceStateRun) String() (ret string) {
684         ret = fmt.Sprintf("%d", psr.Length)
685         ret += func() string {
686                 switch psr.Priority {
687                 case PiecePriorityNext:
688                         return "N"
689                 case PiecePriorityNormal:
690                         return "."
691                 case PiecePriorityReadahead:
692                         return "R"
693                 case PiecePriorityNow:
694                         return "!"
695                 case PiecePriorityHigh:
696                         return "H"
697                 default:
698                         return ""
699                 }
700         }()
701         if psr.Hashing {
702                 ret += "H"
703         }
704         if psr.QueuedForHash {
705                 ret += "Q"
706         }
707         if psr.Marking {
708                 ret += "M"
709         }
710         if psr.Partial {
711                 ret += "P"
712         }
713         if psr.Complete {
714                 ret += "C"
715         }
716         if !psr.Ok {
717                 ret += "?"
718         }
719         return
720 }
721
722 func (t *Torrent) writeStatus(w io.Writer) {
723         fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
724         fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
725         if !t.haveInfo() {
726                 fmt.Fprintf(w, "Metadata have: ")
727                 for _, h := range t.metadataCompletedChunks {
728                         fmt.Fprintf(w, "%c", func() rune {
729                                 if h {
730                                         return 'H'
731                                 } else {
732                                         return '.'
733                                 }
734                         }())
735                 }
736                 fmt.Fprintln(w)
737         }
738         fmt.Fprintf(w, "Piece length: %s\n",
739                 func() string {
740                         if t.haveInfo() {
741                                 return fmt.Sprintf("%v (%v chunks)",
742                                         t.usualPieceSize(),
743                                         float64(t.usualPieceSize())/float64(t.chunkSize))
744                         } else {
745                                 return "no info"
746                         }
747                 }(),
748         )
749         if t.info != nil {
750                 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
751                 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
752                 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
753                 // availability frequencies instead.
754                 if false {
755                         fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
756                                 for _, run := range t.pieceAvailabilityRuns() {
757                                         ret = append(ret, run.String())
758                                 }
759                                 return
760                         }(), " "))
761                 }
762                 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
763                         func() (ret []string) {
764                                 for avail, freq := range t.pieceAvailabilityFrequencies() {
765                                         if freq == 0 {
766                                                 continue
767                                         }
768                                         ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
769                                 }
770                                 return
771                         }(),
772                         ", "))
773         }
774         fmt.Fprintf(w, "Reader Pieces:")
775         t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
776                 fmt.Fprintf(w, " %d:%d", begin, end)
777                 return true
778         })
779         fmt.Fprintln(w)
780
781         fmt.Fprintf(w, "Enabled trackers:\n")
782         func() {
783                 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
784                 fmt.Fprintf(tw, "    URL\tExtra\n")
785                 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
786                         lu := l.URL()
787                         ru := r.URL()
788                         var luns, runs url.URL = *lu, *ru
789                         luns.Scheme = ""
790                         runs.Scheme = ""
791                         var ml missinggo.MultiLess
792                         ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
793                         ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
794                         return ml.Less()
795                 }).([]torrentTrackerAnnouncer) {
796                         fmt.Fprintf(tw, "    %q\t%v\n", ta.URL(), ta.statusLine())
797                 }
798                 tw.Flush()
799         }()
800
801         fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
802
803         dumpStats(w, t.statsLocked())
804
805         fmt.Fprintf(w, "webseeds:\n")
806         t.writePeerStatuses(w, maps.Values(t.webSeeds))
807
808         peerConns := maps.Keys(t.conns)
809         // Peers without priorities first, then those with. I'm undecided about how to order peers
810         // without priorities.
811         sort.Slice(peerConns, func(li, ri int) bool {
812                 l := peerConns[li]
813                 r := peerConns[ri]
814                 ml := multiless.New()
815                 lpp := g.ResultFromTuple(l.peerPriority()).ToOption()
816                 rpp := g.ResultFromTuple(r.peerPriority()).ToOption()
817                 ml = ml.Bool(lpp.Ok, rpp.Ok)
818                 ml = ml.Uint32(rpp.Value, lpp.Value)
819                 return ml.Less()
820         })
821
822         fmt.Fprintf(w, "%v peer conns:\n", len(peerConns))
823         t.writePeerStatuses(w, g.SliceMap(peerConns, func(pc *PeerConn) *Peer {
824                 return &pc.Peer
825         }))
826 }
827
828 func (t *Torrent) writePeerStatuses(w io.Writer, peers []*Peer) {
829         var buf bytes.Buffer
830         for _, c := range peers {
831                 fmt.Fprintf(w, "- ")
832                 buf.Reset()
833                 c.writeStatus(&buf)
834                 w.Write(bytes.TrimRight(
835                         bytes.ReplaceAll(buf.Bytes(), []byte("\n"), []byte("\n  ")),
836                         " "))
837         }
838 }
839
840 func (t *Torrent) haveInfo() bool {
841         return t.info != nil
842 }
843
844 // Returns a run-time generated MetaInfo that includes the info bytes and
845 // announce-list as currently known to the client.
846 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
847         return metainfo.MetaInfo{
848                 CreationDate: time.Now().Unix(),
849                 Comment:      "dynamic metainfo from client",
850                 CreatedBy:    "go.torrent",
851                 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
852                 InfoBytes: func() []byte {
853                         if t.haveInfo() {
854                                 return t.metadataBytes
855                         } else {
856                                 return nil
857                         }
858                 }(),
859                 UrlList: func() []string {
860                         ret := make([]string, 0, len(t.webSeeds))
861                         for url := range t.webSeeds {
862                                 ret = append(ret, url)
863                         }
864                         return ret
865                 }(),
866         }
867 }
868
869 // Returns a count of bytes that are not complete in storage, and not pending being written to
870 // storage. This value is from the perspective of the download manager, and may not agree with the
871 // actual state in storage. If you want read data synchronously you should use a Reader. See
872 // https://github.com/anacrolix/torrent/issues/828.
873 func (t *Torrent) BytesMissing() (n int64) {
874         t.cl.rLock()
875         n = t.bytesMissingLocked()
876         t.cl.rUnlock()
877         return
878 }
879
880 func (t *Torrent) bytesMissingLocked() int64 {
881         return t.bytesLeft()
882 }
883
884 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
885         roaring.Flip(b, 0, end).Iterate(cb)
886 }
887
888 func (t *Torrent) bytesLeft() (left int64) {
889         iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
890                 p := t.piece(pieceIndex(x))
891                 left += int64(p.length() - p.numDirtyBytes())
892                 return true
893         })
894         return
895 }
896
897 // Bytes left to give in tracker announces.
898 func (t *Torrent) bytesLeftAnnounce() int64 {
899         if t.haveInfo() {
900                 return t.bytesLeft()
901         } else {
902                 return -1
903         }
904 }
905
906 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
907         if t.pieceComplete(piece) {
908                 return false
909         }
910         if t.pieceAllDirty(piece) {
911                 return false
912         }
913         return t.pieces[piece].hasDirtyChunks()
914 }
915
916 func (t *Torrent) usualPieceSize() int {
917         return int(t.info.PieceLength)
918 }
919
920 func (t *Torrent) numPieces() pieceIndex {
921         return t.info.NumPieces()
922 }
923
924 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
925         return pieceIndex(t._completedPieces.GetCardinality())
926 }
927
928 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
929         if !t.closed.Set() {
930                 err = errors.New("already closed")
931                 return
932         }
933         for _, f := range t.onClose {
934                 f()
935         }
936         if t.storage != nil {
937                 wg.Add(1)
938                 go func() {
939                         defer wg.Done()
940                         t.storageLock.Lock()
941                         defer t.storageLock.Unlock()
942                         if f := t.storage.Close; f != nil {
943                                 err1 := f()
944                                 if err1 != nil {
945                                         t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
946                                 }
947                         }
948                 }()
949         }
950         t.iterPeers(func(p *Peer) {
951                 p.close()
952         })
953         if t.storage != nil {
954                 t.deletePieceRequestOrder()
955         }
956         t.assertAllPiecesRelativeAvailabilityZero()
957         t.pex.Reset()
958         t.cl.event.Broadcast()
959         t.pieceStateChanges.Close()
960         t.updateWantPeersEvent()
961         return
962 }
963
964 func (t *Torrent) assertAllPiecesRelativeAvailabilityZero() {
965         for i := range t.pieces {
966                 p := t.piece(i)
967                 if p.relativeAvailability != 0 {
968                         panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
969                 }
970         }
971 }
972
973 func (t *Torrent) requestOffset(r Request) int64 {
974         return torrentRequestOffset(t.length(), int64(t.usualPieceSize()), r)
975 }
976
977 // Return the request that would include the given offset into the torrent data. Returns !ok if
978 // there is no such request.
979 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
980         return torrentOffsetRequest(t.length(), t.info.PieceLength, int64(t.chunkSize), off)
981 }
982
983 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
984         //defer perf.ScopeTimerErr(&err)()
985         n, err := t.pieces[piece].Storage().WriteAt(data, begin)
986         if err == nil && n != len(data) {
987                 err = io.ErrShortWrite
988         }
989         return err
990 }
991
992 func (t *Torrent) bitfield() (bf []bool) {
993         bf = make([]bool, t.numPieces())
994         t._completedPieces.Iterate(func(piece uint32) (again bool) {
995                 bf[piece] = true
996                 return true
997         })
998         return
999 }
1000
1001 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
1002         return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
1003 }
1004
1005 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
1006         return t._chunksPerRegularPiece
1007 }
1008
1009 func (t *Torrent) numChunks() RequestIndex {
1010         if t.numPieces() == 0 {
1011                 return 0
1012         }
1013         return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
1014 }
1015
1016 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
1017         t.dirtyChunks.RemoveRange(
1018                 uint64(t.pieceRequestIndexOffset(pieceIndex)),
1019                 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
1020 }
1021
1022 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
1023         if t.info.PieceLength == 0 {
1024                 // There will be no variance amongst pieces. Only pain.
1025                 return 0
1026         }
1027         if t.info.FilesArePieceAligned() {
1028                 p := t.piece(piece)
1029                 file := p.mustGetOnlyFile()
1030                 if piece == file.EndPieceIndex()-1 {
1031                         return pp.Integer(file.length - (p.torrentBeginOffset() - file.offset))
1032                 }
1033                 return pp.Integer(t.usualPieceSize())
1034         }
1035         if piece == t.numPieces()-1 {
1036                 ret := pp.Integer(t.length() % t.info.PieceLength)
1037                 if ret != 0 {
1038                         return ret
1039                 }
1040         }
1041         return pp.Integer(t.info.PieceLength)
1042 }
1043
1044 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
1045         return &blockCheckingWriter{
1046                 cache:        &t.smartBanCache,
1047                 requestIndex: t.pieceRequestIndexOffset(piece),
1048                 chunkSize:    t.chunkSize.Int(),
1049         }
1050 }
1051
1052 func (t *Torrent) hashPiece(piece pieceIndex) (
1053         ret metainfo.Hash,
1054         // These are peers that sent us blocks that differ from what we hash here.
1055         differingPeers map[bannableAddr]struct{},
1056         err error,
1057 ) {
1058         p := t.piece(piece)
1059         p.waitNoPendingWrites()
1060         storagePiece := t.pieces[piece].Storage()
1061
1062         // Does the backend want to do its own hashing?
1063         if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
1064                 var sum metainfo.Hash
1065                 // log.Printf("A piece decided to self-hash: %d", piece)
1066                 sum, err = i.SelfHash()
1067                 missinggo.CopyExact(&ret, sum)
1068                 return
1069         }
1070
1071         hash := pieceHash.New()
1072         const logPieceContents = false
1073         smartBanWriter := t.smartBanBlockCheckingWriter(piece)
1074         writers := []io.Writer{hash, smartBanWriter}
1075         var examineBuf bytes.Buffer
1076         if logPieceContents {
1077                 writers = append(writers, &examineBuf)
1078         }
1079         _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
1080         if logPieceContents {
1081                 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
1082         }
1083         smartBanWriter.Flush()
1084         differingPeers = smartBanWriter.badPeers
1085         missinggo.CopyExact(&ret, hash.Sum(nil))
1086         return
1087 }
1088
1089 func (t *Torrent) haveAnyPieces() bool {
1090         return !t._completedPieces.IsEmpty()
1091 }
1092
1093 func (t *Torrent) haveAllPieces() bool {
1094         if !t.haveInfo() {
1095                 return false
1096         }
1097         return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1098 }
1099
1100 func (t *Torrent) havePiece(index pieceIndex) bool {
1101         return t.haveInfo() && t.pieceComplete(index)
1102 }
1103
1104 func (t *Torrent) maybeDropMutuallyCompletePeer(
1105         // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1106         // okay?
1107         p *PeerConn,
1108 ) {
1109         if !t.cl.config.DropMutuallyCompletePeers {
1110                 return
1111         }
1112         if !t.haveAllPieces() {
1113                 return
1114         }
1115         if all, known := p.peerHasAllPieces(); !(known && all) {
1116                 return
1117         }
1118         if p.useful() {
1119                 return
1120         }
1121         p.logger.Levelf(log.Debug, "is mutually complete; dropping")
1122         p.drop()
1123 }
1124
1125 func (t *Torrent) haveChunk(r Request) (ret bool) {
1126         // defer func() {
1127         //      log.Println("have chunk", r, ret)
1128         // }()
1129         if !t.haveInfo() {
1130                 return false
1131         }
1132         if t.pieceComplete(pieceIndex(r.Index)) {
1133                 return true
1134         }
1135         p := &t.pieces[r.Index]
1136         return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1137 }
1138
1139 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1140         return chunkIndexType(cs.Begin / chunkSize)
1141 }
1142
1143 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1144         return !t._pendingPieces.IsEmpty() && t._pendingPieces.Contains(uint32(index))
1145 }
1146
1147 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1148 // conns (which is a map).
1149 var peerConnSlices sync.Pool
1150
1151 func getPeerConnSlice(cap int) []*PeerConn {
1152         getInterface := peerConnSlices.Get()
1153         if getInterface == nil {
1154                 return make([]*PeerConn, 0, cap)
1155         } else {
1156                 return getInterface.([]*PeerConn)[:0]
1157         }
1158 }
1159
1160 // Calls the given function with a slice of unclosed conns. It uses a pool to reduce allocations as
1161 // this is a frequent occurrence.
1162 func (t *Torrent) withUnclosedConns(f func([]*PeerConn)) {
1163         sl := t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))
1164         f(sl)
1165         peerConnSlices.Put(sl)
1166 }
1167
1168 func (t *Torrent) worstBadConnFromSlice(opts worseConnLensOpts, sl []*PeerConn) *PeerConn {
1169         wcs := worseConnSlice{conns: sl}
1170         wcs.initKeys(opts)
1171         heap.Init(&wcs)
1172         for wcs.Len() != 0 {
1173                 c := heap.Pop(&wcs).(*PeerConn)
1174                 if opts.incomingIsBad && !c.outgoing {
1175                         return c
1176                 }
1177                 if opts.outgoingIsBad && c.outgoing {
1178                         return c
1179                 }
1180                 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1181                         return c
1182                 }
1183                 // If the connection is in the worst half of the established
1184                 // connection quota and is older than a minute.
1185                 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1186                         // Give connections 1 minute to prove themselves.
1187                         if time.Since(c.completedHandshake) > time.Minute {
1188                                 return c
1189                         }
1190                 }
1191         }
1192         return nil
1193 }
1194
1195 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1196 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1197 // established connections for more than a minute. This is O(n log n). If there was a way to not
1198 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1199 func (t *Torrent) worstBadConn(opts worseConnLensOpts) (ret *PeerConn) {
1200         t.withUnclosedConns(func(ucs []*PeerConn) {
1201                 ret = t.worstBadConnFromSlice(opts, ucs)
1202         })
1203         return
1204 }
1205
1206 type PieceStateChange struct {
1207         Index int
1208         PieceState
1209 }
1210
1211 func (t *Torrent) publishPieceStateChange(piece pieceIndex) {
1212         t.cl._mu.Defer(func() {
1213                 cur := t.pieceState(piece)
1214                 p := &t.pieces[piece]
1215                 if cur != p.publicPieceState {
1216                         p.publicPieceState = cur
1217                         t.pieceStateChanges.Publish(PieceStateChange{
1218                                 int(piece),
1219                                 cur,
1220                         })
1221                 }
1222         })
1223 }
1224
1225 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1226         if t.pieceComplete(piece) {
1227                 return 0
1228         }
1229         return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1230 }
1231
1232 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1233         return t.pieces[piece].allChunksDirty()
1234 }
1235
1236 func (t *Torrent) readersChanged() {
1237         t.updateReaderPieces()
1238         t.updateAllPiecePriorities("Torrent.readersChanged")
1239 }
1240
1241 func (t *Torrent) updateReaderPieces() {
1242         t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1243 }
1244
1245 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1246         if from == to {
1247                 return
1248         }
1249         t.updateReaderPieces()
1250         // Order the ranges, high and low.
1251         l, h := from, to
1252         if l.begin > h.begin {
1253                 l, h = h, l
1254         }
1255         if l.end < h.begin {
1256                 // Two distinct ranges.
1257                 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1258                 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1259         } else {
1260                 // Ranges overlap.
1261                 end := l.end
1262                 if h.end > end {
1263                         end = h.end
1264                 }
1265                 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1266         }
1267 }
1268
1269 func (t *Torrent) maybeNewConns() {
1270         // Tickle the accept routine.
1271         t.cl.event.Broadcast()
1272         t.openNewConns()
1273 }
1274
1275 func (t *Torrent) onPiecePendingTriggers(piece pieceIndex, reason string) {
1276         if t._pendingPieces.Contains(uint32(piece)) {
1277                 t.iterPeers(func(c *Peer) {
1278                         // if c.requestState.Interested {
1279                         //      return
1280                         // }
1281                         if !c.isLowOnRequests() {
1282                                 return
1283                         }
1284                         if !c.peerHasPiece(piece) {
1285                                 return
1286                         }
1287                         if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1288                                 return
1289                         }
1290                         c.updateRequests(reason)
1291                 })
1292         }
1293         t.maybeNewConns()
1294         t.publishPieceStateChange(piece)
1295 }
1296
1297 func (t *Torrent) updatePiecePriorityNoTriggers(piece pieceIndex) (pendingChanged bool) {
1298         if !t.closed.IsSet() {
1299                 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1300                 // request order.
1301                 t.updatePieceRequestOrderPiece(piece)
1302         }
1303         p := &t.pieces[piece]
1304         newPrio := p.uncachedPriority()
1305         // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1306         if newPrio == PiecePriorityNone {
1307                 return t._pendingPieces.CheckedRemove(uint32(piece))
1308         } else {
1309                 return t._pendingPieces.CheckedAdd(uint32(piece))
1310         }
1311 }
1312
1313 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1314         if t.updatePiecePriorityNoTriggers(piece) && !t.disableTriggers {
1315                 t.onPiecePendingTriggers(piece, reason)
1316         }
1317         t.updatePieceRequestOrderPiece(piece)
1318 }
1319
1320 func (t *Torrent) updateAllPiecePriorities(reason string) {
1321         t.updatePiecePriorities(0, t.numPieces(), reason)
1322 }
1323
1324 // Update all piece priorities in one hit. This function should have the same
1325 // output as updatePiecePriority, but across all pieces.
1326 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1327         for i := begin; i < end; i++ {
1328                 t.updatePiecePriority(i, reason)
1329         }
1330 }
1331
1332 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1333 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1334         if off >= t.length() {
1335                 return
1336         }
1337         if off < 0 {
1338                 size += off
1339                 off = 0
1340         }
1341         if size <= 0 {
1342                 return
1343         }
1344         begin = pieceIndex(off / t.info.PieceLength)
1345         end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1346         if end > pieceIndex(t.info.NumPieces()) {
1347                 end = pieceIndex(t.info.NumPieces())
1348         }
1349         return
1350 }
1351
1352 // Returns true if all iterations complete without breaking. Returns the read regions for all
1353 // readers. The reader regions should not be merged as some callers depend on this method to
1354 // enumerate readers.
1355 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1356         for r := range t.readers {
1357                 p := r.pieces
1358                 if p.begin >= p.end {
1359                         continue
1360                 }
1361                 if !f(p.begin, p.end) {
1362                         return false
1363                 }
1364         }
1365         return true
1366 }
1367
1368 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1369         return t.piece(piece).uncachedPriority()
1370 }
1371
1372 func (t *Torrent) pendRequest(req RequestIndex) {
1373         t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1374 }
1375
1376 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1377         t.cl.event.Broadcast()
1378         if t.pieceComplete(piece) {
1379                 t.onPieceCompleted(piece)
1380         } else {
1381                 t.onIncompletePiece(piece)
1382         }
1383         t.updatePiecePriority(piece, reason)
1384 }
1385
1386 func (t *Torrent) numReceivedConns() (ret int) {
1387         for c := range t.conns {
1388                 if c.Discovery == PeerSourceIncoming {
1389                         ret++
1390                 }
1391         }
1392         return
1393 }
1394
1395 func (t *Torrent) numOutgoingConns() (ret int) {
1396         for c := range t.conns {
1397                 if c.outgoing {
1398                         ret++
1399                 }
1400         }
1401         return
1402 }
1403
1404 func (t *Torrent) maxHalfOpen() int {
1405         // Note that if we somehow exceed the maximum established conns, we want
1406         // the negative value to have an effect.
1407         establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1408         extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1409         // We want to allow some experimentation with new peers, and to try to
1410         // upset an oversupply of received connections.
1411         return int(min(
1412                 max(5, extraIncoming)+establishedHeadroom,
1413                 int64(t.cl.config.HalfOpenConnsPerTorrent),
1414         ))
1415 }
1416
1417 func (t *Torrent) openNewConns() (initiated int) {
1418         defer t.updateWantPeersEvent()
1419         for t.peers.Len() != 0 {
1420                 if !t.wantOutgoingConns() {
1421                         return
1422                 }
1423                 if len(t.halfOpen) >= t.maxHalfOpen() {
1424                         return
1425                 }
1426                 if len(t.cl.dialers) == 0 {
1427                         return
1428                 }
1429                 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1430                         return
1431                 }
1432                 p := t.peers.PopMax()
1433                 opts := outgoingConnOpts{
1434                         peerInfo:                 p,
1435                         t:                        t,
1436                         requireRendezvous:        false,
1437                         skipHolepunchRendezvous:  false,
1438                         receivedHolepunchConnect: false,
1439                         HeaderObfuscationPolicy:  t.cl.config.HeaderObfuscationPolicy,
1440                 }
1441                 initiateConn(opts, false)
1442                 initiated++
1443         }
1444         return
1445 }
1446
1447 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1448         p := t.piece(piece)
1449         uncached := t.pieceCompleteUncached(piece)
1450         cached := p.completion()
1451         changed := cached != uncached
1452         complete := uncached.Complete
1453         p.storageCompletionOk = uncached.Ok
1454         x := uint32(piece)
1455         if complete {
1456                 t._completedPieces.Add(x)
1457                 t.openNewConns()
1458         } else {
1459                 t._completedPieces.Remove(x)
1460         }
1461         p.t.updatePieceRequestOrderPiece(piece)
1462         t.updateComplete()
1463         if complete && len(p.dirtiers) != 0 {
1464                 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1465         }
1466         if changed {
1467                 //slog.Debug(
1468                 //      "piece completion changed",
1469                 //      slog.Int("piece", piece),
1470                 //      slog.Any("from", cached),
1471                 //      slog.Any("to", uncached))
1472                 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1473         }
1474         return changed
1475 }
1476
1477 // Non-blocking read. Client lock is not required.
1478 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1479         for len(b) != 0 {
1480                 p := &t.pieces[off/t.info.PieceLength]
1481                 p.waitNoPendingWrites()
1482                 var n1 int
1483                 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1484                 if n1 == 0 {
1485                         break
1486                 }
1487                 off += int64(n1)
1488                 n += n1
1489                 b = b[n1:]
1490         }
1491         return
1492 }
1493
1494 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1495 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1496 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1497 func (t *Torrent) maybeCompleteMetadata() error {
1498         if t.haveInfo() {
1499                 // Nothing to do.
1500                 return nil
1501         }
1502         if !t.haveAllMetadataPieces() {
1503                 // Don't have enough metadata pieces.
1504                 return nil
1505         }
1506         err := t.setInfoBytesLocked(t.metadataBytes)
1507         if err != nil {
1508                 t.invalidateMetadata()
1509                 return fmt.Errorf("error setting info bytes: %s", err)
1510         }
1511         if t.cl.config.Debug {
1512                 t.logger.Printf("%s: got metadata from peers", t)
1513         }
1514         return nil
1515 }
1516
1517 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1518         t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1519                 if end > begin {
1520                         now.Add(bitmap.BitIndex(begin))
1521                         readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1522                 }
1523                 return true
1524         })
1525         return
1526 }
1527
1528 func (t *Torrent) needData() bool {
1529         if t.closed.IsSet() {
1530                 return false
1531         }
1532         if !t.haveInfo() {
1533                 return true
1534         }
1535         return !t._pendingPieces.IsEmpty()
1536 }
1537
1538 func appendMissingStrings(old, new []string) (ret []string) {
1539         ret = old
1540 new:
1541         for _, n := range new {
1542                 for _, o := range old {
1543                         if o == n {
1544                                 continue new
1545                         }
1546                 }
1547                 ret = append(ret, n)
1548         }
1549         return
1550 }
1551
1552 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1553         ret = existing
1554         for minNumTiers > len(ret) {
1555                 ret = append(ret, nil)
1556         }
1557         return
1558 }
1559
1560 func (t *Torrent) addTrackers(announceList [][]string) {
1561         fullAnnounceList := &t.metainfo.AnnounceList
1562         t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1563         for tierIndex, trackerURLs := range announceList {
1564                 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1565         }
1566         t.startMissingTrackerScrapers()
1567         t.updateWantPeersEvent()
1568 }
1569
1570 // Don't call this before the info is available.
1571 func (t *Torrent) bytesCompleted() int64 {
1572         if !t.haveInfo() {
1573                 return 0
1574         }
1575         return t.length() - t.bytesLeft()
1576 }
1577
1578 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1579         t.cl.lock()
1580         defer t.cl.unlock()
1581         return t.setInfoBytesLocked(b)
1582 }
1583
1584 // Returns true if connection is removed from torrent.Conns.
1585 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1586         if !c.closed.IsSet() {
1587                 panic("connection is not closed")
1588                 // There are behaviours prevented by the closed state that will fail
1589                 // if the connection has been deleted.
1590         }
1591         _, ret = t.conns[c]
1592         delete(t.conns, c)
1593         // Avoid adding a drop event more than once. Probably we should track whether we've generated
1594         // the drop event against the PexConnState instead.
1595         if ret {
1596                 if !t.cl.config.DisablePEX {
1597                         t.pex.Drop(c)
1598                 }
1599         }
1600         torrent.Add("deleted connections", 1)
1601         c.deleteAllRequests("Torrent.deletePeerConn")
1602         t.assertPendingRequests()
1603         if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1604                 panic(t.connsWithAllPieces)
1605         }
1606         return
1607 }
1608
1609 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1610         if t.deleteConnWithAllPieces(p) {
1611                 return
1612         }
1613         if !t.haveInfo() {
1614                 return
1615         }
1616         p.peerPieces().Iterate(func(i uint32) bool {
1617                 p.t.decPieceAvailability(pieceIndex(i))
1618                 return true
1619         })
1620 }
1621
1622 func (t *Torrent) assertPendingRequests() {
1623         if !check.Enabled {
1624                 return
1625         }
1626         // var actual pendingRequests
1627         // if t.haveInfo() {
1628         //      actual.m = make([]int, t.numChunks())
1629         // }
1630         // t.iterPeers(func(p *Peer) {
1631         //      p.requestState.Requests.Iterate(func(x uint32) bool {
1632         //              actual.Inc(x)
1633         //              return true
1634         //      })
1635         // })
1636         // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1637         // if diff != "" {
1638         //      panic(diff)
1639         // }
1640 }
1641
1642 func (t *Torrent) dropConnection(c *PeerConn) {
1643         t.cl.event.Broadcast()
1644         c.close()
1645         if t.deletePeerConn(c) {
1646                 t.openNewConns()
1647         }
1648 }
1649
1650 // Peers as in contact information for dialing out.
1651 func (t *Torrent) wantPeers() bool {
1652         if t.closed.IsSet() {
1653                 return false
1654         }
1655         if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1656                 return false
1657         }
1658         return t.wantOutgoingConns()
1659 }
1660
1661 func (t *Torrent) updateWantPeersEvent() {
1662         if t.wantPeers() {
1663                 t.wantPeersEvent.Set()
1664         } else {
1665                 t.wantPeersEvent.Clear()
1666         }
1667 }
1668
1669 // Returns whether the client should make effort to seed the torrent.
1670 func (t *Torrent) seeding() bool {
1671         cl := t.cl
1672         if t.closed.IsSet() {
1673                 return false
1674         }
1675         if t.dataUploadDisallowed {
1676                 return false
1677         }
1678         if cl.config.NoUpload {
1679                 return false
1680         }
1681         if !cl.config.Seed {
1682                 return false
1683         }
1684         if cl.config.DisableAggressiveUpload && t.needData() {
1685                 return false
1686         }
1687         return true
1688 }
1689
1690 func (t *Torrent) onWebRtcConn(
1691         c datachannel.ReadWriteCloser,
1692         dcc webtorrent.DataChannelContext,
1693 ) {
1694         defer c.Close()
1695         netConn := webrtcNetConn{
1696                 ReadWriteCloser:    c,
1697                 DataChannelContext: dcc,
1698         }
1699         peerRemoteAddr := netConn.RemoteAddr()
1700         //t.logger.Levelf(log.Critical, "onWebRtcConn remote addr: %v", peerRemoteAddr)
1701         if t.cl.badPeerAddr(peerRemoteAddr) {
1702                 return
1703         }
1704         localAddrIpPort := missinggo.IpPortFromNetAddr(netConn.LocalAddr())
1705         pc, err := t.cl.initiateProtocolHandshakes(
1706                 context.Background(),
1707                 netConn,
1708                 t,
1709                 false,
1710                 newConnectionOpts{
1711                         outgoing:        dcc.LocalOffered,
1712                         remoteAddr:      peerRemoteAddr,
1713                         localPublicAddr: localAddrIpPort,
1714                         network:         webrtcNetwork,
1715                         connString:      fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1716                 },
1717         )
1718         if err != nil {
1719                 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1720                 return
1721         }
1722         if dcc.LocalOffered {
1723                 pc.Discovery = PeerSourceTracker
1724         } else {
1725                 pc.Discovery = PeerSourceIncoming
1726         }
1727         pc.conn.SetWriteDeadline(time.Time{})
1728         t.cl.lock()
1729         defer t.cl.unlock()
1730         err = t.runHandshookConn(pc)
1731         if err != nil {
1732                 t.logger.WithDefaultLevel(log.Debug).Printf("error running handshook webrtc conn: %v", err)
1733         }
1734 }
1735
1736 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1737         err := t.runHandshookConn(pc)
1738         if err != nil || logAll {
1739                 t.logger.WithDefaultLevel(level).Levelf(log.ErrorLevel(err), "error running handshook conn: %v", err)
1740         }
1741 }
1742
1743 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1744         t.logRunHandshookConn(pc, false, log.Debug)
1745 }
1746
1747 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1748         wtc, release := t.cl.websocketTrackers.Get(u.String(), t.infoHash)
1749         // This needs to run before the Torrent is dropped from the Client, to prevent a new webtorrent.TrackerClient for
1750         // the same info hash before the old one is cleaned up.
1751         t.onClose = append(t.onClose, release)
1752         wst := websocketTrackerStatus{u, wtc}
1753         go func() {
1754                 err := wtc.Announce(tracker.Started, t.infoHash)
1755                 if err != nil {
1756                         t.logger.WithDefaultLevel(log.Warning).Printf(
1757                                 "error in initial announce to %q: %v",
1758                                 u.String(), err,
1759                         )
1760                 }
1761         }()
1762         return wst
1763 }
1764
1765 func (t *Torrent) startScrapingTracker(_url string) {
1766         if _url == "" {
1767                 return
1768         }
1769         u, err := url.Parse(_url)
1770         if err != nil {
1771                 // URLs with a leading '*' appear to be a uTorrent convention to disable trackers.
1772                 if _url[0] != '*' {
1773                         t.logger.Levelf(log.Warning, "error parsing tracker url: %v", err)
1774                 }
1775                 return
1776         }
1777         if u.Scheme == "udp" {
1778                 u.Scheme = "udp4"
1779                 t.startScrapingTracker(u.String())
1780                 u.Scheme = "udp6"
1781                 t.startScrapingTracker(u.String())
1782                 return
1783         }
1784         if _, ok := t.trackerAnnouncers[_url]; ok {
1785                 return
1786         }
1787         sl := func() torrentTrackerAnnouncer {
1788                 switch u.Scheme {
1789                 case "ws", "wss":
1790                         if t.cl.config.DisableWebtorrent {
1791                                 return nil
1792                         }
1793                         return t.startWebsocketAnnouncer(*u)
1794                 case "udp4":
1795                         if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1796                                 return nil
1797                         }
1798                 case "udp6":
1799                         if t.cl.config.DisableIPv6 {
1800                                 return nil
1801                         }
1802                 }
1803                 newAnnouncer := &trackerScraper{
1804                         u:               *u,
1805                         t:               t,
1806                         lookupTrackerIp: t.cl.config.LookupTrackerIp,
1807                 }
1808                 go newAnnouncer.Run()
1809                 return newAnnouncer
1810         }()
1811         if sl == nil {
1812                 return
1813         }
1814         if t.trackerAnnouncers == nil {
1815                 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1816         }
1817         t.trackerAnnouncers[_url] = sl
1818 }
1819
1820 // Adds and starts tracker scrapers for tracker URLs that aren't already
1821 // running.
1822 func (t *Torrent) startMissingTrackerScrapers() {
1823         if t.cl.config.DisableTrackers {
1824                 return
1825         }
1826         t.startScrapingTracker(t.metainfo.Announce)
1827         for _, tier := range t.metainfo.AnnounceList {
1828                 for _, url := range tier {
1829                         t.startScrapingTracker(url)
1830                 }
1831         }
1832 }
1833
1834 // Returns an AnnounceRequest with fields filled out to defaults and current
1835 // values.
1836 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1837         // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1838         // dependent on the network in use.
1839         return tracker.AnnounceRequest{
1840                 Event: event,
1841                 NumWant: func() int32 {
1842                         if t.wantPeers() && len(t.cl.dialers) > 0 {
1843                                 return 200 // Win has UDP packet limit. See: https://github.com/anacrolix/torrent/issues/764
1844                         } else {
1845                                 return 0
1846                         }
1847                 }(),
1848                 Port:     uint16(t.cl.incomingPeerPort()),
1849                 PeerId:   t.cl.peerID,
1850                 InfoHash: t.infoHash,
1851                 Key:      t.cl.announceKey(),
1852
1853                 // The following are vaguely described in BEP 3.
1854
1855                 Left:     t.bytesLeftAnnounce(),
1856                 Uploaded: t.stats.BytesWrittenData.Int64(),
1857                 // There's no mention of wasted or unwanted download in the BEP.
1858                 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1859         }
1860 }
1861
1862 // Adds peers revealed in an announce until the announce ends, or we have
1863 // enough peers.
1864 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1865         cl := t.cl
1866         for v := range pvs {
1867                 cl.lock()
1868                 added := 0
1869                 for _, cp := range v.Peers {
1870                         if cp.Port == 0 {
1871                                 // Can't do anything with this.
1872                                 continue
1873                         }
1874                         if t.addPeer(PeerInfo{
1875                                 Addr:   ipPortAddr{cp.IP, cp.Port},
1876                                 Source: PeerSourceDhtGetPeers,
1877                         }) {
1878                                 added++
1879                         }
1880                 }
1881                 cl.unlock()
1882                 // if added != 0 {
1883                 //      log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1884                 // }
1885         }
1886 }
1887
1888 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1889 // announce ends. stop will force the announce to end.
1890 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1891         ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1892         if err != nil {
1893                 return
1894         }
1895         _done := make(chan struct{})
1896         done = _done
1897         stop = ps.Close
1898         go func() {
1899                 t.consumeDhtAnnouncePeers(ps.Peers())
1900                 close(_done)
1901         }()
1902         return
1903 }
1904
1905 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1906         _, stop, err := t.AnnounceToDht(s)
1907         if err != nil {
1908                 return err
1909         }
1910         select {
1911         case <-t.closed.Done():
1912         case <-time.After(5 * time.Minute):
1913         }
1914         stop()
1915         return nil
1916 }
1917
1918 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1919         cl := t.cl
1920         cl.lock()
1921         defer cl.unlock()
1922         for {
1923                 for {
1924                         if t.closed.IsSet() {
1925                                 return
1926                         }
1927                         // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1928                         // TODO: We can include the announce_peer step depending on whether we can receive
1929                         // inbound connections. We should probably only announce once every 15 mins too.
1930                         if !t.wantAnyConns() {
1931                                 goto wait
1932                         }
1933                         // TODO: Determine if there's a listener on the port we're announcing.
1934                         if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1935                                 goto wait
1936                         }
1937                         break
1938                 wait:
1939                         cl.event.Wait()
1940                 }
1941                 func() {
1942                         t.numDHTAnnounces++
1943                         cl.unlock()
1944                         defer cl.lock()
1945                         err := t.timeboxedAnnounceToDht(s)
1946                         if err != nil {
1947                                 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1948                         }
1949                 }()
1950         }
1951 }
1952
1953 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1954         for _, p := range peers {
1955                 if t.addPeer(p) {
1956                         added++
1957                 }
1958         }
1959         return
1960 }
1961
1962 // The returned TorrentStats may require alignment in memory. See
1963 // https://github.com/anacrolix/torrent/issues/383.
1964 func (t *Torrent) Stats() TorrentStats {
1965         t.cl.rLock()
1966         defer t.cl.rUnlock()
1967         return t.statsLocked()
1968 }
1969
1970 func (t *Torrent) statsLocked() (ret TorrentStats) {
1971         ret.ActivePeers = len(t.conns)
1972         ret.HalfOpenPeers = len(t.halfOpen)
1973         ret.PendingPeers = t.peers.Len()
1974         ret.TotalPeers = t.numTotalPeers()
1975         ret.ConnectedSeeders = 0
1976         for c := range t.conns {
1977                 if all, ok := c.peerHasAllPieces(); all && ok {
1978                         ret.ConnectedSeeders++
1979                 }
1980         }
1981         ret.ConnStats = t.stats.Copy()
1982         ret.PiecesComplete = t.numPiecesCompleted()
1983         return
1984 }
1985
1986 // The total number of peers in the torrent.
1987 func (t *Torrent) numTotalPeers() int {
1988         peers := make(map[string]struct{})
1989         for conn := range t.conns {
1990                 ra := conn.conn.RemoteAddr()
1991                 if ra == nil {
1992                         // It's been closed and doesn't support RemoteAddr.
1993                         continue
1994                 }
1995                 peers[ra.String()] = struct{}{}
1996         }
1997         for addr := range t.halfOpen {
1998                 peers[addr] = struct{}{}
1999         }
2000         t.peers.Each(func(peer PeerInfo) {
2001                 peers[peer.Addr.String()] = struct{}{}
2002         })
2003         return len(peers)
2004 }
2005
2006 // Reconcile bytes transferred before connection was associated with a
2007 // torrent.
2008 func (t *Torrent) reconcileHandshakeStats(c *Peer) {
2009         if c._stats != (ConnStats{
2010                 // Handshakes should only increment these fields:
2011                 BytesWritten: c._stats.BytesWritten,
2012                 BytesRead:    c._stats.BytesRead,
2013         }) {
2014                 panic("bad stats")
2015         }
2016         c.postHandshakeStats(func(cs *ConnStats) {
2017                 cs.BytesRead.Add(c._stats.BytesRead.Int64())
2018                 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
2019         })
2020         c.reconciledHandshakeStats = true
2021 }
2022
2023 // Returns true if the connection is added.
2024 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
2025         defer func() {
2026                 if err == nil {
2027                         torrent.Add("added connections", 1)
2028                 }
2029         }()
2030         if t.closed.IsSet() {
2031                 return errors.New("torrent closed")
2032         }
2033         for c0 := range t.conns {
2034                 if c.PeerID != c0.PeerID {
2035                         continue
2036                 }
2037                 if !t.cl.config.DropDuplicatePeerIds {
2038                         continue
2039                 }
2040                 if c.hasPreferredNetworkOver(c0) {
2041                         c0.close()
2042                         t.deletePeerConn(c0)
2043                 } else {
2044                         return errors.New("existing connection preferred")
2045                 }
2046         }
2047         if len(t.conns) >= t.maxEstablishedConns {
2048                 numOutgoing := t.numOutgoingConns()
2049                 numIncoming := len(t.conns) - numOutgoing
2050                 c := t.worstBadConn(worseConnLensOpts{
2051                         // We've already established that we have too many connections at this point, so we just
2052                         // need to match what kind we have too many of vs. what we're trying to add now.
2053                         incomingIsBad: (numIncoming-numOutgoing > 1) && c.outgoing,
2054                         outgoingIsBad: (numOutgoing-numIncoming > 1) && !c.outgoing,
2055                 })
2056                 if c == nil {
2057                         return errors.New("don't want conn")
2058                 }
2059                 c.close()
2060                 t.deletePeerConn(c)
2061         }
2062         if len(t.conns) >= t.maxEstablishedConns {
2063                 panic(len(t.conns))
2064         }
2065         t.conns[c] = struct{}{}
2066         t.cl.event.Broadcast()
2067         // We'll never receive the "p" extended handshake parameter.
2068         if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
2069                 t.pex.Add(c)
2070         }
2071         return nil
2072 }
2073
2074 func (t *Torrent) newConnsAllowed() bool {
2075         if !t.networkingEnabled.Bool() {
2076                 return false
2077         }
2078         if t.closed.IsSet() {
2079                 return false
2080         }
2081         if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2082                 return false
2083         }
2084         return true
2085 }
2086
2087 func (t *Torrent) wantAnyConns() bool {
2088         if !t.networkingEnabled.Bool() {
2089                 return false
2090         }
2091         if t.closed.IsSet() {
2092                 return false
2093         }
2094         if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
2095                 return false
2096         }
2097         return len(t.conns) < t.maxEstablishedConns
2098 }
2099
2100 func (t *Torrent) wantOutgoingConns() bool {
2101         if !t.newConnsAllowed() {
2102                 return false
2103         }
2104         if len(t.conns) < t.maxEstablishedConns {
2105                 return true
2106         }
2107         numIncomingConns := len(t.conns) - t.numOutgoingConns()
2108         return t.worstBadConn(worseConnLensOpts{
2109                 incomingIsBad: numIncomingConns-t.numOutgoingConns() > 1,
2110                 outgoingIsBad: false,
2111         }) != nil
2112 }
2113
2114 func (t *Torrent) wantIncomingConns() bool {
2115         if !t.newConnsAllowed() {
2116                 return false
2117         }
2118         if len(t.conns) < t.maxEstablishedConns {
2119                 return true
2120         }
2121         numIncomingConns := len(t.conns) - t.numOutgoingConns()
2122         return t.worstBadConn(worseConnLensOpts{
2123                 incomingIsBad: false,
2124                 outgoingIsBad: t.numOutgoingConns()-numIncomingConns > 1,
2125         }) != nil
2126 }
2127
2128 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
2129         t.cl.lock()
2130         defer t.cl.unlock()
2131         oldMax = t.maxEstablishedConns
2132         t.maxEstablishedConns = max
2133         wcs := worseConnSlice{
2134                 conns: t.appendConns(nil, func(*PeerConn) bool {
2135                         return true
2136                 }),
2137         }
2138         wcs.initKeys(worseConnLensOpts{})
2139         heap.Init(&wcs)
2140         for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
2141                 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
2142         }
2143         t.openNewConns()
2144         return oldMax
2145 }
2146
2147 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
2148         t.logger.LazyLog(log.Debug, func() log.Msg {
2149                 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
2150         })
2151         p := t.piece(piece)
2152         p.numVerifies++
2153         t.cl.event.Broadcast()
2154         if t.closed.IsSet() {
2155                 return
2156         }
2157
2158         // Don't score the first time a piece is hashed, it could be an initial check.
2159         if p.storageCompletionOk {
2160                 if passed {
2161                         pieceHashedCorrect.Add(1)
2162                 } else {
2163                         log.Fmsg(
2164                                 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
2165                         ).AddValues(t, p).LogLevel(
2166
2167                                 log.Debug, t.logger)
2168
2169                         pieceHashedNotCorrect.Add(1)
2170                 }
2171         }
2172
2173         p.marking = true
2174         t.publishPieceStateChange(piece)
2175         defer func() {
2176                 p.marking = false
2177                 t.publishPieceStateChange(piece)
2178         }()
2179
2180         if passed {
2181                 if len(p.dirtiers) != 0 {
2182                         // Don't increment stats above connection-level for every involved connection.
2183                         t.allStats((*ConnStats).incrementPiecesDirtiedGood)
2184                 }
2185                 for c := range p.dirtiers {
2186                         c._stats.incrementPiecesDirtiedGood()
2187                 }
2188                 t.clearPieceTouchers(piece)
2189                 hasDirty := p.hasDirtyChunks()
2190                 t.cl.unlock()
2191                 if hasDirty {
2192                         p.Flush() // You can be synchronous here!
2193                 }
2194                 err := p.Storage().MarkComplete()
2195                 if err != nil {
2196                         t.logger.Levelf(log.Warning, "%T: error marking piece complete %d: %s", t.storage, piece, err)
2197                 }
2198                 t.cl.lock()
2199
2200                 if t.closed.IsSet() {
2201                         return
2202                 }
2203                 t.pendAllChunkSpecs(piece)
2204         } else {
2205                 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2206                         // Peers contributed to all the data for this piece hash failure, and the failure was
2207                         // not due to errors in the storage (such as data being dropped in a cache).
2208
2209                         // Increment Torrent and above stats, and then specific connections.
2210                         t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2211                         for c := range p.dirtiers {
2212                                 // Y u do dis peer?!
2213                                 c.stats().incrementPiecesDirtiedBad()
2214                         }
2215
2216                         bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2217                         for c := range p.dirtiers {
2218                                 if !c.trusted {
2219                                         bannableTouchers = append(bannableTouchers, c)
2220                                 }
2221                         }
2222                         t.clearPieceTouchers(piece)
2223                         slices.Sort(bannableTouchers, connLessTrusted)
2224
2225                         if t.cl.config.Debug {
2226                                 t.logger.Printf(
2227                                         "bannable conns by trust for piece %d: %v",
2228                                         piece,
2229                                         func() (ret []connectionTrust) {
2230                                                 for _, c := range bannableTouchers {
2231                                                         ret = append(ret, c.trust())
2232                                                 }
2233                                                 return
2234                                         }(),
2235                                 )
2236                         }
2237
2238                         if len(bannableTouchers) >= 1 {
2239                                 c := bannableTouchers[0]
2240                                 if len(bannableTouchers) != 1 {
2241                                         t.logger.Levelf(log.Debug, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2242                                 } else {
2243                                         // Turns out it's still useful to ban peers like this because if there's only a
2244                                         // single peer for a piece, and we never progress that piece to completion, we
2245                                         // will never smart-ban them. Discovered in
2246                                         // https://github.com/anacrolix/torrent/issues/715.
2247                                         t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2248                                         c.ban()
2249                                 }
2250                         }
2251                 }
2252                 t.onIncompletePiece(piece)
2253                 p.Storage().MarkNotComplete()
2254         }
2255         t.updatePieceCompletion(piece)
2256 }
2257
2258 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2259         start := t.pieceRequestIndexOffset(piece)
2260         end := start + t.pieceNumChunks(piece)
2261         for ri := start; ri < end; ri++ {
2262                 t.cancelRequest(ri)
2263         }
2264 }
2265
2266 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2267         t.pendAllChunkSpecs(piece)
2268         t.cancelRequestsForPiece(piece)
2269         t.piece(piece).readerCond.Broadcast()
2270         for conn := range t.conns {
2271                 conn.have(piece)
2272                 t.maybeDropMutuallyCompletePeer(conn)
2273         }
2274 }
2275
2276 // Called when a piece is found to be not complete.
2277 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2278         if t.pieceAllDirty(piece) {
2279                 t.pendAllChunkSpecs(piece)
2280         }
2281         if !t.wantPieceIndex(piece) {
2282                 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2283                 return
2284         }
2285         // We could drop any connections that we told we have a piece that we
2286         // don't here. But there's a test failure, and it seems clients don't care
2287         // if you request pieces that you already claim to have. Pruning bad
2288         // connections might just remove any connections that aren't treating us
2289         // favourably anyway.
2290
2291         // for c := range t.conns {
2292         //      if c.sentHave(piece) {
2293         //              c.drop()
2294         //      }
2295         // }
2296         t.iterPeers(func(conn *Peer) {
2297                 if conn.peerHasPiece(piece) {
2298                         conn.updateRequests("piece incomplete")
2299                 }
2300         })
2301 }
2302
2303 func (t *Torrent) tryCreateMorePieceHashers() {
2304         for !t.closed.IsSet() && t.activePieceHashes < t.cl.config.PieceHashersPerTorrent && t.tryCreatePieceHasher() {
2305         }
2306 }
2307
2308 func (t *Torrent) tryCreatePieceHasher() bool {
2309         if t.storage == nil {
2310                 return false
2311         }
2312         pi, ok := t.getPieceToHash()
2313         if !ok {
2314                 return false
2315         }
2316         p := t.piece(pi)
2317         t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2318         p.hashing = true
2319         t.publishPieceStateChange(pi)
2320         t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2321         t.storageLock.RLock()
2322         t.activePieceHashes++
2323         go t.pieceHasher(pi)
2324         return true
2325 }
2326
2327 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2328         t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2329                 if t.piece(i).hashing {
2330                         return true
2331                 }
2332                 ret = i
2333                 ok = true
2334                 return false
2335         })
2336         return
2337 }
2338
2339 func (t *Torrent) dropBannedPeers() {
2340         t.iterPeers(func(p *Peer) {
2341                 remoteIp := p.remoteIp()
2342                 if remoteIp == nil {
2343                         if p.bannableAddr.Ok {
2344                                 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2345                         }
2346                         return
2347                 }
2348                 netipAddr := netip.MustParseAddr(remoteIp.String())
2349                 if Some(netipAddr) != p.bannableAddr {
2350                         t.logger.WithDefaultLevel(log.Debug).Printf(
2351                                 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2352                                 p, remoteIp, p.bannableAddr)
2353                 }
2354                 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2355                         // Should this be a close?
2356                         p.drop()
2357                         t.logger.WithDefaultLevel(log.Debug).Printf("dropped %v for banned remote IP %v", p, netipAddr)
2358                 }
2359         })
2360 }
2361
2362 func (t *Torrent) pieceHasher(index pieceIndex) {
2363         p := t.piece(index)
2364         sum, failedPeers, copyErr := t.hashPiece(index)
2365         correct := sum == *p.hash
2366         switch copyErr {
2367         case nil, io.EOF:
2368         default:
2369                 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2370         }
2371         t.storageLock.RUnlock()
2372         t.cl.lock()
2373         defer t.cl.unlock()
2374         if correct {
2375                 for peer := range failedPeers {
2376                         t.cl.banPeerIP(peer.AsSlice())
2377                         t.logger.WithDefaultLevel(log.Debug).Printf("smart banned %v for piece %v", peer, index)
2378                 }
2379                 t.dropBannedPeers()
2380                 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2381                         t.smartBanCache.ForgetBlock(ri)
2382                 }
2383         }
2384         p.hashing = false
2385         t.pieceHashed(index, correct, copyErr)
2386         t.updatePiecePriority(index, "Torrent.pieceHasher")
2387         t.activePieceHashes--
2388         t.tryCreateMorePieceHashers()
2389 }
2390
2391 // Return the connections that touched a piece, and clear the entries while doing it.
2392 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2393         p := t.piece(pi)
2394         for c := range p.dirtiers {
2395                 delete(c.peerTouchedPieces, pi)
2396                 delete(p.dirtiers, c)
2397         }
2398 }
2399
2400 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2401         t.iterPeers(func(p *Peer) {
2402                 ret = append(ret, p)
2403         })
2404         return
2405 }
2406
2407 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2408         piece := t.piece(pieceIndex)
2409         if piece.hash == nil && !piece.hashV2.Ok {
2410                 return
2411         }
2412         if piece.queuedForHash() {
2413                 return
2414         }
2415         t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2416         t.publishPieceStateChange(pieceIndex)
2417         t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2418         t.tryCreateMorePieceHashers()
2419 }
2420
2421 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2422 // before the Info is available.
2423 func (t *Torrent) VerifyData() {
2424         for i := pieceIndex(0); i < t.NumPieces(); i++ {
2425                 t.Piece(i).VerifyData()
2426         }
2427 }
2428
2429 func (t *Torrent) connectingToPeerAddr(addrStr string) bool {
2430         return len(t.halfOpen[addrStr]) != 0
2431 }
2432
2433 func (t *Torrent) hasPeerConnForAddr(x PeerRemoteAddr) bool {
2434         addrStr := x.String()
2435         for c := range t.conns {
2436                 ra := c.RemoteAddr
2437                 if ra.String() == addrStr {
2438                         return true
2439                 }
2440         }
2441         return false
2442 }
2443
2444 func (t *Torrent) getHalfOpenPath(
2445         addrStr string,
2446         attemptKey outgoingConnAttemptKey,
2447 ) nestedmaps.Path[*PeerInfo] {
2448         return nestedmaps.Next(nestedmaps.Next(nestedmaps.Begin(&t.halfOpen), addrStr), attemptKey)
2449 }
2450
2451 func (t *Torrent) addHalfOpen(addrStr string, attemptKey *PeerInfo) {
2452         path := t.getHalfOpenPath(addrStr, attemptKey)
2453         if path.Exists() {
2454                 panic("should be unique")
2455         }
2456         path.Set(attemptKey)
2457         t.cl.numHalfOpen++
2458 }
2459
2460 // Start the process of connecting to the given peer for the given torrent if appropriate. I'm not
2461 // sure all the PeerInfo fields are being used.
2462 func initiateConn(
2463         opts outgoingConnOpts,
2464         ignoreLimits bool,
2465 ) {
2466         t := opts.t
2467         peer := opts.peerInfo
2468         if peer.Id == t.cl.peerID {
2469                 return
2470         }
2471         if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2472                 return
2473         }
2474         addr := peer.Addr
2475         addrStr := addr.String()
2476         if !ignoreLimits {
2477                 if t.connectingToPeerAddr(addrStr) {
2478                         return
2479                 }
2480         }
2481         if t.hasPeerConnForAddr(addr) {
2482                 return
2483         }
2484         attemptKey := &peer
2485         t.addHalfOpen(addrStr, attemptKey)
2486         go t.cl.outgoingConnection(
2487                 opts,
2488                 attemptKey,
2489         )
2490 }
2491
2492 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2493 // quickly make one Client visible to the Torrent of another Client.
2494 func (t *Torrent) AddClientPeer(cl *Client) int {
2495         return t.AddPeers(func() (ps []PeerInfo) {
2496                 for _, la := range cl.ListenAddrs() {
2497                         ps = append(ps, PeerInfo{
2498                                 Addr:    la,
2499                                 Trusted: true,
2500                         })
2501                 }
2502                 return
2503         }())
2504 }
2505
2506 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2507 // connection.
2508 func (t *Torrent) allStats(f func(*ConnStats)) {
2509         f(&t.stats)
2510         f(&t.cl.connStats)
2511 }
2512
2513 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2514         return t.pieces[i].hashing
2515 }
2516
2517 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2518         return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2519 }
2520
2521 func (t *Torrent) dialTimeout() time.Duration {
2522         return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2523 }
2524
2525 func (t *Torrent) piece(i int) *Piece {
2526         return &t.pieces[i]
2527 }
2528
2529 func (t *Torrent) onWriteChunkErr(err error) {
2530         if t.userOnWriteChunkErr != nil {
2531                 go t.userOnWriteChunkErr(err)
2532                 return
2533         }
2534         t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2535         t.disallowDataDownloadLocked()
2536 }
2537
2538 func (t *Torrent) DisallowDataDownload() {
2539         t.cl.lock()
2540         defer t.cl.unlock()
2541         t.disallowDataDownloadLocked()
2542 }
2543
2544 func (t *Torrent) disallowDataDownloadLocked() {
2545         t.dataDownloadDisallowed.Set()
2546         t.iterPeers(func(p *Peer) {
2547                 // Could check if peer request state is empty/not interested?
2548                 p.updateRequests("disallow data download")
2549                 p.cancelAllRequests()
2550         })
2551 }
2552
2553 func (t *Torrent) AllowDataDownload() {
2554         t.cl.lock()
2555         defer t.cl.unlock()
2556         t.dataDownloadDisallowed.Clear()
2557         t.iterPeers(func(p *Peer) {
2558                 p.updateRequests("allow data download")
2559         })
2560 }
2561
2562 // Enables uploading data, if it was disabled.
2563 func (t *Torrent) AllowDataUpload() {
2564         t.cl.lock()
2565         defer t.cl.unlock()
2566         t.dataUploadDisallowed = false
2567         t.iterPeers(func(p *Peer) {
2568                 p.updateRequests("allow data upload")
2569         })
2570 }
2571
2572 // Disables uploading data, if it was enabled.
2573 func (t *Torrent) DisallowDataUpload() {
2574         t.cl.lock()
2575         defer t.cl.unlock()
2576         t.dataUploadDisallowed = true
2577         for c := range t.conns {
2578                 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2579                 c.updateRequests("disallow data upload")
2580         }
2581 }
2582
2583 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2584 // or if nil, a critical message is logged, and data download is disabled.
2585 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2586         t.cl.lock()
2587         defer t.cl.unlock()
2588         t.userOnWriteChunkErr = f
2589 }
2590
2591 func (t *Torrent) iterPeers(f func(p *Peer)) {
2592         for pc := range t.conns {
2593                 f(&pc.Peer)
2594         }
2595         for _, ws := range t.webSeeds {
2596                 f(ws)
2597         }
2598 }
2599
2600 func (t *Torrent) callbacks() *Callbacks {
2601         return &t.cl.config.Callbacks
2602 }
2603
2604 type AddWebSeedsOpt func(*webseed.Client)
2605
2606 // Sets the WebSeed trailing path escaper for a webseed.Client.
2607 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2608         return func(c *webseed.Client) {
2609                 c.PathEscaper = custom
2610         }
2611 }
2612
2613 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2614         t.cl.lock()
2615         defer t.cl.unlock()
2616         for _, u := range urls {
2617                 t.addWebSeed(u, opts...)
2618         }
2619 }
2620
2621 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2622         if t.cl.config.DisableWebseeds {
2623                 return
2624         }
2625         if _, ok := t.webSeeds[url]; ok {
2626                 return
2627         }
2628         // I don't think Go http supports pipelining requests. However, we can have more ready to go
2629         // right away. This value should be some multiple of the number of connections to a host. I
2630         // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2631         // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2632         // "https://webtorrent.io/torrents/".
2633         const maxRequests = 16
2634         ws := webseedPeer{
2635                 peer: Peer{
2636                         t:                        t,
2637                         outgoing:                 true,
2638                         Network:                  "http",
2639                         reconciledHandshakeStats: true,
2640                         // This should affect how often we have to recompute requests for this peer. Note that
2641                         // because we can request more than 1 thing at a time over HTTP, we will hit the low
2642                         // requests mark more often, so recomputation is probably sooner than with regular peer
2643                         // conns. ~4x maxRequests would be about right.
2644                         PeerMaxRequests: 128,
2645                         // TODO: Set ban prefix?
2646                         RemoteAddr: remoteAddrFromUrl(url),
2647                         callbacks:  t.callbacks(),
2648                 },
2649                 client: webseed.Client{
2650                         HttpClient: t.cl.httpClient,
2651                         Url:        url,
2652                         ResponseBodyWrapper: func(r io.Reader) io.Reader {
2653                                 return &rateLimitedReader{
2654                                         l: t.cl.config.DownloadRateLimiter,
2655                                         r: r,
2656                                 }
2657                         },
2658                 },
2659                 activeRequests: make(map[Request]webseed.Request, maxRequests),
2660         }
2661         ws.peer.initRequestState()
2662         for _, opt := range opts {
2663                 opt(&ws.client)
2664         }
2665         ws.peer.initUpdateRequestsTimer()
2666         ws.requesterCond.L = t.cl.locker()
2667         for i := 0; i < maxRequests; i += 1 {
2668                 go ws.requester(i)
2669         }
2670         for _, f := range t.callbacks().NewPeer {
2671                 f(&ws.peer)
2672         }
2673         ws.peer.logger = t.logger.WithContextValue(&ws)
2674         ws.peer.peerImpl = &ws
2675         if t.haveInfo() {
2676                 ws.onGotInfo(t.info)
2677         }
2678         t.webSeeds[url] = &ws.peer
2679 }
2680
2681 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2682         t.iterPeers(func(p1 *Peer) {
2683                 if p1 == p {
2684                         active = true
2685                 }
2686         })
2687         return
2688 }
2689
2690 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2691         index := t.pieceIndexOfRequestIndex(ri)
2692         return Request{
2693                 pp.Integer(index),
2694                 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2695         }
2696 }
2697
2698 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2699         return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2700 }
2701
2702 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2703         return RequestIndex(piece) * t.chunksPerRegularPiece()
2704 }
2705
2706 func (t *Torrent) updateComplete() {
2707         t.Complete.SetBool(t.haveAllPieces())
2708 }
2709
2710 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2711         p := t.requestingPeer(r)
2712         if p != nil {
2713                 p.cancel(r)
2714         }
2715         // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2716         //delete(t.pendingRequests, r)
2717         if _, ok := t.requestState[r]; ok {
2718                 panic("expected request state to be gone")
2719         }
2720         return p
2721 }
2722
2723 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2724         return t.requestState[r].peer
2725 }
2726
2727 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2728         if t.connsWithAllPieces == nil {
2729                 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2730         }
2731         t.connsWithAllPieces[p] = struct{}{}
2732 }
2733
2734 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2735         _, ok := t.connsWithAllPieces[p]
2736         delete(t.connsWithAllPieces, p)
2737         return ok
2738 }
2739
2740 func (t *Torrent) numActivePeers() int {
2741         return len(t.conns) + len(t.webSeeds)
2742 }
2743
2744 func (t *Torrent) hasStorageCap() bool {
2745         f := t.storage.Capacity
2746         if f == nil {
2747                 return false
2748         }
2749         _, ok := (*f)()
2750         return ok
2751 }
2752
2753 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2754         return pieceIndex(ri / t.chunksPerRegularPiece())
2755 }
2756
2757 func (t *Torrent) iterUndirtiedRequestIndexesInPiece(
2758         reuseIter *typedRoaring.Iterator[RequestIndex],
2759         piece pieceIndex,
2760         f func(RequestIndex),
2761 ) {
2762         reuseIter.Initialize(&t.dirtyChunks)
2763         pieceRequestIndexOffset := t.pieceRequestIndexOffset(piece)
2764         iterBitmapUnsetInRange(
2765                 reuseIter,
2766                 pieceRequestIndexOffset, pieceRequestIndexOffset+t.pieceNumChunks(piece),
2767                 f,
2768         )
2769 }
2770
2771 type requestState struct {
2772         peer *Peer
2773         when time.Time
2774 }
2775
2776 // Returns an error if a received chunk is out of bounds in someway.
2777 func (t *Torrent) checkValidReceiveChunk(r Request) error {
2778         if !t.haveInfo() {
2779                 return errors.New("torrent missing info")
2780         }
2781         if int(r.Index) >= t.numPieces() {
2782                 return fmt.Errorf("chunk index %v, torrent num pieces %v", r.Index, t.numPieces())
2783         }
2784         pieceLength := t.pieceLength(pieceIndex(r.Index))
2785         if r.Begin >= pieceLength {
2786                 return fmt.Errorf("chunk begins beyond end of piece (%v >= %v)", r.Begin, pieceLength)
2787         }
2788         // We could check chunk lengths here, but chunk request size is not changed often, and tricky
2789         // for peers to manipulate as they need to send potentially large buffers to begin with. There
2790         // should be considerable checks elsewhere for this case due to the network overhead. We should
2791         // catch most of the overflow manipulation stuff by checking index and begin above.
2792         return nil
2793 }
2794
2795 func (t *Torrent) peerConnsWithDialAddrPort(target netip.AddrPort) (ret []*PeerConn) {
2796         for pc := range t.conns {
2797                 dialAddr, err := pc.remoteDialAddrPort()
2798                 if err != nil {
2799                         continue
2800                 }
2801                 if dialAddr != target {
2802                         continue
2803                 }
2804                 ret = append(ret, pc)
2805         }
2806         return
2807 }
2808
2809 func wrapUtHolepunchMsgForPeerConn(
2810         recipient *PeerConn,
2811         msg utHolepunch.Msg,
2812 ) pp.Message {
2813         extendedPayload, err := msg.MarshalBinary()
2814         if err != nil {
2815                 panic(err)
2816         }
2817         return pp.Message{
2818                 Type:            pp.Extended,
2819                 ExtendedID:      MapMustGet(recipient.PeerExtensionIDs, utHolepunch.ExtensionName),
2820                 ExtendedPayload: extendedPayload,
2821         }
2822 }
2823
2824 func sendUtHolepunchMsg(
2825         pc *PeerConn,
2826         msgType utHolepunch.MsgType,
2827         addrPort netip.AddrPort,
2828         errCode utHolepunch.ErrCode,
2829 ) {
2830         holepunchMsg := utHolepunch.Msg{
2831                 MsgType:  msgType,
2832                 AddrPort: addrPort,
2833                 ErrCode:  errCode,
2834         }
2835         incHolepunchMessagesSent(holepunchMsg)
2836         ppMsg := wrapUtHolepunchMsgForPeerConn(pc, holepunchMsg)
2837         pc.write(ppMsg)
2838 }
2839
2840 func incHolepunchMessages(msg utHolepunch.Msg, verb string) {
2841         torrent.Add(
2842                 fmt.Sprintf(
2843                         "holepunch %v %v messages %v",
2844                         msg.MsgType,
2845                         addrPortProtocolStr(msg.AddrPort),
2846                         verb,
2847                 ),
2848                 1,
2849         )
2850 }
2851
2852 func incHolepunchMessagesReceived(msg utHolepunch.Msg) {
2853         incHolepunchMessages(msg, "received")
2854 }
2855
2856 func incHolepunchMessagesSent(msg utHolepunch.Msg) {
2857         incHolepunchMessages(msg, "sent")
2858 }
2859
2860 func (t *Torrent) handleReceivedUtHolepunchMsg(msg utHolepunch.Msg, sender *PeerConn) error {
2861         incHolepunchMessagesReceived(msg)
2862         switch msg.MsgType {
2863         case utHolepunch.Rendezvous:
2864                 t.logger.Printf("got holepunch rendezvous request for %v from %p", msg.AddrPort, sender)
2865                 sendMsg := sendUtHolepunchMsg
2866                 senderAddrPort, err := sender.remoteDialAddrPort()
2867                 if err != nil {
2868                         sender.logger.Levelf(
2869                                 log.Warning,
2870                                 "error getting ut_holepunch rendezvous sender's dial address: %v",
2871                                 err,
2872                         )
2873                         // There's no better error code. The sender's address itself is invalid. I don't see
2874                         // this error message being appropriate anywhere else anyway.
2875                         sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSuchPeer)
2876                 }
2877                 targets := t.peerConnsWithDialAddrPort(msg.AddrPort)
2878                 if len(targets) == 0 {
2879                         sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NotConnected)
2880                         return nil
2881                 }
2882                 for _, pc := range targets {
2883                         if !pc.supportsExtension(utHolepunch.ExtensionName) {
2884                                 sendMsg(sender, utHolepunch.Error, msg.AddrPort, utHolepunch.NoSupport)
2885                                 continue
2886                         }
2887                         sendMsg(sender, utHolepunch.Connect, msg.AddrPort, 0)
2888                         sendMsg(pc, utHolepunch.Connect, senderAddrPort, 0)
2889                 }
2890                 return nil
2891         case utHolepunch.Connect:
2892                 holepunchAddr := msg.AddrPort
2893                 t.logger.Printf("got holepunch connect request for %v from %p", holepunchAddr, sender)
2894                 if g.MapContains(t.cl.undialableWithoutHolepunch, holepunchAddr) {
2895                         setAdd(&t.cl.undialableWithoutHolepunchDialedAfterHolepunchConnect, holepunchAddr)
2896                         if g.MapContains(t.cl.accepted, holepunchAddr) {
2897                                 setAdd(&t.cl.probablyOnlyConnectedDueToHolepunch, holepunchAddr)
2898                         }
2899                 }
2900                 opts := outgoingConnOpts{
2901                         peerInfo: PeerInfo{
2902                                 Addr:         msg.AddrPort,
2903                                 Source:       PeerSourceUtHolepunch,
2904                                 PexPeerFlags: sender.pex.remoteLiveConns[msg.AddrPort].UnwrapOrZeroValue(),
2905                         },
2906                         t: t,
2907                         // Don't attempt to start our own rendezvous if we fail to connect.
2908                         skipHolepunchRendezvous:  true,
2909                         receivedHolepunchConnect: true,
2910                         // Assume that the other end initiated the rendezvous, and will use our preferred
2911                         // encryption. So we will act normally.
2912                         HeaderObfuscationPolicy: t.cl.config.HeaderObfuscationPolicy,
2913                 }
2914                 initiateConn(opts, true)
2915                 return nil
2916         case utHolepunch.Error:
2917                 torrent.Add("holepunch error messages received", 1)
2918                 t.logger.Levelf(log.Debug, "received ut_holepunch error message from %v: %v", sender, msg.ErrCode)
2919                 return nil
2920         default:
2921                 return fmt.Errorf("unhandled msg type %v", msg.MsgType)
2922         }
2923 }
2924
2925 func addrPortProtocolStr(addrPort netip.AddrPort) string {
2926         addr := addrPort.Addr()
2927         switch {
2928         case addr.Is4():
2929                 return "ipv4"
2930         case addr.Is6():
2931                 return "ipv6"
2932         default:
2933                 panic(addrPort)
2934         }
2935 }
2936
2937 func (t *Torrent) trySendHolepunchRendezvous(addrPort netip.AddrPort) error {
2938         rzsSent := 0
2939         for pc := range t.conns {
2940                 if !pc.supportsExtension(utHolepunch.ExtensionName) {
2941                         continue
2942                 }
2943                 if pc.supportsExtension(pp.ExtensionNamePex) {
2944                         if !g.MapContains(pc.pex.remoteLiveConns, addrPort) {
2945                                 continue
2946                         }
2947                 }
2948                 t.logger.Levelf(log.Debug, "sent ut_holepunch rendezvous message to %v for %v", pc, addrPort)
2949                 sendUtHolepunchMsg(pc, utHolepunch.Rendezvous, addrPort, 0)
2950                 rzsSent++
2951         }
2952         if rzsSent == 0 {
2953                 return errors.New("no eligible relays")
2954         }
2955         return nil
2956 }
2957
2958 func (t *Torrent) numHalfOpenAttempts() (num int) {
2959         for _, attempts := range t.halfOpen {
2960                 num += len(attempts)
2961         }
2962         return
2963 }
2964
2965 func (t *Torrent) getDialTimeoutUnlocked() time.Duration {
2966         cl := t.cl
2967         cl.rLock()
2968         defer cl.rUnlock()
2969         return t.dialTimeout()
2970 }