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