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