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