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