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