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