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