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