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