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